Exemple #1
0
    def readjust_scores(self, driver, context, report):
        choices = self._get_ui(driver)

        if False:
            if len(choices) != len(self.choices):
                raise IntegrityException(
                    "wrong number of choices in readjustment.")
            for key, score in self.choices.items():
                if choices[key] != score:
                    raise IntegrityException(
                        "wrong choice score in readjustment.")

        table = Texttable()
        table.set_deco(Texttable.HEADER)
        table.set_cols_dtype(['t', 'a', 'a'])
        table.add_row(['', 'old', 'readjusted'])

        for key, score in list(choices.items()):
            new_score = _readjust_score(context.random, score)
            choices[key] = new_score
            table.add_row([key, score, new_score])

        report(table)

        self._set_ui(driver, choices)
        self.choices = choices

        return True, list()
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
Exemple #3
0
def nilai():
    from texttable import Texttable
    table = Texttable()
    jawab = 'y'
    nama = []
    nilai = []
    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):
        induk = int(nim[i])
        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_dtype(['a', 'i', 'i', 'i', 'i', 'i', 'i'])
        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())
def list_instances():
    table       = Texttable( max_width=0 )

    table.set_deco( Texttable.HEADER )
    table.set_cols_dtype( [ 't', 't', 't', 't', 't', 't', 't', 't' ] )
    table.set_cols_align( [ 'l', 'l', 'l', 'l', 'l', 'l', 'l', 't' ] )

    if not options.no_header:
        ### using add_row, so the headers aren't being centered, for easier grepping
        table.add_row(
            [ '# id', 'Name', 'Type', 'Zone', 'Group', 'State', 'Root', 'Volumes' ] )

    instances = get_instances()
    for i in instances:

        ### XXX there's a bug where you can't get the size of the volumes, it's
        ### always reported as None :(
        volumes = ", ".join( [ ebs.volume_id for ebs in i.block_device_mapping.values()
                                if ebs.delete_on_termination == False ] )

        ### you can use i.region instead of i._placement, but it pretty
        ### prints to RegionInfo:us-east-1. For now, use the private version
        ### XXX EVERY column in this output had better have a non-zero length
        ### or texttable blows up with 'width must be greater than 0' error
        table.add_row( [ i.id, i.tags.get( 'Name', ' ' ), i.instance_type,
                         i._placement , i.groups[0].name, i.state,
                         i.root_device_type, volumes or '-' ] )

        #PP.pprint( i.__dict__ )

    ### table.draw() blows up if there is nothing to print
    if instances or not options.no_header:
        print table.draw()
Exemple #5
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()
    def showResult(self, res):
        full = self.full
        user_id = self.user_id
        user_i_rated = full[full["user_id"] == user_id][[
            'title', 'release_date'
        ]]
        print("")
        print("所查询的用户曾经访问过的电影为:")
        rows = []
        table = Texttable()  # 创建表格并显示
        table.set_deco(Texttable.HEADER)
        table.set_cols_dtype(['t', 'f'])
        table.set_cols_align(["l", "l"])
        rows.append(["电影名称", "发行时间"])
        for row in user_i_rated[user_i_rated['title'] != 'unknown'].fillna(
                0).values:  # Datasets contains "unknown" noises.
            rows.append(row)
        table.add_rows(rows)
        table.set_deco(Texttable.HEADER)
        print(table.draw())

        print("")
        print("个性化推荐系统所推荐的电影为:")
        rows = []
        table = Texttable()  #创建表格并显示
        table.set_deco(Texttable.HEADER)
        table.set_cols_dtype(['t', 'f', 'a'])
        table.set_cols_align(["l", "l", "l"])
        rows.append(["电影名称", "发行时间", "推荐指数"])
        for row in res.fillna(0).values:
            rows.append(row)
        table.add_rows(rows)
        table.set_deco(Texttable.HEADER)
        print(table.draw())
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
Exemple #8
0
def images_to_ascii_table(images):
    """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 images.iteritems():
            out.write(str(host) + "\n")
            t = TextTable()
            t.set_deco(TextTable.HEADER)
            t.set_cols_dtype(['t'] * 5)
            t.set_cols_align(["l"] * 5)
            rows = []
            rows.append(['Repository', 'Tag', 'Id', 'Created', 'Size'])
            for image in values:
                rows.append([
                    image.repository or '<none>',
                    image.tag or '<none>',
                    image.id[:12],
                    time_ago(image.created),
                    human_size(image.size)
                ])
            t.add_rows(rows)
            out.write(t.draw() + "\n\n")
        return out.getvalue()
Exemple #9
0
def print_price_data(data):

    # Current BTC Price
    # --------------------
    print '\n%s' % colorize('CaVirtex Market\n---------------', colors.CYAN)
    

    status_color = colors.GREEN if data['net'] > 0 else colors.RED

    print '\n%s' % colorize('Price', colors.BLUE)
    
    print '\n%s' % colorize('$%.2f CAD/BTC' % data['current_price'], status_color)

    # Latest Trades
    # ----------------
    print '\n%s\n' % colorize('Latest Trades', colors.BLUE)
    
    trades_table = Texttable()
    trades_table.set_deco(Texttable.HEADER)
    trades_table.set_precision(2)
    trades_table.set_cols_dtype(['f', 'f', 'f', 't'])
    trades_table.add_rows(data['latest_trades'])

    print trades_table.draw()
    
    # Investment Returns
    # ---------------------
    print '\n%s' % colorize('Your Investment', colors.BLUE)

    print '\nNet: %s' % colorize('$%.2f CAD' % data['net'], status_color)
    print '\nVOI: %s' % colorize('$%.2f CAD' % data['voi'], status_color)
    print '\nROI: %s' % colorize('%.2f%%' % data['roi'], status_color)
Exemple #10
0
def nilai():

    from texttable import Texttable
    table = Texttable()

    jawab = "y"
    nol = 0
    nama = []
    nim = []
    nilai_tugas = []
    nilai_uts = []
    nilai_uas = []

    while (jawab == "y"):
        nama.append(input("\nMasukan Nama : "))
        nim.append(input("\nMasukan Nim : "))
        nilai_tugas.append(input("\nMasukan Nilai Tugas : "))
        nilai_uts.append(input("\nMasukan Nilai UTS :"))
        nilai_uas.append(input("\nMasukan Nilai UAS :"))
        jawab = input("\nTambah DAta (y/n)? ")
        nol += 1
    for f in range(nol):
        tugas = int(nilai_tugas[f])
        uts = int(nilai_uts[f])
        uas = int(nilai_uas[f])
        akhir = (tugas * 30 / 100) + (uts * 35 / 100) + (uas * 35 / 100)
        table.set_cols_dtype(['t', 't', 't', 't', 't', 't', 't'])
        table.add_rows([['NO', 'Nama', 'NIM', 'Tugas', 'Uts', 'Uas', 'Akhir'],
                        [
                            f + 1, nama[f], nim[f], nilai_tugas[f],
                            nilai_uts[f], nilai_uas[f], akhir
                        ]])
    print(table.draw())
def main(args):
    if args.gevent:
        import gevent.monkey
        gevent.monkey.patch_all()
    if not args.strict:
        args.name = ['*' + name + '*' for name in args.name]
    table = Texttable(args.width)
    table.set_cols_dtype(['t'] * len(args.fields))
    table.set_cols_align([args.align] * len(args.fields))
    if not args.quiet:
        table.add_row([pretify_field(field) for field in args.fields])
    table.set_deco(0)
    instances = []
    for required_name in args.name:
        instances.extend(
            get_instances_by_id_or_name(required_name,
                                        projects=args.projects,
                                        raw=args.raw,
                                        regions=args.regions,
                                        clouds=args.clouds))
    if args.active:
        instances = [
            instance for instance in instances if instance.state == 'running'
        ]
    if not instances:
        sys.exit(1)
    instances.sort(key=lambda instance:
                   [getattr(instance, field) for field in args.sort_by])
    table.add_rows([[getattr(instance, field) for field in args.fields]
                    for instance in instances],
                   header=False)
    print table.draw()
Exemple #12
0
 def do_list(self, args):
         try:                        
                 #call UForge API
                 printer.out("Getting scans for ["+self.login+"] ...")
                 myScannedInstances = self.api.Users(self.login).Scannedinstances.Get(None, Includescans="true")
                 if myScannedInstances is None or not hasattr(myScannedInstances, 'get_scannedInstance'):
                         printer.out("No scans available")
                         return
                 else:
                         table = Texttable(800)
                         table.set_cols_dtype(["t","t","t","t"])
                         table.header(["Id", "Name", "Status", "Distribution"])
                         myScannedInstances = generics_utils.oder_list_object_by(myScannedInstances.get_scannedInstance(), "name")
                         for myScannedInstance in myScannedInstances:
                                     table.add_row([myScannedInstance.dbId, myScannedInstance.name, "", myScannedInstance.distribution.name + " "+ myScannedInstance.distribution.version + " " + myScannedInstance.distribution.arch])
                                     scans = generics_utils.oder_list_object_by(myScannedInstance.get_scans().get_scan(), "name")
                                     for scan in scans:
                                                 if (scan.status.complete and not scan.status.error and not scan.status.cancelled):
                                                         status = "Done"
                                                 elif(not scan.status.complete and not scan.status.error and not scan.status.cancelled):
                                                         status = str(scan.status.percentage)+"%"
                                                 else:
                                                         status = "Error"
                                                 table.add_row([scan.dbId, "\t"+scan.name, status, "" ])
                                                 
                         print table.draw() + "\n"
                         printer.out("Found "+str(len(myScannedInstances))+" scans")
         except ArgumentParserError as e:
                 printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
                 self.help_list()
         except Exception as e:        
                 return generics_utils.handle_uforge_exception(e)
Exemple #13
0
    def to_string(self):
        from texttable import Texttable

        table = Texttable()
        header = [""]
        shapes = {k: [k] for k in self._targets.keys()}

        for step in self._steps[1:]:
            header.append(step)
            for target in self._targets.keys():
                v = str(self._targets[target].get(step, "n/a"))
                shapes[target].append(v)

        table.header(header)

        table.set_cols_dtype(["t"] * len(header))
        table.set_cols_align(["l"] * len(header))
        table.set_deco(Texttable.HEADER)

        for target in self._targets.keys():
            table.add_row(shapes[target])

        msg = table.draw()

        msg = self._add_caption(msg, "-", "Table: Data layout transformation.")
        return msg
Exemple #14
0
    def __init__(self):
        '''Shows a table Integrate Numerically the Student’s t-distribution
        'probability density 'function ( t-distribution pdf) using Simpson’s'
        'rule. The total' 'probability' is the area of the function (the integral)'
        'from -t to t. The total probability is p'

        '''
        calculate = Calculate('history.txt')
        values = calculate.get_total_probability_p()
        table = Texttable()
        table.set_cols_align(["l", "c", "c"])
        table.set_cols_valign(["m", "m", "m"])
        table.set_cols_dtype(['t', 'i', 'f'])
        table.set_precision(5)
        label = [
            color(bcolors.GREEN,"Test"),'',
            color(bcolors.GREEN,"Expected Values")]
        head = [
            color(bcolors.GREEN,"t"),
            color(bcolors.GREEN,"dof"),
            color(bcolors.GREEN,"p")]
        rows = []
        rows.append(label)
        rows.append(head)
        [rows.append(element) for element in values]
        table.add_rows(rows)
        print(table.draw() + "\n")
Exemple #15
0
 def make_new():
     table = Texttable()
     table.set_deco(Texttable.HEADER)
     table.set_cols_dtype(["t", "t"])
     table.set_cols_align(["l", "l"])
     table.add_row(get_txt(ctx.guild.id, "ws_list_row"))
     return table
Exemple #16
0
    def readjust_scores(self, driver, actual_answers, context: 'TestContext',
                        report) -> Tuple[bool, List]:
        choices = self.choices

        if False:
            if len(choices) != len(self.choices):
                raise IntegrityException(
                    "wrong number of choices in readjustment.")
            for key, score in self.choices.items():
                if choices[key] != score:
                    raise IntegrityException(
                        "wrong choice score in readjustment.")

        table = Texttable()
        table.set_deco(Texttable.HEADER)
        table.set_cols_dtype(['t', 't', 't'])
        table.add_row(['', 'old', 'readjusted'])

        for key, score in list(choices.items()):
            new_score = _readjust_choice_item(context.random, score)
            choices[key] = new_score
            table.add_row([key, '(%f, %f)' % score, '(%f, %f)' % new_score])

        report(table)

        _readjust_ui(context, driver, choices)

        return True, list()
Exemple #17
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')
    def handle(self, *args, **options):
        d = date.today()
        if options['datestring']:
            try:
                d = datetime.strptime(options['datestring'], '%Y-%m-%d').date()
            except ValueError:
                raise CommandError('Invalid date value: {} (use format YYYY-MM-DD)'.format(options['datestring']))

        emails = None
        if options['emails']:
            try:
                emails = options['emails'].split(',')
            except ValueError:
                raise CommandError('Invalid emails value: {} (use comma-separated string)'.format(options['emails']))

        week_start = datetime.combine(d, datetime.min.time()).astimezone(timezone(settings.TIME_ZONE))
        week_end = week_start + timedelta(days=7)
        rfcs = ChangeRequest.objects.filter(planned_start__range=[week_start, week_end]).order_by('planned_start')

        # Construct the HTML / plaintext email content to send.
        context = {
            'start': week_start,
            'object_list': rfcs,
            'domain': Site.objects.get_current().domain,
        }
        html_content = render_to_string('registers/email_cab_rfc_calendar.html', context)

        table = Texttable(max_width=0)
        table.set_cols_dtype(['i', 't', 't', 't', 't', 't', 't', 't'])
        rows = [['Change ref', 'Title', 'Change type', 'Status', 'Requester', 'Endorser', 'Implementer', 'Planned start & end']]
        for rfc in rfcs:
            rows.append(
                [
                    rfc.pk,
                    rfc.title,
                    rfc.get_change_type_display(),
                    rfc.get_status_display(),
                    rfc.requester.get_full_name(),
                    rfc.endorser.get_full_name(),
                    rfc.implementer.get_full_name(),
                    '{}\n{}'.format(rfc.planned_start.strftime('%A, %d-%b-%Y %H:%M'), rfc.planned_end.strftime('%A, %d-%b-%Y %H:%M'))
                ]
            )
        table.add_rows(rows, header=True)
        text_content = table.draw()

        # Email the CAB members group.
        if not Group.objects.filter(name='CAB members').exists():
            raise CommandError('"CAB members" group does not exist.')
        cab = Group.objects.get(name='CAB members')
        subject = 'Weekly change calendar starting {}'.format(week_start.strftime('%A, %d %b %Y'))
        recipients = list(User.objects.filter(groups__in=[cab], is_active=True).values_list('email', flat=True))

        # Optional additional email recipients.
        if emails:
            recipients = recipients + emails

        msg = EmailMultiAlternatives(subject, text_content, settings.NOREPLY_EMAIL, recipients)
        msg.attach_alternative(html_content, 'text/html')
        msg.send()
Exemple #19
0
 def do_list(self, args):
     try:
         #call UForge API
         printer.out("Getting templates for ["+self.login+"] ...")
         appliances = self.api.Users(self.login).Appliances().Getall()
         appliances = appliances.appliances
         if appliances is None or not hasattr(appliances, 'appliance'):
             printer.out("No template")
         else:
             images = self.api.Users(self.login).Images.Get()
             images = images.images
             table = Texttable(800)
             table.set_cols_dtype(["t","t","t","t","t","t","t","t","t","t"])
             table.header(["Id", "Name", "Version", "OS", "Created", "Last modified", "# Imgs", "Updates", "Imp", "Shared"])
             appliances = generics_utils.order_list_object_by(appliances.appliance, "name")
             for appliance in appliances:
                 nbImage=0
                 if images is not None and hasattr(images, 'image'):
                     for image in images.image:
                         if hasattr(image, 'applianceUri') and image.applianceUri == appliance.uri:
                             nbImage+=1
                 table.add_row([appliance.dbId, appliance.name, str(appliance.version), appliance.distributionName+" "+appliance.archName,
                                appliance.created.strftime("%Y-%m-%d %H:%M:%S"), appliance.lastModified.strftime("%Y-%m-%d %H:%M:%S"), nbImage, appliance.nbUpdates, "X" if appliance.imported else "", "X" if appliance.shared else ""])
             print table.draw() + "\n"
             printer.out("Found "+str(len(appliances))+" templates")
         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)
Exemple #20
0
def test_texttable_header():
    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_dtype([
        't',  # text
        'f',  # float (decimal)
        'e',  # float (exponent)
        'i',  # integer
        'a',  # automatic
    ])
    table.set_cols_align(["l", "r", "r", "r", "l"])
    table.add_rows([
        ["text",    "float", "exp", "int", "auto"],
        ["abcd",    "67",    654,   89,    128.001],
        ["efghijk", 67.5434, .654,  89.6,  12800000000000000000000.00023],
        ["lmn",     5e-78,   5e-78, 89.4,  .000000000000128],
        ["opqrstu", .023,    5e+78, 92.,   12800000000000000000000],
    ])
    assert clean(table.draw()) == dedent('''\
         text     float       exp      int     auto
        ==============================================
        abcd      67.000   6.540e+02    89   128.001
        efghijk   67.543   6.540e-01    90   1.280e+22
        lmn        0.000   5.000e-78    89   0.000
        opqrstu    0.023   5.000e+78    92   1.280e+22
    ''')
Exemple #21
0
    def do_info_draw_general(self, info_image):
        table = Texttable(0)
        table.set_cols_dtype(["a", "t"])
        table.set_cols_align(["l", "l"])

        table.add_row(["Name", info_image.name])
        table.add_row(["Format", info_image.targetFormat.name])
        table.add_row(["Id", info_image.dbId])
        table.add_row(["Version", info_image.version])
        table.add_row(["Revision", info_image.revision])
        table.add_row(["Uri", info_image.uri])

        self.do_info_draw_source(info_image.parentUri, table)

        table.add_row(
            ["Created",
             info_image.created.strftime("%Y-%m-%d %H:%M:%S")])
        table.add_row(["Size", size(info_image.fileSize)])
        table.add_row(["Compressed", "Yes" if info_image.compress else "No"])

        if self.is_docker_based(info_image.targetFormat.format.name):
            registring_name = None
            if info_image.status.complete:
                registring_name = info_image.registeringName
            table.add_row(["RegisteringName", registring_name])
            table.add_row(
                ["Entrypoint",
                 info_image.entrypoint.replace("\\", "")])

        self.do_info_draw_generation(info_image, table)

        print table.draw() + "\n"
Exemple #22
0
    def do_list(self, args):
        try:
            #call UForge API
            printer.out("Getting all your bundles ...")
            bundles = self.api.Users(self.login).Mysoftware.Getall()
            bundles = bundles.mySoftwareList.mySoftware
            if bundles is None or len(bundles) == 0:
                printer.out("No bundles available")
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t", "t", "t", "t", "t", "t", "t"])
                table.header([
                    "Id", "Name", "Version", "Description", "Category", "Size",
                    "Imported"
                ])
                bundles = generics_utils.order_list_object_by(bundles, "name")
                for bundle in bundles:
                    category = ""
                    if bundle.category is not None:
                        category = bundle.category.name
                    table.add_row([
                        bundle.dbId, bundle.name, bundle.version,
                        bundle.description, category,
                        size(bundle.size), "X" if bundle.imported else ""
                    ])
                print table.draw() + "\n"
                printer.out("Found " + str(len(bundles)) + " bundles")

            return 0
        except Exception as e:
            return handle_uforge_exception(e)
Exemple #23
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 #24
0
    def showTable(self, userId):
        neighbors_id = [i[1] for i in self.neighbors]
        table = Texttable()
        table.set_deco(Texttable.HEADER)
        table.set_cols_dtype(["t", "t", "t", "t"])
        table.set_cols_align(["l", "l", "l", "l"])
        rows = []
        rows.append([u"movie ID", u"Name", u"genre", u"from userID"])
        nodes = []
        for item in self.recommandList:

            node = []

            fromID = []

            for _, row in self.movies.iterrows():
                if row.movieId == item[1]:
                    movie = [row.movieId, row.title, row.genres]
                    break

            for i in self.ItemUser[item[1]]:
                if i in neighbors_id:
                    fromID.append(int(i))
            movie.append(fromID)
            rows.append(movie)

            with open('neighbour.txt', 'ab') as f:
                for first in fromID:
                    temp = str(userId) + ',' + str(first) + '\n'
                    f.write(temp)

        table.add_rows(rows)
        print(table.draw())
Exemple #25
0
def SearchCust(x, cur, con):
    try:
        cur.execute(
            "SELECT * FROM CUSTOMER WHERE fname LIKE %s OR lname LIKE %s",
            ("%" + x + "%", "%" + x + "%"))
        table = Texttable()
        table.header(
            ["Cust ID", "Fname", "Lname", "POI Type", "POI Number", "Contact"])
        table.set_cols_dtype(["i", "t", "t", "t", "t", "t"])
        custs = []
        for r in cur:
            custs.append(r)
        for row in custs:
            cur.execute("SELECT phone FROM CONTACT WHERE cust_id=%s",
                        (row['cust_id']))
            contacts = ""
            for ph in cur:
                contacts += ph['phone'] + '\n'
            table.add_row([
                row['cust_id'], row['fname'], row['lname'], row['poi_type'],
                row['poi_number'], contacts
            ])
        print(table.draw())
    except Exception as e:
        con.rollback()
        print("Failed to retreive values.")
        print(">>>>>>>>>>>>>", e)
Exemple #26
0
def print_results(missions: Dict[Mission, Cabin]) -> None:
    """
    Prints the result of mission assignments
    """
    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_dtype(["t", "t", "i", "t", "f", "f"])
    table.add_rows([[
        "Faction",
        "Name",
        "Cabin Class",
        "Cabin Quality",
        "Algorithm Score",
        "Reward",
    ]])

    for mission, cabin in missions.items():
        table.add_row([
            mission.faction,
            mission.name,
            cabin.cclass,
            cabin.quality,
            cabin.fit_passengers(mission.min_quality, mission.passenger_count),
            mission.reward,
        ])

    print(table.draw())
Exemple #27
0
def process(health, armor, dodge, defense):
    weights = {
        'hitpoint': 1.,
        'armor': one_armor(health, armor, dodge, defense),
        'stamina': one_stamina(),
        'agility': one_agility(health, armor, dodge, defense),
        'dodge': one_dodge(health, armor, dodge, defense),
        'defense': one_defense(health, armor, dodge, defense)
    }

    status = Texttable()
    status.header(['health', 'armor', 'dodge', 'defense'])
    status.set_cols_align(['r' for i in range(4)])
    status.add_row(['%d' % health, '%d' % armor,
                    '%.2f%%' % (dodge * 100.), '%d' % defense])
    print(status.draw())

    table = Texttable()
    dims = ['armor', 'stamina', 'agility', 'dodge', 'defense']
    table.header([''] + dims)
    table.set_cols_dtype(['t' for i in range(len(dims) + 1)])
    table.set_cols_align(['r' for i in range(len(dims) + 1)])
    for att in ['hitpoint'] + dims:
        row = [att]
        for col in dims:
            try:
                row.append('%.6f' % (weights[att] / weights[col]))
            except ZeroDivisionError:
                row.append('inf')
        table.add_row(row)
    print(table.draw())
Exemple #28
0
    def do_info_draw_general(self, info_image):
        table = Texttable(0)
        table.set_cols_dtype(["a", "t"])
        table.set_cols_align(["l", "l"])

        table.add_row(["Name", info_image.name])
        table.add_row(["Format", info_image.targetFormat.name])
        table.add_row(["Id", info_image.dbId])
        table.add_row(["Version", info_image.version])
        table.add_row(["Revision", info_image.revision])
        table.add_row(["Uri", info_image.uri])

        self.do_info_draw_source(info_image.parentUri, table)

        table.add_row(["Created", info_image.created.strftime("%Y-%m-%d %H:%M:%S")])
        table.add_row(["Size", size(info_image.fileSize)])
        table.add_row(["Compressed", "Yes" if info_image.compress else "No"])

        if self.is_docker_based(info_image.targetFormat.format.name):
            registring_name = None
            if info_image.status.complete:
                registring_name = info_image.registeringName
            table.add_row(["RegisteringName",registring_name])
            table.add_row(["Entrypoint", info_image.entrypoint.replace("\\", "")])

        self.do_info_draw_generation(info_image, table)

        print table.draw() + "\n"
Exemple #29
0
def print_deploy_header():
    table = Texttable(200)
    table.set_cols_dtype(["t", "t", "t", "t", "t", "t", "t", "t", "t"])
    table.header(
        ["Deployment name", "Deployment ID", "Cloud provider", "Region", "Hostname", "Source type", "Source ID",
         "Source name", "Status"])
    return table
Exemple #30
0
 def do_list(self, args):
     try:
         # call UForge API
         printer.out("Getting all your accounts ...")
         accounts = self.api.Users(self.login).Accounts.Getall()
         accounts = accounts.credAccounts.credAccount
         if accounts is None or len(accounts) == 0:
             printer.out("No accounts available")
         else:
             table = Texttable(800)
             table.set_cols_dtype(["t", "t", "t", "t"])
             table.header(["Id", "Name", "Type", "Created"])
             accounts = generics_utils.order_list_object_by(
                 accounts, "name")
             for account in accounts:
                 table.add_row([
                     account.dbId, account.name,
                     account.targetPlatform.name,
                     account.created.strftime("%Y-%m-%d %H:%M:%S")
                 ])
             print table.draw() + "\n"
             printer.out("Found " + str(len(accounts)) + " accounts")
         return 0
     except Exception as e:
         return handle_uforge_exception(e)
def penilaian():

    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_dtype(['i', 't', 't', 't', 't', 't', 't'])
        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())
Exemple #32
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())
Exemple #33
0
    def do_search(self, args):
        try:
            #add arguments
            doParser = self.arg_search()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                    return 2

            #call UForge API
            printer.out("Search package '"+doArgs.pkg+"' ...")
            distribution = self.api.Distributions(doArgs.id).Get()
            printer.out("for OS '"+distribution.name+"', version "+distribution.version)
            pkgs = self.api.Distributions(distribution.dbId).Pkgs.Getall(Query="name=="+doArgs.pkg)
            pkgs = pkgs.pkgs.pkg
            if pkgs is None or len(pkgs) == 0:
                printer.out("No package found")
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t","t","t","t","t"])
                table.header(["Name", "Version", "Arch", "Release", "Build date", "Size", "FullName"])
                pkgs = generics_utils.order_list_object_by(pkgs, "name")
                for pkg in pkgs:
                    table.add_row([pkg.name, pkg.version, pkg.arch, pkg.release, pkg.pkgBuildDate.strftime("%Y-%m-%d %H:%M:%S"), size(pkg.size), pkg.fullName])
                print table.draw() + "\n"
                printer.out("Found "+str(len(pkgs))+" packages")
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_search()
        except Exception as e:
            return handle_uforge_exception(e)
Exemple #34
0
 def do_search(self, args):
         try:
                 #add arguments
                 doParser = self.arg_search()
                 try:
                         doArgs = doParser.parse_args(args.split())
                 except SystemExit as e:
                         return
                 #call UForge API
                 printer.out("Search package '"+doArgs.pkg+"' ...")
                 distribution = self.api.Distributions(doArgs.id).Get()
                 printer.out("for OS '"+distribution.name+"', version "+distribution.version)
                 pkgs = self.api.Distributions(distribution.dbId).Pkgs.Getall(Search=doArgs.pkg, Version=distribution.version)
                 
                 if pkgs is None or not hasattr(pkgs, 'pkgs'):
                         printer.out("No package found")
                 else:
                     table = Texttable(800)
                     table.set_cols_dtype(["t","t","t","t","t","t"])
                     table.header(["Name", "Version", "Arch", "Release", "Build date", "Size"])
                     pkgs = generics_utils.oder_list_object_by(pkgs.get_pkgs().get_pkg(), "name")
                     for pkg in pkgs:
                             table.add_row([pkg.name, pkg.version, pkg.arch, pkg.release, pkg.pkgBuildDate.strftime("%Y-%m-%d %H:%M:%S"), size(pkg.size)])
                     print table.draw() + "\n"
                     printer.out("Found "+str(len(pkgs))+" packages")
         except ArgumentParserError as e:
                 printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
                 self.help_search()
         except Exception as e:        
                 generics_utils.print_uforge_exception(e)
Exemple #35
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()
Exemple #36
0
def _make_text_table(shap_values,
                     normalized_values,
                     pipeline_features,
                     top_k,
                     include_shap_values=False):
    """Make a table displaying the SHAP values for a prediction.

    Arguments:
        shap_values (dict): Dictionary mapping the feature names to their SHAP values. In a multiclass setting,
            this dictionary for correspond to the SHAP values for a single class.
        normalized_values (dict): Normalized SHAP values. Same structure as shap_values parameter.
        top_k (int): How many of the highest/lowest features to include in the table.
        include_shap_values (bool): Whether to include the SHAP values in their own column.

    Returns:
        str
    """
    n_cols = 4 if include_shap_values else 3
    dtypes = ["t"] * n_cols
    alignment = ["c"] * n_cols

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_dtype(dtypes)
    table.set_cols_align(alignment)

    header = ["Feature Name", "Feature Value", "Contribution to Prediction"]
    if include_shap_values:
        header.append("SHAP Value")

    rows = [header]
    rows += _make_rows(shap_values, normalized_values, pipeline_features,
                       top_k, include_shap_values)
    table.add_rows(rows)
    return table.draw()
Exemple #37
0
def print_matrix(m: np.ndarray, head: np.ndarray = None, title: str = "", c_type: str = 'a') -> None:
    """ display matrix
    :param m:
    :param head: head matrix
    :param title: title matrix
    :param c_type:
    :return:
    """
    cols_align = []
    cols_m = m.shape[1]
    rows_m = m.shape[0]
    for i in range(0, cols_m):
        if i == 0:
            cols_align.append("l")
        else:
            cols_align.append("r")

    content = []
    if head is None:
        head = [' ' for x in range(0, cols_m)]
    content.append(head)
    for i in range(0, rows_m):
        content.append(m[i])

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_header_align(cols_align)
    table.set_cols_dtype([c_type] * cols_m)  # automatic
    table.set_cols_align(cols_align)
    table.add_rows(content)

    if title != "":
        print("**********************  " + title + "  **********************")

    print(table.draw())
Exemple #38
0
    def showTable(self):

        neighbors_id = [i[1] for i in self.neighbors]

        table = Texttable()

        table.set_deco(Texttable.HEADER)

        table.set_cols_dtype(["t", "t", "t", "t"])

        table.set_cols_align(["l", "l", "l", "l"])

        rows = []

        rows.append([u"movie ID", u"Name", u"release", u"from userID"])

        for item in self.recommandList:

            fromID = []

            for i in self.movies:

                if i[0] == item[1]:
                    movie = i

                    break

            for i in self.ItemUser[item[1]]:

                if i in neighbors_id:
                    fromID.append(i)
            movie.append(fromID)
            rows.append(movie)
        table.add_rows(rows)
        print(table.draw())
class tabela_ambiente():
    def __init__(self, ambiente):
        self.ambiente = ambiente
        self.table = Texttable()

    def print_table(self, global_time):
        self.table.reset()
        self.table.set_deco(Texttable.HEADER)
        self.table.set_cols_dtype(['t',  # text
                              't',  # float 
                            ])
        self.table.set_cols_align(["l", "c"])
 
        self.table.add_rows([["Informações do ambiente", ""],
                       ["Hora: ", str(datetime.timedelta(seconds=global_time))],
                       ["Temperatura: ", str(round(self.ambiente.temperatura, 2))],
                       ["Chuva: ", str(self.ambiente.chuva)],
                       ["Estado Atmosférico: ", str(self.ambiente.estado_atmosferico)],
                       ["Sujeira: ", str(self.ambiente.sujeira)],
                       [" ", " "],
                       ["Último movimento foi há: ", str(datetime.timedelta(seconds=self.ambiente.mov_count))],
                       ["Ar-condicionado: ", str(self.ambiente.ar_condicionado)],
                       ["Aquecedor: ", str(self.ambiente.aquecedor)],
                       ["Lâmpada: ", str(self.ambiente.lampada)],
                       ["Porta: ", str(self.ambiente.porta)],
                       ["Janela: ", str(self.ambiente.janela)],
                       ["Televisão: ", str(self.ambiente.televisão)],
                       ["Aspirador de pó: ", str(self.ambiente.aspirador)]])
        
        print(self.table.draw())
Exemple #40
0
def create_finding_report(metadata: PackageMetadata, report: Report) -> str:
    """Reports on the findings.

    # noqa:DAR101
    # noqa:DAR201
    """
    if len(report.findings.keys()) == 0:
        findings_report = "<comment>No findings</comment>"
    else:
        findings_table = Texttable()
        findings_table.set_cols_dtype(["t", "t", "t", "t", "t"])
        findings_table.set_cols_align(["c", "c", "c", "l", "l"])
        findings_table.header(
            ["Priority", "ID", "Category", "Title", "Message"])
        for finding in report.all_findings:
            findings_table.add_row([
                finding.level.value,
                finding.id,
                finding.category,
                finding.title,
                finding.message,
            ])

        findings_report = findings_table.draw()

    report_title = (
        f"Report: {report.provider_details.display_name} [{metadata.coordinates}]"
    )

    return f"<h1>{report_title}</h1>\n{findings_report}\n\n"
Exemple #41
0
    def do_delete(self, args):
        try:
            #add arguments
            doParser = self.arg_delete()
            try:
                doArgs = doParser.parse_args(args.split())
            except SystemExit as e:
                return
            #call UForge API
            printer.out("Searching template with id ["+doArgs.id+"] ...")
            myAppliance = self.api.Users(self.login).Appliances(doArgs.id).Get()
            if myAppliance is None or type(myAppliance) is not Appliance:
                printer.out("Template not found")
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t","t","t","t","t","t","t","t"])
                table.header(["Id", "Name", "Version", "OS", "Created", "Last modified", "# Imgs", "Updates", "Imp", "Shared"])
                table.add_row([myAppliance.dbId, myAppliance.name, str(myAppliance.version), myAppliance.distributionName+" "+myAppliance.archName,
                               myAppliance.created.strftime("%Y-%m-%d %H:%M:%S"), myAppliance.lastModified.strftime("%Y-%m-%d %H:%M:%S"), len(myAppliance.imageUris.uri),myAppliance.nbUpdates, "X" if myAppliance.imported else "", "X" if myAppliance.shared else ""])
                print table.draw() + "\n"

                if doArgs.no_confirm:
                    self.api.Users(self.login).Appliances(myAppliance.dbId).Delete()
                    printer.out("Template deleted", printer.OK)
                elif generics_utils.query_yes_no("Do you really want to delete template with id "+str(myAppliance.dbId)):
                    self.api.Users(self.login).Appliances(myAppliance.dbId).Delete()
                    printer.out("Template deleted", printer.OK)
            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e)
Exemple #42
0
def test_texttable_header():
    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_dtype([
        't',  # text
        'f',  # float (decimal)
        'e',  # float (exponent)
        'i',  # integer
        'a',  # automatic
    ])
    table.set_cols_align(["l", "r", "r", "r", "l"])
    table.add_rows([
        ["text", "float", "exp", "int", "auto"],
        ["abcd", "67", 654, 89, 128.001],
        ["efghijk", 67.5434, .654, 89.6, 12800000000000000000000.00023],
        ["lmn", 5e-78, 5e-78, 89.4, .000000000000128],
        ["opqrstu", .023, 5e+78, 92., 12800000000000000000000],
    ])
    assert clean(table.draw()) == dedent('''\
         text     float       exp      int     auto
        ==============================================
        abcd      67.000   6.540e+02    89   128.001
        efghijk   67.543   6.540e-01    90   1.280e+22
        lmn        0.000   5.000e-78    89   0.000
        opqrstu    0.023   5.000e+78    92   1.280e+22
    ''')
Exemple #43
0
    def do_delete(self, args):
        try:
            #add arguments
            doParser = self.arg_delete()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                return 2

            #call UForge API
            printer.out("Searching bundle with id ["+doArgs.id+"] ...")
            myBundle = self.api.Users(self.login).Mysoftware(doArgs.id).Get()
            if myBundle is None or type(myBundle) is not MySoftware:
                printer.out("Bundle not found", printer.WARNING)
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t", "t","t", "t"])
                table.header(["Id", "Name", "Version", "Description", "Size", "Imported"])
                table.add_row([myBundle.dbId, myBundle.name, myBundle.version, myBundle.description, size(myBundle.size), "X" if myBundle.imported else ""])
                print table.draw() + "\n"
                if generics_utils.query_yes_no("Do you really want to delete bundle with id "+str(myBundle.dbId)):
                    self.api.Users(self.login).Mysoftware(myBundle.dbId).Delete()
                    printer.out("Bundle deleted", printer.OK)


        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e)
Exemple #44
0
    def do_delete(self, args):
        try:
            # add arguments
            doParser = self.arg_delete()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                    return 2

            # call UForge API
            printer.out("Searching account with id [" + doArgs.id + "] ...")
            account = self.api.Users(self.login).Accounts(doArgs.id).Get()
            if account is None:
                printer.out("No Account available", printer.WARNING)
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t", "t", "t", "t"])
                table.header(["Id", "Name", "Type", "Created"])
                table.add_row(
                    [account.dbId, account.name, account.targetPlatform.name, account.created.strftime("%Y-%m-%d %H:%M:%S")])
                print table.draw() + "\n"
                if doArgs.no_confirm:
                    self.api.Users(self.login).Accounts(doArgs.id).Delete()
                    printer.out("Account deleted", printer.OK)
                elif generics_utils.query_yes_no("Do you really want to delete account with id " + str(account.dbId)):
                    self.api.Users(self.login).Accounts(doArgs.id).Delete()
                    printer.out("Account deleted", printer.OK)
            return 0

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e)
Exemple #45
0
 def do_list(self, args):
     try:
         #call UForge API
         printer.out("Getting distributions for ["+self.login+"] ...")
         distributions = self.api.Users(self.login).Distros.Getall()
         distributions = distributions.distributions
         if distributions is None or not hasattr(distributions, "distribution"):
             printer.out("No distributions available")
         else:
             table = Texttable(800)
             table.set_cols_dtype(["t","t","t","t","t", "t"])
             table.header(["Id", "Name", "Version", "Architecture", "Release Date", "Profiles"])
             distributions = generics_utils.order_list_object_by(distributions.distribution, "name")
             for distribution in distributions:
                 profiles = self.api.Distributions(distribution.dbId).Profiles.Getall()
                 profiles = profiles.distribProfiles.distribProfile
                 if len(profiles) > 0:
                     profile_text=""
                     for profile in profiles:
                         profile_text+=profile.name+"\n"
                     table.add_row([distribution.dbId, distribution.name, distribution.version, distribution.arch, distribution.releaseDate.strftime("%Y-%m-%d %H:%M:%S") if distribution.releaseDate is not None else "", profile_text])
                 else:
                     table.add_row([distribution.dbId, distribution.name, distribution.version, distribution.arch, distribution.releaseDate.strftime("%Y-%m-%d %H:%M:%S") if distribution.releaseDate is not None else "", "-"])
             print table.draw() + "\n"
             printer.out("Found "+str(len(distributions))+" distributions")
         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)
Exemple #46
0
def scan_table(scanInstances, scan=None):
    table = Texttable(800)
    table.set_cols_dtype(["t", "t", "t", "t", "t"])
    table.set_cols_align(["c", "l", "c", "c", "c"])
    table.header(["Id", "Name", "Status", "Distribution", "With overlay"])
    if scan:
        table.add_row([scan.dbId, "\t" + scan.name, scan_status(scan), "", ""])
        return table
    for myScannedInstance in scanInstances:
        withOverlayStr = ''
        if myScannedInstance.overlayIncluded:
            withOverlayStr = 'X'
        table.add_row([
            myScannedInstance.dbId, myScannedInstance.name, "",
            myScannedInstance.distribution.name + " " +
            myScannedInstance.distribution.version + " " +
            myScannedInstance.distribution.arch, withOverlayStr
        ])
        scans = generics_utils.order_list_object_by(
            myScannedInstance.scans.scan, "name")
        for lscan in scans:
            table.add_row(
                [lscan.dbId, "\t" + lscan.name,
                 scan_status(lscan), "", ""])
    return table
Exemple #47
0
def display_departures(station_name, limit=10, mode=None):
    station_name = get_station_name(station_name)
    departuresJSON = get_departures_by_name(station_name)
    departures = []
    if mode is not None:
        for d in departuresJSON:
            if mode.upper() in d['product']:
                departures += [Departure(d)]
    else:
        departures = [Departure(i) for i in departuresJSON]

    departures = departures[:limit]

    print('\nStation: ' + station_name + '\n')

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_dtype(['t', 't', 'i'])
    table.set_cols_align(['l', 'l', 'r'])

    rows = []
    rows.append([
        '\x1b[38;5;231m\x1b[48;5;23mline\x1b[0m', 'destination',
        'departure (min)'
    ])
    for dep in departures:
        rows.append([
            dep.get_label_colored(), dep.destination,
            dep.departure_time_minutes
        ])
    table.add_rows(rows)
    print(color(table.draw(), fore=MVG_FG, back=MVG_BG))
Exemple #48
0
    def command_password(self, params):
        '''[set/get/list] <pdu> <port> <password>

        password set <pdu> <port> <password>
        Set port password on pdu
        e.g.
        - Set password "A01" for port 1 on pdu 1
        password set 1 1 A01

        password get <pdu> <port>
        Get port password on pdu
        e.g.
        - Get password for port 1 on pdu 1
        password get 1 1

        password list <pdu>
        Display password of all ports on pdu
        e.g.
        - Display all ports password on pdu 1
        password list 1

        '''
        subcommand = params[0]
        if subcommand == 'set':
            if len(params) != 4:
                self.writeresponse("Invalid parameters.")
                return
            pdu = int(params[1])
            port = int(params[2])
            passwd = params[3]
            password.write_password(pdu, port, passwd)
        elif subcommand == 'get':
            if len(params) != 3:
                self.writeresponse("Invalid parameters.")
                return
            pdu = int(params[1])
            port = int(params[2])
            password_str = password.read_password(pdu, port)
            if password_str == "":
                self.writeresponse("Not found password.")
                return
            response = "Password is: " + password_str
            self.writeresponse(response)
        elif subcommand == 'list':
            if len(params) != 2:
                self.writeresponse("Invalid parameters.")
                return

            pdu = int(params[1])
            table = Texttable()
            table.header(["Port", "Password"])
            table.set_cols_dtype(['d', 't'])
            table.set_cols_align(['c', 'c'])
            for port_index in range(24):
                passwd = password.read_password(pdu, port_index + 1)
                if passwd == "":
                    continue
                table.add_row([port_index + 1, passwd])
            self.writeresponse(table.draw())
Exemple #49
0
 def print_log(self):
     table = Texttable(140)
     table.set_cols_dtype(['t', 't', 't'])
     table.set_cols_align(['c', 'c', 'c'])
     table.add_row(['Action','Description','Date'])
     for logitem in self.log_items:
         table.add_row([logitem.status, logitem.description, logitem.date])
     print table.draw()
Exemple #50
0
 def show_items(self, items):
     table = Texttable(max_width=0)
     table.header(['#', 'item'])
     table.set_deco(Texttable.HEADER | Texttable.VLINES)
     table.set_cols_dtype(['i', 't'])
     table.add_rows([(i, item) for i, item in enumerate(items)],
                    header=False)
     print(table.draw())
Exemple #51
0
    def main(self):
        from texttable import Texttable
        import shutil
        # egt weekrpt also showing stats by project, and by tags
        e = self.make_egt(self.args.projects)
        # TODO: add an option to choose the current time
        # if self.args.projects:
        #     end = datetime.datetime.strptime(self.args.projects[0], "%Y-%m-%d").date()
        # else:
        #     end = None
        end = None

        termsize = shutil.get_terminal_size((80, 25))
        table = Texttable(max_width=termsize.columns)
        table.set_deco(Texttable.HEADER)
        table.set_cols_align(("l", "r", "r", "r", "r"))
        table.set_cols_dtype(('t', "i", "i", "i", "i"))
        table.add_row(("Tag", "Entries", "Hours", "h/day", "h/wday"))
        rep = e.weekrpt(end=end)
        print()
        print(" * Activity from %s to %s" % (rep["begin"], rep["until"]))
        print()
        log = rep["log"]

        # Global stats
        table.add_row(("(any)", rep["count"], rep["hours"], rep["hours_per_day"], rep["hours_per_workday"]))

        # Per-tag stats
        all_tags = set()
        for p in e.projects:
            all_tags |= p.tags
        for t in sorted(all_tags):
            rep = e.weekrpt(end=end, tags=frozenset((t,)))
            table.add_row((t, rep["count"], rep["hours"], rep["hours_per_day"], rep["hours_per_workday"]))

        print(table.draw())
        print()

        # Per-package stats
        table = Texttable(max_width=termsize.columns)
        table.set_deco(Texttable.HEADER)
        table.set_cols_align(("l", "r", "r", "r", "r"))
        table.set_cols_dtype(('t', "i", "i", "i", "i"))
        table.add_row(("Project", "Entries", "Hours", "h/day", "h/wday"))
        for p in e.projects:
            rep = e.weekrpt(end=end, projs=[p])
            if not rep["count"]:
                continue
            table.add_row((p.name, rep["count"], rep["hours"], rep["hours_per_day"], rep["hours_per_workday"]))

        print(table.draw())
        print()

        log.sort(key=lambda x: x[0].begin)
        for l, p in log:
            l.print(sys.stdout, project=p.name)
Exemple #52
0
    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
Exemple #53
0
def process_ppa_stats(ppa_owner, ppa_name, versions, archs):
    # Login into Launchpad Anoymously
    lp_login = Launchpad.login_anonymously('ppastats', 'edge',
                                           '~/.launchpadlib/cache/',
                                           version='devel')
    # PPA owner
    owner = lp_login.people[ppa_owner]
    # PPA name
    archive = owner.getPPAByName(name=ppa_name)

    # Base URL to Launchpad API
    base_url = 'https://api.launchpad.net/devel/ubuntu/{}/{}'

    # Print heading
    header = 'Download stats for ' + ppa_owner + ' PPA'
    print header
    print '-' * len(header)

    # For each version
    for version in versions:
        print ''
        print 'Packages for ' + version

        result = [['Package', 'Version', 'Arch', 'Count']]

        # For each architecture
        for arch in archs:
            url_to_check = base_url.format(version, arch)

            for individual_archive in archive.getPublishedBinaries(
                    status='Published', distro_arch_series=url_to_check):

                result.append(
                    [
                        individual_archive.binary_package_name,
                        individual_archive.binary_package_version,
                        arch,
                        str(individual_archive.getDownloadCount())
                    ]
                )

        if not use_table:
            # Simple terminal output
            for value in result:
                print value[0] + "\t" + value[1] + "\t" + value[2] + "\t" + \
                    value[3]
        else:
            # Show the result in a beautiful table
            table = Texttable()

            table.set_cols_dtype(['t', 't', 't', 'i'])
            table.set_cols_align(['l', 'r', 'r', 'r'])
            table.add_rows(result)

            print table.draw()
Exemple #54
0
	def printContent(self):
		table = Texttable()
		table.set_deco(Texttable.HEADER)
		table.set_cols_dtype(['t',
                              't',
                              'a'])
		table.add_row(['Tag','hex','binary'])
		for key, value in self.rcDict.iteritems():
			table.add_row([key,value,binascii.unhexlify(value)])
			#print key, "\t", value, "\t\t", binascii.unhexlify(value)
		print table.draw()
Exemple #55
0
    def do_list(self, args):
        try:
            # call UForge API
            # get images
            printer.out("Getting all images and publications for [" + self.login + "] ...")
            images = self.api.Users(self.login).Images.Getall()
            images = images.images.image
            # get publications
            pimages = self.api.Users(self.login).Pimages.Getall()
            pimages = pimages.publishImages.publishImage
            if images is None or len(images) == 0:
                printer.out("No images available")
            else:
                printer.out("Images:")
                table = Texttable(800)
                table.set_cols_dtype(["t", "t", "t", "t", "t", "t", "t", "c", "t"])
                table.header(
                    ["Id", "Name", "Version", "Rev.", "Format", "Created", "Size", "Compressed", "Generation Status"])
                images = generics_utils.order_list_object_by(images, "name")
                for image in images:
                    imgStatus = self.get_image_status(image.status)
                    table.add_row([image.dbId, image.name, image.version, image.revision, image.targetFormat.name,
                                   image.created.strftime("%Y-%m-%d %H:%M:%S"), size(image.fileSize),
                                   "X" if image.compress else "", imgStatus])
                print table.draw() + "\n"
                printer.out("Found " + str(len(images)) + " images")

            if pimages is None or len(pimages) == 0:
                printer.out("No publication available")
            else:
                printer.out("Publications:")
                table = Texttable(800)
                table.set_cols_dtype(["t", "t", "t", "t", "t", "t", "t"])
                table.header(["Template name", "Image ID", "Publish ID", "Account name", "Format", "Cloud ID", "Status"])
                pimages = generics_utils.order_list_object_by(pimages, "name")
                for pimage in pimages:
                    pubStatus = self.get_publish_status(pimage.status)
                    table.add_row([pimage.name,
                                   generics_utils.extract_id(pimage.imageUri),
                                   pimage.dbId,
                                   pimage.credAccount.name if pimage.credAccount is not None else "-",
                                   pimage.credAccount.targetPlatform.name,
                                   pimage.cloudId if pimage.cloudId is not None else "-", pubStatus])
                print table.draw() + "\n"
                printer.out("Found " + str(len(pimages)) + " publications")

            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)
Exemple #56
0
def migration_table(migrations):
    table = Texttable(800)
    table.set_cols_dtype(["t", "t", "t"])
    table.set_cols_align(["c", "l", "c"])
    table.header(["Id", "Name", "Status"])

    for migration in migrations:
        status = migration.status.message + " (" + str(migration.status.percentage) + "%)"
        if migration.status.complete or migration.status.error or migration.status.cancelled:
            status = migration.status.message
        table.add_row([migration.dbId, migration.name, status])

    return table
Exemple #57
0
def markdown_table(records):
    from texttable import Texttable
    fields = ['label', 'timestamp', 'reason', 'duration']
    table = Texttable()
    table.set_cols_dtype(['t'] * len(fields))
    rows = [fields]
    for record in records:
        rows.append([str(getattr(record, field)) for field in fields])
    table.add_rows(rows)
    out = table.draw().replace('=', '-')
    out = out.replace('\n+-', '\n|-')
    out = '|' + out[1:-1] + '|'
    return out
 def print_table(self):
     print("Count of resource tags for %d EC2 Instances, Images, Security "
           "Groups, Snapshots, Volumes, and ASGs\n" % self.res_count)
     t = Texttable()
     t.set_cols_dtype(['t', 'i'])
     rows = [['Tag Name', 'Count']]
     for k in sorted(self.tags.keys(), key=lambda s: s.lower()):
         rows.append([k, self.tags[k]])
     t.add_rows(rows)
     print(t.draw() + "\n")
     print(
         "Generated by: https://github.com/jantman/misc-scripts/blob/"
         "master/aws-count-tag-names.py\n")
Exemple #59
0
    def dns(self, **kwargs):
        data = yield self._remote_exec('dns')

        table = Texttable(max_width=120)
        table.set_cols_dtype(['t', 'a'])
        # table.set_cols_width([20,  100])

        rows = [["Name", "Value"]]
        for name, val in data.items():
            rows.append([name, val])

        table.add_rows(rows)
        print table.draw() + "\\n"
Exemple #60
0
def scan_table(scanInstances, scan = None):
    table = Texttable(800)
    table.set_cols_dtype(["t","t","t","t"])
    table.header(["Id", "Name", "Status", "Distribution"])
    if scan:
        table.add_row([scan.dbId, "\t"+scan.name, scan_status(scan), "" ])
        return table
    for myScannedInstance in scanInstances:
        table.add_row([myScannedInstance.dbId, myScannedInstance.name, "", myScannedInstance.distribution.name + " "+ myScannedInstance.distribution.version + " " + myScannedInstance.distribution.arch])
        scans = generics_utils.order_list_object_by(myScannedInstance.scans.scan, "name")
        for lscan in scans:
            table.add_row([lscan.dbId, "\t"+lscan.name, scan_status(lscan), "" ])
    return table