Example #1
0
            handler: function(request, reply) {

                if(global.NODE_ENV==="dev"){  Utils.logObj("request.params", request.params)  }

                // we couldn't fetch any data for the given slug
                if(request.pre.initiative.length === 0){
                    reply(Boom.notFound("this initiative does not exist (TODO: show a user friendly page with the error)"));
                }

                var definitionsById = {};

                //if(global.NODE_ENV==="dev"){  Utils.logObj("request.pre.definitions", request.pre.definitions)  }

                definitionsById.initiativeStatus = _.indexBy(request.pre.definitions.initiativeStatus, "id");
                definitionsById.type = _.indexBy(request.pre.definitions.type, "id");
                definitionsById.scope = _.indexBy(request.pre.definitions.scope, "id");
                definitionsById.visitors = _.indexBy(request.pre.definitions.visitors, "id");

                var context = {
                    urlParam1: "iniciativas",
                    data: request.pre.initiative[0],
                    definitions: request.pre.definitions,
                    definitionsById: definitionsById
                };

                return reply.view(Path.join(__dirname, "templates/initiative.html"), {ctx: context});
            },
Example #2
0
function modelCollectionAdd(state, action) {
    return stateModels(
        state,
        action.model,
        _.values(_.extend(_.indexBy((state[action.model] || []).slice(), 'pk'), _.indexBy(action.models, 'pk')))
    );
}
Example #3
0
    userArtists.findOne({ userId: userId }, function (err, result) {
        if(err || !result) {
            userArtists.update({ userId: userId }, { $set: { artists: artists }}, { upsert: true }, callback);
        } else {
            var uniqueArtists = _.union(artists, result.artists || []),
                resultIndex = _.indexBy(result.artists, 'name'),
                artistsIndex = _.indexBy(artists, 'name');

            uniqueArtists = _.uniq(uniqueArtists, false, function (artist) {
                return artist.name;
            });

            _.each(uniqueArtists, function (artist) {
                var score = 0,
                    count = 0;

                if(resultIndex[artist.name]) {
                    score += resultIndex[artist.name].score * resultIndex[artist.name].count;
                    count += resultIndex[artist.name].count;
                }
                if(artistsIndex[artist.name]) {
                    score += artistsIndex[artist.name].score * artistsIndex[artist.name].count;
                    count += artistsIndex[artist.name].count;
                }

                artist.score = score / count;
                artist.count = count;
            });

            userArtists.update({ userId: userId }, { $set: { artists: uniqueArtists }}, { upsert: true }, callback);
        }
    });
Example #4
0
  $q.all({users: UserService.getAllUsers(), teams: Team.query().$promise, layers: Layer.query().$promise, event: Event.get({id: $routeParams.eventId, populate: false}).$promise}).then(function(result) {
    $scope.teams = result.teams;
    teamsById = _.indexBy(result.teams, 'id');

    $scope.layers = result.layers;
    layersById = _.indexBy(result.layers, 'id');

    $scope.event = result.event;

    var eventTeamId = _.find($scope.event.teamIds, function(teamId) {
      if (teamsById[teamId]) {
        return teamsById[teamId].teamEventId === $scope.event.id;
      }
    });
    eventTeam = teamsById[eventTeamId];

    var teamIdsInEvent = _.filter($scope.event.teamIds, function(teamId) {
      if (teamsById[teamId]) {
        return teamsById[teamId].teamEventId !== $scope.event.id;
      }
    });
    var teamsInEvent = _.map(teamIdsInEvent, function(teamId) { return teamsById[teamId]; });

    var usersInEvent = _.filter(result.users, function(user) {
      return _.findWhere(eventTeam.users, {id: user.id});
    });

    $scope.eventMembers = _.map(usersInEvent.concat(teamsInEvent), function(item) { return normalize(item); });

    var teamsNotInEvent = _.filter($scope.teams, function(team) {
      return $scope.event.teamIds.indexOf(team.id) === -1 && !team.teamEventId;
    });
    var usersNotInEvent = _.reject(result.users, function(user) {
      return _.findWhere(eventTeam.users, {id: user.id});
    });
    $scope.eventNonMembers = _.map(usersNotInEvent.concat(teamsNotInEvent), function(item) { return normalize(item); });

    $scope.layer = {};
    $scope.eventLayers = _.chain($scope.event.layerIds)
      .filter(function(layerId) {
        return layersById[layerId]; })
      .map(function(layerId) {
        return layersById[layerId];
      }).value();

    $scope.nonLayers = _.filter($scope.layers, function(layer) {
      return $scope.event.layerIds.indexOf(layer.id) === -1;
    });

    var myAccess = $scope.event.acl[UserService.myself.id];
    var aclPermissions = myAccess ? myAccess.permissions : [];

    $scope.hasReadPermission = _.contains(UserService.myself.role.permissions, 'READ_EVENT_ALL') || _.contains(aclPermissions, 'read');
    $scope.hasUpdatePermission = _.contains(UserService.myself.role.permissions, 'UPDATE_EVENT') || _.contains(aclPermissions, 'update');
    $scope.hasDeletePermission = _.contains(UserService.myself.role.permissions, 'DELETE_EVENT') || _.contains(aclPermissions, 'delete');
  });
Example #5
0
    this.client.listContainers({all: true}, (err, containers) => {
      if (err) {
        return;
      }

      let modifiedContainers = _.map(containers, container => {
        container.Name = container.Names[0].replace('/', '');
        delete container.Names;

        // HACK: fill in some data based on simple list data
        container.State = {};
        container.Config = {
          Image: container.Image
        };
        if (container.Status.indexOf('Exited') !== -1) {
          container.State.Stopped = true;
        } else if (container.Status.indexOf('Paused') !== -1) {
          container.State.Stopped = true;
        } else if (container.Status.indexOf('Up') !== -1) {
          container.State.Running = true;
        }
        return container;
      });
      containerServerActions.allUpdated({containers: _.indexBy(modifiedContainers.concat(_.values(this.placeholders)), 'Name')});
    });
Example #6
0
    .exec( function(err, users){
      if( err ) { callback(err); }

      network._doc.admins = _.indexBy( users, '_id');

      callback( false );
    });
 db.query(query, [], function(err, rows) {
   if (err) {
     return next(err);
   }
   self.set(table, _.indexBy(rows, pKey));
   return next();
 });
Example #8
0
 new AV.Query(Category).find().then(function(categories) {
   return redisClient.hmsetAsync('categories', _.mapObject(_.indexBy(categories, function(category) {
     return category.get('name');
   }), stringifyAVObject)).then(function() {
     response.success();
   });
 }).catch(function(err) {
Example #9
0
    .exec( function(err, users){
      if( err ) { callback(err); }

      board._doc.members = _.indexBy( users, '_id');

      callback( false );
    });
Example #10
0
 }, (err, containers) => {
   if (err) {
     // TODO: add a global error handler for this
     return;
   }
   containerServerActions.allUpdated({containers: _.indexBy(containers.concat(_.values(this.placeholders)), 'Name')});
 });
Example #11
0
    handler: function(request, reply) {

//        if(Config.get('hapi.auth')!==false){
    //console.log("request.auth", request.auth)
            if (request.auth.isAuthenticated) {
                console.log("loginForm handler: valid cookie, will now redirect to /" + request.params.lang + "/dashboard");
                return reply.redirect("/" + request.params.lang + "/dashboard");
            }
            // else if (request.auth.isFakeAuthenticated) {
            //     console.log("loginForm handler: fake authenticated, will now redirect to /" + request.params.lang + "/dashboard");
            //     return reply.redirect("/" + request.params.lang + "/dashboard");
            // }
//        }
        // else{
        //     console.log("loginForm handler: dev-no-auth, will now redirect to /" + request.params.lang + "/dashboard");
             //request.auth.credentials = Hoek.clone(Config.get("hapi.dummyCredentials"));
             //request.auth.isAuthenticated = true;
             //request.auth.authenticated = true;
        //     return reply.redirect("/" + request.params.lang + "/dashboard");
        // }

        var context = {
            texts: _.indexBy(request.pre.texts, "id"),
            auth: request.auth,
            urlParam1: "login",
            showEnglish: request.pre.showEnglish,
            lfr: request.query.lfr || "" // login fail reason
        };

        //console.log("context.auth: ", context.auth)

        return reply.view('login', {
            ctx: context
        });
    },
Example #12
0
            ContentDAO.Revisions.getAllRevisionsForContent(contentIds, function(err, revisionsByContent) {
                if (err) {
                    log().error({'err': err}, 'Error trying to retrieve revisions for content');
                }

                // Stick the revisions on their content item
                var filteredContentById = _.indexBy(filteredContent, 'contentId');
                _.each(revisionsByContent, function(revisions, contentId) {
                    filteredContentById[contentId].revisions = revisions;
                });
                filteredContent = _.values(filteredContentById);

                // Run the second filtering phase
                filteredContent = filterGenerator.filterRevisions(filteredContent);

                // Submit all those are left
                _.each(filteredContent, function(content) {
                    _.each(content.revisions, function(revision) {
                        totalReprocessed++;
                        submitForProcessing(content.contentId, revision.revisionId);
                    });
                });

                return done();
            });
/*
 * Prepare the data received by the component for the internal working.
 */
function prepareData(newData, field) {
	// The data will be inmutable inside the component
	let data = Immutable.fromJS(newData), index = 0;
	let indexed = [], parsed = [];

	// Parsing data to add new fields (selected or not, field, rowIndex)
	parsed = data.map(row => {
		if (!row.get(field, false)) {
			row = row.set(field, _.uniqueId());
		} else {
			row = row.set(field, row.get(field).toString());
		}

		if (!row.get('_selected', false)) {
			row = row.set('_selected', false);
		}

		row = row.set('_rowIndex', index++);

		return row;
	});

	// Prepare indexed data.
	indexed = _.indexBy(parsed.toJSON(), field);

	return {
		rawdata: data,
		data: parsed,
		indexed: indexed
	};
}
Example #14
0
    request(options, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var diff = {
                isModified: false,
                newApps: [],
                deleteApps: [],
                updateApps: []
            };
            var localApps = am.all();
            var newApps = _.indexBy(body, 'id');

            _.each(localApps, function (localApp) {
                if (!newApps[localApp.id]) {
                    diff.deleteApps.push(localApp);
                    diff.isModified = true;
                } else if (newApps[localApp.id].version_code > localApp.version_code) {
                    diff.updateApps.push(newApps[localApp.id]);
                    diff.isModified = true;
                }
                delete newApps[localApp.id];
            });

            _.each(newApps, function (newApp) {
                diff.newApps.push(newApp);
                diff.isModified = true;
            });
            console.log('parse apps over,return parsed diff...');
            cb(undefined, diff);
        } else {
            console.log('get apps failed...');
            cb(error, undefined);
        }
    });
Example #15
0
	var controller = function() {
		var ctrl = this;

		var sortParam = ctrl.sortParam || 'sortField';

		var modelValues = null;
		if (ctrl.modelValue) {
			modelValues = _.indexBy(ctrl.sortOptions, 'value');
		}

		ctrl.sortValue = ctrl.sortFilter.model(sortParam);

		ctrl.sort = function(){
			var sortModel;

			if (modelValues) {
				sortModel = modelValues[ctrl.sortValue].model 
			} else {
				sortModel = {};
				sortModel[sortParam] = ctrl.sortValue;	
			}

			if (ctrl.preSortFn) {
				ctrl.preSortFn(sortModel);
			}

			ctrl.sortFilter.filter(sortModel, ctrl.sortExclude);

			if (ctrl.onSortFn) {
				ctrl.onSortFn(sortModel);
			}
		};
	};
Example #16
0
 SearchTestUtil.whenIndexingComplete(function() {
     var callbackArgs = [];
     callbackArgs.push(null);
     callbackArgs.push(_.indexBy(_createdUsers, function(user) { return user.user.id; }));
     callbackArgs = _.union(callbackArgs, _createdUsers);
     return callback.apply(callback, callbackArgs);
 });
Example #17
0
    hc.getReq(function(e,r){
        if(e){
            response.send(404,e);
        }else{
            console.log("bbbbb",r);
            if(0=== r.error){
                var prices = [];
                var priceHash = us.indexBy(r.data,'date');
                for(var today = new Date(sd).getTime();today <= new Date(ed).getTime();today += 86400000 ){
                    if( priceHash[today] && priceHash[today].inventory > 0){
                        prices.push(priceHash[today].price);
                    }   else{
                        prices.push(0);
                    }
                }
//                r.data.forEach(function(p){
//                    prices.push(p.packagePrice);
//                });
                var result = {};
                result.id = id;
                result.prices = prices;
                result.time = new Date(sd).getTime();
                response.render('wap/productCalendar',{'titleName':'选择日期','product':result});
            }else{
                response.send(404,r.errorMsg);
            }
        }
    });
Example #18
0
 StudentGroupStore.addGroups = function(newlyFetchedGroups){
   const newGroupsHash = _.indexBy(newlyFetchedGroups, "id")
   const newGroupsState = _.extend(newGroupsHash, this.getState().groups)
   this.setState({
     groups: newGroupsState
   })
 }
  function transformObservations(observations, event) {
    if (!_.isArray(observations)) observations = [observations];

    var formMap = _.indexBy(event.forms, 'id');
    _.each(observations, function(observation) {
      var formId = null;
      var formStyle = null;
      var primaryField = null;
      var variantField = null;

      if (observation.properties.forms.length) {
        var firstForm = observation.properties.forms[0];
        var form = formMap[firstForm.formId];
        formId = form.id;
        formStyle = form.style;
        primaryField = firstForm[form.primaryField];
        variantField = firstForm[form.variantField];
      }

      var style = getObservationStyle(event.style, formStyle, primaryField, variantField);
      style.iconUrl = getObservationIconUrlForEvent(event.id, formId, primaryField, variantField);

      observation.style = style;
      if (observation.geometry.type === 'Polygon') {
        minimizePolygon(observation.geometry.coordinates);
      } else if (observation.geometry.type === 'LineString') {
        minimizeLineString(observation.geometry.coordinates);
      }

    });
  }
Example #20
0
        it('columnModelMap이 정상적으로 가공되었는지 확인한다.', function() {
            var dataColumns = columnModelInstance.get('dataColumns');
            var rowHeaders = columnModelInstance.get('rowHeaders');
            var columnModelMap = columnModelInstance.get('columnModelMap');
            var expectResult = _.indexBy(_.union(rowHeaders, dataColumns), 'name');

            expect(columnModelMap).toEqual(expectResult);
        });
Example #21
0
              .exec(function (err, users) {
                if (err) {
                  return reply(Boom.badRequest(err));
                }

                conversation.members = _.indexBy(users, '_id');
                return reply({conversation: conversation});
              });
 convertToHtml: function(element) {
     var comments = _.indexBy(
         element.type === documents.types.document ? element.comments : [],
         "commentId"
     );
     var conversion = new DocumentConversion(options, comments);
     return conversion.convertToHtml(element);
 }
			.then(function(behaviorDocs){
				var docMap = _.indexBy(_.pluck(behaviorDocs.rows || [], 'doc'), '_id');
				return regions.map(function(region){
					return {
						region: region,
						behavior: docMap[region.value.id],
					};
				});
			});
Example #24
0
 var onUsers = function(err, arg1, arg2, cb) {
     if (err) return cb(err);
     if (_.isObject(arg1)) {
         return cb(null, arg1, _.isArray(arg2) ? arg2 : _.toArray(arg1));
     }
     if (_.isArray(arg1)) {
         return cb(null, _.isObject(arg2) ? arg2 : _.indexBy(arg1, '_uid'), arg1);
     }
 };
Example #25
0
  _calculateHistograms (trends, maxX) {
    const bins = this.bins;
    const byTrend = _.groupBy(trends, 'trend');

    const min = _.reduce(trends, (memo, num) => {
      let current = deArray(num.current, d3.min);
      return Math.min(memo, current);
    }, 0);  // we want 0 to be the min

    const maxXSet = !_.isNaN(parseFloat(maxX));
    let max;
    let binWidth;
    if (maxXSet) {
      // We have a maximum set, put everything beyond this max
      // in the same 'Beyond' bin.
      max = parseFloat(maxX);
      binWidth = (max - min) / (bins - 1);
    } else {
      max = _.reduce(trends, (memo, num) => {
        return Math.max(memo, deArray(num.current, d3.max));
      }, 0);
      binWidth = (max - min) / bins;
    }

    let hists = _.map(byTrend, (element, key) => {
      let el = {trend: this.trendMap[key].display_name};
      el['values'] = _.countBy(_.map(element, (value) => {
        let current = deArray(value.current, d3.median);
        let res = Math.floor(current / binWidth);
        if (maxXSet) {
          if (res > bins - 1) {
            res = bins - 1;
          }
        } else {
          if (res > bins) {
            res = bins;
          }
        }
        return res;
      }), (num) => { return num; });
      return el;
    }, this);

    hists = _.indexBy(hists, 'trend');
    this.xLabels = [];
    this.xLabels.push(binWidth / 2);
    for (let i = 1; i < bins; ++i) {
      this.xLabels.push(this.xLabels[i - 1] + binWidth);
    }
    this.xLabels = _.map(this.xLabels, (value) => {
      return value.toFixed(1);
    });
    if (maxXSet) {
      this.xLabels[this.xLabels.length - 1] = 'Beyond';
    }
    return hists;
  }
Example #26
0
                    topicModel.populate(result, {path: "_id"}, function(err, active){
                        var with_topic = _.filter(active, function(t){ return t._id; });
                        var ordered = _.indexBy(with_topic, 'posts');
                        var in_array = _.toArray(ordered);
                        var most_active = _.last(in_array, req.query.active);

                        req.objects = most_active;
                        return next();
                    });
Example #27
0
 }, function (gifts, cb) {
     var index = _.indexBy(gifts, "sourceGiftCardId");
     _.each(ret.items, function (giftCard) {
         if (index[giftCard.id]) {
             giftCard.isGiftedToAnotherPerson = true;
         }
     });
     cb();
 }
 it('Should invalidate polygon with insufficient coordinates', () => {
   const invalid = {
     polygon: [[[11.777615079114867,55.57305838952234],[11.777615079114867,55.57305838952234]]],
     srid: 4326
   };
   const params = [...commonParameters.crs, ...commonParameters.geomWithin];
   const paramMap = _.indexBy(params, 'name');
   const validationResult = parameterParsing.validateParameters(invalid, paramMap);
   expect(validationResult).to.have.length(1);
 });
 it('Should invalidate a polygon which has a coordinate outside the permitted bounding box', function() {
   var invalid = {
     polygon: [[[10.3,55.3],[-2000,55.3],[10.4,55.31],[10.4,55.31],[10.3,55.3]]],
     srid: 4326
   };
   var params = commonParameters.crs.concat(commonParameters.geomWithin);
   var paramMap = _.indexBy(params, 'name');
   var validationResult = parameterParsing.validateParameters(invalid, paramMap);
   expect(validationResult).to.have.length(1);
 });
 it('Should invalidate a circle which has center outside the permitted bounding box', function() {
   var invalid = {
     cirkel: "10,10,1",
     srid: 25832
   };
   var params = commonParameters.crs.concat(commonParameters.geomWithin);
   var paramMap = _.indexBy(params, 'name');
   var validationResult = parameterParsing.validateParameters(invalid, paramMap);
   expect(validationResult).to.have.length(1);
 });