[Checkins] SVN: keas.unit/trunk/ Import the little package.

Stephan Richter srichter at cosmos.phy.tufts.edu
Wed Feb 11 08:30:59 EST 2009


Log message for revision 96446:
  Import the little package.
  

Changed:
  A   keas.unit/trunk/
  A   keas.unit/trunk/bootstrap.py
  A   keas.unit/trunk/buildout.cfg
  A   keas.unit/trunk/setup.py
  A   keas.unit/trunk/src/
  A   keas.unit/trunk/src/keas/
  A   keas.unit/trunk/src/keas/__init__.py
  A   keas.unit/trunk/src/keas/unit/
  A   keas.unit/trunk/src/keas/unit/README.txt
  A   keas.unit/trunk/src/keas/unit/__init__.py
  A   keas.unit/trunk/src/keas/unit/interfaces.py
  A   keas.unit/trunk/src/keas/unit/test-conversions.dat
  A   keas.unit/trunk/src/keas/unit/tests.py
  A   keas.unit/trunk/src/keas/unit/unit.py

-=-
Added: keas.unit/trunk/bootstrap.py
===================================================================
--- keas.unit/trunk/bootstrap.py	                        (rev 0)
+++ keas.unit/trunk/bootstrap.py	2009-02-11 13:30:59 UTC (rev 96446)
@@ -0,0 +1,52 @@
+##############################################################################
+#
+# Copyright (c) 2007 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Bootstrap a buildout-based project
+
+Simply run this script in a directory containing a buildout.cfg.
+The script accepts buildout command-line options, so you can
+use the -c option to specify an alternate configuration file.
+
+$Id$
+"""
+
+import os, shutil, sys, tempfile, urllib2
+
+tmpeggs = tempfile.mkdtemp()
+
+ez = {}
+exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
+                     ).read() in ez
+ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
+
+import pkg_resources
+
+cmd = 'from setuptools.command.easy_install import main; main()'
+if sys.platform == 'win32':
+    cmd = '"%s"' % cmd # work around spawn lamosity on windows
+
+ws = pkg_resources.working_set
+assert os.spawnle(
+    os.P_WAIT, sys.executable, sys.executable,
+    '-c', cmd, '-mqNxd', tmpeggs, 'zc.buildout',
+    dict(os.environ,
+         PYTHONPATH=
+         ws.find(pkg_resources.Requirement.parse('setuptools')).location
+         ),
+    ) == 0
+
+ws.add_entry(tmpeggs)
+ws.require('zc.buildout')
+import zc.buildout.buildout
+zc.buildout.buildout.main(sys.argv[1:] + ['bootstrap'])
+shutil.rmtree(tmpeggs)


Property changes on: keas.unit/trunk/bootstrap.py
___________________________________________________________________
Added: svn:keywords
   + Id

Added: keas.unit/trunk/buildout.cfg
===================================================================
--- keas.unit/trunk/buildout.cfg	                        (rev 0)
+++ keas.unit/trunk/buildout.cfg	2009-02-11 13:30:59 UTC (rev 96446)
@@ -0,0 +1,18 @@
+[buildout]
+develop = .
+parts = test coverage-test coverage-report
+
+[test]
+recipe = zc.recipe.testrunner
+eggs = keas.unit [test]
+
+[coverage-test]
+recipe = zc.recipe.testrunner
+eggs = keas.unit [test]
+defaults = ['--coverage', '../../coverage']
+
+[coverage-report]
+recipe = zc.recipe.egg
+eggs = z3c.coverage
+scripts = coverage=coverage-report
+arguments = ('coverage', 'coverage/report')

Added: keas.unit/trunk/setup.py
===================================================================
--- keas.unit/trunk/setup.py	                        (rev 0)
+++ keas.unit/trunk/setup.py	2009-02-11 13:30:59 UTC (rev 96446)
@@ -0,0 +1,24 @@
+import os
+from setuptools import setup, find_packages
+
+def read(*rnames):
+    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
+
+setup(
+    name='keas.unit',
+    version = '0.1.0-dev',
+    author='Keas Inc.',
+    description="A simple wrapper around the 'units' shell command",
+    packages=find_packages('src'),
+    package_dir = {'': 'src'},
+    extras_require=dict(
+        test=['zope.testing'],
+        ),
+    install_requires=[
+        'setuptools',
+        'zope.interface',
+        'zope.schema'
+        ],
+    include_package_data = True,
+    zip_safe = False,
+    )


Property changes on: keas.unit/trunk/setup.py
___________________________________________________________________
Added: svn:keywords
   + Id

Added: keas.unit/trunk/src/keas/__init__.py
===================================================================
--- keas.unit/trunk/src/keas/__init__.py	                        (rev 0)
+++ keas.unit/trunk/src/keas/__init__.py	2009-02-11 13:30:59 UTC (rev 96446)
@@ -0,0 +1,6 @@
+try:
+    # Declare this a namespace package if pkg_resources is available.
+    import pkg_resources
+    pkg_resources.declare_namespace(__name__)
+except ImportError:
+    pass


Property changes on: keas.unit/trunk/src/keas/__init__.py
___________________________________________________________________
Added: svn:keywords
   + Id

Added: keas.unit/trunk/src/keas/unit/README.txt
===================================================================
--- keas.unit/trunk/src/keas/unit/README.txt	                        (rev 0)
+++ keas.unit/trunk/src/keas/unit/README.txt	2009-02-11 13:30:59 UTC (rev 96446)
@@ -0,0 +1,87 @@
+==============
+Unit Converter
+==============
+
+The unit converter is a simple utility to convert units. While it may seem to
+be a trivial task initially, there are many different conventions and
+combinations. Instead of inventing yet another unit conversion utility, this
+package reuses the `units` shell command, which has the best implementation
+that I have found out there.
+
+  >>> from keas.unit import unit
+
+The first step is to instantiate the unit converter object:
+
+  >>> converter = unit.UnitConverter()
+
+By default the converter uses the following path for the `units` command:
+
+  >>> converter.executable
+  '/usr/bin/units'
+
+So let's make a simple unit conversion:
+
+  >>> converter.convert('atm', 'kPa')
+  Decimal("101.325")
+
+There are several options that can be set on the conversion object. The first
+one is the output format, which allows you to specify the precision on the
+output. Of course, we then convert this output to a decimal:
+
+  >>> converter.format
+  >>> converter.format = '%.15g' # 15 decimal places
+  >>> converter.convert('atm', 'kPa')
+  Decimal("101.325")
+
+Next you can specify additional unit conversion data filenames, so that custom
+conversions can be loaded:
+
+  >>> import os
+  >>> datafile = os.path.join(
+  ...     os.path.dirname(unit.__file__), 'test-conversions.dat')
+
+  >>> converter.filenames
+  >>> converter.filenames = ('', datafile)
+
+  >>> converter.convert('keas', 'l')
+  Decimal("0.54321")
+
+  >>> converter.filenames = None
+
+An empty name means that the default data file should be loaded as well.
+
+The final option allows you to set whether the '-' character should be treated
+as a multiplication operator, since it is used as such in some notations.
+
+  >>> converter.minusAsProduct
+  False
+  >>> converter.minusAsProduct = True
+
+  >>> converter.convert('m-m-m', 'l')
+  Decimal("1000")
+
+Finally, let's have a look at some error scenarios.
+
+1. There is no known conversion from one unit to another:
+
+  >>> converter.convert('kg', 'm')
+  Traceback (most recent call last):
+  ...
+  UnitConversionError: ('/usr/bin/units -t -o %.15g -p "kg" "m"',
+                        'conformability error')
+
+2. One of the units is unknown:
+
+  >>> converter.convert('kg', 'foo')
+  Traceback (most recent call last):
+  ...
+  UnitConversionError: ('/usr/bin/units -t -o %.15g -p "kg" "foo"',
+                        "Unknown unit 'foo'")
+
+3. One of the units contains an invalid expression:
+
+  >>> converter.convert('kg', 'm *')
+  Traceback (most recent call last):
+  ...
+  UnitConversionError: ('/usr/bin/units -t -o %.15g -p "kg" "m *"',
+                        "Error in 'm *': Parse error")


Property changes on: keas.unit/trunk/src/keas/unit/README.txt
___________________________________________________________________
Added: svn:eol-style
   + native

Added: keas.unit/trunk/src/keas/unit/__init__.py
===================================================================
--- keas.unit/trunk/src/keas/unit/__init__.py	                        (rev 0)
+++ keas.unit/trunk/src/keas/unit/__init__.py	2009-02-11 13:30:59 UTC (rev 96446)
@@ -0,0 +1 @@
+# Make a package.


Property changes on: keas.unit/trunk/src/keas/unit/__init__.py
___________________________________________________________________
Added: svn:keywords
   + Id

Added: keas.unit/trunk/src/keas/unit/interfaces.py
===================================================================
--- keas.unit/trunk/src/keas/unit/interfaces.py	                        (rev 0)
+++ keas.unit/trunk/src/keas/unit/interfaces.py	2009-02-11 13:30:59 UTC (rev 96446)
@@ -0,0 +1,63 @@
+##############################################################################
+#
+# Copyright (c) 2008 Zope Foundation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Interfaces for a unit converter
+
+$Id$
+"""
+__docformat__ = "reStructuredText"
+import zope.interface
+import zope.schema
+
+# set up internationalization
+import zope.i18nmessageid
+_ = zope.i18nmessageid.MessageFactory("keas.com")
+
+class IUnitConversionError(zope.interface.Interface):
+    """An error raised when the unit conversion failed."""
+
+class UnitConversionError(ValueError):
+    zope.interface.implements(IUnitConversionError)
+
+
+class IUnitConverter(zope.interface.Interface):
+    """Component to provide the conversion factor of one unit to another."""
+
+    executable = zope.schema.ASCIILine(
+        title = u'Units executable',
+        description = u'The path to the executable `units` script.',
+        default = '/usr/bin/units')
+
+    format = zope.schema.ASCIILine(
+        title = u'Output format',
+        description = u'The format used to produce the output.',
+        required = False)
+
+    filenames = zope.schema.Tuple(
+        title = u'Data Files',
+        description = u'A list of data files to use for the conversions.',
+        required = False)
+
+    minusAsProduct = zope.schema.Bool(
+        title = u'Minus as Product',
+        description = u'The minus character acts as a product operator.',
+        default = False)
+
+    def convert(fromUnit, toUnit):
+        """Convert from one unit to another.
+
+        Returns a decimal representing the conversion factor from one unit
+        to another.
+
+        If an error occurs, a `UnitConversionError` error is rasied.
+        """


Property changes on: keas.unit/trunk/src/keas/unit/interfaces.py
___________________________________________________________________
Added: svn:keywords
   + Id

Added: keas.unit/trunk/src/keas/unit/test-conversions.dat
===================================================================
--- keas.unit/trunk/src/keas/unit/test-conversions.dat	                        (rev 0)
+++ keas.unit/trunk/src/keas/unit/test-conversions.dat	2009-02-11 13:30:59 UTC (rev 96446)
@@ -0,0 +1 @@
+keas                    0.54321 l

Added: keas.unit/trunk/src/keas/unit/tests.py
===================================================================
--- keas.unit/trunk/src/keas/unit/tests.py	                        (rev 0)
+++ keas.unit/trunk/src/keas/unit/tests.py	2009-02-11 13:30:59 UTC (rev 96446)
@@ -0,0 +1,30 @@
+##############################################################################
+#
+# Copyright (c) 2008 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""
+$Id$
+"""
+import unittest
+import doctest
+from zope.testing.doctestunit import DocFileSuite
+
+# set up internationalization
+import zope.i18nmessageid
+_ = zope.i18nmessageid.MessageFactory("keas.com")
+
+def test_suite():
+    return unittest.TestSuite((
+        DocFileSuite(
+            'README.txt',
+            optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS),
+        ))


Property changes on: keas.unit/trunk/src/keas/unit/tests.py
___________________________________________________________________
Added: svn:keywords
   + Id

Added: keas.unit/trunk/src/keas/unit/unit.py
===================================================================
--- keas.unit/trunk/src/keas/unit/unit.py	                        (rev 0)
+++ keas.unit/trunk/src/keas/unit/unit.py	2009-02-11 13:30:59 UTC (rev 96446)
@@ -0,0 +1,58 @@
+##############################################################################
+#
+# Copyright (c) 2008 Zope Foundation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Implementation of a unit converter
+
+$Id$
+"""
+__docformat__ = "reStructuredText"
+import decimal
+import popen2
+import zope.interface
+from zope.schema.fieldproperty import FieldProperty
+from keas.unit import interfaces
+
+# set up internationalization
+import zope.i18nmessageid
+_ = zope.i18nmessageid.MessageFactory("keas.com")
+
+class UnitConverter(object):
+    zope.interface.implements(interfaces.IUnitConverter)
+
+    executable = FieldProperty(interfaces.IUnitConverter['executable'])
+    format = FieldProperty(interfaces.IUnitConverter['format'])
+    filenames = FieldProperty(interfaces.IUnitConverter['filenames'])
+    minusAsProduct = FieldProperty(interfaces.IUnitConverter['minusAsProduct'])
+
+    def convert(self, fromUnit, toUnit):
+        """See interfaces.IUnitConverter"""
+        # Build the command
+        cmd = self.executable + ' -t'
+        if self.format:
+            cmd += ' -o ' + self.format
+        if self.filenames:
+            cmd += ' -f ' + ' -f '.join([repr(fn) for fn in self.filenames])
+        if self.minusAsProduct:
+            cmd += ' ' + '-p'
+        cmd += ' "' + fromUnit + '" "' + toUnit + '"'
+        # Run the command
+        stdout, stdin, stderr = popen2.popen3(cmd)
+        result = stdout.read()
+        try:
+            return decimal.Decimal(result)
+        except decimal.InvalidOperation, err:
+            errorMessage = result
+            if not errorMessage:
+                errorMessage = stderr.read()
+            errorMessage = errorMessage.split('\n')[0]
+            raise interfaces.UnitConversionError(cmd, errorMessage)


Property changes on: keas.unit/trunk/src/keas/unit/unit.py
___________________________________________________________________
Added: svn:keywords
   + Id



More information about the Checkins mailing list