Report overall results

        Returns
        -------
        str
            result report in string format
482926
def result_report_overall(self):
        

        results = self.results_overall_metrics()

        output = self.ui.section_header('Overall metrics (micro-average)', indent=2) + '\n'

        if results['f_measure']:
            output += self.ui.line('F-measure', indent=2) + '\n'
            output += self.ui.data(field='F-measure (F1)', value=float(results['f_measure']['f_measure']) * 100,
                                   unit='%', indent=4) + '\n'
            output += self.ui.data(field='Precision', value=float(results['f_measure']['precision']) * 100,
                                   unit='%', indent=4) + '\n'
            output += self.ui.data(field='Recall', value=float(results['f_measure']['recall']) * 100,
                                   unit='%', indent=4) + '\n'

        if results['error_rate']:
            output += self.ui.line('Error rate', indent=2) + '\n'
            output += self.ui.data(field='Error rate (ER)', value=float(results['error_rate']['error_rate']),
                                   indent=4) + '\n'
            output += self.ui.data(field='Substitution rate', value=float(results['error_rate']['substitution_rate']),
                                   indent=4) + '\n'
            output += self.ui.data(field='Deletion rate', value=float(results['error_rate']['deletion_rate']),
                                   indent=4) + '\n'
            output += self.ui.data(field='Insertion rate', value=float(results['error_rate']['insertion_rate']),
                                   indent=4) + '\n'

        if results['accuracy']:
            output += self.ui.line('Accuracy', indent=2) + '\n'
            output += self.ui.data(field='Sensitivity', value=float(results['accuracy']['sensitivity']*100),
                                   unit='%', indent=4) + '\n'
            output += self.ui.data(field='Specificity', value=float(results['accuracy']['specificity'] * 100),
                                   unit='%', indent=4) + '\n'
            output += self.ui.data(field='Balanced accuracy', value=float(results['accuracy']['balanced_accuracy'] * 100),
                                   unit='%', indent=4) + '\n'
            output += self.ui.data(field='Accuracy', value=float(results['accuracy']['accuracy'] * 100),
                                   unit='%', indent=4) + '\n'

        return output
1279868
def all_to_str(self):
        
        def stringify(x):
            # float --> string,
            # truncating floats like 3.0 --> 3
            if isinstance(x, float):
                if x.is_integer():
                    #print('{} --> {}'.format(x, str(x).rstrip('0').rstrip('.')))
                    return str(x).rstrip('0').rstrip('.')
                return(str(x))
            # keep strings as they are,
            # unless it is a string like "3.0",
            # in which case truncate that too
            if isinstance(x, str):
                try:
                    float(x)
                    if x.endswith('0'):
                        if x.rstrip('0').endswith('.'):
                            #print('{} --> {}'.format(x, x.rstrip('0').rstrip('.')))
                            return x.rstrip('0').rstrip('.')
                except (ValueError, TypeError):
                    pass
            # integer --> string
            if isinstance(x, int):
                return str(x)
            # if it is not int/str/float, just return as is
            return x

        def remove_extra_digits(x, prog):
            """
            Remove extra digits
            x is a string,
            prog is always the following '_sre.SRE_Pattern':
            prog = re.compile("\d*[.]\d*([0]{5,100}|[9]{5,100})\d*\Z").
            However, it is compiled outside of this sub-function
            for performance reasons.
            """
            if not isinstance(x, str):
                return x
            result = prog.match(x)
            if result:
                decimals = result.string.split('.')[1]
                result = result.string
                if decimals[-3] == '0':
                    result = x[:-2].rstrip('0')
                if decimals[-3] == '9':
                    result = x[:-2].rstrip('9')
                    try:
                        last_digit = int(result[-1])
                        result = result[:-1] + str(last_digit + 1)
                    except ValueError:
                        result = float(result[:-1]) + 1
                #if result != x:
                #    print('changing {} to {}'.format(x, result))
                return result
            return x

        for col in self.df.columns:
            self.df[col] = self.df[col].apply(stringify)

        prog = re.compile("\d*[.]\d*([0]{5,100}|[9]{5,100})\d*\Z")
        for col in self.df.columns:
            self.df[col] = self.df[col].apply(lambda x: remove_extra_digits(x, prog))
1259182
def _sec_to_str(t):
    
    from functools import reduce
    return "%d:%02d:%02d.%02d" % \
        reduce(lambda ll, b: divmod(ll[0], b) + ll[1:],
               [(t*100,), 100, 60, 60])
184912
def results(self):
        

        results = {
            'overall': self.results_overall_metrics(),
            'class_wise': self.results_class_wise_metrics(),
            'class_wise_average': self.results_class_wise_average_metrics()
        }

        return results
903202
def output(results_dir, config, parent='../../'):
    
    start = time.time()
    print("Compiling results...")
    results_dir = os.path.abspath(results_dir)
    results = ReportResults(config['run_time'], config['results_ts_interval'])
    results.compile_results()
    print("Results compiled in {} seconds\n".format(time.time() - start))

    if results.total_transactions == 0:
        print("No results, cannot create report")
        return False

    print_infos(results)

    data = {
        'report': results,
        'run_time': config['run_time'],
        'ts_interval': config['results_ts_interval'],
        'turrets_config': results.turrets,
        'results': {"all": results.main_results, "timers": results.timers_results}
    }

    print("Generating graphs...")
    partial = time.time()
    generate_graphs(results.main_results, 'All_Transactions', results_dir)

    for key, value in results.timers_results.items():
        generate_graphs(value, key, results_dir)
    print("All graphs generated in {} seconds\n".format(time.time() - partial))

    write_template(data, results_dir, parent)
    print("Full report generated in {} seconds".format(time.time() - start))
    return True
706116
def get_report(self):
    
    ostr = ''
    ostr += "Nodes: "+str(len(self.__nodes.keys()))+"\n"
    ostr += "Edges: "+str(len(self.__edges.keys()))+"\n"
    return ostr
745899
def as_strings(self):
        """"""
        if self.value == '' or self.value is None:
            return '{0};\n'.format(self.name)
        if '"' not in self.value and (';' in self.value or '#' in self.value):
            return '{0} "{1}";\n'.format(self.name, self.value)
        return '{0} {1};\n'.format(self.name, self.value)
284033
def format(self, result):
        
        m = self.meta
        lines = ['-' * len(self.TITLE),
                 self.TITLE,
                 '-' * len(self.TITLE),
                 "Compared: {db1} <-> {db2}".format(**m),
                 "Filter: {filter}".format(**m),
                 "Run time: {start_time} -- {end_time} ({elapsed:.1f} sec)".format(**m),
                 ""]
        for section in result.keys():
            lines.append("* " + section.title())
            indent = " " * 4
            if len(result[section]) == 0:
                lines.append("{}EMPTY".format(indent))
            else:
                keyset, maxwid = self.result_subsets(result[section])
                for columns in keyset:
                    ocol = self.ordered_cols(columns, section)
                    mw = maxwid[columns]
                    mw_i = [columns.index(c) for c in ocol]  # reorder indexes
                    fmt = '  '.join(["{{:{:d}s}}".format(mw[i]) for i in mw_i])
                    lines.append("")
                    lines.append(indent + fmt.format(*ocol))
                    lines.append(indent + '-_' * (sum(mw)/2 + len(columns)))
                    rows = result[section]
                    self.sort_rows(rows, section)
                    for r in rows:
                        key = tuple(sorted(r.keys()))
                        if key == columns:
                            values = [str(r[k]) for k in ocol]
                            lines.append(indent + fmt.format(*values))
        return '\n'.join(lines)
143928
def get_tabular_str(self):
        
        hsp_string = ""

        try:
            hsp_list = [
                {"length": self.align_length},
                {"e-value": self.expect},
                {"score": self.score},
                {"identities": self.identities},
                {"positives": self.positives},
                {"bits": self.bits},
                {"query start": self.query_start},
                {"query end": self.query_end},
                {"subject start": self.sbjct_start},
                {"subject end": self.sbjct_end},
            ]

            for h in hsp_list:
                for k, v in h.items():
                    hsp_string += "{}\t{}\n".format(k, v)
        except:
            pass

        return hsp_string
1203864
def _extract(self, raw: str, station: str = None) -> str:
        
        resp = parsexml(raw)
        try:
            report = resp['response']['data'][self.rtype.upper()]
        except KeyError:
            raise self.make_err(raw)
        # Find report string
        if isinstance(report, dict):
            report = report['raw_text']
        elif isinstance(report, list) and report:
            report = report[0]['raw_text']
        else:
            raise self.make_err(raw, '"raw_text"')
        # Remove excess leading and trailing data
        for item in (self.rtype.upper(), 'SPECI'):
            if report.startswith(item + ' '):
                report = report[len(item) + 1:]
        return report
1267669
def get_str(cls, result_type):
        
        if result_type == cls.ALARM:
            return "Alarm"
        elif result_type == cls.LOG:
            return "Log Message"
        elif result_type == cls.ERROR:
            return "Error Message"
        elif result_type == cls.HOST_DETAIL:
            return "Host Detail"
        else:
            assert False, "Erroneous result type {0}.".format(result_type)
788174
def formatted_str(self, format):
        
        assert(format in ('json', 'csv'))
        ret_str_list = []
        for rec in self._records:
            if format == 'json':
                ret_str_list.append('{')
                for i in xrange(len(rec)):
                    colname, colval = self._rdef[i].name, rec[i]
                    ret_str_list.append('"%s":"%s"' % (colname, str(colval).replace('"', r'\"')))
                    ret_str_list.append(',')
                ret_str_list.pop()  # drop last comma
                ret_str_list.append('}%s' % (os.linesep))
            elif format == 'csv':
                for i in xrange(len(rec)):
                    colval = rec[i]
                    ret_str_list.append('"%s"' % (str(colval).replace('"', r'\"')))
                    ret_str_list.append(',')
                ret_str_list.pop()  # drop last comma
                ret_str_list.append('%s' % (os.linesep))
            else:
                assert(False)
        return ''.join(ret_str_list)
371162
private List<String> formatResult(Result result, Server server) {
		List<String> resultStrings = new LinkedList<>();

		if (result.getValuePath().isEmpty()) {
			processOneMetric(resultStrings, server, result, result.getValue(), null, null);
		} else {
			processOneMetric(resultStrings, server, result, result.getValue(), tagName, StringUtils.join(result.getValuePath(), '.'));
		}
		return resultStrings;
	}
305514
def format_response(self, data):
        
        self.count = self.max_count

        return OrderedDict([
            ('highest_count', self.max_count),
            ('overall_total', self.total),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('results', data)
        ])
1172351
def string_result(result, func, arguments):
    
    if result:
        # make a python string copy
        s = bytes_to_str(ctypes.string_at(result))
        # free original string ptr
        libvlc_free(result)
        return s
    return None
580168
def str(self,local=False,ifempty=None):
        
        ts = self.get(local)
        if not ts: return ifempty
        return ts.strftime('%Y-%m-%d %H:%M:%S')
312284
def format_result(result):
    """"""
    instance = None
    error = None

    if result["instance"] is not None:
        instance = format_instance(result["instance"])

    if result["error"] is not None:
        error = format_error(result["error"])

    result = {
        "success": result["success"],
        "plugin": format_plugin(result["plugin"]),
        "instance": instance,
        "error": error,
        "records": format_records(result["records"]),
        "duration": result["duration"]
    }

    if os.getenv("PYBLISH_SAFE"):
        schema.validate(result, "result")

    return result