File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.157: download - view: text, annotated - select for diffs
Wed Jun 8 01:39:28 2011 UTC (12 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #2020: work on preprocessor

    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.157 2011/06/08 01:39:28 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 $preprocess=$LONCAPA::CAPAresponse_args{'preprocess'};
  275:     $preprocess=~s/^\&//;
  276: 
  277:     my $num_input_lines =
  278: 	scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}});
  279:     
  280:     if ($type ne '' ) {
  281: 	if (scalar(@$responses) < $num_input_lines) {
  282: 	    return 'MISSING_ANSWER';
  283: 	}
  284: 	if (scalar(@$responses) > $num_input_lines) {
  285: 	    return 'EXTRA_ANSWER';
  286: 	}
  287: 
  288:     }
  289: 
  290:     foreach my $which (0..($num_input_lines-1)) {
  291: 	my $answer_size = 
  292: 	    scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
  293: 	if ($type ne '' 
  294: 	    && $answer_size > 1) {
  295: 	    $responses->[$which]=[split(/,/,$responses->[$which])];
  296: 	} else {
  297: 	    $responses->[$which]=[$responses->[$which]];
  298: 	}
  299:     }
  300:     foreach my $which (0..($num_input_lines-1)) {
  301: 	my $answer_size = 
  302: 	    scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
  303: 	my $response_size = 
  304: 	    scalar(@{$responses->[$which]});
  305: 	if ($answer_size > $response_size) {
  306: 	    return 'MISSING_ANSWER';
  307: 	}
  308: 	if ($answer_size < $response_size) {
  309: 	    return 'EXTRA_ANSWER';
  310: 	}
  311:     }
  312: 
  313:     &LONCAPA_INTERNAL_DEBUG("Initial final response :$responses->[0][-1]:");
  314:     my $unit;
  315:     my ($allowalgebra)=(&parameter_setting('allowalgebra',&currentpart())=~/^(yes|1|on)$/i);
  316:     if ($type eq 'float' || $type eq '') {
  317: 	#for numerical problems split off the unit
  318:         my $part1;
  319:         my $part2;
  320:         if ($allowalgebra) {
  321:            ($part1,$part2)=($responses->[0][-1]=~ /^(.*[^\s])\s+([^\s]+)$/); 
  322:         } else {
  323:            ($part1,$part2)=($responses->[0][-1]=~ /^([\d\.\,\s\$]*(?:(?:[xX\*]10[\^\*]*|[eE]*)[\+\-]*\d*)*(?:^|\S)\d+)([\$\s\w\^\*\/\(\)\+\-]*[^\d\.\s\,][\$\s\w\^\*\/\(\)\+\-]*)$/);
  324:         }
  325:         if (defined($part1) && defined($part2)) {
  326: 	    $responses->[0][-1]=$part1;
  327: 	    $unit=&capa_formula_fix($part2);
  328:             &LONCAPA_INTERNAL_DEBUG("Found unit :$unit:");
  329: 	}
  330:     }
  331:     &LONCAPA_INTERNAL_DEBUG("Final final response :$responses->[0][-1]:$unit:");
  332:     $unit=~s/\s//;
  333:     my $error;
  334:     foreach my $response (@$responses) {
  335:        foreach my $element (@$response) {
  336:           # See if we have preprocessor
  337:           if ($preprocess=~/\S/) {
  338:              if (defined(&$preprocess)) {
  339:                 no strict 'refs';
  340:                 $element=&$preprocess($element);
  341:                 use strict 'refs';
  342:              }
  343:           }
  344:           if (($type eq 'float') || (($type eq '') && ($unit ne ''))) {
  345:               $element =~ s/\s//g;
  346:           }
  347:           my $appendunit=$unit;
  348: # Deal with percentages
  349: # unit is unit entered by student, answerunit is unit by author
  350: # Deprecated: divide answer by 100 if student entered percent,
  351: # but author did not. Too much confusion
  352: #          if (($unit=~/\%/) && ($answerunit ne '%'))  {
  353: #             $element=$element/100;
  354: #             $appendunit=~s/\%//;
  355: #          }    
  356: # Author entered percent, student did not
  357:           if (($unit!~/\%/) && ($answerunit=~/\%/)) {
  358:              $element=$element*100;
  359:              $appendunit='%'.$appendunit;
  360:           }
  361: # Zero does not need a dimension
  362:           if (($element==0) && ($unit!~/\w/) && ($answerunit=~/\w/)) {
  363:              $appendunit=$answerunit;
  364:           }
  365: # Do the math for the student if allowed
  366:           if ($allowalgebra) {
  367:              $element=&cas('maxima',$element);
  368:           }
  369:           if ($appendunit ne '') {
  370:               $element .= " $appendunit";
  371:           }  
  372:           &LONCAPA_INTERNAL_DEBUG("Made response element :$element:");
  373:        }
  374:     }
  375:     
  376:     foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
  377: 	if (!defined($thisanswer)) {
  378: 	    return ('ERROR','answer was undefined');
  379: 	}
  380:     }
  381: 
  382:     my $allow_control_char = 0;
  383:     my $control_chars_removed = 0;
  384:     my $ansstring;
  385:     if ($type eq 'cs' || $type eq 'ci') {
  386:         if (ref($LONCAPA::CAPAresponse_answer->{'answers'}) eq 'ARRAY') {
  387:             foreach my $strans (@{$LONCAPA::CAPAresponse_answer->{'answers'}}) {
  388:                 if (ref($strans) eq 'ARRAY') {
  389:                     $ansstring = join("\0",@{$strans});
  390:                     foreach my $item (@{$strans}) {  
  391:                         if ($item =~ /[\000-\037]/) {
  392:                             $allow_control_char = 1;
  393:                         }
  394:                     }
  395:                 }
  396:             }
  397:         }
  398:     }
  399: 
  400: #    &LONCAPA_INTERNAL_DEBUG(&LONCAPA_INTERNAL_Dumper($responses));
  401:     my %memoized;
  402:     if ($LONCAPA::CAPAresponse_answer->{'type'}  eq 'ordered') {
  403: 	for (my $i=0; $i<scalar(@$responses);$i++) {
  404: 	    my $answer   = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
  405: 	    my $response = $responses->[$i];
  406: 	    my $key = "$answer\0$response";
  407: 	    my (@awards,@msgs);
  408: 	    for (my $j=0; $j<scalar(@$response); $j++) {
  409:                 if ($type eq 'cs' || $type eq 'ci') {
  410:                     unless ($allow_control_char) {
  411:                         if ($response->[$j] =~ /[\000-\037]/) { 
  412:                             $response->[$j] =~ s/[\000-\037]//g;
  413:                             $control_chars_removed = 1;
  414:                         }  
  415:                     }
  416:                 }
  417: 		my ($award,$msg) = &caparesponse_check($answer->[$j],
  418: 						       $response->[$j]);
  419:                 if ($type eq 'cs' || $type eq 'ci') {
  420:                     $error = &verify_stringresponse($type,$award,$response->[$j],
  421:                                                     $answer->[$j]);
  422:                 }
  423: 		push(@awards,$award);
  424: 		push(@msgs,  $msg);
  425: 	    }
  426: 	    my ($award,$msg) = 
  427: 		&LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
  428: 	    $memoized{$key} = [$award,$msg];
  429: 	}
  430:     } else {
  431: 	#FIXME broken with unorder responses where one is a <value>
  432:         #      and the other is a <vector> (need to delay parse til
  433:         #      inside the loop?)
  434: 	foreach my $response (@$responses) {
  435: 	    my $response_size = scalar(@{$response});
  436: 	    foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
  437: 		my $key = "$answer\0$response";
  438: 		my $answer_size =  scalar(@{$answer});
  439: 		my ($award,$msg);
  440: 		if ($answer_size > $response_size) {
  441: 		    $award = 'MISSING_ANSWER';
  442: 		} elsif ($answer_size < $response_size) {
  443: 		    $award = 'EXTRA_ANSWER';
  444: 		} else {
  445: 		    my (@awards,@msgs);
  446: 		    for (my $j=0; $j<scalar(@$response); $j++) {
  447:                         if ($type eq 'cs' || $type eq 'ci') {
  448:                             unless ($allow_control_char) {
  449:                                 if ($response->[$j] =~ /[\000-\037]/) {
  450:                                     $response->[$j] =~ s/[\000-\037]//g;
  451:                                     $control_chars_removed = 1;
  452:                                 }
  453:                             }
  454:                         }
  455: 			my ($award,$msg) = &caparesponse_check($answer->[$j],
  456: 							       $response->[$j]);
  457:                         if ($type eq 'cs' || $type eq 'ci') {
  458:                             $error = &verify_stringresponse($type,$award,$response->[$j],
  459:                                                             $answer->[$j]);
  460:                         }
  461: 			push(@awards,$award);
  462: 			push(@msgs,  $msg);
  463: 		    }
  464: 		    ($award,$msg) = 
  465: 			&LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
  466: 		}
  467: 		$memoized{$key} = [$award,$msg];
  468: 	    }
  469: 	}
  470:     }
  471: 
  472:     my ($final_award,$final_msg);
  473:     &init_permutation(scalar(@$responses),
  474: 		      $LONCAPA::CAPAresponse_answer->{'type'});
  475: 
  476:     # possible FIXMEs
  477:     # - significant time is spent calling non-safe space routine
  478:     #   from safe space
  479:     # - early outs could be possible with classifying awards is to stratas
  480:     #   and stopping as so as hitting the top strata 
  481:     # - some early outs also might be possible with check ing the 
  482:     #   memoized hash of results (is correct even possible? etc.)
  483: 
  484:     my (@final_awards,@final_msg);
  485:     while( &get_permutations_left() ) {
  486: 	my $order = &get_next_permutation();
  487: 	my (@awards, @msgs, $i);
  488: 	foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
  489: 	    my $key = "$thisanswer\0".$responses->[$order->[$i]];
  490: 	    push(@awards,$memoized{$key}[0]);
  491: 	    push(@msgs,$memoized{$key}[1]);
  492: 	    $i++;
  493: 
  494: 	}
  495: 	&LONCAPA_INTERNAL_DEBUG(" all awards ".join(':',@awards));
  496: 
  497: 	my ($possible_award,$possible_msg) = 
  498: 	    &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
  499: 	&LONCAPA_INTERNAL_DEBUG(" pos awards ".$possible_award);
  500: 	push(@final_awards,$possible_award);
  501: 	push(@final_msg,$possible_msg);
  502:     }
  503: 
  504:     &LONCAPA_INTERNAL_DEBUG(" all final_awards ".join(':',@final_awards));
  505:     my ($final_award,$final_msg) = 
  506: 	&LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
  507:     return ($final_award,$final_msg,$error,$control_chars_removed,$ansstring);
  508: }
  509: 
  510: sub verify_stringresponse {
  511:     my ($type,$award,$resp,$ans) = @_;
  512:     return if ($award eq 'EXACT_ANS');
  513:     my $error;
  514:     if ($resp =~ /^\s|\s$/) {
  515:         $resp =~ s{^\s+|\s+$}{}g;
  516:     }
  517:     if ($ans =~ /^\s|\s$/) {
  518:         $ans =~ s{^\s+|\s+$}{}g;
  519:     }
  520:     if ($type eq 'ci') {
  521:         $resp = lc($resp);
  522:         $ans = lc($ans);
  523:     }
  524:     if ($resp eq $ans) {
  525:         if ($award eq 'INCORRECT') {
  526:             $error = 'MISGRADED';
  527:         }
  528:     }
  529:     return $error;
  530: }
  531: 
  532: sub cas {
  533:     my ($system,$input,$library)=@_;
  534:     my $output;
  535:     my $dump;
  536:     if ($system eq 'maxima') {
  537:        $output=&maxima_eval($input,$library);
  538:     } elsif ($system eq 'R') {
  539:        ($output,$dump)=&r_eval($input,$library,0);
  540:     } else {
  541:        $output='Error: unrecognized CAS';
  542:     }
  543:     return $output;
  544: }
  545: 
  546: sub cas_hashref {
  547:     my ($system,$input,$library)=@_;
  548:     if ($system eq 'maxima') {
  549:        return 'Error: unsupported CAS';
  550:     } elsif ($system eq 'R') {
  551:        return &r_eval($input,$library,1);
  552:     } else {
  553:        return 'Error: unrecognized CAS';
  554:     }
  555: }
  556: 
  557: #
  558: # cas_hashref_entry takes a list of indices and gets the entry in a hash generated by Rreturn.
  559: # Call: cas_hashref_entry(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
  560: # Rentry will return the first scalar value it encounters (ignoring excess indices).
  561: # If an invalid key is given, it returns undef.
  562: #
  563: sub cas_hashref_entry {
  564:     return &Rentry(@_);
  565: }
  566: 
  567: #
  568: # cas_hashref_array takes a list of indices and gets a column array from a hash generated by Rreturn.
  569: # Call: cas_hashref_array(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
  570: # If an invalid key is given, it returns undef.
  571: #
  572: sub cas_hashref_array {
  573:     return &Rarray(@_);
  574: }
  575: 
  576: sub tex {
  577:     if ( $external::target eq "tex" ) {
  578: 	return $_[0];
  579:     } else {
  580: 	return $_[1];
  581:     }
  582: }
  583: 
  584: sub var_in_tex {
  585:     if ( $external::target eq "tex" ) {
  586: 	return $_[0];
  587:     } else {
  588: 	return "";
  589:     }
  590: }
  591: 
  592: sub web {
  593:     if ( $external::target eq "tex" ) {
  594: 	return $_[1];
  595:     } else {
  596: 	if ( $external::target eq "web" || $external::target eq "answer") {
  597: 	    return $_[2];
  598: 	} else {
  599: 	    return $_[0];
  600: 	}
  601:     }
  602: }
  603: 
  604: sub html {
  605:     if ( $external::target eq "web" ) {
  606: 	return shift;
  607:     }
  608: }
  609: 
  610: sub hinton {
  611:     return 0;
  612: }
  613: 
  614: sub random {
  615:     my ($start,$end,$step)=@_;
  616:     if ( ! $hidden::RANDOMINIT ) {
  617: 	if ($external::randomseed == 0) { $external::randomseed=1; }
  618: 	if ($external::randomseed =~/,/) {
  619: 	    my ($num1,$num2)=split(/,/,$external::randomseed);
  620: 	    &random_set_seed(1,abs($num1));
  621: 	} elsif ($external::randomseed =~/:/) {
  622: 	    my ($num1,$num2)=split(/:/,$external::randomseed);
  623: 	    &random_set_seed(abs($num1),abs($num2));
  624: 	} else {
  625: 	    &random_set_seed(1,int(abs($external::randomseed)));
  626: 	}
  627: 	&math_random_uniform();
  628: 	$hidden::RANDOMINIT=1;
  629:     }
  630:     if (!defined($step)) { $step=1; }
  631:     my $num=1+int(($end-$start)/$step);
  632:     my $result=$start + int(&math_random_uniform() * $num)*$step;
  633:     return $result;
  634: }
  635: 
  636: sub random_normal {
  637:     my ($item_cnt,$seed,$av,$std_dev) = @_;
  638:     my @oldseed=&random_get_seed();
  639:     my @retArray;
  640:     &random_set_seed_from_phrase($seed);
  641:     @retArray=&math_random_normal($item_cnt,$av,$std_dev);
  642:     &random_set_seed(@oldseed);
  643:     return @retArray;
  644: }
  645: 
  646: sub random_beta {
  647:     my ($item_cnt,$seed,$aa,$bb) = @_;
  648:     my @oldseed=&random_get_seed();
  649:     my @retArray;
  650:     &random_set_seed_from_phrase($seed);
  651:     @retArray=&math_random_beta($item_cnt,$aa,$bb);
  652:     &random_set_seed(@oldseed);
  653:     return @retArray;
  654: }
  655: 
  656: sub random_gamma {
  657:     my ($item_cnt,$seed,$a,$r) = @_;
  658:     my @oldseed=&random_get_seed();
  659:     my @retArray;
  660:     &random_set_seed_from_phrase($seed);
  661:     @retArray=&math_random_gamma($item_cnt,$a,$r);
  662:     &random_set_seed(@oldseed);
  663:     return @retArray;
  664: }
  665: 
  666: sub random_exponential {
  667:     my ($item_cnt,$seed,$av) = @_;
  668:     my @oldseed=&random_get_seed();
  669:     my @retArray;
  670:     &random_set_seed_from_phrase($seed);
  671:     @retArray=&math_random_exponential($item_cnt,$av);
  672:     &random_set_seed(@oldseed);
  673:     return @retArray;
  674: }
  675: 
  676: sub random_poisson {
  677:     my ($item_cnt,$seed,$mu) = @_;
  678:     my @oldseed=&random_get_seed();
  679:     my @retArray;
  680:     &random_set_seed_from_phrase($seed);
  681:     @retArray=&math_random_poisson($item_cnt,$mu);
  682:     &random_set_seed(@oldseed);
  683:     return @retArray;
  684: }
  685: 
  686: sub random_chi {
  687:     my ($item_cnt,$seed,$df) = @_;
  688:     my @oldseed=&random_get_seed();
  689:     my @retArray;
  690:     &random_set_seed_from_phrase($seed);
  691:     @retArray=&math_random_chi_square($item_cnt,$df);
  692:     &random_set_seed(@oldseed);
  693:     return @retArray;
  694: }
  695: 
  696: sub random_noncentral_chi {
  697:     my ($item_cnt,$seed,$df,$nonc) = @_;
  698:     my @oldseed=&random_get_seed();
  699:     my @retArray;
  700:     &random_set_seed_from_phrase($seed);
  701:     @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
  702:     &random_set_seed(@oldseed);
  703:     return @retArray;
  704: }
  705: 
  706: sub random_f {
  707:     my ($item_cnt,$seed,$dfn,$dfd) = @_;
  708:     my @oldseed=&random_get_seed();
  709:     my @retArray;
  710:     &random_set_seed_from_phrase($seed);
  711:     @retArray=&math_random_f($item_cnt,$dfn,$dfd);
  712:     &random_set_seed(@oldseed);
  713:     return @retArray;
  714: }
  715: 
  716: sub random_noncentral_f {
  717:     my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
  718:     my @oldseed=&random_get_seed();
  719:     my @retArray;
  720:     &random_set_seed_from_phrase($seed);
  721:     @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
  722:     &random_set_seed(@oldseed);
  723:     return @retArray;
  724: }
  725: 
  726: sub random_multivariate_normal {
  727:     my ($item_cnt,$seed,$mean,$covar) = @_;
  728:     my @oldseed=&random_get_seed();
  729:     &random_set_seed_from_phrase($seed);
  730:     my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
  731:     &random_set_seed(@oldseed);
  732:     return @retArray;
  733: }
  734: 
  735: sub random_multinomial {
  736:     my ($item_cnt,$seed,@p) = @_;
  737:     my @oldseed=&random_get_seed();
  738:     my @retArray;
  739:     &random_set_seed_from_phrase($seed);
  740:     my @retArray=&math_random_multinomial($item_cnt,@p);
  741:     &random_set_seed(@oldseed);
  742:     return @retArray;
  743: }
  744: 
  745: sub random_permutation {
  746:     my ($seed,@inArray) = @_;
  747:     my @oldseed=&random_get_seed();
  748:     my @retArray;
  749:     &random_set_seed_from_phrase($seed);
  750:     @retArray=&math_random_permutation(@inArray);
  751:     &random_set_seed(@oldseed);
  752:     return @retArray;
  753: }
  754: 
  755: sub random_uniform {
  756:     my ($item_cnt,$seed,$low,$high) = @_;
  757:     my @oldseed=&random_get_seed();
  758:     my @retArray;
  759:     &random_set_seed_from_phrase($seed);
  760:     @retArray=&math_random_uniform($item_cnt,$low,$high);
  761:     &random_set_seed(@oldseed);
  762:     return @retArray;
  763: }
  764: 
  765: sub random_uniform_integer {
  766:     my ($item_cnt,$seed,$low,$high) = @_;
  767:     my @oldseed=&random_get_seed();
  768:     my @retArray;
  769:     &random_set_seed_from_phrase($seed);
  770:     @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
  771:     &random_set_seed(@oldseed);
  772:     return @retArray;
  773: }
  774: 
  775: sub random_binomial {
  776:     my ($item_cnt,$seed,$nt,$p) = @_;
  777:     my @oldseed=&random_get_seed();
  778:     my @retArray;
  779:     &random_set_seed_from_phrase($seed);
  780:     @retArray=&math_random_binomial($item_cnt,$nt,$p);
  781:     &random_set_seed(@oldseed);
  782:     return @retArray;
  783: }
  784: 
  785: sub random_negative_binomial {
  786:     my ($item_cnt,$seed,$ne,$p) = @_;
  787:     my @oldseed=&random_get_seed();
  788:     my @retArray;
  789:     &random_set_seed_from_phrase($seed);
  790:     @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
  791:     &random_set_seed(@oldseed);
  792:     return @retArray;
  793: }
  794: 
  795: sub abs { CORE::abs(shift) }
  796: sub sin { CORE::sin(shift) }
  797: sub cos { CORE::cos(shift) }
  798: sub exp { CORE::exp(shift) }
  799: sub int { CORE::int(shift) }
  800: sub log { CORE::log(shift) }
  801: sub atan2 { CORE::atan2($_[0],$_[1]) }
  802: sub sqrt { CORE::sqrt(shift) }
  803: 
  804: sub tan  { CORE::sin($_[0]) / CORE::cos($_[0]) }
  805: #sub atan { atan2($_[0], 1); }
  806: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
  807: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) );  }
  808: 
  809: sub log10 { CORE::log($_[0])/CORE::log(10); }
  810: 
  811: sub factorial {
  812:     my $input = CORE::int(shift);
  813:     return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
  814:     return "Error - factorial result is greater than system limit ($input)" if $input > 170;
  815:     return 1 if $input == 0;
  816:     my $result = 1; 
  817:     for (my $i=2; $i<=$input; $i++) { $result *= $i }
  818:     return $result;
  819: }
  820: 
  821: sub sgn {
  822:     return -1 if $_[0] < 0;
  823:     return 0 if $_[0] == 0;
  824:     return 1 if $_[0] > 0;
  825: }
  826: 
  827: sub min {
  828:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  829:     return shift @sorted;
  830: }
  831: 
  832: sub max {
  833:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  834:     return pop @sorted;
  835: }
  836: 
  837: sub roundto {
  838:     my ($input,$n) = @_;
  839:     return sprintf('%.'.$n.'f',$input);
  840: }
  841: 
  842: sub to_string {
  843:     my ($input,$n) = @_;
  844:     return sprintf($input) if $n eq "";
  845:     $n = '.'.$n if $n !~ /^\./;
  846:     return sprintf('%'.$n,$input) if $n ne "";
  847: }
  848: 
  849: sub sub_string {
  850:     my ($str,$start,$len) = @_;
  851:     return substr($str,$start-1,$len);
  852: }
  853: 
  854: sub pow   {return $_[0] ** $_[1]; }
  855: sub ceil  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
  856: sub floor  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
  857: #sub floor {return int($_[0]); }
  858: 
  859: sub format {
  860:     my ($value,$fmt)=@_;
  861:     my ($dollarmode,$commamode,$alwaysperiod,$options);
  862:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
  863:     #if ($options =~ /\$/) { $dollamode=1; }
  864:     #if ($options =~ /,/)  { $commamode=1; }
  865:     if ($options =~ /\./) { $alwaysperiod=1; }
  866:     my $result;
  867:     if ($fmt=~/s$/i) {
  868: 	$result=&format_significant_figures($value,$fmt);
  869:     } else {
  870: 	$fmt=~s/e/E/g;
  871: 	$result=sprintf('%.'.$fmt,$value);
  872: 	if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
  873: 	$result=~s/(E[+-]*)0/$1/;
  874:     }
  875:     #if ($dollarmode) {$result=&dollarformat($result);}
  876:     #if ($commamode) {$result=&commaformat($result);}
  877:     return $result;
  878: }
  879: 
  880: sub chemparse {
  881:     my ($reaction) = @_;
  882:     my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
  883:     my $formula = '';
  884:     foreach my $token (@tokens) {
  885: 	if ($token eq '->' ) {
  886: 	    $formula .= '<m>\ensuremath{\rightarrow}</m> ';
  887: 	    next;
  888: 	}
  889: 	if ($token eq '<-' ) {
  890: 	    $formula .= '<m>\ensuremath{\leftarrow}</m> ';
  891: 	    next;
  892: 	}  
  893: 	if ($token eq '<=>') {
  894: 	    if ($external::target eq 'web' &&
  895: 		&EXT('request.browser.unicode')) {
  896: 		$formula .= '&#8652; ';
  897: 	    } else {
  898: 		$formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
  899: 				 '&lt;=&gt; ');
  900: 	    }
  901: 	    next;
  902: 	}
  903: 	if ($token eq '.') {
  904: 	  $formula =~ s/(\&nbsp\;| )$//;
  905: 	  $formula .= '&middot;';
  906: 	  next;
  907: 	}
  908: 	$token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
  909:         $formula .= $1 if ($1 ne '1');  # stoichiometric coefficient
  910: 	
  911: 	my $molecule = $2;
  912: 	# subscripts
  913: 	$molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
  914: 	# superscripts
  915: 	$molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
  916: 	# strip whitespace
  917: 	$molecule =~ s/\s*//g;
  918: 	# forced space
  919: 	$molecule =~ s/_/ /g;
  920: 	$molecule =~ s/-/&minus;/g;
  921: 	$formula .= $molecule.'&nbsp;';
  922:     }
  923:     # get rid of trailing space
  924:     $formula =~ s/(\&nbsp\;| )$//;
  925:     return &xmlparse($formula);
  926: }
  927: 
  928: sub prettyprint {
  929:     my ($value,$fmt,$target)=@_;
  930:     my $result;
  931:     if (!$target) { $target = $external::target; }
  932:     if ($fmt =~ /chem/i) { return(&chemparse($value)); }
  933:     my ($dollarmode,$commamode,$alwaysperiod,$options);
  934:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
  935:     if ($options =~ /\$/) { $dollarmode=1; }
  936:     if ($options =~ /,/)  { $commamode=1; }
  937:     if ($options =~ /\./) { $alwaysperiod=1; }
  938:     if ($fmt=~/s$/i) {
  939: 	$value=&format_significant_figures($value,$fmt);
  940:     } elsif ($fmt) {
  941: 	$value=sprintf('%.'.$fmt,$value);
  942:     }
  943:     if ($alwaysperiod && $fmt eq '0f') {
  944: 	if ($target eq 'tex') {
  945: 	    $value .='\\ensuremath{.}';
  946: 	} else {
  947: 	    $value .='.';
  948: 	}
  949:     }
  950:     if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
  951: 	my $frac=$1;
  952: 	if ($dollarmode) { $frac=&dollarformat($frac); }
  953: 	if ($commamode) { $frac=&commaformat($frac); }
  954: 	my $exponent=$2;
  955: 	$exponent=~s/^\+0*//;
  956: 	$exponent=~s/^-0*/-/;
  957: 	$exponent=~s/^-0*/-/;
  958: 	if ($exponent eq '-') { undef($exponent); }
  959: 	if ($exponent) {
  960: 	    if ($target eq 'web') {
  961: 		$result=$frac.'&#215;10<sup>'.$exponent.'</sup>';
  962: 	    } elsif ($target eq 'tex') {
  963: 		$result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
  964: 	    } else {
  965: 		$result=$value;
  966: 	    }
  967: 	} else {
  968: 	    $result=$frac;
  969: 	}
  970:     } else {
  971: 	$result=$value;
  972: 	if    ($dollarmode) { $result=&dollarformat($result,$target); }
  973: 	elsif ($commamode)  { $result=&commaformat($result,$target); }
  974:     }
  975:     return $result;
  976: }
  977: 
  978: sub commaformat {
  979:     my ($number,$target) = @_;
  980:     if ($number =~ /\./) {
  981: 	while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
  982: 	    $number = $1.$2.','.$3.$4;
  983: 	}
  984:     } else {
  985: 	while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
  986: 	    $number = $1.$2.','.$3.$4;
  987: 	}
  988:     }
  989:     return $number;
  990: }
  991: 
  992: sub dollarformat {
  993:     my ($number,$target) = @_;
  994:     if (!$target) { $target = $external::target; }
  995:     $number=&commaformat($number,$target);
  996:     if ($target eq 'tex') {
  997: 	$number='\$'.$number; #' stupid emacs
  998:     } else {
  999: 	$number='$'.$number; #' stupid emacs
 1000:     }
 1001:     return $number; 
 1002: }
 1003: 
 1004: # format of form ns or nS where n is an integer
 1005: sub format_significant_figures {
 1006:     my ($number,$format) = @_; 
 1007:     return '0' if ($number == 0);
 1008:     # extract number of significant figures needed
 1009:     my ($sig) = ($format =~ /(\d+)s/i);
 1010:     # arbitrary choice - suggestions ?? or throw error message?
 1011:     $sig = 3 if ($sig eq '');
 1012:     # save the minus sign
 1013:     my $sign = ($number < 0) ? '-' : '';
 1014:     $number = abs($number);
 1015:     # needed to correct for a number greater than 1 (or
 1016:     my $power = ($number < 1) ? 0 : 1;
 1017:     # could round up. Take the integer part of log10.
 1018:     my $x10 = int(log($number)/log(10));
 1019:     # find number with values left of decimal pt = # of sign figs.
 1020:     my $xsig = $number*10**($sig-$x10-$power);
 1021:     # get just digits left of decimal pt - also rounds off correctly
 1022:     my $xint  = sprintf('%.0f',$xsig);
 1023:     # save any trailing zero's
 1024:     my ($zeros) = ($xint =~ /(0+)$/);
 1025:     # return number to original magnitude
 1026:     my $numSig = $xint*10**($x10-$sig+$power);
 1027:     # insert trailing zero's if have decimal point
 1028:     $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
 1029:     # put a decimal pt for number ending with 0 and length = # of sig fig
 1030:     $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
 1031:     if (length($numSig) < $sig) {
 1032: 	$numSig.='.'.substr($zeros,0,($sig-length($numSig)));
 1033:     }
 1034:     # return number with sign
 1035:     return $sign.$numSig;
 1036: 
 1037: }
 1038: 
 1039: sub map {
 1040:     my ($phrase,$dest,$source)=@_;
 1041:     my @oldseed=&random_get_seed();
 1042:     my @seed = &random_seed_from_phrase($phrase);
 1043:     &random_set_seed(@seed);
 1044:     my $destct = scalar(@$dest);
 1045:     if (!$source) {
 1046: 	my @output;
 1047: 	my @idx = &math_random_permuted_index($destct);
 1048: 	my $ctr = 0;
 1049: 	while ($ctr < $destct) {
 1050: 	    $output[$ctr] = $$dest[$idx[$ctr]];
 1051: 	    $ctr++;
 1052: 	}
 1053:         &random_set_seed(@oldseed);
 1054: 	return @output;
 1055:     } else {
 1056: 	my $num = scalar(@$source);
 1057: 	my @idx = &math_random_permuted_index($num);
 1058: 	my $ctr = 0;
 1059: 	my $tot = $num;
 1060: 	$tot = $destct if $destct < $num;
 1061: 	if (ref($$dest[0])) {
 1062: 	    while ($ctr < $tot) {
 1063: 		${$$dest[$ctr]} = $$source[$idx[$ctr]];
 1064: 	        $ctr++;
 1065:             }
 1066:         } else {
 1067: 	    while ($ctr < $tot) {
 1068: 		$$dest[$ctr] = $$source[$idx[$ctr]];
 1069: 		$ctr++;
 1070: 	    }
 1071: 	}
 1072:     }
 1073:     &random_set_seed(@oldseed);
 1074:     return '';
 1075: }
 1076: 
 1077: sub rmap {
 1078:     my ($phrase,$dest,$source)=@_;
 1079:     my @oldseed=&random_get_seed();
 1080:     my @seed = &random_seed_from_phrase($phrase);
 1081:     &random_set_seed(@seed);
 1082:     my $destct = scalar(@$dest);
 1083:     if (!$source) {
 1084: 	my @idx = &math_random_permuted_index($destct);
 1085: 	my $ctr = 0;
 1086: 	my @r_idx;
 1087: 	while ($ctr < $destct) {
 1088: 	    $r_idx[$idx[$ctr]] = $ctr;
 1089: 	    $ctr++;
 1090: 	}
 1091: 	my @output;
 1092: 	$ctr = 0;
 1093: 	while ($ctr < $destct) {
 1094: 	    $output[$ctr] = $$dest[$r_idx[$ctr]];
 1095: 	    $ctr++;
 1096: 	}
 1097:         &random_set_seed(@oldseed);
 1098: 	return @output;
 1099:     } else {
 1100: 	my $num = scalar(@$source);
 1101: 	my @idx = &math_random_permuted_index($num);
 1102: 	my $ctr = 0;
 1103: 	my $tot = $num;
 1104: 	$tot = $destct if $destct < $num;
 1105: 	my @r_idx;
 1106: 	while ($ctr < $tot) {
 1107: 	    $r_idx[$idx[$ctr]] = $ctr;
 1108: 	    $ctr++;
 1109: 	}
 1110: 	$ctr = 0;
 1111: 	if (ref($$dest[0])) {
 1112: 	    while ($ctr < $tot) {
 1113: 		${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
 1114: 	        $ctr++;
 1115:             }
 1116:         } else {
 1117: 	    while ($ctr < $tot) {
 1118: 		$$dest[$ctr] = $$source[$r_idx[$ctr]];
 1119: 		$ctr++;
 1120: 	    }
 1121: 	}
 1122:     }
 1123:     &random_set_seed(@oldseed);
 1124:     return '';
 1125: }
 1126: 
 1127: sub capa_id { return }
 1128: 
 1129: sub problem { return }
 1130: 
 1131: sub name{
 1132:     my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
 1133:     $fullname = "" if $fullname eq ",  ";
 1134:     $fullname =~ s/\%2d/-/g;
 1135:     return $fullname;
 1136: }
 1137: 
 1138: sub student_number { 
 1139:     my $id = &EXT('environment.id');
 1140:     $id = '' if $id eq "";
 1141:     return $id;
 1142: }
 1143: 
 1144: sub class {
 1145:     my $course = &EXT('course.description');
 1146:     $course = '' if $course eq "";
 1147:     return $course;
 1148: }
 1149: 
 1150: sub classid {
 1151:     my $courseid = &EXT('request.course.id');
 1152:     $courseid = '' if $courseid eq "";
 1153:     return $courseid;
 1154: }
 1155: 
 1156: sub firstname {
 1157:     my $firstname = &EXT('environment.firstname');
 1158:     $firstname = '' if $firstname eq "";
 1159:     return $firstname;
 1160: }
 1161: 
 1162: sub middlename {
 1163:     my $middlename = &EXT('environment.middlename');
 1164:     $middlename = '' if $middlename eq "";
 1165:     return $middlename;
 1166: }
 1167: 
 1168:                                                                                 
 1169: sub lastname {
 1170:     my $lastname = &EXT('environment.lastname');
 1171:     $lastname = '' if $lastname eq "";
 1172:     return $lastname;
 1173: }
 1174: 
 1175: sub sec { 
 1176:     my $sec = &EXT('request.course.sec');
 1177:     $sec = '' if $sec eq "";
 1178:     return $sec;
 1179: }
 1180: 
 1181: sub submission {
 1182:    my ($partid,$responseid,$subnumber)=@_;
 1183:    my $sub='';
 1184:    if ($subnumber) { $sub=$subnumber.':'; }
 1185:    return &EXT('user.resource.'.$sub.'resource.'.$partid.'.'.$responseid.'.submission');
 1186: }
 1187: 
 1188: sub currentpart {
 1189:    return $external::part;
 1190: }
 1191: 
 1192: sub eval_time {
 1193:    my ($timestamp)=@_;
 1194:    unless ($timestamp) { return ''; }
 1195:    return &locallocaltime($timestamp);
 1196: }
 1197: 
 1198: sub open_date { 
 1199:     my ($partid)=@_;
 1200:     unless ($partid) { $partid=0; }
 1201:     return &eval_time(&EXT('resource.'.$partid.'.opendate'));
 1202: }
 1203: 
 1204: sub due_date {
 1205:     my ($partid)=@_;
 1206:     unless ($partid) { $partid=0; } 
 1207:     return &eval_time(&EXT('resource.'.$partid.'.duedate'));
 1208: }
 1209: 
 1210: sub answer_date { 
 1211:     my ($partid)=@_;
 1212:     unless ($partid) { $partid=0; }
 1213:     return &eval_time(&EXT('resource.'.$partid.'.answerdate'));
 1214: }
 1215: 
 1216: sub open_date_epoch {
 1217:     my ($partid)=@_;
 1218:     unless ($partid) { $partid=0; }
 1219:     return &EXT('resource.'.$partid.'.opendate');
 1220: }
 1221: 
 1222: sub due_date_epoch {
 1223:     my ($partid)=@_;
 1224:     unless ($partid) { $partid=0; }
 1225:     return &EXT('resource.'.$partid.'.duedate');
 1226: }
 1227: 
 1228: sub answer_date_epoch {
 1229:     my ($partid)=@_;
 1230:     unless ($partid) { $partid=0; }
 1231:     return &EXT('resource.'.$partid.'.answerdate');
 1232: }
 1233: 
 1234: sub parameter_setting {
 1235:     my ($which,$partid)=@_;
 1236:     unless ($partid) { $partid=0; }
 1237:     return &EXT('resource.'.$partid.'.'.$which);
 1238: }
 1239: 
 1240: sub stored_data {
 1241:     my ($which,$partid)=@_;
 1242:     unless ($partid) { $partid=0; }
 1243:     return &EXT('user.resource.resource.'.$partid.'.'.$which);
 1244: }
 1245: 
 1246: sub wrong_bubbles {
 1247:     my ($correct,$lower,$upper,$step,@given)=@_;
 1248:     my @array=();
 1249:     my %hash=();
 1250:     foreach my $new (@given) {
 1251:         $hash{$new}=1;
 1252:     }
 1253:     my $num=int(&parameter_setting('numbubbles',&currentpart()));
 1254:     unless ($num) { $num=8; }
 1255:     if ($num>1) {
 1256:         for (my $i=0;$i<=500;$i++) {
 1257:             my $new=&random($lower,$upper,$step);
 1258:             if ($hash{$new}) { next; }
 1259:             if (abs($new-$correct)<$step) { next; }
 1260:             $hash{$new}=1;
 1261:             @array=keys(%hash);
 1262:             if ($#array+2>=$num) { last; }
 1263:         }
 1264:     }
 1265:     return @array;
 1266: }
 1267: 
 1268: sub array_moments {
 1269:     my @input=@_;
 1270:     my (@output,$N);
 1271:     $N=scalar (@input);
 1272:     $output[0]=$N;
 1273:     if ($N <= 1) {
 1274: 	$output[1]=$input[0];
 1275: 	$output[1]="Input array not defined" if ($N == 0);
 1276: 	$output[2]="variance undefined for N<=1";
 1277: 	$output[3]="skewness undefined for N<=1";
 1278: 	$output[4]="kurtosis undefined for N<=1";
 1279: 	return @output;
 1280:     }
 1281:     my $sum=0;
 1282:     foreach my $line (@input) {
 1283: 	$sum+=$line;
 1284:     }
 1285:     $output[1] = $sum/$N;
 1286:     my ($x,$sdev,$var,$skew,$kurt) = 0;
 1287:     foreach my $line (@input) {
 1288: 	$x=$line-$output[1];
 1289: 	$var+=$x**2;
 1290: 	$skew+=$x**3;
 1291: 	$kurt+=$x**4;
 1292:     }
 1293:     $output[2]=$var/($N-1);
 1294:     $sdev=CORE::sqrt($output[2]);
 1295:     if ($sdev == 0) {
 1296: 	$output[3]="inf-variance=0";
 1297: 	$output[4]="inf-variance=0";
 1298: 	return @output;
 1299:     }
 1300:     $output[3]=$skew/($sdev**3*$N);
 1301:     $output[4]=$kurt/($sdev**4*$N)-3;
 1302:     return @output;
 1303: }
 1304: 
 1305: sub choose {
 1306:     my $num = $_[0];
 1307:     return $_[$num];
 1308: }
 1309: 
 1310: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
 1311: #sub sum1 {
 1312: #    my ($start,$end,$sub)=@_;
 1313: #    my $sum=0;
 1314: #    for (my $i=$start;$i<=$end;$i++) {
 1315: #        $sum+=&$sub($i);
 1316: #    }
 1317: #    return $sum
 1318: #}
 1319: 
 1320: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
 1321: #sub sum2 {
 1322: #    my ($varname,$start,$end,$line)=@_;
 1323: #    my $sum=0;
 1324: #    for (my $i=$start;$i<=$end;$i++) {
 1325: #	my $func=sub {
 1326: #	    eval("\$".$varname."=$i");
 1327: #	    eval($line);
 1328: #	};
 1329: #        $sum+=&$func($i);
 1330: #    }
 1331: #    return $sum
 1332: #}
 1333: 
 1334: # expiremental idea
 1335: sub proper_path {
 1336:     my ($path)=@_;
 1337:     if ( $external::target eq "tex" ) {
 1338: 	return '/home/httpd/html'.$path;
 1339:     } else {
 1340: 	return $path;
 1341:     }
 1342: }
 1343: 

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