From ff6fdf02f33ad8a277f8ef1a68ea950d0c08da64 Mon Sep 17 00:00:00 2001 From: Jeremy Fincher Date: Thu, 2 Oct 2003 23:19:38 +0000 Subject: [PATCH] Added convert and units command. --- plugins/Math.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ test/test_Math.py | 11 +++++++++++ 2 files changed, 56 insertions(+) diff --git a/plugins/Math.py b/plugins/Math.py index fe16dc91a..63165c193 100644 --- a/plugins/Math.py +++ b/plugins/Math.py @@ -41,6 +41,8 @@ import math import cmath from itertools import imap +import unum.units + import utils import privmsgs import callbacks @@ -189,8 +191,51 @@ class Math(callbacks.Privmsg): s = ', '.join(imap(self._complexToString, imap(complex, stack))) irc.reply(msg, 'Stack: [%s]' % s) + _convertEnv = {'__builtins__': new.module('__builtins__')} + for (k, v) in unum.units.__dict__.iteritems(): + if isinstance(v, unum.Unum): + _convertEnv[k.lower()] = v + def convert(self, irc, msg, args): + """ to + Converts the first number of to the . Valid units + expressions include the standard Python math operators applied to valid + units. + """ + (n, unit1, to, unit2) = privmsgs.getArgs(args, needed=4) + if to != 'to': + raise callbacks.ArgumentError + try: + n = float(n) + except ValueError: + irc.error(msg, '%s is not a valid number.' % n) + return + try: + u1 = eval(unit1.lower(), self._convertEnv, self._convertEnv) + except: + irc.error(msg, '%s is not a valid units expression.' % units1) + return + try: + u2 = eval(unit2.lower(), self._convertEnv, self._convertEnv) + except: + irc.error(msg, '%s is not a valid units expression.' % units2) + return + try: + irc.reply(msg, str((n*u1).as(u2))) + except Exception, e: + irc.error(msg, str(e)) + def units(self, irc, msg, args): + """takes no arguments + + Returns all the valid units. + """ + L = self._convertEnv.keys() + L.remove('__builtins__') + L.sort() + irc.reply(msg, utils.commaAndify(L)) + + Class = Math # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: diff --git a/test/test_Math.py b/test/test_Math.py index 8649b48ee..2e0bdb890 100644 --- a/test/test_Math.py +++ b/test/test_Math.py @@ -49,6 +49,17 @@ class MathTestCase(PluginTestCase, PluginDocumentation): self.assertResponse('rpn 1 dup', 'Stack: [1, 1]') self.assertResponse('rpn 2 3 4 + -', str(2-7)) + def testConvert(self): + self.assertResponse('convert 1 m to cm', '100.0 [cm]') + self.assertResponse('convert 1 M to cm', '100.0 [cm]') + self.assertResponse('convert 1 m to CM', '100.0 [cm]') + self.assertResponse('convert 1 m to cM', '100.0 [cm]') + self.assertError('convert 1 m to kpa') + self.assertNotRegexp('convert 1 m to kpa', 'UNUM_ERROR') + + def testUnits(self): + self.assertNotError('units') + # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: