Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial copy of maglev repository, before Allen's change to use new p…

…ack-unpack
  • Loading branch information...
commit 6a86d67620abcd7d10c58b1a5cf4860af3cf3883 1 parent e377567
Monty Williams authored
Showing with 41,709 additions and 0 deletions.
  1. +6 −0 INSTALL
  2. +40 −0 README
  3. +304 −0 bin/gemstone
  4. +166 −0 bin/jruby
  5. BIN  bin/lib/bsf.jar
  6. BIN  bin/lib/jruby.jar
  7. +106 −0 bin/lib/ruby/1.8/.document
  8. +155 −0 bin/lib/ruby/1.8/English.rb
  9. +18 −0 bin/lib/ruby/1.8/Env.rb
  10. +96 −0 bin/lib/ruby/1.8/README
  11. +103 −0 bin/lib/ruby/1.8/abbrev.rb
  12. +133 −0 bin/lib/ruby/1.8/base64.rb
  13. +569 −0 bin/lib/ruby/1.8/benchmark.rb
  14. +85 −0 bin/lib/ruby/1.8/bigdecimal/jacobian.rb
  15. +84 −0 bin/lib/ruby/1.8/bigdecimal/ludcmp.rb
  16. +235 −0 bin/lib/ruby/1.8/bigdecimal/math.rb
  17. +77 −0 bin/lib/ruby/1.8/bigdecimal/newton.rb
  18. +65 −0 bin/lib/ruby/1.8/bigdecimal/util.rb
  19. +272 −0 bin/lib/ruby/1.8/cgi-lib.rb
  20. +2,303 −0 bin/lib/ruby/1.8/cgi.rb
  21. +2 −0  bin/lib/ruby/1.8/cgi/.document
  22. +484 −0 bin/lib/ruby/1.8/cgi/session.rb
  23. +111 −0 bin/lib/ruby/1.8/cgi/session/pstore.rb
  24. +631 −0 bin/lib/ruby/1.8/complex.rb
  25. +992 −0 bin/lib/ruby/1.8/csv.rb
  26. +1,708 −0 bin/lib/ruby/1.8/date.rb
  27. +1,088 −0 bin/lib/ruby/1.8/date/format.rb
  28. +5 −0 bin/lib/ruby/1.8/date2.rb
  29. +949 −0 bin/lib/ruby/1.8/debug.rb
  30. +335 −0 bin/lib/ruby/1.8/delegate.rb
  31. +254 −0 bin/lib/ruby/1.8/dl.rb
  32. +2 −0  bin/lib/ruby/1.8/drb.rb
  33. +146 −0 bin/lib/ruby/1.8/drb/acl.rb
  34. +1,763 −0 bin/lib/ruby/1.8/drb/drb.rb
  35. +16 −0 bin/lib/ruby/1.8/drb/eq.rb
  36. +64 −0 bin/lib/ruby/1.8/drb/extserv.rb
  37. +96 −0 bin/lib/ruby/1.8/drb/extservm.rb
  38. +122 −0 bin/lib/ruby/1.8/drb/gw.rb
  39. +36 −0 bin/lib/ruby/1.8/drb/invokemethod.rb
  40. +22 −0 bin/lib/ruby/1.8/drb/observer.rb
  41. +190 −0 bin/lib/ruby/1.8/drb/ssl.rb
  42. +91 −0 bin/lib/ruby/1.8/drb/timeridconv.rb
  43. +108 −0 bin/lib/ruby/1.8/drb/unix.rb
  44. +195 −0 bin/lib/ruby/1.8/e2mmap.rb
  45. +826 −0 bin/lib/ruby/1.8/erb.rb
  46. +37 −0 bin/lib/ruby/1.8/eregex.rb
  47. +1,591 −0 bin/lib/ruby/1.8/fileutils.rb
  48. +193 −0 bin/lib/ruby/1.8/finalize.rb
  49. +79 −0 bin/lib/ruby/1.8/find.rb
  50. +218 −0 bin/lib/ruby/1.8/forwardable.rb
  51. +261 −0 bin/lib/ruby/1.8/ftools.rb
  52. +274 −0 bin/lib/ruby/1.8/generator.rb
  53. +621 −0 bin/lib/ruby/1.8/getoptlong.rb
  54. +127 −0 bin/lib/ruby/1.8/getopts.rb
  55. +253 −0 bin/lib/ruby/1.8/gserver.rb
  56. +33 −0 bin/lib/ruby/1.8/importenv.rb
  57. +23 −0 bin/lib/ruby/1.8/io/nonblock.rb
  58. +766 −0 bin/lib/ruby/1.8/ipaddr.rb
  59. +342 −0 bin/lib/ruby/1.8/irb.rb
  60. +33 −0 bin/lib/ruby/1.8/irb/cmd/chws.rb
  61. +39 −0 bin/lib/ruby/1.8/irb/cmd/fork.rb
  62. +34 −0 bin/lib/ruby/1.8/irb/cmd/help.rb
  63. +67 −0 bin/lib/ruby/1.8/irb/cmd/load.rb
  64. +39 −0 bin/lib/ruby/1.8/irb/cmd/nop.rb
  65. +39 −0 bin/lib/ruby/1.8/irb/cmd/pushws.rb
  66. +43 −0 bin/lib/ruby/1.8/irb/cmd/subirb.rb
  67. +205 −0 bin/lib/ruby/1.8/irb/completion.rb
  68. +255 −0 bin/lib/ruby/1.8/irb/context.rb
  69. +62 −0 bin/lib/ruby/1.8/irb/ext/change-ws.rb
  70. +110 −0 bin/lib/ruby/1.8/irb/ext/history.rb
  71. +120 −0 bin/lib/ruby/1.8/irb/ext/loader.rb
  72. +37 −0 bin/lib/ruby/1.8/irb/ext/math-mode.rb
  73. +241 −0 bin/lib/ruby/1.8/irb/ext/multi-irb.rb
  74. +85 −0 bin/lib/ruby/1.8/irb/ext/save-history.rb
  75. +61 −0 bin/lib/ruby/1.8/irb/ext/tracer.rb
  76. +65 −0 bin/lib/ruby/1.8/irb/ext/use-loader.rb
  77. +56 −0 bin/lib/ruby/1.8/irb/ext/workspaces.rb
  78. +264 −0 bin/lib/ruby/1.8/irb/extend-command.rb
  79. +67 −0 bin/lib/ruby/1.8/irb/frame.rb
  80. +33 −0 bin/lib/ruby/1.8/irb/help.rb
  81. +263 −0 bin/lib/ruby/1.8/irb/init.rb
  82. +120 −0 bin/lib/ruby/1.8/irb/input-method.rb
  83. +30 −0 bin/lib/ruby/1.8/irb/lc/error.rb
  84. +35 −0 bin/lib/ruby/1.8/irb/lc/help-message
  85. +27 −0 bin/lib/ruby/1.8/irb/lc/ja/error.rb
  86. +36 −0 bin/lib/ruby/1.8/irb/lc/ja/help-message
  87. +184 −0 bin/lib/ruby/1.8/irb/locale.rb
  88. +145 −0 bin/lib/ruby/1.8/irb/notifier.rb
  89. +85 −0 bin/lib/ruby/1.8/irb/output-method.rb
  90. +1,149 −0 bin/lib/ruby/1.8/irb/ruby-lex.rb
  91. +273 −0 bin/lib/ruby/1.8/irb/ruby-token.rb
  92. +285 −0 bin/lib/ruby/1.8/irb/slex.rb
  93. +16 −0 bin/lib/ruby/1.8/irb/version.rb
  94. +107 −0 bin/lib/ruby/1.8/irb/workspace.rb
  95. +15 −0 bin/lib/ruby/1.8/irb/ws-for-case-2.rb
  96. +86 −0 bin/lib/ruby/1.8/irb/xmp.rb
  97. +220 −0 bin/lib/ruby/1.8/jcode.rb
  98. +228 −0 bin/lib/ruby/1.8/kconv.rb
  99. +703 −0 bin/lib/ruby/1.8/logger.rb
  100. +62 −0 bin/lib/ruby/1.8/mailread.rb
  101. +308 −0 bin/lib/ruby/1.8/mathn.rb
  102. +1,272 −0 bin/lib/ruby/1.8/matrix.rb
  103. +14 −0 bin/lib/ruby/1.8/md5.rb
  104. +352 −0 bin/lib/ruby/1.8/monitor.rb
  105. +122 −0 bin/lib/ruby/1.8/mutex_m.rb
  106. +923 −0 bin/lib/ruby/1.8/net/ftp.rb
  107. +2,288 −0 bin/lib/ruby/1.8/net/http.rb
  108. +173 −0 bin/lib/ruby/1.8/net/https.rb
  109. +3,370 −0 bin/lib/ruby/1.8/net/imap.rb
  110. +879 −0 bin/lib/ruby/1.8/net/pop.rb
  111. +390 −0 bin/lib/ruby/1.8/net/protocol.rb
  112. +697 −0 bin/lib/ruby/1.8/net/smtp.rb
  113. +742 −0 bin/lib/ruby/1.8/net/telnet.rb
  114. +192 −0 bin/lib/ruby/1.8/observer.rb
  115. +679 −0 bin/lib/ruby/1.8/open-uri.rb
  116. +101 −0 bin/lib/ruby/1.8/open3.rb
  117. +1,788 −0 bin/lib/ruby/1.8/optparse.rb
  118. +17 −0 bin/lib/ruby/1.8/optparse/date.rb
  119. +6 −0 bin/lib/ruby/1.8/optparse/shellwords.rb
  120. +10 −0 bin/lib/ruby/1.8/optparse/time.rb
  121. +6 −0 bin/lib/ruby/1.8/optparse/uri.rb
  122. +70 −0 bin/lib/ruby/1.8/optparse/version.rb
  123. +146 −0 bin/lib/ruby/1.8/ostruct.rb
  124. +87 −0 bin/lib/ruby/1.8/parsearg.rb
  125. +53 −0 bin/lib/ruby/1.8/parsedate.rb
  126. +1,065 −0 bin/lib/ruby/1.8/pathname.rb
  127. +64 −0 bin/lib/ruby/1.8/ping.rb
Sorry, we could not display the entire diff because too many files (2,722) changed.
View
6 INSTALL
@@ -0,0 +1,6 @@
+# You don't have to do this unless you're building it from scratch
+# This has already been done in the external distribution
+- Unzip a gemstone product distribution into the gemstone/ directory
+- Copy the ruby extent from gemstone/bin to data/extent0.ruby.dbf
+- Copy a key to etc/maglev.demo.key
+- Load MagLev-avi.170.mcz or later
View
40 README
@@ -0,0 +1,40 @@
+Quick Start:
+
+You can run everything in MagLev using the 'gemstone' bash script in the bin subdirectory.
+For best results, set MAGLEV_HOME, and add $MAGLEV_HOME/bin to your PATH
+
+Usage:
+gemstone {start|start-debug|stop|restart|status|topaz|ruby|squeak|preload|force-reload|help}
+
+First, control the GemStone server from one terminal session:
+gemstone start - Start GemStone server processes
+gemstone start-debug - Start GemStone server processes with verbose output
+gemstone start-parser - Force parser process to start if it's dead
+gemstone stop - Stop GemStone server processes
+gemstone restart - Restart GemStone server processes
+gemstone status - Display GemStone server status
+gemstone preload <file> - Load and commit a file into an already running system
+gemstone force-reload - Stop GemStone server, overwrite with empty repository!!!
+
+Next, in a second terminal session, run other gemstone commands:
+gemstone ruby <file> - Execute a Ruby file
+gemstone topaz - Enter a Topaz shell
+gemstone topaz-debug - Enter a Topaz shell useful for debugging
+gemstone squeak - Start optional Squeak development environment
+gemstone help - Display this text
+
+Note:
+- set MAGLEV_HOME to the full path of this directory, and add $MAGLEV_HOME/bin to your PATH.
+ Then you can use "gemstone ruby" etc from anywhere.
+- if you have multiple installations, set JRUBY_PORT to control
+ which port the parser server listens on
+- the first (and ony the first) time you run a gemstone command that runs Ruby code,
+ it will load and compile prims.rb, which takes up to a minute to run.
+- gemstone ruby prints a topaz banner every time it is run. This will be fixed in a
+ future release. If you run "gemstone topaz" and then "maglev" you'll be in an irb-like
+ environment, and you won't get a banner on every command.
+
+Ruby code:
+- src/ and src/lib/ are both on the require path
+- src/kernel/ has the core Array, String etc files
+
View
304 bin/gemstone
@@ -0,0 +1,304 @@
+#!/bin/bash
+#
+# Runs GemStone scripts that used to be invoked as individual commands
+
+# Environment variable settings
+if [ -z "$MAGLEV_HOME" ]; then
+ if [ -x $PWD/gemstone/bin/startstone ]; then
+ # echo "using $PWD as MAGLEV_HOME"
+ export MAGLEV_HOME=$PWD
+ else
+ echo "$PWD is not a valid MAGLEV_HOME directory"
+ echo "To fix this, set a valid MAGLEV_HOME in your .bashrc"
+ exit 1
+ fi
+fi
+#
+if [ -z "$JRUBY_PORT" ]; then
+ # echo "using 2000 as JRUBY_PORT"
+ export JRUBY_PORT=2000
+fi
+#
+if [ -z "$JAVA_HOME" ]; then
+ # for MacOSX use current installed Java
+ if [[ "`uname -sr | cut -f1 -d '.'`" = "Darwin 9" && -e /Library/Java/Home ]]; then
+ export JAVA_HOME=/Library/Java/Home
+ else
+ # for Linux use either java-1.5 or java-6
+ if [ -e /usr/lib/jvm/java-1.5.0-sun ]; then
+ export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun
+ else
+ if [ -e /usr/lib/jvm/java-6-sun ]; then
+ export JAVA_HOME=/usr/lib/jvm/java-6-sun
+ fi
+ fi
+ fi
+fi
+#
+export GEMSTONE_GLOBAL_DIR=$MAGLEV_HOME
+export GEMSTONE_SYS_CONF=$MAGLEV_HOME/etc/system.conf
+export GEMSTONE_LOG=$MAGLEV_HOME/log/gs64stone.log
+export GEMSTONE=$MAGLEV_HOME/gemstone
+export TOPAZ_CMD="$GEMSTONE/bin/topaz -q -I $MAGLEV_HOME/etc/.topazini -l "
+export TOPAZDEBUG_CMD="$GEMSTONE/bin/topaz -I $MAGLEV_HOME/etc/.topazdebugini -l "
+export JRUBY_HOME=$MAGLEV_HOME/bin
+
+# Commands
+startserver() {
+ $GEMSTONE/bin/startnetldi -g &>/dev/null
+ $GEMSTONE/bin/startstone gs64stone &>/dev/null
+ $GEMSTONE/bin/waitstone gs64stone &>/dev/null
+ echo "GemStone server gs64stone started"
+}
+
+startserver-debug() {
+ $GEMSTONE/bin/startnetldi -g
+ $GEMSTONE/bin/startstone -z $MAGLEV_HOME/etc/system-debug.conf gs64stone
+ $GEMSTONE/bin/waitstone gs64stone
+ echo "GemStone server gs64stone started in verbose mode"
+}
+
+startparser() {
+ if [ -z "`lsof -Fp -iTCP:${JRUBY_PORT}`" ]; then
+ nohup $MAGLEV_HOME/bin/jruby $MAGLEV_HOME/bin/parser.rb \
+ >$MAGLEV_HOME/log/parser.log 2>/dev/null &
+ PARSER_PID="$!"
+ echo "MagLev Parse Server process $PARSER_PID started on port $JRUBY_PORT"
+ else
+ echo "MagLev Parse Server process already running on port $JRUBY_PORT"
+ fi
+}
+
+forceparser() {
+ nohup $MAGLEV_HOME/bin/jruby $MAGLEV_HOME/bin/parser.rb \
+ >$MAGLEV_HOME/log/parser.log 2>/dev/null &
+ PARSER_PID="$!"
+}
+
+startparser-debug() {
+ if [ -z "`lsof -Fp -iTCP:${JRUBY_PORT}`" ]; then
+ nohup $MAGLEV_HOME/bin/jruby $MAGLEV_HOME/bin/parser.rb \
+ >$MAGLEV_HOME/log/parser.log 2>$MAGLEV_HOME/log/parser.err &
+ PARSER_PID="$!"
+ echo "MagLev Parse Server process $PARSER_PID started on port $JRUBY_PORT in verbose mode"
+ echo "Parser logfiles are \$MAGLEV_HOME/log/parser.*"
+ else
+ echo "MagLev Parse Server process already running on port $JRUBY_PORT"
+ fi
+}
+
+stopserver() {
+ $GEMSTONE/bin/stopstone gs64stone DataCurator swordfish -i
+ $GEMSTONE/bin/stopnetldi
+}
+
+stopparser() {
+ if [ ! -z "`lsof -Fp -iTCP:${JRUBY_PORT}`" ]; then
+ kill `lsof -Fp -iTCP:${JRUBY_PORT} | cut -c2-`
+ fi
+}
+
+status() {
+ echo "MAGLEV_HOME = $MAGLEV_HOME"
+ $GEMSTONE/bin/gslist -clv
+ if [ ! -z "`lsof -Fp -iTCP:${JRUBY_PORT}`" ]; then
+ echo "MagLev Parse Server port = $JRUBY_PORT"
+ lsof -P -iTCP:${JRUBY_PORT}
+ netstat -an | grep "[:.]$JRUBY_PORT " | grep "LISTEN"
+ else
+ echo "MagLev Parse Server is not running on port $JRUBY_PORT"
+ fi
+}
+
+ruby() {
+ FILE=$PWD/$2
+ $TOPAZ_CMD <<ENDRUBY
+run
+RubyContext load.
+RubyContext loadFileNamed: '$FILE'.
+%
+exit
+ENDRUBY
+}
+
+spec() {
+ WD=$PWD
+ $TOPAZ_CMD <<ENDSPEC
+run
+RubyContext load.
+RubyContext requireFileNamed: 'mspec.rb'.
+RubyCompiler new evaluateString: '\$formatter = DottedFormatter.new; \$formatter.register'.
+('$*' findTokens: Character space) allButFirst do:
+ [:ea |
+ RubyContext loadFileNamed: '$WD/', ea].
+RubyCompiler new evaluateString: '\$formatter.finish'
+%
+exit
+ENDSPEC
+}
+
+topaz() {
+ if [ -z "`which rlwrap`" ]; then
+ $TOPAZ_CMD $@
+ else
+ rlwrap $TOPAZ_CMD $@
+ fi
+}
+
+topaz-debug() {
+ if [ -z "`which rlwrap`" ]; then
+ $TOPAZDEBUG_CMD $@
+ else
+ rlwrap $TOPAZDEBUG_CMD $@
+ fi
+}
+
+initialize() {
+ # grab a virgin repository if no repository exists
+ if [ ! -e $MAGLEV_HOME/data/extent0.ruby.dbf ]; then
+ cp -p $GEMSTONE/bin/extent0.ruby.dbf $MAGLEV_HOME/data/
+ chmod 660 $MAGLEV_HOME/data/extent0.ruby.dbf
+ fi
+}
+
+preload() {
+ $TOPAZ_CMD <<ENDPRELOAD
+run
+RubyContext load.
+RubyContext default loadFileNamed: '$1'.
+RubyContext save.
+%
+commit
+maglev
+puts 'MagLev preload $1 completed'
+quit
+exit
+ENDPRELOAD
+}
+
+destroy() {
+ rm -rf $MAGLEV_HOME/data/*dbf $MAGLEV_HOME/log/* $MAGLEV_HOME/locks/*
+}
+
+squeak() {
+ # If you use Squeak for development and debugging
+ if [ -e /Applications/GemTools.app ]; then
+ open /Applications/GemTools.app
+ else
+ echo "The application used by the 'squeak' command was not found on your system"
+ echo "To fix this, correct the 'squeak' command in the gemstone script"
+ fi
+}
+
+mri() {
+ export DYLD_LIBRARY_PATH=$GEMSTONE/lib32
+ irb -I $MAGLEV_HOME/gci -rgci
+}
+
+gemx() {
+ # If you use Squeak for development and debugging
+ if [ -e /Applications/GemX.app ]; then
+ open /Applications/GemX.app
+ else
+ echo "The application used by the 'gemx' command was not found on your system"
+ echo "To fix this, correct the 'gemx' command in the gemstone script"
+ fi
+}
+
+
+help() {
+cat <<ENDHELP
+Server Commands:
+gemstone start - Start GemStone server processes
+gemstone start-debug - Start GemStone server processes with verbose output
+gemstone start-parser - Force parser process to start if it's dead
+gemstone stop - Stop GemStone server processes
+gemstone restart - Restart GemStone server processes
+gemstone status - Display GemStone server status
+gemstone preload <file> - Load and commit a file into an already running system
+gemstone force-reload - Stop GemStone server, overwrite with empty repository!!!
+
+User Commands:
+gemstone ruby <file> - Execute a Ruby file
+gemstone topaz - Enter a Topaz shell
+gemstone topaz-debug - Enter a Topaz shell useful for debugging
+gemstone squeak - Start optional Squeak development environment
+gemstone help - Display this text
+
+Note:
+For best results, set MAGLEV_HOME, and add \$MAGLEV_HOME/bin to your PATH
+ENDHELP
+}
+
+# See what we were asked to do
+case "$1" in
+ start)
+ initialize
+ startserver
+ startparser
+ ;;
+ start-parser)
+ initialize
+ forceparser
+ ;;
+ start-debug)
+ initialize
+ startserver-debug
+ startparser-debug
+ ;;
+ stop)
+ stopserver
+ stopparser
+ ;;
+ restart)
+ stopserver
+ stopparser
+ startserver
+ startparser
+ ;;
+ status)
+ status
+ ;;
+ topaz)
+ shift
+ # pass params so we can execute 'gemstone topaz -T200000'
+ topaz $@
+ ;;
+ topaz-debug)
+ shift
+ # pass params so we can execute 'gemstone topaz -T200000'
+ topaz-debug $@
+ ;;
+ ruby)
+ # pass params so we can execute 'gemstone ruby <FILE>'
+ ruby $@
+ ;;
+ spec)
+ spec $@
+ ;;
+ squeak)
+ squeak
+ ;;
+ mri)
+ mri
+ ;;
+ gemx)
+ gemx
+ ;;
+ preload)
+ preload $2
+ ;;
+ force-reload)
+ stopserver
+ stopparser
+ destroy
+ initialize
+ ;;
+ help)
+ help
+ ;;
+ *)
+ echo $"Usage: "
+ echo $"gemstone {start|start-debug|stop|restart|status|topaz|topaz-debug|ruby|squeak|preload|force-reload|help}"
+ exit 1
+esac
View
166 bin/jruby
@@ -0,0 +1,166 @@
+#!/bin/bash
+# -----------------------------------------------------------------------------
+# jruby.sh - Start Script for the JRuby interpreter
+#
+# Environment Variable Prequisites
+#
+# JRUBY_BASE (Optional) Base directory for resolving dynamic portions
+# of a JRuby installation. If not present, resolves to
+# the same directory that JRUBY_HOME points to.
+#
+# JRUBY_HOME (Optional) May point at your JRuby "build" directory.
+# If not present, the current working directory is assumed.
+#
+# JRUBY_OPTS (Optional) Default JRuby command line args
+# JRUBY_SHELL Where/What is system shell
+#
+# JAVA_HOME Must point at your Java Development Kit installation.
+#
+# -----------------------------------------------------------------------------
+
+cygwin=false
+
+# ----- Identify OS we are running under --------------------------------------
+case "`uname`" in
+CYGWIN*) cygwin=true
+esac
+
+# ----- Verify and Set Required Environment Variables -------------------------
+
+if [ -z "$JRUBY_HOME" ] ; then
+ ## resolve links - $0 may be a link to home
+ PRG=$0
+ progname=`basename "$0"`
+
+ while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '.*/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG="`dirname $PRG`/$link"
+ fi
+ done
+
+ JRUBY_HOME_1=`dirname "$PRG"` # the ./bin dir
+ JRUBY_HOME_1=`dirname "$JRUBY_HOME_1"` # the . dir
+ if [ -d "${JRUBY_HOME_1}/lib" ] ; then
+ JRUBY_HOME="${JRUBY_HOME_1}"
+ fi
+else
+ if $cygwin; then
+ JRUBY_HOME=`cygpath -u "$JRUBY_HOME"`
+ fi
+fi
+
+if [ -z "$JRUBY_OPTS" ] ; then
+ JRUBY_OPTS=""
+fi
+
+if [ -z "$JAVA_HOME" ] ; then
+ JAVA_CMD='java'
+else
+ if $cygwin; then
+ JAVA_HOME=`cygpath -u "$JAVA_HOME"`
+ fi
+ JAVA_CMD="$JAVA_HOME/bin/java"
+fi
+
+JRUBY_SHELL=/bin/sh
+
+# ----- Set Up The System Classpath -------------------------------------------
+
+if [ "$JRUBY_PARENT_CLASSPATH" != "" ]; then
+ # Use same classpath propagated from parent jruby
+ CP=$JRUBY_PARENT_CLASSPATH
+else
+ if [ "$CLASSPATH" != "" ]; then
+ CP="$CLASSPATH"
+ if $cygwin; then
+ CP=`cygpath -p -u "$CP"`
+ fi
+ else
+ CP=""
+ fi
+
+ CP_DELIMETER=":"
+
+ # add necessary jars for command-line execution
+ for j in "$JRUBY_HOME"/lib/*.jar; do
+ if [ "$CP" ]; then
+ CP="$CP$CP_DELIMETER$j"
+ else
+ CP="$j"
+ fi
+ done
+
+ if $cygwin; then
+ CP=`cygpath -p -w "$CP"`
+ fi
+fi
+
+# ----- Set Up JRUBY_BASE If Necessary -------------------------------------
+
+if [ -z "$JRUBY_BASE" ] ; then
+ JRUBY_BASE="$JRUBY_HOME"
+fi
+
+# ----- Execute The Requested Command -----------------------------------------
+
+
+JAVA_MEM=-Xmx378m
+JAVA_STACK=-Xss1024k
+
+# Split out any -J argument for passing to the JVM.
+# Scanning for args is aborted by '--'.
+java_args=()
+ruby_args=()
+ while [ $# -gt 0 ]
+do
+ case "$1" in
+ # Stuff after '-J' in this argument goes to JVM
+ -J*)
+ val=${1:2}
+ if [ "${val:0:4}" = "-Xmx" ]; then
+ JAVA_MEM=$val
+ elif [ "${val:0:4}" = "-Xss" ]; then
+ JAVA_STACK=$val
+ else
+ java_args=("${java_args[@]}" "${1:2}")
+ fi
+ ;;
+ # Match switches that take an argument
+ -e|-I|-S) ruby_args=("${ruby_args[@]}" "$1" "$2"); shift ;;
+ # Match same switches with argument stuck together
+ -e*|-I*|-S*) ruby_args=("${ruby_args[@]}" "$1" ) ;;
+ # Abort processing on the double dash
+ --) break ;;
+ # Other opts go to ruby
+ -*) ruby_args=("${ruby_args[@]}" "$1") ;;
+ # Abort processing on first non-opt arg
+ *) break ;;
+ esac
+ shift
+done
+
+# Append the rest of the arguments
+ruby_args=("${ruby_args[@]}" "$@")
+
+# Put the ruby_args back into the position arguments $1, $2 etc
+set -- "${ruby_args[@]}"
+
+JAVA_OPTS="$JAVA_OPTS ${java_args[@]} $JAVA_MEM $JAVA_STACK"
+
+if $cygwin; then
+ JAVA_HOME=`cygpath --mixed "$JAVA_HOME"`
+ JRUBY_BASE=`cygpath --mixed "$JRUBY_BASE"`
+ JRUBY_HOME=`cygpath --mixed "$JRUBY_HOME"`
+ JRUBY_SHELL=`cygpath --mixed "$JRUBY_SHELL"`
+fi
+
+exec "$JAVA_CMD" $JAVA_OPTS -classpath "$CP" \
+ "-Djruby.base=$JRUBY_BASE" "-Djruby.home=$JRUBY_HOME" \
+ "-Djruby.lib=$JRUBY_BASE/lib" -Djruby.script=jruby \
+ "-Djruby.shell=$JRUBY_SHELL" \
+ org.jruby.Main $JRUBY_OPTS "$@"
+
View
BIN  bin/lib/bsf.jar
Binary file not shown
View
BIN  bin/lib/jruby.jar
Binary file not shown
View
106 bin/lib/ruby/1.8/.document
@@ -0,0 +1,106 @@
+# We only run RDoc on the top-level files in here: we skip
+# all the helper stuff in sub-directories
+
+# Eventually, we hope to see...
+# *.rb
+
+# But for now
+
+English.rb
+Env.rb
+README
+abbrev.rb
+base64.rb
+benchmark.rb
+cgi
+cgi.rb
+cgi-lib.rb
+complex.rb
+csv.rb
+date
+date.rb
+date2.rb
+debug.rb
+delegate.rb
+drb
+drb.rb
+e2mmap.rb
+erb.rb
+eregex.rb
+fileutils.rb
+finalize.rb
+find.rb
+forwardable.rb
+ftools.rb
+generator.rb
+getoptlong.rb
+getopts.rb
+gserver.rb
+importenv.rb
+ipaddr.rb
+irb
+irb.rb
+jcode.rb
+logger.rb
+mailread.rb
+mathn.rb
+matrix.rb
+mkmf.rb
+monitor.rb
+mutex_m.rb
+net
+observer.rb
+open-uri.rb
+open3.rb
+optparse
+optparse.rb
+ostruct.rb
+parsearg.rb
+parsedate.rb
+pathname.rb
+ping.rb
+pp.rb
+prettyprint.rb
+profile.rb
+profiler.rb
+pstore.rb
+racc
+rational.rb
+rdoc
+readbytes.rb
+resolv-replace.rb
+resolv.rb
+rexml
+rinda
+rss
+rss.rb
+rubyunit.rb
+runit
+scanf.rb
+set.rb
+shell
+shell.rb
+shellwords.rb
+singleton.rb
+soap
+sync.rb
+tempfile.rb
+test
+thread.rb
+thwait.rb
+time.rb
+timeout.rb
+tmpdir.rb
+tracer.rb
+tsort.rb
+un.rb
+uri
+uri.rb
+weakref.rb
+webrick
+webrick.rb
+wsdl
+xmlrpc
+xsd
+yaml
+yaml.rb
View
155 bin/lib/ruby/1.8/English.rb
@@ -0,0 +1,155 @@
+# Include the English library file in a Ruby script, and you can
+# reference the global variables such as \VAR{\$\_} using less
+# cryptic names, listed in the following table.% \vref{tab:english}.
+#
+# Without 'English':
+#
+# $\ = ' -- '
+# "waterbuffalo" =~ /buff/
+# print $", $', $$, "\n"
+#
+# With English:
+#
+# require "English"
+#
+# $OUTPUT_FIELD_SEPARATOR = ' -- '
+# "waterbuffalo" =~ /buff/
+# print $LOADED_FEATURES, $POSTMATCH, $PID, "\n"
+
+
+# The exception object passed to +raise+.
+alias $ERROR_INFO $!
+
+# The stack backtrace generated by the last
+# exception. <tt>See Kernel.caller</tt> for details. Thread local.
+alias $ERROR_POSITION $@
+
+# The default separator pattern used by <tt>String.split</tt>. May be
+# set from the command line using the <tt>-F</tt> flag.
+alias $FS $;
+
+# The default separator pattern used by <tt>String.split</tt>. May be
+# set from the command line using the <tt>-F</tt> flag.
+alias $FIELD_SEPARATOR $;
+
+# The separator string output between the parameters to methods such
+# as <tt>Kernel.print</tt> and <tt>Array.join</tt>. Defaults to +nil+,
+# which adds no text.
+alias $OFS $,
+
+# The separator string output between the parameters to methods such
+# as <tt>Kernel.print</tt> and <tt>Array.join</tt>. Defaults to +nil+,
+# which adds no text.
+alias $OUTPUT_FIELD_SEPARATOR $,
+
+# The input record separator (newline by default). This is the value
+# that routines such as <tt>Kernel.gets</tt> use to determine record
+# boundaries. If set to +nil+, +gets+ will read the entire file.
+alias $RS $/
+
+# The input record separator (newline by default). This is the value
+# that routines such as <tt>Kernel.gets</tt> use to determine record
+# boundaries. If set to +nil+, +gets+ will read the entire file.
+alias $INPUT_RECORD_SEPARATOR $/
+
+# The string appended to the output of every call to methods such as
+# <tt>Kernel.print</tt> and <tt>IO.write</tt>. The default value is
+# +nil+.
+alias $ORS $\
+
+# The string appended to the output of every call to methods such as
+# <tt>Kernel.print</tt> and <tt>IO.write</tt>. The default value is
+# +nil+.
+alias $OUTPUT_RECORD_SEPARATOR $\
+
+# The number of the last line read from the current input file.
+alias $INPUT_LINE_NUMBER $.
+
+# The number of the last line read from the current input file.
+alias $NR $.
+
+# The last line read by <tt>Kernel.gets</tt> or
+# <tt>Kernel.readline</tt>. Many string-related functions in the
+# +Kernel+ module operate on <tt>$_</tt> by default. The variable is
+# local to the current scope. Thread local.
+alias $LAST_READ_LINE $_
+
+# The destination of output for <tt>Kernel.print</tt>
+# and <tt>Kernel.printf</tt>. The default value is
+# <tt>$stdout</tt>.
+alias $DEFAULT_OUTPUT $>
+
+# An object that provides access to the concatenation
+# of the contents of all the files
+# given as command-line arguments, or <tt>$stdin</tt>
+# (in the case where there are no
+# arguments). <tt>$<</tt> supports methods similar to a
+# +File+ object:
+# +inmode+, +close+,
+# <tt>closed?</tt>, +each+,
+# <tt>each_byte</tt>, <tt>each_line</tt>,
+# +eof+, <tt>eof?</tt>, +file+,
+# +filename+, +fileno+,
+# +getc+, +gets+, +lineno+,
+# <tt>lineno=</tt>, +path+,
+# +pos+, <tt>pos=</tt>,
+# +read+, +readchar+,
+# +readline+, +readlines+,
+# +rewind+, +seek+, +skip+,
+# +tell+, <tt>to_a</tt>, <tt>to_i</tt>,
+# <tt>to_io</tt>, <tt>to_s</tt>, along with the
+# methods in +Enumerable+. The method +file+
+# returns a +File+ object for the file currently
+# being read. This may change as <tt>$<</tt> reads
+# through the files on the command line. Read only.
+alias $DEFAULT_INPUT $<
+
+# The process number of the program being executed. Read only.
+alias $PID $$
+
+# The process number of the program being executed. Read only.
+alias $PROCESS_ID $$
+
+# The exit status of the last child process to terminate. Read
+# only. Thread local.
+alias $CHILD_STATUS $?
+
+# A +MatchData+ object that encapsulates the results of a successful
+# pattern match. The variables <tt>$&</tt>, <tt>$`</tt>, <tt>$'</tt>,
+# and <tt>$1</tt> to <tt>$9</tt> are all derived from
+# <tt>$~</tt>. Assigning to <tt>$~</tt> changes the values of these
+# derived variables. This variable is local to the current
+# scope. Thread local.
+alias $LAST_MATCH_INFO $~
+
+# If set to any value apart from +nil+ or +false+, all pattern matches
+# will be case insensitive, string comparisons will ignore case, and
+# string hash values will be case insensitive. Deprecated
+alias $IGNORECASE $=
+
+# An array of strings containing the command-line
+# options from the invocation of the program. Options
+# used by the Ruby interpreter will have been
+# removed. Read only. Also known simply as +ARGV+.
+alias $ARGV $*
+
+# The string matched by the last successful pattern
+# match. This variable is local to the current
+# scope. Read only. Thread local.
+alias $MATCH $&
+
+# The string preceding the match in the last
+# successful pattern match. This variable is local to
+# the current scope. Read only. Thread local.
+alias $PREMATCH $`
+
+# The string following the match in the last
+# successful pattern match. This variable is local to
+# the current scope. Read only. Thread local.
+alias $POSTMATCH $'
+
+# The contents of the highest-numbered group matched in the last
+# successful pattern match. Thus, in <tt>"cat" =~ /(c|a)(t|z)/</tt>,
+# <tt>$+</tt> will be set to "t". This variable is local to the
+# current scope. Read only. Thread local.
+alias $LAST_PAREN_MATCH $+
View
18 bin/lib/ruby/1.8/Env.rb
@@ -0,0 +1,18 @@
+# Env.rb -- imports environment variables as global variables, Perlish ;(
+# Usage:
+#
+# require 'Env'
+# p $USER
+# $USER = "matz"
+# p ENV["USER"]
+
+require 'importenv'
+
+if __FILE__ == $0
+ p $TERM
+ $TERM = nil
+ p $TERM
+ p ENV["TERM"]
+ $TERM = "foo"
+ p ENV["TERM"]
+end
View
96 bin/lib/ruby/1.8/README
@@ -0,0 +1,96 @@
+English.rb lets Perl'ish global variables have English names
+Env.rb loads importenv.rb
+README this file
+base64.rb encodes/decodes base64 (obsolete)
+benchmark.rb a benchmark utility
+cgi-lib.rb simple CGI support library (old style)
+cgi.rb CGI support library
+cgi/session.rb CGI session class
+complex.rb complex number support
+csv.rb CSV parser/generator
+date.rb date object
+date/format.rb date parsing and formatting
+date2.rb date object (obsolete; use date)
+debug.rb ruby debugger
+delegate.rb delegates messages to other object
+drb.rb distributed Ruby
+e2mmap.rb exception utilities
+erb.rb tiny eRuby library
+eregex.rb extended regular expression (just a proof of concept)
+fileutils.rb file utilities
+finalize.rb adds finalizer to the object
+find.rb traverses directory tree
+forwardable.rb explicit delegation library
+ftools.rb file tools
+getoptlong.rb GNU getoptlong compatible
+getopts.rb parses command line options (use getoptlong)
+gserver.rb general TCP server
+importenv.rb imports environment variables as global variables
+ipaddr.rb defines the IPAddr class
+irb.rb interactive ruby
+jcode.rb Japanese text handling (replace String methods)
+logger.rb simple logging utility
+mailread.rb reads mail headers
+mathn.rb extended math operation
+matrix.rb matrix calculation library
+mkmf.rb Makefile maker
+monitor.rb exclusive region monitor for thread
+mutex_m.rb mutex mixin
+net/ftp.rb ftp access
+net/http.rb HTTP access
+net/imap.rb IMAP4 access
+net/pop.rb POP3 access
+net/protocol.rb abstract class for net library (DO NOT USE)
+net/smtp.rb SMTP access
+net/telnet.rb telnet library
+observer.rb observer desing pattern library (provides Observable)
+open-uri.rb easy-to-use network interface using URI and Net
+open3.rb opens subprocess connection stdin/stdout/stderr
+optparse.rb command line option analysis
+ostruct.rb python style object
+parsearg.rb argument parser using getopts
+parsedate.rb parses date string
+pathname.rb Object-Oriented Pathname Class
+ping.rb checks whether host is up, using TCP echo.
+pp.rb pretty print objects
+prettyprint.rb pretty printing algorithm
+profile.rb runs ruby profiler
+profiler.rb ruby profiler module
+pstore.rb persistent object strage using marshal
+racc/parser.rb racc (Ruby yACC) runtime
+rational.rb rational number support
+rdoc source-code documentation tool
+readbytes.rb define IO#readbytes
+resolv-replace.rb replace Socket DNS by resolve.rb
+resolv.rb DNS resolver in Ruby
+rexml an XML parser for Ruby, in Ruby
+rubyunit.rb original Ruby Unit testing framework
+scanf.rb scanf for Ruby
+set.rb defines the Set class
+shell.rb runs commands and does pipeline operations like shell
+shellwords.rb split into words like shell
+singleton.rb singleton design pattern library
+soap SOAP 1.1 implementation
+sync.rb 2 phase lock
+tempfile.rb temporary file with automatic removal
+test/unit Ruby Unit Testing Framework
+thread.rb thread support
+thwait.rb thread syncronization class
+time.rb RFC2822, RFC2616, ISO8601 style time formatting/parsing
+timeout.rb provides timeout
+tmpdir.rb retrieve temporary directory path
+tracer.rb execution tracer
+tsort.rb topological sorting
+un.rb Utilities to replace common UNIX commands in Makefiles etc
+uri.rb URI support
+uri/ftp.rb ftp scheme support
+uri/http.rb http scheme support
+uri/https.rb https scheme support
+uri/ldap.rb ldap scheme support
+uri/mailto.rb mailto scheme support
+weakref.rb weak reference class
+webrick.rb WEB server toolkit
+wsdl WSDL 1.1 implementation
+xmlrpc XML-RPC implementation
+xsd XML Schema Datatypes implementation
+yaml.rb YAML implementation
View
103 bin/lib/ruby/1.8/abbrev.rb
@@ -0,0 +1,103 @@
+#!/usr/bin/env ruby
+=begin
+#
+# Copyright (c) 2001,2003 Akinori MUSHA <knu@iDaemons.org>
+#
+# All rights reserved. You can redistribute and/or modify it under
+# the same terms as Ruby.
+#
+# $Idaemons: /home/cvs/rb/abbrev.rb,v 1.2 2001/05/30 09:37:45 knu Exp $
+# $RoughId: abbrev.rb,v 1.4 2003/10/14 19:45:42 knu Exp $
+# $Id: abbrev.rb 2906 2007-02-02 00:35:06Z headius $
+=end
+
+# Calculate the set of unique abbreviations for a given set of strings.
+#
+# require 'abbrev'
+# require 'pp'
+#
+# pp Abbrev::abbrev(['ruby', 'rules']).sort
+#
+# <i>Generates:</i>
+#
+# [["rub", "ruby"],
+# ["ruby", "ruby"],
+# ["rul", "rules"],
+# ["rule", "rules"],
+# ["rules", "rules"]]
+#
+# Also adds an +abbrev+ method to class +Array+.
+
+module Abbrev
+
+ # Given a set of strings, calculate the set of unambiguous
+ # abbreviations for those strings, and return a hash where the keys
+ # are all the possible abbreviations and the values are the full
+ # strings. Thus, given input of "car" and "cone", the keys pointing
+ # to "car" would be "ca" and "car", while those pointing to "cone"
+ # would be "co", "con", and "cone".
+ #
+ # The optional +pattern+ parameter is a pattern or a string. Only
+ # those input strings matching the pattern, or begging the string,
+ # are considered for inclusion in the output hash
+
+ def abbrev(words, pattern = nil)
+ table = {}
+ seen = Hash.new(0)
+
+ if pattern.is_a?(String)
+ pattern = /^#{Regexp.quote(pattern)}/ # regard as a prefix
+ end
+
+ words.each do |word|
+ next if (abbrev = word).empty?
+ while (len = abbrev.rindex(/[\w\W]\z/)) > 0
+ abbrev = word[0,len]
+
+ next if pattern && pattern !~ abbrev
+
+ case seen[abbrev] += 1
+ when 1
+ table[abbrev] = word
+ when 2
+ table.delete(abbrev)
+ else
+ break
+ end
+ end
+ end
+
+ words.each do |word|
+ next if pattern && pattern !~ word
+
+ table[word] = word
+ end
+
+ table
+ end
+
+ module_function :abbrev
+end
+
+class Array
+ # Calculates the set of unambiguous abbreviations for the strings in
+ # +self+. If passed a pattern or a string, only the strings matching
+ # the pattern or starting with the string are considered.
+ #
+ # %w{ car cone }.abbrev #=> { "ca" => "car", "car" => "car",
+ # "co" => "cone", "con" => cone",
+ # "cone" => "cone" }
+ def abbrev(pattern = nil)
+ Abbrev::abbrev(self, pattern)
+ end
+end
+
+if $0 == __FILE__
+ while line = gets
+ hash = line.split.abbrev
+
+ hash.sort.each do |k, v|
+ puts "#{k} => #{v}"
+ end
+ end
+end
View
133 bin/lib/ruby/1.8/base64.rb
@@ -0,0 +1,133 @@
+#
+# = base64.rb: methods for base64-encoding and -decoding stings
+#
+# Author:: Yukihiro Matsumoto
+# Documentation:: Dave Thomas and Gavin Sinclair
+#
+# Until Ruby 1.8.1, these methods were defined at the top-level. Now
+# they are in the Base64 module but included in the top-level, where
+# their usage is deprecated.
+#
+# See Base64 for documentation.
+#
+
+require "kconv"
+
+
+# The Base64 module provides for the encoding (#encode64) and decoding
+# (#decode64) of binary data using a Base64 representation.
+#
+# The following particular features are also provided:
+# - encode into lines of a given length (#b64encode)
+# - decode the special format specified in RFC2047 for the
+# representation of email headers (decode_b)
+#
+# == Example
+#
+# A simple encoding and decoding.
+#
+# require "base64"
+#
+# enc = Base64.encode64('Send reinforcements')
+# # -> "U2VuZCByZWluZm9yY2VtZW50cw==\n"
+# plain = Base64.decode64(enc)
+# # -> "Send reinforcements"
+#
+# The purpose of using base64 to encode data is that it translates any
+# binary data into purely printable characters. It is specified in
+# RFC 2045 (http://www.faqs.org/rfcs/rfc2045.html).
+
+module Base64
+ module_function
+
+ # Returns the Base64-decoded version of +str+.
+ #
+ # require 'base64'
+ # str = 'VGhpcyBpcyBsaW5lIG9uZQpUaGlzIG' +
+ # 'lzIGxpbmUgdHdvClRoaXMgaXMgbGlu' +
+ # 'ZSB0aHJlZQpBbmQgc28gb24uLi4K'
+ # puts Base64.decode64(str)
+ #
+ # <i>Generates:</i>
+ #
+ # This is line one
+ # This is line two
+ # This is line three
+ # And so on...
+
+ def decode64(str)
+ str.unpack("m")[0]
+ end
+
+
+ # Decodes text formatted using a subset of RFC2047 (the one used for
+ # mime-encoding mail headers).
+ #
+ # Only supports an encoding type of 'b' (base 64), and only supports
+ # the character sets ISO-2022-JP and SHIFT_JIS (so the only two
+ # encoded word sequences recognized are <tt>=?ISO-2022-JP?B?...=</tt> and
+ # <tt>=?SHIFT_JIS?B?...=</tt>). Recognition of these sequences is case
+ # insensitive.
+
+ def decode_b(str)
+ str.gsub!(/=\?ISO-2022-JP\?B\?([!->@-~]+)\?=/i) {
+ decode64($1)
+ }
+ str = Kconv::toeuc(str)
+ str.gsub!(/=\?SHIFT_JIS\?B\?([!->@-~]+)\?=/i) {
+ decode64($1)
+ }
+ str = Kconv::toeuc(str)
+ str.gsub!(/\n/, ' ')
+ str.gsub!(/\0/, '')
+ str
+ end
+
+ # Returns the Base64-encoded version of +str+.
+ #
+ # require 'base64'
+ # Base64.b64encode("Now is the time for all good coders\nto learn Ruby")
+ #
+ # <i>Generates:</i>
+ #
+ # Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
+ # UnVieQ==
+
+ def encode64(bin)
+ [bin].pack("m")
+ end
+
+ # _Prints_ the Base64 encoded version of +bin+ (a +String+) in lines of
+ # +len+ (default 60) characters.
+ #
+ # require 'base64'
+ # data = "Now is the time for all good coders\nto learn Ruby"
+ # Base64.b64encode(data)
+ #
+ # <i>Generates:</i>
+ #
+ # Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g
+ # UnVieQ==
+
+ def b64encode(bin, len = 60)
+ encode64(bin).scan(/.{1,#{len}}/) do
+ print $&, "\n"
+ end
+ end
+
+
+ module Deprecated # :nodoc:
+ include Base64
+
+ for m in Base64.private_instance_methods(false)
+ module_eval %{
+ def #{m}(*args)
+ warn("\#{caller(1)[0]}: #{m} is deprecated; use Base64.#{m} instead")
+ super
+ end
+ }
+ end
+ end
+end
+
+include Base64::Deprecated
View
569 bin/lib/ruby/1.8/benchmark.rb
@@ -0,0 +1,569 @@
+=begin
+#
+# benchmark.rb - a performance benchmarking library
+#
+# $Id: benchmark.rb 2062 2006-06-10 19:14:15Z headius $
+#
+# Created by Gotoken (gotoken@notwork.org).
+#
+# Documentation by Gotoken (original RD), Lyle Johnson (RDoc conversion), and
+# Gavin Sinclair (editing).
+#
+=end
+
+# == Overview
+#
+# The Benchmark module provides methods for benchmarking Ruby code, giving
+# detailed reports on the time taken for each task.
+#
+
+# The Benchmark module provides methods to measure and report the time
+# used to execute Ruby code.
+#
+# * Measure the time to construct the string given by the expression
+# <tt>"a"*1_000_000</tt>:
+#
+# require 'benchmark'
+#
+# puts Benchmark.measure { "a"*1_000_000 }
+#
+# On my machine (FreeBSD 3.2 on P5, 100MHz) this generates:
+#
+# 1.166667 0.050000 1.216667 ( 0.571355)
+#
+# This report shows the user CPU time, system CPU time, the sum of
+# the user and system CPU times, and the elapsed real time. The unit
+# of time is seconds.
+#
+# * Do some experiments sequentially using the #bm method:
+#
+# require 'benchmark'
+#
+# n = 50000
+# Benchmark.bm do |x|
+# x.report { for i in 1..n; a = "1"; end }
+# x.report { n.times do ; a = "1"; end }
+# x.report { 1.upto(n) do ; a = "1"; end }
+# end
+#
+# The result:
+#
+# user system total real
+# 1.033333 0.016667 1.016667 ( 0.492106)
+# 1.483333 0.000000 1.483333 ( 0.694605)
+# 1.516667 0.000000 1.516667 ( 0.711077)
+#
+# * Continuing the previous example, put a label in each report:
+#
+# require 'benchmark'
+#
+# n = 50000
+# Benchmark.bm(7) do |x|
+# x.report("for:") { for i in 1..n; a = "1"; end }
+# x.report("times:") { n.times do ; a = "1"; end }
+# x.report("upto:") { 1.upto(n) do ; a = "1"; end }
+# end
+#
+# The result:
+#
+# user system total real
+# for: 1.050000 0.000000 1.050000 ( 0.503462)
+# times: 1.533333 0.016667 1.550000 ( 0.735473)
+# upto: 1.500000 0.016667 1.516667 ( 0.711239)
+#
+#
+# * The times for some benchmarks depend on the order in which items
+# are run. These differences are due to the cost of memory
+# allocation and garbage collection. To avoid these discrepancies,
+# the #bmbm method is provided. For example, to compare ways to
+# sort an array of floats:
+#
+# require 'benchmark'
+#
+# array = (1..1000000).map { rand }
+#
+# Benchmark.bmbm do |x|
+# x.report("sort!") { array.dup.sort! }
+# x.report("sort") { array.dup.sort }
+# end
+#
+# The result:
+#
+# Rehearsal -----------------------------------------
+# sort! 11.928000 0.010000 11.938000 ( 12.756000)
+# sort 13.048000 0.020000 13.068000 ( 13.857000)
+# ------------------------------- total: 25.006000sec
+#
+# user system total real
+# sort! 12.959000 0.010000 12.969000 ( 13.793000)
+# sort 12.007000 0.000000 12.007000 ( 12.791000)
+#
+#
+# * Report statistics of sequential experiments with unique labels,
+# using the #benchmark method:
+#
+# require 'benchmark'
+#
+# n = 50000
+# Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
+# tf = x.report("for:") { for i in 1..n; a = "1"; end }
+# tt = x.report("times:") { n.times do ; a = "1"; end }
+# tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
+# [tf+tt+tu, (tf+tt+tu)/3]
+# end
+#
+# The result:
+#
+# user system total real
+# for: 1.016667 0.016667 1.033333 ( 0.485749)
+# times: 1.450000 0.016667 1.466667 ( 0.681367)
+# upto: 1.533333 0.000000 1.533333 ( 0.722166)
+# >total: 4.000000 0.033333 4.033333 ( 1.889282)
+# >avg: 1.333333 0.011111 1.344444 ( 0.629761)
+
+module Benchmark
+
+ BENCHMARK_VERSION = "2002-04-25" #:nodoc"
+
+ def Benchmark::times() # :nodoc:
+ Process::times()
+ end
+
+
+ # Invokes the block with a <tt>Benchmark::Report</tt> object, which
+ # may be used to collect and report on the results of individual
+ # benchmark tests. Reserves <i>label_width</i> leading spaces for
+ # labels on each line. Prints _caption_ at the top of the
+ # report, and uses _fmt_ to format each line.
+ # If the block returns an array of
+ # <tt>Benchmark::Tms</tt> objects, these will be used to format
+ # additional lines of output. If _label_ parameters are
+ # given, these are used to label these extra lines.
+ #
+ # _Note_: Other methods provide a simpler interface to this one, and are
+ # suitable for nearly all benchmarking requirements. See the examples in
+ # Benchmark, and the #bm and #bmbm methods.
+ #
+ # Example:
+ #
+ # require 'benchmark'
+ # include Benchmark # we need the CAPTION and FMTSTR constants
+ #
+ # n = 50000
+ # Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x|
+ # tf = x.report("for:") { for i in 1..n; a = "1"; end }
+ # tt = x.report("times:") { n.times do ; a = "1"; end }
+ # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end }
+ # [tf+tt+tu, (tf+tt+tu)/3]
+ # end
+ #
+ # <i>Generates:</i>
+ #
+ # user system total real
+ # for: 1.016667 0.016667 1.033333 ( 0.485749)
+ # times: 1.450000 0.016667 1.466667 ( 0.681367)
+ # upto: 1.533333 0.000000 1.533333 ( 0.722166)
+ # >total: 4.000000 0.033333 4.033333 ( 1.889282)
+ # >avg: 1.333333 0.011111 1.344444 ( 0.629761)
+ #
+
+ def benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) # :yield: report
+ sync = STDOUT.sync
+ STDOUT.sync = true
+ label_width ||= 0
+ fmtstr ||= FMTSTR
+ raise ArgumentError, "no block" unless iterator?
+ print caption
+ results = yield(Report.new(label_width, fmtstr))
+ Array === results and results.grep(Tms).each {|t|
+ print((labels.shift || t.label || "").ljust(label_width),
+ t.format(fmtstr))
+ }
+ STDOUT.sync = sync
+ end
+
+
+ # A simple interface to the #benchmark method, #bm is generates sequential reports
+ # with labels. The parameters have the same meaning as for #benchmark.
+ #
+ # require 'benchmark'
+ #
+ # n = 50000
+ # Benchmark.bm(7) do |x|
+ # x.report("for:") { for i in 1..n; a = "1"; end }
+ # x.report("times:") { n.times do ; a = "1"; end }
+ # x.report("upto:") { 1.upto(n) do ; a = "1"; end }
+ # end
+ #
+ # <i>Generates:</i>
+ #
+ # user system total real
+ # for: 1.050000 0.000000 1.050000 ( 0.503462)
+ # times: 1.533333 0.016667 1.550000 ( 0.735473)
+ # upto: 1.500000 0.016667 1.516667 ( 0.711239)
+ #
+
+ def bm(label_width = 0, *labels, &blk) # :yield: report
+ benchmark(" "*label_width + CAPTION, label_width, FMTSTR, *labels, &blk)
+ end
+
+
+ # Sometimes benchmark results are skewed because code executed
+ # earlier encounters different garbage collection overheads than
+ # that run later. #bmbm attempts to minimize this effect by running
+ # the tests twice, the first time as a rehearsal in order to get the
+ # runtime environment stable, the second time for
+ # real. <tt>GC.start</tt> is executed before the start of each of
+ # the real timings; the cost of this is not included in the
+ # timings. In reality, though, there's only so much that #bmbm can
+ # do, and the results are not guaranteed to be isolated from garbage
+ # collection and other effects.
+ #
+ # Because #bmbm takes two passes through the tests, it can
+ # calculate the required label width.
+ #
+ # require 'benchmark'
+ #
+ # array = (1..1000000).map { rand }
+ #
+ # Benchmark.bmbm do |x|
+ # x.report("sort!") { array.dup.sort! }
+ # x.report("sort") { array.dup.sort }
+ # end
+ #
+ # <i>Generates:</i>
+ #
+ # Rehearsal -----------------------------------------
+ # sort! 11.928000 0.010000 11.938000 ( 12.756000)
+ # sort 13.048000 0.020000 13.068000 ( 13.857000)
+ # ------------------------------- total: 25.006000sec
+ #
+ # user system total real
+ # sort! 12.959000 0.010000 12.969000 ( 13.793000)
+ # sort 12.007000 0.000000 12.007000 ( 12.791000)
+ #
+ # #bmbm yields a Benchmark::Job object and returns an array of
+ # Benchmark::Tms objects.
+ #
+ def bmbm(width = 0, &blk) # :yield: job
+ job = Job.new(width)
+ yield(job)
+ width = job.width
+ sync = STDOUT.sync
+ STDOUT.sync = true
+
+ # rehearsal
+ print "Rehearsal "
+ puts '-'*(width+CAPTION.length - "Rehearsal ".length)
+ list = []
+ job.list.each{|label,item|
+ print(label.ljust(width))
+ res = Benchmark::measure(&item)
+ print res.format()
+ list.push res
+ }
+ sum = Tms.new; list.each{|i| sum += i}
+ ets = sum.format("total: %tsec")
+ printf("%s %s\n\n",
+ "-"*(width+CAPTION.length-ets.length-1), ets)
+
+ # take
+ print ' '*width, CAPTION
+ list = []
+ ary = []
+ job.list.each{|label,item|
+ GC::start
+ print label.ljust(width)
+ res = Benchmark::measure(&item)
+ print res.format()
+ ary.push res
+ list.push [label, res]
+ }
+
+ STDOUT.sync = sync
+ ary
+ end
+
+ #
+ # Returns the time used to execute the given block as a
+ # Benchmark::Tms object.
+ #
+ def measure(label = "") # :yield:
+ t0, r0 = Benchmark.times, Time.now
+ yield
+ t1, r1 = Benchmark.times, Time.now
+ Benchmark::Tms.new(t1.utime - t0.utime,
+ t1.stime - t0.stime,
+ t1.cutime - t0.cutime,
+ t1.cstime - t0.cstime,
+ r1.to_f - r0.to_f,
+ label)
+ end
+
+ #
+ # Returns the elapsed real time used to execute the given block.
+ #
+ def realtime(&blk) # :yield:
+ Benchmark::measure(&blk).real
+ end
+
+
+
+ #
+ # A Job is a sequence of labelled blocks to be processed by the
+ # Benchmark.bmbm method. It is of little direct interest to the user.
+ #
+ class Job # :nodoc:
+ #
+ # Returns an initialized Job instance.
+ # Usually, one doesn't call this method directly, as new
+ # Job objects are created by the #bmbm method.
+ # _width_ is a initial value for the label offset used in formatting;
+ # the #bmbm method passes its _width_ argument to this constructor.
+ #
+ def initialize(width)
+ @width = width
+ @list = []
+ end
+
+ #
+ # Registers the given label and block pair in the job list.
+ #
+ def item(label = "", &blk) # :yield:
+ raise ArgmentError, "no block" unless block_given?
+ label.concat ' '
+ w = label.length
+ @width = w if @width < w
+ @list.push [label, blk]
+ self
+ end
+
+ alias report item
+
+ # An array of 2-element arrays, consisting of label and block pairs.
+ attr_reader :list
+
+ # Length of the widest label in the #list, plus one.
+ attr_reader :width
+ end
+
+ module_function :benchmark, :measure, :realtime, :bm, :bmbm
+
+
+
+ #
+ # This class is used by the Benchmark.benchmark and Benchmark.bm methods.
+ # It is of little direct interest to the user.
+ #
+ class Report # :nodoc:
+ #
+ # Returns an initialized Report instance.
+ # Usually, one doesn't call this method directly, as new
+ # Report objects are created by the #benchmark and #bm methods.
+ # _width_ and _fmtstr_ are the label offset and
+ # format string used by Tms#format.
+ #
+ def initialize(width = 0, fmtstr = nil)
+ @width, @fmtstr = width, fmtstr
+ end
+
+ #
+ # Prints the _label_ and measured time for the block,
+ # formatted by _fmt_. See Tms#format for the
+ # formatting rules.
+ #
+ def item(label = "", *fmt, &blk) # :yield:
+ print label.ljust(@width)
+ res = Benchmark::measure(&blk)
+ print res.format(@fmtstr, *fmt)
+ res
+ end
+
+ alias report item
+ end
+
+
+
+ #
+ # A data object, representing the times associated with a benchmark
+ # measurement.
+ #
+ class Tms
+ CAPTION = " user system total real\n"
+ FMTSTR = "%10.6u %10.6y %10.6t %10.6r\n"
+
+ # User CPU time
+ attr_reader :utime
+
+ # System CPU time
+ attr_reader :stime
+
+ # User CPU time of children
+ attr_reader :cutime
+
+ # System CPU time of children
+ attr_reader :cstime
+
+ # Elapsed real time
+ attr_reader :real
+
+ # Total time, that is _utime_ + _stime_ + _cutime_ + _cstime_
+ attr_reader :total
+
+ # Label
+ attr_reader :label
+
+ #
+ # Returns an initialized Tms object which has
+ # _u_ as the user CPU time, _s_ as the system CPU time,
+ # _cu_ as the children's user CPU time, _cs_ as the children's
+ # system CPU time, _real_ as the elapsed real time and _l_
+ # as the label.
+ #
+ def initialize(u = 0.0, s = 0.0, cu = 0.0, cs = 0.0, real = 0.0, l = nil)
+ @utime, @stime, @cutime, @cstime, @real, @label = u, s, cu, cs, real, l
+ @total = @utime + @stime + @cutime + @cstime
+ end
+
+ #
+ # Returns a new Tms object whose times are the sum of the times for this
+ # Tms object, plus the time required to execute the code block (_blk_).
+ #
+ def add(&blk) # :yield:
+ self + Benchmark::measure(&blk)
+ end
+
+ #
+ # An in-place version of #add.
+ #
+ def add!
+ t = Benchmark::measure(&blk)
+ @utime = utime + t.utime
+ @stime = stime + t.stime
+ @cutime = cutime + t.cutime
+ @cstime = cstime + t.cstime
+ @real = real + t.real
+ self
+ end
+
+ #
+ # Returns a new Tms object obtained by memberwise summation
+ # of the individual times for this Tms object with those of the other
+ # Tms object.
+ # This method and #/() are useful for taking statistics.
+ #
+ def +(other); memberwise(:+, other) end
+
+ #
+ # Returns a new Tms object obtained by memberwise subtraction
+ # of the individual times for the other Tms object from those of this
+ # Tms object.
+ #
+ def -(other); memberwise(:-, other) end
+
+ #
+ # Returns a new Tms object obtained by memberwise multiplication
+ # of the individual times for this Tms object by _x_.
+ #
+ def *(x); memberwise(:*, x) end
+
+ #
+ # Returns a new Tms object obtained by memberwise division
+ # of the individual times for this Tms object by _x_.
+ # This method and #+() are useful for taking statistics.
+ #
+ def /(x); memberwise(:/, x) end
+
+ #
+ # Returns the contents of this Tms object as
+ # a formatted string, according to a format string
+ # like that passed to Kernel.format. In addition, #format
+ # accepts the following extensions:
+ #
+ # <tt>%u</tt>:: Replaced by the user CPU time, as reported by Tms#utime.
+ # <tt>%y</tt>:: Replaced by the system CPU time, as reported by #stime (Mnemonic: y of "s*y*stem")
+ # <tt>%U</tt>:: Replaced by the children's user CPU time, as reported by Tms#cutime
+ # <tt>%Y</tt>:: Replaced by the children's system CPU time, as reported by Tms#cstime
+ # <tt>%t</tt>:: Replaced by the total CPU time, as reported by Tms#total
+ # <tt>%r</tt>:: Replaced by the elapsed real time, as reported by Tms#real
+ # <tt>%n</tt>:: Replaced by the label string, as reported by Tms#label (Mnemonic: n of "*n*ame")
+ #
+ # If _fmtstr_ is not given, FMTSTR is used as default value, detailing the
+ # user, system and real elapsed time.
+ #
+ def format(arg0 = nil, *args)
+ fmtstr = (arg0 || FMTSTR).dup
+ fmtstr.gsub!(/(%[-+\.\d]*)n/){"#{$1}s" % label}
+ fmtstr.gsub!(/(%[-+\.\d]*)u/){"#{$1}f" % utime}
+ fmtstr.gsub!(/(%[-+\.\d]*)y/){"#{$1}f" % stime}
+ fmtstr.gsub!(/(%[-+\.\d]*)U/){"#{$1}f" % cutime}
+ fmtstr.gsub!(/(%[-+\.\d]*)Y/){"#{$1}f" % cstime}
+ fmtstr.gsub!(/(%[-+\.\d]*)t/){"#{$1}f" % total}
+ fmtstr.gsub!(/(%[-+\.\d]*)r/){"(#{$1}f)" % real}
+ arg0 ? Kernel::format(fmtstr, *args) : fmtstr
+ end
+
+ #
+ # Same as #format.
+ #
+ def to_s
+ format
+ end
+
+ #
+ # Returns a new 6-element array, consisting of the
+ # label, user CPU time, system CPU time, children's
+ # user CPU time, children's system CPU time and elapsed
+ # real time.
+ #
+ def to_a
+ [@label, @utime, @stime, @cutime, @cstime, @real]
+ end
+
+ protected
+ def memberwise(op, x)
+ case x
+ when Benchmark::Tms
+ Benchmark::Tms.new(utime.__send__(op, x.utime),
+ stime.__send__(op, x.stime),
+ cutime.__send__(op, x.cutime),
+ cstime.__send__(op, x.cstime),
+ real.__send__(op, x.real)
+ )
+ else
+ Benchmark::Tms.new(utime.__send__(op, x),
+ stime.__send__(op, x),
+ cutime.__send__(op, x),
+ cstime.__send__(op, x),
+ real.__send__(op, x)
+ )
+ end
+ end
+ end
+
+ # The default caption string (heading above the output times).
+ CAPTION = Benchmark::Tms::CAPTION
+
+ # The default format string used to display times. See also Benchmark::Tms#format.
+ FMTSTR = Benchmark::Tms::FMTSTR
+end
+
+if __FILE__ == $0
+ include Benchmark
+
+ n = ARGV[0].to_i.nonzero? || 50000
+ puts %Q([#{n} times iterations of `a = "1"'])
+ benchmark(" " + CAPTION, 7, FMTSTR) do |x|
+ x.report("for:") {for i in 1..n; a = "1"; end} # Benchmark::measure
+ x.report("times:") {n.times do ; a = "1"; end}
+ x.report("upto:") {1.upto(n) do ; a = "1"; end}
+ end
+
+ benchmark do
+ [
+ measure{for i in 1..n; a = "1"; end}, # Benchmark::measure
+ measure{n.times do ; a = "1"; end},
+ measure{1.upto(n) do ; a = "1"; end}
+ ]
+ end
+end
View
85 bin/lib/ruby/1.8/bigdecimal/jacobian.rb
@@ -0,0 +1,85 @@
+#
+# require 'bigdecimal/jacobian'
+#
+# Provides methods to compute the Jacobian matrix of a set of equations at a
+# point x. In the methods below:
+#
+# f is an Object which is used to compute the Jacobian matrix of the equations.
+# It must provide the following methods:
+#
+# f.values(x):: returns the values of all functions at x
+#
+# f.zero:: returns 0.0
+# f.one:: returns 1.0
+# f.two:: returns 1.0
+# f.ten:: returns 10.0
+#
+# f.eps:: returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal.
+#
+# x is the point at which to compute the Jacobian.
+#
+# fx is f.values(x).
+#
+module Jacobian
+ #--
+ def isEqual(a,b,zero=0.0,e=1.0e-8)
+ aa = a.abs
+ bb = b.abs
+ if aa == zero && bb == zero then
+ true
+ else
+ if ((a-b)/(aa+bb)).abs < e then
+ true
+ else
+ false
+ end
+ end
+ end
+ #++
+
+ # Computes the derivative of f[i] at x[i].
+ # fx is the value of f at x.
+ def dfdxi(f,fx,x,i)
+ nRetry = 0
+ n = x.size
+ xSave = x[i]
+ ok = 0
+ ratio = f.ten*f.ten*f.ten
+ dx = x[i].abs/ratio
+ dx = fx[i].abs/ratio if isEqual(dx,f.zero,f.zero,f.eps)
+ dx = f.one/f.ten if isEqual(dx,f.zero,f.zero,f.eps)
+ until ok>0 do
+ s = f.zero
+ deriv = []
+ if(nRetry>100) then
+ raize "Singular Jacobian matrix. No change at x[" + i.to_s + "]"
+ end
+ dx = dx*f.two
+ x[i] += dx
+ fxNew = f.values(x)
+ for j in 0...n do
+ if !isEqual(fxNew[j],fx[j],f.zero,f.eps) then
+ ok += 1
+ deriv <<= (fxNew[j]-fx[j])/dx
+ else
+ deriv <<= f.zero
+ end
+ end
+ x[i] = xSave
+ end
+ deriv
+ end
+
+ # Computes the Jacobian of f at x. fx is the value of f at x.
+ def jacobian(f,fx,x)
+ n = x.size
+ dfdx = Array::new(n*n)
+ for i in 0...n do
+ df = dfdxi(f,fx,x,i)
+ for j in 0...n do
+ dfdx[j*n+i] = df[j]
+ end
+ end
+ dfdx
+ end
+end
View
84 bin/lib/ruby/1.8/bigdecimal/ludcmp.rb
@@ -0,0 +1,84 @@
+#
+# Solves a*x = b for x, using LU decomposition.
+#
+module LUSolve
+ # Performs LU decomposition of the n by n matrix a.
+ def ludecomp(a,n,zero=0,one=1)
+ prec = BigDecimal.limit(nil)
+ ps = []
+ scales = []
+ for i in 0...n do # pick up largest(abs. val.) element in each row.
+ ps <<= i
+ nrmrow = zero
+ ixn = i*n
+ for j in 0...n do
+ biggst = a[ixn+j].abs
+ nrmrow = biggst if biggst>nrmrow
+ end
+ if nrmrow>zero then
+ scales <<= one.div(nrmrow,prec)
+ else
+ raise "Singular matrix"
+ end
+ end
+ n1 = n - 1
+ for k in 0...n1 do # Gaussian elimination with partial pivoting.
+ biggst = zero;
+ for i in k...n do
+ size = a[ps[i]*n+k].abs*scales[ps[i]]
+ if size>biggst then
+ biggst = size
+ pividx = i
+ end
+ end
+ raise "Singular matrix" if biggst<=zero
+ if pividx!=k then
+ j = ps[k]
+ ps[k] = ps[pividx]
+ ps[pividx] = j
+ end
+ pivot = a[ps[k]*n+k]
+ for i in (k+1)...n do
+ psin = ps[i]*n
+ a[psin+k] = mult = a[psin+k].div(pivot,prec)
+ if mult!=zero then
+ pskn = ps[k]*n
+ for j in (k+1)...n do
+ a[psin+j] -= mult.mult(a[pskn+j],prec)
+ end
+ end
+ end
+ end
+ raise "Singular matrix" if a[ps[n1]*n+n1] == zero
+ ps
+ end
+
+ # Solves a*x = b for x, using LU decomposition.
+ #
+ # a is a matrix, b is a constant vector, x is the solution vector.
+ #
+ # ps is the pivot, a vector which indicates the permutation of rows performed
+ # during LU decomposition.
+ def lusolve(a,b,ps,zero=0.0)
+ prec = BigDecimal.limit(nil)
+ n = ps.size
+ x = []
+ for i in 0...n do
+ dot = zero
+ psin = ps[i]*n
+ for j in 0...i do
+ dot = a[psin+j].mult(x[j],prec) + dot
+ end
+ x <<= b[ps[i]] - dot
+ end
+ (n-1).downto(0) do |i|
+ dot = zero
+ psin = ps[i]*n
+ for j in (i+1)...n do
+ dot = a[psin+j].mult(x[j],prec) + dot
+ end
+ x[i] = (x[i]-dot).div(a[psin+i],prec)
+ end
+ x
+ end
+end
View
235 bin/lib/ruby/1.8/bigdecimal/math.rb
@@ -0,0 +1,235 @@
+#
+#--
+# Contents:
+# sqrt(x, prec)
+# sin (x, prec)
+# cos (x, prec)
+# atan(x, prec) Note: |x|<1, x=0.9999 may not converge.
+# exp (x, prec)
+# log (x, prec)
+# PI (prec)
+# E (prec) == exp(1.0,prec)
+#
+# where:
+# x ... BigDecimal number to be computed.
+# |x| must be small enough to get convergence.
+# prec ... Number of digits to be obtained.
+#++
+#
+# Provides mathematical functions.
+#
+# Example:
+#
+# require "bigdecimal"
+# require "bigdecimal/math"
+#
+# include BigMath
+#
+# a = BigDecimal((PI(100)/2).to_s)
+# puts sin(a,100) # -> 0.10000000000000000000......E1
+#
+module BigMath
+
+ # Computes the square root of x to the specified number of digits of
+ # precision.
+ #
+ # BigDecimal.new('2').sqrt(16).to_s
+ # -> "0.14142135623730950488016887242096975E1"
+ #
+ def sqrt(x,prec)
+ x.sqrt(prec)
+ end
+
+ # Computes the sine of x to the specified number of digits of precision.
+ #
+ # If x is infinite or NaN, returns NaN.
+ def sin(x, prec)
+ raise ArgumentError, "Zero or negative precision for sin" if prec <= 0
+ return BigDecimal("NaN") if x.infinite? || x.nan?
+ n = prec + BigDecimal.double_fig
+ one = BigDecimal("1")
+ two = BigDecimal("2")
+ x1 = x
+ x2 = x.mult(x,n)
+ sign = 1
+ y = x
+ d = y
+ i = one
+ z = one
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ sign = -sign
+ x1 = x2.mult(x1,n)
+ i += two
+ z *= (i-one) * i
+ d = sign * x1.div(z,m)
+ y += d
+ end
+ y
+ end
+
+ # Computes the cosine of x to the specified number of digits of precision.
+ #
+ # If x is infinite or NaN, returns NaN.
+ def cos(x, prec)
+ raise ArgumentError, "Zero or negative precision for cos" if prec <= 0
+ return BigDecimal("NaN") if x.infinite? || x.nan?
+ n = prec + BigDecimal.double_fig
+ one = BigDecimal("1")
+ two = BigDecimal("2")
+ x1 = one
+ x2 = x.mult(x,n)
+ sign = 1
+ y = one
+ d = y
+ i = BigDecimal("0")
+ z = one
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ sign = -sign
+ x1 = x2.mult(x1,n)
+ i += two
+ z *= (i-one) * i
+ d = sign * x1.div(z,m)
+ y += d
+ end
+ y
+ end
+
+ # Computes the arctangent of x to the specified number of digits of precision.
+ #
+ # If x is infinite or NaN, returns NaN.
+ # Raises an argument error if x > 1.
+ def atan(x, prec)
+ raise ArgumentError, "Zero or negative precision for atan" if prec <= 0
+ return BigDecimal("NaN") if x.infinite? || x.nan?
+ raise ArgumentError, "x.abs must be less than 1.0" if x.abs>=1
+ n = prec + BigDecimal.double_fig
+ y = x
+ d = y
+ t = x
+ r = BigDecimal("3")
+ x2 = x.mult(x,n)
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ t = -t.mult(x2,n)
+ d = t.div(r,m)
+ y += d
+ r += 2
+ end
+ y
+ end
+
+ # Computes the value of e (the base of natural logarithms) raised to the
+ # power of x, to the specified number of digits of precision.
+ #
+ # If x is infinite or NaN, returns NaN.
+ #
+ # BigMath::exp(BigDecimal.new('1'), 10).to_s
+ # -> "0.271828182845904523536028752390026306410273E1"
+ def exp(x, prec)
+ raise ArgumentError, "Zero or negative precision for exp" if prec <= 0
+ return BigDecimal("NaN") if x.infinite? || x.nan?
+ n = prec + BigDecimal.double_fig
+ one = BigDecimal("1")
+ x1 = one
+ y = one
+ d = y
+ z = one
+ i = 0
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ x1 = x1.mult(x,n)
+ i += 1
+ z *= i
+ d = x1.div(z,m)
+ y += d
+ end
+ y
+ end
+
+ # Computes the natural logarithm of x to the specified number of digits
+ # of precision.
+ #
+ # Returns x if x is infinite or NaN.
+ #
+ def log(x, prec)
+ raise ArgumentError, "Zero or negative argument for log" if x <= 0 || prec <= 0
+ return x if x.infinite? || x.nan?
+ one = BigDecimal("1")
+ two = BigDecimal("2")
+ n = prec + BigDecimal.double_fig
+ x = (x - one).div(x + one,n)
+ x2 = x.mult(x,n)
+ y = x
+ d = y
+ i = one
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ x = x2.mult(x,n)
+ i += two
+ d = x.div(i,m)
+ y += d
+ end
+ y*two
+ end
+
+ # Computes the value of pi to the specified number of digits of precision.
+ def PI(prec)
+ raise ArgumentError, "Zero or negative argument for PI" if prec <= 0
+ n = prec + BigDecimal.double_fig
+ zero = BigDecimal("0")
+ one = BigDecimal("1")
+ two = BigDecimal("2")
+
+ m25 = BigDecimal("-0.04")
+ m57121 = BigDecimal("-57121")
+
+ pi = zero
+
+ d = one
+ k = one
+ w = one
+ t = BigDecimal("-80")
+ while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ t = t*m25
+ d = t.div(k,m)
+ k = k+two
+ pi = pi + d
+ end
+
+ d = one
+ k = one
+ w = one
+ t = BigDecimal("956")
+ while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ t = t.div(m57121,n)
+ d = t.div(k,m)
+ pi = pi + d
+ k = k+two
+ end
+ pi
+ end
+
+ # Computes e (the base of natural logarithms) to the specified number of
+ # digits of precision.
+ def E(prec)
+ raise ArgumentError, "Zero or negative precision for E" if prec <= 0
+ n = prec + BigDecimal.double_fig
+ one = BigDecimal("1")
+ y = one
+ d = y
+ z = one
+ i = 0
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ i += 1
+ z *= i
+ d = one.div(z,m)
+ y += d
+ end
+ y
+ end
+end
View
77 bin/lib/ruby/1.8/bigdecimal/newton.rb
@@ -0,0 +1,77 @@
+#
+# newton.rb
+#
+# Solves the nonlinear algebraic equation system f = 0 by Newton's method.
+# This program is not dependent on BigDecimal.
+#
+# To call:
+# n = nlsolve(f,x)
+# where n is the number of iterations required,
+# x is the initial value vector
+# f is an Object which is used to compute the values of the equations to be solved.
+# It must provide the following methods:
+#
+# f.values(x):: returns the values of all functions at x
+#
+# f.zero:: returns 0.0
+# f.one:: returns 1.0
+# f.two:: returns 1.0
+# f.ten:: returns 10.0
+#
+# f.eps:: returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal.
+#
+# On exit, x is the solution vector.
+#
+require "bigdecimal/ludcmp"
+require "bigdecimal/jacobian"
+
+module Newton
+ include LUSolve
+ include Jacobian
+
+ def norm(fv,zero=0.0)
+ s = zero
+ n = fv.size
+ for i in 0...n do
+ s += fv[i]*fv[i]
+ end
+ s
+ end
+
+ def nlsolve(f,x)
+ nRetry = 0
+ n = x.size
+
+ f0 = f.values(x)
+ zero = f.zero
+ one = f.one
+ two = f.two
+ p5 = one/two
+ d = norm(f0,zero)
+ minfact = f.ten*f.ten*f.ten
+ minfact = one/minfact
+ e = f.eps
+ while d >= e do
+ nRetry += 1
+ # Not yet converged. => Compute Jacobian matrix
+ dfdx = jacobian(f,f0,x)
+ # Solve dfdx*dx = -f0 to estimate dx
+ dx = lusolve(dfdx,f0,ludecomp(dfdx,n,zero,one),zero)
+ fact = two
+ xs = x.dup
+ begin
+ fact *= p5
+ if fact < minfact then
+ raise "Failed to reduce function values."
+ end
+ for i in 0...n do
+ x[i] = xs[i] - dx[i]*fact
+ end
+ f0 = f.values(x)
+ dn = norm(f0,zero)
+ end while(dn>=d)
+ d = dn
+ end
+ nRetry
+ end
+end
View
65 bin/lib/ruby/1.8/bigdecimal/util.rb
@@ -0,0 +1,65 @@
+#
+# BigDecimal utility library.
+#
+# To use these functions, require 'bigdecimal/util'
+#
+# The following methods are provided to convert other types to BigDecimals:
+#
+# String#to_d -> BigDecimal
+# Float#to_d -> BigDecimal
+# Rational#to_d -> BigDecimal
+#
+# The following method is provided to convert BigDecimals to other types:
+#
+# BigDecimal#to_r -> Rational
+#
+# ----------------------------------------------------------------------
+#
+class Float < Numeric
+ def to_d
+ BigDecimal(self.to_s)
+ end
+end
+
+class String
+ def to_d
+ BigDecimal(self)
+ end
+end
+
+class BigDecimal < Numeric
+ # Converts a BigDecimal to a String of the form "nnnnnn.mmm".
+ # This method is deprecated; use BigDecimal#to_s("F") instead.
+ def to_digits
+ if self.nan? || self.infinite? || self.zero?
+ self.to_s
+ else
+ i = self.to_i.to_s
+ s,f,y,z = self.frac.split
+ i + "." + ("0"*(-z)) + f
+ end
+ end
+
+ # Converts a BigDecimal to a Rational.
+ def to_r
+ sign,digits,base,power = self.split
+ numerator = sign*digits.to_i
+ denomi_power = power - digits.size # base is always 10
+ if denomi_power < 0
+ Rational(numerator,base ** (-denomi_power))
+ else
+ Rational(numerator * (base ** denomi_power),1)
+ end
+ end
+end
+