Created
November 1, 2012 09:46
-
-
Save playpauseandstop/3992772 to your computer and use it in GitHub Desktop.
Rates calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# | |
# Rates calculator. | |
# | |
# Requirements | |
# ============ | |
# | |
# * `Python <http://www.python.org/>`_ 2.7 | |
# | |
# Installation | |
# ============ | |
# | |
# * Save ``ralc`` script somewhere in your ``$PATH``, in most cases ``~/bin`` | |
# would be enough. | |
# * Give the execution rights to this script, ``chmod +x ~/bin/ralc`` | |
# | |
# Usage | |
# ===== | |
# | |
# :: | |
# | |
# $ ralc HH[:MM[:SS]] RATE | |
# | |
import sys | |
from decimal import Decimal, ROUND_UP | |
__author__ = 'Igor Davydenko' | |
__license__ = 'BSD License' | |
__script__ = 'ralc' | |
__version__ = '0.1' | |
def main(): | |
""" | |
Make calculations if all arguments passed properly. | |
""" | |
if len(sys.argv) != 3: | |
usage() | |
_, delta, rate = sys.argv | |
hours, minutes, seconds = 0, 0, 0 | |
if not ':' in delta: | |
hours = delta | |
elif delta.count(':') == 1: | |
hours, minutes = delta.split(':') | |
elif delta.count(':') == 2: | |
hours, minutes, seconds = delta.split(':') | |
else: | |
print >> sys.stderr, 'ERROR: Invalid value for hours, please use ' \ | |
'next format, HH[:MM[:SS]]. Exit..' | |
sys.exit(1) | |
hours = to_int(hours, 'hours') | |
minutes = to_int(minutes, 'minutes') | |
seconds = to_int(seconds, 'seconds') | |
rate = to_decimal(rate, 'rate') | |
remainder = Decimal(minutes * 60 + seconds) / Decimal(3600) | |
remainder = remainder.quantize(Decimal('.01'), ROUND_UP) | |
value = Decimal(hours) + remainder | |
result = (value * rate).quantize(Decimal('.01'), ROUND_UP) | |
print('> {} x {} = {}'.format(value, rate, result)) | |
def to_decimal(value, label): | |
""" | |
Try to convert value to decimal and exit if fails. | |
""" | |
try: | |
return Decimal(value) | |
except (TypeError, ValueError): | |
print >> sys.stderr, 'ERROR: Cannot convert {}, {!r}, to decimal. ' \ | |
'Exit...'.format(label, value) | |
sys.exit(1) | |
def to_int(value, label): | |
""" | |
Try to convert value to integer and exit if fails. | |
""" | |
try: | |
return int(value) | |
except (TypeError, ValueError): | |
print >> sys.stderr, 'ERROR: Cannot convert {}, {!r}, to integer. ' \ | |
'Exit...'.format(label, value) | |
sys.exit(1) | |
def usage(): | |
""" | |
Print usage message to stderr and exit. | |
""" | |
print >> sys.stderr, 'Usage: {} HH[:MM[:SS]] RATE'.format(__script__) | |
sys.exit(1) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment