Esempio n. 1
0
 def asrun_instance(cls, **kwargs):
     """Return a singleton instance of the main AsterRun object."""
     if not cls._cache_run:
         from asrun import create_run_instance
         cls._stream = Stream2Func()
         opts = {'log_progress': cls._stream}
         opts['debug_stderr'] = debug_mode() > 1
         if debug_mode() <= 1:
             opts['stderr'] = LogFiles.filename(name='asrun')
         opts.update(kwargs)
         cls._cache_run = create_run_instance(**opts)
     return cls._cache_run
Esempio n. 2
0
 def _simulation_time(self):
     """
     Returns the simulation calculation random time in msec.
     """
     delay = randint(3, 5) if not (debug_mode() or self._unittest) else 0.1
     self.log("Emulating a run for {0} s...".format(delay))
     return delay
Esempio n. 3
0
 def __init__(self, ostream, sort=True, limit=0):
     self._sort = sort
     self._limit = limit
     self._limit_reached = False
     if debug_mode():
         self._write = _debug_write(ostream.write)  # pragma: no cover
     else:
         self._write = ostream.write
Esempio n. 4
0
def debug_ajs(js_text):  # pragma: no cover
    """For debugging, use one file name per session"""
    if not debug_mode():
        return
    if not hasattr(debug_ajs, "cache"):
        debug_ajs.cache = tempfile.mkstemp(prefix='astdy-', suffix='.ajs')[1]

    with open(debug_ajs.cache, "w") as js_file:
        js_file.write(js_text)
    debug_message("File saved:", debug_ajs.cache)
Esempio n. 5
0
def _debug_parse(num, val, line):  # pragma: no cover
    """Debug helper"""
    if debug_mode():
        if num == token.NEWLINE:
            snum = "*" * 12
        elif num == tokenize.NL:
            snum = "+" * 12
        elif num == tokenize.COMMENT:
            snum = "#" * 12
        else:
            snum = token.tok_name[num]
        fmt = "{0:<12} {1!r:<20}: {2!r}"
        debug_message(fmt.format(snum, val, line))
Esempio n. 6
0
    def _setup(self):
        """Build and setup the context to evaluate the commands file.

        Returns:
            dict: Context to execute the commands file.
        """
        context = {}

        # Update context with commands from preceding stages
        for stage in self._stg.preceding_stages:
            for command in stage:
                if command.name in ['', '_']:
                    continue

                # Create an instance of the result type
                result_type = command.gettype(self._strict)

                if isinstance(result_type, basestring):
                    result = result_type
                else:
                    result = result_type()

                try:
                    self._results_cmd[result] = command
                except TypeError: # pragma: no cover
                    # ignore list, dict results
                    pass
                context[command.name] = result

        # add code_aster command dictionary
        context.update(CATA.iteritems())

        # support of CO object
        context['CO'] = _CO

        # add basic mathematical functions
        context.update(Variable.initial_context())

        # We could generate the function name to avoid possible conflict
        context["_post_conversion"] = self._post_conversion
        # change output streams
        if not debug_mode():
            self._saved['sys.stdout'] = sys.stdout
            sys.stdout = open(os.devnull, "wb")
            self._saved['sys.stderr'] = sys.stderr
            sys.stderr = open(os.devnull, "wb")

        return context
Esempio n. 7
0
    def __init__(self, astergui, parent=None):
        """
        Create view.

        Arguments:
            astergui (AsterGui): *AsterGui* instance.
            parent (Optional[QWidget]): Parent widget. Defaults to
                *None*.
        """
        super(DataSettings, self).__init__(parent)
        self._astergui = astergui

        base = Q.QVBoxLayout(self)
        base.setContentsMargins(0, 0, 0, 0)

        self._view = TreeWidget(self)
        self._view.itemDelegate().setEditColumns(0)
        self._view.setColumnCount(2)
        if debug_mode():
            self._view.setColumnCount(3)
        self._view.setSelectionMode(Q.QTreeWidget.ExtendedSelection)
        header = self._view.header()
        header.hide()
        header.setSectionResizeMode(Q.QHeaderView.ResizeToContents)
        header.setMaximumSectionSize(250)
        header.setStretchLastSection(True)
        root = self._view.invisibleRootItem()
        root.setData(0, Role.IdRole, root_node_type())
        base.addWidget(self._view)

        self._finder = Searcher(astergui, self)
        self._finder.setAutoHide(behavior().auto_hide_search)
        base.addWidget(self._finder)

        connect(self._view.itemSelectionChanged, self.itemSelectionChanged)
        connect(self._view.itemDoubleClicked, self._itemDoubleClicked)
        connect(self._view.itemChanged, self._itemChanged)

        self.update()
Esempio n. 8
0
 def _teardown(self):
     """Restore initial state."""
     if not debug_mode():
         sys.stdout = self._saved['sys.stdout']
         sys.stderr = self._saved['sys.stderr']
Esempio n. 9
0
    def validate(self):
        """
        Perform value validation.

        Returns:
           bool: Validation status: True if value is valid; False
           otherwise.
        """
        state = True
        checker = CATA.package('Syntax').SyntaxCheckerVisitor()
        cond_context = self.conditionStorage(with_default=True)
        # conditionStorage returns values for simple keyword
        if isinstance(cond_context, dict):
            checker.set_parent_context(cond_context)

        exc_message = []
        try:
            self.keyword().accept(checker, self.itemValue())
        except Exception as exc:  # pragma pylint: disable=broad-except
            from traceback import format_exc
            exc_message.append("Raw output message:\n{}\n".format(exc.args[0]))
            if debug_mode():
                exc_message.append("\n" + format_exc(exc))
            state = False

        if state:
            return True

        rule = None
        stack = checker.stack
        if len(stack) > 0 and not isinstance(stack[-1], basestring):
            rule = stack.pop()

        item = self
        while len(stack) > 0:
            items = item.findItemsByName(stack.pop(0))
            for i in items:
                if not i.testFlags(self.ItemFlags.Filtered) and \
                        not i.testFlags(self.ItemFlags.Excluded):
                    item = i
                    break


#        pos = self.contentsRect().center()
        msgInfo = []
        hiframe = None
        if item is not None and item != self:
            rect = item.itemRect()
            space = self.grid().spacing() / 2
            rect.adjust(-space, -space, space, space)
            self.ensureVisible.emit(rect)
            #            pos = rect.center()

            hiframe = ParameterItemHilighter(rect, self)
            hiframe.show()
            kwtext = Options.translate_command(item.command().title,
                                               item.itemName())
            msgInfo.append(
                translate("ParameterPanel",
                          "Invalid input in {0}.").format(kwtext))
        else:
            msgInfo.append(translate("ParameterPanel", "Invalid input."))

        if rule is not None:
            rulemsg = translate(
                "ParameterPanel", "Not respected the rule: {0}"
                " with keywords: {1}.")
            msgInfo.append(
                rulemsg.format(type(rule).__name__, ", ".join(rule.ruleArgs)))

        msgInfo.append(
            translate("ParameterPanel",
                      "Do you want to save the changes any way?"))

        #        balloon = ParameterBaloon(self)
        #        balloon.setTitle(translate("ParameterPanel", "Error"))
        #        balloon.setMessage("<br>".join(msg))
        #        balloon.setPositon(self.mapToGlobal(pos))
        #        balloon.show()

        details = " ".join(exc_message)
        answer = MessageBox.question(self,
                                     translate("ParameterPanel", "Error"),
                                     "\n".join(msgInfo),
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.Yes,
                                     detailedText=details)

        if hiframe is not None:
            hiframe.hide()

        return answer == QMessageBox.Yes
Esempio n. 10
0
    def updateTranslations(self):
        """
        Update translation.
        """
        if not self.isVisible():
            return

        path = self.path()
        name = path.name()
        command = path.command()

        # get business-oriented translation if present and set label's text
        if name.isdigit():
            self._titlelabel.setText("[%s]" % name)
            name = path.parentPath().name()
            translation = Options.translate_command(command.title, name)
        else:
            translation = Options.translate_command(command.title, name)
            self._titlelabel.setText(translation)

        # compute tooltip / what's this base info
        if translation != name:
            wttext = italic(translation) + " ({})".format(bold(name))
        else:
            wttext = bold(name)
        wttext = preformat(wttext)

        # set content
        contstr = ""
        if self.contentsMode() != "none" and \
                self.contentsValue() is not None:
            contstr = self._contentsText(self.path())
        self._contentslabel.setText(contstr)
        self._contentslabel.setVisible(len(self._contentslabel.text()) > 0)

        # set tooltip
        tooltip = wttext
        if debug_mode():
            tooltip += "<br>"
            tooltip += path.path()

        contstr = ""
        if self.contentsValue() is not None:
            contstr = self._contentsText(self.path(), None, "parameters")
        if len(contstr) > 0:
            tooltip += "<hr>" + contstr

        self.setToolTip(tooltip)

        # set what's this
        # - add native doc string if present
        docs = path.keyword().udocstring
        if len(docs):
            wttext = wttext + "<hr>" + docs

        # - add value type and default value information if present
        typeinfo = self._typeInformation()
        if len(typeinfo):
            listinfo = self._listInformation()
            if len(listinfo):
                typeinfo += "<br>" + listinfo
            wttext = wttext + "<hr>" + typeinfo
        definfo = self._defaultInformation()
        if len(definfo):
            wttext = wttext + "<br>" + definfo

        # - add rules description if present
        rules = self.rules()
        if rules is not None and len(rules) > 0:
            rulelines = []
            for rule in rules:
                # translate rule
                line = bold(translate_rule(rule.itemName()))
                kw_list = []
                for kword in rule.ruleKeywords():
                    if name == kword:
                        kw_list.append(font(kword, color="#0000ff"))
                    else:
                        kw_list.append(kword)
                line = line + ": " + ", ".join(kw_list)
                rulelines.append(line)
            wttext = wttext + "<hr>" + "<br>".join(rulelines)

        # - finally assign what's this info
        self.setWhatsThis(wttext)