Пример #1
0
def cmd_calculation_paste(ensoapi):
    """ Paste the results of the last calculation """
    global last_calculation
    
    #paste_command = CommandManager.get().getCommand("paste")
    #if paste_command:
    #    print dir(paste_command)
    #    paste_command.valid_args

    selection.set({ "text": unicode(last_calculation) })
Пример #2
0
def cmd_calculation_paste(ensoapi):
    """ Paste the results of the last calculation """
    global last_calculation

    #paste_command = CommandManager.get().getCommand("paste")
    #if paste_command:
    #    print dir(paste_command)
    #    paste_command.valid_args

    selection.set({ "text": unicode(last_calculation) })
Пример #3
0
    def set_selection(self, seldict):
        """
        Sets the current selection to the contents of the given
        selection dictionary.

        Alternatively, if a string is provided instead of a
        dictionary, the current selection is set to the unicode
        contents of the string.
        """

        if isinstance(seldict, basestring):
            seldict = { "text" : unicode(seldict) }
        return selection.set(seldict)
Пример #4
0
    def set_selection(self, seldict):
        """
        Sets the current selection to the contents of the given
        selection dictionary.

        Alternatively, if a string is provided instead of a
        dictionary, the current selection is set to the unicode
        contents of the string.
        """

        if isinstance(seldict, basestring):
            seldict = {"text": unicode(seldict)}
        return selection.set(seldict)
    def run(self):
        result = RecentResult.get().get_result()

        if result is None:
            ensoapi.display_message(u"Nothing to put!")
            return

        pasted = selection.set({"text": unicode(result)})
        print pasted
        if not pasted:
            ensoapi.display_message(u"Can't paste the text here!")
        else:
            # Trigger disappearing of mini-message
            _ = RecentResult.get().pop_result()
Пример #6
0
def cmd_calculate(ensoapi, expression = None):
    u""" Calculate the given expression
    Calculate mathematical expression.<br/><br/>
    Supported operators:<br/>
    <code>
    -, +, /, *, ^, **, (, ), %, mod
    </code><br/>
    functions:<br/>
    <code>
    mod, currency, acos, asin, atan, atan2, ceil, cos, cosh,
    degrees, exp, fabs, floor, fmod, frexp, hypot, ldexp,
    log, log10, modf, pow, radians, sin, sinh, sqrt, tan, tanh
    </code><br/>
    constants:<br/>
    <code>
    pi, e
    </code><br/>
    conversions:<br/>
    <code>
    abs, chr, hex
    </code><br/>
    currency conversion:<br/>
    <code>150eur in usd</code><br/>
    <code>1 gbp to eur</code><br/>
    <code>usd in eur</code><br/>
    <code>to eur</code> 
    (when some text representing amount + currency is selected, 
    like $1000, gbp10, €4.5, 10 GBP)<br/>
    """
    #_cache_currencies()
    #print "TO CURRENCIES: " + "|".join(_to_currencies.keys())
    seldict = ensoapi.get_selection()
    if seldict.get(u"text"):
        selected_text = seldict[u'text'].strip().strip("\0")
    else:
        selected_text = None

    got_selection = False
    if expression is None:
        if selected_text:
            expression = selected_text
            got_selection = expression is not None

    if expression is None:
        ensoapi.display_message("No expression given.")
        return        
    
    math_funcs = [f for f in dir(math) if f[:2] != '__']

    whitelist = '|'.join(
        # oprators, digits
        [' ', '\.', ',', '\-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '%', '\d+']
        + ['abs', 'chr\([0-9]+\)', 'hex\([0-9]+\)', 'mod', 'currency']
        # functions of math module (ex. __xxx__)
        + math_funcs)

    print whitelist

    math_funcs_dict = dict([ (mf, eval('math.%s' % mf)) for mf in math_funcs])
    math_funcs_dict['abs'] = abs
    math_funcs_dict['chr'] = chr
    math_funcs_dict['hex'] = hex
    math_funcs_dict['currency'] = currency

    expression = expression.replace(' mod ', ' % ')

    currconv_match = complete_currency_re.search(expression)
    if currconv_match:
        #print "currconv match"
        if currconv_match.group(1):
            amount = currconv_match.group(1)
            print amount
        else:
            amount_str = (selected_text if selected_text else "1").replace(" ", "")
            print amount_str
            try:
                amount = float(amount_str)
            except:
                amount = 1
        
        #print  r"(.*)(" + "|".join(_from_currencies.keys()) + ") (in|to) (" + "|".join(_to_currencies.keys()) + ")(.*)"
        expression = "currency(%s, '%s', '%s') %s" % (
            amount, 
            currconv_match.group(2).upper(), 
            currconv_match.group(4).upper(), 
            currconv_match.group(5))
        #print expression
    else:
        currconv_match = partial_currency_re.match(expression.strip())
        if currconv_match:
            #print "partial match"
            amount_str, from_currency, amount = _handle_currency_symbols(
                (selected_text if selected_text else "1").replace(" ", ""))
            #print amount_str, from_currency, amount
            #print currconv_match.groups()
            expression = "currency(%s, '%s', '%s') %s" % (
                amount, 
                from_currency, 
                currconv_match.group(2).upper(),
                currconv_match.group(3)
            )
        #print expression

    #print expression = expression.replace(' in ', ' % ')

    #print math_funcs_dict

    if re.match(whitelist, expression):
        if expression.endswith("="):
            expression = expression[:-1]
            append_result = True
        else:
            append_result = False
        
        try:
            result = eval(expression, {"__builtins__": None}, math_funcs_dict)
            global last_calculation
            last_calculation = result

            pasted = False
            if got_selection:
                if append_result:
                    pasted = selection.set({ "text" : expression.strip() + " = " + unicode(result) })
                else:
                    pasted = selection.set({ "text" : unicode(result) })
            
            if not pasted:
                displayMessage(u"<p>%s</p><caption>%s</caption>" % (result, expression))
        except Exception, e:
            logging.info(e)
            ensoapi.display_message("Invalid syntax", "Error")
Пример #7
0
def cmd_calculate(ensoapi, expression = None):
    u""" Calculate the given expression
    Calculate mathematical expression.<br><br>
    Supported operators:<br>
    <code>
    -, +, /, *, ^, **, (, ), %, mod
    </code><br>
    functions:<br>
    <code>
    mod, currency, acos, asin, atan, atan2, ceil, cos, cosh,
    degrees, exp, fabs, floor, fmod, frexp, hypot, ldexp,
    log, log10, modf, pow, radians, sin, sinh, sqrt, tan, tanh
    </code><br>
    constants:<br>
    <code>
    pi, e
    </code><br>
    conversions:<br>
    <code>
    abs, chr, hex
    </code><br>
    currency conversion:<br>
    <code>150eur in usd</code><br>
    <code>1 gbp to eur</code><br>
    <code>usd in eur</code><br>
    <code>to eur</code>
    (when some text representing amount + currency is selected,
    like $1000, gbp10, €4.5, 10 GBP)<br>
    """
    #_cache_currencies()
    #print "TO CURRENCIES: " + "|".join(_to_currencies.keys())

    got_selection = False

    if expression is None:
        seldict = ensoapi.get_selection()
        if seldict.get(u"text"):
            selected_text = seldict[u"text"].strip().strip("\0")
        else:
            selected_text = None

        if selected_text:
            expression = selected_text
            got_selection = expression is not None

        if not got_selection:
            ensoapi.display_message("No expression given.")
            return

    math_funcs = [f for f in dir(math) if f[:2] != '__']

    whitelist = '|'.join(
        # oprators, digits
        [' ', '\.', ',', '\-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '%', '\d+']
        + ['abs', 'chr\([0-9]+\)', 'hex\([0-9]+\)', 'mod', 'currency']
        # functions of math module (ex. __xxx__)
        + math_funcs)

    print whitelist

    math_funcs_dict = dict([ (mf, eval('math.%s' % mf)) for mf in math_funcs])
    math_funcs_dict['abs'] = abs
    math_funcs_dict['chr'] = chr
    math_funcs_dict['hex'] = hex
    math_funcs_dict['currency'] = currency

    expression = expression.replace(' mod ', ' % ')

    currconv_match = complete_currency_re.search(expression)
    if currconv_match:
        #print "currconv match"
        if currconv_match.group(1):
            amount = currconv_match.group(1)
            print amount
        else:
            amount_str = (selected_text if selected_text else "1").replace(" ", "")
            print amount_str
            try:
                amount = float(amount_str)
            except:
                amount = 1

        #print  r"(.*)(" + "|".join(_from_currencies.keys()) + ") (in|to) (" + "|".join(_to_currencies.keys()) + ")(.*)"
        expression = "currency(%s, '%s', '%s') %s" % (
            amount,
            currconv_match.group(2).upper(),
            currconv_match.group(4).upper(),
            currconv_match.group(5))
        #print expression
    else:
        currconv_match = partial_currency_re.match(expression.strip())
        if currconv_match:
            #print "partial match"
            amount_str, from_currency, amount = _handle_currency_symbols(
                (selected_text if selected_text else "1").replace(" ", ""))
            #print amount_str, from_currency, amount
            #print currconv_match.groups()
            expression = "currency(%s, '%s', '%s') %s" % (
                amount,
                from_currency,
                currconv_match.group(2).upper(),
                currconv_match.group(3)
            )
        #print expression

    #print expression = expression.replace(' in ', ' % ')

    #print math_funcs_dict

    if re.match(whitelist, expression):
        if expression.endswith("="):
            expression = expression[:-1]
            append_result = True
        else:
            append_result = False

        try:
            result = eval(expression, {"__builtins__": None}, math_funcs_dict)
            global last_calculation
            last_calculation = result

            if got_selection:
                if append_result:
                    selection.set({ "text" : expression.strip() + " = " + unicode(result) })
                else:
                    selection.set({ "text" : unicode(result) })
            else:
                displayMessage(u"<p>%s</p><caption>%s</caption>" % (result, expression))

        except Exception, e:
            logging.info(e)
            ensoapi.display_message("Invalid syntax", "Error")
Пример #8
0
def cmd_calculate(ensoapi, expression=None):
    """ Calculate %s
    <p>Calculate mathematical expression.</p>
    """

    got_selection = False
    if expression is None:
        seldict = ensoapi.get_selection()
        if seldict.get(u"text"):
            selected_text = seldict[u'text'].strip().strip("\0")
        else:
            selected_text = None
        if selected_text:
            expression = selected_text
            got_selection = expression is not None

    if expression is None:
        ensoapi.display_message(
            u"No expression. Please type or select some mathematic expression."
        )
        return None, None

    if isinstance(expression, str):
        expression = expression.decode("utf-8", "ignore")
    expression = _convert_language(expression)

    if "=" in expression:
        expression = expression.split("=")[0].strip()
        append_result = True
    else:
        append_result = False
    """
    123
    4354
    3*3
    234+23
    asd
    fdf
    123

    """
    if expression.count("\n"):
        new_lines = []
        total = 0
        for line in expression.split("\n"):
            leading_whitespace = "".join(
                s for s in itertools.takewhile(str.isspace, line))
            try:
                result, expr = fourfn.evaluate(line.strip())
                new_lines.append(u"%s%s" %
                                 (leading_whitespace, unicode(result)))
                total += long(result)
            except ZeroDivisionError as e:
                logging.warning(e)
                new_lines.append(line.rstrip())
            except ArithmeticError as e:
                logging.warning(e)
                new_lines.append(line.rstrip())
            except Exception as e:
                logging.warning(e)
                new_lines.append(line.rstrip())
        expression = " +\n".join(new_lines) + "\n"
        result = total
        append_result = True
    else:
        try:
            result, expression = fourfn.evaluate(expression)
        except ZeroDivisionError as e:
            logging.warning(e)
            return str(e), expression
        except ArithmeticError as e:
            logging.warning(e)
            return e[1], expression
        except Exception as e:
            logging.warning(e)
            return str(e), expression

    pasted = False
    if got_selection:
        if append_result:
            pasted = selection.set(
                {"text": expression.strip() + " = " + unicode(result)})
        else:
            pasted = selection.set({"text": unicode(result)})

    _ = pasted  # keep pylint happy

    msg = u"%s = %s" % (xml_escape(expression), xml_escape(unicode(result)))
    RecentResult.get().push_result(result, msg)
    """
    #TODO: Testing for return value of selection.set() is not working,
    # returns always True, even after the pasting didn't succeed.
    if pasted:
        msg = u"%s = %s" % (xml_escape(expression), xml_escape(unicode(result)))
        RecentResult.get().push_result(result, msg)
        #displayMessage(
        #    u"<p>%s</p><p>Use <command>put</command> command to insert result.</p><caption>%s</caption>"
        #    % (xml_escape(unicode(result)), xml_escape(expression)))
        #paste_command = get_paste_command()
        #if paste_command:
        #    paste_command.update_pastings({".calculation result" : unicode(result)})
    """
    return result, unicode(expression)
Пример #9
0
def cmd_calculate(ensoapi, expression=None):
    """ Calculate the given expression
    Calculate mathematical expression.<br/><br/>
    Supported operators:<br/>
    <code>
    -, +, /, *, ^, **, (, ), %, mod
    </code><br/>
    functions:<br/>
    <code>
    mod, acos, asin, atan, atan2, ceil, cos, cosh,
    degrees, exp, fabs, floor, fmod, frexp, hypot, ldexp,
    log, log10, modf, pow, radians, sin, sinh, sqrt, tan, tanh
    </code><br/>
    constants:<br/>
    <code>
    pi, e
    </code><br/>
    conversions:<br/>
    <code>
    abs, chr, hex
    </code>
    """
    seldict = ensoapi.get_selection()
    if seldict.get("text"):
        selected_text = seldict['text'].strip().strip("\0")
    else:
        selected_text = None

    got_selection = False
    if expression is None:
        if selected_text:
            expression = selected_text
            got_selection = expression is not None

    if expression is None:
        ensoapi.display_message("No expression given.")
        return

    math_funcs = [f for f in dir(math) if f[:2] != '__']

    whitelist = '|'.join(
        # oprators, digits
        [
            ' ', '\.', ',', '\-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(',
            '\)', '%', '\d+'
        ] + ['abs', 'chr\([0-9]+\)', 'hex\([0-9]+\)', 'mod']
        # functions of math module (ex. __xxx__)
        + math_funcs)

    print(whitelist)

    math_funcs_dict = dict([(mf, eval('math.%s' % mf)) for mf in math_funcs])
    math_funcs_dict['abs'] = abs
    math_funcs_dict['chr'] = chr
    math_funcs_dict['hex'] = hex

    expression = expression.replace(' mod ', ' % ')

    if re.match(whitelist, expression):
        if expression.endswith("="):
            expression = expression[:-1]
            append_result = True
        else:
            append_result = False

        try:
            result = eval(expression, {"__builtins__": None}, math_funcs_dict)
            global last_calculation
            last_calculation = result

            pasted = False
            if got_selection:
                if append_result:
                    pasted = selection.set(
                        {"text": expression.strip() + " = " + str(result)})
                else:
                    pasted = selection.set({"text": str(result)})

            if not pasted:
                displayMessage("<p>%s</p><caption>%s</caption>" %
                               (result, expression))
        except Exception as e:
            logging.info(e)
            ensoapi.display_message("Invalid syntax", "Error")
    else:
        ensoapi.display_message("Invalid expression", "Error")
Пример #10
0
def cmd_calculate(ensoapi, expression = None):
    """ Calculate the given expression
    Calculate mathematical expression.<br/><br/>
    Supported operators:<br/>
    <code>
    -, +, /, *, ^, **, (, ), %, mod
    </code><br/>
    functions:<br/>
    <code>
    mod, acos, asin, atan, atan2, ceil, cos, cosh,
    degrees, exp, fabs, floor, fmod, frexp, hypot, ldexp,
    log, log10, modf, pow, radians, sin, sinh, sqrt, tan, tanh
    </code><br/>
    constants:<br/>
    <code>
    pi, e
    </code><br/>
    conversions:<br/>
    <code>
    abs, chr, hex
    </code>
    """
    seldict = ensoapi.get_selection()
    if seldict.get("text"):
        selected_text = seldict['text'].strip().strip("\0")
    else:
        selected_text = None

    got_selection = False
    if expression is None:
        if selected_text:
            expression = selected_text
            got_selection = expression is not None

    if expression is None:
        ensoapi.display_message("No expression given.")
        return        
    
    math_funcs = [f for f in dir(math) if f[:2] != '__']

    whitelist = '|'.join(
        # oprators, digits
        [' ', '\.', ',', '\-', '\+', '/', '\\', '\*', '\^', '\*\*', '\(', '\)', '%', '\d+']
        + ['abs', 'chr\([0-9]+\)', 'hex\([0-9]+\)', 'mod']
        # functions of math module (ex. __xxx__)
        + math_funcs)

    print(whitelist)

    math_funcs_dict = dict([ (mf, eval('math.%s' % mf)) for mf in math_funcs])
    math_funcs_dict['abs'] = abs
    math_funcs_dict['chr'] = chr
    math_funcs_dict['hex'] = hex

    expression = expression.replace(' mod ', ' % ')

    if re.match(whitelist, expression):
        if expression.endswith("="):
            expression = expression[:-1]
            append_result = True
        else:
            append_result = False
        
        try:
            result = eval(expression, {"__builtins__": None}, math_funcs_dict)
            global last_calculation
            last_calculation = result

            pasted = False
            if got_selection:
                if append_result:
                    pasted = selection.set({ "text" : expression.strip() + " = " + str(result) })
                else:
                    pasted = selection.set({ "text" : str(result) })
            
            if not pasted:
                displayMessage("<p>%s</p><caption>%s</caption>" % (result, expression))
        except Exception as e:
            logging.info(e)
            ensoapi.display_message("Invalid syntax", "Error")
    else:
        ensoapi.display_message("Invalid expression", "Error")