find categories/products that match search terms
556955
public function categorySearchChildrenAction()
    {
        $type = $this->params('type');
        $children = $this->getService($type)->getAll();

        $viewVars = array('children' => $children, 'type' => $type);
        return $this->partialView('category-search-children', $viewVars);
    }
371925
def filterItems(self,
                    terms,
                    autoExpand=True,
                    caseSensitive=False):
        
        # create a dictionary of options
        if type(terms) != dict:
            terms = {'*': nativestring(terms)}
        
        # create a dictionary of options
        if type(terms) != dict:
            terms = {'*': nativestring(terms)}
        
        # validate the "all search"
        if '*' in terms and type(terms['*']) != list:
            sterms = nativestring(terms['*'])
            
            if not sterms.strip():
                terms.pop('*')
            else:
                dtype_matches = COLUMN_FILTER_EXPR.findall(sterms)
                
                # generate the filter for each data type
                for match, dtype, values in dtype_matches:
                    sterms = sterms.replace(match, '')
                    terms.setdefault(dtype, [])
                    terms[dtype] += values.split(',')
                
                keywords = sterms.replace(',', '').split()
                while '' in keywords:
                    keywords.remove('')
                
                terms['*'] = keywords
        
        # filter out any columns that are not being searched
        filtered_columns = self.filteredColumns()
        filter_terms = {}
        for column, keywords in terms.items():
            index = self.column(column)
            if column != '*' and not index in filtered_columns:
                continue
            
            if not caseSensitive:
                keywords = [nativestring(keyword).lower() for keyword in keywords]
            else:
                keywords = map(str, keywords)
            
            filter_terms[index] = keywords
        
        self.__filterItems(filter_terms, autoExpand, caseSensitive, 0)
196276
def match_fields(fields, searches,
                 ignore_case=False, wholename=False, complement=False):
    
    if ignore_case:
        fields = [f.lower() for f in fields]
        searches = [s.lower() for s in searches]
    if wholename:
        match_found = _complete_match
    else:
        match_found = _partial_match

    fields = [(i, field) for i, field in enumerate(fields)]
    matched = []
    for search, (idx, field) in itertools.product(searches, fields):
        if not search:  ## don't return all fields for ''
            continue
        if match_found(search, field) and idx not in matched:
            matched.append(idx)

    if complement:
        matched = [idx for idx in list(zip(*fields))[0] if idx not in matched]

    return matched
849484
def search(self):
        """"""

        matches = []
        for index, cell in enumerate(self.cells):
            for pattern in Config.patterns:
                if ismatch(cell, pattern):
                    matches.append(index)
                    break

        return matches
965617
def build_search(self):
        
        s = self.search()
        s = self.query(s, self._query)
        s = self.filter(s)
        if self.fields:
            s = self.highlight(s)
        s = self.sort(s)
        self.aggregate(s)
        return s
1281808
def find_matches(text):
    
    """
    path = os.path.expanduser(text)
    if os.path.isdir(path) and not path.endswith('/'):
        return [ text + '/' ]

    pattern = path + '*'
    is_implicit_cwd = not (path.startswith('/') or path.startswith('./'))
    if is_implicit_cwd:
        pattern = './' + pattern
    rawlist = glob.glob(pattern)
    ret = []
    for fname in rawlist:
        if is_implicit_cwd:
            fname = fname[2:]
        if os.path.isdir(fname):
            ret.append(fname + '/')
        else:
            ret.append(fname)
    return ret
718597
def query(self, search, query):
        '''
        
        '''
        if not query:
            return search

        included, excluded = [], []
        for term in query.split(' '):
            if not term.strip():
                continue
            if term.startswith('-'):
                excluded.append(term[1:])
            else:
                included.append(term)
        if included:
            search = search.query(self.multi_match(included))
        for term in excluded:
            search = search.query(~self.multi_match([term]))
        return search
164032
def search_for(self, query, include_draft=False):
        
        query = query.lower()
        if not query:
            return []

        def contains_query_keyword(post_or_page):
            contains = query in post_or_page.title.lower() \
                       or query in Markup(
                get_parser(post_or_page.format).parse_whole(
                    post_or_page.raw_content)
            ).striptags().lower()
            return contains

        return filter(contains_query_keyword,
                      chain(self.get_posts(include_draft=include_draft),
                            self.get_pages(include_draft=include_draft)
                            if current_app.config[
                                'ALLOW_SEARCH_PAGES'] else []))
163234
def _build_search_query(self, from_date):
        

        sort = [{self._sort_on_field: {"order": "asc"}}]

        filters = []
        if self._repo:
            filters.append({"term": {"origin": self._repo}})

        if from_date:
            filters.append({"range": {self._sort_on_field: {"gte": from_date}}})

        if filters:
            query = {"bool": {"filter": filters}}
        else:
            query = {"match_all": {}}

        search_query = {
            "query": query,
            "sort": sort
        }

        return search_query
1082237
function (items, query, fields, exact) {
        var self = this;
        var isTarget = function (fieldName) {
          return fields.indexOf(fieldName) !== -1;
        };
        if (query === '') {
          return items;
        }
        fields = fields || ['name', 'owner', 'description', 'keyword'];
        return _.filter(items, function (item) {
          if ((isTarget('name') && self.matchedInString(query, item.name, exact)) ||
              (isTarget('owner') && self.matchedInString(query, item.owner, exact)) ||
              (isTarget('description') && self.matchedInString(query, item.description, exact)) ||
              (isTarget('keyword') && self.matchedInArray(query, item.keywords, exact))) {
            return true;
          }
          return false;
        });
      }
1215781
def list_matching_entries(program, arguments):
    """"""
    output("\n".join(entry.name for entry in program.smart_search(*arguments)))
425140
public function findAllByFilters($category, Array $options, $getResults = true)
    {
        $qb = $this->getQueryBuilder()
            ->select('p');

        if (is_null($category) && array_key_exists('s-with-dashes', $options)) {
            // searching
            $orX = $qb->expr()->orX();
            $orX->add('p.name LIKE :searchWithDashes')
                ->add('p.name LIKE :searchWithSpaces');
            $qb->andWhere($orX)
                ->setParameter('searchWithDashes', '%'.$options['s-with-dashes'].'%')
                ->setParameter('searchWithSpaces', '%'.$options['s-with-spaces'].'%');
        } elseif (!is_null($category)) {
            if (!is_null($category->getParentCategory())) {
                // listing by subcategory (put in 'where' as it is)
                $qb->andWhere('p.category = :category')
                    ->setParameter('category', $category);
            } else {
                // listing by category (put its subcategories in a chained 'or')
                $orX = $qb->expr()->orX();

                foreach ($category->getSubcategories() as $subcategory) {
                    $orX->add('IDENTITY(p.category) = '.$subcategory->getId());
                }

                $qb->andWhere($orX);
            }
        }

        // sort filter
        if (false === array_key_exists('sort', $options)) {
            $options['sort'] = 'price-asc';
        }

        switch ($options['sort']) {
            case 'newest':
                $qb->orderBy('p.createdAt', 'desc');
                break;
            case 'oldest':
                $qb->orderBy('p.createdAt', 'asc');
                break;
            case 'price-asc':
                $qb->orderBy('p.price', 'asc');
                break;
            case 'price-desc':
                $qb->orderBy('p.price', 'desc');
                break;
        }

        // brands filter
        if (array_key_exists('brands', $options)) {
            $orX = $qb->expr()->orX();

            foreach ($options['brands'] as $brand) {
                $orX->add('IDENTITY(p.brand) = '.$brand);
            }

            $qb->andWhere($orX);
        }

        // attributes filter
        if (array_key_exists('attributes', $options)) {
            $qb->join('p.attributeValues', 'av');

            $orX = $qb->expr()->orX();

            foreach ($options['attributes'] as $attribute) {
                $orX->add('av.id = '.$attribute);
            }

            $qb->andWhere($orX);
        }

        // features filter
        if (array_key_exists('features', $options)) {
            $qb->join('p.featureValues', 'fv');

            $orX = $qb->expr()->orX();

            foreach ($options['features'] as $feature) {
                $orX->add('fv.id = '.$feature);
            }

            $qb->andWhere($orX);
            $qb->having('count(p.id) >= :num_features');
            $numFeatures = count($options['features']);
            $qb->setParameter('num_features', $numFeatures);
        }
        $qb->groupBy('p.id');

        // attribute ranges filter
/*        if (array_key_exists('attribute-min', $options) && array_key_exists('attribute-max', $options)) {
            if (false === array_key_exists('attributes', $options)) {
                $qb->join('p.attributeValues', 'av');
            }

            $andX = $qb->expr()->andX();

            foreach ($options['attribute-min'] as $value) {
                $andX->add('av.name >= '.$value);
            }

            foreach ($options['attribute-max'] as $value) {
                $andX->add('av.name <= '.$value);
            }

            $qb->andWhere($andX);
        }*/

        // feature ranges filter
/*        if (array_key_exists('feature-min', $options) && array_key_exists('feature-max', $options)) {
            if (false === array_key_exists('features', $options)) {
                $qb->join('p.featureValues', 'fv');
            }

            $andX = $qb->expr()->andX();

            foreach ($options['feature-min'] as $value) {
                $andX->add('fv.name >= '.$value);
            }

            foreach ($options['feature-max'] as $value) {
                $andX->add('fv.name <= '.$value);
            }

            $qb->andWhere($andX);
        }*/

        $query = $qb->getQuery();

        return $getResults ? $query->getResult() : $query;
    }
1278215
def search(self):
        """"""

        matches = []
        for pattern in Config.patterns:
            matches += self.termfinder(pattern)

        return sorted(set(matches), key=int)
884461
def search_prod_type_tags(self, tipo, ins, tags, pipeline):
        """"""

        drp = self.drps.query_by_name(ins)
        label = drp.product_label(tipo)

        # Strip () is present
        if label.endswith("()"):
            label_alt = label[:-2]
        else:
            label_alt = label

        # search results of these OBs
        for prod in self.prod_table[ins]:
            pk = prod['type'] 
            pt = prod['tags']
            if ((pk == label) or (pk == label_alt)) and tags_are_valid(pt, tags):
                # this is a valid product
                # We have found the result, no more checks
                # Make a copy
                rprod = dict(prod)
                rprod['content'] = numina.store.load(tipo, prod['content'])
                return StoredProduct(**rprod)
        else:
            msg = 'type %s compatible with tags %r not found' % (tipo, tags)
            raise NoResultFound(msg)
325578
def query_names(self, pat):
        """"""

        for item in self.chnames.items():
            if fnmatch.fnmatchcase(item[1], pat):
                print item
424250
def _build_label_filter(category, *args, **kwargs):
    """"""
    terms = list(args)
    for key, value in six.iteritems(kwargs):
        if value is None:
            continue

        suffix = None
        if key.endswith(
            ("_prefix", "_suffix", "_greater", "_greaterequal", "_less", "_lessequal")
        ):
            key, suffix = key.rsplit("_", 1)

        if category == "resource" and key == "resource_type":
            key = "resource.type"
        else:
            key = ".".join((category, "label", key))

        if suffix == "prefix":
            term = '{key} = starts_with("{value}")'
        elif suffix == "suffix":
            term = '{key} = ends_with("{value}")'
        elif suffix == "greater":
            term = "{key} > {value}"
        elif suffix == "greaterequal":
            term = "{key} >= {value}"
        elif suffix == "less":
            term = "{key} < {value}"
        elif suffix == "lessequal":
            term = "{key} <= {value}"
        else:
            term = '{key} = "{value}"'

        terms.append(term.format(key=key, value=value))

    return " AND ".join(sorted(terms))
523710
def search_mode_provides(self, product, pipeline='default'):
        """"""

        pipeline = self.pipelines[pipeline]
        for obj, mode, field in self.iterate_mode_provides(self.modes, pipeline):
            # extract name from obj
            if obj.name() == product:
                return ProductEntry(obj.name(), mode.key, field)
        else:
            raise ValueError('no mode provides %s' % product)