예제 #1
0
 def test_registerFeatureUsage(self):
     UsageService.setEnabled(False)
     #this will do nothing as it is disabled
     UsageService.registerFeatureUsage(FeatureType.Algorithm, "testv1", True)
     UsageService.setEnabled(True)
     UsageService.registerFeatureUsage(FeatureType.Algorithm, "testv1", True)
     UsageService.registerFeatureUsage(FeatureType.Algorithm, ["testv1","level2feature"], True)
예제 #2
0
    def error_handler(self, continue_working, share, name, email, textBox):
        status = -1
        if share == 0:
            errorReporter = ErrorReporter("mantidplot",
                                          UsageService.getUpTime(),
                                          self._exit_code, True, str(name),
                                          str(email), str(textBox))
            status = errorReporter.sendErrorReport()
        elif share == 1:
            errorReporter = ErrorReporter("mantidplot",
                                          UsageService.getUpTime(),
                                          self._exit_code, False, str(name),
                                          str(email), str(textBox))
            status = errorReporter.sendErrorReport()

        if status != 201:
            self._view.display_message_box(
                'Error contacting server',
                'There was an error when sending the report.'
                'Please contact [email protected] directly',
                'http request returned with status {}'.format(status))
            self.error_log.error(
                "Failed to send error report http request returned status {}".
                format(status))

        if not continue_working:
            self.error_log.error("Terminated by user.")
            self._view.quit()
        else:
            self.error_log.error("Continue working.")
예제 #3
0
def qapplication():
    """Either return a reference to an existing application instance
    or create a new one
    :return: A reference to the QApplication object
    """
    app = QApplication.instance()
    if app is None:
        # attributes that must be set before creating QApplication
        QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)

        argv = sys.argv[:]
        argv[0] = APPNAME  # replace application name
        # Workaround a segfault importing readline with PyQt5
        # This is because PyQt5 messes up pystate (internal) modules_by_index
        # so PyState_FindModule will return null instead of the module address.
        # Readline (so far) is the only module that falls over during init as it blindly uses FindModules result
        # The workaround mentioned in https://groups.google.com/forum/#!topic/leo-editor/ghiIN7irzY0
        if sys.platform == "linux" or sys.platform == "linux2" or sys.platform == "darwin":
            importlib.import_module("readline")

        app = QApplication(argv)
        app.setOrganizationName(ORGANIZATION)
        app.setOrganizationDomain(ORG_DOMAIN)
        app.setApplicationName(APPNAME)
        app.setApplicationVersion(mantid_version_str())
        # Spin up the usage service and set the name for the usage reporting
        # The report is sent when the FrameworkManager kicks up
        UsageService.setApplicationName(APPNAME)

        app.setAttribute(Qt.AA_UseHighDpiPixmaps)
        if hasattr(Qt, 'AA_DisableWindowContextHelpButton'):
            app.setAttribute(Qt.AA_DisableWindowContextHelpButton)

    return app
예제 #4
0
def qapplication():
    """Either return a reference to an existing application instance
    or create a new one
    :return: A reference to the QApplication object
    """
    app = QApplication.instance()
    if app is None:
        QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
        argv = sys.argv[:]
        argv[0] = APPNAME  # replace application name
        # Workaround a segfault with the IPython console when using Python 3.5 + PyQt 5
        # Without this using this fix the above combination causes a segfault when the IPython
        # console is started
        # The workaround mentioned in https://groups.google.com/forum/#!topic/leo-editor/ghiIN7irzY0
        # is to ensure readline is imported before the QApplication object is created
        if sys.version_info[0] == 3 and sys.version_info[1] == 5:
            importlib.import_module("readline")
        app = QApplication(argv)
        app.setOrganizationName(ORGANIZATION)
        app.setOrganizationDomain(ORG_DOMAIN)
        app.setApplicationName(APPNAME)
        app.setApplicationVersion(mantid_version_str())
        # Spin up the usage service and set the name for the usage reporting
        # The report is sent when the FrameworkManager kicks up
        UsageService.setApplicationName(APPNAME)

    return app
예제 #5
0
def qapplication():
    """Either return a reference to an existing application instance
    or create a new one
    :return: A reference to the QApplication object
    """
    app = QApplication.instance()
    if app is None:
        QCoreApplication.setAttribute(Qt.AA_ShareOpenGLContexts)
        argv = sys.argv[:]
        argv[0] = APPNAME  # replace application name
        # Workaround a segfault with the IPython console when using Python 3.5 + PyQt 5
        # Without this using this fix the above combination causes a segfault when the IPython
        # console is started
        # The workaround mentioned in https://groups.google.com/forum/#!topic/leo-editor/ghiIN7irzY0
        # is to ensure readline is imported before the QApplication object is created
        if sys.version_info[0] == 3 and sys.version_info[1] == 5:
            importlib.import_module("readline")
        app = QApplication(argv)
        app.setOrganizationName(ORGANIZATION)
        app.setOrganizationDomain(ORG_DOMAIN)
        app.setApplicationName(APPNAME)
        app.setApplicationVersion(mantid_version_str())
        # Spin up the usage service and set the name for the usage reporting
        # The report is sent when the FrameworkManager kicks up
        UsageService.setApplicationName(APPNAME)

        if is_required_version(required_version='5.10.0', version=qVersion()):
            app.setAttribute(Qt.AA_DisableWindowContextHelpButton)

    return app
예제 #6
0
 def test_getSetEnabled(self):
     UsageService.setEnabled(False)
     self.assertEqual(UsageService.isEnabled(), False)
     UsageService.setEnabled(True)
     self.assertEqual(UsageService.isEnabled(), True)
     UsageService.setEnabled(False)
     self.assertEqual(UsageService.isEnabled(), False)
예제 #7
0
 def test_getSetEnabled(self):
     UsageService.setEnabled(False)
     self.assertEquals(UsageService.isEnabled(),False)
     UsageService.setEnabled(True)
     self.assertEquals(UsageService.isEnabled(),True)
     UsageService.setEnabled(False)
     self.assertEquals(UsageService.isEnabled(),False)
예제 #8
0
 def __init__(self, name="", facility=""):
     self.instrument_name = name
     self.facility_name = facility
     self._observers = []
     self._output_directory = os.path.expanduser('~')
     if HAS_MANTID:
         config = ConfigService.Instance()
         #register startup
         if HAS_MANTID:
             UsageService.registerFeatureUsage(FeatureType.Interface, "Reduction_gui:{0:.5}-{1:.10}".format(facility, name), False)
         try:
             head, _tail = os.path.split(config.getUserFilename())
             if os.path.isdir(head):
                 self._output_directory = head
         except (StopIteration, AttributeError, ImportError, NameError, TypeError, ValueError, Warning):
             Logger("scripter").debug("Could not get user filename")
예제 #9
0
def exception_logger(main_window, exc_type, exc_value, exc_traceback):
    """
    Captures ALL EXCEPTIONS.
    Prevents the Workbench from crashing silently, instead it logs the error on ERROR level.

    :param main_window: A reference to the main window, that will be used to close it in case of the user
                        choosing to terminate the execution.
    :param exc_type: The type of the exception
    :param exc_value: Value of the exception, typically contains the error message.
    :param exc_traceback: Stack trace of the exception.
    """
    logger.error("".join(
        traceback.format_exception(exc_type, exc_value, exc_traceback)))

    if UsageService.isEnabled():
        page = CrashReportPage(show_continue_terminate=True)
        presenter = ErrorReporterPresenter(
            page, '', 'workbench',
            traceback.format_exception(exc_type, exc_value, exc_traceback))
        presenter.show_view_blocking()
        if not page.continue_working:
            main_window.close()
    else:
        # show the exception message without the traceback
        WorkbenchErrorMessageBox(
            main_window,
            "".join(traceback.format_exception_only(exc_type,
                                                    exc_value))).exec_()
예제 #10
0
 def share_non_identifiable_information(self, continue_working):
     uptime = UsageService.getUpTime()
     status = self._send_report_to_server(share_identifiable=False,
                                          uptime=uptime)
     self.error_log.notice("Sent non-identifiable information")
     self._handle_exit(continue_working)
     return status
예제 #11
0
    def share_all_information(self, continue_working, name, email, text_box):
        uptime = UsageService.getUpTime()
        try:
            recovery_archive, file_hash = zip_recovery_directory()
        except Exception as exc:
            self.error_log.information(
                "Error creating recovery archive: {}. No recovery information will be sent"
            )
            recovery_archive, file_hash = None, ""
        status = self._send_report_to_server(share_identifiable=True,
                                             uptime=uptime,
                                             name=name,
                                             email=email,
                                             file_hash=file_hash,
                                             text_box=text_box)
        self.error_log.notice("Sent full information")
        if status == 201 and recovery_archive:
            self._upload_recovery_file(recovery_archive=recovery_archive)
            try:
                os.remove(recovery_archive)
            except OSError as exc:
                self.error_log.information(
                    "Unable to remove zipped recovery information: {}".format(
                        str(exc)))

        self._handle_exit(continue_working)
        return status
예제 #12
0
    def _save_workspaces(self, directory):
        """
        Save all workspaces present in the ADS to the given directory
        :param directory: String; Path to where to save the workspaces
        """
        # Get all present workspaces
        ws_list = ADS.getObjectNames()

        if len(ws_list) == 0:
            return

        start_time = UsageService.getStartTime().toISO8601String()

        alg_name = "GeneratePythonScript"
        alg = AlgorithmManager.createUnmanaged(alg_name, 1)
        alg.setChild(True)
        alg.setLogging(False)

        for index, ws in enumerate(ws_list):
            if self._empty_group_workspace(ws):
                continue

            filename = str(index) + ".py"
            filename = os.path.join(directory, filename)

            alg.initialize()
            alg.setProperty("AppendTimestamp", True)
            alg.setProperty("AppendExecCount", True)
            alg.setProperty("InputWorkspace", ws)
            alg.setPropertyValue("Filename", filename)
            alg.setPropertyValue("StartTimestamp", start_time)
            alg.setProperty("IgnoreTheseAlgs", ALGS_TO_IGNORE)
            alg.setProperty("IgnoreTheseAlgProperties", ALG_PROPERTIES_TO_IGNORE)

            alg.execute()
예제 #13
0
 def __init__(self, name="", facility=""):
     self.instrument_name = name
     self.facility_name = facility
     self._observers = []
     self._output_directory = os.path.expanduser('~')
     if HAS_MANTID:
         config = ConfigService.Instance()
         #register startup
         if HAS_MANTID:
             UsageService.registerFeatureUsage("Interface",
                                               "Reduction_gui:{0:.5}-{1:.10}".format(facility, name),False)
         try:
             head, _tail = os.path.split(config.getUserFilename())
             if os.path.isdir(head):
                 self._output_directory = head
         except (StopIteration, AttributeError, ImportError, NameError, TypeError, ValueError, Warning):
             Logger("scripter").debug("Could not get user filename")
예제 #14
0
def main():
    if not UsageService.isEnabled():
        return int(command_line_args.exit_code)
    app = QtGui.QApplication(sys.argv)
    form = CrashReportPage(show_continue_terminate=False)
    ErrorReporterPresenter(form, command_line_args.exit_code)
    app.exec_()
    return int(command_line_args.exit_code)
예제 #15
0
 def test_getSetApplication(self):
     self.assertEqual(UsageService.getApplicationName(), "python")
     UsageService.setApplicationName("python unit tests")
     self.assertEqual(UsageService.getApplicationName(),
                      "python unit tests")
     UsageService.setApplicationName("python")
     self.assertEqual(UsageService.getApplicationName(), "python")
예제 #16
0
 def share_non_identifiable_information(self, continue_working, text_box):
     uptime = UsageService.getUpTime()
     status = self._send_report_to_server(share_identifiable=False,
                                          uptime=uptime,
                                          text_box=text_box)
     self.error_log.notice("Sent non-identifiable information")
     self._handle_exit(continue_working)
     if not self._view.rememberContactInfoCheckbox.checkState():
         self.forget_contact_info()
     return status
예제 #17
0
    def error_handler(self, continue_working, share, name, email):
        if share == 0:
            errorReporter = ErrorReporter("mantidplot",
                                          UsageService.getUpTime(),
                                          self._exit_code, True, str(name),
                                          str(email))
            errorReporter.sendErrorReport()
        elif share == 1:
            errorReporter = ErrorReporter("mantidplot",
                                          UsageService.getUpTime(),
                                          self._exit_code, False, str(name),
                                          str(email))
            errorReporter.sendErrorReport()

        if not continue_working:
            self.error_log.error("Terminated by user.")
            self._view.quit()
        else:
            self.error_log.error("Continue working.")
예제 #18
0
    def share_all_information(self, continue_working, name, email, text_box):
        uptime = UsageService.getUpTime()
        status = self._send_report_to_server(share_identifiable=True,
                                             uptime=uptime,
                                             name=name,
                                             email=email,
                                             text_box=text_box)
        self.error_log.notice("Sent full information")

        self._handle_exit(continue_working)
        return status
예제 #19
0
    def show_more_details(self):
        error_reporter = ErrorReporter(
            self._application, UsageService.getUpTime(), self._exit_code, True,
            str(self._view.input_name_line_edit.text()),
            str(self._view.input_email_line_edit.text()),
            str(self._view.input_free_text.toPlainText()),
            "".join(self._traceback))

        error_message_json = json.loads(error_reporter.generateErrorMessage())
        stacktrace_text = error_message_json["stacktrace"]
        del error_message_json[
            "stacktrace"]  # remove this entry so it doesn't appear twice.
        user_information = ''.join(
            '{}: {}\n'.format(key, error_message_json[key])
            for key in error_message_json)
        self._view.display_more_details(user_information, stacktrace_text)
    def share_all_information(self, continue_working, name, email, text_box):
        uptime = UsageService.getUpTime()
        try:
            recovery_archive, file_hash = zip_recovery_directory()
        except Exception as exc:
            self.error_log.information("Error creating recovery archive: {}. No recovery information will be sent")
            recovery_archive, file_hash = None, ""
        status = self._send_report_to_server(share_identifiable=True, uptime=uptime, name=name, email=email, file_hash=file_hash,
                                             text_box=text_box)
        self.error_log.notice("Sent full information")
        if status == 201 and recovery_archive:
            self._upload_recovery_file(recovery_archive=recovery_archive)
            try:
                os.remove(recovery_archive)
            except OSError as exc:
                self.error_log.information("Unable to remove zipped recovery information: {}".format(str(exc)))

        self._handle_exit(continue_working)
        return status
예제 #21
0
    def share_all_information(self, continue_working, new_name, new_email,
                              text_box):
        uptime = UsageService.getUpTime()
        status = self._send_report_to_server(share_identifiable=True,
                                             uptime=uptime,
                                             name=new_name,
                                             email=new_email,
                                             text_box=text_box)
        self.error_log.notice("Sent full information")
        self._handle_exit(continue_working)

        # Remember name and email in QSettings
        if self._view.rememberContactInfoCheckbox.checkState():
            settings = QSettings()
            settings.beginGroup(self._view.CONTACT_INFO)
            settings.setValue(self._view.NAME, new_name)
            settings.setValue(self._view.EMAIL, new_email)
            settings.endGroup()
        else:
            self.forget_contact_info()
        return status
예제 #22
0
    def _save_workspaces(self, directory):
        """
        Save all workspaces present in the ADS to the given directory
        :param directory: String; Path to where to save the workspaces
        """
        # Get all present workspaces
        ws_list = ADS.getObjectNames()

        if len(ws_list) == 0:
            return

        start_time = UsageService.getStartTime().toISO8601String()

        alg_name = "GeneratePythonScript"
        alg = AlgorithmManager.createUnmanaged(alg_name, 1)
        alg.setChild(True)
        alg.setLogging(False)

        for index, ws in enumerate(ws_list):
            if self._empty_group_workspace(ws):
                continue

            filename = str(index) + ".py"
            filename = os.path.join(directory, filename)

            alg.initialize()
            alg.setProperty("AppendTimestamp", True)
            alg.setProperty("AppendExecCount", True)
            alg.setProperty("InputWorkspace", ws)
            alg.setPropertyValue("Filename", filename)
            alg.setPropertyValue("StartTimestamp", start_time)
            alg.setProperty("IgnoreTheseAlgs", ALGS_TO_IGNORE)
            alg.setProperty("IgnoreTheseAlgProperties",
                            ALG_PROPERTIES_TO_IGNORE)

            alg.execute()
 def share_non_identifiable_information(self, continue_working):
     uptime = UsageService.getUpTime()
     status = self._send_report_to_server(share_identifiable=False, uptime=uptime)
     self.error_log.notice("Sent non-identifiable information")
     self._handle_exit(continue_working)
     return status
예제 #24
0
 def test_Flush(self):
     UsageService.setEnabled(False)
     #this will do nothing as it is disabled
     UsageService.flush()
예제 #25
0
 def test_setInterval(self):
     UsageService.setEnabled(False)
     UsageService.setInterval(60)
예제 #26
0
 def test_Shutdown(self):
     UsageService.shutdown()
예제 #27
0
 def test_Shutdown(self):
     UsageService.shutdown()
예제 #28
0
 def test_registerFeatureUsage(self):
     UsageService.setEnabled(False)
     #this will do nothing as it is disabled
     UsageService.registerFeatureUsage("Algorithm","Test.v1",True)
예제 #29
0
 def test_Flush(self):
     UsageService.setEnabled(False)
     #this will do nothing as it is disabled
     UsageService.flush()
예제 #30
0
 def test_registerStartup(self):
     UsageService.setEnabled(False)
     #this will do nothing as it is disabled
     UsageService.registerStartup()
예제 #31
0
 def test_setInterval(self):
     UsageService.setEnabled(False)
     UsageService.setInterval(60)
예제 #32
0
 def test_registerFeatureUsage(self):
     UsageService.setEnabled(False)
     #this will do nothing as it is disabled
     UsageService.registerFeatureUsage("Algorithm","Test.v1",True)
예제 #33
0
 def open_mantid_help(self):
     UsageService.registerFeatureUsage(FeatureType.Feature.Interface,
                                       ["Mantid Help"], False)
     self.interface_manager.showHelpPage('')
예제 #34
0
def report_interface_startup(name):
    #interface startup
    UsageService.registerFeatureUsage(FeatureType.Interface, name, False)
예제 #35
0
 def test_registerStartup(self):
     UsageService.setEnabled(False)
     #this will do nothing as it is disabled
     UsageService.registerStartup()
예제 #36
0
 def test_getSetApplication(self):
     self.assertEquals(UsageService.getApplication(),"python")
     UsageService.setApplication("python unit tests")
     self.assertEquals(UsageService.getApplication(),"python unit tests")
     UsageService.setApplication("python")
     self.assertEquals(UsageService.getApplication(),"python")