def makePretty(coord, progress, storage, file_seq, path):

    print("--------------------------------------------------------")
    print("Looking @ " + file_seq)
    print("--------------------------------------------------------")

    f.write("\n Looking @ " + file_seq + "\n")
    t = Texttable()
    t.add_rows([[
        'Node ID', 'X', 'Y', 'Storage', 'Progress', '+%(1)', '+%(2)',
        'Neighbors'
    ]])
    A = 0
    # for x in range(0,9):
    # 	t.add_row([coord.iloc[A,0],coord.iloc[A,1],coord.iloc[A,2], storage.iloc[A-1, 1], progress.iloc[A,:]])
    # 	A+=1

    neighbors = path + "/neighbors_dump" + file_seq + ".dat"

    for line in open(neighbors):
        #print(getProgress(seq,args.path).iloc[A,2])

        neighbors_list = line.rstrip(';\n').split(';')
        t.add_row([
            coord.iloc[A, 0], coord.iloc[A, 1], coord.iloc[A, 2],
            storage.iloc[A, 1], progress.iloc[A, :],
            goodProgress(file_seq, path, A, 1),
            goodProgress(file_seq, path, A, 2), neighbors_list
        ])
        A += 1

    print(t.draw())
    f.write(t.draw())

    t.reset()
Example #2
0
 def to_txt_file(self, rounds,file, print_header): 
     table = Texttable()
     table.set_cols_width([len(self.team_one.get_name()) + 9, len(self.team_two.get_name()) + 9])
     if print_header:
         deco = Texttable.HEADER | Texttable.VLINES
         table.header([self.team_one.get_name(), self.team_two.get_name()])
     else:
         deco = Texttable.VLINES
     table.set_deco(deco)
     table.set_chars(['-', '|', '=', '='])
     rows = [[str(rounds[0].get_team_one_points()),str(rounds[0].get_team_two_points())]]
     for i in range(1,len(rounds)):
         column1 = f"{sum([x.get_team_one_points() for x in rounds[:i]])} + {rounds[i].get_team_one_points()}"
         column2 = f"{sum([x.get_team_two_points() for x in rounds[:i]])} + {rounds[i].get_team_two_points()}"
         rows.append([column1,column2])
     column1 = f"{sum([x.get_team_one_points() for x in rounds])}"
     column2 = f"{sum([x.get_team_two_points() for x in rounds])}"
     rows.append([column1,column2])
     table.add_rows(rows, header = False)
     file.write(table.draw())
     file.write('\n')
     self.write_divider_to_file(file)
     table.reset()
     table.add_row([f"({self.team_one.games_won})", f"({self.team_two.games_won})"])
     table.set_cols_align(["c","c"])        
     file.write(table.draw())
     file.write('\n')
     self.write_divider_to_file(file)
def dump(relation):
    width, height = term_size()
    table = Texttable(width)

    sample, iterator = tee(relation)

    table.add_rows(take(1000, sample))
    table._compute_cols_width()
    del sample

    table.reset()

    table.set_deco(Texttable.HEADER)
    table.header([f.name for f in relation.schema.fields])

    rows = take(height - 3, iterator)

    try:
        while rows:
            table.add_rows(rows, header=False)
            print table.draw()
            rows = take(height - 3, iterator)
            if rows:
                raw_input("-- enter for more ^c to quit --")
    except KeyboardInterrupt:
        print
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())
Example #5
0
def printTable(coord, progress, storage, file_seq, path):

    print("--------------------------------------------------------")
    print("Looking @ " + file_seq)
    print("--------------------------------------------------------")

    f.write("\n Looking @ " + file_seq + "\n")
    t = Texttable()
    t.add_rows([[
        'Node ID', 'X', 'Y', 'Storage', 'Progress', '+%(1)', '+%(2)',
        'Neighbors'
    ]])
    A = 0

    neighbors = path + "/neighbors_dump" + file_seq + ".dat"

    for line in open(neighbors):

        neighbors_list = line.rstrip(';\n').split(';')
        t.add_row([
            coord.iloc[A, 0], coord.iloc[A, 1], coord.iloc[A, 2],
            storage.iloc[A, 1], progress.iloc[A, :],
            progressSinceLastInterval(file_seq, path, A, 1),
            progressSinceLastInterval(file_seq, path, A, 2), neighbors_list
        ])
        A += 1

    print(t.draw())
    f.write(t.draw())

    t.reset()
def dump(relation):
  width,height = term_size()
  table = Texttable(width)


  sample, iterator = tee(relation)


  table.add_rows(take(1000,sample))
  table._compute_cols_width()
  del sample
  
  table.reset()

  table.set_deco(Texttable.HEADER)
  table.header([f.name for f in relation.schema.fields])



  rows = take(height-3, iterator)

  try:
    while rows:
      table.add_rows(rows, header=False)
      print table.draw()
      rows = take(height-3, iterator)
      if rows:
        raw_input("-- enter for more ^c to quit --")
  except KeyboardInterrupt:
    print
Example #7
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
Example #8
0
    def print_info(self, script, syntax, runtime):
        from texttable import Texttable

        table = Texttable();
        table.reset()
        table.set_cols_align(["l","l","l"])
        table.add_rows([
                          ['Script Name', 'Syntax Error', 'Runtime Error'],
                          [script, syntax, list(error for error in runtime)],
                  ])
        print(table.draw())
Example #9
0
    def describe(self):
        change_set = self.client.describe_change_set(StackName=self.stack,
                                                     ChangeSetName=self.name)
        table = Texttable(max_width=150)

        logger.info("Deployment metadata:")
        parameters = ', '.join([
            parameter['ParameterKey'] + '=' + parameter['ParameterValue']
            for parameter in change_set.get('Parameters', [])
        ])
        table.add_row(['Parameters', parameters])
        tags = [
            tag['Key'] + '=' + tag['Value']
            for tag in change_set.get('Tags', [])
        ]
        table.add_row(["Tags ", ', '.join(tags)])
        table.add_row(
            ["Capabilities ", ', '.join(change_set.get('Capabilities', []))])
        logger.info(table.draw() + '\n')

        table.reset()
        table = Texttable(max_width=150)
        table.add_rows([CHANGE_SET_HEADER])

        def __change_detail(change):
            target_ = change['Target']
            attribute = target_['Attribute']
            if attribute == 'Properties':
                return target_['Name']
            else:
                return attribute

        for change in change_set['Changes']:
            resource_change = change['ResourceChange']
            table.add_row([
                resource_change['Action'],
                resource_change['LogicalResourceId'],
                resource_change.get('PhysicalResourceId',
                                    ''), resource_change['ResourceType'],
                resource_change.get('Replacement', ''), ', '.join(
                    sorted(
                        set([
                            __change_detail(c)
                            for c in resource_change['Details']
                        ])))
            ])

        logger.info('Resource Changes:')
        logger.info(table.draw())
Example #10
0
def top_100_rated_movies(dataset_path):
    ratings = toDf(os.path.join(dataset_path, 'ratings.csv'),
                   dropCols=['timestamp', 'userId'])
    movies = toDf(os.path.join(dataset_path, 'movies.csv'),
                  dropCols=['genres'])
    average_rating = ratings.groupby(by='movieId').mean()
    rating_count = ratings.groupby(by='movieId').count().rename(
        columns={'rating': 'rating_count'})
    movie_stat = average_rating.merge(rating_count,
                                      left_index=True,
                                      right_index=True).sort_values(
                                          by='rating_count',
                                          ascending=False).reset_index()
    movie_stat = movie_stat.merge(movies,
                                  left_on='movieId',
                                  right_on='movieId')
    total_movies_rated = len(movie_stat.index)
    print(total_movies_rated)
    # print(average_rating.head())
    # print(rating_count.head())
    theMiddle = int(total_movies_rated * 0.2)
    middle100 = movie_stat.iloc[theMiddle -
                                100:theMiddle].drop(columns=['movieId'])
    print('From %d to %d, the mean rate is %f' %
          (theMiddle - 100, theMiddle, middle100['rating'].mean()))
    middle100.plot(y=['rating'],
                   title='Rating of Not so hot movies',
                   grid=True)
    plt.show()
    hot100 = movie_stat.iloc[0:100].drop(columns=['movieId'])
    print('From 0 to 99, the mean rate is %f' % hot100['rating'].mean())
    # print(movie_stat.head())
    tb = Texttable()
    tb.set_cols_align(['l', 'r', 'r'])
    tb.set_cols_dtype(['f', 'i', 't'])
    tb.header(hot100.columns.get_values())
    tb.add_rows(hot100.values, header=False)
    with open('hot_100.txt', 'w') as ofile:
        ofile.write(tb.draw().encode('utf8'))
    hot100.plot(y=['rating'], title='Rating of Hot 100 movies', grid=True)
    hot_sucks = hot100[hot100['rating'] < 3.2]
    tb.reset()
    tb.header(hot_sucks.columns.get_values())
    tb.add_rows(hot_sucks.values, header=False)
    with open('hot_sucks.txt', 'w') as ofile:
        ofile.write(tb.draw().encode('utf8'))
    # print(hot100.mean())
    # print(cool100.mean())
    plt.show()
Example #11
0
def print_class(c):
	blank = []
	for i in range(10):
		blank.append('   ')
	table = Texttable()
	table.set_deco(Texttable.HEADER)
	for cs,item in c.items():
		table.header(blank)
		print "Class identifier: %g"%(cs)
		row = []
		for i in item:
			row.append(i)
			if len(row) == 10:
				table.add_row(row)
				row = []
		if len(row) != 0 and len(row) < 10:
			row += blank[(len(row)):]
			table.add_row(row)
		print table.draw()
		table.reset()
class tabela_tarefas():
    def __init__(self, lista_tarefas):
        self.lista = lista_tarefas
        self.table = Texttable()

    def print_table(self):
        self.table.reset()
        self.table.set_deco(Texttable.HEADER)
        self.table.set_cols_dtype(['t',  # text
                              't',  # text
                              't', #text
                              't',  #text
                              't' #text            
                            ])
        self.table.set_cols_align(["l", "l", "c", "c", "c"])
 
        self.table.add_rows([["Fila de tarefas", "", "", "", ""],
                            ["ID: ", "Nome: ", "Deadline: ", "T. Execução: ", "T. Requerido"]]
                            )
        for tarefa in self.lista:
            self.table.add_row([str(tarefa.id), str(tarefa.nome), str(tarefa.deadline), str(tarefa.tempo_exec), str(tarefa.tempo_req)])

        print(self.table.draw())
Example #13
0
        message_send(
            "Try again but make sure to include PC with your year following it!"
        )


while True:
    time.sleep(.5)
    now = datetime.datetime.now()
    if now > reset_time:
        if now < reset_time_end:
            # This command is not available before version 3.3
            #lunch_list.clear()
            #dinner_list.clear()
            del lunch_list[:]
            del dinner_list[:]
            lunch_output_table.reset()
            dinner_output_table.reset()
            clear()
            dinner_output_table.add_row([['        Dinner         ']])
            lunch_output_table.add_row([['         Lunch         ']])
            lunch_output_table.set_cols_align("c")
            dinner_output_table.set_cols_align("c")
            print(
                text.Text("LATE PLATE BOT",
                          color='0000ff',
                          shadow=True,
                          skew=5))
            print(lunch_output_table.draw())
            print(dinner_output_table.draw())
        else:
            pass
Example #14
0
def generate_api_index_for_module(the_module):
    module_description = generate_module_doc(the_module)
    if module_description is None:
        module_description = ''
    module_doc = ''

    module_header_flag = False
    # Document functions first, if any
    tab = Texttable()
    for func in the_module[
            'functions']:  # Iterate through the module functions
        name = func['function_name']
        obj = getattr(the_module['module_object'],
                      name)  # Retrieve the function object
        description = get_function_short_description(obj).strip()
        tab.add_rows([[name, description]], header=False)

    module_name = ''
    func_doc = tab.draw()
    if func_doc and func_doc != '':  # If the function list is not empty then add module name to the document
        module_name = the_module['module_name']
        module_doc += create_header_str(module_name, '~') + '\n\n' + module_description + '\n\n' + \
            create_header_str('Functions:', '-') + \
            '\n\n' + func_doc + '\n\n'
        module_header_flag = True

    # Document classes
    classes_header_flag = False
    for the_class in the_module[
            'classes']:  # Iterate through the module classes
        tab.reset()
        class_name = the_class['class_name']
        class_obj = the_class['class_object']
        class_description = class_obj.__doc__
        if not class_description:
            class_description = ''
        class_doc = ''
        class_header_flag = False

        # Document class attributes first, if any
        for attr in the_class[
                'class_attributes']:  # Iterate through the class attributes
            name = attr
            obj = getattr(the_class['class_object'],
                          name)  # Retrieve the attribute object
            description = get_function_short_description(obj).strip()
            tab.add_rows([[name, description]], header=False)

        attr_doc = tab.draw()
        if attr_doc and attr_doc != '':  # If the attribute list is not empty then add class name to the document
            class_header_flag = True
            class_doc += create_header_str(class_name, '^') + '\n\n' + class_description + '\n\n' + \
                create_header_str('Attributes:', '+') + \
                '\n\n' + attr_doc + '\n\n'

        # Document class methods, if any
        for method in the_class[
                'class_methods']:  # Iterate through the class methods
            name = method
            obj = getattr(the_class['class_object'],
                          name)  # Retrieve the method object
            description = get_function_short_description(obj).strip()
            tab.add_rows([[name, description]], header=False)

        method_doc = tab.draw()
        if method_doc and method_doc != '':  # If the method list is not empty then add class name to the document
            if not class_header_flag:
                class_doc += create_header_str(class_name, '^') + '\n\n' + class_description + '\n\n' + \
                             create_header_str('Methods:', '+') + \
                             '\n\n' + method_doc + '\n\n'
                class_header_flag = True
            else:
                class_doc += create_header_str('Methods:', '+') + \
                             '\n\n' + method_doc + '\n\n'

        if not module_header_flag:  # There is no module header yet
            if class_header_flag:  # There were methods/attributes for the class
                module_doc += create_header_str(module_name, '~') + '\n\n' + module_description + '\n\n' + \
                              create_header_str('Classes:', '-') + \
                              '\n\n' + class_doc + '\n\n'
                module_header_flag = True
                classes_header_flag = True
        else:  # The module header has been added
            if class_header_flag:  # There are new methods/attributes for the class
                if not classes_header_flag:  # First class of the module description
                    module_doc += create_header_str('Classes:', '-') + '\n\n'
                module_doc += '\n\n' + class_doc + '\n\n'
    return module_doc
Example #15
0
    time.sleep(8)

    f = open("/var/www/html/output/wad/wad.csv", "r")
    a = f.readlines()
    tt = Texttable()
    table = []
    versions = {}
    tt.set_cols_width([35, 35, 15, 45])
    for i in a:
        i = i.split(",", 3)
        versions.update({i[1]: i[2]})
        table.append(i)
    tt.add_rows(table)
    with open('/var/www/html/output/wad/wad.txt', 'w') as f:
        print('', tt.draw(), file=f)
        tt.reset()
        f.close()
    os.system("cat /var/www/html/output/wad/wad.txt")
    scan_info(1, hostname)
    os.system(
        "cat /var/www/html/output/wad/wad.txt|aha --black --word-wrap >> /var/www/html/output/Wad.html"
    )
    print("\n")
    change = cwd + "/input/webscreenshot.py"
    os.system("python " + change + " 127.0.0.1/output/Wad.html" + " -o " +
              cwd + "/output/screenshot/" + hostname)

except Exception as e:
    print(e)

#Exploit Search
Example #16
0
    def describe(self, print_metadata=True):
        if self.change_set_arn:
            cs_options = dict(ChangeSetName=self.change_set_arn)
        else:
            cs_options = dict(StackName=self.stack, ChangeSetName=self.name)
        change_set = cf.describe_change_set(**cs_options)
        table = Texttable(max_width=150)

        if print_metadata:
            logger.info("Deployment metadata:")
            parameters = ", ".join([
                parameter["ParameterKey"] + "=" + parameter["ParameterValue"]
                for parameter in change_set.get("Parameters", [])
            ])
            table.add_row(["Parameters", parameters])
            tags = [
                tag["Key"] + "=" + tag["Value"]
                for tag in change_set.get("Tags", [])
            ]
            table.add_row(["Tags ", ", ".join(tags)])
            table.add_row([
                "Capabilities ", ", ".join(change_set.get("Capabilities", []))
            ])
            logger.info(table.draw() + "\n")
            logger.info("Resource Changes:")

        table.reset()
        table = Texttable(max_width=150)
        table.add_rows([CHANGE_SET_HEADER])

        def __change_detail(change):
            target_ = change["Target"]
            attribute = target_["Attribute"]
            if attribute == "Properties":
                return target_.get("Name", "")
            else:
                return attribute

        for change in change_set["Changes"]:
            resource_change = change["ResourceChange"]
            table.add_row([
                resource_change["Action"],
                resource_change["LogicalResourceId"],
                resource_change.get("PhysicalResourceId", ""),
                resource_change["ResourceType"],
                resource_change.get("Replacement", ""),
                ", ".join(
                    sorted(
                        set([
                            __change_detail(c)
                            for c in resource_change["Details"]
                        ]))),
            ])

        logger.info(table.draw())

        nested_change_sets = [(change["ResourceChange"]["LogicalResourceId"],
                               change["ResourceChange"]["ChangeSetId"])
                              for change in change_set["Changes"]
                              if change["ResourceChange"]["ResourceType"] ==
                              "AWS::CloudFormation::Stack"
                              and change["ResourceChange"].get("ChangeSetId")]
        for nested_change_set in nested_change_sets:
            logger.info(f"\nChanges for nested Stack: {nested_change_set[0]}")
            ChangeSet(stack=self.stack,
                      arn=nested_change_set[1]).describe(print_metadata=False)