We need to accomodate queries where a single email,
        or list of email addresses is supplied as arguments. For example:

        - Email.objects.filter(to='mail@example.com')
        - Email.objects.filter(to=['one@example.com', 'two@example.com'])
559677
def get_prep_value(self, value):
        
        if isinstance(value, six.string_types):
            return value
        else:
            return ', '.join(map(lambda s: s.strip(), value))
528585
def sort(self, **kwargs):
        
        query = {}
        for field in kwargs:
            query[field] = kwargs[field]
        self._q.append({'$sort': query})
        return self
927850
def _do_filter(cnf, args):
    
    if args.query:
        cnf = API.query(cnf, args.query)
    elif args.get:
        cnf = _do_get(cnf, args.get)
    elif args.set:
        (key, val) = args.set.split('=')
        API.set_(cnf, key, anyconfig.parser.parse(val))

    return cnf
789632
def split_query(query: str) -> List[str]:
    
    try:
        _query = query.strip()
    except (ValueError, AttributeError):
        raise QueryParserException('query is not valid, received instead {}'.format(query))

    expressions = _query.split(',')
    expressions = [exp.strip() for exp in expressions if exp.strip()]
    if not expressions:
        raise QueryParserException('Query is not valid: {}'.format(query))

    return expressions
686358
def parse_filters_kwargs(request, client_keywords=None):
    
    filters = {}
    kwargs = {}
    client_keywords = client_keywords or {}
    for param in request.GET:
        param_value = PARAM_MAPPING.get(request.GET[param], request.GET[param])
        if param in client_keywords:
            kwargs[param] = param_value
        else:
            filters[param] = param_value
    return filters, kwargs
982178
def query_params(*es_query_params):
    

    def _wrapper(func):
        @wraps(func)
        def _wrapped(*args, **kwargs):
            params = {}
            if "params" in kwargs:
                params = kwargs.pop("params").copy()
            for p in es_query_params + GLOBAL_PARAMS:
                if p in kwargs:
                    v = kwargs.pop(p)
                    if v is not None:
                        params[p] = _escape(v)

            # don't treat ignore and request_timeout as other params to avoid escaping
            for p in ("ignore", "request_timeout"):
                if p in kwargs:
                    params[p] = kwargs.pop(p)
            return func(*args, params=params, **kwargs)

        return _wrapped

    return _wrapper
789597
def exclude(self, *args, **kwargs) -> "QuerySet":
        
        return self._filter_or_exclude(negate=True, *args, **kwargs)
1358517
def get(self, *args, **kwargs):
        
        clone = self.filter(*args, **kwargs)
        num = len(clone)
        if num == 1:
            return clone._result_cache[0]
        if not num:
            raise self.model.DoesNotExist(
                "%s matching query does not exist. "
                "Lookup parameters were %s" %
                #(self.model._meta.object_name, kwargs))
                (self.model.__class__.__name__, kwargs))
        raise self.model.MultipleObjectsReturned(
            "get() returned more than one %s -- it returned %s! "
            "Lookup parameters were %s" %
            #(self.model._meta.object_name, num, kwargs))
            (self.model.__class__.__name__, num, kwargs))
871128
def aggregate(self, *args, **kwargs):
        
        if self.query.distinct_fields:
            raise NotImplementedError("aggregate() + distinct(fields) not implemented.")
        for arg in args:
            # The default_alias property may raise a TypeError, so we use
            # a try/except construct rather than hasattr in order to remain
            # consistent between PY2 and PY3 (hasattr would swallow
            # the TypeError on PY2).
            try:
                arg.default_alias
            except (AttributeError, TypeError):
                raise TypeError("Complex aggregates require an alias")
            kwargs[arg.default_alias] = arg

        if django.VERSION < (2, 0):
            query = self.query.clone(CTEAggregateQuery)
        else:
            query = self.query.chain(CTEAggregateQuery)
        for (alias, aggregate_expr) in kwargs.items():
            query.add_annotation(aggregate_expr, alias, is_summary=True)
            if not query.annotations[alias].contains_aggregate:
                raise TypeError("%s is not an aggregate expression" % alias)
        return query.get_aggregation(self.db, kwargs.keys())
98448
def _one_to_many_query(cls, query_obj, search4, model_attrib):
        
        model = model_attrib.parent.class_

        already_joined_tables = [mapper.class_ for mapper in query_obj._join_entities]

        if isinstance(search4, (str, int, Iterable)) and model not in already_joined_tables:
            query_obj = query_obj.join(model)

        if isinstance(search4, str):
            query_obj = query_obj.filter(model_attrib.like(search4))

        elif isinstance(search4, int):
            query_obj = query_obj.filter(model_attrib == search4)

        elif isinstance(search4, Iterable):
            query_obj = query_obj.filter(model_attrib.in_(search4))

        return query_obj
1124556
def lookup(self, query=''):
        """"""
        res = []
        query = re.compile('.*%s.*' % re.escape(query), self.reflags)
        for name, email in self.get_contacts():
            if query.match(name) or query.match(email):
                res.append((name, email))
        return res
1257978
function filter_email(value) {
    var m = EMAIL_RE.exec(value);
    if(m == null) throw OptError('Excpeted an email address.');
    return m[1];
}
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
385166
def _query(cls, *args, **kwds):
    
    # Validating distinct.
    if 'distinct' in kwds:
      if 'group_by' in kwds:
        raise TypeError(
            'cannot use distinct= and group_by= at the same time')
      projection = kwds.get('projection')
      if not projection:
        raise TypeError(
            'cannot use distinct= without projection=')
      if kwds.pop('distinct'):
        kwds['group_by'] = projection

    # TODO: Disallow non-empty args and filter=.
    from .query import Query  # Import late to avoid circular imports.
    qry = Query(kind=cls._get_kind(), **kwds)
    qry = qry.filter(*cls._default_filters())
    qry = qry.filter(*args)
    return qry
696541
def filter_queryset(self, request, queryset, view):
        "
        self.ordering_param = view.SORT

        ordering = self.get_ordering(request, queryset, view)
        if ordering:
            return queryset.order_by(*ordering)

        return queryset
1186711
def create_attr_filter(request, mapped_class):
    

    mapping = {
        'eq': '__eq__',
        'ne': '__ne__',
        'lt': '__lt__',
        'lte': '__le__',
        'gt': '__gt__',
        'gte': '__ge__',
        'like': 'like',
        'ilike': 'ilike'
    }
    filters = []
    if 'queryable' in request.params:
        queryable = request.params['queryable'].split(',')
        for k in request.params:
            if len(request.params[k]) <= 0 or '__' not in k:
                continue
            col, op = k.split("__")
            if col not in queryable or op not in mapping:
                continue
            column = getattr(mapped_class, col)
            f = getattr(column, mapping[op])(request.params[k])
            filters.append(f)
    return and_(*filters) if len(filters) > 0 else None
645891
def filter_search(self, search):
        
        builder = QueryBuilder(
            self.filtering_fields,
            self.filtering_map,
            self
        )
        search, unmatched = builder.build(search, self.get_query_params())

        # Ensure that no unsupported arguments were used.
        for argument in self.get_always_allowed_arguments():
            unmatched.pop(argument, None)

        if unmatched:
            msg = 'Unsupported parameter(s): {}. Please use a combination of: {}.'.format(
                ', '.join(unmatched),
                ', '.join(self.filtering_fields),
            )
            raise ParseError(msg)

        return search