"filters" must be something similar to:
            filters = {
                'R': (150, 255), # (min, max)
                'S': (150, 255),
            }
517102
def detect_blob(self, img, filters):
        
        acc_mask = ones(img.shape[:2], dtype=uint8) * 255

        rgb = img.copy()
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

        for c, (min, max) in filters.items():
            img = rgb if c in 'RGB' else hsv

            mask = img[:, :, self.channels[c]]
            mask[mask < min] = 0
            mask[mask > max] = 0

            acc_mask &= mask

        kernel = ones((5, 5), uint8)
        acc_mask = cv2.dilate(cv2.erode(acc_mask, kernel), kernel)

        circles = cv2.HoughCircles(acc_mask, cv2.HOUGH_GRADIENT, 3, img.shape[0] / 5.)
        return circles.reshape(-1, 3) if circles is not None else []
345485
def range_filter(field, start_date_math=None, end_date_math=None, **kwargs):
    
    def inner(values):
        if len(values) != 1 or values[0].count('--') != 1 or values[0] == '--':
            raise RESTValidationError(
                errors=[FieldError(field, 'Invalid range format.')])

        range_ends = values[0].split('--')
        range_args = dict()

        ineq_opers = [{'strict': 'gt', 'nonstrict': 'gte'},
                      {'strict': 'lt', 'nonstrict': 'lte'}]
        date_maths = [start_date_math, end_date_math]

        # Add the proper values to the dict
        for (range_end, strict, opers,
             date_math) in zip(range_ends, ['>', '<'], ineq_opers, date_maths):

            if range_end != '':
                # If first char is '>' for start or '<' for end
                if range_end[0] == strict:
                    dict_key = opers['strict']
                    range_end = range_end[1:]
                else:
                    dict_key = opers['nonstrict']

                if date_math:
                    range_end = '{0}||{1}'.format(range_end, date_math)

                range_args[dict_key] = range_end

        args = kwargs.copy()
        args.update(range_args)

        return Range(**{field: args})

    return inner
264098
def filters(self):
        
        results = []
        filters = self.qs.get('filter')
        if filters is not None:
            try:
                results.extend(json.loads(filters))
            except (ValueError, TypeError):
                raise InvalidFilters("Parse error")
        if self._get_key_values('filter['):
            results.extend(self._simple_filters(self._get_key_values('filter[')))
        return results
467435
def print_filters():
    """"""
    for filter_name in VALID_FILTERS:
        filter_func = getattr(filters, 'filter_{0}'.format(filter_name))
        description = filter_func.__doc__
        if description:
            description = re.sub(r'\n\s+', ' ', description)
            description.strip()

        print('{0}: {1}\n'.format(filter_name, description))
379759
def make_filter(**tests):
    """"""
    tests = [AttrTest(k, v) for k, v in tests.items()]
    return Filter(tests)
271329
def filter_data(self, min_len, max_len):
        
        logging.info(f'Filtering data, min len: {min_len}, max len: {max_len}')

        initial_len = len(self.src)
        filtered_src = []
        for src in self.src:
            if min_len <= len(src) <= max_len:
                filtered_src.append(src)

        self.src = filtered_src
        filtered_len = len(self.src)
        logging.info(f'Pairs before: {initial_len}, after: {filtered_len}')
293769
def trim_filter(filter, levels=1):
    ''''''
    trimmed = [f[levels:] for f in filter]
    return [f for f in trimmed if f]
1287003
function _getFilterIndex(filterSets, filter) {
        var index = -1;

        if (!filter || !filterSets.length) {
            return index;
        }

        return _.findIndex(filterSets, _.partial(_.isEqual, filter));
    }
885580
def parse_values(self, query):
        
        values = {}
        for name, filt in self.filters.items():
            val = filt.parse_value(query)
            if val is None:
                continue
            values[name] = val
        return values
11780
def get_filters(self):
        
        return dict(
            moment_format=self.format,
            moment_calendar=self.calendar,
            moment_fromnow=self.from_now,
        )
932204
def incremental_filter(input, list, delim)
      i = 0; input.gsub(delim) {|e| i+= 1 }
      delim_chars = delim.split('').uniq.join('')
      current_matches, future_matches = default_search(input, list).partition {|e|
        e[/^[^#{delim_chars}]*(#{delim}[^#{delim_chars}]+){0,#{i}}$/] }
      (current_matches + future_matches.map {|e| e[/^(([^#{delim_chars}]*#{delim}){0,#{i+1}})/, 1] }).uniq
    end
482276
def get_filters_values(self):
        
        return [(flt, value) for flt, value in zip(self.filters, self.values)]
865261
def apply_filters(self, filters):
        
        _configs = self.configs
        _stats = self.stats
        self.configs = {}
        self.stats = {}
        for f in filters:
            if f in _configs:
                self.configs[f] = _configs[f]
            elif f in _stats:
                self.stats[f] = _stats[f]
            else:
                raise NoSuchControlFileError("%s for %s" % (f, self.subsystem.name))
441
def _homogenize_data_filter(dfilter):
    
    if isinstance(dfilter, tuple) and (len(dfilter) == 1):
        dfilter = (dfilter[0], None)
    if (dfilter is None) or (dfilter == (None, None)) or (dfilter == (None,)):
        dfilter = (None, None)
    elif isinstance(dfilter, dict):
        dfilter = (dfilter, None)
    elif isinstance(dfilter, (list, str)) or (
        isinstance(dfilter, int) and (not isinstance(dfilter, bool))
    ):
        dfilter = (None, dfilter if isinstance(dfilter, list) else [dfilter])
    elif isinstance(dfilter[0], dict) or (
        (dfilter[0] is None) and (not isinstance(dfilter[1], dict))
    ):
        pass
    else:
        dfilter = (dfilter[1], dfilter[0])
    return dfilter
524865
function checkFilter(filter, type, test, real) {
    if (type == Table.TYPE_DATETIME) {
        if (typeof real != 'object')
            real = new Date(real * 1000);
        if (filter == Table.FILTER_BETWEEN
                && Array.isArray(test) && test.length == 2) {
            test = [
                test[0] ? moment.unix(test[0]) : null,
                test[1] ? moment.unix(test[1]) : null,
            ];
        } else if (filter != Table.FILTER_BETWEEN) {
            test = moment.unix(test);
        } else {
            return null;
        }
    } else {
        if (filter == Table.FILTER_BETWEEN) {
            if (!Array.isArray(test) || test.length != 2)
                return null;
        }
    }

    switch (filter) {
        case Table.FILTER_LIKE:
            return real !== null && real.indexOf(test) != -1;
        case Table.FILTER_EQUAL:
            return real !== null && test == real;
        case Table.FILTER_BETWEEN:
            if (real === null)
                return false;
            if (test[0] !== null && real < test[0])
                return false;
            if (test[1] !== null && real > test[1])
                return false;
            return true;
        case Table.FILTER_NULL:
            return real === null;
        default:
            throw new Error("Unknown filter: " + filter);
    }

    return false;
}
1112895
def filter_to_dmql(filter_dict):
        """"""

        if not isinstance(filter_dict, (dict, collections.OrderedDict)):
            raise TypeError('Expected a dictionary type buy got {} instead.'.format(type(filter_dict)))

        def is_date_time_type(val):
            """Returns True if the value is a datetime"""
            return isinstance(val, (datetime.datetime, datetime.date, datetime.time))

        def evaluate_datetime(val):
            """Converts the datetime object into the RETS expected format"""
            date_format = '%Y-%m-%d'
            time_format = '%H:%M:%S'
            datetime_format = '{}T{}'.format(date_format, time_format)

            if isinstance(val, datetime.datetime):
                evaluated = val.strftime(datetime_format)
            elif isinstance(val, datetime.date):
                evaluated = val.strftime(date_format)
            elif isinstance(val, datetime.time):
                evaluated = val.strftime(time_format)
            else:
                evaluated = val

            return evaluated

        def evaluate_operators(key_dict):
            """Turns the custom filter operators into the expected RETS query"""
            allowed_operators = ['$gte', '$lte', '$contains', '$begins', '$ends', '$in', '$nin', '$neq']

            # If key not in allowed_operators, assume it is a field name with the and operation.
            if not all(op in allowed_operators for op in key_dict.keys()):
                raise ValueError("You have supplied an invalid operator. "
                                 "Please provide one of the following {}".format(allowed_operators))

            # We can have a single operator key, or the combination of gte/lte
            keys = key_dict.keys()
            string = ''

            # Search between two numbers or two dates
            if len(keys) == 2 and all(k in ['$gte', '$lte'] for k in keys):
                if all(is_date_time_type(key_dict[v]) for v in keys):
                    # comparing dates
                    string = '{}-{}'.format(evaluate_datetime(key_dict['$gte']), evaluate_datetime(key_dict['$lte']))
                else:
                    # comparing numbers
                    try:
                        float(key_dict['$gte'])
                        float(key_dict['$lte'])
                    except ValueError:
                        raise ValueError("$gte and $lte expect numeric or datetime values")
                    string = '{:.2f}-{:.2f}'.format(key_dict['$gte'], key_dict['$lte'])

            # Using a single operator key
            elif len(keys) == 1:
                if '$gte' in key_dict:
                    if is_date_time_type(key_dict['$gte']):
                        string = '{}+'.format(evaluate_datetime(key_dict['$gte']))
                    else:
                        try:
                            float(key_dict['$gte'])
                        except ValueError:
                            raise ValueError("$gte expects a numeric value or a datetime object")
                        string = '{:.2f}+'.format(key_dict['$gte'])

                elif '$lte' in key_dict:
                    if is_date_time_type(key_dict['$lte']):
                        string = '{}-'.format(evaluate_datetime(key_dict['$lte']))
                    else:
                        try:
                            float(key_dict['$lte'])
                        except ValueError:
                            raise ValueError("$lte expects a numeric value or a datetime object")
                        string = '{:.2f}-'.format(key_dict['$lte'])

                elif '$in' in key_dict:
                    if not isinstance(key_dict['$in'], list):
                        raise ValueError("$in expects a list of strings")
                    key_dict['$in'] = [evaluate_datetime(v) for v in key_dict['$in']]
                    if not all(isinstance(v, string_types) for v in key_dict['$in']):
                        raise ValueError("$in expects a list of strings")
                    options = ','.join(key_dict['$in'])
                    string = '{}'.format(options)

                elif '$nin' in key_dict:
                    if not isinstance(key_dict['$nin'], list):
                        raise ValueError("$nin expects a list of strings")
                    key_dict['$nin'] = [evaluate_datetime(v) for v in key_dict['$nin']]
                    if not all(isinstance(v, string_types) for v in key_dict['$nin']):
                        raise ValueError("$nin expects a list of strings")
                    options = ','.join(key_dict['$nin'])
                    string = '~{}'.format(options)

                elif '$contains' in key_dict:
                    if not isinstance(key_dict['$contains'], string_types):
                        raise ValueError("$contains expects a string.")
                    string = '*{}*'.format(key_dict['$contains'])

                elif '$begins' in key_dict:
                    if not isinstance(key_dict['$begins'], string_types):
                        raise ValueError("$begins expects a string.")
                    string = '{}*'.format(key_dict['$begins'])

                elif '$ends' in key_dict:
                    if not isinstance(key_dict['$ends'], string_types):
                        raise ValueError("$ends expects a string.")
                    string = '*{}'.format(key_dict['$ends'])

                elif '$neq' in key_dict:
                    string = '~{}'.format(key_dict['$neq'])

            else:
                # Provided too many or too few operators
                raise ValueError("Please supply $gte and $lte for getting values between numbers or 1 of {}".format(
                    allowed_operators))

            return string

        dmql_search_filters = []

        for filt, value in filter_dict.items():
            dmql_string = '({}='.format(filt)
            if isinstance(value, dict):
                # Applying an operator. This will need to be recursive because of the or possibility
                dmql_string += evaluate_operators(key_dict=value)
            else:
                # Simle equals statement
                dmql_string += '{}'.format(evaluate_datetime(value))
            dmql_string += ')'
            dmql_search_filters.append(dmql_string)

        search_string = ','.join(dmql_search_filters)
        # Converts the filter dictionary to dmqp string
        logger.debug("Filter returned the following DMQL: {}".format(search_string))
        return search_string
592194
def filter(self, search):
        '''
        
        '''
        if not self._filters:
            return search
        filters = Q('match_all')
        for f in self._filters.values():
            filters &= f
        return search.filter(filters)