Converts the given filter specification to a CQL filter expression.
188015
def make_filter_string(cls, filter_specification):
        
        registry = get_current_registry()
        visitor_cls = registry.getUtility(IFilterSpecificationVisitor,
                                          name=EXPRESSION_KINDS.CQL)
        visitor = visitor_cls()
        filter_specification.accept(visitor)
        return str(visitor.expression)
22040
def to_filter(self, query, arg):
        """"""
        return filter_from_url_arg(self.model_cls, query, arg, query_operator=or_)
109688
def filter_like(self, **filters):
        ''' 
        '''
        Query = {}
        for name, value in filters.items():
            name = resolve_name(self.type, name)
            Query[name] = re_compile(value, IGNORECASE)
        self.filter(QueryExpression(Query))
        return self
781016
def get_filter_qobj(self, keys=None):
    
    # only care about columns in aggregates right?
    cols = set()
    for agg in self.select.aggregates:
        cols.update(agg.cols)
    sels = [SelectExpr(col, [col], col, None) for col in cols]
    select = Select(sels)
    where = list(self.where)
    if keys:
      keys = list(keys)
      keys = map(sqlize, list(keys))
      expr = self.select.nonaggs[0].expr

      clause = []
      if None in keys:
        clause.append("%s is null" % expr)
      if len([k for k in keys if k is not None]) > 0:
        clause.append("%s in %%s" % expr)
      clause = " or ".join(clause)
      where.append(clause)
    else:
      where.append( '%s = %%s' % (self.select.nonaggs[0].expr ) )
    q = Query(self.db, select, self.fr, where)
    return q
779312
def filter(self, **filters):
        

        q = self._clone()
        for key, value in filters.items():
            filter_key = re.split('__', key)
            filter_attr = filter_key[0]
            if filter_attr not in self._valid_filter_attrs:
                raise ClientValidationError("Invalid filter attribute: %s" % key)

            # we use __ as a separator in the Python library, the APIs use '.'
            q._filters['.'.join(filter_key)].append(value)
        return q
1297318
public QueryBuilder populateFilterBuilder(Expression condtionalExp, EntityMetadata m)
    {
        log.info("Populating filter for expression: " + condtionalExp);
        QueryBuilder filter = null;

        if (condtionalExp instanceof SubExpression)
        {
            filter = populateFilterBuilder(((SubExpression) condtionalExp).getExpression(), m);
        }
        else if (condtionalExp instanceof ComparisonExpression)
        {
            filter = getFilter(populateFilterClause((ComparisonExpression) condtionalExp), m);
        }
        else if (condtionalExp instanceof BetweenExpression)
        {
            filter = populateBetweenFilter((BetweenExpression) condtionalExp, m);
        }
        else if (condtionalExp instanceof LogicalExpression)
        {
            filter = populateLogicalFilterBuilder(condtionalExp, m);
        }
        else if (condtionalExp instanceof LikeExpression)
        {
            filter = populateLikeQuery((LikeExpression) condtionalExp, m);
        }
        else if (condtionalExp instanceof InExpression)
        {
            filter = populateInQuery((InExpression) condtionalExp, m);
        }
        else
        {
            log.error(condtionalExp.toParsedText() + "found in where clause. Not supported in elasticsearch.");
            throw new KunderaException(condtionalExp.toParsedText() + " not supported in ElasticSearch");
        }

        log.debug("Following is the populated filter for required query: " + filter);
        return filter;
    }
352843
private ExpressionAndSubstitution convertIntoExpressionAndSubstitution(ImmutableExpression expression,
                                                                                            ImmutableSet<Variable> nonLiftableVariables)
            throws UnsatisfiableConditionException {

        ImmutableSet<ImmutableExpression> expressions = expression.flattenAND();
        ImmutableSet<ImmutableExpression> functionFreeEqualities = expressions.stream()
                .filter(e -> e.getFunctionSymbol().equals(EQ))
                .filter(e -> {
                    ImmutableList<? extends ImmutableTerm> arguments = e.getTerms();
                    return arguments.stream().allMatch(t -> t instanceof NonFunctionalTerm);
                })
                .collect(ImmutableCollectors.toSet());

        ImmutableSubstitution<NonFunctionalTerm> normalizedUnifier = unify(functionFreeEqualities.stream()
                        .map(ImmutableFunctionalTerm::getTerms)
                        .map(args -> Maps.immutableEntry(
                                (NonFunctionalTerm) args.get(0),
                                (NonFunctionalTerm)args.get(1))),
                nonLiftableVariables);

        Optional<ImmutableExpression> newExpression = immutabilityTools.foldBooleanExpressions(
                Stream.concat(
                        // Expressions that are not function-free equalities
                        expressions.stream()
                                .filter(e -> !functionFreeEqualities.contains(e))
                                .map(normalizedUnifier::applyToBooleanExpression),

                        // Equalities that must remain
                        normalizedUnifier.getImmutableMap().entrySet().stream()
                                .filter(e -> nonLiftableVariables.contains(e.getKey()))
                                .map(e -> termFactory.getImmutableExpression(EQ, e.getKey(), e.getValue()))
                ));

        return new ExpressionAndSubstitution(newExpression,
                normalizedUnifier.reduceDomainToIntersectionWith(
                        Sets.difference(normalizedUnifier.getDomain(), nonLiftableVariables).immutableCopy()));
    }
538344
def __filter(filterable, filter_, logic_operation='and'):
        
        condition = []
        if not filter_:
            return filterable
        elif filter_.get('type') == '__ANY__':
            return filterable
        else:
            for key, value in filter_.items():
                condition.append('{key} == "{value}"'.format(key=key, value=value))
        try:
            res = filterable.query(" {operation} ".format(operation=logic_operation).join(condition))
        except pd.core.computation.ops.UndefinedVariableError:
            return pd.DataFrame()
        else:
            return res
732412
@Nullable
  public static Filter toFilter(@Nullable DimFilter dimFilter)
  {
    return dimFilter == null ? null : dimFilter.toFilter();
  }
879660
protected void applyQueryFilter(Map<String, Object> params, QueryFilter queryFilter) {
    	if (queryFilter != null) {
    	    applyQueryContext(params, queryFilter);
        	if (queryFilter.getFilterParams() != null && !queryFilter.getFilterParams().isEmpty()) {
        		params.put(FILTER, queryFilter.getFilterParams());
        		for(String key : queryFilter.getParams().keySet()){
                    params.put(key, queryFilter.getParams().get(key));
                }
        	}
        }
    }
35415
def build_filter(self, filter):
        
        try:
            self.filter = Filter.from_string(filter, self.limit)
        except ValueError:
            raise

        return self
703247
def convert!(*filters)
      filters = filters.flatten.map { |f| Filters.resolve!(f) }

      fields.each_pair do |k, v|
        (!block_given? || yield(k, v)) ? v.convert!(*filters) : v
      end

      self
    end
710699
def Filter(self, match=None, **_):
    """"""
    arg = self.stack.pop(-1)

    # Filters can be specified as a comma separated list.
    for filter_name in match.group(1).split(","):
      filter_object = ConfigFilter.classes_by_name.get(filter_name)
      if filter_object is None:
        raise FilterError("Unknown filter function %r" % filter_name)

      if not filter_object.sensitive_arg:
        logging.debug("Applying filter %s for %s.", filter_name, arg)
      arg = filter_object().Filter(arg)
      precondition.AssertType(arg, Text)

    self.stack[-1] += arg
136954
private QueryBuilder populateBetweenFilter(BetweenExpression betweenExpression, EntityMetadata m)
    {
        String lowerBoundExpression = getBetweenBoundaryValues(betweenExpression.getLowerBoundExpression());
        String upperBoundExpression = getBetweenBoundaryValues(betweenExpression.getUpperBoundExpression());
        String field = getField(betweenExpression.getExpression().toParsedText());

        log.debug("Between clause for field " + field + "with lower bound " + lowerBoundExpression + "and upper bound "
                + upperBoundExpression);

        return new AndQueryBuilder(getFilter(kunderaQuery.new FilterClause(field, Expression.GREATER_THAN_OR_EQUAL,
                lowerBoundExpression, field), m), getFilter(kunderaQuery.new FilterClause(field,
                Expression.LOWER_THAN_OR_EQUAL, upperBoundExpression,field), m));
    }
1181836
def filter(self, *args, **kwargs):
        
        #add arguments to the where clause filters
        if len([x for x in kwargs.values() if x is None]):
            raise CQLEngineException("None values on filter are not allowed")

        clone = copy.deepcopy(self)
        for operator in args:
            if not isinstance(operator, WhereClause):
                raise QueryException('{} is not a valid query operator'.format(operator))
            clone._where.append(operator)

        for arg, val in kwargs.items():
            col_name, col_op = self._parse_filter_arg(arg)
            quote_field = True
            #resolve column and operator
            try:
                column = self.model._get_column(col_name)
            except KeyError:
                if col_name == 'pk__token':
                    if not isinstance(val, Token):
                        raise QueryException("Virtual column 'pk__token' may only be compared to Token() values")
                    column = columns._PartitionKeysToken(self.model)
                    quote_field = False
                else:
                    raise QueryException("Can't resolve column name: '{}'".format(col_name))

            if isinstance(val, Token):
                if col_name != 'pk__token':
                    raise QueryException("Token() values may only be compared to the 'pk__token' virtual column")
                partition_columns = column.partition_columns
                if len(partition_columns) != len(val.value):
                    raise QueryException(
                        'Token() received {} arguments but model has {} partition keys'.format(
                            len(val.value), len(partition_columns)))
                val.set_columns(partition_columns)

            #get query operator, or use equals if not supplied
            operator_class = BaseWhereOperator.get_operator(col_op or 'EQ')
            operator = operator_class()

            if isinstance(operator, InOperator):
                if not isinstance(val, (list, tuple)):
                    raise QueryException('IN queries must use a list/tuple value')
                query_val = [column.to_database(v) for v in val]
            elif isinstance(val, BaseQueryFunction):
                query_val = val
            else:
                query_val = column.to_database(val)

            clone._where.append(WhereClause(column.db_field_name, operator, query_val, quote_field=quote_field))

        return clone
1249031
def _build_filters(_filters):
    
    root = utils.NestedDict({})
    for _filter in _filters:
        operation = None
        for operation, token in SPLIT_TOKENS:
            # split "some.key=value" into ["some.key", "value"]
            top_parts = _filter.split(token, 1)
            if len(top_parts) == 2:
                break
        else:
            raise exceptions.CLIAbort('Failed to find valid operation for: %s'
                                      % _filter)

        key, value = top_parts
        current = root
        # split "some.key" into ["some", "key"]
        parts = [part.strip() for part in key.split('.')]

        # Actually drill down and add the filter
        for part in parts[:-1]:
            current = current[part]

        if operation == 'eq':
            current[parts[-1]] = utils.query_filter(value.strip())
        elif operation == 'in':
            current[parts[-1]] = {
                'operation': 'in',
                'options': [{
                    'name': 'data',
                    'value': [p.strip() for p in value.split(',')],
                }],
            }

    return root.to_dict()
479892
private void validateFilter(Filter filter) throws IllegalArgumentException {
    switch (filter.getFilterTypeCase()) {
      case COMPOSITE_FILTER:
        for (Filter subFilter : filter.getCompositeFilter().getFiltersList()) {
          validateFilter(subFilter);
        }
        break;
      case PROPERTY_FILTER:
        if (UNSUPPORTED_OPERATORS.contains(filter.getPropertyFilter().getOp())) {
          throw new IllegalArgumentException("Query cannot have any inequality filters.");
        }
        break;
      default:
        throw new IllegalArgumentException(
            "Unsupported filter type: " + filter.getFilterTypeCase());
    }
  }