Exemple #1
0
def weekly_report():
    print("Generate report!")
    start = input("Enter start date(yyyy-mm-dd): ")
    end = input("Enter end date(yyyy-mm-dd): ")

    sql_select_Query = "select b.isbn, ib.issue_date, count(*) as number_of_copies, datediff(ib.book_due_date, ib.issue_date) as no_of_days, b.author, b.title, lm.ssn, lm.name from issue_book as ib, library_member as lm, book as b where ib.issue_date between '{}' and '{}' and b.isbn=ib.isbn and lm.ssn=ib.member_ssn group by b.isbn".format(
        start, end)
    cursor = mydb.cursor()
    cursor.execute(sql_select_Query)
    records = cursor.fetchall()
    index = 1

    table = Texttable()
    table.set_max_width(max_width=110)

    table.add_row([
        'Index', 'Book Title', 'Book Author', 'Book ISBN', 'Member Name',
        'Member SSN', 'Issue Date', 'No of Copies', 'Loan Days'
    ])
    for row in records:
        table.add_row([
            index, row[5], row[4], row[0], row[7], row[6], row[1], row[2],
            row[3]
        ])
        index += 1

    print("Report generated to report.txt file!")
    file = open("report.txt", "w+", encoding='utf-8')

    file.write("Weekly Report!\n\n")

    file.write(table.draw())

    file.close()
Exemple #2
0
def test_chaining():
    table = Texttable()
    table.reset()
    table.set_max_width(50)
    table.set_chars(list('-|+='))
    table.set_deco(Texttable.BORDER)
    table.set_header_align(list('lll'))
    table.set_cols_align(list('lll'))
    table.set_cols_valign(list('mmm'))
    table.set_cols_dtype(list('ttt'))
    table.set_cols_width([3, 3, 3])
    table.set_precision(3)
    table.header(list('abc'))
    table.add_row(list('def'))
    table.add_rows([list('ghi')], False)
    s1 = table.draw()
    s2 = (Texttable()
          .reset()
          .set_max_width(50)
          .set_chars(list('-|+='))
          .set_deco(Texttable.BORDER)
          .set_header_align(list('lll'))
          .set_cols_align(list('lll'))
          .set_cols_valign(list('mmm'))
          .set_cols_dtype(list('ttt'))
          .set_cols_width([3, 3, 3])
          .set_precision(3)
          .header(list('abc'))
          .add_row(list('def'))
          .add_rows([list('ghi')], False)
          .draw())
    assert s1 == s2
Exemple #3
0
def print_warehouse_rules(line, user_ns):
    warehouse = eval(line, user_ns)
    result = warehouse_rules(warehouse)

    if not result:
        return

    locations = list(result.values())[0].keys()

    attrs = []
    attrs.append([''] + [format_location(location) for location in locations])

    for route, locations in result.items():
        row = [format_route(route, warehouse)]
        attrs.append(row)
        for location, rules in locations.items():
            row.append('\n\n'.join(map(format_rule, rules)))

    table = Texttable()

    table.set_deco(Texttable.HEADER | Texttable.VLINES | Texttable.HLINES)
    table.set_max_width(180)

    table.add_rows(attrs)

    print(table.draw())
Exemple #4
0
    def get_table(self, width: int = 120):
        table = Texttable()
        table.set_deco(Texttable.HEADER | Texttable.HLINES)
        table.set_max_width(width)

        header = [
            'Property', 'Description', 'Type', 'Dist.', 'Mean', 'Sigma',
            'Offset', 'Truth'
        ]
        table.set_cols_dtype(['t', 't', 't', 't', 'a', 'a', 'a', 'a'])
        table.set_header_align(['l', 'l', 'l', 'l', 'l', 'l', 'l', 'l'])

        rows = [header]
        for name in self.design_properties:
            design_property = self.design_properties[name]
            row = [
                design_property.name, design_property.description,
                design_property.property_type, design_property.distribution,
                design_property.mean, design_property.sigma,
                design_property.get_offset(),
                self.true_properties[design_property.name].get_value()
            ]
            rows.append(row)

        table.add_rows(rows)
        return table.draw()
Exemple #5
0
def ner_confusion_matrix(golden, pred, suffix=False):
    labels = [
        'address', 'book', 'company', 'game', 'government', 'movie', 'name',
        'organization', 'position', 'scene', 'O'
    ]
    true_entities = set(get_entities(golden, suffix))
    pred_entities = set(get_entities(pred, suffix))
    true_span2type = {(i, j): k for k, i, j in true_entities}
    pred_span2type = {(i, j): k for k, i, j in pred_entities}

    add_span = set()
    pred_label = []
    true_label = []
    # 根据span判断pred和golden的对应预测标签,如果span在golden中,但是没在pred中,那么认为pred为O
    for span, label in true_span2type.items():
        true_label.append(label)
        pred_label.append(pred_span2type.get(span, 'O'))
        add_span.add(span)
    # span在pred中没在gold中,那么认为gold为O
    for span, label in pred_span2type.items():
        if span in add_span:
            continue
        pred_label.append(label)
        true_label.append(true_span2type.get(span, 'O'))
    cf_matrix = confusion_matrix(true_label, pred_label, labels=labels)
    table = Texttable()
    table.add_row([" "] + [i[:4] for i in labels])
    table.set_max_width(2000)
    for idx, r in enumerate(cf_matrix):
        table.add_row([labels[idx][:4]] + [str(i) for i in cf_matrix[idx]])
    return table.draw()
Exemple #6
0
	def __printTable(self, header, rows):
		table = Texttable()
		col, line = os.get_terminal_size()
		table.set_max_width(col)
		table.header(header)
		table.add_rows([rows], header = False)
		return table.draw()
Exemple #7
0
def get_two_column_table_head():
    table = Texttable()
    table.set_cols_align(["l", "l"])
    table.set_cols_valign(["t", "t"])
    table.set_deco(Texttable.HEADER | Texttable.VLINES | Texttable.BORDER)
    table.set_max_width(0)
    return table
def get_text_table(nbColumn):
    result = Texttable()
    result.set_max_width(get_console_window_width())
    result.set_cols_align(['c'] * nbColumn)
    result.set_cols_valign(['m'] * nbColumn)
    result.set_cols_dtype(['t'] * nbColumn)
    return result
def show_json_table(header, data, att, mul=False):
    tb = Texttable()
    list = getJSONArray(data, att)
    tb.add_rows(list)
    tb.header(header)
    tb.set_max_width(220)
    print(tb.draw())
    def _generate_table_report_adv(self,
                                   results,
                                   show_mem=True,
                                   show_inside_server=True):

        tbl_report = "=" * 52 + "\n"

        table = Texttable()
        table.set_deco(Texttable.HEADER)

        header_names = ["size", "samples", "iters", "min", "avg", "max"]
        header_types = ["t", "i", "i", "f", "f", "f"]
        col_allign = ["l", "r", "r", "r", "r", "r"]

        if show_mem:
            header_names.extend(["used (MB)", "total (MB)"])
            header_types.extend(["f", "f"])
            col_allign.extend(["r", "r"])

        if show_inside_server:
            header_names.extend(["prediction"])
            header_types.extend(["f"])
            col_allign.extend(["r"])

        table.set_cols_dtype(header_types)
        table.set_cols_align(col_allign)

        try:
            terminal_size = shutil.get_terminal_size()
            table.set_max_width(terminal_size.columns)
        except Exception as e:
            pass

        rows = [header_names]

        for res in results:
            row = [res.name, res.samples, res.iterations]
            d = res.stats_obj.dict_report(CMRunTests.REPORT_NAME)
            row.extend([d["min"], d["avg"], d["max"]])
            server_stats = json.loads(
                res.server_stats) if res.server_stats else None

            if show_mem:
                if server_stats and "mem_info" in server_stats:
                    mem_info = server_stats["mem_info"]
                    row.extend([mem_info["predictor_rss"], mem_info["total"]])
                else:
                    row.extend([-9999, -9999])
                rows.append(row)

            if show_inside_server and server_stats:
                time_info = server_stats["time_info"]
                row.extend([
                    time_info["run_predictor_total"]["avg"],
                ])

        table.add_rows(rows)
        tbl_report = table.draw()
        return tbl_report
Exemple #11
0
def print_db_table(data_frame):
    tb = Texttable()
    tb.header(data_frame.columns.array)
    tb.set_max_width(0)
    # text * cols
    tb.set_cols_dtype(['t'] * data_frame.shape[1])
    tb.add_rows(data_frame.to_numpy(), header=False)
    logger.info(tb.draw())
Exemple #12
0
def createTable(headers, rows):
    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_precision(2)
    table.set_max_width(32)
    table.header(headers)
    for row in rows:
        table.add_row(row)
    return table
Exemple #13
0
    def generate_table(self, border=True, short=True):
        """Generate a Textable string with the report.

        Args:
            border (bool, optional): Border around the table. Defaults to True.
            short (bool, optional): Return only 10 rows/values. Defaults to False.
            Only for multi tables.
        """

        table_final = ""
        table_obj = Texttable()
        table_obj.set_max_width(80)
        table_count = 0

        for key in self.data.keys():

            if table_count > 0 and self.table_type == 'multi':
                table_final += "\n\n"

            if self.table_type == 'single':
                data_value = self.data[key]
                table_obj.add_row([key, data_value])
            else:
                # Second round, initialize another instance
                if table_count > 0:
                    table_obj = Texttable()
                    table_obj.set_max_width(80)

                table_obj.header([key])

                value_count = 0
                for value in self.data[key]:
                    if short is True and value_count >= 10:
                        table_obj.add_row(['[...]'])
                        break
                    # Print just 80 chars, improve readability
                    short_value = value[0:76]
                    table_obj.add_row([short_value])
                    value_count += 1

            if border is False:
                table_obj.set_deco(Texttable.HEADER | Texttable.VLINES)
            else:
                table_obj.set_deco(Texttable.BORDER | Texttable.HEADER | Texttable.VLINES)

            # Print many tables for multi type
            if self.table_type == 'multi':
                table_final += table_obj.draw()

            table_count += 1

        # Print just one table for single type
        if self.table_type == 'single':
            table_final += table_obj.draw()

        # short=False
        return table_final
Exemple #14
0
def show_lcs_table(memo_table):
    table = Texttable()
    table.set_cols_align(["c", "c"])
    table.set_cols_valign(["t", "t"])
    table.set_deco(Texttable.VLINES | Texttable.BORDER)
    table.set_max_width(0)
    for memo_line in memo_table:
        table.add_row(memo_line)
    print(table.draw())
def show_table(header, data, mutiline=False):
    tb = Texttable()
    if mutiline:
        tb.add_rows(data)
    else:
        tb.add_row(data)
    tb.header(header)
    tb.set_max_width(150)
    print(tb.draw())
Exemple #16
0
def printTextTable(alignment, header, data):
	tt = Texttable(0)
	tt.set_max_width(0)
	tt.set_deco(Texttable.HEADER)
	tt.set_cols_align(alignment)
	tt.header(header)
	tt.add_rows(data, header=False)
	print()
	print(tt.draw())
Exemple #17
0
def print_model_attrs(attrs):
    table = Texttable()

    table.set_deco(Texttable.HEADER | Texttable.VLINES | Texttable.HLINES)
    table.set_max_width(180)

    table.add_rows(attrs)

    print((table.draw()))
def utilization(obj, targets):
    # This plugin only works for SlurmBackend
    backend_cls = Backend.from_config(obj)
    if not issubclass(backend_cls, SlurmBackend):
        raise GWFError('Utilization plugin only works for Slurm backend!')

    graph = Graph.from_config(obj)

    # If user specified list of targets, only report utilization for these.
    # Otherwise, report utilization for all targets.
    matches = graph.targets.values()
    if targets:
        matches = filter_names(matches, targets)

    with backend_cls() as backend:
        job_ids = []
        for target in matches:
            try:
                job_ids.append(backend.get_job_id(target))
            except KeyError:
                pass

    rows = [[
        'Target', 'Cores', 'Walltime Alloc', 'Walltime Used', 'Memory Alloc',
        'Memory Used', 'CPU Time Alloc', 'CPU Time Used', 'Walltime %',
        'Memory %', 'CPU %'
    ]]
    for job in get_jobs(job_ids):
        rows.append([
            job.name, job.allocated_cores,
            pretty_time(job.allocated_time_per_core),
            pretty_time(job.used_walltime),
            pretty_size(job.allocated_memory),
            pretty_size(job.used_memory),
            pretty_time(job.allocated_cpu_time),
            pretty_time(job.used_cpu_time),
            str(format(job.walltime_utilization, '.1f')),
            format(job.memory_utilization, '.1f'),
            format(job.cpu_utilization, '.1f')
        ])

    table = Texttable()

    table.set_deco(Texttable.BORDER | Texttable.HEADER | Texttable.VLINES)

    ncols = len(rows[0])

    table.set_max_width(0)
    table.set_header_align('l' * ncols)
    table.set_cols_align(['l'] + (ncols - 1) * ['r'])
    table.set_cols_dtype(['t'] * ncols)

    table.add_rows(rows)

    print(table.draw())
Exemple #19
0
def table_setup(model, width):
    if not isinstance(model, Model):
        raise TypeError('Error in model_table. ' +
                        ': model argument must be a Model object')

    # show table of modifiers

    table = Texttable()
    table.set_deco(Texttable.HEADER | Texttable.HLINES)
    table.set_max_width(width)
    return table
Exemple #20
0
 def create_table(streams):
     '''Creates a terminal-friendly table from streams.'''
     table = Texttable()
     table.set_deco(Texttable.HEADER | Texttable.VLINES)
     table.set_header_align(['l', 'l', 'l'])
     table.set_max_width(0)
     data = [['Streamer', 'Title', 'Viewers']]
     data.extend(
         list(
             map(
                 lambda stream:
                 [stream.streamer, stream.name, stream.viewers], streams)))
     table.add_rows(data)
     return table.draw()
Exemple #21
0
def short(args) -> None:
    table = Texttable()
    output = main(args)
    pran = list(output.values())[0]['PRAN Number']
    date = list(output.values())[0]['Date']
    header = [f"NPS {pran} ({date})", "Percentage", "Units", "NAV", "Value"]
    table.header(header)
    table.set_cols_dtype(['t', 't', 't', 't', 't'])
    table.set_max_width(0)
    for scheme, scheme_data in output.items():
        row = [scheme,
               scheme_data['Percentage'],
               scheme_data['Total Units'].replace(',', ''),
               scheme_data['NAV (Rs.)'].replace(',', ''),
               scheme_data['Amount (Rs.)'].replace(',', '')]
        table.add_row(row)
    print(table.draw())
Exemple #22
0
    def validation_test(self):
        # TODO: create infrastructure to easily add more checks

        cmd_list = sys.argv
        cmd_list[1] = ArgumentsOptions.SCORE

        if ArgumentsOptions.OUTPUT not in cmd_list:
            cmd_list.extend([
                ArgumentsOptions.OUTPUT,
                "placeholder_to_replace_later_during_test_case"
            ])

        test_cases_results = [
            self._basic_batch_prediction_check(),
            self._null_value_imputation_check(),
        ]

        table = Texttable()
        table.set_deco(Texttable.HEADER)

        try:
            terminal_size = shutil.get_terminal_size()
            table.set_max_width(terminal_size.columns)
        except Exception as e:
            pass

        header_names = ["Test case", "Status", "Details"]
        col_types = ["t", "t", "t"]
        col_align = ["l", "l", "l"]

        rows = []
        rows.append(header_names)
        for test_name, test_passed, failure_message in test_cases_results:
            rows.append([
                test_name,
                "PASSED" if test_passed else "FAILED",
                "" if test_passed else failure_message,
            ])

        table.set_cols_dtype(col_types)
        table.set_cols_align(col_align)
        table.add_rows(rows)
        tbl_report = table.draw()
        print("\n\nValidation checks results")
        print(tbl_report)
Exemple #23
0
def test_exceeding_max_width3():
    table = Texttable()
    table.set_max_width(35)
    table.set_deco(Texttable.HEADER)
    table.add_rows([
        ["key", "value"],
        [1, "a"],
        [2, "b"],
        [3, "very long, very long, very long"],
    ])
    assert clean(table.draw()) == dedent('''\
        key               value
        ===================================
        1     a
        2     b
        3     very long, very long, very
              long
    ''')
Exemple #24
0
    def get_locks(self):
        # Setup query
        api_url = f"https://api.masterlockvault.com/v4/product"
        query = api_url + '?' + self._get_cred_param()

        # make query
        response = self._make_query("GET", query, "")
        response = re.search('\[.*\]', response).group(0)
        response = json.loads(response)

        # print locks info
        t = Texttable()
        t.header(["Lock Name", "Product ID"])
        t.set_max_width(0)
        for i in response:
            t.add_row([i['Name'], i['Id']])

        print(t.draw())
Exemple #25
0
def test_exceeding_max_width4():
    table = Texttable()
    table.set_max_width(14)
    table.add_rows([
        ["a", "b"],
        [1, "+"],
        [22, "++++++++"],
    ])
    assert clean(table.draw()) == dedent('''\
        +----+-------+
        | a  |   b   |
        +====+=======+
        | 1  | +     |
        +----+-------+
        | 22 | +++++ |
        |    | +++   |
        +----+-------+
    ''')
Exemple #26
0
def display_books_available_in_lib():
    sql_select_Query = "select * from books_available_in_lib"
    cursor = mydb.cursor()
    cursor.execute(sql_select_Query)
    records = cursor.fetchall()
    index = 1

    table = Texttable()
    table.set_max_width(max_width=120)

    table.add_row([
        'Index', 'ISBN', 'Can be rented flag', 'Total No Copies',
        'No of copies lented', 'Book Description', 'Book Type'
    ])
    for row in records:
        table.add_row([index, row[0], row[1], row[2], row[3], row[4], row[5]])
        index += 1

    print(table.draw())
Exemple #27
0
    def print_paths(self, paths):
        table = Texttable()
        table.set_max_width(400)
        table.set_cols_align(['l' for _ in range(8)])
        table.set_cols_valign(['t' for _ in range(8)])

        table.header([
            'direction', 'goal', 'point_type', 'point_id', 'distance',
            'points', 'scores', 'final_score'
        ])
        for path in paths:
            table.add_row([
                self._point_direction_lookup[path['points'][0]],
                path['goal_type'], path['point_type'], path['point_id'],
                path['distance'], '\n'.join(map(str, path['points'])),
                '\n'.join(map(str, path['scores'])), path['final_score']
            ])

        print(table.draw())
Exemple #28
0
def display_book():
    sql_select_Query = "select * from book"
    cursor = mydb.cursor()
    cursor.execute(sql_select_Query)
    records = cursor.fetchall()
    index = 1

    table = Texttable()
    table.set_max_width(max_width=150)

    table.add_row([
        'Index', 'ISBN', 'Title', 'Author', 'Subject Area', 'Language',
        'Binding Type', 'Edition'
    ])
    for row in records:
        table.add_row(
            [index, row[0], row[1], row[2], row[3], row[4], row[5], row[6]])
        index += 1

    print(table.draw())
Exemple #29
0
    def print(self):
        height_range = reversed(range(-1, self.get_height() + 1))
        width_range = range(-1, self.get_width() + 1)

        table = Texttable()
        table.set_max_width(400)
        table.set_deco(Texttable.BORDER | Texttable.HLINES | Texttable.VLINES)
        table.set_cols_align(['l' for _ in width_range])
        table.set_cols_valign(['t' for _ in width_range])
        for y in height_range:
            row = []
            for x in width_range:
                cell = self._get_cell((x, y))
                row.append("'point': (" + str(x) + "," + str(y) + ")\n" +
                           ("\n".join(
                               "{!r}: {!r},".format(k.name, v.to_string())
                               for k, v in cell.items())))
            table.add_row(row)

        print(table.draw())
Exemple #30
0
def writetab(llargs, fout, kset):
    t = Texttable()
    t.set_max_width(500)
    info = ['dataset', 'al_type', 'knn', 'clustering']
    restricted = ['knn', 'clustering']
    header = []
    format_row = []

    # if show_exp_fd:
    #     header = ["exp_fd"]
    #     format_row.append("t")
    for k in info:
        if k not in ["exp_fd"]:
            header.append(k)
            format_row.append("t")  # text

    header.append('AUC*')
    format_row.append('f')
    t.header(header)
    t.set_cols_dtype(format_row)

    for item, aucx in llargs:
        row = []
        for k in info:
            if item['al_type'] == constants.AL_LP:
                row.append(item[k])
            else:
                if k in restricted:
                    row.append(None)
                else:
                    row.append(item[k])

        row.append(aucx)
        t.add_row(row)

    print("Subset: {}".format(kset))
    print(t.draw())  # print in std_out
    ff = open(fout, 'w')
    print(t.draw(), file=ff)
    print("Subset: {}".format(kset), file=ff)
    ff.close()