コード例 #1
0
def resp_delta(message, *something):
    connection = MySQLdb.connect(host='localhost',
                                 user='******',
                                 passwd='pass',
                                 db='raspberry',
                                 charset='utf8')

    try:
        with connection.cursor() as cursor:
            sql = "SELECT KINMU_YMD,SYUSSYA_TIME,TAISYA_TIME FROM KINTAI_TABLE INNER JOIN SLACK_ID_TABLE ON KINTAI_TABLE.SYAIN_CD = SLACK_ID_TABLE.SYAIN_CD WHERE SLACK_ID_TABLE.SLACK_ID = '" + message.body[
                'user'] + "';"

            cursor.execute(sql)
            result = cursor.fetchall()

            table = Texttable()
            table.set_deco(Texttable.HEADER)
            table.set_cols_align(["l", "l", "l"])
            table.set_cols_width([20, 20, 20])
            table.header(['勤務日', '出社時間', '退勤時間'])
            table.add_rows(result, False)

            message.reply('')
            message.send(table.draw())

    except:
        message.send('例外が発生しました')
コード例 #2
0
def evt_handler(sender, object, iface, signal, args):
    event, tags = args
    print("evt_handler called %s" % event)

    if event == 'dhcp-lease-added':
        print("event %s for mac %s" % (event, tags['mac']))
        ret = dev.xget(
            "/status/rg/dhcp[pool='%s'][mac='%s']/leases" % (tags['pool-name'], tags['mac']))
  
        try:
            result = xmltodict.parse(ret)
        except:
            print("XML = " + ret)
            raise 
        # print(json.dumps(result, sort_keys=True, indent=4))
        lease = result['status']['rg']['dhcp']['leases']['lease']
        print(lease)

        table = Texttable()
        table.set_deco(Texttable.HEADER)
        table.set_cols_dtype(['t', 't', 't', 'i', 't', 't'])
        table.set_cols_width([6, 17, 18, 12, 28, 10])
        table.header(['Pool','MAC','IP Address','Expiry','DHCP Option','Ifname'])
        table.add_row([
            lease['pool'],
            lease['mac'],
            lease['ipaddr'],
            lease['expiry'],
            '\n'.join(lease['dhcp-option']),
            lease['ifname']])
        print(table.draw())
コード例 #3
0
ファイル: entitlement.py プロジェクト: lqueiroga/uforge-cli
    def do_list(self, args):
        try:
            doParser = self.arg_list()
            doArgs = doParser.parse_args(shlex.split(args))

            printer.out("Getting entitlements list of the UForge :")
            entList = self.api.Entitlements.Getall()
            if entList is None:
                printer.out("No entitlements found.", printer.OK)
            else:
                entList = generics_utils.order_list_object_by(
                    entList.entitlements.entitlement, "name")
                printer.out("Entitlement list for the UForge :")
                table = Texttable(200)
                table.set_cols_align(["l", "l"])
                table.header(["Name", "Description"])
                table.set_cols_width([30, 60])
                for item in entList:
                    table.add_row([item.name, item.description])
                print table.draw() + "\n"
            return 0

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_list()
        except Exception as e:
            return handle_uforge_exception(e)
コード例 #4
0
    def output_table_list(tables):
        terminal_size = get_terminal_size()[1]
        widths = []
        for tab in tables:
            for i in range(0, len(tab.columns)):
                current_width = len(tab.columns[i].label)
                if len(widths) < i + 1:
                    widths.insert(i, current_width)
                elif widths[i] < current_width:
                    widths[i] = current_width
                for row in tab.data:
                    current_width = len(resolve_cell(row, tab.columns[i].accessor))
                    if current_width > widths[i]:
                        widths[i] = current_width

        if sum(widths) != terminal_size:
            widths[-1] = terminal_size - sum(widths[:-1]) - len(widths) * 3

        for tab in tables:
            table = Texttable(max_width=terminal_size)
            table.set_cols_width(widths)
            table.set_deco(0)
            table.header([i.label for i in tab.columns])
            table.add_rows([[AsciiOutputFormatter.format_value(resolve_cell(row, i.accessor), i.vt) for i in tab.columns] for row in tab.data], False)
            six.print_(table.draw() + "\n")
コード例 #5
0
    def __init__(self):
        '''Show results

        '''
        calculate = Requeriments()
        values = calculate.calculate_all_values()
        labels = ["r","r^2","Significance","B0","B1","P","Range","UPI(70%)","LIP(70%)"]
        table = Texttable()
        table.set_cols_align(["c", "c","c"])
        table.set_cols_valign(["m","m","m"])
        table.set_cols_dtype(['t','t','f'])
        table.set_cols_width([15 for i in range(3)])
        table.set_precision(9)
        label = [
            color(bcolors.GREEN,"Test"),
            color(bcolors.GREEN,"Parameter"),
            color(bcolors.GREEN,"Expected Value")]
        rows = []
        rows.append(label)
        number = 0
        for item in values:
            number += 1
            text = 'Test%d' % number
            for pos in range(9):
                rows.append([text, labels[pos], item[pos]])
        table.add_rows(rows)
        print(table.draw() + "\n")
コード例 #6
0
ファイル: ascii.py プロジェクト: williambr/middleware
    def output_table(tab):
        max_width = get_terminal_size()[1]
        table = Texttable(max_width=max_width)
        table.set_deco(0)
        table.header([i.label for i in tab.columns])
        widths = []
        number_columns = len(tab.columns)
        remaining_space = max_width
        # set maximum column width based on the amount of terminal space minus the 3 pixel borders
        max_col_width = (remaining_space - number_columns * 3) / number_columns
        for i in range(0, number_columns):
            current_width = len(tab.columns[i].label)
            tab_cols_acc = tab.columns[i].accessor
            max_row_width = max(
                    [len(str(resolve_cell(row, tab_cols_acc))) for row in tab.data ]
                    )
            current_width = max_row_width if max_row_width > current_width else current_width
            if current_width < max_col_width:
                widths.insert(i, current_width)
                # reclaim space not used
                remaining_columns = number_columns - i - 1
                remaining_space = remaining_space - current_width - 3
                if remaining_columns != 0:
                    max_col_width = (remaining_space - remaining_columns * 3)/ remaining_columns
            else:
                widths.insert(i, max_col_width)
                remaining_space = remaining_space - max_col_width - 3
        table.set_cols_width(widths)

        table.add_rows([[AsciiOutputFormatter.format_value(resolve_cell(row, i.accessor), i.vt) for i in tab.columns] for row in tab.data], False)
        print(table.draw())
コード例 #7
0
    def scrape_score(self):
        """ Scrape web page, retrieve necessary data, format it and return to the user """
        page = requests.get(self.url)
        parsed_markup = BeautifulSoup(page.text, "html.parser")

        # final version of the table to send to the user
        scores = Texttable()

        # settings for table
        scores.set_cols_width([10, 1, 10])
        scores.set_cols_align(['l', 'c', 'r'])  # c - center align (horizontal), l - left, r - right
        scores.set_cols_valign(['m', 'm', 'm'])  # m - middle align (vertical)
        scores.set_chars(['—', '|', '+', '='])  # replace dash with em dash
        scores.header(["Home Team", "", "Away Team"])

        # scrape needed data from the parsed markup
        for element in parsed_markup.find_all("div", "row-gray"):

            match_name_element = element.find(attrs={"class": "scorelink"})

            if match_name_element is not None and element.find("div", "sco").get_text().split("-")[0].strip() == "?":
                home_team = shorten_name(' '.join(element.find("div", "tright").get_text().strip().split(" ")))
                away_team = shorten_name(' '.join(element.find(attrs={"class": "ply name"}).get_text().strip().split(" ")))

                scores.add_row([home_team, "-", away_team])

        return '`' + scores.draw() + '`'
コード例 #8
0
    def print_histogram(self, minimum=5, maximum=100, max_range=10):
        table = Texttable()
        table.set_deco(Texttable.HEADER)
        table.set_cols_align(('l', 'r', 'l'))
        table.set_cols_width((10, 3, maximum))
        table.header(('range', '#', ''))

        start = 0
        previous = 0
        current_sum = 0

        for value, count in sorted(self.histogram.items()):
            new_row = \
                    (value - start) > max_range or \
                    current_sum >= minimum or \
                    current_sum + count >= maximum
            if new_row:
                # passing **locals() is such a hax, don't do this
                table.add_row(self._format_histogram_row(**locals()))
                start = value
                previous = value
                current_sum = count
            else:
                previous = value
                current_sum += count

        # passing **locals() is such a hax, don't do this
        table.add_row(self._format_histogram_row(**locals()))
        print table.draw()
コード例 #9
0
ファイル: factory.py プロジェクト: ITDevLtd/MCVirt
    def list(self):
        """List the Drbd volumes and statuses"""
        # Set permissions as having been checked, as listing VMs
        # does not require permissions
        self._get_registered_object('auth').set_permission_asserted()

        # Create table and add headers
        table = Texttable()
        table.set_deco(Texttable.HEADER | Texttable.VLINES)
        table.header(('Name', 'Type', 'Location', 'Nodes', 'Shared', 'Free Space', 'ID'))

        # Set column alignment and widths
        table.set_cols_width((15, 5, 30, 70, 6, 15, 50))
        table.set_cols_align(('l', 'l', 'l', 'l', 'l', 'l', 'l'))

        for storage_backend in self.get_all():
            table.add_row((
                storage_backend.name,
                storage_backend.storage_type,
                storage_backend.get_location(),
                ', '.join(storage_backend.nodes),
                str(storage_backend.shared),
                SizeConverter(storage_backend.get_free_space()).to_string(),
                storage_backend.id_
            ))
        return table.draw()
コード例 #10
0
ファイル: items.py プロジェクト: reynoni/blind-prophet
def build_table(matches, result_map, headers):
    table = Texttable()
    if len(matches) > 1:
        table.set_deco(Texttable.HEADER | Texttable.HLINES | Texttable.VLINES)
        table.set_cols_align(['c'] * len(headers))
        table.set_cols_valign(['c'] * len(headers))
        table.header(headers)

        for match in matches:
            print(f'match: {match}: {result_map[match]}')
            data = [match]
            data.extend(value for value in result_map[match][0:])
            # print(f'Adding row: {data}')
            table.add_row(data)

        output = '```' + table.draw() + '```'
    else:
        table.set_cols_align(["l", "r"])
        table.set_cols_valign(["m", "m"])
        table.set_cols_width([10, 20])
        table.header([headers[0], matches[0]])
        data = list(zip(headers[1:], (result_map[matches[0]])[0:]))
        table.add_rows(data, header=False)
        output = '`' + table.draw() + '`'

    return output
コード例 #11
0
def print_empty_docs(dataset: StructuredDataset):
    """
    Prints the empty documents in the given dataset.
    """
    # Create table for better printing
    table = Texttable()
    table.set_cols_width([30, 15, 10, 10, 10])
    table.set_cols_align(['c', 'c', 'c', 'c', 'l'])
    # Specify header
    table.set_header_align(['c', 'c', 'c', 'c', 'c'])
    table.header([
        'Category name', 'Doc index inside category list of docs', 'Num words',
        'Document name', 'Content preview'
    ])
    num_empty_docs = 0
    for category_name, category_docs in dataset.files_dict.items():
        doc_index_in_category = 0
        for doc in category_docs:
            doc_words = doc.content.split()
            if len(doc_words) == 0:
                num_empty_docs += 1
                num_words_in_doc = len(doc_words)
                # Add row for each doc that contain the given word
                table.add_row([
                    category_name, doc_index_in_category, num_words_in_doc,
                    doc.name, doc.content
                ])
            doc_index_in_category += 1
    print(table.draw())
    print(" Num empty docs:", num_empty_docs)
コード例 #12
0
ファイル: drbd.py プロジェクト: joesingo/MCVirt
    def list(self):
        """List the Drbd volumes and statuses"""
        # Create table and add headers
        table = Texttable()
        table.set_deco(Texttable.HEADER | Texttable.VLINES)
        table.header(('Volume Name', 'VM', 'Minor', 'Port', 'Role', 'Connection State',
                      'Disk State', 'Sync Status'))

        # Set column alignment and widths
        table.set_cols_width((30, 20, 5, 5, 20, 20, 20, 13))
        table.set_cols_align(('l', 'l', 'c', 'c', 'l', 'c', 'l', 'c'))

        # Iterate over Drbd objects, adding to the table
        for drbd_object in self.get_all_drbd_hard_drive_object(True):
            table.add_row((drbd_object.resource_name,
                           drbd_object.vm_object.get_name(),
                           drbd_object.drbd_minor,
                           drbd_object.drbd_port,
                           'Local: %s, Remote: %s' % (drbd_object._drbdGetRole()[0].name,
                                                      drbd_object._drbdGetRole()[1].name),
                           drbd_object._drbdGetConnectionState().name,
                           'Local: %s, Remote: %s' % (drbd_object._drbdGetDiskState()[0].name,
                                                      drbd_object._drbdGetDiskState()[1].name),
                           'In Sync' if drbd_object._isInSync() else 'Out of Sync'))
        return table.draw()
コード例 #13
0
    def printGuildScores(self, war):
        data = self.api.getGuildScoresIndiv(war)
        tab = Texttable()

        scores = []
        scores = self.getGuildScores(war)

        if len(scores) % 2 != 0:
            scores.append([len(scores), '', ''])
        scores.sort(key=lambda x: x[0])

        # make table double wide to fit on terminal screen
        dw = [[]]
        mid = int(len(scores) / 2)

        for i in range(0, mid):
            dw.append([
                scores[i][0], scores[i][1], scores[i][2], scores[i + mid][0],
                scores[i + mid][1], scores[i + mid][2]
            ])

        tab.add_rows(dw)
        tab.set_cols_align(['r', 'r', 'r', 'r', 'r', 'r'])
        tab.set_cols_width([5, 20, 10, 5, 20, 10])
        tab.header(['Rank', 'Name', 'Score', 'Rank', 'Name', 'Score'])
        print(tab.draw())
コード例 #14
0
def log_api_exception(sender, exception, **extra):
    fallback_message = u'Exception raised inside `log_api_exception`!'
    try:
        messages = []

        # If debugging or testing, log verbose request, browser, and user information
        if (sender.debug or sender.testing) and sender.config.get('API_LOG_EXTRA_REQUEST_INFO_ON_REQUEST_EXCEPTION'):
            request_info, browser_info, user_info = gather_api_exception_log_data()

            if request_info:
                table = Texttable()
                table.set_cols_width([10, 62])  # Accommodates an overall table width of 79 characters
                table.add_rows([('Request', 'Information')] + request_info)
                messages.append(table.draw())

            if browser_info:
                table = Texttable()
                table.add_rows([('Browser', 'Information')] + browser_info)
                messages.append(table.draw())

            if user_info:
                table = Texttable()
                table.add_rows([('User', 'Information')] + user_info)
                messages.append(table.draw())
        else:
            messages.append(u'{0}'.format(exception))

        message = '\n\n'.join(messages) if messages else None
    except Exception:
        message = fallback_message
    sender.logger.exception(message, **extra)
コード例 #15
0
def cmd_list():
    imap = connectIMAP(CONFIG.accounts[0])
    # open readonly b/c otherwise messages will be marked as read '\\Seen'
    imap.select_folder(ARGS.mailbox, readonly=True)

    imap = connectIMAP(CONFIG.accounts[0])
    # open readonly b/c otherwise messages will be marked as read '\\Seen'
    imap.select_folder(ARGS.mailbox, readonly=True)
    try:
        msgs = iterMessages(imap)
        msgs = sorted(msgs, key=lambda m: m.date)
        ids = [m.id for m in msgs]
        table = Texttable()
        table.set_deco(Texttable.HEADER | Texttable.HLINES)
        table.header(
            ['Date', 'ID', 'Score', 'From', 'Subject', 'Flags', 'age (mins)'])
        table.set_cols_width([20, 10, 6, 30, 30, 12, 10])
        table.set_precision(1)
        for m in msgs:
            if m.score is not None and m.score < ARGS.score:
                if ARGS.verbose:
                    verbose(
                        'skipping message id=%d date=%s score=%s below threshold of %s'
                        % (m.id, m.date, m.scoreStr(), str(ARGS.score)))
                continue
            table.add_row([
                m.date, m.id,
                m.scoreStr(),
                m.headers.get('From', None),
                m.headers.get('Subject', None), m.flags,
                m.ageMinutes()
            ])
        info(table.draw())
    finally:
        imap.logout()
コード例 #16
0
def nilai():
    from texttable import Texttable
    table = Texttable()
    jawab = "y"
    no = 0
    nama = []
    nim = []
    nilai_tugas = []
    nilai_uts = []
    nilai_uas = []
    while (jawab == "y"):
        nama.append(input("Masukan Nama  :"))
        nim.append(input("Masukan Nim   :"))
        nilai_tugas.append(input("Nilai Tugas   :"))
        nilai_uts.append(input("Nilai Uts     :"))
        nilai_uas.append(input("Nilai Uas     :"))
        jawab = input("Tambah data (y/t) ?")
        no += 1

    for i in range(no):
        tugas = int(nilai_tugas[i])
        uts = int(nilai_uts[i])
        uas = int(nilai_uas[i])
        akhir = (tugas * 30 / 100) + (uts * 35 / 100) + (uas * 35 / 100)
        table.set_cols_width([2, 10, 10, 5, 5, 5, 5])
        table.set_cols_dtype(['i', 't', 'i', 'i', 'i', 'i', 'i'])
        table.set_cols_align(['c', 'l', 'c', 'c', 'c', 'c', 'c'])
        table.add_rows([['No', 'Nama', 'Nim', 'Tugas', 'Uts', 'Uas', 'Akhir'],
                        [
                            i + 1, nama[i], nim[i], nilai_tugas[i],
                            nilai_uts[i], nilai_uas[i], akhir
                        ]])
    print(table.draw())
コード例 #17
0
def print_result(result):
    
    table = Texttable()
    table.set_deco(Texttable.BORDER)
    table.set_cols_width([21, 40])

    sha1 = result.get('sha1', None)
    data = {
        'SHA-1:':sha1,
        'Resource:':result['resource'],
        'Detection ratio:':'{}/{} ({:.2f}% Malicious)'.format(
            result['positives'], 
            result['total'],
            result['positives']/result['total']*100
        )
    }

    for item in data.items():
        table.add_row(item)
    print(table.draw())


    print('\n\033[1;30;47m{:26}{:32}{:10}\033[0m'.format('Antivirus', 'Result', 'Update'))
    for item in result['scans'].items():
        antivirus = item[0]
        detected  = 'malicious' if item[1]['detected'] else 'Undetected'
        update    = item[1].get('update', '00000000')
        if detected == 'malicious':
            row = '{}{:26.24}{:32.30}{:10}{}'.format(
                    RED, antivirus, item[1]['result'], update, RESET)
        else:
            row = '{:26.24}{:32}{:10}'.format(antivirus, detected, update)

        print(row)
コード例 #18
0
def grid(desc, provider, type, service, region):
    """
    Create and print grid for result

    Arguments:
        desc: Description of actions to reduce costs
        provider: Cloud Provider (aws)
        type: Type (Compute,Storage)
        service: Cloud Service (ec2,cloudwatch)
        region: Cloud Provider region
    Returns:
        print grid
    """
    count = 0
    table = Texttable()
    table.set_cols_width([5, 10, 10, 10, 10, 180])
    table.add_rows(
        [["#", "Provider", "Type", "Region", "Service", "Description"]])
    for toto in desc:
        for i in toto:
            table.add_row([count, provider, type, region, service, i])
            count += 1
    response = table.draw()
    logger.info(response)
    return response
コード例 #19
0
ファイル: stack.py プロジェクト: zlatozar/pytak
    def view(self, key=None):
        """Nice stack data view.

        Use colorama module to highlight key if passed and
        texttable for data visualisation
        """

        def __print_select():
            for idx, row in enumerate(self):
                for i in row:
                    if key in i:
                        console_logger.info("select('%s').key(%s)\n" %
                                            (Fore.RED + row['class'] + Style.RESET_ALL,
                                             Fore.RED + i + Style.RESET_ALL))
                        console_logger.info("Value of '%s' is %s\n" % (i,
                                                                       Fore.RED + str(row[i]) + Style.RESET_ALL))

        console_logger.info("\nStack size: %s\n" % self.size())

        table = Texttable()
        table.set_cols_align(["c", "c"])
        table.set_cols_valign(["t", "m"])
        table.set_cols_width([8, 150])
        table.add_row(["Current Index", "Entry"])

        for idx, row in enumerate(self):
            table.add_row([idx, row])

        console_logger.info(table.draw() + "\n")
        if key:
            __print_select()
コード例 #20
0
ファイル: brain.py プロジェクト: B3DS-D01/B3dsDemo
def similarity_text(idx, distance_matrix, data, d, n_similar=n_similar_val):
    # similarity_text(idx, distance_matrix, new_data,d)
    t = Texttable()
    t.set_cols_width([50, 20])
    sorted_distance_idxs = np.argsort(
        distance_matrix[idx])[:n_similar]  # EX: [252, 102, 239, ...]
    #argsort() - Returns the indices that would sort an array.

    # x = numpy.array([1.48,1.41,0.0,0.1])
    # print x.argsort()

    # >[2 3 1 0]
    most_sim_idx = sorted_distance_idxs[1]
    t.add_rows([['Text', 'Similarity']])
    faq_match = None

    for similar_idx in sorted_distance_idxs:
        datum = data[similar_idx]
        distance = distance_matrix[idx][similar_idx]
        similarity = 1 - distance
        t.add_rows([[datum, str(round(similarity, 2))]])
        if similar_idx == most_sim_idx and similarity >= 0.75:
            faq_match = data[most_sim_idx]
        else:
            sorry = "Sorry, I'm not sure how to respond. Let me find someone who can help you."
    if faq_match is not None:
        fqa = {}
        fqa["API_INPUT"] = d["API_INPUT"]
        fqa["MESSAGE"] = faqs[faq_match]
        response = json.dumps(fqa)
        return response

    else:
        return sorry
コード例 #21
0
ファイル: factory.py プロジェクト: ITDevLtd/MCVirt
    def get_hard_drive_list_table(self):
        """Return a table of hard drives"""
        # Manually set permissions asserted, as this function can
        # run high privilege calls, but doesn't not require
        # permission checking
        self._get_registered_object('auth').set_permission_asserted()

        # Create table and set headings
        table = Texttable()
        table.set_deco(Texttable.HEADER | Texttable.VLINES)
        table.header(('ID', 'Size', 'Type', 'Storage Backend', 'Virtual Machine'))
        table.set_cols_width((50, 15, 15, 50, 20))

        # Obtain hard ives and add to table
        for hard_drive_obj in self.get_all():
            vm_object = hard_drive_obj.get_virtual_machine()
            hdd_type = ''
            storage_backend_id = 'Storage backend does not exist'
            try:
                storage_backend_id = hard_drive_obj.storage_backend.id_
                hdd_type = hard_drive_obj.get_type()
                hdd_size = SizeConverter(hard_drive_obj.get_size()).to_string()
            except (VolumeDoesNotExistError,
                    HardDriveDoesNotExistException,
                    StorageBackendDoesNotExist), exc:
                hdd_size = str(exc)

            table.add_row((hard_drive_obj.id_, hdd_size,
                           hdd_type, storage_backend_id,
                           vm_object.get_name() if vm_object else 'Not attached'))
コード例 #22
0
ファイル: user_role.py プロジェクト: lqueiroga/uforge-cli
    def do_list(self, args):
        try:
            doParser = self.arg_list()
            doArgs = doParser.parse_args(shlex.split(args))

            printer.out("Getting roles and their entitlements for user [" +
                        doArgs.account + "]:\n")
            roles = self.api.Users(doArgs.account).Roles.Getall()

            table = Texttable(200)
            table.set_cols_align(["l", "l"])
            table.header(["Name", "Description"])
            table.set_cols_width([30, 60])
            for role in roles.roles.role:
                table.add_row([role.name.upper(), role.description])
                for entitlement in role.entitlements.entitlement:
                    table.add_row(
                        ["===> " + entitlement.name, entitlement.description])

            printer.out("Role entitlements are represented with \"===>\".",
                        printer.INFO)
            print table.draw() + "\n"
            return 0

        except ArgumentParserError as e:
            printer.out("In Arguments: " + str(e), printer.ERROR)
            self.help_list()
        except Exception as e:
            return handle_uforge_exception(e)
コード例 #23
0
    def list(self):
        """List the Drbd volumes and statuses"""
        # Create table and add headers
        table = Texttable()
        table.set_deco(Texttable.HEADER | Texttable.VLINES)
        table.header(('Volume Name', 'VM', 'Minor', 'Port', 'Role',
                      'Connection State', 'Disk State', 'Sync Status'))

        # Set column alignment and widths
        table.set_cols_width((30, 20, 5, 5, 20, 20, 20, 13))
        table.set_cols_align(('l', 'l', 'c', 'c', 'l', 'c', 'l', 'c'))

        # Iterate over Drbd objects, adding to the table
        for drbd_object in self.get_all_drbd_hard_drive_object(True):
            table.add_row(
                (drbd_object.resource_name, drbd_object.vm_object.get_name(),
                 drbd_object.drbd_minor, drbd_object.drbd_port,
                 'Local: %s, Remote: %s' %
                 (drbd_object._drbdGetRole()[0].name,
                  drbd_object._drbdGetRole()[1].name),
                 drbd_object._drbdGetConnectionState().name,
                 'Local: %s, Remote: %s' %
                 (drbd_object._drbdGetDiskState()[0].name,
                  drbd_object._drbdGetDiskState()[1].name),
                 'In Sync' if drbd_object._isInSync() else 'Out of Sync'))
        return table.draw()
コード例 #24
0
ファイル: interop.py プロジェクト: e-schumann/crossbar
def run(host, port):

    port = int(port)

    from . import interop_tests
    test_names = [x for x in dir(interop_tests) if x.startswith("test_")]

    tests = [getattr(interop_tests, test_name) for test_name in test_names]

    results = []
    with click.progressbar(tests, label="Running interop tests...") as _tests:
        for test in _tests:
            results.append(test(host, port))

    fmt_results = []
    for r in results:
        fmt_results.append((r.name, "True" if r.success else "False",
                            r.reason if r.reason else "", r.transcript))

    t = Texttable()
    t.set_cols_width([20, 10, 80, 60])
    rows = [["Name", "Successful", "Reason", "Client Transcript"]]
    rows.extend(fmt_results)
    t.add_rows(rows)
    print(t.draw(), file=sys.__stdout__)

    failures = []
    for x in results:
        if not x.success:
            failures.append(False)

    if failures:
        sys.exit(len(failures))
    sys.exit(0)
コード例 #25
0
ファイル: component_info.py プロジェクト: Aayush-Kasurde/zato
def format_info(value, format, cols_width=None, dumper=None):
    if format in(INFO_FORMAT.DICT, INFO_FORMAT.JSON, INFO_FORMAT.YAML):
        value['component_details'] = json_loads(value['component_details'])

    if format == INFO_FORMAT.JSON:
        return json_dumps(value)

    elif format == INFO_FORMAT.YAML:
        buff = StringIO()
        yaml.dump_all([value], default_flow_style=False, indent=4, Dumper=dumper, stream=buff)
        value = buff.getvalue()
        buff.close()

        return value

    elif format == INFO_FORMAT.TEXT:
        cols_width = (elem.strip() for elem in cols_width.split(','))
        cols_width = [int(elem) for elem in cols_width]

        table = Texttable()
        table.set_cols_width(cols_width)

        # Use text ('t') instead of auto so that boolean values don't get converted into ints
        table.set_cols_dtype(['t', 't'])

        rows = [['Key', 'Value']]
        rows.extend(sorted(value.items()))

        table.add_rows(rows)

        return table.draw()

    else:
        return value
コード例 #26
0
def list():
    api.getCredentials()
    log.debug("Command: List.")

    url = "/gists"
    gists = api.get(url)
    public_count = 0
    private_count = 0

    table = Texttable(max_width=defaults.max_width)
    table.set_deco(Texttable.HEADER | Texttable.HLINES)
    table.set_cols_align(["l", "l", "l", "l", "l"])
    table.set_cols_width([4, 30, 6, 20, 30])

    table.header(["", "Files", "Public", "Gist ID", "Description"])

    for (i, gist) in enumerate(gists):
        private = False
        file_list = ''
        for (file, data) in gist['files'].items():
            file_list += "'" + file + "' "
        if gist['public']:
            public_count += 1
        else:
            private_count += 1
        table.add_row([
            i + 1, file_list,
            str(gist['public']), gist['id'], gist['description']
        ])

    print(table.draw())

    print('')
    print("You have %i Gists. (%i Private)" % (len(gists), private_count))
コード例 #27
0
ファイル: signin.py プロジェクト: killkill/schemanizer
 def do_list_changesets(self, arg, opts=None):
     """Show changesets needing review."""
     changesets = requests.get(
         "http://%s/api/v1/changeset/" % self.site, params={"review_status": "needs"}, auth=self.api_auth
     )
     objects = changesets.json().get("objects")
     table = Texttable()
     table.set_deco(Texttable.HEADER)
     table.set_cols_align(["c", "c", "c", "c", "c"])
     table.set_cols_width([5, 20, 15, 15, 10])
     rows = [["ID", "Type", "Classification", "Version Control URL", "Submitted By"]]
     for cs in objects:
         user = requests.get("http://%s%s" % (self.site, cs.get("submitted_by")), auth=self.api_auth)
         user_detail = user.json()
         rows.append(
             [
                 cs.get("id"),
                 cs.get("type"),
                 cs.get("classification"),
                 cs.get("version_control_url"),
                 user_detail.get("name"),
             ]
         )
     table.add_rows(rows)
     print "Changesets That Need To Be Reviewed:"
     print table.draw()
コード例 #28
0
    def printMatches(self):
        resp = self.api.getGuildWarStatus()
        matches = [[]]
        tab = Texttable()

        if not resp['guild_war_active']:
            print("No guild war in progress")
            return

        for match in resp['guild_war_matches']:
            result = int(match['us_kills']) - int(match['them_kills'])
            winner = 'Win'
            if result < 0:
                winner = 'Loss'
            matches.append([
                match['them_name'].encode('utf8'), match['us_kills'],
                match['them_kills'], result, winner
            ])

        if len(matches) > 1:
            tab.add_rows(matches[1:])
            tab.set_cols_align(['r', 'r', 'r', 'r', 'r'])
            tab.set_cols_width([40, 15, 15, 10, 12])
            tab.header(['Enemy', 'Our Score', 'Their Score', 'Diff', 'Result'])
            print(tab.draw())
コード例 #29
0
def print_empty_docs(dataset: UnstructuredDataset):
    """
    Prints the empty documents in the given dataset.
    """
    # Create table for better printing
    table = Texttable()
    table.set_cols_width([15, 10, 10, 10])
    table.set_cols_align(['c', 'c', 'c', 'l'])
    # Specify header
    table.set_header_align(['c', 'c', 'c', 'c'])
    table.header(
        ['Doc index', 'Num words', 'Document name', 'Content preview'])

    num_empty_docs = 0
    doc_index = 0
    for doc in dataset.files_list:
        doc_words = doc.content.split()
        if len(doc_words) == 0:
            num_empty_docs += 1
            num_words_in_doc = len(doc_words)
            # Add row for each doc that contain the given word
            table.add_row([doc_index, num_words_in_doc, doc.name, doc.content])
        doc_index += 1

    print(table.draw())
    print(" Num empty docs:", num_empty_docs)
コード例 #30
0
ファイル: actions.py プロジェクト: khilnani/gists.cli
def list ():
  api.getCredentials()
  log.debug ("Command: List.")

  url = "/gists"
  gists = api.get(url)
  public_count = 0
  private_count = 0

  table = Texttable(max_width=defaults.max_width)
  table.set_deco(Texttable.HEADER | Texttable.HLINES)
  table.set_cols_align(["l", "l", "l", "l", "l"])
  table.set_cols_width([4, 30, 6, 20, 30])

  table.header( ["","Files","Public", "Gist ID",  "Description"] )

  for (i, gist) in enumerate(gists):
    private = False
    file_list = ''
    for (file, data) in gist['files'].items():
      file_list += "'" + file + "' " 
    if gist['public']:
      public_count += 1
    else:
      private_count += 1
    table.add_row( [i+1, file_list, str(gist['public']), gist['id'], gist['description']] )

  print table.draw()

  print ''
  print "You have %i Gists. (%i Private)" % (len(gists), private_count)
コード例 #31
0
ファイル: librations.py プロジェクト: 4xxi/resonances
def show_librations(asteroid_condition: AsteroidCondition = None,
                    planet_condtion: PlanetCondition = None,
                    is_pure: bool = None, is_apocentric: bool = None,
                    axis_interval: AxisInterval = None, integers: List[str] = None,
                    body_count=3, limit=100, offset=0):
    body_count = BodyNumberEnum(body_count)
    is_three = (body_count == BodyNumberEnum.three)
    query = _build_libration_query(asteroid_condition, planet_condtion, is_pure, is_apocentric,
                                   axis_interval, integers, body_count, limit, offset)
    table = Texttable(max_width=120)
    witdths = [10] * body_count.value
    table.set_cols_width(witdths + [30, 15, 10, 10])
    headers = ['First planet']
    if is_three:
        headers.append('Second planet')
    headers += ['Asteroid', 'Integers and semi major axis of asteroid', 'apocentric', 'pure',
                'axis (degrees)']
    table.add_row(headers)

    for resonance in query:  # type: ResonanceMixin
        libration = resonance.libration
        data = [x.name for x in resonance.get_big_bodies()]
        data += [
            resonance.small_body.name,
            resonance,
            '%sapocentric' % ('not ' if not libration.is_apocentric else ''),
            '%spure' % ('not ' if not libration.is_pure else ''),
            resonance.asteroid_axis
        ]
        table.add_row(data)

    print(table.draw())
コード例 #32
0
def main():
    # locations
    locations = ast.literal_eval(config['now_location']['locations'])
    status = ast.literal_eval(config['now_states']['status'])
    # payload creation
    count = 0
    # while (count < int(sys.argv[1])):
    while (count < 10):
        requester = names.get_full_name()
        location = random.choice(locations)
        temp = temp_check()
        ppe = random.choice(status)
        access = access_check(temp[1], ppe)
        print(Fore.YELLOW + '\nThermalNet Simulator Data' + Style.RESET_ALL)
        t = Texttable()
        t.set_cols_width([20, 10, 8, 8, 8, 8])
        t.set_cols_align(['c', 'c', 'c', 'c', 'c', 'c'])
        t.add_rows(
            [['requester', 'location', 'temp', 'temp ok', 'ppe ok', 'access'],
             [requester, location, temp[0], temp[1], ppe, access[0]]])
        print(t.draw())
        now(requester, location, temp[0], temp[1], ppe, access[0])
        # time.sleep(cycle_time)
        print('\n')
        # visual cycle time
        for i in tqdm(range(cycle_time)):
            time.sleep(1)
        count = count + 1
コード例 #33
0
ファイル: deck.py プロジェクト: phenmp/atassist-api
    def printDeck(self, context):
        if context.sort:
            self.cards.sort(key=lambda x: (x.type, x.name, -x.level))

        if context.title == "":
            title = self.name

        rows = [[]]
        deck_size = 0

        rows = self.getPrintableDeckArray()
        deck_size = len(rows) - 1

        tab = Texttable()

        if context.amount:
            del rows[context.amount:]

        header = ['Name', 'Level', 'Attack', 'Health', 'Type', 'Skills']

        tab.add_rows(rows)
        tab.set_cols_align(['r', 'r', 'r', 'r', 'r', 'l'])
        tab.set_cols_width([30, 5, 6, 6, 6, 50])
        tab.header(header)

        deck_output = "{0}\n".format(title)
        deck_output += "Deck Size: {0}\n".format(deck_size)
        deck_output += tab.draw()

        # TODO: Should convert deck response to JSON instead of printable table, no longer command line app

        # write to file
        writeToCsvFile(context.userId, header, rows)

        return deck_output
コード例 #34
0
ファイル: pretty.py プロジェクト: carriercomm/shipper
def containers_to_ascii_table(containers):
    """Just a method that formats the images to ascii table.
    Expects dictionary {host: [images]}
    and prints multiple tables
    """
    with closing(StringIO()) as out:
        for host, values in containers.iteritems():
            out.write("[" + str(host) + "] \n")
            t = TextTable(max_width=400)
            t.set_deco(TextTable.HEADER)
            t.set_cols_dtype(['t'] * 6)
            t.set_cols_align(["l"] * 6)
            t.set_cols_width([12, 25, 25, 15, 20, 15])
            rows = []
            rows.append(
                ['Id', 'Image', 'Command', 'Created', 'Status', 'Ports'])
            for container in values:
                rows.append([
                    container.id[:12],
                    container.image,
                    container.command[:20],
                    time_ago(container.created),
                    container.status,
                    container.ports
                ])
            t.add_rows(rows)
            out.write(t.draw() + "\n\n")
        return out.getvalue()
コード例 #35
0
        def do_list(self, args):
                try:
                        doParser = self.arg_list()
                        doArgs = doParser.parse_args(shlex.split(args))

                        printer.out("Getting entitlements list of the UForge :")
                        entList = self.api.Entitlements.Getall()
                        if entList is None:
                                printer.out("No entitlements found.", printer.OK)
                        else:
                                entList=generics_utils.order_list_object_by(entList.entitlements.entitlement, "name")
                                printer.out("Entitlement list for the UForge :")
                                table = Texttable(200)
                                table.set_cols_align(["l", "l"])
                                table.header(["Name", "Description"])
                                table.set_cols_width([30,60])
                                for item in entList:
                                        table.add_row([item.name, item.description])
                                print table.draw() + "\n"
                        return 0

                except ArgumentParserError as e:
                        printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
                        self.help_list()
                except Exception as e:
                        return handle_uforge_exception(e)
コード例 #36
0
ファイル: top-commands.py プロジェクト: minyoung/dotfiles
def sub(db, command, *filters):
    counts = collections.defaultdict(int)
    user_filter = ' '.join(itertools.chain([command], filters))
    total = 0

    query = '''
    SELECT user_string
    FROM commands
    WHERE
        timestamp > ?
        AND command = ?
    '''

    for row in db.execute(query, (TIMESTAMP, command)):
        command = normalize_user_string(row[0])
        if command.startswith(user_filter):
            counts[command] += 1
            total += 1
    percentage = 100 / float(total)

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_align(('r', 'r', 'l'))
    table.set_cols_width((5, 6, 75))
    table.header(('count', '%', 'command'))
    for key, value in sorted(counts.iteritems(), key=lambda (k, v): (v, k), reverse=True)[:20]:
        table.add_row((value, value * percentage, key))
    print table.draw()
コード例 #37
0
ファイル: find-commands.py プロジェクト: minyoung/dotfiles
def find_commands(db, *filters):
    user_filter = '\s+'.join(filters)
    user_re = re.compile(user_filter)
    RE_CACHE[user_filter] = user_re

    query = '''
    SELECT hostname, timestamp, duration, user_string
    FROM commands
    WHERE timestamp > ? AND user_string REGEXP ?
    ORDER BY timestamp
    '''

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_align(('l', 'r', 'r', 'l'))
    table.header(('host', 'date', 'duration', 'command'))

    host_width = 6
    max_command_width = 9
    now = time.time()
    for row in db.execute(query, (TIMESTAMP, user_filter)):
        host_width = max(host_width, len(row[0]))
        max_command_width = max(max_command_width, len(row[3]))
        table.add_row((
            row[0],
            format_time(row[1], now),
            format_duration(row[2]) if row[2] > 0 else '',
            highlight(row[3], user_re)))

    table.set_cols_width((host_width, 30, 10, max_command_width + 2))

    print table.draw()
コード例 #38
0
def containers_to_ascii_table(containers):
    """Just a method that formats the images to ascii table.
    Expects dictionary {host: [images]}
    and prints multiple tables
    """
    with closing(StringIO()) as out:
        for host, values in containers.iteritems():
            out.write("[" + str(host) + "] \n")
            t = TextTable(max_width=400)
            t.set_deco(TextTable.HEADER)
            t.set_cols_dtype(['t'] * 6)
            t.set_cols_align(["l"] * 6)
            t.set_cols_width([12, 25, 25, 15, 20, 15])
            rows = []
            rows.append(
                ['Id', 'Image', 'Command', 'Created', 'Status', 'Ports'])
            for container in values:
                rows.append([
                    container.id[:12], container.image, container.command[:20],
                    time_ago(container.created), container.status,
                    container.ports
                ])
            t.add_rows(rows)
            out.write(t.draw() + "\n\n")
        return out.getvalue()
コード例 #39
0
    def print_sell_list(self):

        global sell_list

        self.selling_group.setHidden(False)

        table = Texttable()
        table.set_cols_width([20, 7, 8, 9, 9])
        # table.set_cols_align(["r", "r", "r", "r"])

        table.header(
            ["المنتج", "العدد", "سعر القطعه", "الاجمالي", "بعد الخصم"])
        x = 0
        for item in sell_list:
            name = item[0]
            number = item[1]
            unit_price = item[3]
            total = item[4]
            last_price = item[5]
            x += int(total)
            table.add_row([name, number, unit_price, total, last_price])
        fix_cost = float(self.new_client_cost.text())
        print(fix_cost)
        if fix_cost > 0:
            self.selling_label.setText(
                table.draw() + '\n\n\t\t' + f'منتجات = {x}' + '\n\t\t' +
                f'بعد الخصم = {self.all_sell_total_after.text()}' + '\n\t\t' +
                f'مصنعيه = {fix_cost}' + '\n\n\t\t' +
                f'الاجمالي = {x+fix_cost}')
        else:
            self.selling_label.setText(
                table.draw() + '\n\n\t\t' + f'الاجمالي = {x}' + '/n\t\t' +
                f'بعد الخصم = {self.all_sell_total_after.text()}')
コード例 #40
0
def load_fs():
    t = Texttable()
    # headers/columns
    columns = ['Fset#']
    for k, h in sorted(features_map.items(), key=lambda kv: kv[1][1]):
        columns.append(h[1])

    matrix_length = len(columns)
    t.set_cols_width([5] * matrix_length)
    t.set_cols_align(['c'] * matrix_length)
    t.set_cols_valign(['m'] * matrix_length)
    t.set_cols_dtype(['t'] * matrix_length)

    root_path = os.path.dirname(os.path.realpath(__file__))
    fs_dir = os.path.join(root_path, 'config/general_config/')

    for fs_filename in sorted(os.listdir(fs_dir)):
        fs_dict = {}
        if fs_filename.startswith('featureset0') and \
           fs_filename.endswith('.yml'):
            with open(os.path.join(fs_dir, fs_filename)) as fs_file:
                fs_dict = yaml.load(fs_file, yaml.SafeLoader)
                datarow = get_data_from_yaml(fs_dict, fs_filename)
                t.add_rows([columns, datarow])
                fs_list.append(fs_filename[10:13])
    print(t.draw())
    print('\n')
コード例 #41
0
ファイル: ec2.py プロジェクト: rotemjac/aws-python-boto3
def printing_as_table(list):
    from texttable import Texttable
    list_for_table = []
    list_for_table.append([
        'InstanceId', 'State', 'VpcId', 'SubnetId', 'AvailabilityZone',
        'PublicIpAddress', 'SecurityGroupsNumber', 'FirstSecurityGroupsName',
        'KeyName', 'Monitoring', 'Encrypted'
    ])

    for item in list:
        list_for_table.append([
            item.instance_id, item.state, item.vpc_id, item.subnet_id,
            item.availability_zone, item.public_ip_address,
            item.number_of_security_groups, item.first_security_group_name,
            item.key_name, item.monitoring, item.encrypted
        ])

    t = Texttable()
    col_size = 10
    t.set_cols_width([
        col_size, col_size, col_size, col_size, col_size, col_size, col_size,
        col_size, col_size, col_size, col_size
    ])
    t.add_rows(list_for_table)

    print(t.draw())
コード例 #42
0
ファイル: interop.py プロジェクト: NinjaMSP/crossbar
def run(host, port):

    port = int(port)

    from . import interop_tests
    test_names = [x for x in dir(interop_tests) if x.startswith("test_")]

    tests = [getattr(interop_tests, test_name) for test_name in test_names]

    results = []
    with click.progressbar(tests, label="Running interop tests...") as _tests:
        for test in _tests:
            results.append(test(host, port))

    fmt_results = []
    for r in results:
        fmt_results.append((r.name,
                            "True" if r.success else "False", r.reason if r.reason else "", r.transcript))

    t = Texttable()
    t.set_cols_width([20, 10, 80, 60])
    rows = [["Name", "Successful", "Reason", "Client Transcript"]]
    rows.extend(fmt_results)
    t.add_rows(rows)
    print(t.draw(), file=sys.__stdout__)

    failures = []
    for x in results:
        if not x.success:
            failures.append(False)

    if failures:
        sys.exit(len(failures))
    sys.exit(0)
コード例 #43
0
ファイル: core.py プロジェクト: MrBadge/CAM-interpreter
    def print_steps(self, show_result=True):
        def max_len_of_list_of_str(s):
            return max(len(line) for line in str(s).split('\n'))

        def autodetect_width(d):
            widths = [0] * len(d[0])
            for line in d:
                for _i in range(len(line)):
                    widths[_i] = max(widths[_i], max_len_of_list_of_str(line[_i]))
            return widths

        if self.save_history:
            if self.errors:
                self.history = self.history[:-1]
            t = Texttable()
            header = ['№', 'Term', 'Code'] if self.parallel else ['№', 'Term', 'Code', 'Stack']
            data = [header] + [
                [repr(i) for i in item][:-1] if self.parallel else [repr(i) for i in item] for item in self.history]
            t.add_rows(data)
            t.set_cols_align(['l'] + ['r'] * (len(header) - 1))
            t.set_cols_valign(['m'] + ['m'] * (len(header) - 1))
            t.set_cols_width(autodetect_width(data))
            print t.draw()
        else:
            if not self.errors:
                print ' Steps: %10s' % self.iteration
                if show_result:
                    print 'Result: %10s' % repr(self.term)
コード例 #44
0
 def to_txt_file(self, rounds,file, print_header): 
     table = Texttable()
     table.set_cols_width([len(self.team_one.get_name()) + 9, len(self.team_two.get_name()) + 9])
     if print_header:
         deco = Texttable.HEADER | Texttable.VLINES
         table.header([self.team_one.get_name(), self.team_two.get_name()])
     else:
         deco = Texttable.VLINES
     table.set_deco(deco)
     table.set_chars(['-', '|', '=', '='])
     rows = [[str(rounds[0].get_team_one_points()),str(rounds[0].get_team_two_points())]]
     for i in range(1,len(rounds)):
         column1 = f"{sum([x.get_team_one_points() for x in rounds[:i]])} + {rounds[i].get_team_one_points()}"
         column2 = f"{sum([x.get_team_two_points() for x in rounds[:i]])} + {rounds[i].get_team_two_points()}"
         rows.append([column1,column2])
     column1 = f"{sum([x.get_team_one_points() for x in rounds])}"
     column2 = f"{sum([x.get_team_two_points() for x in rounds])}"
     rows.append([column1,column2])
     table.add_rows(rows, header = False)
     file.write(table.draw())
     file.write('\n')
     self.write_divider_to_file(file)
     table.reset()
     table.add_row([f"({self.team_one.games_won})", f"({self.team_two.games_won})"])
     table.set_cols_align(["c","c"])        
     file.write(table.draw())
     file.write('\n')
     self.write_divider_to_file(file)
コード例 #45
0
ファイル: user_role.py プロジェクト: DimitriSCOLE/uforge-cli
        def do_list(self, args):
                try:
                        doParser = self.arg_list()
                        doArgs = doParser.parse_args(shlex.split(args))

                        printer.out("Getting roles and their entitlements for user [" + doArgs.account + "]:\n")
                        roles = self.api.Users(doArgs.account).Roles.Getall()

                        table = Texttable(200)
                        table.set_cols_align(["l", "l"])
                        table.header(["Name", "Description"])
                        table.set_cols_width([30,60])
                        for role in roles.roles.role:
                                table.add_row([role.name.upper(), role.description])
                                for entitlement in role.entitlements.entitlement:
                                        table.add_row(["===> " + entitlement.name, entitlement.description])

                        printer.out("Role entitlements are represented with \"===>\".", printer.INFO)
                        print table.draw() + "\n"
                        return 0

                except ArgumentParserError as e:
                        printer.out("In Arguments: "+str(e), printer.ERROR)
                        self.help_list()
                except Exception as e:
                        return handle_uforge_exception(e)
コード例 #46
0
def printing_as_table(list):
    from texttable import Texttable
    list_for_table = []
    list_for_table.append([
        'DBInstanceIdentifier', 'DBInstanceClass', 'Engine',
        'DBInstanceStatus', 'MasterUsername', 'PubliclyAccessible',
        'StorageEncrypted', 'DeletionProtection', 'MultiAZ',
        'AutoMinorVersionUpgrade', 'CACertificateIdentifier', 'Endpoint_Port',
        'IAM_DB_DAuth_Enabled'
    ])

    for item in list:
        list_for_table.append([
            item.dbInstanceIdentifier, item.dbInstanceClass, item.engine,
            item.dbInstanceStatus, item.masterUsername,
            item.publicly_accessible, item.storage_encrypted,
            item.deletion_protection, item.multi_az,
            item.auto_minor_version_upgrade, item.ca_certificate_identifier,
            item.endpoint_port, item.iam_database_authentication_enabled
        ])

    t = Texttable()
    col_size = 8
    t.set_cols_width([
        col_size, col_size, col_size, col_size, col_size, col_size, col_size,
        col_size, col_size, col_size, col_size, col_size, col_size
    ])

    t.add_rows(list_for_table)

    print(t.draw())
コード例 #47
0
def _dataframe_to_texttable(df, align=None):
    """Convert data frame to texttable. Sets column widths to the
    widest entry in each column."""
    ttab = Texttable()
    ttab.set_precision(1)
    h = [[x for x in df]]
    h.extend([x for x in df.to_records(index=False)])
    if align:
        colWidths = [max(len(x), len(".. class:: {}".format(y))) for x,y in izip(df.columns, align)]
    else:
        colWidths = [len(x) for x in df.columns]
    for row in h:
        for i in range(0, len(row)):
            if type(row[i]) == str:
                colWidths[i] = max([len(str(x)) for x in row[i].split("\n")] + [colWidths[i]])
            colWidths[i] = max(len(str(row[i])), colWidths[i])
    table_data = []
    if align:
        for row in h:
            table_row = []
            i = 0
            for col, aln in izip(row, align):
                table_row.append(".. class:: {}".format(aln) + " " * colWidths[i] + "{}".format(col))
                i = i + 1
            table_data.append(table_row)
    else:
        table_data = h
    ttab.add_rows(table_data)
    ttab.set_cols_width(colWidths)
    # Note: this does not affect the final pdf output
    ttab.set_cols_align(["r"] * len(colWidths))
    return ttab
コード例 #48
0
ファイル: core.py プロジェクト: MrBadge/CAM-interpreter
    def print_steps(self, show_result=True):
        def max_len_of_list_of_str(s):
            return max(len(line) for line in str(s).split('\n'))

        def autodetect_width(d):
            widths = [0] * len(d[0])
            for line in d:
                for _i in range(len(line)):
                    widths[_i] = max(widths[_i],
                                     max_len_of_list_of_str(line[_i]))
            return widths

        if self.save_history:
            if self.errors:
                self.history = self.history[:-1]
            t = Texttable()
            header = ['№', 'Term', 'Code'
                      ] if self.parallel else ['№', 'Term', 'Code', 'Stack']
            data = [header] + [[repr(i) for i in item][:-1]
                               if self.parallel else [repr(i) for i in item]
                               for item in self.history]
            t.add_rows(data)
            t.set_cols_align(['l'] + ['r'] * (len(header) - 1))
            t.set_cols_valign(['m'] + ['m'] * (len(header) - 1))
            t.set_cols_width(autodetect_width(data))
            print t.draw()
        else:
            if not self.errors:
                print ' Steps: %10s' % self.iteration
                if show_result:
                    print 'Result: %10s' % repr(self.term)
コード例 #49
0
def showJson(data):
    table = Texttable()
    table.set_deco(Texttable.BORDER)
    table.set_cols_align([
        "l", "l", "l", "l", "l", "l", "l", "l", "l", "l", "l", "l", "l", "l",
        "l"
    ])  # require three  columns
    table.set_cols_valign([
        "m", "m", "m", "m", "m", "m", "m", "m", "m", "m", "m", "m", "m", "m",
        "m"
    ])
    table.set_cols_width(
        [15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15])

    print(data)
    for i in range(len(data)):
        l = {}
        # print(type(l))
        for j in data[i]:
            #print((data[i][j]))
            #print(data[i][j])
            l[j] = data[i][j]
            #print(j, data[i][j])
        print(l.values())
        table.add_rows([l, l.values()])
    print(table.draw() + "\n")
コード例 #50
0
ファイル: ascii.py プロジェクト: erinix/cli
    def format_table(tab, conv2ascii=False):
        def _try_conv2ascii(s):
            return ascii(s) if not _is_ascii(s) and isinstance(s, str) else s

        max_width = get_terminal_size()[1]
        table = Texttable(max_width=max_width)
        table.set_deco(0)
        table.header([i.label for i in tab.columns])

        widths = []
        ideal_widths = []
        number_columns = len(tab.columns)
        remaining_space = max_width
        # set maximum column width based on the amount of terminal space minus the 3 pixel borders
        max_col_width = (remaining_space - number_columns * 3) / number_columns
        for i in range(0, number_columns):
            current_width = len(tab.columns[i].label)
            tab_cols_acc = tab.columns[i].accessor
            if len(tab.data) > 0:
                max_row_width = max(
                        [len(str(resolve_cell(row, tab_cols_acc))) for row in tab.data ]
                        )
                ideal_widths.insert(i, max_row_width)
                current_width = max_row_width if max_row_width > current_width else current_width
            if current_width < max_col_width:
                widths.insert(i, current_width)
                # reclaim space not used
                remaining_columns = number_columns - i - 1
                remaining_space = remaining_space - current_width - 3
                if remaining_columns != 0:
                    max_col_width = (remaining_space - remaining_columns * 3)/ remaining_columns
            else:
                widths.insert(i, max_col_width)
                remaining_space = remaining_space - max_col_width - 3
        if remaining_space > 0 and len(ideal_widths) > 0:
            for i in range(0, number_columns):
                if remaining_space == 0:
                    break
                if ideal_widths[i] > widths[i]:
                    needed_space = ideal_widths[i] - widths[i]
                    if needed_space <= remaining_space:
                        widths[i] = ideal_widths[i]
                        remaining_space = remaining_space - needed_space
                    elif needed_space > remaining_space:
                        widths[i] = widths[i] + remaining_space
                        remaining_space = 0
        table.set_cols_width(widths)

        table.set_cols_dtype(['t'] * len(tab.columns))
        if conv2ascii:
            table.add_rows([[AsciiOutputFormatter.format_value(
                _try_conv2ascii(resolve_cell(row, i.accessor)), i.vt) for i in tab.columns] for row in tab.data], False)
        else:
            table.add_rows([[AsciiOutputFormatter.format_value(
                resolve_cell(row, i.accessor), i.vt) for i in tab.columns] for row in tab.data], False)
        return table
コード例 #51
0
ファイル: org_repo.py プロジェクト: DimitriSCOLE/uforge-cli
        def do_list(self, args):
                try:
                        doParser = self.arg_list()
                        doArgs = doParser.parse_args(shlex.split(args))

                        org = org_utils.org_get(self.api, doArgs.org)
                        allRepo = self.api.Orgs(org.dbId).Repositories.Getall()

                        if allRepo is None:
                                printer.out("No repositories found in [" + org.name + "].")
                                return 0

                        if doArgs.sort is not None:
                                if doArgs.sort.lower() == "name":
                                        printer.out("Repository list ordered by [name] :")
                                        allRepo = order_list_object_by(allRepo.repositories.repository, "name")
                                elif doArgs.sort.lower() == "id":
                                        printer.out("Repository list ordered by [id] :")
                                        allRepo = sorted(allRepo.repositories.repository, key=lambda x: getattr(x, "dbId"), reverse=False)
                                elif doArgs.sort.lower() == "url":
                                        printer.out("Repository list ordered by [url] :")
                                        allRepo = order_list_object_by(allRepo.repositories.repository, "url")
                                elif doArgs.sort.lower() == "type":
                                        printer.out("Repository list ordered by [type] :")
                                        allRepo = order_list_object_by(allRepo.repositories.repository, "packagingType")
                                else:
                                        printer.out("Sorting parameter filled don't exist.", printer.WARNING)
                                        printer.out("Repository list :")
                                        allRepo = sorted(allRepo.repositories.repository, key=lambda x: getattr(x, "dbId"), reverse=False)
                        else:
                                printer.out("Repository list :")
                                allRepo = sorted(allRepo.repositories.repository, key=lambda x: getattr(x, "dbId"), reverse=False)

                        table = Texttable(200)
                        table.set_cols_align(["c", "c", "l", "l", "c"])
                        table.set_cols_width([5,5,30,80,8])
                        table.header(["Id", "Off. Supported", "Name", "URL", "Type"])

                        for item in allRepo:
                                if item.officiallySupported:
                                        officiallySupported = "X"
                                else:
                                        officiallySupported = ""
                                table.add_row([item.dbId, officiallySupported, item.name, item.url, item.packagingType])

                        print table.draw() + "\n"

                        printer.out("Found " + str(len(allRepo)) + " repositories.")

                        return 0

                except ArgumentParserError as e:
                        printer.out("In Arguments: "+str(e), printer.ERROR)
                        self.help_list()
                except Exception as e:
                        return handle_uforge_exception(e)
コード例 #52
0
ファイル: metrics.py プロジェクト: ParaToolsInc/taucmdr
 def _draw_table(self, targ, metric, rows):
     parts = [util.hline("%s Metrics on Target '%s'" % (metric, targ['name']), 'cyan')]
     table = Texttable(logger.LINE_WIDTH)
     table.set_cols_align(['r', 'l'])
     name_width = max([len(row[0]) for row in rows])
     table.set_cols_width([name_width+1, logger.LINE_WIDTH-name_width-4])
     table.set_deco(Texttable.HEADER | Texttable.VLINES)
     table.add_rows(rows)
     parts.extend([table.draw(), ''])
     return parts
コード例 #53
0
ファイル: util.py プロジェクト: m0rcq/zato
def dump_stacks(*ignored):
    pid = os.getpid()

    table = Texttable()
    table.set_cols_width((30, 90))
    table.set_cols_dtype(['t', 't'])

    rows = [['Proc:Thread/Greenlet', 'Traceback']]

    rows.extend(sorted(get_threads_traceback(pid).items()))
    rows.extend(sorted(get_greenlets_traceback(pid).items()))

    table.add_rows(rows)
    logger.info('\n' + table.draw())
コード例 #54
0
def print_boards_for_member_texttable(member):
  table = Texttable()
  boards_with_membership_info_sorted = sorted(member["boards_with_membership_info"], key = lambda b :(-(b["board_readable_to_user"]), b["name"]))
  table.header(["readable?", "Name", "URL", "member type", "board unconfirmed", "board deactivated"])
  table.set_cols_width([10, 30, 30, 10, 11, 11])
  for board_with_membership_info in boards_with_membership_info_sorted:
    table.add_row([str(board_with_membership_info["board_readable_to_user"]),
                  board_with_membership_info["name"],
                  board_with_membership_info["shortUrl"],
                  board_with_membership_info["board_member_type"],
                  str(board_with_membership_info["board_unconfirmed"]),
                  str(board_with_membership_info["board_deactivated"])])

  print table.draw()
コード例 #55
0
def format_table(table, titles, widths):
    res = [titles]
    for row in table:
        res.append([join_if_list(row[title]) for title in titles])

    if Texttable:
        table = Texttable()
        table.set_cols_dtype(['t'] * len(titles))
        table.set_cols_width(widths)
        table.add_rows(res)
        return table.draw()
    else:
        res = ['\t'.join(l) for l in res]
        return '\n'.join(res)
コード例 #56
0
def print_members_list_texttable(member_list):
  table = Texttable()
  table.header(["org member type", "full name", "username", "org deactivated", "org unconfirmed", "# boards readable", "# boards deactivated"])
  table.set_cols_width([10, 30, 30, 15, 11, 10, 11])

  for m in member_list:
    table.add_row([m["org_member_type"], 
                 m["fullName"], 
                 m["username"], 
                 str(m["org_deactivated"]), 
                 str(m["org_unconfirmed"]), 
                 len([b for b in m["boards_with_membership_info"] if b["board_readable_to_user"]]),
                 len([b for b in m["boards_with_membership_info"] if b["board_deactivated"]])])

  print table.draw()
コード例 #57
0
ファイル: tests.py プロジェクト: ah73/pingSweep.py
def test_set_cols_width():
    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_width([10, 10])
    table.add_rows([
        ["key", "value"],
        [1,     "a"],
        [2,     "b"],
    ])
    assert clean(table.draw()) == dedent('''\
           key         value
        =======================
        1            a
        2            b
    ''')
コード例 #58
0
    def describe(self, environment):
        description = "\nEnvironment: " + environment.get_name() + '\n'

        table = Texttable()
        table.set_cols_width([10, 50, 20, 15])
        rows = [["Location", "DNS", "Services", "ID"]]

        for location in environment.get_locations():

            for node in location.get_nodes():
                rows.append([location.get_name(), node.attributes()['dns_name'], node.attributes()['services'], node.attributes()['id']])

        table.add_rows(rows)
        description += table.draw()

        return description
コード例 #59
0
ファイル: actions.py プロジェクト: khilnani/gists.cli
def help ():
  log.debug ("Help command.")

  print 'Gists.CLI'
  print ''
  print textwrap.fill('An easy to use CLI to manage your GitHub Gists. Create, edit, append, view, search and backup your Gists.', defaults.max_width)
  print ''
  print 'Author: Nik Khilnani - https://github.com/khilnani/gists.cli'
  print ''
  print "Note - GIST_ID can be a Gist ID or Index ID (of the Gist in the List view)."
  print "Index is 1 based and must be in the format '#N', '%N' , '.N' or ':N'."

  table = Texttable(max_width=defaults.max_width)
  table.set_deco(Texttable.HEADER | Texttable.HLINES)
  table.set_cols_align(["l", "l", "l"])
  table.set_cols_width([8, 45, 37])

  table.header( ["Action","Usage", "Description"] )
  
  table.add_row( _getHelpTableRow("Help", help='Display the help documentation') )

  table.add_row( _getHelpTableRow("Token", 'TOKEN', help='Save your Github  OAuth Token. Will be prefeered over ~/.git-credentials to avoid user/password prompts. Saves to ~/.gists') )

  table.add_row( _getHelpTableRow("List", help='Lists your public and private Gists.') )

  table.add_row( _getHelpTableRow("View", "GIST_ID|'.'INDEX [FILE]", help="Displays contents of a Gist on screen. To view a specific file, specify [FILE]. Instead of the Gist ID, the (1 based) index of the Gist in the List screen can be used. eg. %1, .1, :1 or '#1'") )

  table.add_row( _getHelpTableRow("Download", "GIST_ID|'.'INDEX PATH [FILE]", help="Get or Download the files in a Gist to (1) Current Directory, or (2) Directory with Gist ID as its name. To download a specific file, specify [FILE]. Instead of the Gist ID, the (1 based) index of the Gist in the List screen can be used. eg. %1, .1, :1 or '#1'") )

  table.add_row( _getHelpTableRow("New", '[PUBLIC_BOOL] [DESCRIPTION] [CONTENT|FILE]', help='Create a new Gist. Will prompt for Public/Private, Description etc. if not provided as arguments. Default is Private.') )

  table.add_row( _getHelpTableRow("Append", 'GIST_ID [DESCRIPTION] CONTENT|FILE', help="Will append to each file in a Gist. Use '?' to keep current value.") )

  table.add_row( _getHelpTableRow("Update", 'GIST_ID [DESCRIPTION] CONTENT|FILE', help="Update the content of a Gist if a file name match is found. If not, a new file is added. Use '?' to keep current value.") )

  table.add_row( _getHelpTableRow("Delete", help='Delete a Gist.') )

  table.add_row( _getHelpTableRow("Backup", help='Backup or Export all Gists. NOT IMPLEMENTED') )

  table.add_row( _getHelpTableRow("Search", help='Text search the content of your Gists. NOT IMPLEMENTED') )

  table.add_row( _getHelpTableRow("Supress", help='Supress prompts. Defaults will be used.') )

  table.add_row( _getHelpTableRow("Debug", help='Output Debug info. NOTE - Reveals sesnitive info such as OAuth tokens.') )

  print table.draw()