Search a sharepoint host for sites with the provided keyword

        :param keyword: a keyword to search sites
        :rtype: list[Site]
168268
def search_site(self, keyword):
        
        if not keyword:
            raise ValueError('Must provide a valid keyword')

        url = self.build_url(
            self._endpoints.get('search').format(keyword=keyword))

        response = self.con.get(url)
        if not response:
            return []

        data = response.json()

        # Everything received from cloud must be passed as self._cloud_data_key
        return [
            self.site_constructor(parent=self, **{self._cloud_data_key: site})
            for site in data.get('value', [])]
192763
def __get_hosts(self, pattern):
        

        (name, enumeration_details) = self._enumeration_info(pattern)
        hpat = self._hosts_in_unenumerated_pattern(name)
        hpat = sorted(hpat, key=lambda x: x.name)

        return set(self._apply_ranges(pattern, hpat))
593977
def search(self, q, language=None, current_site_only=True):
        
        from cms.plugin_pool import plugin_pool

        qs = self.get_queryset()
        qs = qs.public()

        if current_site_only:
            site = Site.objects.get_current()
            qs = qs.filter(tree__site=site)

        qt = Q(title_set__title__icontains=q)

        # find 'searchable' plugins and build query
        qp = Q()
        plugins = plugin_pool.get_all_plugins()
        for plugin in plugins:
            cmsplugin = plugin.model
            if not (
                hasattr(cmsplugin, 'search_fields') and
                hasattr(cmsplugin, 'cmsplugin_ptr')
            ):
                continue
            field = cmsplugin.cmsplugin_ptr.field
            related_query_name = field.related_query_name()
            if related_query_name and not related_query_name.startswith('+'):
                for field in cmsplugin.search_fields:
                    qp |= Q(**{
                        'placeholders__cmsplugin__{0}__{1}__icontains'.format(
                            related_query_name,
                            field,
                        ): q})
        if language:
            qt &= Q(title_set__language=language)
            qp &= Q(cmsplugin__language=language)

        qs = qs.filter(qt | qp)

        return qs.distinct()
942497
def search(self, keyword, children=None, arg=None):
        
        if children is None:
            children = self.substmts
        return [ ch for ch in children
                 if (ch.keyword == keyword and
                     (arg is None or ch.arg == arg))]
747966
def get_namespace_by_keyword_version(self, keyword: str, version: str) -> Optional[Namespace]:
        """"""
        filt = and_(Namespace.keyword == keyword, Namespace.version == version)
        return self.session.query(Namespace).filter(filt).one_or_none()
629773
def endpoint_search(filter_fulltext, filter_owner_id, filter_scope):
    
    if filter_scope == "all" and not filter_fulltext:
        raise click.UsageError(
            "When searching all endpoints (--filter-scope=all, the default), "
            "a full-text search filter is required. Other scopes (e.g. "
            "--filter-scope=recently-used) may be used without specifying "
            "an additional filter."
        )

    client = get_client()

    owner_id = filter_owner_id
    if owner_id:
        owner_id = maybe_lookup_identity_id(owner_id)

    search_iterator = client.endpoint_search(
        filter_fulltext=filter_fulltext,
        filter_scope=filter_scope,
        filter_owner_id=owner_id,
    )

    formatted_print(
        search_iterator,
        fields=ENDPOINT_LIST_FIELDS,
        json_converter=iterable_response_to_dict,
    )
1104478
def ListClientsForKeywords(self, keywords, start_time=None, cursor=None):
    """"""
    keywords = set(keywords)
    hash_to_kw = {mysql_utils.Hash(kw): kw for kw in keywords}
    result = {kw: [] for kw in keywords}

    query = """
      SELECT keyword_hash, client_id
      FROM client_keywords
      FORCE INDEX (client_index_by_keyword_hash)
      WHERE keyword_hash IN ({})
    """.format(", ".join(["%s"] * len(result)))
    args = list(iterkeys(hash_to_kw))
    if start_time:
      query += " AND timestamp >= FROM_UNIXTIME(%s)"
      args.append(mysql_utils.RDFDatetimeToTimestamp(start_time))
    cursor.execute(query, args)

    for kw_hash, cid in cursor.fetchall():
      result[hash_to_kw[kw_hash]].append(db_utils.IntToClientID(cid))
    return result
335198
def search():
    """"""
    pattern = flask.request.args.get('pattern', "*").strip().lower()

    # if the pattern contains "in:<collection>" (eg: in:builtin),
    # filter results to only that (or those) collections
    # This was kind-of hacked together, but seems to work well enough
    collections = [c["name"].lower() for c in current_app.kwdb.get_collections()]
    words = []
    filters = []
    if pattern.startswith("name:"):
        pattern = pattern[5:].strip()
        mode = "name"
    else:
        mode="both"

    for word in pattern.split(" "):
        if word.lower().startswith("in:"):
            filters.extend([name for name in collections if name.startswith(word[3:])])
        else:
            words.append(word)
    pattern = " ".join(words)

    keywords = []
    for keyword in current_app.kwdb.search(pattern, mode):
        kw = list(keyword)
        collection_id = kw[0]
        collection_name = kw[1].lower()
        if len(filters) == 0 or collection_name in filters:
            url = flask.url_for(".doc_for_library", collection_id=kw[0], keyword=kw[2])
            row_id = "row-%s.%s" % (keyword[1].lower(), keyword[2].lower().replace(" ","-"))
            keywords.append({"collection_id": keyword[0],
                             "collection_name": keyword[1],
                             "name": keyword[2],
                             "synopsis": keyword[3],
                             "version": __version__,
                             "url": url,
                             "row_id": row_id
                         })

    keywords.sort(key=lambda kw: kw["name"])
    return flask.render_template("search.html",
                                 data={"keywords": keywords,
                                       "version": __version__,
                                       "pattern": pattern
                                   })
1008910
def search(self, keyword, p_index=''):
        '''
        
        '''
        if p_index == '' or p_index == '-1':
            current_page_number = 1
        else:
            current_page_number = int(p_index)
        res_all = self.ysearch.get_all_num(keyword)
        results = self.ysearch.search_pager(
            keyword,
            page_index=current_page_number,
            doc_per_page=CMS_CFG['list_num']
        )
        page_num = int(res_all / CMS_CFG['list_num'])
        kwd = {'title': '查找结果',
               'pager': '',
               'count': res_all,
               'keyword': keyword,
               'catid': '',
               'current_page': current_page_number}
        self.render('misc/search/search_list.html',
                    kwd=kwd,
                    srecs=results,
                    pager=gen_pager_bootstrap_url(
                        '/search/{0}'.format(keyword),
                        page_num,
                        current_page_number
                    ),
                    userinfo=self.userinfo,
                    cfg=CMS_CFG)
334352
def keywords(self):
        
        return [x[0] for x in self.session.query(models.Keyword.name).all()]
1233383
def on_site(self):
        
        return super(EntryPublishedManager, self).get_queryset().filter(
            sites=Site.objects.get_current())
738471
def _get_keywords(self, location, keywords):
        """"""
        if 'xml' in keywords:
            keywords.pop('xml')
            self.xml = True
        else:
            keywords['file_type'] = 'json'
        if 'id' in keywords:
            if location != 'series':
                location = location.rstrip('s')
            key = '%s_id' % location
            value = keywords.pop('id')
            keywords[key] = value
        if 'start' in keywords:
            time = keywords.pop('start')
            keywords['realtime_start'] = time
        if 'end' in keywords:
            time = keywords.pop('end')
            keywords['realtime_end'] = time
        if 'sort' in keywords:
            order = keywords.pop('sort')
            keywords['sort_order'] = order
        keywords['api_key'] = self.api_key
        return keywords
126966
def get_hosts(self, pattern="all"):
        

        # process patterns
        if isinstance(pattern, list):
            pattern = ';'.join(pattern)
        patterns = pattern.replace(";",":").split(":")
        hosts = self._get_hosts(patterns)

        # exclude hosts not in a subset, if defined
        if self._subset:
            subset = self._get_hosts(self._subset)
            hosts.intersection_update(subset)

        # exclude hosts mentioned in any restriction (ex: failed hosts)
        if self._restriction is not None:
            hosts = [ h for h in hosts if h.name in self._restriction ]
        if self._also_restriction is not None:
            hosts = [ h for h in hosts if h.name in self._also_restriction ]

        return sorted(hosts, key=lambda x: x.name)
147090
def list_sites():
    '''
    
    '''
    ret = dict()
    ps_cmd = ['Get-ChildItem',
              '-Path', r"'IIS:\Sites'",
              '|',
              'Select-Object applicationPool, applicationDefaults, Bindings, ID, Name, PhysicalPath, State']

    keep_keys = ('certificateHash', 'certificateStoreName', 'protocol', 'sslFlags')

    cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True)

    try:
        items = salt.utils.json.loads(cmd_ret['stdout'], strict=False)
    except ValueError:
        raise CommandExecutionError('Unable to parse return data as Json.')

    for item in items:
        bindings = dict()

        for binding in item['bindings']['Collection']:

            # Ignore bindings which do not have host names
            if binding['protocol'] not in ['http', 'https']:
                continue

            filtered_binding = dict()

            for key in binding:
                if key in keep_keys:
                    filtered_binding.update({key.lower(): binding[key]})

            binding_info = binding['bindingInformation'].split(':', 2)
            ipaddress, port, hostheader = [element.strip() for element in binding_info]
            filtered_binding.update({'hostheader': hostheader,
                                     'ipaddress': ipaddress,
                                     'port': port})
            bindings[binding['bindingInformation']] = filtered_binding

        # ApplicationDefaults
        application_defaults = dict()

        for attribute in item['applicationDefaults']['Attributes']:
            application_defaults.update({attribute['Name']: attribute['Value']})
        # ApplicationDefaults

        ret[item['name']] = {'apppool': item['applicationPool'],
                             'bindings': bindings,
                             'applicationDefaults': application_defaults,
                             'id': item['id'],
                             'state': item['state'],
                             'sourcepath': item['physicalPath']}

    if not ret:
        log.warning('No sites found in output: %s', cmd_ret['stdout'])

    return ret
1359105
def keyword_informations(keyword, options={})
      response = connection.get do |req|
        req.url "insight/keywords/#{keyword}", options
      end
      return_error_or_body(response)
    end
915534
def filter_host_by_regex(regex):
    
    host_re = re.compile(regex)

    def inner_filter(items):
        """Inner filter for host. Accept if regex match host_name"""
        host = items["host"]
        if host is None:
            return False
        return host_re.match(host.host_name) is not None

    return inner_filter
253241
def set_keywords(self, keywords):
        
        self._query_params += str(QueryParam.KEYWORDS) + '+'.join(keywords)