Ejemplo n.º 1
0
def _create_span(spans, mention_start_idx, mention_end_idx):
  start_span_idx = _.find_index(spans,
                                lambda span: span[0] <= mention_start_idx and span[1] >= mention_start_idx)
  assert start_span_idx != -1
  end_span_offset = _.find_index(spans[start_span_idx:],
                                 lambda span: mention_end_idx <= span[1] and mention_end_idx >= span[0])
  assert end_span_offset != -1
  end_span_idx = start_span_idx + end_span_offset
  return spans[start_span_idx][0], spans[end_span_idx][1]
Ejemplo n.º 2
0
    def get_test_case_id(self, test_result):
        test_case = self.get_test_case_from_test_result(test_result)
        conf_file = test_case[
            'conf_file'] if 'conf_file' in test_case else self.get_conf_from_store(
                test_case)
        if not conf_file:
            return
        if "conf/" in conf_file:
            conf_file = conf_file.replace("conf/", '')
        test_cases = self.get_test_cases_from_conf(conf_file)
        test_cases_clone = pydash.clone_deep(test_cases)

        def remove_group(x):
            pydash.unset(x, 'GROUP')
            pydash.unset(x, 'commented')
            pydash.unset(x, 'testLine')

        test_cases_dict_without_groups = pydash.for_each(
            test_cases_clone, remove_group)
        callback = lambda x: set(x.items()).issubset(set(test_case.items()))
        index = pydash.find_index(test_cases_dict_without_groups, callback)
        if index == -1:
            return None
        name = test_cases[index]
        self.remove_unwanted_fields(name)
        return hashlib.md5(json.dumps(name, sort_keys=True)).hexdigest()
Ejemplo n.º 3
0
def s_get(cls, attr_path):
    '''
    Method to get attribute across space via inferring agent <-> env paths.
    @example
    self.agent.agent_space.aeb_space.clock
    # equivalently
    util.s_get(self, 'aeb_space.clock')
    '''
    from_class_name = get_class_name(cls, lower=True)
    from_idx = ps.find_index(
        SPACE_PATH, lambda s: from_class_name in (s, s.replace('_', '')))
    from_idx = max(from_idx, 0)
    attr_path = attr_path.split('.')
    to_idx = SPACE_PATH.index(attr_path[0])
    assert -1 not in (from_idx, to_idx)
    if from_idx < to_idx:
        path_link = SPACE_PATH[from_idx:to_idx]
    else:
        path_link = ps.reverse(SPACE_PATH[to_idx:from_idx])

    res = cls
    for attr in path_link + attr_path:
        if not (get_class_name(res, lower=True) in (attr, attr.replace(
                '_', ''))):
            res = getattr(res, attr)
    return res
Ejemplo n.º 4
0
    def update_options(self, *args):
        self.run_command_button.pack_forget()
        self.copy_command_button.pack_forget()
        if self.usage:
            self.usage.pack_forget()
            self.usage = None
        if len(self.form_widgets) > 0:
            self.clear_form_widgets()
        self.master.geometry('')

        changed_variable = None
        for variable in self.variables:
            if str(variable) == args[0]:
                changed_variable = variable
                break
        if changed_variable == find_last(self.variables,
                                         lambda varaible: variable.get()):
            selected_object = self.get_selected_object()
            if selected_object and "choices" in selected_object:
                self.dropdown_map[str(changed_variable)].config(
                    font='TkDefaultFont')
                self.add_dropdown_option(selected_object)
            self.update_displayed_options(selected_object, changed_variable)

        else:
            context_to_remove = self.variables[find_index(
                self.variables, lambda variable: variable == changed_variable
            ) + 1:]

            self.remove_variables(context_to_remove)
            selected_object = self.get_selected_object()
            if selected_object and "choices" in selected_object:
                self.add_dropdown_option(selected_object)
            self.update_displayed_options(selected_object, changed_variable)
Ejemplo n.º 5
0
    async def _do_work(self):

        message_manager = self.context.message_manager;
        messages = self.context.blackboard.get('recv_messages')
        if messages and len(messages) > 0:

            msg_idx = pydash.find_index(messages, {'receiver': self.context.worker.uuid})
            if msg_idx != -1:
                msg = pydash.clone(messages[msg_idx])
                print('start handle message :{}'.format(msg))
                pydash.pull_at(messages, msg_idx)

                self.context.blackboard.set('recv_messages', messages)
                message_inst = message_manager.find_message(msg['name'])
                if message_inst is None:
                    print('malformed message handler: {}, {}'.format(msg['key'], {'message': msg}))
                    self.async_task_status = py_trees.common.Status.FAILURE
                    return

                try:
                    await message_inst.on_handler(self.context, msg['body'])
                except Exception as err:
                    print('error occurred while processing message : {}'.format({
                        'message':msg
                    }))

        self.async_task_status = py_trees.common.Status.SUCCESS
Ejemplo n.º 6
0
    def find_request_by_button(self, button, uuid):
        self._load()
        target_idx = pydash.find_index(self._button_req, {
            'button': button,
            'uuid': uuid
        })
        if target_idx == -1:
            return None

        return self._button_req[target_idx]
Ejemplo n.º 7
0
    def set_button_request(self, button_request):
        self._load()
        target_idx = pydash.find_index(
            self._button_req, pydash.pick(button_request,
                                          ['button_id', 'uuid']))
        if target_idx != -1:
            self._button_req[target_idx] = button_request
        else:
            self._button_req.append(button_request)

        self.save()
        return self._button_req
Ejemplo n.º 8
0
    def _split_combined_step(self, step, step_num):
        """
        converts steps that have a combined control mode (CCCV) into separated steps that are compatible with BT-Lab
        """
        step_part1 = clone_deep_with(step)
        step_part2 = clone_deep_with(step)

        if isinstance(get(step_part1, "Ends.EndEntry"), list):
            indx = find_index(get(step_part1, "Ends.EndEntry"),
                              lambda x: x["EndType"] == "Current")
            path = "Ends.EndEntry.{}".format(indx)
        else:
            path = "Ends.EndEntry"

        if step_part1["StepMode"] == "Current" and "Voltage" in step_part1[
                "Limits"].keys():
            if step_part1["StepType"] == "Charge":
                set_(step_part1, path + ".Oper", ">=")
            elif step_part1["StepType"] == "Dischrge":
                set_(step_part1, path + ".Oper", "<=")
            else:
                raise NotImplementedError
            set_(step_part1, path + ".EndType", "Voltage")
            set_(step_part1, path + ".Value", step["Limits"]["Voltage"])
            set_(step_part1, path + ".Step", str(step_num + 1).zfill(3))
            step_part1["Limits"] = None

            step_part2["StepMode"] = "Voltage"
            step_part2["StepValue"] = step["Limits"]["Voltage"]
            step_part2["Limits"] = None

        elif step_part1["StepMode"] == "Voltage" and "Current" in step_part1[
                "Limits"].keys():
            if step_part1["StepType"] == "Charge":
                set_(step_part1, path + ".Oper", ">=")
            elif step_part1["StepType"] == "Dischrge":
                set_(step_part1, path + ".Oper", "<=")
            else:
                raise NotImplementedError
            step_part1["StepMode"] = "Current"
            step_part1["StepValue"] = step["Limits"]["Current"]
            set_(step_part1, path + ".EndType", "Voltage")
            set_(step_part1, path + ".Value", step["StepValue"])
            set_(step_part1, path + ".Step", str(step_num + 1).zfill(3))
            step_part1["Limits"] = None

            step_part2["StepMode"] = "Voltage"
            step_part2["StepValue"] = step["StepValue"]
            step_part2["Limits"] = None

        return step_part1, step_part2
Ejemplo n.º 9
0
    def remove_button_request(self, button_id, uuid):
        self._load()
        target_idx = pydash.find_index(self._button_req, {
            'button_id': button_id,
            'uuid': uuid
        })
        if target_idx != -1:
            pydash.pull_at(self._button_req, target_idx)
        else:
            print('cannot remove button request')

        self.save()
        print('buttonRequest removed')
        return self._button_req
Ejemplo n.º 10
0
    def get_simulated_open_trade(self, coin_pair):
        """
        Used to get the coin pairs simulated unsold trade in the database

        :param coin_pair: String literal for the market (ex: BTC-LTC)
        :type coin_pair: str
        """
        trade_index = py_.find_index(
            self.simulated_trades['trades'], lambda trade: trade['coinPair'] ==
            coin_pair and 'sell' not in trade)
        if trade_index == -1:
            logger.error(
                'Could not find simulated open trade for {} coin pair'.format(
                    coin_pair))
            return None
        return self.simulated_trades['trades'][trade_index]
Ejemplo n.º 11
0
        def get_open_trade(self, coin_pair):
            """
            Used to get the coin pair's unsold trade in the database

            :param coin_pair: String literal for the market (ex: BTC-LTC)
            :type coin_pair: str

            :return: The open trade object
            :rtype : dict
            """
            trade_index = py_.find_index(self.trades["trades"],
                                         lambda trade: trade["coinPair"] == coin_pair and "sell" not in trade)

            if trade_index == -1:
                logger.error("Could not find open trade for {} coin pair".format(coin_pair))
                return None

            return self.trades["trades"][trade_index]
Ejemplo n.º 12
0
def test_find_index(case, filter_by, expected):
    assert _.find_index(case, filter_by) == expected
Ejemplo n.º 13
0
def handle_message(event):
    # CONFIG
    max_question = 10
    #################################

    text = event.message.text

    if event.reply_token == '00000000000000000000000000000000':
        # Line trying to verify the Webhook
        return

    cache_prefix = get_cache_prefix(event)
    player_identity = get_player_identity(event)
    participant_identity = get_participant_identity(event)

    is_game_started = cache.get(cache_prefix + '.is_started', False)
    last_question = cache.get(cache_prefix + '.last_question', 1)
    remaining_time = cache.get(cache_prefix + '.remaining_time', False)
    participants = json.loads(cache.get(cache_prefix + '.participants', '[]'))
    current_question = json.loads(
        cache.get(cache_prefix + '.current_question', '{}'))
    standings = json.loads(cache.get(cache_prefix + '.standings', '[]'))
    player = cache.get(cache_prefix + '.player', False)

    if not player:
        player = Player.objects.filter(key=player_identity).first()

        if not player:
            player = Player.objects.create(key=player_identity)

        player = {'id': player.id, 'key': player.key}

        cache.set(cache_prefix + '.player', json.dumps(player), None)
    else:
        player = json.loads(player)

    participant = cache.get('user_profiles.' + participant_identity)

    if not participant or text == '/join':
        try:
            line_profile = line_bot_api.get_profile(participant_identity)
            participant = {
                'user_id': line_profile.user_id,
                'display_name': line_profile.display_name
            }
            cache.set('user_profiles.' + participant_identity,
                      json.dumps(participant))
        except LineBotApiError:
            # It seems participant not add bot as friend.
            line_bot_api.reply_message(
                event.reply_token,
                [
                    TextSendMessage(
                        'Yahh, kamu gak bisa ikutan main.\n\n' +
                        'Kamu belum add Bot %s jadi teman. ' % BOT_NAME +
                        'Add dulu dong Bot, biar kamu bisa ikutan main.'),
                    TemplateSendMessage(
                        alt_text='Tambah sebagai teman',
                        template=ButtonsTemplate(
                            # thumbnail_image_url='https://example.com/image.jpg',
                            title=BOT_NAME,
                            text=
                            'Tekan tombol di bawah ini untuk menambahkan bot sbg teman',
                            actions=[
                                URIAction('Tambahkan Teman',
                                          'line://ti/p/@%s' % BOT_ID)
                            ]))
                ])
            return
    else:
        participant = json.loads(participant)

    process_text = False

    if text[0] == '/':
        if text == '/menu':
            output = '[Menu Permainan]\n\n'\
                '/join => Untuk berpartisipasi dalam permainan.\n\n'\
                '/mulai => Untuk memulai permainan.\n\n'\
                '/skip => Untuk skip pertanyaan (pertanyaan berikutnya).\n\n'\
                '/ulang => Untuk mengulangi permainan.\n\n'\
                '/klasemen => Untuk menampilkan klasemen permainan.\n\n'\
                '/identitas => Untuk mendapatkan ID Permainan.\n\n'

            if isinstance(event.source, SourceUser):
                output += '/tambah-pertanyaan => Untuk menambahkan pertanyaan ke sebuah permainan.\n\n'

            output += '/menu => Untuk memunculkan menu permainan ini.\n\n'\
                '/reset-paksa => Untuk mereset paksa bot (riwayat permainan akan hilang).\n\n'\
                '/tentang => Untuk melihat kontak creator.\n\n'\
                '/keluar => Untuk mengeluarkan bot.'

            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(output))
        elif text == '/tentang':
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    ('[Creator Bot %s]\n\n' % BOT_NAME) +
                    'Jika anda menemukan bug, ingin mengirimkan ide, dan lain-lain, silahkan kontak '
                    + 'creator di line://ti/p/@ajf4387b\n\n' +
                    'Copyright @2020 nmflabs'))
        elif text == '/identitas':
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage('ID Permainan: %s' % player_identity))
        elif text == '/keluar':
            fresh_data(event)
            exit_text = 'Selamat tinggal semuanya. Kapan-kapan invite lagi yaa :*'

            if isinstance(event.source, SourceGroup):
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(exit_text))
                line_bot_api.leave_group(event.source.group_id)
            elif isinstance(event.source, SourceRoom):
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(exit_text))
                line_bot_api.leave_room(event.source.room_id)
            else:
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(
                        'Bot tidak bisa keluar otomatis. Silahkan unfriend Bot ini :('
                    ))
        elif text == '/mulai':
            if is_game_started:
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage('Permainan sudah dimulai.'))

                return
            elif len(participants) == 0:
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(
                        'Tidak bisa memulai permainan. Belum ada peserta.'))

                return

            cache.set(cache_prefix + '.is_started', True, None)

            question = get_next_question(event, player['id'])

            if not question:
                fresh_data(event)
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(
                        'Mohon maaf, belum ada pertanyaan. Silahkan coba lain waktu :('
                    ))
            else:
                line_bot_api.reply_message(
                    event.reply_token,
                    [TextSendMessage('Permainan dimulai.'), question])
        elif text == '/join':
            if is_game_started:
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage('Permainan sudah dimulai.'))
                return

            idx = pydash.find_index(
                participants, lambda s: s['id'] == participant['user_id'])

            if idx != -1:
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage('%s telah tergabung dalam permainan.' %
                                    participant['display_name']))
                return

            participants.append({
                'id': participant['user_id'],
                'name': participant['display_name'],
                'total_score': 0
            })
            cache.set(cache_prefix + '.participants', json.dumps(participants),
                      None)
            show_participants(event, participants)
        elif text == '/klasemen':
            output = 'Klasemen\n'
            if len(standings) == 0:
                output += '\nKlasemen masih kosong.'
            else:
                for index, _participant in enumerate(standings):
                    output += '\n%s. %s (%s poin)' % (index + 1,
                                                      _participant['name'],
                                                      _participant['points'])

            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(output))
        elif text == '/skip':
            process_text = True
        elif text == '/ulang':
            # Ulangi permainan pada sesi ini
            if not is_game_started:
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage('Permainan belum dimulai.'))
                return

            cache.delete(cache_prefix + '.last_question')
            cache.delete(cache_prefix + '.remaining_time')
            cache.delete(cache_prefix + '.current_question')
            cache.delete(cache_prefix + '.current_standings')

            line_bot_api.reply_message(event.reply_token, [
                TextSendMessage('Permainan diulang.'),
                get_next_question(event, player['id'], True)
            ])
        elif text == '/reset-paksa':
            fresh_data(event)
            cache.delete(cache_prefix + '.standings')

            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage('Bot behasil di reset paksa.'))
        else:
            if text.startswith('/tambah-pertanyaan'):
                if not isinstance(event.source, SourceUser):
                    line_bot_api.reply_message(
                        event.reply_token,
                        TextSendMessage('Perintah tidak tersedia.'))
                    return

                errors_text = [
                    '- Skor harus lebih dari 0 dan Total skor harus 100',
                    '- Panjang pertanyaan minimal 20 dan maksimal 100 karakter',
                    '- Panjang jawaban minimal 3 dan maksimal 25 karakter',
                    '- Jumlah jawaban minimal 1 dan maksimal 10',
                    '- Pertanyaan tidak boleh mengandung karakter %s' % "';'",
                    '- Jawaban hanya boleh mengandung huruf dan spasi'
                ]

                if text == '/tambah-pertanyaan':
                    output = 'Anda dapat menambahkan pertanyaan ke dalam Permainan lain.\n'\
                        'Silahkan ulangi perintah dengan menuliskan pertanyaan sesuai format berikut:\n\n'\
                        '/tambah-pertanyaan ID_PERMAINAN;PERTANYAAN;JAWABAN (Skor),JAWABAN (Skor),....\n\n'\
                        'Keterangan:'

                    for error_text in errors_text:
                        output += '\n%s' % error_text

                    line_bot_api.reply_message(event.reply_token, [
                        TextSendMessage(output),
                        TextSendMessage(
                            'Contoh:\n' +
                            '/tambah-pertanyaan g-U8f41v103t42f90ops6fgqr;' +
                            'Nama-nama hewan berawalan A?;' +
                            'Ayam (70),Anjing (10)')
                    ])
                else:
                    text = text.replace('/tambah-pertanyaan ', '')
                    data = text.split(';')
                    game_id = ''
                    question = ''
                    answers = []
                    errors = []

                    format_correct = True

                    try:
                        game_id = data[0].strip()
                        question = data[1].strip()
                        answers = list(filter(None, data[2].split(',')))

                        total = 0
                        for index, answer in enumerate(answers):
                            if index >= 10:
                                # break fast if answers more than 10
                                break

                            answer = answer.strip()
                            result = re.search(r'.* \(([^)]+)\)$', answer)
                            ans = pydash.replace_end(answer,
                                                     ' (%s)' % result[1], '')

                            if len(ans) < 3 or len(ans) > 25:
                                errors.append(2)
                                format_correct = False

                            if not re.search(r'^[a-zA-Z ]*$', ans):
                                errors.append(5)
                                format_correct = False

                            score = int(result[1])

                            if score < 1:
                                errors.append(1)
                                format_correct = False

                            answers[index] = [ans, score]
                            total += score

                        if total != 100:
                            errors.append(0)
                            format_correct = False

                        if len(answers) > 10:
                            errors.append(3)
                            format_correct = False

                        if len(question) > 100 or len(question) < 20:
                            errors.append(1)
                            format_correct = False
                    except:
                        format_correct = False

                    if len(data) > 3:
                        errors.append(4)
                        format_correct = False

                    if len(answers) == 0:
                        errors.append(3)
                        format_correct = False

                    _player = Player.objects.filter(key=game_id).first()

                    if not _player:
                        line_bot_api.reply_message(
                            event.reply_token,
                            TextSendMessage('ID Permainan tidak ditemukan.'))
                    elif format_correct:
                        Question.objects.create(value=question,
                                                answers=answers,
                                                creator_id=player['id'],
                                                for_player=_player)

                        line_bot_api.reply_message(
                            event.reply_token,
                            TextSendMessage(
                                'Anda berhasil menambahkan pertanyaan ke dalam '
                                + 'Permainan dengan ID %s' % game_id))
                    else:
                        output = 'Format tidak sesuai. Pastikan Anda menuliskan sesuai format.'

                        if len(errors) > 0:
                            output += '\n\nKesalahan:'

                            errors = list(set(errors))

                            for error in errors:
                                output += '\n%s' % errors_text[error]

                        line_bot_api.reply_message(event.reply_token,
                                                   TextSendMessage(output))
                return

            line_bot_api.reply_message(
                event.reply_token, TextSendMessage('Perintah tidak tersedia.'))

    if process_text or text[0] != '/':
        text = text.strip()
        line_messanges = []

        if text == '/skip':
            if not is_game_started:
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(
                        'Permainan belum dimulai. Ketik /mulai untuk memulai permainan.'
                    ))
                return

            line_messanges.append(
                TextSendMessage('Masa gitu aja udah nyerah :('))

        if not is_game_started:
            fresh_data(event)
            return
        else:
            answers = current_question['answers']
            current_standings = json.loads(
                cache.get(cache_prefix + '.current_standings', '[]'))

            if text != '/skip':
                if remaining_time:
                    answer_id = -1
                    correct_answer = False
                    score = 0

                    for index, answer in enumerate(answers):
                        if answer[0].lower() == text.lower():
                            correct_answer = True
                            answer_id = index
                            score = answer[1]
                            break

                    if correct_answer:
                        idx = pydash.find_index(
                            current_standings,
                            lambda s: s['answer_id'] == answer_id)

                        # Check whether the answer already used or not
                        if idx != -1:
                            return

                        current_standings.append({
                            'id':
                            participant['user_id'],
                            'name':
                            participant['display_name'],
                            'answer_id':
                            answer_id,
                            'score':
                            score
                        })

                        cache.set(cache_prefix + '.current_standings',
                                  json.dumps(current_standings), None)
                    else:
                        line_bot_api.reply_message(
                            event.reply_token,
                            TextSendMessage(
                                '"%s" tidak ada dalam daftar jawaban.' % text))
                        return
                else:
                    line_messanges.append(TextSendMessage('Waktu habis!'))

            output = '%sPertanyaan ke %s dari %s.\n\n' % (
                '(Skip) ' if text == '/skip' else '', last_question,
                max_question)
            output += current_question['text'] + '\n'
            for index, answer in enumerate(answers):
                idx = pydash.find_index(current_standings,
                                        lambda s: s['answer_id'] == index)

                if idx != -1:
                    output += '\n%s. %s (%s) - %s' % (
                        index + 1, answer[0], answer[1],
                        current_standings[idx]['name'])
                else:
                    output += '\n%s. ____________' % (index + 1)

            line_messanges.append(TextSendMessage(output))

            if (text == '/skip' or len(current_standings) >= len(answers)
                    or not remaining_time):
                for _participant in participants:
                    total_score = _participant['total_score']
                    for cs in current_standings:
                        if cs['id'] == _participant['id']:
                            total_score += cs['score']
                    _participant['total_score'] = total_score

                participants.sort(key=lambda p: p['total_score'], reverse=True)
                output = 'Daftar Pemain\n'
                for index, _participant in enumerate(participants):
                    output += '\n%s. %s (%s)' % (index + 1,
                                                 _participant['name'],
                                                 _participant['total_score'])

                line_messanges.append(TextSendMessage(output))

                cache.set(cache_prefix + '.participants',
                          json.dumps(participants), None)

                question = get_next_question(event, player['id'])

                if question:
                    line_messanges.append(question)
                else:
                    # No more question

                    line_messanges.append(
                        TextSendMessage('Pertandingan berakhir!'))
                    if participants[0]['total_score'] == 0:
                        output = 'Pemenang\n\nTidak ada pemenang.'
                    else:
                        output = 'Pemenang\n'
                        points = [3, 1]
                        for index, _participant in enumerate(participants):
                            if _participant['total_score'] == 0:
                                break

                            point = points[index]
                            output += '\n%s. %s (+%s poin)' % (
                                index + 1, _participant['name'], point)

                            idx = pydash.find_index(
                                standings,
                                lambda s: s['id'] == _participant['id'])
                            if idx != -1:
                                standings[idx]['points'] += point
                            else:
                                standings.append({
                                    'id': _participant['id'],
                                    'name': _participant['name'],
                                    'points': point
                                })

                            if index == len(points) - 1:
                                break

                        standings.sort(key=lambda s: s['points'], reverse=True)
                        cache.set(cache_prefix + '.standings',
                                  json.dumps(standings), None)

                    line_messanges.append(TextSendMessage(output))

                    fresh_data(event)

        line_bot_api.reply_message(event.reply_token, line_messanges)