Edit a aggregation
343044
def POST_AUTH(self, courseid, aggregationid=''):  # pylint: disable=arguments-differ
        
        course, __ = self.get_course_and_check_rights(courseid, allow_all_staff=True)

        if course.is_lti():
            raise web.notfound()

        msg=''
        error = False
        errored_students = []
        data = web.input(delete=[], tutors=[], groups=[], aggregationfile={})
        if len(data["delete"]):

            for classid in data["delete"]:
                # Get the aggregation
                aggregation = self.database.aggregations.find_one({"_id": ObjectId(classid), "courseid": courseid}) if ObjectId.is_valid(classid) else None

                if aggregation is None:
                    msg = _("Classroom with id {} not found.").format(classid) if course.use_classrooms() else _("Team with id {} not found.").format(classid)
                    error = True
                elif aggregation['default'] and aggregationid:
                    msg = _("You can't remove your default classroom.")
                    error = True
                else:
                    self.database.aggregations.find_one_and_update({"courseid": courseid, "default": True},
                                                                 {"$push": {
                                                                     "students": {"$each": aggregation["students"]}
                                                                 }})

                    self.database.aggregations.delete_one({"_id": ObjectId(classid)})
                    msg = _("Classroom updated.")

            if aggregationid and aggregationid in data["delete"]:
                raise web.seeother(self.app.get_homepath() + "/admin/" + courseid + "/aggregations")

        try:
            if "upload" in data:
                self.database.aggregations.delete_many({"courseid": course.get_id()})
                aggregations = custom_yaml.load(data["aggregationfile"].file)
            else:
                aggregations = json.loads(data["aggregations"])

            for index, new_aggregation in enumerate(aggregations):
                # In case of file upload, no id specified
                new_aggregation['_id'] = new_aggregation['_id'] if '_id' in new_aggregation else 'None'

                # In case of no aggregation usage, set the first entry default
                new_aggregation["default"] = not aggregationid and index == 0

                # If no groups field set, create group from class students if in groups only mode
                if "groups" not in new_aggregation:
                    new_aggregation["groups"] = [] if aggregationid else [{'size': len(new_aggregation['students']),
                                                                       'students': new_aggregation['students']}]

                # Update the aggregation
                aggregation, errors = self.update_aggregation(course, new_aggregation['_id'], new_aggregation)

                # If file upload was done, get the default aggregation id
                if course.use_classrooms() and aggregation['default']:
                    aggregationid = aggregation['_id']
                errored_students += errors

            if len(errored_students) > 0:
                msg = _("Changes couldn't be applied for following students :") + "<ul>"
                for student in errored_students:
                    msg += "<li>" + student + "</li>"
                msg += "</ul>"
                error = True
            elif not error:
                msg = _("Classroom updated.") if course.use_classrooms() else _("Teams updated.")
        except:
            msg = _('An error occurred while parsing the data.')
            error = True

        # Display the page
        return self.display_page(course, aggregationid, msg, error)
943362
def eval_agg_call(self, exp):
    ""
    if not isinstance(self.c_row,list): raise TypeError('aggregate function expected a list of rows')
    if len(exp.args.children)!=1: raise ValueError('aggregate function expected a single value',exp.args)
    arg,=exp.args.children # intentional: error if len!=1
    vals=[Evaluator(c_r,self.nix,self.tables).eval(arg) for c_r in self.c_row]
    if not vals: return None
    if exp.f=='min': return min(vals)
    elif exp.f=='max': return max(vals)
    elif exp.f=='count': return len(vals)
    else: raise NotImplementedError('unk_func',exp.f)
1037274
function _validateAggregationColumnsAndInteractivity (aggregationColumns, clickColumns, overColumns) {
  var aggColumns = (aggregationColumns && Object.keys(aggregationColumns)) || [];

  _validateColumnsConcordance(aggColumns, clickColumns, 'featureClick');
  _validateColumnsConcordance(aggColumns, overColumns, 'featureOver');
}
98704
def aggregate!(ts = Time.now.floor)
      unless self.ancestors.include?MongoMapper::Document
        raise NoMethodError, "aggregate! not defined for this counter"
      end

      aggr = aggregate(ts)
      aggr.each do |_ts, counterVals|
        counterVals.each do |obj, count|
          args = gen_args_for_instance obj, count, _ts, TYPE_MINUTE
          counter = self.new args
          counter.save!
        end
      end
      call_completion_hook(TYPE_MINUTE, ts)
    end
290989
def get_aggregations_fields(cls, params):
        
        fields = []
        for key, val in params.items():
            if isinstance(val, dict):
                fields += cls.get_aggregations_fields(val)
            if key == 'field':
                fields.append(val)
        return fields
1349380
private AggregateOperator<T> aggregate(Aggregations agg, int field, String callLocationName) {
		return new AggregateOperator<T>(this, agg, field, callLocationName);
	}
1181662
def _aggop(self, query):
        
        if isinstance(query.select, list):
            # RETURN SINGLE OBJECT WITH AGGREGATES
            for s in query.select:
                if s.aggregate not in aggregates:
                    Log.error("Expecting all columns to have an aggregate: {{select}}", select=s)

            selects = FlatList()
            for s in query.select:
                selects.append(sql_alias(aggregates[s.aggregate].replace("{{code}}", s.value),quote_column(s.name)))

            sql = expand_template("""
                SELECT
                    {{selects}}
                FROM
                    {{table}}
                {{where}}
            """, {
                "selects": SQL(",\n".join(selects)),
                "table": self._subquery(query["from"])[0],
                "where": self._where2sql(query.filter)
            })

            return sql, lambda sql: self.db.column(sql)[0]  # RETURNING SINGLE OBJECT WITH AGGREGATE VALUES
        else:
            # RETURN SINGLE VALUE
            s0 = query.select
            if s0.aggregate not in aggregates:
                Log.error("Expecting all columns to have an aggregate: {{select}}", select=s0)

            select = sql_alias(aggregates[s0.aggregate].replace("{{code}}", s0.value) , quote_column(s0.name))

            sql = expand_template("""
                SELECT
                    {{selects}}
                FROM
                    {{table}}
                {{where}}
            """, {
                "selects": SQL(select),
                "table": self._subquery(query["from"])[0],
                "where": self._where2sql(query.where)
            })

            def post(sql):
                result = self.db.column_query(sql)
                return result[0][0]

            return sql, post
79441
def agg(self, aggregations):
        
        check_type(aggregations, list)

        new_index = Index(np.array(aggregations, dtype=np.bytes_), np.dtype(np.bytes_))

        return _series_agg(self, aggregations, new_index)
796693
def aggregations(self):
        """"""

        prev_month_start = get_prev_month(self.end,
                                          self.closed.query.interval_)
        self.closed.query.since(prev_month_start,
                                field="closed_at")
        closed_agg = self.closed.aggregations()
        self.opened.query.since(prev_month_start)
        opened_agg = self.opened.aggregations()
        if opened_agg == 0:
            bmi = 1.0  # if no submitted issues/prs, bmi is at 100%
        else:
            bmi = closed_agg / opened_agg
        return bmi
92033
private static int aggregateStamp(int stamp_a, int stamp_b) {
        if (stamp_a == UNSET || stamp_b == UNSET) {
            return UNSET;
        }
        return (stamp_a > stamp_b) ? stamp_a : stamp_b;
    }
950022
def aggregate_grouploop(*args, **kwargs):
    """"""
    extrafuncs = {'allnan': allnan, 'anynan': anynan,
                  'first': itemgetter(0), 'last': itemgetter(-1),
                  'nanfirst': nanfirst, 'nanlast': nanlast}
    func = kwargs.pop('func')
    func = extrafuncs.get(func, func)
    if isinstance(func, str):
        raise NotImplementedError("Grouploop needs to be called with a function")
    return aggregate_numpy.aggregate(*args, func=lambda x: func(x), **kwargs)
398099
function postAggregation(type, name) {
  if (utils.isObject(type)) {
    return type
  }

  if (!name) {
    throw new FieldError('Missing post-aggregation name')
  }
  else if (!postAggregations.hasOwnProperty(type)) {
    throw new FieldError('Unknown post-aggregation type: ' + type)
  }

  var args = utils.args(arguments, 2)
    , postAggregation = {
      type: type,
      name: name
    }

  postAggregations[type].apply(postAggregation, args)

  return postAggregation
}
178455
private void buildAggregation(DBObject group, Expression expression, EntityMetadata metadata, EntityType entityType,
            boolean hasLob)
    {
        if (expression instanceof AggregateFunction)
        {
            AggregateFunction aggregateFunction = (AggregateFunction) expression;
            String identifier = aggregateFunction.getIdentifier().toLowerCase();

            Expression child = aggregateFunction.getExpression();

            if (child instanceof StateFieldPathExpression)
            {
                StateFieldPathExpression sfpExp = (StateFieldPathExpression) child;
                String columnName = getColumnName(metadata, entityType, sfpExp.toActualText());
                String actualColumnName = columnName;
                if (hasLob)
                {
                    actualColumnName = "metadata." + columnName;
                }
                else if (metadata.getIdAttribute().equals(entityType.getAttribute(metadata.getFieldName(columnName))))
                {
                    actualColumnName = "_id";
                }

                BasicDBObject item = new BasicDBObject("$" + identifier, "$" + actualColumnName);
                group.put(identifier + "_" + columnName, item);
            }
            else if (expression instanceof CountFunction)
            {
                group.put("count", new BasicDBObject("$sum", 1));
            }
        }
        else if (expression instanceof CollectionExpression)
        {
            for (Expression child : expression.children())
            {
                buildAggregation(group, child, metadata, entityType, hasLob);
            }
        }
        else if (expression instanceof StateFieldPathExpression)
        {
            StateFieldPathExpression sfpExp = (StateFieldPathExpression) expression;

            BasicDBObject idObject;
            Object existing = group.get("_id");
            if (existing != null)
            {
                idObject = (BasicDBObject) existing;
            }
            else
            {
                idObject = new BasicDBObject();
                group.put("_id", idObject);
            }

            String columnName = getColumnName(metadata, entityType, sfpExp.toActualText());
            String actualColumnName = columnName;
            if (hasLob)
            {
                actualColumnName = "metadata." + columnName;
            }

            idObject.put(columnName, "$" + actualColumnName);
        }
    }
928122
public function updateTotals()
    {
        foreach ($this->totals_plan as $key => $val) {

            // if value is array, then we treat it as built-in or callable aggregate method
            if (is_array($val)) {
                $f = $val[0]; // shortcut

                // initial value is always 0
                if (!isset($this->totals[$key])) {
                    $this->totals[$key] = 0;
                }

                // closure support
                // arguments - current value, key, \atk4\ui\Table object
                if ($f instanceof \Closure) {
                    $this->totals[$key] += ($f($this->model[$key], $key, $this) ?: 0);
                }
                // built-in methods
                elseif (is_string($f)) {
                    switch ($f) {
                        case 'sum':
                            $this->totals[$key] += $this->model[$key];
                            break;
                        case 'count':
                            $this->totals[$key] += 1;
                            break;
                        case 'min':
                            if ($this->model[$key] < $this->totals[$key]) {
                                $this->totals[$key] = $this->model[$key];
                            }
                            break;
                        case 'max':
                            if ($this->model[$key] > $this->totals[$key]) {
                                $this->totals[$key] = $this->model[$key];
                            }
                            break;
                        default:
                            throw new Exception(['Aggregation method does not exist', 'method' => $f]);
                    }
                }
            }
        }
    }
1178225
def _aggregate(self, source, aggregators, data, result):
    """"""
    if data is None:
      return

    if hasattr(aggregators, 'items'):
      # Keep walking the tree.
      for key, value in six.iteritems(aggregators):
        if isinstance(key, tuple):
          key, regex = key
          for dataKey, dataValue in six.iteritems(data):
            if regex.match(dataKey):
              result.setdefault(key, {})
              self._aggregate(source, value, dataValue, result[key])
        else:
          if key == '*':
            for dataKey, dataValue in six.iteritems(data):
              result.setdefault(dataKey, {})
              self._aggregate(source, value, dataValue, result[dataKey])
          elif key in data:
            result.setdefault(key, {})
            self._aggregate(source, value, data[key], result[key])

    else:
      # We found a leaf.
      for aggregator in aggregators:
        if aggregator.name not in result:
          result[aggregator.name] = aggregator.clone()
        result[aggregator.name].addValue(source, data)
939025
private Map<String, Object> toAggsMap(Map<String, Aggregation> fields) throws SqlParseException {
		Map<String, Object> result = new HashMap<>();
		for (Entry<String, Aggregation> entry : fields.entrySet()) {
			result.put(entry.getKey(), covenValue(entry.getValue()));
		}
		return result;
	}
1011582
def load_aggregate(args):
    """"""
    repos = load_config(args.config, args.expand_env)
    dirmatch = args.dirmatch
    for repo_dict in repos:
        r = Repo(**repo_dict)
        logger.debug('%s' % r)
        if not match_dir(r.cwd, dirmatch):
            logger.info("Skip %s", r.cwd)
            continue
        r.aggregate()
        if args.do_push:
            r.push()