Query wikis randomly.
426716
def query_random(num=6, kind='1'):
        '''
        
        '''
        return TabWiki.select().where(
            TabWiki.kind == kind
        ).order_by(
            peewee.fn.Random()
        ).limit(num)
194648
def wiki(searchterm):
    """"""
    searchterm = quote(searchterm)

    url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json"
    url = url.format(searchterm)

    result = requests.get(url).json()

    pages = result["query"]["search"]

    # try to reject disambiguation pages
    pages = [p for p in pages if 'may refer to' not in p["snippet"]]

    if not pages:
        return ""

    page = quote(pages[0]["title"].encode("utf8"))
    link = "http://en.wikipedia.org/wiki/{0}".format(page)

    r = requests.get(
        "http://en.wikipedia.org/w/api.php?format=json&action=parse&page={0}".
        format(page)).json()
    soup = BeautifulSoup(r["parse"]["text"]["*"], "html5lib")
    p = soup.find('p').get_text()
    p = p[:8000]

    return u"{0}\n{1}".format(p, link)
935616
def wikipedia_search(query, lang="en", max_result=1):
    
    query = any2unicode(query)
    params = {
        "action":"opensearch",
        "search": query,
        "format":"json",
        #"formatversion":2,
        #"namespace":0,
        "suggest":"true",
        "limit": 10
    }
    urlBase = "https://{}.wikipedia.org/w/api.php?".format(lang)
    url = urlBase + urllib.urlencode(any2utf8(params))
    #logging.info(url)
    r = requests.get(url)
    jsonData = json.loads(r.content)
    #logging.info(jsonData)

    items = []
    ret = {"query":query, "itemList":items}
    for idx, label in enumerate(jsonData[1][0:max_result]):
        description = jsonData[2][idx]
        url = jsonData[3][idx]

        item = {
            "name": label,
            "description":description,
            "url": url,
        }
        items.append(item)

    return ret
716082
def query_walkers():
    """"""
    return [
        import_string(walker)() if isinstance(walker, six.string_types)
        else walker() for walker in current_app.config[
            'COLLECTIONS_QUERY_WALKERS']
    ]
991599
def search_list(kb, value=None, match_type=None,
                    page=None, per_page=None, unique=False):
        """"""
        # init
        page = page or 1
        per_page = per_page or 10

        if kb.kbtype == models.KnwKB.KNWKB_TYPES['written_as']:
            # get the base query
            query = api.query_kb_mappings(
                kbid=kb.id,
                value=value or '',
                match_type=match_type or 's'
            ).with_entities(models.KnwKBRVAL.m_value)
            # if you want a 'unique' list
            if unique:
                query = query.distinct()
            # run query and paginate
            return [item.m_value for item in
                    pagination.RestfulSQLAlchemyPagination(
                        query, page=page or 1,
                        per_page=per_page or 10
                    ).items]
        elif kb.kbtype == models.KnwKB.KNWKB_TYPES['dynamic']:
            items = api.get_kbd_values(kb.name, value)
            return pagination.RestfulPagination(
                page=page, per_page=per_page,
                total_count=len(items)
            ).slice(items)
        return []
347424
def index():
    """"""
    page = request.values.get('page', 1, type=int)
    size = request.values.get('size', 2, type=int)
    search = ExampleSearch()[(page - 1) * size:page * size]
    if 'q' in request.values:
        search = search.query(QueryString(query=request.values.get('q')))

    search = search.sort(
        request.values.get('sort', 'title')
    )
    search = ExampleSearch.faceted_search(search=search)
    results = search.execute().to_dict()
    return jsonify({'hits': results.get('hits')})
435828
def query(qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
          tcp=False, source=None, raise_on_no_answer=True, resolver=None):
    """"""
    if resolver is None:
        resolver = get_default_resolver()
    return resolver.query(qname, rdtype, rdclass, tcp, source, raise_on_no_answer)
711753
def random(pages=1):
  '''
  
  '''
  #http://en.wikipedia.org/w/api.php?action=query&list=random&rnlimit=5000&format=jsonfm
  query_params = {
    'list': 'random',
    'rnnamespace': 0,
    'rnlimit': pages,
  }

  request = _wiki_request(query_params)
  titles = [page['title'] for page in request['query']['random']]

  if len(titles) == 1:
    return titles[0]

  return titles
1253750
def query_most(num=8, kind='1'):
        '''
        
        '''
        return TabWiki.select().where(
            TabWiki.kind == kind
        ).order_by(
            TabWiki.view_count.desc()
        ).limit(num)
125719
def wiki_pages(self, extra_params=None):
        
        return self.api._get_json(
            WikiPage,
            space=self,
            rel_path=self._build_rel_path('wiki_pages'),
            extra_params=extra_params,
        )
1291068
def query(self):
        """"""
        if self._query is None:
            query_string = self.environ.get('QUERY_STRING')
            self._query = QueryDict([
                (k.decode('utf-8'), v.decode('utf-8'))
                for k, v in urlparse.parse_qsl(
                    query_string, keep_blank_values=True)
            ])
        return self._query
505105
def get_query(self, q, request):
        
        return Group.objects.filter(
            Q(name__icontains=q)
            | Q(description__icontains=q)
        )
1269300
def query(wosclient, wos_query, xml_query=None, count=5, offset=1, limit=100):
    """"""
    results = [single(wosclient, wos_query, xml_query, min(limit, count-x+1), x)
               for x in range(offset, count+1, limit)]
    if xml_query:
        return [el for res in results for el in res]
    else:
        pattern = _re.compile(r'^<\?xml.*?\n<records>\n|\n</records>$.*')
        return ('<?xml version="1.0" ?>\n<records>' +
                '\n'.join(pattern.sub('', res) for res in results) +
                '</records>')
251573
def refresh(self):
        '''
        
        '''
        kwd = {
            'pager': '',
            'title': '最近文档',
        }
        self.render('wiki_page/wiki_list.html',
                    view=MWiki.query_dated(16),
                    format_date=tools.format_date,
                    kwd=kwd,
                    userinfo=self.userinfo)
331250
def index_queryset(self, using=None):
        """"""

        kwargs = {"active": True}

        # if permissions are enabled then we want only public pages
        # https://github.com/leonardo-modules/leonardo-module-pagepermissions
        if hasattr(Page(), 'permissions'):
            kwargs['permissions__isnull'] = True

        # https://github.com/leonardo-modules/leonardo-page-search
        if hasattr(Page(), 'search_exclude'):
            kwargs['search_exclude'] = False

        return self.get_model().objects.filter(**kwargs)
137476
def get_last(postid):
        '''
        
        '''
        recs = TabWikiHist.select().where(
            TabWikiHist.wiki_id == postid
        ).order_by(TabWikiHist.time_update.desc())

        return None if recs.count() == 0 else recs.get()
1189497
def query(self, query):
    ''''''
    results = super(SymlinkDatastore, self).query(query)
    return self._follow_link_gen(results)