Ejemplo n.º 1
0
def distribution_process(distribution, dist_class):
    increase = defaultdict(int)
    decrease = defaultdict(int)
    same = defaultdict(int)
    category = dict({'nao_eleitos': defaultdict(int), 'reeleitos': defaultdict(int), 'novos': defaultdict(int)})
    total = defaultdict(int)
    for cond, dep in distribution.items():
        for d, val in dep.items():
            total[cond] += 1
            before, election = dist_dep(val)
            ks = ks_2samp(before, election)
            # reject null hypotesis
            if ks[1] < 0.05:
                if np.mean(before) < np.mean(election):
                    increase[cond] += 1
                else:
                    decrease[cond] += 1
            else:
                same[cond] += 1
    print(dist_class)
    table = BeautifulTable()
    table.column_headers = ["","RE", "LS", "NC", "total"]
    table.append_row("increase", increase["reeleitos"], increase["nao_eleitos"], increase["novos"], (increase["reeleitos"] + increase["nao_eleitos"] + increase["novos"]))
    table.append_row("maintained",same["reeleitos"], same["nao_eleitos"], same["novos"],(same["reeleitos"] + same["nao_eleitos"] + same["novos"]))
    table.append_row("decrease",decrease["reeleitos"], decrease["nao_eleitos"], decrease["novos"], (decrease["reeleitos"] + decrease["nao_eleitos"] + decrease["novos"]))
    table.append_row("total",(decrease["reeleitos"]+same["reeleitos"]+decrease["reeleitos"]), (decrease["nao_eleitos"]+same["nao_eleitos"]+decrease["nao_eleitos"]), (decrease["novos"]+same["novos"]+decrease["novos"]) )
    print(table)
Ejemplo n.º 2
0
    def text(self):
        totals = summary_template.format(
            self.compiled_result['counts']['total'],
            self.compiled_result['counts']['valid'],
            self.compiled_result['counts']['failed'],
            self.compiled_result['counts']['fatal']
        )

        ssl_info = 'No valid SSL certificate detected'
        if self.compiled_result['network']['ssl']:
            ssl_info = 'Valid SSL certificate detected'

        network = network_template.format(
            ssl_info,
            self.compiled_result['network']['average_ttl']
        )

        try:
            max_columns = int(subprocess.check_output(['stty', 'size']).split()[1])
        except Exception:
            max_columns = 80

        entities = ''

        for entity, messages in self.compiled_result['object_messages'].items():
            table = BeautifulTable(max_columns)
            table.column_headers = ['', 'severity', 'message', 'occurences']

            entity_list = ''

            message_key = 1
            for message in messages:
                message = self.compiled_result['object_messages'][entity][message]

                row = []

                row.append(message_key)
                row.append(message['severity'])
                row.append(message['message'])
                row.append(message['count'])

                for object in message['objects']:
                    entity_list += '[{}] {},\n'.format(message_key, object)

                table.append_row(row)
                message_key += 1

            entities += '# {}\n{}\n\nAffected Entities:\n\n{}\n\n'.format(entity, table, entity_list[:-2])

        return 'Validation Result:\n\n{}\n{}\n{}'.format(totals, network, entities[:-2])
Ejemplo n.º 3
0
def ejecutarAGEAC(_data, _target):
    _inicio = current_milli_time()
    _time_actual = _inicio
    #Realizo las 5 particiones con mezcla y semilla
    skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEMILLA)
    skf.get_n_splits(_data, _target)
    #recorro cada una de las
    sumatoriaClas = 0
    sumatoriaRed = 0
    sumatoriaAgregada = 0
    _cont = 1
    tabla = BeautifulTable()
    tabla.column_headers = ["Particion", "%cls", "%redu", "%agr", "tiempo"]
    for _train_index, _test_index in skf.split(_data, _target):
        #obtengo las particiones de test y train
        X_train, _X_test = _data[_train_index], _data[_test_index]
        y_train, _y_test = _target[_train_index], _target[_test_index]
        #obtengo los pèsos para esta particion
        _W = AGEAC(X_train, y_train)

        #obtengo las tasas  de evaular la solución
        tasa_clas, tasa_red, tasa_agr = evaluate(_W, _X_test, _y_test)
        time_anterior = _time_actual
        _time_actual = current_milli_time()
        sumatoriaClas += tasa_clas
        sumatoriaRed += tasa_red
        sumatoriaAgregada += tasa_agr
        tabla.append_row([
            _cont, tasa_clas, tasa_red, tasa_agr,
            ((_time_actual - time_anterior) / 1000.0)
        ])
        _cont += 1

    _final = current_milli_time()
    #calculo el tiempo de ejecucion
    diferencia = (_final - _inicio) / 1000.0
    #muestro los estadisticos
    tabla.append_row([
        "Media", sumatoriaClas / 5, sumatoriaRed / 5, sumatoriaAgregada / 5,
        (diferencia / 5)
    ])
    print(tabla)
Ejemplo n.º 4
0
    def __str__(self):

        atoms_str = BeautifulTable()
        atoms_str.numeric_precision = 4
        atoms_str.intersection_char = ''
        column_headers = ['Number', 'x', 'y', 'z']

        for i in self.atom_labels.keys():
            column_headers.append(i)

        atoms_str.column_headers = column_headers
        atom_sites_frac = self.atom_sites_frac

        for atom_idx in range(atom_sites_frac.shape[1]):

            row = [
                atom_idx, *(atom_sites_frac[:, atom_idx]),
                *[v[0][v[1]][atom_idx] for _, v in self.atom_labels.items()]
            ]
            prt(row, 'row')
            atoms_str.append_row(row)

        ret = ('{!s}-{!s} Bravais lattice + {!s}-atom motif\n\n'
               'Lattice parameters:\n'
               'a = {!s}\nb = {!s}\nc = {!s}\n'
               'α = {!s}°\nβ = {!s}°\nγ = {!s}°\n'
               '\nLattice vectors = \n{!s}\n'
               '\nLattice sites (fractional) = \n{!s}\n'
               '\nLattice sites (Cartesian) = \n{!s}\n'
               '\nAtoms (fractional coordinates of '
               'unit cell) = \n{!s}\n').format(
                   self.bravais_lattice.lattice_system,
                   self.bravais_lattice.centring_type,
                   self.motif['atoms']['sites'].shape[1],
                   self.bravais_lattice.a, self.bravais_lattice.b,
                   self.bravais_lattice.c, self.bravais_lattice.α,
                   self.bravais_lattice.β, self.bravais_lattice.γ,
                   self.bravais_lattice.vecs,
                   self.bravais_lattice.lattice_sites_frac,
                   self.bravais_lattice.lattice_sites, atoms_str)

        return ret
Ejemplo n.º 5
0
def hours_as_table(content, current_month, full, show_weekday):
    """
    Validates that you can actually use the configured project.
    """
    table = BeautifulTable()
    if full:
        column_headers = [
            "Date", "Hours", "Project", "Assigment Type", "Description"
        ]
    else:
        column_headers = ["Date", "Description"]

    if show_weekday:
        column_headers = ["Weekday"] + column_headers

    table.column_headers = column_headers

    rows = content.find(class_='tbl-respuestas').find_all('tr')

    for row in rows[:-1]:
        cols = row.find_all('td')
        if cols:
            date = cols[0].string if not current_month else cols[0].string[:2]
            if full:
                values = [
                    date, cols[1].string, cols[2].string, cols[3].string,
                    cols[4].string
                ]
            else:
                values = [date, cols[4].string]
            if show_weekday:
                weekday = datetime.strptime(cols[0].string,
                                            r'%d/%m/%Y').weekday()
                values = [WEEKDAYS[weekday]] + values
            table.append_row(values)

    if full:
        values = ["" for i in range(len(column_headers))]
        values[column_headers.index("Hours")] = rows[-1].find_all(
            'td')[1].string
        table.append_row(values)
    return table
Ejemplo n.º 6
0
    def Update_Row(self):
        """Launch a sequence to update a row chosen by the user

        Returns:
            [None]: If all went well it will return None, however it will display an error
        """
        try:
            modele_user = Users_modele()
            table_before = BeautifulTable(maxwidth=300)
            table_before.columns.header = self.aff_col

            modele_user.PK_user_id = self.vue_users.Row_getId()
            if modele_user.PK_user_id != False:
                cursor = self.DAO_users.Select_Rows(modele_user.PK_user_id)
                for row in cursor:
                    table_before.rows.append(row)
                self.vue_users.Display_Rows(table_before)

                confirmation = self.vue_users.getConfirmation(
                    modele_user.PK_user_id, 0)
                if confirmation == True:
                    row = self.vue_users.getRow(self.aff_col)
                    row[3] = self.hash_password(row[3])  #hash du mdp

                    modele_user.name = row[1]
                    modele_user.pseudonyme = row[2]
                    modele_user.password = row[3]

                    if row != None:
                        modification_reussie = self.DAO_users.Update_Row(
                            modele_user)
                        if modification_reussie == True:
                            self.vue_users.Display_BackToMenu()
                            return None
                    self.vue_users.Display_Alter_Error()
                else:
                    self.vue_users.AucuneActionEntreprise()
        except:
            self.vue_users.Display_Alter_Error()
Ejemplo n.º 7
0
    def execute(self):
        zlist = Zone.objects.all()
        table = BeautifulTable(default_padding=0)
        table.column_headers = ['Index', 'Zone Name']
        table.set_style(BeautifulTable.STYLE_COMPACT)
        table.columns.alignment = BeautifulTable.ALIGN_LEFT
        table.column_alignments['Index'] = BeautifulTable.ALIGN_RIGHT
        table.column_widths = [7, 44]
        table.columns.header.alignment = BeautifulTable.ALIGN_LEFT

        if not zlist:
            self.msg(f"No Zones to show!")
        else:
            for z in zlist:
                table.rows.append([
                    f'{z.id})',
                    f'{Colors.fg.CYAN}{z.name}{Colors.style.RESET_ALL}'
                ])

        self.msg(table)
Ejemplo n.º 8
0
def pert_table(file):
    data, standard_deviation = algo.pert(file)
    table = BeautifulTable()
    table.set_style(BeautifulTable.STYLE_BOX)
    # create table headers
    col_headers = [
        "Cinnost", "Zavislosti", "aij", "mij", "bij", "trvanie", "odchylka",
        "rozptyl"
    ]

    # Set column headers
    table.column_headers = col_headers

    for row in data:
        table.append_row(row)
    print(table)
    print("Smerodajna odchylka trvanie projektu q(Te)= {}".format(
        standard_deviation))

    PromptUtils(Screen()).enter_to_continue()
Ejemplo n.º 9
0
def show_play(board):
    """
    It prints a table using the library BeautifulTable.
    The values are filled with the board argument.
    ------
    :param board:  3x3 list.
                3 dimensions list with 3 elements each.
    ------
    :return: Print a table as a board.
    """

    print("The game now is:")
    table = BeautifulTable()
    table.column_headers = ["", "1", "2", "3"]
    table.append_row(["x", board[0][0], board[0][1], board[0][2]])
    table.append_row(["y", board[1][0], board[1][1], board[1][2]])
    table.append_row(["z", board[2][0], board[2][1], board[2][2]])

    print(table)
    print("")
Ejemplo n.º 10
0
def printfun(t_num):
    print("`````````````````````````````````````````````````````")
    table = BeautifulTable()
    if t_num == '1':
        t_name = "battle"
        table.columns.header = ["NAME", "DATE"]
        c.execute("select * from " + t_name)
        conn.commit()
        for row in c.fetchall():
            table.rows.append(row)
            #print(row)

    elif t_num == '2':
        t_name = "classes"
        table.columns.header = [
            "CLASS", "TYPE", " COUNTRY", "NO_GUNS", " BORE", " DISPLACEMENT"
        ]
        c.execute("select * from " + t_name)
        conn.commit()
        for row in c.fetchall():
            table.rows.append(row)
            #print(row)
    elif t_num == '3':
        t_name = "outcomes"
        table.columns.header = ["SHIP", " BATTLE", " RESULT"]
        c.execute("select * from " + t_name)
        conn.commit()
        for row in c.fetchall():
            table.rows.append(row)
            #print(row)
    elif t_num == '4':
        t_name = "ships"
        table.columns.header = ["SHIP_NAME", "CLASS", "LAUNCHED DATE"]
        c.execute("select * from " + t_name)
        conn.commit()
        for row in c.fetchall():
            table.rows.append(row)
            #print(row)
    print(table)
Ejemplo n.º 11
0
    def __str__(self):
        problems = self.problems
        concerned_data = self.data['result']['data']['content']
        submissions = {
            x['problemCode']: x['successfulSubmissions'] for x in concerned_data['problemsList']}
        for problem in problems:
            problem.submissions_count = submissions[problem.code]

        table = BeautifulTable()
        table.width_exceed_policy = BeautifulTable.WEP_WRAP
        # TODO: use map style.headers instead of str
        # requires change with beautifultable. we may try dev version
        # TODO: sort with submission
        # TODO add status with color code (AC, WA .. etc)
        table.column_headers = list(
            map(str, ['code', 'name', 'submissions']))
        for problem in problems:
            table.append_row(
                [
                    problem.code, problem.name, problem.submissions_count
                ]
            )
        table.sort('submissions', reverse=True)
        return str(table)
Ejemplo n.º 12
0
    def do_l(self, arg):
        res = self.my_bittrex.get_balances()
        res = res['result']
        btc_value = 0
        if arg:
            parts = arg.split()
            btc_value = parts[0]
        print("btc value is " + str(btc_value))
        # data = json.dumps(res)
        # print(type(res))
        # # data = json.load(res)
        # print(type(data))
        # df = pd.DataFrame(data) 
        # print(df)
        # print(res)
        # pp.pprint(res['result'])


        if res:
            table = BeautifulTable(max_width=150)
            table.numeric_precision = 10
            table.column_headers = ["Index","CurrencyLong","Currency","Available","Balance","Pending","TxFee","Last","btc_value"]

            index = 1
            for order in res:
                # print(order)
                if order['BitcoinMarket'] is not None and order['Balance']['Balance'] != 0:
                    # print("here")
                    table.append_row([
                        index,
                        order['Currency']['CurrencyLong'],
                        order['Currency']['Currency'],
                        order['Balance']['Available'],
                        order['Balance']['Balance'],
                        order['Balance']['Pending'],
                        order['Currency']['TxFee'],
                        float(order['BitcoinMarket']['Last']),
                        float(order['BitcoinMarket']['Last']) * float(order['Balance']['Balance'])
                    ])
                    index += 1

            print(table)
            # return table
        else:
            print("No Open Orders")
        print('done')
Ejemplo n.º 13
0
 def get_running_contests(self):
     logger.debug('get running contests')
     contests = get_data.running_contests(self)
     table = BeautifulTable()
     table.width_exceed_policy = BeautifulTable.WEP_WRAP
     # TODO: use map style.headers instead of str
     # requires change with beautifultable. we may try dev version
     table.column_headers = list(
         map(str, ['code', 'name', 'end', 'start']))
     for contest in contests:
         table.append_row(
             [
                 contest['code'], contest['name'],
                 str(contest['startDate']), str(contest['endDate'])
             ]
         )
     return table
Ejemplo n.º 14
0
    async def do_list_files(self, arg):
        try:
            file_list_dict = await self._peer.list_file()
        except TrackerNotConnectedError:
            print('Tracker is not connected, try \'connect <tracker_ip> <tracker_port>\' to connect.')
        except (ConnectionError, RuntimeError, IncompleteReadError):
            print('Error occured during communications with tracker, '
                  'try \'connect <tracker_ip> <tracker_port>\' to re-connect.')
        else:
            table = BeautifulTable()
            table.row_separator_char = ''

            for filename, fileinfo in file_list_dict.items():
                if table.column_count == 0:
                    table.column_headers = ['Filename'] + list(map(lambda x: x.capitalize(), tuple(fileinfo.keys())))
                table.append_row((filename,) + tuple(fileinfo.values()))
            print(table)
Ejemplo n.º 15
0
    def get_parse_table(self):
        count = len(self.parse_table)
        if count > 0:
            table = BeautifulTable()
            table._max_table_width = 200
            table.column_headers = [
                "     №     ", "        Stack         ", "     Relation    ",
                "         Input row           "
            ]
            for i in range(0, count):
                table.append_row([
                    self.parse_table[i].number, self.parse_table[i].stack,
                    self.parse_table[i].relation, self.parse_table[i].input_row
                ])
            return str(table)

        return ''
Ejemplo n.º 16
0
    def show_plz_table(self):
        count = len(self.plz_table)
        if count > 0:
            table = BeautifulTable()
            table._max_table_width = 200
            table.column_headers = [
                "    input     ", "        stack         ",
                "             output             "
            ]
            for i in range(0, count):
                table.append_row([
                    self.plz_table[i].input, self.plz_table[i].stack,
                    self.plz_table[i].output
                ])
            return str(table)

        return ''
Ejemplo n.º 17
0
    def showKanban(self):
        """
        render kanban
        https://beautifultable.readthedocs.io/en/latest/quickstart.html
        """
        table = BeautifulTable()
        table.set_style(BeautifulTable.STYLE_COMPACT)
        project = self.config.get("project")

        rows_qnt = 0

        groups_list = {}
        for group in self.statuses_groups.getKeys():
            groups_list[group] = []

        for group in self.statuses_groups.getKeys():
            status_list = self.statuses_groups[group]
            statuses_str = ','.join(str(e) for e in status_list)
            jql = "project = " + project + " and assignee=currentUser() and status in (" + statuses_str + ")"
            tasks_list = []
            for task in self.searchIssues(jql)['issues']:
                task_color = task['fields']['status']['statusCategory'][
                    'colorName']
                if task_color not in COLORS.keys():
                    task_color = 'white'
                tasks_list.append(
                    colored(task['key'], task_color, attrs=['bold']))

            groups_list[group] = tasks_list
            if len(tasks_list) > rows_qnt:
                rows_qnt = len(tasks_list)

        for index, group in enumerate(self.statuses_groups.getKeys()):
            tasks_list = groups_list[group]
            rows = []
            r = 0
            while r <= rows_qnt:
                task = tasks_list[r] if r < len(tasks_list) else ''
                rows.append(task)
                r += 1

            group = colored(group, 'white', attrs=['bold'])

            table.insert_column(index, group, rows)

        print(table)
Ejemplo n.º 18
0
    def tabular_show(self, log_tag=''):
        table = BeautifulTable()
        table_c = BeautifulTable()
        for key, color in zip(self.keys, self.colors):
            if self.counts[key] == 0:
                value = ''
            elif self.counts[key] == 1:
                value = self.values[key]
            else:
                value = self.values[key] / self.counts[key]
            key_c = key if color is None else colored(
                key, color, attrs=['bold'])
            table.append_row([key, value])
            table_c.append_row([key_c, value])

        def customize(table):
            table.set_style(BeautifulTable.STYLE_NONE)
            table.left_border_char = '|'
            table.right_border_char = '|'
            table.column_separator_char = '|'
            table.top_border_char = '-'
            table.bottom_border_char = '-'
            table.intersect_top_left = '+'
            table.intersect_top_mid = '+'
            table.intersect_top_right = '+'
            table.intersect_bottom_left = '+'
            table.intersect_bottom_mid = '+'
            table.intersect_bottom_right = '+'
            table.column_alignments[0] = BeautifulTable.ALIGN_LEFT
            table.column_alignments[1] = BeautifulTable.ALIGN_LEFT

        customize(table)
        customize(table_c)
        self.log_time(log_tag)
        self.debug(table)
        print(table_c)
Ejemplo n.º 19
0
    def table_lexes_to_string(collection_records_label) -> str:
        count = len(collection_records_label)
        if count > 0:
            table = BeautifulTable()
            table._max_table_width = 400
            table.column_headers = [
                "                Label code                 ",
                "                Label name               "
            ]
            for i in range(0, count):
                table.append_row([
                    collection_records_label[i].code,
                    collection_records_label[i].name
                ])

            return str(table)
        return ''
Ejemplo n.º 20
0
def table_print(name, array):
    table = BeautifulTable()
    table.set_style(BeautifulTable.STYLE_BOX)
    # Create array with aplhabet chars
    row_headers = [[string.ascii_uppercase[x] for x in range(array.shape[0])]]
    # Transpose to get collumn with chars
    row_headers = np.asarray(row_headers).T
    # Create array with table name + alphabet chars
    col_headers = [name] + [
        string.ascii_uppercase[x] for x in range(array.shape[0])
    ]
    # Set column headers
    table.column_headers = col_headers
    # Append first column with aplhabet chars
    array = np.hstack((row_headers, array))

    for row in array:
        print(row)
        print(type(row))
        table.append_row(row)
    print(table)
def ViewCourses(token):
    #connecting to db
    mydb = mysql.connector.connect(host="localhost",
                                   user="******",
                                   password="******",
                                   database="Course_registration")
    mycursor = mydb.cursor()

    #getting student's stream_id
    command1 = "SELECT Stream_id, Current_sem, Current_year FROM Student where Student_id = %s"
    mycursor.execute(command1, (token[0], ))
    result = mycursor.fetchall()
    stream_id = result[0][0]
    student_sem = result[0][1]
    student_year = result[0][2]

    #getting department offering above stream
    command2 = "SELECT Dept_name from Stream where Stream_id = %s"
    mycursor.execute(command2, (stream_id, ))
    result = mycursor.fetchall()
    dept_name = result[0][0]

    #getting all the courses offered by the above dept
    command3 = "SELECT Course_id, Course_name, Course_credits, Course_type, Lec, Tut, Lab, Total_seats from Course where Dept_name = %s and Course_year = %s and Course_sem = %s"
    mycursor.execute(command3, (dept_name, student_year, student_sem))
    result = mycursor.fetchall()

    #printing result
    table = BeautifulTable()
    table.columns.header = [
        "Course_id", "Course_name", "Course_credits", "Course_type", "Lec",
        "Tut", "Lab", "Total_seats"
    ]
    for x in result:
        table.rows.append(x)
    print(table)
    mycursor.close()
    mydb.close()
Ejemplo n.º 22
0
    def print_rules(self, attributes=('coverage', 'confidence', 'lift')):
        """Print the generated rules in a tabular format.

        Parameters
        ----------
        attributes : array_like
            pass
        """
        table = BeautifulTable()
        table.column_headers = (
            ['Antecedent', 'Consequent'] +
            list(attr.replace('_', ' ').title() for attr in attributes))

        table.column_alignments[0] = table.ALIGN_LEFT
        table.column_alignments[1] = table.ALIGN_LEFT
        for rule in self.rules:
            table.append_row([rule.antecedent2str(),
                              rule.consequent2str()] +
                             list(getattr(rule, attr) for attr in attributes))

        print(table)
Ejemplo n.º 23
0
def print_network_stats(free_ips):
    print("Subnet: \t/24")
    print("Used IP's: \t%s" % len(HONEYPOT_DICTS))
    print("Free IP's: \t%s" % len(free_ips))
    percentage_free = 100 * float(len(free_ips))/float(255)
    print("Percent Free: \t%d%%" % percentage_free)

    table = BeautifulTable()
    table.column_headers=["IP Address", "OS", "Port", "Protocol"]

    for _os in HONEYPOT_DICTS:
        first_row = True
        port_list = _os['ports']
        for port in port_list:
            if first_row:
                first_row = False
                table.append_row([_os['ip'], _os['os'], port['PORTID'], port['PROTOCOL']])
            else:
                table.append_row(["", "", port['PORTID'], port['PROTOCOL']])

    print(table)
Ejemplo n.º 24
0
    def Display_Rows(self):  #OK
        """Launch a sequence to display the table to the user
        """
        try:
            DAO_factureRow = FactureRow_DAO(self.cnx)
            cursor = DAO_factureRow.Select_Rows(self.id_facture)
            table = BeautifulTable(
                maxwidth=300
            )  #Préparation de l'affichage des lignes de façon organisée

            #On exécute la query et on y place tous ses éléments dans un module qui va gérer l'affichage
            table.columns.header = self.aff_col

            for row in cursor:
                table.rows.append(row)

            #Affichage de la table
            self.vue_factureRow.Display_Rows(table)
            self.Menu()
        except:
            return None
        finally:
            cursor.close()
Ejemplo n.º 25
0
def get_all_stocks():
    logging.info("Getting all stocks")
    url = base_url + "/stocks"
    r = requests.get(url, cookies=cookies)

    if r.status_code == 200:
        data = json.loads(r.text)
        table = BeautifulTable()

        for item in data:
            table.rows.append([
                item['id'], item['company'], item['name'], item['code_name'],
                item['current_price'], item['available_stocks'],
                item['total_stocks'], item['about'], item['address']
            ])

        table.columns.header = [
            "ID", "Company ID", "Name", "Code Name", "Current Price",
            "Avilable Stocks", "Total Stocks", "About", "Address"
        ]
        print(table)
    else:
        print("Error while getting the stocks")
Ejemplo n.º 26
0
    def Create_Row(self):
        """Launch a sequence to create a row in the table

        Returns:
            [None]: If all went well it will return None, however it will display an error
        """
        try:
            DAO_factureRow = FactureRow_DAO(self.cnx)
            table_before = BeautifulTable(maxwidth=300)
            table_before.columns.header = self.aff_col

            cursor = DAO_factureRow.Select_Rows(self.id_facture)
            for row in cursor:
                table_before.rows.append(row)
            self.vue_factureRow.Display_Rows(table_before)
            confirmation = self.vue_factureRow.getConfirmation(
                self.id_facture, 2)
            if confirmation == True:
                row = self.vue_factureRow.getRow(self.aff_col,
                                                 self.table_drugs)

                modele_facture_row = Facture_row_modele()
                modele_facture_row.FK_facture_id = self.id_facture
                modele_facture_row.item_count = row[2]
                modele_facture_row.FK_drug_id = row[1]

                if row != None:
                    creation_reussie = DAO_factureRow.Insert_Row(
                        modele_facture_row)
                    if creation_reussie == True:
                        self.vue_factureRow.Display_BackToMenu()
                        return None
                self.vue_factureRow.Display_Create_Error()
            else:
                self.vue_factureRow.AucuneActionEntreprise()
        except:
            self.vue_factureRow.Display_Create_Error()
Ejemplo n.º 27
0
    def do_grep_regs(self, arg):
        '''
        Search all process registry requests by key name or value
        Ex:  grep_regs *MACHINE\SYSTEM*
        '''
        if (self.sqlite_conn is None):
            sys.stderr.write(
                "Please load a database first with the load_db command\n")
            return

        if not arg:
            if self.process_context:
                arg = self.process_context
            else:
                sys.stderr.write(
                    "Please specify a process id or descriptor address\n")
                return

        arg = arg.strip()
        cursor = self.sqlite_conn.cursor()

        table = BeautifulTable(max_width=160)
        table.column_headers = [
            "Time", "PID", "Process Descriptor", "Image", "Operation", "Key",
            "Aux Data"
        ]

        regs = cursor.execute("SELECT time, pid, desc_address, COALESCE(image, ''), \
            op, name, COALESCE(data, '') FROM operation \
            JOIN resource ON r_id = resource.id JOIN process ON p_id = process.id \
            WHERE (name LIKE '%s' OR data LIKE '%s') AND type = 'R'" \
            % (arg.replace("*", "%"), arg.replace("*", "%")))

        for rowIni in regs:
            table.append_row(rowIni)

        print(table)
        print("Total:  %d\n" % len(table))
        table.clear()
Ejemplo n.º 28
0
    def Display_Rows(self):
        """
        launch display row sequence
        """
        try:
            DAO_facture = Facture_DAO(self.cnx)  #Création du modèle
            vue_facture = Facture_vue()
            cursor = DAO_facture.Select_Rows()
            table = BeautifulTable(
                maxwidth=300
            )  #Préparation de l'affichage des lignes de façon organisée

            #On exécute la query et on y place tous ses éléments dans un module qui va gérer l'affichage
            table.columns.header = self.aff_col

            for row in cursor:
                table.rows.append(row)

            #Affichage de la table
            vue_facture.Display_Rows(table)
        except:
            vue_facture.Display_Select_Error()
        finally:
            cursor.close()
Ejemplo n.º 29
0
 def __init__(self):
     import os
     from beautifultable import BeautifulTable
     table = BeautifulTable(max_width=200)
     data = []
     rows = set()
     all_colors = set()
     directory = "TestImages/"
     for file in os.listdir(directory):
         if file.endswith(".jpg"):
             file_settings = file[:-4].split("_")
             predicted_color = ImageProcessor(os.path.join(
                 directory, file)).get_avg_pixel_color()[1]
             all_colors.add(file_settings[0])
             rows.add(int(file_settings[2][0]))
             # distance, direction, real color, predicted color
             data.append((file_settings[2], file_settings[1],
                          file_settings[0], predicted_color))
     table.column_headers = [" "] + list(all_colors)
     second_row = [" "]
     columns = {}
     for color in table.column_headers[1:]:
         columns[color] = {
             "direct": [""] * (max(rows) + 1),
             "indirect": [""] * (max(rows) + 1)
         }
         second_row.append("direct | indirect")
     table.append_row(second_row)
     for distance, direction, real_color, predicted_color in data:
         columns[real_color][direction][int(distance[0])] = predicted_color
     rows = sorted(rows)
     for i, distance in enumerate(rows):
         row = [str(distance) + " m"]
         for color in table.column_headers[1:]:
             row.append(columns[color]["direct"][rows[i]] + " | " +
                        columns[color]["indirect"][rows[i]])
         table.append_row(row)
     print(table)
Ejemplo n.º 30
0
def write_performance_metrics(cms, names, aurocs, man_aurocs, auprcs, man_auprcs, indet_array, threshold_array, excluded_algs, noshow):
	from beautifultable import BeautifulTable
	table = BeautifulTable(max_width=300)
	table.append_column(' ', ['sensitivity', 'specificity', 'PPV', 'NPV', 'accuracy', 'Manual AUROC', 'Manual AUPRC', '% indet', 'Dec. Thresh. (%)'])
	count = 0
	for cm in cms:
		if (names[count] in excluded_algs):
			print('Did not include ' + str(names[count]) + 'results!')
			count += 1 
			continue 
		if (names[count] in noshow):
			#print('Did not show ' + str(names[count]) + 'results!')
			count += 1 
			continue      
#		if (names[count] == 'APRI' or names[count] == 'FIB4'):
#        		count += 1
#        		continue
		#if (names[count] != 'ENS1' and names[count] != 'ENS2' and names[count] != 'ENS3'):
        #		count += 1
        #		continue
		tot = cm[0,0] + cm[0,1] + cm[1,0] + cm[1,1]
		tp = cm[1,1]
		fp = cm[0,1]
		tn = cm[0,0]
		fn = cm[1,0]

		accuracy = 100*(tp + tn)/(tot)
		precision = 100*tp/(tp + fp)
		negPredVal = 100*tn/(tn + fn)
		sensitivity = 100*tp/(tp + fn)
		falseNegRate = 100*fn/(fn + tp)
		specificity = 100*tn/(tn + fp)
		falsePosRate = 100*fp/(fp + tn)
		f1 = 100*2*precision*sensitivity/(precision + sensitivity)
		auc = aurocs[count]
		man_aucs = man_aurocs[count]
		prc = auprcs[count]
		man_prcs = man_auprcs[count]
		indt = indet_array[count]
		thresh = threshold_array[count]
		table.append_column(names[count], [(' %0.1f' % sensitivity), (' %0.1f' % specificity), (' %0.1f' % precision), (' %0.1f' % negPredVal), (' %0.1f' % accuracy), (' %0.1f' % (100*man_aucs)), (' %0.1f' % (100*man_prcs)), (' %0.1f' % (100*indt)), thresh])
		count += 1
	print(table)
Ejemplo n.º 31
0
    def do_oh(self, arg):
        res = self.my_bittrex.get_order_history()
        res = res['result']
        # print(res)
        # pp.pprint(res['result'])
        if res:
            table = BeautifulTable(max_width=170)
            table.numeric_precision = 10
            # table._width_exceed_policy = BeautifulTable.WEP_WRAP
            table.column_headers = ["Index","Exchange"
            # ,"TimeStamp"
            , "OrderType", "Quantity", "PricePerUnit","%5","%10","%15","%20","%30","%50", "Commission", "Price"
            # ,"Btcmults"
            ]

            index = 1
            for order in res:
                table.append_row([
                    index,
                    order['Exchange'],
                    # order['TimeStamp'],
                    order['OrderType'],
                    order['Quantity'],
                    order['PricePerUnit'],
                    order['PricePerUnit'] * 1.05,
                    order['PricePerUnit'] * 1.10,
                    order['PricePerUnit'] * 1.15,
                    order['PricePerUnit'] * 1.20,
                    order['PricePerUnit'] * 1.30,
                    order['PricePerUnit'] * 1.50,
                    # "{:.8f}".format(float(self.my_bittrex.get_ticker(order['Exchange'])['result']['Last'])),
                    "{:.6f}".format(float(order['Commission'])),
                    "{:.6f}".format(float(order['Price']))
                    # str(order['Price']*1.05) + "," + str(order['Price']*1.10 )+  "," + str(order['Price']*1.15)
                ])
                index += 1

            print(table)
            # return table
        else:
            print("No Open Orders")
        print('done')
Ejemplo n.º 32
0
    def table_lexes_to_string(collection_records_con) -> str:
        print('tyt')
        count = len(collection_records_con)
        print(count)
        if count > 0:
            table = BeautifulTable()
            table._max_table_width = 400
            table.column_headers = [
                "       Constant code        ", "       Constant name      ",
                "        Constant type        "
            ]
            for i in range(0, count):
                table.append_row([
                    collection_records_con[i].code,
                    collection_records_con[i].name,
                    collection_records_con[i].type
                ])

            return str(table)
        return ' '
Ejemplo n.º 33
0
        z1 = initialization.spectral(k, G)
        Z1 = eclust.ztoZ(z1)
        
        # Hartigan's method
        zh = eclust.energy_hartigan(k, G, Z0)
        table[i,1] = accuracy(z, zh)
        
        zh = eclust.energy_hartigan(k, G, Z1)
        table[i,2] = accuracy(z, zh)
    
        # standard k-means
        km = KMeans(2)
        zh = km.fit_predict(Y)
        table[i, 3] = accuracy(z, zh)

        # GMM
        gmm = GMM(2)
        gmm.fit(Y)
        zh = gmm.predict(Y)
        table[i, 4] = accuracy(z, zh)
    
    t = BeautifulTable()
    t.column_headers = ["Method", "Mean Accuracy", "Std Error"]
    t.append_row(["Energy1D", table[:,0].mean(), sem(table[:,0])])
    t.append_row(["H-Energy++:", table[:,1].mean(), sem(table[:,1])])
    t.append_row(["H-Energy-top:", table[:,2].mean(), sem(table[:,2])])
    t.append_row(["k-means:", table[:,3].mean(), sem(table[:,3])])
    t.append_row(["GMM:", table[:,4].mean(), sem(table[:,4])])
    print t
    
Ejemplo n.º 34
0
    X, z = data.multivariate_lognormal([m1, m2], [s1, s2], [n1, n2])
    k = 2

    def rho(x,y):
        norm = np.power(np.linalg.norm(x-y), 1)
        return norm
    
    G = kernel_matrix(X, rho)
    
    # initialization
    mu0, z0 = initialization.kmeanspp(k, X, ret='both')
    Z0 = ztoZ(z0)
    z1 = initialization.spectral(k, G)
    Z1 = ztoZ(z1)

    t = BeautifulTable()
    t.column_headers = ["Method", "Accuracy", "Objective", "Exec Time"]
    
    start = timer()
    zh = energy_clustering_brute(k, G, Z0)
    end = timer()
    Zh = ztoZ(zh)
    t.append_row(["E-clustering brute", metric.accuracy(z, zh), 
                  objective(Zh, G), end-start])
    
    start = timer()
    zh = energy_hartigan(k, G, Z0)
    end = timer()
    Zh = ztoZ(zh)
    t.append_row(["E-H-clustering++", metric.accuracy(z, zh), 
                  objective(Zh, G), end-start])
Ejemplo n.º 35
0
    def select(self, publications: List[Publication]) -> Publication:
        """
        Print the search results and asks the user to choose one to download.

        :param publications: list of Publication
        :returns: a Publication
        """

        preferred_order = [
            'id', 'title', 'authors', 'pages', 'extension', 'size', 'series',
            'publisher', 'lang', 'isbn'
        ]

        unsorted_headers, rows = Mirror.get_headers_values(publications)
        # sort the headers by preferred order
        sorted_headers = []
        for header in preferred_order:
            if header in unsorted_headers:
                sorted_headers.append(header)
                unsorted_headers.remove(header)
        # alphabetize the rest
        sorted_headers += sorted(unsorted_headers)

        term_c, term_r = os.get_terminal_size(0)
        table = BeautifulTable(
            default_alignment=BeautifulTable.ALIGN_LEFT,
            max_width=term_c - 1
        )
        table.column_headers = sorted_headers
        table.left_border_char = ''
        table.right_border_char = ''
        table.top_border_char = '━'
        table.bottom_border_char = ' '
        table.header_separator_char = '━'
        table.row_separator_char = '─'
        table.intersection_char = '┼'
        table.column_separator_char = '│'

        # build a table using order of sorted_headers and blank out missing data
        for row in rows:
            expanded_row = []
            for key in sorted_headers:
                if key in row.keys():
                    if type(row[key]) is list:
                        expanded_row.append(','.join(row[key]))
                    else:
                        expanded_row.append(row[key])
                else:
                    expanded_row.append('')
            table.append_row(expanded_row)

        print(table)

        while True:
            try:
                choice = input('Choose publication by ID: ')
                publications = [p for p in publications if p.id == choice]
                if not publications:
                    raise ValueError
                else:
                    return publications[0]
            except ValueError:
                print('Invalid choice. Try again.')
                continue
            except (KeyboardInterrupt, EOFError) as e:
                print(e)
                sys.exit(1)
            break
Ejemplo n.º 36
0
import requests
import time
from beautifultable import BeautifulTable
count = raw_input('Enter number of URLs to test:')
print count
timeO = raw_input('Enter threashold time in seconds:')
print timeO
urls = []
for i in range(int(count)):
        temp = raw_input('Enter URL:')
        print temp
        urls.append(temp)
j = 0
k = 0
table = BeautifulTable()
table.column_headers = ["Current Time Stamp", "Status", "URL","Response Time","Reason For Failure"]
while j < len(urls):
        ts = time.time()
        try:
                response = requests.get(urls[j], timeout=float(timeO))
                response.raise_for_status()
                table.append_row([ts,response.status_code, urls[j], response.elapsed.total_seconds(), "NA"])
                j += 1
        except requests.exceptions.ConnectionError as e:
                k += 1
                print(k)
                if (k>=3):
                        #table.append_row([ts,"Connection Exception", urls[j], "0", e])
                        table.append_row([ts,"Connection Exception", urls[j], time.time() - ts, e])
                        k = 0
                        j += 1