def print_table(self,
                    table_style=TableStyle.UNICODE,
                    local_src=LocalFlag.BOTH,
                    local_dst=LocalFlag.BOTH,
                    nat=NatFlag.ALL,
                    projection=[],
                    aliases={}):
        """
        Print the table showing the synthesis

        Args:
            table_style (TableStyle): select the style of the table
            local_src (LocalFlag): hide local addresses if explicitly removed from ranges in the source IP
            local_dst (LocalFlag): hide local addresses if explicitly removed from ranges in the destination IP
            nat (NatFlag): show only nat or filter rules
        """
        rules = self.get_rules()
        hide_src = local_src == LocalFlag.NOLOCAL
        hide_dst = local_dst == LocalFlag.NOLOCAL
        hide_nats = nat == NatFlag.FILTER
        hide_filters = nat == NatFlag.NAT
        table_printer.print_table(
            rules,
            table_style, [ipaddr.IPv4Address(a) for a in self.firewall.locals],
            hide_src,
            hide_dst,
            hide_nats,
            hide_filters,
            projection,
            aliases=aliases)
def balance_display_loop(start_balance, interest_rate, num_months):
    balance = start_balance
    data = [("Months", "Balance")] # table header

    for n in range(1, num_months+1):
        balance *= (1 + interest_rate)
        data += [(n, "$"+format(balance, ".2f"))]

    print_table(data, options={'col_align': {1: '^', 2: '>'}})
def main():
    TAX_RATE = 0.0825
    bill_with_tax = get_float("Enter the bill with tax: $", limit=(1, 9e9))

    data = [("Tip %", "Total Due")] # table header

    for tip_rate in [0.100, 0.125, 0.150, 0.175, 0.200, 0.225, 0.250]:
        total = get_total_due(bill_with_tax, TAX_RATE, tip_rate)
        data += [ ( format(tip_rate * 100, '.2f'), format(total, ',.2f') ) ]

    print_table(data, options={'col_align': {1: '^', 2: '>'}})
    def do_result(self, args):
        """Print the current query result.

        Prints a table with the query result, each column
        corresponding to a result. The query that is printed along
        with the result.

        If the verbose_results config parameter is set (default: off),
        the similarities for each attribute is shown after the value
        in the form (normalised/weighed).

        If adaptation is turned on (which is the default; turn it off
        with 'config set adapt 0'), an adapted version of the best
        result is shown along with the results if adaptation is
        possible. Adaptation is possible if any of the parameters of
        the query are adaptable, and the query value differs from the
        value of the best result.

        No adaptation is done if the adapted result is worse (i.e. has
        a lower similarity) than the best query match. This can happen
        if the adjusted attribute is part of the query.

        Note that the query shown in the result can differ from the
        current one, if the query has been altered and not rerun (by
        default, the query is re-run whenever it is altered, but this
        can be changed with the 'auto_run' parameter."""
        if not self.result:
            print ("No result.")
            return
        query,result = self.result
        header = ["Attribute", "Query"]
        results = [query]
        add = 1
        for i,(sim,res) in enumerate(result):
            if sim == 'adapted':
                header.append("Adapted result (sim. %.3f)" % query.similarity(res))
                add = 0
            else:
                header.append("Result %d (sim. %.3f)" % (i+add, sim))
            if self.config['verbose_results']:
                r = {}
                for k,v in res.items():
                    if k in query:
                        s = query[k].similarity(v)
                        w = query[k].weight
                    else:
                        s = 1.0
                        w = 1.0
                    r[k] = "%s (%.2f/%.2f)" % (v, s/w, s)
                results.append(r)
            else:
                results.append(res)
        print_table((results,header))
Example #5
0
    def do_result(self, args):
        """Print the current query result.

        Prints a table with the query result, each column
        corresponding to a result. The query that is printed along
        with the result.

        If the verbose_results config parameter is set (default: off),
        the similarities for each attribute is shown after the value
        in the form (normalised/weighed).

        If adaptation is turned on (which is the default; turn it off
        with 'config set adapt 0'), an adapted version of the best
        result is shown along with the results if adaptation is
        possible. Adaptation is possible if any of the parameters of
        the query are adaptable, and the query value differs from the
        value of the best result.

        No adaptation is done if the adapted result is worse (i.e. has
        a lower similarity) than the best query match. This can happen
        if the adjusted attribute is part of the query.

        Note that the query shown in the result can differ from the
        current one, if the query has been altered and not rerun (by
        default, the query is re-run whenever it is altered, but this
        can be changed with the 'auto_run' parameter."""
        if not self.result:
            print "No result."
            return
        query,result = self.result
        header = ["Attribute", "Query"]
        results = [query]
        add = 1
        for i,(sim,res) in enumerate(result):
            if sim == 'adapted':
                header.append("Adapted result (sim. %.3f)" % query.similarity(res))
                add = 0
            else:
                header.append("Result %d (sim. %.3f)" % (i+add, sim))
            if self.config['verbose_results']:
                r = {}
                for k,v in res.items():
                    if k in query:
                        s = query[k].similarity(v)
                        w = query[k].weight
                    else:
                        s = 1.0
                        w = 1.0
                    r[k] = "%s (%.2f/%.2f)" % (v, s/w, s)
                results.append(r)
            else:
                results.append(res)
        print_table(results,header)
    def do_config(self, args):
        """View or set configuration variables.

        config [show]              Show current config.
        config set <key> <value>   Set <key> to <value>.

        Configuration keys:
        adapt:                     Whether or not to adapt the best case if not a perfect match.
        auto_display:              Automatically display results after running query.
        auto_run:                  Automatically run query when it changes.
        retrieve:                  How many cases to retrieve when running queries.
        verbose_results:           Show similarities (normalised/weighed) for each attribute."""
        if args in ('', 'show'):
            print ("Current config:")
            print_table([self.config], ['Key', 'Value'])
        elif args.startswith('set'):
            parts = args.split(None, 2)
            if len(parts) < 3:
                print ("Usage: config set <key> <value>.")
                return
            key,value = parts[1:3]
            if not key in self.config:
                print( "Unrecognised config key: '%s'" )% key
            try:
                if type(self.config[key]) in (int, float):
                    self.config[key] = type(self.config[key])(value)
                elif type(self.config[key]) == bool:
                    if value.lower().strip() in ("1", "t", "y", "yes", "true"):
                        self.config[key] = True
                    elif value.lower().strip() in ("0", "f", "n", "no", "false"):
                        self.config[key] = False
                    else:
                        raise ValueError
            except ValueError:
                print ("Invalid type for key %s: '%s'") % (key,value)
        else:
            print ("Unrecognised argument.")
            self.help_config()
Example #7
0
    def do_config(self, args):
        """View or set configuration variables.

        config [show]              Show current config.
        config set <key> <value>   Set <key> to <value>.

        Configuration keys:
        adapt:                     Whether or not to adapt the best case if not a perfect match.
        auto_display:              Automatically display results after running query.
        auto_run:                  Automatically run query when it changes.
        retrieve:                  How many cases to retrieve when running queries.
        verbose_results:           Show similarities (normalised/weighed) for each attribute."""
        if args in ('', 'show'):
            print "Current config:"
            print_table([self.config], ['Key', 'Value'])
        elif args.startswith('set'):
            parts = args.split(None, 2)
            if len(parts) < 3:
                print "Usage: config set <key> <value>."
                return
            key,value = parts[1:3]
            if not key in self.config:
                print "Unrecognised config key: '%s'" % key
            try:
                if type(self.config[key]) in (int, float):
                    self.config[key] = type(self.config[key])(value)
                elif type(self.config[key]) == bool:
                    if value.lower().strip() in ("1", "t", "y", "yes", "true"):
                        self.config[key] = True
                    elif value.lower().strip() in ("0", "f", "n", "no", "false"):
                        self.config[key] = False
                    else:
                        raise ValueError
            except ValueError:
                print "Invalid type for key %s: '%s'" % (key,value)
        else:
            print "Unrecognised argument."
            self.help_config()
    def print_table_no_duplicates(self):
        table_style = TableStyle.UNICODE
        local_src = LocalFlag.BOTH
        local_dst = LocalFlag.BOTH
        nat = NatFlag.ALL
        projection = []
        aliases = {}

        rules = self.get_rules_no_duplicates()
        hide_src = local_src == LocalFlag.NOLOCAL
        hide_dst = local_dst == LocalFlag.NOLOCAL
        hide_nats = nat == NatFlag.FILTER
        hide_filters = nat == NatFlag.NAT

        table_printer.print_table(
            rules,
            table_style, [ipaddr.IPv4Address(a) for a in self.firewall.locals],
            hide_src,
            hide_dst,
            hide_nats,
            hide_filters,
            projection,
            aliases=aliases)
Example #9
0
    def do_query(self, arg):
        """Manipulate the query.

        query [show]                   Show current query.
        query reset                    Reset query to be empty.
        query set <attribute> <value>  Set query attribute <attribute> to <value>.
        query unset <attribute>        Unset query attribute <attribute>.
        query names [attribute]        Show possible attribute names.
        query run                      Run the current query.

        By default, the query is automatically run when changed, and
        the result is automatically displayed when run. This behaviour
        can be changed by setting respectively the 'auto_run' and
        'auto_display' config parameters."""
        if arg in ('', 'show'):
            if self.query:
                print_table([self.query], ["Attribute", "Value"])
            else:
                print "No current query."
        elif arg == "reset":
            self.query = Case()
        elif arg.startswith('set'):
            parts = arg.split(None, 2)
            if len(parts) < 3:
                print "Usage: query set <attribute> <value>."
                return
            arg,key,val = parts
            try:
                self.query[key_name(key, possible_attributes)] = val
                if self.config['auto_run']:
                    self.do_query("run")
            except KeyError:
                print "Invalid attribute name '%s'." % key
                print "Possible attribute names:"
                print "\n".join(["  "+i for i in sorted(possible_attributes.keys())])
            except ValueError, e:
                print str(e)
    def do_query(self, arg):
        """Manipulate the query.

        query [show]                   Show current query.
        query reset                    Reset query to be empty.
        query set <attribute> <value>  Set query attribute <attribute> to <value>.
        query unset <attribute>        Unset query attribute <attribute>.
        query names [attribute]        Show possible attribute names.
        query run                      Run the current query.

        By default, the query is automatically run when changed, and
        the result is automatically displayed when run. This behaviour
        can be changed by setting respectively the 'auto_run' and
        'auto_display' config parameters."""
        if arg in ('', 'show'):
            if self.query:
                print_table([self.query], ["Attribute", "Value"])
            else:
                print ("No current query.")
        elif arg == "reset":
            self.query = Case()
        elif arg.startswith('set'):
            parts = arg.split(None, 2)
            if len(parts) < 3:
                print ("Usage: query set <attribute> <value>.")
                return
            arg,key,val = parts
            try:
                self.query[key_name(key, possible_attributes)] = val
                if self.config['auto_run']:
                    self.do_query("run")
            except KeyError:
                print ("Invalid attribute name '%s'.") % key
                print ("Possible attribute names:")
                print ("\n".join(["  "+i for i in sorted(possible_attributes.keys())]))
            except ValueError as e:
                print (str(e))
        elif arg.startswith('unset'):
            parts = arg.split()
            if len(parts) < 2:
                print ("Usage: query unset <attribute>.")
                return
            arg,key = parts[:2]
            try:
                key = key_name(key, possible_attributes)
                del self.query[key]
                if self.config['auto_run']:
                    self.do_query("run")
            except KeyError:
                print ("Attribute '%s' not found.") % key
                return
        elif arg.startswith('names'):
            parts = arg.split()
            if len(parts) < 2:
                print ("Possible attributes:")
                print_table([dict([(k,v._weight) for (k,v) in possible_attributes.items()]),
                             dict([(k,v._adaptable) for (k,v) in possible_attributes.items()]),
                             dict([(k,v._adjustable) for (k,v) in possible_attributes.items()]),],
                            ["Attribute name", "Weight", "Adaptable", "Adjusted"])
                print ("\n".join(("Weight is the weight of the attribute for case similarity.",
                                 "",
                                 "Adaptable specifies whether the attribute can be adapted to",
                                 "the query value.",
                                 "",
                                 "Adjustable specifies whether the attribute is adjusted based",
                                 "on the adaptable ones.",
                                 "",
                                 "Run 'query names <attribute>' for help on an attribute.")))

            else:
                try:
                    key = key_name(parts[1], possible_attributes)
                    attr = possible_attributes[key]
                    print ("\n".join(("Attribute :  %s" % key,
                                     "Weight    :  %s" % attr._weight,
                                     "Adaptable :  %s" % attr._adaptable,
                                     "Adjusted  :  %s" % attr._adjustable,
                                     "")))
                    print (self.gen_help(attr))
                except KeyError:
                    print ("Unrecognised attribute name: %s" % parts[1])
        elif arg.startswith('run'):
            if not self.query:
                print ("No query to run.")
                return
            result = self.matcher.match(self.query, self.config['retrieve'])
            if result:
                if self.config['adapt']:
                    try:
                        result.insert(0, self.matcher.adapt(self.query, result))
                    except AdaptationError:
                        pass
                self.result = (Case(self.query), result)
                if self.config['auto_display']:
                    self.do_result("")
                elif self.interactive:
                    print ("Query run successfully. Use the 'result' command to view the result.")
            else:
                print ("no result.")
        else:
            print ("Unrecognised argument. Type 'help query' for help.")
Example #11
0
                return
            arg,key = parts[:2]
            try:
                key = key_name(key, possible_attributes)
                del self.query[key]
                if self.config['auto_run']:
                    self.do_query("run")
            except KeyError:
                print "Attribute '%s' not found." % key
                return
        elif arg.startswith('names'):
            parts = arg.split()
            if len(parts) < 2:
                print "Possible attributes:"
                print_table([dict([(k,v._weight) for (k,v) in possible_attributes.items()]),
                             dict([(k,v._adaptable) for (k,v) in possible_attributes.items()]),
                             dict([(k,v._adjustable) for (k,v) in possible_attributes.items()]),],
                            ["Attribute name", "Weight", "Adaptable", "Adjusted"])
                print "\n".join(("Weight is the weight of the attribute for case similarity.",
                                 "",
                                 "Adaptable specifies whether the attribute can be adapted to",
                                 "the query value.",
                                 "",
                                 "Adjustable specifies whether the attribute is adjusted based",
                                 "on the adaptable ones.",
                                 "",
                                 "Run 'query names <attribute>' for help on an attribute."))

            else:
                try:
                    key = key_name(parts[1], possible_attributes)
                    attr = possible_attributes[key]
Example #12
0
    def do_query(self, arg):
        """Manipulate the query.

        query [show]                   Show current query.
        query reset                    Reset query to be empty.
        query set <attribute> <value>  Set query attribute <attribute> to <value>.
        query unset <attribute>        Unset query attribute <attribute>.
        query names [attribute]        Show possible attribute names.
        query run                      Run the current query.

        By default, the query is automatically run when changed, and
        the result is automatically displayed when run. This behaviour
        can be changed by setting respectively the 'auto_run' and
        'auto_display' config parameters."""
        if arg in ('', 'show'):
            if self.query:
                print_table([self.query], ["Attribute", "Value"])
            else:
                print("No current query.")
        elif arg == "reset":
            self.query = Case()
        elif arg.startswith('set'):
            parts = arg.split(None, 2)
            if len(parts) < 3:
                print("Usage: query set <attribute> <value>.")
                return
            arg,key,val = parts
            try:
                self.query[key_name(key, possible_attributes)] = val
                if self.config['auto_run']:
                    self.do_query("run")
            except KeyError:
                print("Invalid attribute name '%s'." % key)
                print("Possible attribute names:")
                print("\n".join(["  "+i for i in sorted(possible_attributes.keys())]))
            except ValueError as e:
                print(str(e))
        elif arg.startswith('unset'):
            parts = arg.split()
            if len(parts) < 2:
                print("Usage: query unset <attribute>.")
                return
            arg,key = parts[:2]
            try:
                key = key_name(key, possible_attributes)
                del self.query[key]
                if self.config['auto_run']:
                    self.do_query("run")
            except KeyError:
                print("Attribute '%s' not found." % key)
                return
        elif arg.startswith('names'):
            parts = arg.split()
            if len(parts) < 2:
                print("Possible attributes:")
                print_table([dict([(k,v._weight) for (k,v) in list(possible_attributes.items())]),
                             dict([(k,v._adaptable) for (k,v) in list(possible_attributes.items())]),
                             dict([(k,v._adjustable) for (k,v) in list(possible_attributes.items())]),],
                            ["Attribute name", "Weight", "Adaptable", "Adjusted"])
                print("\n".join(("Weight is the weight of the attribute for case similarity.",
                                 "",
                                 "Adaptable specifies whether the attribute can be adapted to",
                                 "the query value.",
                                 "",
                                 "Adjustable specifies whether the attribute is adjusted based",
                                 "on the adaptable ones.",
                                 "",
                                 "Run 'query names <attribute>' for help on an attribute.")))

            else:
                try:
                    key = key_name(parts[1], possible_attributes)
                    attr = possible_attributes[key]
                    print("\n".join(("Attribute :  %s" % key,
                                     "Weight    :  %s" % attr._weight,
                                     "Adaptable :  %s" % attr._adaptable,
                                     "Adjusted  :  %s" % attr._adjustable,
                                     "")))
                    print(self.gen_help(attr))
                except KeyError:
                    print("Unrecognised attribute name: %s" % parts[1])
        elif arg.startswith('run'):
            if not self.query:
                print("No query to run.")
                return
            result = self.matcher.match(self.query, self.config['retrieve'])
            if result:
                if self.config['adapt']:
                    try:
                        result.insert(0, self.matcher.adapt(self.query, result))
                    except AdaptationError:
                        pass
                self.result = (Case(self.query), result)
                if self.config['auto_display']:
                    self.do_result("")
                elif self.interactive:
                    print("Query run successfully. Use the 'result' command to view the result.")
            else:
                print("no result.")
        else:
            print("Unrecognised argument. Type 'help query' for help.")
def test_eval(test_input, expected, capsys):
    print_table(test_input)
    out, err = capsys.readouterr()
    assert out == expected