File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.156: download - view: text, annotated - select for diffs
Tue Jun 7 22:07:09 2011 UTC (12 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #6311: Allow for algebraic input in numerical response

    1: # The LearningOnline Network with CAPA 
    2: # used by lonxml::xmlparse() as input variable $safeinit to Apache::run::run()
    3: #
    4: # $Id: default_homework.lcpm,v 1.156 2011/06/07 22:07:09 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: #
   29: 
   30: #init some globals
   31: $hidden::RANDOMINIT=0;
   32: $pi=atan2(1,1)*4;
   33: $rad2deg=180.0/$pi;
   34: $deg2rad=$pi/180.0;
   35: $"=' ';
   36: use strict;
   37: {
   38:     my $n = 0;
   39:     my $total = 0;
   40:     my $num_left = 0;
   41:     my @order;
   42:     my $type;
   43: 
   44:     sub init_permutation {
   45: 	my ($size,$requested_type) = @_;
   46: 	@order = (0..$size-1);
   47: 	$n = $size;
   48: 	$type = $requested_type;
   49: 	if ($type eq 'ordered') {
   50: 	    $total = $num_left = 1;
   51: 	} elsif ($type eq 'unordered') {
   52: 	    $total = $num_left = &factorial($size);
   53: 	} else {
   54: 	    die("Unkown type: $type");
   55: 	}
   56:     }
   57: 
   58:     sub get_next_permutation {
   59: 	if ($num_left == $total) {
   60: 	    $num_left--;
   61: 	    return \@order;
   62: 	}
   63: 
   64: 	# Find largest index j with a[j] < a[j+1]
   65: 
   66: 	my $j = scalar(@order) - 2;
   67: 	while ($order[$j] > $order[$j+1]) {
   68: 	    $j--;
   69: 	}
   70: 
   71: 	# Find index k such that a[k] is smallest integer
   72: 	# greater than a[j] to the right of a[j]
   73: 
   74: 	my $k = scalar(@order) - 1;
   75: 	while ($order[$j] > $order[$k]) {
   76: 	    $k--;
   77: 	}
   78: 
   79: 	# Interchange a[j] and a[k]
   80: 
   81: 	@order[($k,$j)] = @order[($j,$k)];
   82: 
   83: 	# Put tail end of permutation after jth position in increasing order
   84: 
   85: 	my $r = scalar(@order) - 1;
   86: 	my $s = $j + 1;
   87: 
   88: 	while ($r > $s) {
   89: 	    @order[($s,$r)]=@order[($r,$s)];
   90: 	    $r--;
   91: 	    $s++;
   92: 	}
   93: 
   94: 	$num_left--;
   95: 	return(\@order);
   96:     }
   97:     
   98:     sub get_permutations_left {
   99: 	return $num_left;
  100:     }
  101: }
  102: 
  103: sub check_commas {
  104:     my ($response)=@_;
  105:     #print("$response ");
  106:     my @numbers=split(',',$response);
  107:     #print(" numbers ".join('-',@numbers)." ");
  108:     if (scalar(@numbers) > 1) {
  109:         #print(" numbers[0] ".$numbers[0]." "); 
  110: 	if (length($numbers[0]) > 3 || length($numbers[0]) == 0) { return -1; }
  111: 	shift(@numbers);
  112: 	#print(" numbers ".scalar(@numbers)." ");
  113: 	while (scalar(@numbers) > 1) {
  114: 	    #print(" numbers ".join('-',@numbers)." ");
  115: 	    if (length($numbers[0]) != 3) { return -2; }
  116: 	    shift(@numbers);
  117: 	}
  118: 	my ($number)=split('\.',$numbers[0]);
  119: 	#print(" number ".$number." ");
  120: 	#print(" numbers[0] ".$numbers[0]." ");
  121: 	if (length($number) != 3) { return -3; }
  122:     } else {
  123: 	my ($number)=split('\.',$numbers[0]);
  124: 	if (length($number) > 3) { return -4; }
  125:     }
  126:     return 1;
  127: }
  128: 
  129: 
  130: sub caparesponse_check {
  131:     my ($answer,$response)=@_;
  132:     #not properly used yet: calc
  133:     #not to be used: $ans_fmt
  134:     my $type=$LONCAPA::CAPAresponse_args{'type'};
  135:     my $tol=$LONCAPA::CAPAresponse_args{'tol'};
  136:     my $sig=$LONCAPA::CAPAresponse_args{'sig'};
  137:     my $ans_fmt=$LONCAPA::CAPAresponse_args{'format'};
  138:     my $unit=$LONCAPA::CAPAresponse_args{'unit'};
  139:     my $calc=$LONCAPA::CAPAresponse_args{'calc'};
  140:     my $samples=$LONCAPA::CAPAresponse_args{'samples'};
  141:     
  142:     my $tol_type=''; # gets it's value from whether tol has a % or not done
  143:     my $sig_lbound=''; #done
  144:     my $sig_ubound=''; #done
  145: 
  146: 
  147:     #type's definitons come from capaParser.h
  148: 
  149:     #remove leading and trailing whitespace
  150:     if (!defined($response)) {
  151: 	$response='';
  152:     }
  153:     if ($response=~ /^\s|\s$/) {
  154: 	$response=~ s:^\s+|\s+$::g;
  155: 	&LONCAPA_INTERNAL_DEBUG("Removed ws now :$response:");
  156:     }
  157: 
  158:     #&LONCAPA_INTERNAL_DEBUG(" type is $type ");
  159:     if ($type eq 'cs' || $type eq 'ci') {
  160: 	#for string answers make sure all places spaces occur, there is 
  161:         #really only 1 space, in both the answer and the response
  162: 	$answer=~s/ +/ /g;
  163: 	$response=~s/ +/ /g;
  164:     } elsif ($type eq 'mc') {
  165: 	$answer=~s/[\s,]//g;
  166: 	$response=~s/[\s,]//g;
  167:     }
  168:     if ($type eq 'float' && $unit=~/\$/) {
  169: 	if ($response!~/^\$|\$$/)  { return ('NO_UNIT', undef); }
  170: 	$response=~s/\$//g;
  171:     }
  172:     if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
  173: 	return "COMMA_FAIL:";
  174:     }
  175:     $ans_fmt=~s/\W//g;
  176:     $unit=~s/[\$,]//g;
  177:     if ($type eq 'float') { $response=~s/,//g; }
  178: 
  179:     if (length($response) > 500) { return ('TOO_LONG',undef); }
  180: 
  181:     if ($type eq '' ) {
  182: 	&LONCAPA_INTERNAL_DEBUG("Didn't find a type :$type: defaulting");
  183: 	if ( $answer eq ($answer *1.0)) { $type = 2;
  184: 				      } else { $type = 3; }
  185:     } else {
  186: 	if    ($type eq 'cs')    { $type = 4; }
  187: 	elsif ($type eq 'ci')    { $type = 3 }
  188: 	elsif ($type eq 'mc')    { $type = 5; }
  189: 	elsif ($type eq 'fml')   { $type = 8; }
  190:         elsif ($type eq 'math')  { $type = 9; }
  191: 	elsif ($type eq 'subj')  { $type = 7; }
  192: 	elsif ($type eq 'float') { $type = 2; }
  193: 	elsif ($type eq 'int')   { $type = 1; }
  194: 	else { return ('ERROR', "Unknown type of answer: $type") }
  195:     }
  196: 
  197:     my $points;
  198:     my $id_list;
  199:     #formula type setup the sample points
  200:     if ($type eq '8') {
  201: 	($id_list,$points)=split(/@/,$samples);
  202: 	&LONCAPA_INTERNAL_DEBUG("Found :$id_list:$points: points in $samples");
  203:     }
  204:     if ($tol eq '') {
  205: 	$tol=0.0;
  206: 	$tol_type=1; #TOL_ABSOLUTE
  207:     } else {
  208: 	if ($tol =~ /%$/) {
  209: 	    chop $tol;
  210: 	    $tol_type=2; #TOL_PERCENTAGE
  211: 	} else {
  212: 	    $tol_type=1; #TOL_ABSOLUTE
  213: 	}
  214:     }
  215: 
  216:     ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
  217: 
  218:     my $reterror="";
  219:     my $result;
  220:     if (($type eq '9') || ($type eq '8')) {
  221:         if ($response=~/\=/) {
  222:             return ('BAD_FORMULA','Please submit just an expression, not an equation.');
  223:         } elsif ($response =~ /\,/ and $response !~ /^\s*\{.*\}\s*$/) {
  224:             return ('BAD_FORMULA');
  225:         }
  226:     }
  227:     if ($type eq '9') {
  228:       $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
  229:     } else {
  230: 	if ($type eq '8') { # fml type
  231: 	    $response = &capa_formula_fix($response);
  232: 	    $answer   = &capa_formula_fix($answer);
  233: 	}
  234:        $result = &caparesponse_capa_check_answer($response,$answer,$type,
  235: 						 $tol_type,$tol,
  236: 						 $sig_lbound,$sig_ubound,
  237: 						 $ans_fmt,$unit,$calc,$id_list,
  238: 						 $points,$external::randomseed,
  239: 						 \$reterror);
  240:     }
  241:     if    ($result == '1') { $result='EXACT_ANS'; } 
  242:     elsif ($result == '2') { $result='APPROX_ANS'; }
  243:     elsif ($result == '3') { $result='SIG_FAIL'; }
  244:     elsif ($result == '4') { $result='UNIT_FAIL'; }
  245:     elsif ($result == '5') { $result='NO_UNIT'; }
  246:     elsif ($result == '6') { $result='UNIT_OK'; }
  247:     elsif ($result == '7') { $result='INCORRECT'; }
  248:     elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
  249:     elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
  250:     elsif ($result =='10') { $result='SUB_RECORDED'; }
  251:     elsif ($result =='11') { $result='BAD_FORMULA'; }
  252:     elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
  253:     elsif ($result =='12') { $result='WANTED_NUMERIC'; }
  254:     elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
  255:     elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
  256:     elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
  257:     elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
  258:     elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
  259:     else  {$result = "ERROR: Unknown Result:$result:$@:";}
  260: 
  261:     &LONCAPA_INTERNAL_DEBUG("RetError $reterror: Answer $answer: Response $response:  type-$type|$tol|$tol_type|$sig:$sig_lbound:$sig_ubound|$unit|");
  262:     &LONCAPA_INTERNAL_DEBUG(" $answer $response $result ");
  263:     return ($result,$reterror);
  264: }
  265: 
  266: 
  267: sub caparesponse_check_list {
  268:     my $responses=$LONCAPA::CAPAresponse_args{'response'};
  269:     &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
  270:     my $type = $LONCAPA::CAPAresponse_args{'type'};
  271:     my $answerunit=$LONCAPA::CAPAresponse_args{'unit'};
  272:     &LONCAPA_INTERNAL_DEBUG("Got type :$type: answer unit :$answerunit:\n");
  273:     
  274:     my $num_input_lines =
  275: 	scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}});
  276:     
  277:     if ($type ne '' ) {
  278: 	if (scalar(@$responses) < $num_input_lines) {
  279: 	    return 'MISSING_ANSWER';
  280: 	}
  281: 	if (scalar(@$responses) > $num_input_lines) {
  282: 	    return 'EXTRA_ANSWER';
  283: 	}
  284: 
  285:     }
  286: 
  287:     foreach my $which (0..($num_input_lines-1)) {
  288: 	my $answer_size = 
  289: 	    scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
  290: 	if ($type ne '' 
  291: 	    && $answer_size > 1) {
  292: 	    $responses->[$which]=[split(/,/,$responses->[$which])];
  293: 	} else {
  294: 	    $responses->[$which]=[$responses->[$which]];
  295: 	}
  296:     }
  297:     foreach my $which (0..($num_input_lines-1)) {
  298: 	my $answer_size = 
  299: 	    scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
  300: 	my $response_size = 
  301: 	    scalar(@{$responses->[$which]});
  302: 	if ($answer_size > $response_size) {
  303: 	    return 'MISSING_ANSWER';
  304: 	}
  305: 	if ($answer_size < $response_size) {
  306: 	    return 'EXTRA_ANSWER';
  307: 	}
  308:     }
  309: 
  310:     &LONCAPA_INTERNAL_DEBUG("Initial final response :$responses->[0][-1]:");
  311:     my $unit;
  312:     my ($allowalgebra)=(&parameter_setting('allowalgebra',&currentpart())=~/^(yes|1|on)$/i);
  313:     if ($type eq 'float' || $type eq '') {
  314: 	#for numerical problems split off the unit
  315:         my $part1;
  316:         my $part2;
  317:         if ($allowalgebra) {
  318:            ($part1,$part2)=($responses->[0][-1]=~ /^(.*[^\s])\s+([^\s]+)$/); 
  319:         } else {
  320:            ($part1,$part2)=($responses->[0][-1]=~ /^([\d\.\,\s\$]*(?:(?:[xX\*]10[\^\*]*|[eE]*)[\+\-]*\d*)*(?:^|\S)\d+)([\$\s\w\^\*\/\(\)\+\-]*[^\d\.\s\,][\$\s\w\^\*\/\(\)\+\-]*)$/);
  321:         }
  322:         if ($part1 && $part2) {
  323: 	    $responses->[0][-1]=$part1;
  324: 	    $unit=&capa_formula_fix($part2);
  325:             &LONCAPA_INTERNAL_DEBUG("Found unit :$unit:");
  326: 	}
  327:     }
  328:     &LONCAPA_INTERNAL_DEBUG("Final final response :$responses->[0][-1]:$unit:");
  329:     $unit=~s/\s//;
  330:     my $error;
  331:     foreach my $response (@$responses) {
  332:        foreach my $element (@$response) {	
  333:           if (($type eq 'float') || (($type eq '') && ($unit ne ''))) {
  334:               $element =~ s/\s//g;
  335:           }
  336:           my $appendunit=$unit;
  337: # Deal with percentages
  338: # unit is unit entered by student, answerunit is unit by author
  339: # Deprecated: divide answer by 100 if student entered percent,
  340: # but author did not. Too much confusion
  341: #          if (($unit=~/\%/) && ($answerunit ne '%'))  {
  342: #             $element=$element/100;
  343: #             $appendunit=~s/\%//;
  344: #          }    
  345: # Author entered percent, student did not
  346:           if (($unit!~/\%/) && ($answerunit=~/\%/)) {
  347:              $element=$element*100;
  348:              $appendunit='%'.$appendunit;
  349:           }
  350: # Zero does not need a dimension
  351:           if (($element==0) && ($unit!~/\w/) && ($answerunit=~/\w/)) {
  352:              $appendunit=$answerunit;
  353:           }
  354: # Do the math for the student if allowed
  355:           if ($allowalgebra) {
  356:              $element=&cas('maxima',$element);
  357:           }
  358:           if ($appendunit ne '') {
  359:               $element .= " $appendunit";
  360:           }  
  361:           &LONCAPA_INTERNAL_DEBUG("Made response element :$element:");
  362:        }
  363:     }
  364:     
  365:     foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
  366: 	if (!defined($thisanswer)) {
  367: 	    return ('ERROR','answer was undefined');
  368: 	}
  369:     }
  370: 
  371:     my $allow_control_char = 0;
  372:     my $control_chars_removed = 0;
  373:     my $ansstring;
  374:     if ($type eq 'cs' || $type eq 'ci') {
  375:         if (ref($LONCAPA::CAPAresponse_answer->{'answers'}) eq 'ARRAY') {
  376:             foreach my $strans (@{$LONCAPA::CAPAresponse_answer->{'answers'}}) {
  377:                 if (ref($strans) eq 'ARRAY') {
  378:                     $ansstring = join("\0",@{$strans});
  379:                     foreach my $item (@{$strans}) {  
  380:                         if ($item =~ /[\000-\037]/) {
  381:                             $allow_control_char = 1;
  382:                         }
  383:                     }
  384:                 }
  385:             }
  386:         }
  387:     }
  388: 
  389: #    &LONCAPA_INTERNAL_DEBUG(&LONCAPA_INTERNAL_Dumper($responses));
  390:     my %memoized;
  391:     if ($LONCAPA::CAPAresponse_answer->{'type'}  eq 'ordered') {
  392: 	for (my $i=0; $i<scalar(@$responses);$i++) {
  393: 	    my $answer   = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
  394: 	    my $response = $responses->[$i];
  395: 	    my $key = "$answer\0$response";
  396: 	    my (@awards,@msgs);
  397: 	    for (my $j=0; $j<scalar(@$response); $j++) {
  398:                 if ($type eq 'cs' || $type eq 'ci') {
  399:                     unless ($allow_control_char) {
  400:                         if ($response->[$j] =~ /[\000-\037]/) { 
  401:                             $response->[$j] =~ s/[\000-\037]//g;
  402:                             $control_chars_removed = 1;
  403:                         }  
  404:                     }
  405:                 }
  406: 		my ($award,$msg) = &caparesponse_check($answer->[$j],
  407: 						       $response->[$j]);
  408:                 if ($type eq 'cs' || $type eq 'ci') {
  409:                     $error = &verify_stringresponse($type,$award,$response->[$j],
  410:                                                     $answer->[$j]);
  411:                 }
  412: 		push(@awards,$award);
  413: 		push(@msgs,  $msg);
  414: 	    }
  415: 	    my ($award,$msg) = 
  416: 		&LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
  417: 	    $memoized{$key} = [$award,$msg];
  418: 	}
  419:     } else {
  420: 	#FIXME broken with unorder responses where one is a <value>
  421:         #      and the other is a <vector> (need to delay parse til
  422:         #      inside the loop?)
  423: 	foreach my $response (@$responses) {
  424: 	    my $response_size = scalar(@{$response});
  425: 	    foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
  426: 		my $key = "$answer\0$response";
  427: 		my $answer_size =  scalar(@{$answer});
  428: 		my ($award,$msg);
  429: 		if ($answer_size > $response_size) {
  430: 		    $award = 'MISSING_ANSWER';
  431: 		} elsif ($answer_size < $response_size) {
  432: 		    $award = 'EXTRA_ANSWER';
  433: 		} else {
  434: 		    my (@awards,@msgs);
  435: 		    for (my $j=0; $j<scalar(@$response); $j++) {
  436:                         if ($type eq 'cs' || $type eq 'ci') {
  437:                             unless ($allow_control_char) {
  438:                                 if ($response->[$j] =~ /[\000-\037]/) {
  439:                                     $response->[$j] =~ s/[\000-\037]//g;
  440:                                     $control_chars_removed = 1;
  441:                                 }
  442:                             }
  443:                         }
  444: 			my ($award,$msg) = &caparesponse_check($answer->[$j],
  445: 							       $response->[$j]);
  446:                         if ($type eq 'cs' || $type eq 'ci') {
  447:                             $error = &verify_stringresponse($type,$award,$response->[$j],
  448:                                                             $answer->[$j]);
  449:                         }
  450: 			push(@awards,$award);
  451: 			push(@msgs,  $msg);
  452: 		    }
  453: 		    ($award,$msg) = 
  454: 			&LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
  455: 		}
  456: 		$memoized{$key} = [$award,$msg];
  457: 	    }
  458: 	}
  459:     }
  460: 
  461:     my ($final_award,$final_msg);
  462:     &init_permutation(scalar(@$responses),
  463: 		      $LONCAPA::CAPAresponse_answer->{'type'});
  464: 
  465:     # possible FIXMEs
  466:     # - significant time is spent calling non-safe space routine
  467:     #   from safe space
  468:     # - early outs could be possible with classifying awards is to stratas
  469:     #   and stopping as so as hitting the top strata 
  470:     # - some early outs also might be possible with check ing the 
  471:     #   memoized hash of results (is correct even possible? etc.)
  472: 
  473:     my (@final_awards,@final_msg);
  474:     while( &get_permutations_left() ) {
  475: 	my $order = &get_next_permutation();
  476: 	my (@awards, @msgs, $i);
  477: 	foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
  478: 	    my $key = "$thisanswer\0".$responses->[$order->[$i]];
  479: 	    push(@awards,$memoized{$key}[0]);
  480: 	    push(@msgs,$memoized{$key}[1]);
  481: 	    $i++;
  482: 
  483: 	}
  484: 	&LONCAPA_INTERNAL_DEBUG(" all awards ".join(':',@awards));
  485: 
  486: 	my ($possible_award,$possible_msg) = 
  487: 	    &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
  488: 	&LONCAPA_INTERNAL_DEBUG(" pos awards ".$possible_award);
  489: 	push(@final_awards,$possible_award);
  490: 	push(@final_msg,$possible_msg);
  491:     }
  492: 
  493:     &LONCAPA_INTERNAL_DEBUG(" all final_awards ".join(':',@final_awards));
  494:     my ($final_award,$final_msg) = 
  495: 	&LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
  496:     return ($final_award,$final_msg,$error,$control_chars_removed,$ansstring);
  497: }
  498: 
  499: sub verify_stringresponse {
  500:     my ($type,$award,$resp,$ans) = @_;
  501:     return if ($award eq 'EXACT_ANS');
  502:     my $error;
  503:     if ($resp =~ /^\s|\s$/) {
  504:         $resp =~ s{^\s+|\s+$}{}g;
  505:     }
  506:     if ($ans =~ /^\s|\s$/) {
  507:         $ans =~ s{^\s+|\s+$}{}g;
  508:     }
  509:     if ($type eq 'ci') {
  510:         $resp = lc($resp);
  511:         $ans = lc($ans);
  512:     }
  513:     if ($resp eq $ans) {
  514:         if ($award eq 'INCORRECT') {
  515:             $error = 'MISGRADED';
  516:         }
  517:     }
  518:     return $error;
  519: }
  520: 
  521: sub cas {
  522:     my ($system,$input,$library)=@_;
  523:     my $output;
  524:     my $dump;
  525:     if ($system eq 'maxima') {
  526:        $output=&maxima_eval($input,$library);
  527:     } elsif ($system eq 'R') {
  528:        ($output,$dump)=&r_eval($input,$library,0);
  529:     } else {
  530:        $output='Error: unrecognized CAS';
  531:     }
  532:     return $output;
  533: }
  534: 
  535: sub cas_hashref {
  536:     my ($system,$input,$library)=@_;
  537:     if ($system eq 'maxima') {
  538:        return 'Error: unsupported CAS';
  539:     } elsif ($system eq 'R') {
  540:        return &r_eval($input,$library,1);
  541:     } else {
  542:        return 'Error: unrecognized CAS';
  543:     }
  544: }
  545: 
  546: #
  547: # cas_hashref_entry takes a list of indices and gets the entry in a hash generated by Rreturn.
  548: # Call: cas_hashref_entry(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
  549: # Rentry will return the first scalar value it encounters (ignoring excess indices).
  550: # If an invalid key is given, it returns undef.
  551: #
  552: sub cas_hashref_entry {
  553:     return &Rentry(@_);
  554: }
  555: 
  556: #
  557: # cas_hashref_array takes a list of indices and gets a column array from a hash generated by Rreturn.
  558: # Call: cas_hashref_array(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
  559: # If an invalid key is given, it returns undef.
  560: #
  561: sub cas_hashref_array {
  562:     return &Rarray(@_);
  563: }
  564: 
  565: sub tex {
  566:     if ( $external::target eq "tex" ) {
  567: 	return $_[0];
  568:     } else {
  569: 	return $_[1];
  570:     }
  571: }
  572: 
  573: sub var_in_tex {
  574:     if ( $external::target eq "tex" ) {
  575: 	return $_[0];
  576:     } else {
  577: 	return "";
  578:     }
  579: }
  580: 
  581: sub web {
  582:     if ( $external::target eq "tex" ) {
  583: 	return $_[1];
  584:     } else {
  585: 	if ( $external::target eq "web" || $external::target eq "answer") {
  586: 	    return $_[2];
  587: 	} else {
  588: 	    return $_[0];
  589: 	}
  590:     }
  591: }
  592: 
  593: sub html {
  594:     if ( $external::target eq "web" ) {
  595: 	return shift;
  596:     }
  597: }
  598: 
  599: sub hinton {
  600:     return 0;
  601: }
  602: 
  603: sub random {
  604:     my ($start,$end,$step)=@_;
  605:     if ( ! $hidden::RANDOMINIT ) {
  606: 	if ($external::randomseed == 0) { $external::randomseed=1; }
  607: 	if ($external::randomseed =~/,/) {
  608: 	    my ($num1,$num2)=split(/,/,$external::randomseed);
  609: 	    &random_set_seed(1,abs($num1));
  610: 	} elsif ($external::randomseed =~/:/) {
  611: 	    my ($num1,$num2)=split(/:/,$external::randomseed);
  612: 	    &random_set_seed(abs($num1),abs($num2));
  613: 	} else {
  614: 	    &random_set_seed(1,int(abs($external::randomseed)));
  615: 	}
  616: 	&math_random_uniform();
  617: 	$hidden::RANDOMINIT=1;
  618:     }
  619:     if (!defined($step)) { $step=1; }
  620:     my $num=1+int(($end-$start)/$step);
  621:     my $result=$start + int(&math_random_uniform() * $num)*$step;
  622:     return $result;
  623: }
  624: 
  625: sub random_normal {
  626:     my ($item_cnt,$seed,$av,$std_dev) = @_;
  627:     my @oldseed=&random_get_seed();
  628:     my @retArray;
  629:     &random_set_seed_from_phrase($seed);
  630:     @retArray=&math_random_normal($item_cnt,$av,$std_dev);
  631:     &random_set_seed(@oldseed);
  632:     return @retArray;
  633: }
  634: 
  635: sub random_beta {
  636:     my ($item_cnt,$seed,$aa,$bb) = @_;
  637:     my @oldseed=&random_get_seed();
  638:     my @retArray;
  639:     &random_set_seed_from_phrase($seed);
  640:     @retArray=&math_random_beta($item_cnt,$aa,$bb);
  641:     &random_set_seed(@oldseed);
  642:     return @retArray;
  643: }
  644: 
  645: sub random_gamma {
  646:     my ($item_cnt,$seed,$a,$r) = @_;
  647:     my @oldseed=&random_get_seed();
  648:     my @retArray;
  649:     &random_set_seed_from_phrase($seed);
  650:     @retArray=&math_random_gamma($item_cnt,$a,$r);
  651:     &random_set_seed(@oldseed);
  652:     return @retArray;
  653: }
  654: 
  655: sub random_exponential {
  656:     my ($item_cnt,$seed,$av) = @_;
  657:     my @oldseed=&random_get_seed();
  658:     my @retArray;
  659:     &random_set_seed_from_phrase($seed);
  660:     @retArray=&math_random_exponential($item_cnt,$av);
  661:     &random_set_seed(@oldseed);
  662:     return @retArray;
  663: }
  664: 
  665: sub random_poisson {
  666:     my ($item_cnt,$seed,$mu) = @_;
  667:     my @oldseed=&random_get_seed();
  668:     my @retArray;
  669:     &random_set_seed_from_phrase($seed);
  670:     @retArray=&math_random_poisson($item_cnt,$mu);
  671:     &random_set_seed(@oldseed);
  672:     return @retArray;
  673: }
  674: 
  675: sub random_chi {
  676:     my ($item_cnt,$seed,$df) = @_;
  677:     my @oldseed=&random_get_seed();
  678:     my @retArray;
  679:     &random_set_seed_from_phrase($seed);
  680:     @retArray=&math_random_chi_square($item_cnt,$df);
  681:     &random_set_seed(@oldseed);
  682:     return @retArray;
  683: }
  684: 
  685: sub random_noncentral_chi {
  686:     my ($item_cnt,$seed,$df,$nonc) = @_;
  687:     my @oldseed=&random_get_seed();
  688:     my @retArray;
  689:     &random_set_seed_from_phrase($seed);
  690:     @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
  691:     &random_set_seed(@oldseed);
  692:     return @retArray;
  693: }
  694: 
  695: sub random_f {
  696:     my ($item_cnt,$seed,$dfn,$dfd) = @_;
  697:     my @oldseed=&random_get_seed();
  698:     my @retArray;
  699:     &random_set_seed_from_phrase($seed);
  700:     @retArray=&math_random_f($item_cnt,$dfn,$dfd);
  701:     &random_set_seed(@oldseed);
  702:     return @retArray;
  703: }
  704: 
  705: sub random_noncentral_f {
  706:     my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
  707:     my @oldseed=&random_get_seed();
  708:     my @retArray;
  709:     &random_set_seed_from_phrase($seed);
  710:     @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
  711:     &random_set_seed(@oldseed);
  712:     return @retArray;
  713: }
  714: 
  715: sub random_multivariate_normal {
  716:     my ($item_cnt,$seed,$mean,$covar) = @_;
  717:     my @oldseed=&random_get_seed();
  718:     &random_set_seed_from_phrase($seed);
  719:     my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
  720:     &random_set_seed(@oldseed);
  721:     return @retArray;
  722: }
  723: 
  724: sub random_multinomial {
  725:     my ($item_cnt,$seed,@p) = @_;
  726:     my @oldseed=&random_get_seed();
  727:     my @retArray;
  728:     &random_set_seed_from_phrase($seed);
  729:     my @retArray=&math_random_multinomial($item_cnt,@p);
  730:     &random_set_seed(@oldseed);
  731:     return @retArray;
  732: }
  733: 
  734: sub random_permutation {
  735:     my ($seed,@inArray) = @_;
  736:     my @oldseed=&random_get_seed();
  737:     my @retArray;
  738:     &random_set_seed_from_phrase($seed);
  739:     @retArray=&math_random_permutation(@inArray);
  740:     &random_set_seed(@oldseed);
  741:     return @retArray;
  742: }
  743: 
  744: sub random_uniform {
  745:     my ($item_cnt,$seed,$low,$high) = @_;
  746:     my @oldseed=&random_get_seed();
  747:     my @retArray;
  748:     &random_set_seed_from_phrase($seed);
  749:     @retArray=&math_random_uniform($item_cnt,$low,$high);
  750:     &random_set_seed(@oldseed);
  751:     return @retArray;
  752: }
  753: 
  754: sub random_uniform_integer {
  755:     my ($item_cnt,$seed,$low,$high) = @_;
  756:     my @oldseed=&random_get_seed();
  757:     my @retArray;
  758:     &random_set_seed_from_phrase($seed);
  759:     @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
  760:     &random_set_seed(@oldseed);
  761:     return @retArray;
  762: }
  763: 
  764: sub random_binomial {
  765:     my ($item_cnt,$seed,$nt,$p) = @_;
  766:     my @oldseed=&random_get_seed();
  767:     my @retArray;
  768:     &random_set_seed_from_phrase($seed);
  769:     @retArray=&math_random_binomial($item_cnt,$nt,$p);
  770:     &random_set_seed(@oldseed);
  771:     return @retArray;
  772: }
  773: 
  774: sub random_negative_binomial {
  775:     my ($item_cnt,$seed,$ne,$p) = @_;
  776:     my @oldseed=&random_get_seed();
  777:     my @retArray;
  778:     &random_set_seed_from_phrase($seed);
  779:     @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
  780:     &random_set_seed(@oldseed);
  781:     return @retArray;
  782: }
  783: 
  784: sub abs { CORE::abs(shift) }
  785: sub sin { CORE::sin(shift) }
  786: sub cos { CORE::cos(shift) }
  787: sub exp { CORE::exp(shift) }
  788: sub int { CORE::int(shift) }
  789: sub log { CORE::log(shift) }
  790: sub atan2 { CORE::atan2($_[0],$_[1]) }
  791: sub sqrt { CORE::sqrt(shift) }
  792: 
  793: sub tan  { CORE::sin($_[0]) / CORE::cos($_[0]) }
  794: #sub atan { atan2($_[0], 1); }
  795: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
  796: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) );  }
  797: 
  798: sub log10 { CORE::log($_[0])/CORE::log(10); }
  799: 
  800: sub factorial {
  801:     my $input = CORE::int(shift);
  802:     return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
  803:     return "Error - factorial result is greater than system limit ($input)" if $input > 170;
  804:     return 1 if $input == 0;
  805:     my $result = 1; 
  806:     for (my $i=2; $i<=$input; $i++) { $result *= $i }
  807:     return $result;
  808: }
  809: 
  810: sub sgn {
  811:     return -1 if $_[0] < 0;
  812:     return 0 if $_[0] == 0;
  813:     return 1 if $_[0] > 0;
  814: }
  815: 
  816: sub min {
  817:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  818:     return shift @sorted;
  819: }
  820: 
  821: sub max {
  822:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  823:     return pop @sorted;
  824: }
  825: 
  826: sub roundto {
  827:     my ($input,$n) = @_;
  828:     return sprintf('%.'.$n.'f',$input);
  829: }
  830: 
  831: sub to_string {
  832:     my ($input,$n) = @_;
  833:     return sprintf($input) if $n eq "";
  834:     $n = '.'.$n if $n !~ /^\./;
  835:     return sprintf('%'.$n,$input) if $n ne "";
  836: }
  837: 
  838: sub sub_string {
  839:     my ($str,$start,$len) = @_;
  840:     return substr($str,$start-1,$len);
  841: }
  842: 
  843: sub pow   {return $_[0] ** $_[1]; }
  844: sub ceil  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
  845: sub floor  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
  846: #sub floor {return int($_[0]); }
  847: 
  848: sub format {
  849:     my ($value,$fmt)=@_;
  850:     my ($dollarmode,$commamode,$alwaysperiod,$options);
  851:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
  852:     #if ($options =~ /\$/) { $dollamode=1; }
  853:     #if ($options =~ /,/)  { $commamode=1; }
  854:     if ($options =~ /\./) { $alwaysperiod=1; }
  855:     my $result;
  856:     if ($fmt=~/s$/i) {
  857: 	$result=&format_significant_figures($value,$fmt);
  858:     } else {
  859: 	$fmt=~s/e/E/g;
  860: 	$result=sprintf('%.'.$fmt,$value);
  861: 	if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
  862: 	$result=~s/(E[+-]*)0/$1/;
  863:     }
  864:     #if ($dollarmode) {$result=&dollarformat($result);}
  865:     #if ($commamode) {$result=&commaformat($result);}
  866:     return $result;
  867: }
  868: 
  869: sub chemparse {
  870:     my ($reaction) = @_;
  871:     my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
  872:     my $formula = '';
  873:     foreach my $token (@tokens) {
  874: 	if ($token eq '->' ) {
  875: 	    $formula .= '<m>\ensuremath{\rightarrow}</m> ';
  876: 	    next;
  877: 	}
  878: 	if ($token eq '<-' ) {
  879: 	    $formula .= '<m>\ensuremath{\leftarrow}</m> ';
  880: 	    next;
  881: 	}  
  882: 	if ($token eq '<=>') {
  883: 	    if ($external::target eq 'web' &&
  884: 		&EXT('request.browser.unicode')) {
  885: 		$formula .= '&#8652; ';
  886: 	    } else {
  887: 		$formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
  888: 				 '&lt;=&gt; ');
  889: 	    }
  890: 	    next;
  891: 	}
  892: 	if ($token eq '.') {
  893: 	  $formula =~ s/(\&nbsp\;| )$//;
  894: 	  $formula .= '&middot;';
  895: 	  next;
  896: 	}
  897: 	$token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
  898:         $formula .= $1 if ($1 ne '1');  # stoichiometric coefficient
  899: 	
  900: 	my $molecule = $2;
  901: 	# subscripts
  902: 	$molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
  903: 	# superscripts
  904: 	$molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
  905: 	# strip whitespace
  906: 	$molecule =~ s/\s*//g;
  907: 	# forced space
  908: 	$molecule =~ s/_/ /g;
  909: 	$molecule =~ s/-/&minus;/g;
  910: 	$formula .= $molecule.'&nbsp;';
  911:     }
  912:     # get rid of trailing space
  913:     $formula =~ s/(\&nbsp\;| )$//;
  914:     return &xmlparse($formula);
  915: }
  916: 
  917: sub prettyprint {
  918:     my ($value,$fmt,$target)=@_;
  919:     my $result;
  920:     if (!$target) { $target = $external::target; }
  921:     if ($fmt =~ /chem/i) { return(&chemparse($value)); }
  922:     my ($dollarmode,$commamode,$alwaysperiod,$options);
  923:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
  924:     if ($options =~ /\$/) { $dollarmode=1; }
  925:     if ($options =~ /,/)  { $commamode=1; }
  926:     if ($options =~ /\./) { $alwaysperiod=1; }
  927:     if ($fmt=~/s$/i) {
  928: 	$value=&format_significant_figures($value,$fmt);
  929:     } elsif ($fmt) {
  930: 	$value=sprintf('%.'.$fmt,$value);
  931:     }
  932:     if ($alwaysperiod && $fmt eq '0f') {
  933: 	if ($target eq 'tex') {
  934: 	    $value .='\\ensuremath{.}';
  935: 	} else {
  936: 	    $value .='.';
  937: 	}
  938:     }
  939:     if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
  940: 	my $frac=$1;
  941: 	if ($dollarmode) { $frac=&dollarformat($frac); }
  942: 	if ($commamode) { $frac=&commaformat($frac); }
  943: 	my $exponent=$2;
  944: 	$exponent=~s/^\+0*//;
  945: 	$exponent=~s/^-0*/-/;
  946: 	$exponent=~s/^-0*/-/;
  947: 	if ($exponent eq '-') { undef($exponent); }
  948: 	if ($exponent) {
  949: 	    if ($target eq 'web') {
  950: 		$result=$frac.'&#215;10<sup>'.$exponent.'</sup>';
  951: 	    } elsif ($target eq 'tex') {
  952: 		$result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
  953: 	    } else {
  954: 		$result=$value;
  955: 	    }
  956: 	} else {
  957: 	    $result=$frac;
  958: 	}
  959:     } else {
  960: 	$result=$value;
  961: 	if    ($dollarmode) { $result=&dollarformat($result,$target); }
  962: 	elsif ($commamode)  { $result=&commaformat($result,$target); }
  963:     }
  964:     return $result;
  965: }
  966: 
  967: sub commaformat {
  968:     my ($number,$target) = @_;
  969:     if ($number =~ /\./) {
  970: 	while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
  971: 	    $number = $1.$2.','.$3.$4;
  972: 	}
  973:     } else {
  974: 	while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
  975: 	    $number = $1.$2.','.$3.$4;
  976: 	}
  977:     }
  978:     return $number;
  979: }
  980: 
  981: sub dollarformat {
  982:     my ($number,$target) = @_;
  983:     if (!$target) { $target = $external::target; }
  984:     $number=&commaformat($number,$target);
  985:     if ($target eq 'tex') {
  986: 	$number='\$'.$number; #' stupid emacs
  987:     } else {
  988: 	$number='$'.$number; #' stupid emacs
  989:     }
  990:     return $number; 
  991: }
  992: 
  993: # format of form ns or nS where n is an integer
  994: sub format_significant_figures {
  995:     my ($number,$format) = @_; 
  996:     return '0' if ($number == 0);
  997:     # extract number of significant figures needed
  998:     my ($sig) = ($format =~ /(\d+)s/i);
  999:     # arbitrary choice - suggestions ?? or throw error message?
 1000:     $sig = 3 if ($sig eq '');
 1001:     # save the minus sign
 1002:     my $sign = ($number < 0) ? '-' : '';
 1003:     $number = abs($number);
 1004:     # needed to correct for a number greater than 1 (or
 1005:     my $power = ($number < 1) ? 0 : 1;
 1006:     # could round up. Take the integer part of log10.
 1007:     my $x10 = int(log($number)/log(10));
 1008:     # find number with values left of decimal pt = # of sign figs.
 1009:     my $xsig = $number*10**($sig-$x10-$power);
 1010:     # get just digits left of decimal pt - also rounds off correctly
 1011:     my $xint  = sprintf('%.0f',$xsig);
 1012:     # save any trailing zero's
 1013:     my ($zeros) = ($xint =~ /(0+)$/);
 1014:     # return number to original magnitude
 1015:     my $numSig = $xint*10**($x10-$sig+$power);
 1016:     # insert trailing zero's if have decimal point
 1017:     $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
 1018:     # put a decimal pt for number ending with 0 and length = # of sig fig
 1019:     $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
 1020:     if (length($numSig) < $sig) {
 1021: 	$numSig.='.'.substr($zeros,0,($sig-length($numSig)));
 1022:     }
 1023:     # return number with sign
 1024:     return $sign.$numSig;
 1025: 
 1026: }
 1027: 
 1028: sub map {
 1029:     my ($phrase,$dest,$source)=@_;
 1030:     my @oldseed=&random_get_seed();
 1031:     my @seed = &random_seed_from_phrase($phrase);
 1032:     &random_set_seed(@seed);
 1033:     my $destct = scalar(@$dest);
 1034:     if (!$source) {
 1035: 	my @output;
 1036: 	my @idx = &math_random_permuted_index($destct);
 1037: 	my $ctr = 0;
 1038: 	while ($ctr < $destct) {
 1039: 	    $output[$ctr] = $$dest[$idx[$ctr]];
 1040: 	    $ctr++;
 1041: 	}
 1042:         &random_set_seed(@oldseed);
 1043: 	return @output;
 1044:     } else {
 1045: 	my $num = scalar(@$source);
 1046: 	my @idx = &math_random_permuted_index($num);
 1047: 	my $ctr = 0;
 1048: 	my $tot = $num;
 1049: 	$tot = $destct if $destct < $num;
 1050: 	if (ref($$dest[0])) {
 1051: 	    while ($ctr < $tot) {
 1052: 		${$$dest[$ctr]} = $$source[$idx[$ctr]];
 1053: 	        $ctr++;
 1054:             }
 1055:         } else {
 1056: 	    while ($ctr < $tot) {
 1057: 		$$dest[$ctr] = $$source[$idx[$ctr]];
 1058: 		$ctr++;
 1059: 	    }
 1060: 	}
 1061:     }
 1062:     &random_set_seed(@oldseed);
 1063:     return '';
 1064: }
 1065: 
 1066: sub rmap {
 1067:     my ($phrase,$dest,$source)=@_;
 1068:     my @oldseed=&random_get_seed();
 1069:     my @seed = &random_seed_from_phrase($phrase);
 1070:     &random_set_seed(@seed);
 1071:     my $destct = scalar(@$dest);
 1072:     if (!$source) {
 1073: 	my @idx = &math_random_permuted_index($destct);
 1074: 	my $ctr = 0;
 1075: 	my @r_idx;
 1076: 	while ($ctr < $destct) {
 1077: 	    $r_idx[$idx[$ctr]] = $ctr;
 1078: 	    $ctr++;
 1079: 	}
 1080: 	my @output;
 1081: 	$ctr = 0;
 1082: 	while ($ctr < $destct) {
 1083: 	    $output[$ctr] = $$dest[$r_idx[$ctr]];
 1084: 	    $ctr++;
 1085: 	}
 1086:         &random_set_seed(@oldseed);
 1087: 	return @output;
 1088:     } else {
 1089: 	my $num = scalar(@$source);
 1090: 	my @idx = &math_random_permuted_index($num);
 1091: 	my $ctr = 0;
 1092: 	my $tot = $num;
 1093: 	$tot = $destct if $destct < $num;
 1094: 	my @r_idx;
 1095: 	while ($ctr < $tot) {
 1096: 	    $r_idx[$idx[$ctr]] = $ctr;
 1097: 	    $ctr++;
 1098: 	}
 1099: 	$ctr = 0;
 1100: 	if (ref($$dest[0])) {
 1101: 	    while ($ctr < $tot) {
 1102: 		${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
 1103: 	        $ctr++;
 1104:             }
 1105:         } else {
 1106: 	    while ($ctr < $tot) {
 1107: 		$$dest[$ctr] = $$source[$r_idx[$ctr]];
 1108: 		$ctr++;
 1109: 	    }
 1110: 	}
 1111:     }
 1112:     &random_set_seed(@oldseed);
 1113:     return '';
 1114: }
 1115: 
 1116: sub capa_id { return }
 1117: 
 1118: sub problem { return }
 1119: 
 1120: sub name{
 1121:     my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
 1122:     $fullname = "" if $fullname eq ",  ";
 1123:     $fullname =~ s/\%2d/-/g;
 1124:     return $fullname;
 1125: }
 1126: 
 1127: sub student_number { 
 1128:     my $id = &EXT('environment.id');
 1129:     $id = '' if $id eq "";
 1130:     return $id;
 1131: }
 1132: 
 1133: sub class {
 1134:     my $course = &EXT('course.description');
 1135:     $course = '' if $course eq "";
 1136:     return $course;
 1137: }
 1138: 
 1139: sub classid {
 1140:     my $courseid = &EXT('request.course.id');
 1141:     $courseid = '' if $courseid eq "";
 1142:     return $courseid;
 1143: }
 1144: 
 1145: sub firstname {
 1146:     my $firstname = &EXT('environment.firstname');
 1147:     $firstname = '' if $firstname eq "";
 1148:     return $firstname;
 1149: }
 1150: 
 1151: sub middlename {
 1152:     my $middlename = &EXT('environment.middlename');
 1153:     $middlename = '' if $middlename eq "";
 1154:     return $middlename;
 1155: }
 1156: 
 1157:                                                                                 
 1158: sub lastname {
 1159:     my $lastname = &EXT('environment.lastname');
 1160:     $lastname = '' if $lastname eq "";
 1161:     return $lastname;
 1162: }
 1163: 
 1164: sub sec { 
 1165:     my $sec = &EXT('request.course.sec');
 1166:     $sec = '' if $sec eq "";
 1167:     return $sec;
 1168: }
 1169: 
 1170: sub submission {
 1171:    my ($partid,$responseid,$subnumber)=@_;
 1172:    my $sub='';
 1173:    if ($subnumber) { $sub=$subnumber.':'; }
 1174:    return &EXT('user.resource.'.$sub.'resource.'.$partid.'.'.$responseid.'.submission');
 1175: }
 1176: 
 1177: sub currentpart {
 1178:    return $external::part;
 1179: }
 1180: 
 1181: sub eval_time {
 1182:    my ($timestamp)=@_;
 1183:    unless ($timestamp) { return ''; }
 1184:    return &locallocaltime($timestamp);
 1185: }
 1186: 
 1187: sub open_date { 
 1188:     my ($partid)=@_;
 1189:     unless ($partid) { $partid=0; }
 1190:     return &eval_time(&EXT('resource.'.$partid.'.opendate'));
 1191: }
 1192: 
 1193: sub due_date {
 1194:     my ($partid)=@_;
 1195:     unless ($partid) { $partid=0; } 
 1196:     return &eval_time(&EXT('resource.'.$partid.'.duedate'));
 1197: }
 1198: 
 1199: sub answer_date { 
 1200:     my ($partid)=@_;
 1201:     unless ($partid) { $partid=0; }
 1202:     return &eval_time(&EXT('resource.'.$partid.'.answerdate'));
 1203: }
 1204: 
 1205: sub open_date_epoch {
 1206:     my ($partid)=@_;
 1207:     unless ($partid) { $partid=0; }
 1208:     return &EXT('resource.'.$partid.'.opendate');
 1209: }
 1210: 
 1211: sub due_date_epoch {
 1212:     my ($partid)=@_;
 1213:     unless ($partid) { $partid=0; }
 1214:     return &EXT('resource.'.$partid.'.duedate');
 1215: }
 1216: 
 1217: sub answer_date_epoch {
 1218:     my ($partid)=@_;
 1219:     unless ($partid) { $partid=0; }
 1220:     return &EXT('resource.'.$partid.'.answerdate');
 1221: }
 1222: 
 1223: sub parameter_setting {
 1224:     my ($which,$partid)=@_;
 1225:     unless ($partid) { $partid=0; }
 1226:     return &EXT('resource.'.$partid.'.'.$which);
 1227: }
 1228: 
 1229: sub stored_data {
 1230:     my ($which,$partid)=@_;
 1231:     unless ($partid) { $partid=0; }
 1232:     return &EXT('user.resource.resource.'.$partid.'.'.$which);
 1233: }
 1234: 
 1235: sub wrong_bubbles {
 1236:     my ($correct,$lower,$upper,$step,@given)=@_;
 1237:     my @array=();
 1238:     my %hash=();
 1239:     foreach my $new (@given) {
 1240:         $hash{$new}=1;
 1241:     }
 1242:     my $num=int(&parameter_setting('numbubbles',&currentpart()));
 1243:     unless ($num) { $num=8; }
 1244:     if ($num>1) {
 1245:         for (my $i=0;$i<=500;$i++) {
 1246:             my $new=&random($lower,$upper,$step);
 1247:             if ($hash{$new}) { next; }
 1248:             if (abs($new-$correct)<$step) { next; }
 1249:             $hash{$new}=1;
 1250:             @array=keys(%hash);
 1251:             if ($#array+2>=$num) { last; }
 1252:         }
 1253:     }
 1254:     return @array;
 1255: }
 1256: 
 1257: sub array_moments {
 1258:     my @input=@_;
 1259:     my (@output,$N);
 1260:     $N=scalar (@input);
 1261:     $output[0]=$N;
 1262:     if ($N <= 1) {
 1263: 	$output[1]=$input[0];
 1264: 	$output[1]="Input array not defined" if ($N == 0);
 1265: 	$output[2]="variance undefined for N<=1";
 1266: 	$output[3]="skewness undefined for N<=1";
 1267: 	$output[4]="kurtosis undefined for N<=1";
 1268: 	return @output;
 1269:     }
 1270:     my $sum=0;
 1271:     foreach my $line (@input) {
 1272: 	$sum+=$line;
 1273:     }
 1274:     $output[1] = $sum/$N;
 1275:     my ($x,$sdev,$var,$skew,$kurt) = 0;
 1276:     foreach my $line (@input) {
 1277: 	$x=$line-$output[1];
 1278: 	$var+=$x**2;
 1279: 	$skew+=$x**3;
 1280: 	$kurt+=$x**4;
 1281:     }
 1282:     $output[2]=$var/($N-1);
 1283:     $sdev=CORE::sqrt($output[2]);
 1284:     if ($sdev == 0) {
 1285: 	$output[3]="inf-variance=0";
 1286: 	$output[4]="inf-variance=0";
 1287: 	return @output;
 1288:     }
 1289:     $output[3]=$skew/($sdev**3*$N);
 1290:     $output[4]=$kurt/($sdev**4*$N)-3;
 1291:     return @output;
 1292: }
 1293: 
 1294: sub choose {
 1295:     my $num = $_[0];
 1296:     return $_[$num];
 1297: }
 1298: 
 1299: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
 1300: #sub sum1 {
 1301: #    my ($start,$end,$sub)=@_;
 1302: #    my $sum=0;
 1303: #    for (my $i=$start;$i<=$end;$i++) {
 1304: #        $sum+=&$sub($i);
 1305: #    }
 1306: #    return $sum
 1307: #}
 1308: 
 1309: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
 1310: #sub sum2 {
 1311: #    my ($varname,$start,$end,$line)=@_;
 1312: #    my $sum=0;
 1313: #    for (my $i=$start;$i<=$end;$i++) {
 1314: #	my $func=sub {
 1315: #	    eval("\$".$varname."=$i");
 1316: #	    eval($line);
 1317: #	};
 1318: #        $sum+=&$func($i);
 1319: #    }
 1320: #    return $sum
 1321: #}
 1322: 
 1323: # expiremental idea
 1324: sub proper_path {
 1325:     my ($path)=@_;
 1326:     if ( $external::target eq "tex" ) {
 1327: 	return '/home/httpd/html'.$path;
 1328:     } else {
 1329: 	return $path;
 1330:     }
 1331: }
 1332: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>