Exemplo n.º 1
0
 def do_quit(self, line):
     arg = str(line).lower()
     if not arg == "-f" and not len(self._std.new_data) == 0:
         View.warning("The new data hasn't been saved. "
                      "Enter \"quit -f\" to quit without saving.")
     else:
         View.display("Thanks for using. Bye!")
         return True
Exemplo n.º 2
0
    def do_select(self, line):
        """
        Select a data source
        :param line: <String> Source name
        :return: None
        :Author: Zhiming Liu
        """
        cmd = SelectCommand(line)

        if cmd.resource_type is None:
            View.error("The data resource is not available.")

        elif cmd.resource_type == "csv":
            self.select_csv(cmd)

        elif cmd.resource_type == "db":
            self._std.select_source(cmd.resource_type)
Exemplo n.º 3
0
    def do_import(self, line):
        """
        Import command
        :param line: (String) [-csv|-pk] [file path]
        :return: None
        :Author: Zhiming Liu
        """
        cmd = ImportCommand(line)

        if cmd.file_type is None or cmd.file_name is None:
            View.info("Invalid command.")
            View.help_import()

        elif cmd.file_type == "csv":
            self.import_csv(cmd.file_name)

        elif cmd.file_type == "pk":
            self.import_pickle(cmd.file_name)
Exemplo n.º 4
0
    def select_csv(self, cmd):
        try:
            if not cmd.is_valid_command:
                View.error("Invalid command.")
                View.help_select()

            elif cmd.file_name is None:
                self._std.select_source(cmd.resource_type,
                                        cmd.default_csv_file)
                View.warning("No CSV file path specified. "
                             "A default file \"{0}\" "
                             "will be used.".format(cmd.default_csv_file))
            else:
                self._std.select_source(cmd.resource_type, cmd.file_name,
                                        cmd.create_file)
        except Exception as e:
            View.error(e)
        else:
            View.success("Data source CSV is selected.")
Exemplo n.º 5
0
    def do_add(self, line):
        """
        Add a new entry of data
        :param line: (String) [EMPID] [Age] [Gender] [Sales]
                    [BMI] [Salary] [Birthday]
        :return: None
        :Author: Zhiming Liu
        """
        # Split the input argument to obtain the data
        raw_data = list(arg.lower() for arg in str(line).split())

        try:
            # Check if input data has 7 data fields
            if not len(raw_data) == len(Data):
                raise AttributeError("Please input correct data.")
            else:
                # Check and wash data by check_all() of DataValidator
                result = self._vld.check_all(raw_data)
                # Check if there is any None which stands for invalid input
                if None in result:
                    key = 0
                    # build a list of name list
                    items = list(map(lambda i: i.name, Data))
                    e_str = ""
                    while key < len(result):
                        if result[key] is None:
                            # Left alignment
                            e_str += "{:<10}".format(items[key])
                        key += 1
                    raise ValueError("The following field(s) "
                                     "is invalid:\n%s" % e_str)
                else:
                    self._std.add_data(result)
        except (AttributeError, ValueError) as e:
            View.error(str(e) + "\n")
            View.help_add()
        except CSVError as e:
            View.error(e)
        except Exception as e:
            View.error(e)
        else:
            View.success("Add data")
Exemplo n.º 6
0
 def do_export(self, line):
     """
     Export command
     :param line: (String) [-pk] [file path]
     :return: None
     :Author: Zhiming Liu
     """
     args = list(arg.lower() for arg in str(line).split())
     if args[0] == "-pk" and len(args) > 1:
         try:
             pk = PickleOperations()
             pk.pickle_dump(args[1], self._std.get_all_data())
         except Exception as e:
             View.error(e)
             View.help_export()
         else:
             View.success("Data has been saved to %s" % args[1])
     else:
         View.info("Invalid command")
         View.help_export()
Exemplo n.º 7
0
 def show_bar(self, line):
     # Draw Bars
     try:
         if len(self._std.get_gender()) == 0 or len(
                 self._std.get_gender()) == 0:
             raise ValueError("No data to display.")
         # Draw gender
         if line.upper() == Data.GENDER.name:
             View.plot_bar(self._std.get_gender(), "Gender Distribution")
         # Draw BMI
         if line.upper() == Data.BMI.name:
             View.plot_bar(self._std.get_bmi(), "Body Mass Index (BMI)")
     except ValueError as e:
         View.info(e)
     except Exception as e:
         View.error(e)
Exemplo n.º 8
0
 def do_save(self, arg):
     """
     Save data to specified data source
     :param arg: arg
     :return: None
     """
     # If no data source selected, prompt user to do so.
     try:
         self._std.save_data()
     except ValueError as e:
         View.info(e)
     except (OSError, AttributeError) as e:
         View.error(e)
     except Exception as e:
         View.error(e)
     else:
         View.success("Data is saved")
Exemplo n.º 9
0
 def show_bar(self, line):
     """
     Draw bar chart
     :param line: String
     :return: None
     :Author: Zhiming Liu
     """
     # Draw Bars
     try:
         if self._std.get_gender().total_count == 0 \
                 or len(self._std.get_bmi()) == 0:
             raise ValueError("No data to display.")
         # Draw gender
         if line.upper() == Data.GENDER.name:
             View.plot_bar(self._std.get_gender().formatted_data,
                           "Gender Distribution", "numer of people")
         # Draw BMI
         if line.upper() == Data.BMI.name:
             View.plot_bar(self._std.get_bmi(), "Body Mass Index (BMI)",
                           "number of people")
     except ValueError as e:
         View.info(e)
     except Exception as e:
         View.error(e)
Exemplo n.º 10
0
 def help_select():
     View.display("Select a source of data for reading "
                  "and saving staff information.\n")
     View.help_select()
Exemplo n.º 11
0
    def do_show(self, line):
        # Get all instructions
        args = list(arg.lower() for arg in str(line).split())

        # Those commands are required single arguments
        # single_commands = ["-a"]
        # Those commands are required two arguments
        plot_commands = ["-p", "-b", "-c"]

        # Show data table
        if args[0] == "-t":
            if len(self._std.data) == 0 and len(self._std.new_data) == 0:
                View.info("No data to display.")
            if not len(self._std.data) == 0:
                View.display("ORIGINAL DATA:")
                View.display_data(self._std.data, ind=True)
            if not len(self._std.new_data) == 0:
                View.display("\nNEW DATA:")
                View.display_data(self._std.new_data, ind=True)
                View.display("\n(Input command \"save\" to save the new data)")

        elif args[0] in plot_commands:
            try:
                if len(args) == 1:
                    raise IndexError("Incomplete command line.")

                if args[0] == "-p":
                    self.show_pie(args[1])
                if args[0] == "-b":
                    self.show_bar(args[1])
                if args[0] == "-c":
                    self.show_scatter(args[1])

            except IndexError as e:
                View.error(str(e) + "\n")
                View.help_show()
        else:
            View.info("Invalid command line.\n")
            View.help_show()
Exemplo n.º 12
0
def display_error(txt):
    """
    >>> display_error("Error message")
    Error: Error message
    """
    return view.error(txt)
Exemplo n.º 13
0
 def import_pickle(self, filename):
     try:
         pk = PickleOperations()
         self.import_result(list(pk.pickle_import(filename)))
     except Exception as e:
         View.error(e)
Exemplo n.º 14
0
 def import_result(self, data):
     View.display_import_result(
         list(map(lambda row: self.import_row(row), data)))
Exemplo n.º 15
0
 def help_select():
     View.help_select()
Exemplo n.º 16
0
 def import_csv(self, filename):
     try:
         csv = CSVOperations(filename)
         self.import_result(csv.read())
     except Exception as e:
         View.error(e)
Exemplo n.º 17
0
 def help_add():
     View.help_add()
Exemplo n.º 18
0
 def help_show():
     View.help_show()
Exemplo n.º 19
0
 def help_save():
     View.display("This command is used for saving all newly added data "
                  "to the selected data source.\n")
     View.help_save()
Exemplo n.º 20
0
 def help_add():
     View.display("This command adds a new staff data to the system.\n")
     View.help_add()
Exemplo n.º 21
0
 def help_show():
     View.display("This command is used for displaying all data that "
                  "is existed in the system.\n")
     View.help_show()
Exemplo n.º 22
0
    def do_select(self, line):
        """
        Select a data source
        :param line: <String> Source name
        :return: None
        :Author: Zhiming Liu
        """
        # Available data sources
        options = "-csv", "-db"
        args = list(arg.lower() for arg in str(line).split())

        try:
            # Check if the input data source is available in this program or not
            if args[0] not in options:
                raise ValueError("The data resource is not available.")
            else:
                # Code for initialise CSV data source
                if args[0] == "-csv":
                    try:
                        if len(args) == 1:
                            self._std.select_source(args[0][1:],
                                                    "staffinfo.csv")
                            View.warning(
                                "No CSV file path specified. A default file \"staffinfo.csv\" will be used."
                            )
                        elif len(args) == 2:
                            self._std.select_source(args[0][1:], args[1])
                        elif len(args) == 3:
                            if args[1] == "-a":
                                self._std.select_source(
                                    args[0][1:], args[2], True)
                    except (CSVError, OSError) as e:
                        View.error(e)
                    except Exception as e:
                        View.error(e)
                    else:
                        View.success("Data source CSV is selected.")

                # Code for initialise database source
                elif args[0] == "-db":
                    try:
                        self._std.select_source(args[0][1:])
                    except (ConnectionError, TypeError) as e:
                        View.error(e)
                    except Exception as e:
                        View.error(e)
                    else:
                        View.success("Data source Database is selected.")

                # Code for initialise XXXX data source
                else:
                    pass
        # Catch and display error message
        except ValueError as e:
            View.error(str(e) + "\n")
            View.help_select()
        except Exception as e:
            View.error(e)
Exemplo n.º 23
0
 def help_quit():
     View.display("This command is used for "
                  "quitting the command line mode\n")
     View.help_quit()
Exemplo n.º 24
0
 def help_save():
     View.help_save()
Exemplo n.º 25
0
 def help_import():
     View.display("Import data from a file "
                  "that is specified in the command line.\n")
     View.help_import()
Exemplo n.º 26
0
 def help_quit():
     View.help_quit()
Exemplo n.º 27
0
 def help_export():
     View.display("Export data to a local file "
                  "that is specified in the command line.\n")
     View.help_export()