Пример #1
0
 def __init__(self):
     self.__list = []
     self.__maxID = 1
     try:
         file = open('words.txt')
         for line in file:
             line = line.split(" ")
             if len(line) == 3:
                 word = Word((int(line[0])),line[1],int(line[2]))
                 if word.getId() > self.__maxID:
                     self.__maxID = word.getId()
                 self.__list.append(word)
         file.close()
     except IOError as e:
         self.__list = []
Пример #2
0
def test_game_iter_bad_index():
    bulk_update_dict = {}
    new_index, result = game_service.__game_iter__(1, -2, [Word(word="bad")],
                                                   bulk_update_dict)
    assert new_index == 1
    assert len(bulk_update_dict) == 0
    assert result == "You are trying to go beyond the index."
Пример #3
0
 async def save_word(self, arg_json):
     try:
         word_inst = Word.init_form_json(
             validate_json(Word.get_json_schema(), arg_json))
         if await self.db_layer.word.record_is_exists(word_inst.word):
             return Error(
                 "The dictionary already contains this word. Word - {}".
                 format(word_inst.word))
         await self.db_layer.word.save(vars(word_inst))
         await self.producer.send_message(WordKafkaMessage(word_inst.word))
     except (TypeError, ValidationError) as exp:
         return Error(exp)
     except JSONDecodeError:
         return Error("Not valid JSON was passed.")
     except Exception as exp:
         return self.__unexpected_exception__(exp)
     else:
         return "Word was added!!!"
Пример #4
0
class ScrambleController:
    def __init__(self, repo):
        self.__score = 0
        self.__repo = repo
        self.__currentWord = Word(0, "", 0)

    def getWords(self):
        return self.__repo.findAll()

    def getScore(self):
        return self.__score

    def addWord(self, value, points):
        if value == "":
            print("Cuvantul trebuie sa fie nevid")
        try:
            word = Word(self.__repo.getNewID(), value, int(points))
            self.__repo.add(word)
        except TypeError as e:
            print(e)
            print("Points trebuie sa fie intreg")
        except IndexError as e:
            print(e)
        except ValueError as e:
            print(e)

    def newGame(self):
        words = self.__repo.findAll()
        print(words)
        self.__currentWord = random.sample(words, 1)[0]
        listRepr = list(self.__currentWord.getValue())
        random.shuffle(listRepr)
        return "".join(listRepr)

    def guess(self, wordValue):
        if wordValue == self.__currentWord.getValue():
            self.__score += self.__currentWord.getPoints()
            return True
        else:
            self.__score -= 1
            return False
Пример #5
0
def words():
    if request.method == "POST":
        id = request.form["id"]
        logging.info("word id: {}".format(id))
        try:
            id = int(id)
        except:
            logging.warning("** id type error")
            return abort(404)

        Word(id=id).delete()
        return jsonify()

    words = Word.select_many()
    username = session.get("username", "")
    return render_template("/backend/word_board.html", username=username, words=words)
Пример #6
0
 async def update_word(self, arg_json):
     try:
         json_dict = validate_json(Word.get_json_schema(), arg_json)
         word = json_dict['word']
         new_json_dict = exclude_json_fields(
             json_dict, fields=['translation', 'phrase', 'synonyms'])
         if new_json_dict:
             result = await self.db_layer.word.find_one_and_update(
                 word, new_json_dict)
             if result is None:
                 return Error("Word not found!!!")
     except (TypeError, ValidationError) as exp:
         return Error(exp)
     except JSONDecodeError:
         return Error("Not valid JSON was passed.")
     except Exception as exp:
         return self.__unexpected_exception__(exp)
     else:
         return "Word was updated!!!"
def parse_oxford_response_data(response, word_from_request) -> []:
    result = {}
    if response is None:
        return result.values()
    json_results = response['results'][0]['lexicalEntries']
    for word_definition in json_results:
        try:
            definition = [word_definition['entries'][0]['senses'][0]['definitions'][0]]
            word_type = word_definition['lexicalCategory']
            word = Word(word_from_request, definition, word_type)
            if word.word in result.keys():
                result.get(word.word).append_definition(definition)
            else:
                result[word.word] = word
        except KeyError:
            print('parse error for: ', word_from_request)
    parsed_result = []
    for value in result.values():
        parsed_result.append(value.prepare_for_quizlet())
    return parsed_result
Пример #8
0
def words():
    if request.method == "POST":
        name = request.form['name']
        word = request.form['word']
        validate_code = request.form['validate_code']

        if len(name) > 30:
            return jsonify({"error":True, "msg":u"名字太长"})
        if len(word) > 400:
            return jsonify({"error":True, "msg":u"留言太多"})

        sid = request.cookies.get('sid', None)
        if sid is None:
            return abort(404)

        str_code = session[sid]
        if str_code != validate_code:
            return jsonify({"error":True, "msg":u"验证码错误"})


        writetime = strftime("%Y-%m-%d %H:%M:%S", localtime())
        Word(name=name, content=word, writetime=writetime).insert()

        return jsonify({"error":False, "msg":u"感谢您的留言,谢谢", "writetime":writetime})

    words = Word.select_many(orderbys=[('writetime', "desc")])

    labels, has_login = _prepare_base_data()

    response = make_response(render_template('/frontend/words.html',
                            words=words, labels=labels, has_login=has_login, enumerate=enumerate))
    sid = str(uuid.uuid4())
    session['sid'] = sid
    # One hour expire
    expire_time = 60*60
    response.set_cookie('sid', sid, expire_time)
    return response
Пример #9
0
 def __convert_to_inst__(word_list_json):
     return list(
         map(lambda word_json: Word.init_form_json(word_json),
             word_list_json))
Пример #10
0
def test_game_iter_correct():
    bulk_update_dict = {}
    new_index, result = game_service.__game_iter__(1, -1, [Word(word="bad")],
                                                   bulk_update_dict)
    assert new_index == 0
    assert len(bulk_update_dict) == 1
Пример #11
0
from updatewords.update import UpdateWord
from model.word import Word
word = Word()
word.setWord(input("请输入单词:\n"))
word.setTrans(input("请输入中文释义:\n"))
word.setExample(input("请输入例句:\n"))
ud = UpdateWord()
print(ud.updateAWord(word))
Пример #12
0
 def __init__(self, repo):
     self.__score = 0
     self.__repo = repo
     self.__currentWord = Word(0, "", 0)