Esempio n. 1
0
File: da.py Progetto: jindongh/vps
def analyze(query):
    #1.help/BangZhu
    if query in ['subscribe', 'help', 'menu', u'\u5e2e\u52a9'.encode('utf-8')]:
        return helpMsg()
    #2.birthday
    if query == u'\u751f\u65e5'.encode('utf-8'):
        return '\n'.join(birthList())
    if query.startswith(u'\u751f\u65e5 '.encode('utf-8')):
        return birthOP(query)
    if query.startswith('gmail'):
        return gmail.getMails()
    #3. services
    ensubquery=query.split()
    chsubquery=query.split(u'\u3000'.encode('utf-8'))
    subquery=query
    sublen=0
    if len(ensubquery)>1: #there is subquery in english
        subquery=ensubquery[0]
        sublen=1
    if len(chsubquery)>1 and len(chsubquery[0]) < len(subquery):#there is subquery in chinese and shorter
        subquery=chsubquery[0]
        sublen=3
    if not subquery==query:
        #1.translate
        if subquery in ('translate', u'\u7ffb\u8bd1'.encode('utf-8')):
            return api.translate(query[len(subquery)+1:])
        #2. movie, eatting, shopping, entertain, hotel, travel
        if subquery in SERVICES:
            print SERVICES[subquery].decode('utf-8').encode('gbk')
            return api.search(query[len(subquery)+sublen:], SERVICES[subquery])
    #4 default
    if api.isEnglish(query):
        return 'Transtate:'+api.translate(query)
    else:
        return api.search(query)
Esempio n. 2
0
def navegar():
    """
    GET: Mostra a pagina com o formulario
    POST: preforma a busca na API e mostra os resultados
    """

    # GET request
    if request.method == "GET":
        return render_template("navegar.html")

    # POST request
    elif request.method == "POST":

        # pega os dados da pagina
        query = request.form.get("query")
        seed = request.form.get("seed-mode")

        # determina se e necessaria uma busca por relacionados ou por termo
        if request.form.get("seed-mode") == True:
            videos = search('related', query)
        else:
            videos = search('query', query)

        # render the page
        return render_template("results.html", videos=videos)
Esempio n. 3
0
def parse_input(inputstr):
    """
    Parse the input
    """
    word_list = inputstr.split()

    if word_list[0] == 'roll':
        functions.roll(word_list[1:])

    elif word_list[0] == 'search':
        api.search(word_list[1:])

    elif word_list[0] == 'load':
        return functions.load_char(word_list[1:])
Esempio n. 4
0
def do_search():
    args = dict(
        book_id=request.args.get('book_id', None),
        author_id=request.args.get('author_id', None),
        serie_id=request.args.get('serie_id', None),
        genre_id=request.args.get('genre_id', None),
        keyword_id=request.args.get('keyword_id', None),
        start=int(request.args.get('start', 0)),
        count=int(request.args.get('count', 0)),
        author=request.args.get('author', None),
        title=request.args.get('title', None),
        serie=request.args.get('serie', None),
        genre=request.args.get('genre', None),
        keyword=request.args.get('keyword', None),
        rate_min=request.args.get('rate_min', None),
        rate_max=request.args.get('rate_max', None),
        lang=request.args.get('lang', None),
        order=request.args.get('order', None),
    )

    if (args['book_id'] or args['author_id'] or args['serie_id']
            or (args['count'] < 1000 and args['count'] > 0)
            or (args['author'] and [i for i in args['author'] if i.isalnum()])
            or (args['title'] and [i for i in args['title'] if i.isalnum()])
            or (args['serie'] and [i for i in args['serie'] if i.isalnum()])):
        return api.search(get_db(), **args)
    else:
        return None
Esempio n. 5
0
    def do_GET(self):
        ext = self.path[-3:]
        if ext == "pls":
            query = self.path[:-4].split('/')[1]

            self.send_response(200)
            self.send_header('Content-Type', 'audio/x-scpls')
            self.end_headers()

            self.wfile.write("[playlist]\n\n")
            for i, song in enumerate(api.search(query.replace('+', ' ')), 1):
                self.wfile.write("File%s=%s\n" % (i, sanitize(song)))
                self.wfile.write("Title%s=%s\n" % (i, 
                    song.artist + " - " +  song.title))
                self.wfile.write("Lenght%s=-1\n\n" % i)
            self.wfile.write("NumberOfEntries=%s\n" % (i+1))
            self.wfile.write("Version=2")

        elif ext == 'mp3':
            id = self.path[:-4].rsplit('/', 1)[1]
            self.send_response(200)
            self.send_header('Content-Type', 'audio/mpeg')
            self.end_headers()

            song = api.Song(id=id)

            for data in song.data:
                self.wfile.write(data)
        else:
            self.send_error(404, 'File Not Found: %s' % self.path)
def test_search(search_terms, expected_results):
    results = search(search_terms)
    result_ids = [r.id for r in results]

    assert len(result_ids) == len(expected_results)
    for id in result_ids:
        assert id in expected_results
    assert len(set(result_ids)) == len(result_ids)
Esempio n. 7
0
def getMeal(uid, price, nick):
    user = api.getUser(uid)
    nearby = api.search(uid, nick)
    price = int(10000 * float(price) /
                (100 + float(user["tip"]))) / 100.0 / 1.0875
    # return json.dumps(nearby)
    choices_outer = []
    for rest in nearby:
        if rest["mino"] <= price and rest["is_delivering"] == 1:
            rest_data = api.getDetails(rest["id"])
            choices = []
            addons = []
            if api.cuisineCheck(rest_data["cuisine"], uid):
                for category in rest_data["menu"]:
                    for listing in category["children"]:
                        if float(listing["price"]) <= price:
                            listing["rest"] = rest["id"]
                            foodItem = meal(listing)
                            if foodItem.price < 4.85 or foodItem.price < 0.6 * price or not api.valid(
                                    listing):
                                base = addons
                            else:
                                base = choices
                            if "children" in listing:
                                for option in listing["children"]:
                                    if api.valid(option):
                                        title = option["name"]
                                        flex = api.checkFlexibility(title)
                                        if "children" in option:
                                            for op in option["children"]:
                                                optionItem = meal(op)
                                                foodItem.addOption(
                                                    title, optionItem, flex)
                            base.append(foodItem)
            choices_outer.append([choices, addons])
    meals = []
    spent = 0
    score = 0
    while score < random.random():
        rest_index = random.randrange(len(choices_outer))
        rest_pick = choices_outer[rest_index]
        if len(rest_pick[0]) != 0:
            meal_index = random.randrange(len(rest_pick[0]))
            meal_pick = rest_pick[0][meal_index]
            final_meal, total_price = meal_pick.pickOptions(price)
            if total_price <= price - spent:
                meals.append(final_meal.toDict())
                spent = spent + total_price
            elif spent < total_price:
                meals = final_meal.toDict()
                spent = total_price
            score = (float(spent) / price)**2 + score
        else:
            score = score - 0.01
            # print "swap"
    return json.dumps({"core": meals, "total": spent})
Esempio n. 8
0
def results(id):
    """
    Recebe o id de um video do youtube e pega os seus relacionados
    os resultados sao exibidos para o usuario

    """

    videos = search('related', id)

    return render_template("results.html", videos=videos)
Esempio n. 9
0
def suche():
    if request.method == "POST":
        level, gram_thema, thema = api.check_empty(request.form.getlist('lvl_checkbox')), api.check_empty([api.preprocess_query("select_all_grammar", el) for el in request.form["grammar"].split(" ")]), api.check_empty([api.preprocess_query("select_all_tkeywords", el) for el in request.form["theme"].split(" ")]) #TODO aqui e abaixo: função pros processamentos das strings
        test_search = {"level": level, "grammar": gram_thema, "keywords":thema}
        #jtemp = api.get_json(api.JSON_PATH)
        df = api.create_df_from_sql()
        df_res = api.search(df, test_search)
        str_df_res = api.df_to_html_pretty(df_res)
        return render_template("result.html", content=str_df_res)
    else:
        return render_template("suche.html")
Esempio n. 10
0
def getMeal(uid, price, nick):
    user = api.getUser(uid)
    nearby = api.search(uid, nick)
    price = int(10000 * float(price) / (100 + float(user["tip"]))) / 100.0 / 1.0875
    # return json.dumps(nearby)
    choices_outer = []
    for rest in nearby:
        if rest["mino"] <= price and rest["is_delivering"] == 1:
            rest_data = api.getDetails(rest["id"])
            choices = []
            addons = []
            if api.cuisineCheck(rest_data["cuisine"], uid):
                for category in rest_data["menu"]:
                    for listing in category["children"]:
                        if float(listing["price"]) <= price:
                            listing["rest"] = rest["id"]
                            foodItem = meal(listing)
                            if foodItem.price < 4.85 or foodItem.price < 0.6 * price or not api.valid(listing):
                                base = addons
                            else:
                                base = choices
                            if "children" in listing:
                                for option in listing["children"]:
                                    if api.valid(option):
                                        title = option["name"]
                                        flex = api.checkFlexibility(title)
                                        if "children" in option:
                                            for op in option["children"]:
                                                optionItem = meal(op)
                                                foodItem.addOption(title, optionItem, flex)
                            base.append(foodItem)
            choices_outer.append([choices, addons])
    meals = []
    spent = 0
    score = 0
    while score < random.random():
        rest_index = random.randrange(len(choices_outer))
        rest_pick = choices_outer[rest_index]
        if len(rest_pick[0]) != 0:
            meal_index = random.randrange(len(rest_pick[0]))
            meal_pick = rest_pick[0][meal_index]
            final_meal, total_price = meal_pick.pickOptions(price)
            if total_price <= price - spent:
                meals.append(final_meal.toDict())
                spent = spent + total_price
            elif spent < total_price:
                meals = final_meal.toDict()
                spent = total_price
            score = (float(spent) / price) ** 2 + score
        else:
            score = score - 0.01
            # print "swap"
    return json.dumps({"core": meals, "total": spent})
Esempio n. 11
0
def search():
    query = request.args['query']
    page = int(request.args.get('page', 1))
    context = api.search(query, limit=LIMIT, offset=(page - 1) * LIMIT)
    total = context['hits']['total']
    pages = int(math.ceil(total / 10))
    context['first_page'] = 1
    context['min_page'] = max(1, page - 2)
    context['max_page'] = min(pages, context['min_page'] + 4)
    context['last_page'] = pages
    context['current_page'] = page
    context['query'] = query
    return render_template('results.html', **context)
Esempio n. 12
0
def main():
    print("Talk Python Search:")
    search_terms = input("Search:").split()
    try:
        results = api.search(search_terms)
    except api.NoResultsFound:
        print(f"No results found for {' '.join(search_terms)}")
        return
    for i, episode in enumerate(sorted(results, key=lambda r: r.id)):
        print(f"{i+1}. {episode.id}: {episode.title}")
    id_ = int(input("Choose an episode id:"))
    for episode in results:
        if episode.id == id_:
            webbrowser.open_new_tab(BASE_URL + episode.url)
            break
    else:
        print("Invalid id")
def search_view(request):

    if ("code" in request.GET):
        messages = {}
        api = Api()
        code = request.GET.get('code')

        try:
            result = api.search(code)
        except Exception as e:
            messages['error'] = str(e)
            search_info = {'messages': messages}
        else:
            search_info = result
        finally:
            return render(request, 'simulator/search.html', search_info)

    return render(request, 'simulator/search.html')
Esempio n. 14
0
def stock_detail(request, code):
    stockObj = Stock.objects.get(code=code)
    api = Api()
    stockinfo = api.search(code)
    stock = {}
    stock['code'] = stockObj.code
    stock['name'] = stockObj.name
    stock['current'] = stockinfo['c']
    stock['change'] = stockinfo['change']
    stock['alerts'] = []
    alerts_not_triggered_yet = WatchListAlert.objects.filter(user_id=request.user, stock=stockObj, triggered=False)
    if alerts_not_triggered_yet.count() == 0:
        stock['alert'] = "No alerts to display"
    else:
        stock['alert'] = ""
        for alert in alerts_not_triggered_yet:
            stock['alerts'].append(alert)

    return render(request, 'simulator/stock_detail.html', {'stock': stock})
def main():
    logger.info('Taking user input...')
    user_input = input('Enter search criteria: ')
    logger.info(f'Searching for {user_input}')
    articles = api.search(user_input)
    print(f'Found {len(articles)} articles')
    id_to_article_dict = {}
    for r in articles:
        id_to_article_dict[r.id] = r
        print(f"[{r.id}] {r.title}: {r.category}")

    print("*" * 20)

    user_input = input(
        'For which article do you need more information [q for quit]: ')
    if user_input != 'q':
        web_open("http://talkpython.fm" +
                 id_to_article_dict[int(user_input)].url,
                 new=2)
    logger.info('End of execution')
def checkstart():
    voice.player("现在需要认证你的身份,请看摄像头")
    image = GetReady.getimgFromCam()
    imageType = "BASE64"
    sear_result = api.search(image, imageType)
    print(sear_result)
    if sear_result['error_code'] != 0:
        voice.player("认证失败,原因")
        voice.player(sear_result['error_msg'])
        checkstart()
        return
    if sear_result["result"]["user_list"][0]["score"] > 70:
        print("匹配到用户", sear_result["result"]["user_list"][0]["user_id"])
        voice.player("匹配到用户")
        voice.player(sear_result["result"]["user_list"][0]["user_id"])
        voice.player("认证成功。")
    else:
        print("没有匹配到用户,请重新尝试")
        voice.player("没有匹配到用户,请重新尝试")
        checkstart()
Esempio n. 17
0
def coletar():
    """
    GET: Mostra a pagina com formulario para a coleta
    POST: preforma a busca na API e mostra os resultados

    O prceso é o mesmo da navegacao, mas e possivel fazer em diferentes
    niveis de profundidade:
    nivel 1: apenas resultados de uma busca.
    nivel 2: resultados de busca e suas recomendacoes
    nivel 3: resultados de busca, recomendacoes e recomendacoes subsequentes
    """

    # GET request
    if request.method == "GET":
        return render_template("coletar.html")

    # POST request
    elif request.method == "POST":

        # pega os dados da pagina
        query = request.form.get("query")
        seed = request.form.get("seed-mode")
        profundidade = request.form.get("profundidade")

        # lista final a ser retornada
        final_video_list = []

        # se nao for introduzido um termo ou video_id - retorna um erro
        if query == '':
            # caso a profundidade nao seja informada
            return render_template("coletar.html",
                                   msg="verifique o termo buscado")

        # varia de acordo com a profundidade
        if profundidade == '1':

            if seed == True:

                videos = search('related', query)
                final_video_list += videos

            elif seed == None:

                videos = search('query', query)
                final_video_list += videos
                query_search(query)

        elif profundidade == '2':

            # Faz a busca e coloca os resultados na lista
            if seed == True:
                # level 1
                videos = search('related', query)
                final_video_list += videos

                # itera por cada resultado e faz uma busca de relacionados para cada
                for video in videos:
                    # level 2
                    videos2 = search('related', video[0])
                    final_video_list += videos2

            elif seed == None:
                # level 1
                videos = search('query', query)
                final_video_list += videos
                query_search(query)

                # itera por cada resultado e faz uma busca de relacionados para cada
                for video in videos:
                    # level 2
                    videos2 = search('related', video[0])
                    final_video_list += videos2

        elif profundidade == '3':

            level_2 = []

            # Faz a busca e coloca os resultados na lista
            if seed == True:
                # level 1
                videos = search('related', query)
                final_video_list += videos

                # itera por cada resultado e faz uma busca de relacionados para cada
                for video in videos:
                    # level 2
                    videos2 = search('related', video[0])
                    final_video_list += videos2
                    level_2 += videos2

                    # itera por cada resultado e faz uma busca de relacionados para
                    # cada um mais uma vez
                    for vd in level_2:
                        # level 3
                        videos3 = search('related', vd[0])
                        final_video_list += videos3

            elif seed == None:
                # level 1
                videos = search('query', query)
                final_video_list += videos
                query_search(query)

                # itera por cada resultado e faz uma busca de relacionados para cada
                for video in videos:
                    # Level 2
                    videos2 = search('related', video[0])
                    final_video_list += videos2
                    level_2 += videos2

                    # itera por cada resultado e faz uma busca de relacionados para
                    # cada um mais uma vez
                    for vd in level_2:
                        # level 3
                        videos3 = search('related', vd[0])
                        final_video_list += videos3

        else:
            # caso a profundidade nao seja informada
            return render_template("coletar.html",
                                   msg="verifique a profundidade")

        # renderiza a pagina
        return redirect("/resultados")
Esempio n. 18
0
 def get(self, request, *args, **kwargs):
     term = request.GET.get("q")
     content = search(term) if term else []
     return HttpResponse(content=dumps(content), content_type="application/json")
Esempio n. 19
0
    # Check for collection and category table using the variable taken from above
        # if exist then get the catID and colID
    # Check for existing app record in db
        # if exist then update else create app record using the fields taken from above

    f1 = open('./testfile', 'w+')
    f1.write("%s" %api.details(app_id))
    f1.close()
elif args['collections']:
    dict_collection = dict()
    dict_collection['collection']=collections[0]
    dict_collection['category']= collections[1]
    print(api.collection(dict_collection['collection'], dict_collection['category']))
    f2 = open('./categoryfile', 'w+')
    f2.write("%s" %api.collection(dict_collection['collection'], dict_collection['category']))
    f2.close()
elif args['developer']:
    dict_developer = dict()
    dict_developer['developer'] = developer[0]
    print(api.developer(dict_developer['developer']))
    f3 = open('./developerfile', 'w+')
    f3.write('%s' %api.developer(dict_developer['developer']))
    f3.close()
elif args['search']:
    print(api.search(search))
elif args['list']:
    print(api.categories())


Esempio n. 20
0
 def get(self, network, show, page=1, limit=100):
     q = item(iid=show)['metadata']['search_collection']
     try:
         return search(q, page=page, limit=limit)
     except Exception as e:
         raise ValueError("This show has no episodes.")
Esempio n. 21
0
 def get(self, network, page=1, limit=100):
     return search('mediatype:"collection" AND subject:"%s"' % network,
                   page=page,
                   limit=limit)
Esempio n. 22
0
import json
import os
import sys
import api
import catalog
from fileManage import *


print(api.search("default","test",['*'],"a<>5",sort="a",isreverse=True))
#print(api.deleteRow("test","test","b>5 and b<=6.7"))

'''print(api.search("test","test","*","a<>5"))
print(api.search("test","test",["a"],"a<>5"))'''

'''b = readTable("test", "test", 18, "<10sd")
print(list(b))
btree = readIndex("test", "test0")
btree.pretty()'''


#api.dropIndex("test","test","test")
#api.dropTable("test","test")

#tree=readIndex("test","test")
#tree.pretty()

#api.insertRow("default","test",[1,"ab"])

#api.createIndex("test","test","b","test0")

#api.createTable("test","test",[["a","char(10)","unique"],["b","float","unique"]],{"unique": ["a","b"]})
Esempio n. 23
0
 def get(self):
     i = request.args
     query = i.get('q', '')
     limit = i.get('limit', 50)
     page = i.get('page', 1)
     return search(query, page=page, limit=limit)
Esempio n. 24
0
            if detect['language'] not in settings.LANGUAGES.keys() \
                or not bool(detect['isReliable']):
                
                term1 = translit(term.lower(), 'ar').encode('utf-8')
                print '>>',term1
                term2 = translator.translate(term1, source="ar", target=lang)[0]['translatedText']

                terms['ar'] = term1.decode('utf-8')
                terms[lang] = term2
        except Exception, e:
            sharabelwasl.logger.exception("exception in translit logic ")
    
    sharabelwasl.logger.info(u'executing search for terms %s .  Original query is %s %s' % (terms, term, lang))
    
    es_results, ordered = api.search(terms)
    ordered.append(['terms', terms])
    sharabelwasl.logger.info(u'returning  %d qasidas' % len(ordered))
    response = dict(next='search',data=ordered)
    return flask.jsonify(response)

@sharabelwasl.route('/read/<number>')
# @api.make_ajax
def read(number=None):
    verses = api.read(number)
    return flask.render_template('verses.html', verses=verses)

@sharabelwasl.route('/dynamo/scan/<lang>/<qasida_number>/<line_number>')
# @api.make_ajax
def scan(lang=None, qasida_number=None, line_number=None):
 def get(self, network, page=1, limit=100):
     return search('mediatype:"collection" AND subject:"%s"' % network,
                   page=page, limit=limit)
Esempio n. 26
0
def get_restuarant_by_city(USCitySlot):
    return search(USCitySlot)
Esempio n. 27
0
def loadPage(incr=1, **kwargs):
    global page, posts, column_width, row_height, batch_sprites, row_width
    npage = tools.constrain(page + incr, 1, 750)
    if npage == page:
        return
    page = npage

    nposts = list(api.search(1, tags=query, page=page))

    for post in posts:
        post.clear_cache()
    posts.clear()
    posts.extend(nposts)
    with batch_lock:
        while len(batch_sprites) < len(posts):
            batch_sprites.append(None)
        index = len(batch_sprites) - 1
        for i in range(len(batch_sprites) - len(posts)):
            sprite_deletion.put_nowait(batch_sprites[index])
            index -= 1

    _column_width = []
    _row_height = []
    row_width = []

    index = 0
    for post in posts:
        column = index % 11
        row = index // 11

        post.column = column
        post.row = row
        #width = post.width
        #height = post.height
        width = post.preview_width
        height = post.preview_height

        if len(_column_width) > column:
            if width > _column_width[column]:
                _column_width[column] = width
        else:
            _column_width.append(width)

        if len(_row_height) > row:
            if height > _row_height[row]:
                _row_height[row] = height
        else:
            _row_height.append(height)
        index += 1

    index = 0
    for post in posts:
        column = index % 11
        row = index // 11

        if len(row_width) > row:
            row_width[row] += _column_width[column] + 20
        else:
            row_width.append(_column_width[column] + 20)

        index += 1

    column_width = list(map(lambda x: x + 20, _column_width[:-1]))
    column_width.extend(_column_width[-1:])
    row_height = list(map(lambda x: x + 20, _row_height[:-1]))
    row_height.extend(_row_height[-1:])
    row_width = list(map(lambda x: x - 20, row_width))[::-1]

    index = 0
    image_lock = threading.Condition(threading.Lock())
    vid_handler = lambda x: post_image_queue.put_nowait(x)

    def file_handler(x):
        post, file = x
        try:
            with image_lock:
                ext = os.path.splitext(file)[1]
                if 'animated' in post.tags.split(' ') and ext == '.gif':
                    image = pyglet.image.load_animation(file)
                else:
                    image = pyglet.image.load(file)
                post_image_queue.put_nowait((post, image))
        except Exception as e:
            print(e)

    with batch_lock:
        sort_key = lambda x: x.file_size
        for post in sorted(posts, key=sort_key, reverse=True):
            if post.file_ext == 'webm' and False:
                print('found webm, skipping download')
            else:
                post.load_file(file_handler)
            index += 1
Esempio n. 28
0
import json
import os
import sys
import api
import catalog
from fileManage import *

print(api.search("default", "test", ['*'], "a<>5", sort="a", isreverse=True))
#print(api.deleteRow("test","test","b>5 and b<=6.7"))
'''print(api.search("test","test","*","a<>5"))
print(api.search("test","test",["a"],"a<>5"))'''
'''b = readTable("test", "test", 18, "<10sd")
print(list(b))
btree = readIndex("test", "test0")
btree.pretty()'''

#api.dropIndex("test","test","test")
#api.dropTable("test","test")

#tree=readIndex("test","test")
#tree.pretty()

#api.insertRow("default","test",[1,"ab"])

#api.createIndex("test","test","b","test0")

#api.createTable("test","test",[["a","char(10)","unique"],["b","float","unique"]],{"unique": ["a","b"]})
#api.dropTable("test","test2")
#api.createTable("test","test2",[["a","char(10)",None],["b","int","unique"]],{"unique": ["b"]})

#api.insertRow("test","test",["dedefd",18.5])
Esempio n. 29
0
from api import search

books = search(title='the view from saturday', author='konigsburg')

print "Here are all of the versions available:"
for book in books:
	print book.title

print "\nHere is the second result in more detail:\n",books[1]

print "\nHere are all of the copies of that book:\n"
for copy in books[1].copies:
	print copy

print "\nThese are the ones that are available:\n"
for copy in books[1].available_copies:
	print copy

#this refreshes the copies available
books[1].update_copies()

print "We just refreshed the results. Here are the new ones:\n"
for copy in books[1].copies:
	print copy

print "Did they change? Probably not, unless someone just returned a book!"
def test_no_results():
    with pytest.raises(NoResultsFound):
        search(["zzzzzzz"])
Esempio n. 31
0
 def get(self):
     i = request.args
     query = i.get('q', '')
     limit = i.get('limit', 50)
     page = i.get('page', 1)
     return search(query, page=page, limit=limit)
 def get(self, network, show, page=1, limit=100):
     q = item(iid=show)['metadata']['search_collection']
     try:
         return search(q, page=page, limit=limit)
     except Exception as e:
         raise ValueError("This show has no episodes.")
def main():
    keyword = input('Enter search term: ')
    results = api.search(keyword)
    print(f'There are {len(results)} movies found')
    for movie in results:
        print(f'{movie.title}: has score {movie.imdb_score}')
Esempio n. 34
0
def search_page(search_term):
    return search(search_term)
Esempio n. 35
0
 def testSearch(self):
     response = api.search(self.ds, "", "20-Apr-2020", "20-May-2020")
     self.assertEqual(response[1], 501)
Esempio n. 36
0
from api import search

books = search(title='the view from saturday', author='konigsburg')

print("Here are all of the versions available:")
for book in books:
	print(book.title)

print("\nHere is the second result in more detail:\n",books[1])

print("\nHere are all of the copies of that book:\n")
for copy in books[1].copies:
	print(copy)

print("\nThese are the ones that are available:\n")
for copy in books[1].available_copies:
	print(copy)

#this refreshes the copies available
books[1].update_copies()

print("We just refreshed the results. Here are the new ones:\n")
for copy in books[1].copies:
	print(copy)

print("Did they change? Probably not, unless someone just returned a book!")
Esempio n. 37
0
 def test_search(self):
     # [{"guid": "3030-19578","name": "Scapeghost"}]
     result = api.search('Scapeghost')
     result = result[0]
     self.assertEqual(result['guid'], "3030-19578")
     self.assertEqual(result['name'], "Scapeghost")