File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.176: download - view: text, annotated - select for diffs
Wed Apr 3 21:37:11 2019 UTC (5 years ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_X, version_2_11_4_uiuc, version_2_11_4_msu, version_2_11_4, version_2_11_3_uiuc, version_2_11_3_msu, version_2_11_3, HEAD
- Bug 6903. Args passed to &Math::Random::random_set_seed() need to be
  within bounds, otherwise use &Math::Random::random_set_seed_from_phrase()

    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.176 2019/04/03 21:37:11 raeburn 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:     #type's definitons come from capaParser.h
  147: 
  148:     #remove leading and trailing whitespace
  149:     if (!defined($response)) {
  150: 	$response='';
  151:     }
  152:     if ($response=~ /^\s|\s$/) {
  153: 	$response=~ s:^\s+|\s+$::g;
  154:     }
  155: 
  156:     if ($type eq 'cs' || $type eq 'ci') {
  157: 	#for string answers make sure all places spaces occur, there is 
  158:         #really only 1 space, in both the answer and the response
  159: 	$answer=~s/ +/ /g;
  160: 	$response=~s/ +/ /g;
  161:     } elsif ($type eq 'mc') {
  162: 	$answer=~s/[\s,]//g;
  163: 	$response=~s/[\s,]//g;
  164:     }
  165:     if ($type eq 'float' && $unit=~/\$/) {
  166: 	if ($response!~/^\$|\$$/)  { return ('NO_UNIT', undef); }
  167: 	$response=~s/\$//g;
  168:     }
  169:     if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
  170: 	return "COMMA_FAIL:";
  171:     }
  172:     $ans_fmt=~s/\W//g;
  173:     $unit=~s/[\$,]//g;
  174:     if ($type eq 'float') { $response=~s/,//g; }
  175: 
  176:     if (length($response) > 500) { return ('TOO_LONG',undef); }
  177: 
  178:     if ($type eq '' ) {
  179: 	if ( $answer eq ($answer *1.0)) { $type = 2;
  180: 				      } else { $type = 3; }
  181:     } else {
  182: 	if    ($type eq 'cs')    { $type = 4; }
  183: 	elsif ($type eq 'ci')    { $type = 3 }
  184: 	elsif ($type eq 'mc')    { $type = 5; }
  185: 	elsif ($type eq 'fml')   { $type = 8; }
  186:         elsif ($type eq 'math')  { $type = 9; }
  187: 	elsif ($type eq 'subj')  { $type = 7; }
  188: 	elsif ($type eq 'float') { $type = 2; }
  189: 	elsif ($type eq 'int')   { $type = 1; }
  190: 	else { return ('ERROR', "Unknown type of answer: $type") }
  191:     }
  192: 
  193:     my $points;
  194:     my $id_list;
  195:     #formula type setup the sample points
  196:     if ($type eq '8') {
  197: 	($id_list,$points)=split(/@/,$samples);
  198:     }
  199:     if ($tol eq '') {
  200: 	$tol=0.0;
  201: 	$tol_type=1; #TOL_ABSOLUTE
  202:     } else {
  203: 	if ($tol =~ /%$/) {
  204: 	    chop $tol;
  205: 	    $tol_type=2; #TOL_PERCENTAGE
  206: 	} else {
  207: 	    $tol_type=1; #TOL_ABSOLUTE
  208: 	}
  209:     }
  210: 
  211:     ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
  212: 
  213:     my $reterror="";
  214:     my $result;
  215:     if (($type eq '9') || ($type eq '8')) {
  216:         if ($response=~/\=/) {
  217:             return ('BAD_FORMULA','Please submit just an expression, not an equation.');
  218:         } elsif ($response =~ /\,/ and $response !~ /^\s*\{.*\}\s*$/) {
  219:             return ('BAD_FORMULA');
  220:         }
  221:     }
  222:     if ($type eq '9') {
  223:       $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
  224:     } else {
  225: 	if ($type eq '8') { # fml type
  226: 	    $response = &capa_formula_fix($response);
  227: 	    $answer   = &capa_formula_fix($answer);
  228: 	}
  229:        $result = &caparesponse_capa_check_answer($response,$answer,$type,
  230: 						 $tol_type,$tol,
  231: 						 $sig_lbound,$sig_ubound,
  232: 						 $ans_fmt,$unit,$calc,$id_list,
  233: 						 $points,$external::randomseed,
  234: 						 \$reterror);
  235:     }
  236:     if    ($result == '1') { $result='EXACT_ANS'; } 
  237:     elsif ($result == '2') { $result='APPROX_ANS'; }
  238:     elsif ($result == '3') { $result='SIG_FAIL'; }
  239:     elsif ($result == '4') { $result='UNIT_FAIL'; }
  240:     elsif ($result == '5') { $result='NO_UNIT'; }
  241:     elsif ($result == '6') { $result='UNIT_OK'; }
  242:     elsif ($result == '7') { $result='INCORRECT'; }
  243:     elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
  244:     elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
  245:     elsif ($result =='10') { $result='SUB_RECORDED'; }
  246:     elsif ($result =='11') { $result='BAD_FORMULA'; }
  247:     elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
  248:     elsif ($result =='12') { $result='WANTED_NUMERIC'; }
  249:     elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
  250:     elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
  251:     elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
  252:     elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
  253:     elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
  254:     else  {$result = "ERROR: Unknown Result:$result:$@:";}
  255: 
  256:     return ($result,$reterror);
  257: }
  258: 
  259: 
  260: sub caparesponse_check_list {
  261:     my $responses=$LONCAPA::CAPAresponse_args{'response'};
  262:     &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
  263:     my $type = $LONCAPA::CAPAresponse_args{'type'};
  264:     my $answerunit=$LONCAPA::CAPAresponse_args{'unit'};
  265:     &LONCAPA_INTERNAL_DEBUG("Got type :$type: answer unit :$answerunit:\n");
  266:    
  267:     my $preprocess=$LONCAPA::CAPAresponse_args{'preprocess'};
  268:     $preprocess=~s/^\&//;
  269: 
  270:     my $num_input_lines =
  271: 	scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}});
  272:     
  273:     if ($type ne '' ) {
  274: 	if (scalar(@$responses) < $num_input_lines) {
  275: 	    return 'MISSING_ANSWER';
  276: 	}
  277: 	if (scalar(@$responses) > $num_input_lines) {
  278: 	    return 'EXTRA_ANSWER';
  279: 	}
  280: 
  281:     }
  282: 
  283:     foreach my $which (0..($num_input_lines-1)) {
  284: 	my $answer_size = 
  285: 	    scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
  286: 	if ($type ne '' 
  287: 	    && $answer_size > 1) {
  288: 	    $responses->[$which]=[split(/,/,$responses->[$which])];
  289: 	} else {
  290: 	    $responses->[$which]=[$responses->[$which]];
  291: 	}
  292:     }
  293:     foreach my $which (0..($num_input_lines-1)) {
  294: 	my $answer_size = 
  295: 	    scalar(@{$LONCAPA::CAPAresponse_answer->{'answers'}[$which]});
  296: 	my $response_size = 
  297: 	    scalar(@{$responses->[$which]});
  298: 	if ($answer_size > $response_size) {
  299: 	    return 'MISSING_ANSWER';
  300: 	}
  301: 	if ($answer_size < $response_size) {
  302: 	    return 'EXTRA_ANSWER';
  303: 	}
  304:     }
  305: 
  306:     my $unit;
  307:     my ($allowalgebra)=($LONCAPA::CAPAresponse_args{'allowalgebra'}=~/^(yes|1|on)$/i);
  308:     if ($type eq 'float' || $type eq '') {
  309: 	#for numerical problems split off the unit
  310:         my $part1;
  311:         my $part2;
  312:         my $match_algebra = qr{^(.*[^\s])\s+([^\s]+)$};
  313:         # FIXME: with the above regexp, algebra with spaces will not be evaluated correctly
  314:         my $match_numerical_units = qr{^([\d\.\,\s\$]*(?:(?:[xX\*]10[\^\*]*|[eE]*)[\+\-]*\d*)*(?:^|\S)\d+)([\$\s\w\^\*\/\(\)\+\-]*[^\d\.\s\,][\$\s\w\^\*\/\(\)\+\-]*)$};
  315:         if ($allowalgebra) {
  316:            ($part1,$part2) = ($responses->[0][-1] =~ /$match_algebra/); 
  317:         } else {
  318:            ($part1,$part2) = ($responses->[0][-1] =~ /$match_numerical_units/);
  319:         }
  320:         if (defined($part1) && defined($part2)) {
  321: 	    $responses->[0][-1]=$part1;
  322: 	    $unit=&capa_formula_fix($part2);
  323:             my $customunits=$LONCAPA::CAPAresponse_args{'customunits'};
  324:             if ($customunits =~ /\S/) {
  325:                 foreach my $replacement (split(/\s*\,\s*/,$customunits)) {
  326:                     my ($which,$what)=split(/\s*\=\s*/,$replacement);
  327:                     if ((defined($which)) && (defined($what))) {
  328:                         $what=&capa_formula_fix($what);
  329:                         $unit=~s/$which/\($what\)/g;
  330:                     }
  331:                 }
  332:             }
  333:             if (scalar(@$responses) > 0 && defined $answerunit) {
  334:                 # there are several response values, units should be the same for all
  335:                 $part2 =~ s/^\s+|\s+$//g;
  336:                 for (my $i=1; $i<scalar(@$responses); $i++) {
  337:                     my $element = $responses->[$i][-1];
  338:                     my ($part1i, $part2i);
  339:                     if ($allowalgebra) {
  340:                         ($part1i, $part2i) = ($element =~ /$match_algebra/); 
  341:                     } else {
  342:                         ($part1i, $part2i) = ($element =~ /$match_numerical_units/);
  343:                     }
  344:                     $part2i =~ s/^\s+|\s+$//g;
  345:                     if (!defined $part2i) {
  346:                         return 'NO_UNIT';
  347:                     } elsif ($part2i ne $part2) {
  348:                         return ('UNIT_FAIL', "$part2 $part2i");
  349:                     } else {
  350:                         $responses->[$i][-1] = $part1i;
  351:                     }
  352:                 }
  353:             }
  354: 	}
  355:     }
  356:     $unit=~s/\s//;
  357:     my $error;
  358:     foreach my $response (@$responses) {
  359:        foreach my $element (@$response) {
  360:           # See if we have preprocessor
  361:           if ($preprocess=~/\S/) {
  362:              if (defined(&$preprocess)) {
  363:                 no strict 'refs';
  364:                 $element=&$preprocess($element,$unit);
  365:                 use strict 'refs';
  366:              }
  367:           }
  368:           if (($type eq 'float') || (($type eq '') && ($unit ne ''))) {
  369:               $element =~ s/\s//g;
  370:           }
  371:           my $appendunit=$unit;
  372: # Deal with percentages
  373: # unit is unit entered by student, answerunit is unit by author
  374: # Deprecated: divide answer by 100 if student entered percent,
  375: # but author did not. Too much confusion
  376: #          if (($unit=~/\%/) && ($answerunit ne '%'))  {
  377: #             $element=$element/100;
  378: #             $appendunit=~s/\%//;
  379: #          }    
  380: # Author entered percent, student did not
  381:           if (($unit!~/\%/) && ($answerunit=~/\%/)) {
  382:              $element=$element*100;
  383:              $appendunit='%'.$appendunit;
  384:           }
  385: # Zero does not need a dimension
  386:           if (($element =~ /^[0\.]+$/) && ($unit!~/\w/) && ($answerunit=~/\w/)) {
  387:              $appendunit=$answerunit;
  388:           }
  389: # Do the math for the student if allowed
  390:           if ($allowalgebra) {
  391:              $element=&cas('maxima',$element);
  392:           }
  393:           if ($appendunit ne '') {
  394:               $element .= " $appendunit";
  395:           }  
  396:           &LONCAPA_INTERNAL_DEBUG("Made response element :$element:");
  397:        }
  398:     }
  399:     
  400:     foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
  401: 	if (!defined($thisanswer)) {
  402: 	    return ('ERROR','answer was undefined');
  403: 	}
  404:     }
  405: 
  406:     my $allow_control_char = 0;
  407:     my $control_chars_removed = 0;
  408:     my $ansstring;
  409:     if ($type eq 'cs' || $type eq 'ci') {
  410:         if (ref($LONCAPA::CAPAresponse_answer->{'answers'}) eq 'ARRAY') {
  411:             foreach my $strans (@{$LONCAPA::CAPAresponse_answer->{'answers'}}) {
  412:                 if (ref($strans) eq 'ARRAY') {
  413:                     $ansstring = join("\0",@{$strans});
  414:                     foreach my $item (@{$strans}) {  
  415:                         if ($item =~ /[\000-\037]/) {
  416:                             $allow_control_char = 1;
  417:                         }
  418:                     }
  419:                 }
  420:             }
  421:         }
  422:     }
  423: 
  424: #    &LONCAPA_INTERNAL_DEBUG(&LONCAPA_INTERNAL_Dumper($responses));
  425:     my %memoized;
  426:     if ($LONCAPA::CAPAresponse_answer->{'type'}  eq 'ordered') {
  427: 	for (my $i=0; $i<scalar(@$responses);$i++) {
  428: 	    my $answer   = $LONCAPA::CAPAresponse_answer->{'answers'}[$i];
  429: 	    my $response = $responses->[$i];
  430: 	    my $key = "$answer\0$response";
  431: 	    my (@awards,@msgs);
  432: 	    for (my $j=0; $j<scalar(@$response); $j++) {
  433:                 if ($type eq 'cs' || $type eq 'ci') {
  434:                     unless ($allow_control_char) {
  435:                         if ($response->[$j] =~ /[\000-\037]/) { 
  436:                             $response->[$j] =~ s/[\000-\037]//g;
  437:                             $control_chars_removed = 1;
  438:                         }  
  439:                     }
  440:                 }
  441:                 # See if we have preprocessor for string responses
  442:                 if (($preprocess=~/\S/) && ($type eq 'cs' || $type eq 'ci'))  {
  443:                     if (defined(&$preprocess)) {
  444:                         no strict 'refs';
  445:                         $response->[$j]=&$preprocess($response->[$j]);
  446:                         use strict 'refs';
  447:                     }
  448:                 }
  449: 
  450: 		my ($award,$msg) = &caparesponse_check($answer->[$j],
  451: 						       $response->[$j]);
  452:                 if ($type eq 'cs' || $type eq 'ci') {
  453:                     $error = &verify_stringresponse($type,$award,$response->[$j],
  454:                                                     $answer->[$j]);
  455:                 }
  456: 		push(@awards,$award);
  457: 		push(@msgs,  $msg);
  458: 	    }
  459: 	    my ($award,$msg) = 
  460: 		&LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
  461: 	    $memoized{$key} = [$award,$msg];
  462: 	}
  463:     } else {
  464: 	#FIXME broken with unorder responses where one is a <value>
  465:         #      and the other is a <vector> (need to delay parse til
  466:         #      inside the loop?)
  467: 	foreach my $response (@$responses) {
  468: 	    my $response_size = scalar(@{$response});
  469: 	    foreach my $answer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
  470: 		my $key = "$answer\0$response";
  471: 		my $answer_size =  scalar(@{$answer});
  472: 		my ($award,$msg);
  473: 		if ($answer_size > $response_size) {
  474: 		    $award = 'MISSING_ANSWER';
  475: 		} elsif ($answer_size < $response_size) {
  476: 		    $award = 'EXTRA_ANSWER';
  477: 		} else {
  478: 		    my (@awards,@msgs);
  479: 		    for (my $j=0; $j<scalar(@$response); $j++) {
  480:                         if ($type eq 'cs' || $type eq 'ci') {
  481:                             unless ($allow_control_char) {
  482:                                 if ($response->[$j] =~ /[\000-\037]/) {
  483:                                     $response->[$j] =~ s/[\000-\037]//g;
  484:                                     $control_chars_removed = 1;
  485:                                 }
  486:                             }
  487:                         }
  488:                         # See if we have preprocessor
  489:                         if (($preprocess=~/\S/) && ($type eq 'cs' || $type eq 'ci')) {
  490:                             if (defined(&$preprocess)) {
  491:                                 no strict 'refs';
  492:                                 $response->[$j]=&$preprocess($response->[$j]);
  493:                                 use strict 'refs';
  494:                             }
  495:                         }
  496: 
  497: 			my ($award,$msg) = &caparesponse_check($answer->[$j],
  498: 							       $response->[$j]);
  499:                         if ($type eq 'cs' || $type eq 'ci') {
  500:                             $error = &verify_stringresponse($type,$award,$response->[$j],
  501:                                                             $answer->[$j]);
  502:                         }
  503: 			push(@awards,$award);
  504: 			push(@msgs,  $msg);
  505: 		    }
  506: 		    ($award,$msg) = 
  507: 			&LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
  508: 		}
  509: 		$memoized{$key} = [$award,$msg];
  510: 	    }
  511: 	}
  512:     }
  513: 
  514:     my ($final_award,$final_msg);
  515:     &init_permutation(scalar(@$responses),
  516: 		      $LONCAPA::CAPAresponse_answer->{'type'});
  517: 
  518:     # possible FIXMEs
  519:     # - significant time is spent calling non-safe space routine
  520:     #   from safe space
  521:     # - early outs could be possible with classifying awards is to stratas
  522:     #   and stopping as so as hitting the top strata 
  523:     # - some early outs also might be possible with check ing the 
  524:     #   memoized hash of results (is correct even possible? etc.)
  525: 
  526:     my (@final_awards,@final_msg);
  527:     while( &get_permutations_left() ) {
  528: 	my $order = &get_next_permutation();
  529: 	my (@awards, @msgs, $i);
  530: 	foreach my $thisanswer (@{ $LONCAPA::CAPAresponse_answer->{'answers'} }) {
  531: 	    my $key = "$thisanswer\0".$responses->[$order->[$i]];
  532: 	    push(@awards,$memoized{$key}[0]);
  533: 	    push(@msgs,$memoized{$key}[1]);
  534: 	    $i++;
  535: 
  536: 	}
  537: 	&LONCAPA_INTERNAL_DEBUG(" all awards ".join(':',@awards));
  538: 
  539: 	my ($possible_award,$possible_msg) = 
  540: 	    &LONCAPA_INTERNAL_FINALIZEAWARDS(\@awards,\@msgs);
  541: 	&LONCAPA_INTERNAL_DEBUG(" pos awards ".$possible_award);
  542: 	push(@final_awards,$possible_award);
  543: 	push(@final_msg,$possible_msg);
  544:     }
  545: 
  546:     &LONCAPA_INTERNAL_DEBUG(" all final_awards ".join(':',@final_awards));
  547:     my ($final_award,$final_msg) = 
  548: 	&LONCAPA_INTERNAL_FINALIZEAWARDS(\@final_awards,\@final_msg,undef,1);
  549:     return ($final_award,$final_msg,$error,$control_chars_removed,$ansstring);
  550: }
  551: 
  552: sub verify_stringresponse {
  553:     my ($type,$award,$resp,$ans) = @_;
  554:     return if ($award eq 'EXACT_ANS');
  555:     my $error;
  556:     if ($resp =~ /^\s|\s$/) {
  557:         $resp =~ s{^\s+|\s+$}{}g;
  558:     }
  559:     if ($ans =~ /^\s|\s$/) {
  560:         $ans =~ s{^\s+|\s+$}{}g;
  561:     }
  562:     if ($type eq 'ci') {
  563:         $resp = lc($resp);
  564:         $ans = lc($ans);
  565:     }
  566:     if ($resp eq $ans) {
  567:         if ($award eq 'INCORRECT') {
  568:             $error = 'MISGRADED';
  569:         }
  570:     }
  571:     return $error;
  572: }
  573: 
  574: sub cas {
  575:     my ($system,$input,$library)=@_;
  576:     my $output;
  577:     my $dump;
  578:     if ($system eq 'maxima') {
  579:        $output=&maxima_eval($input,$library);
  580:     } elsif ($system eq 'R') {
  581:        ($output,$dump)=&r_eval($input,$library,0);
  582:     } else {
  583:        $output='Error: unrecognized CAS';
  584:     }
  585:     return $output;
  586: }
  587: 
  588: sub cas_hashref {
  589:     my ($system,$input,$library)=@_;
  590:     if ($system eq 'maxima') {
  591:        return 'Error: unsupported CAS';
  592:     } elsif ($system eq 'R') {
  593:        return &r_eval($input,$library,1);
  594:     } else {
  595:        return 'Error: unrecognized CAS';
  596:     }
  597: }
  598: 
  599: #
  600: # cas_hashref_entry takes a list of indices and gets the entry in a hash generated by Rreturn.
  601: # Call: cas_hashref_entry(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
  602: # Rentry will return the first scalar value it encounters (ignoring excess indices).
  603: # If an invalid key is given, it returns undef.
  604: #
  605: sub cas_hashref_entry {
  606:     return &Rentry(@_);
  607: }
  608: 
  609: #
  610: # cas_hashref_array takes a list of indices and gets a column array from a hash generated by Rreturn.
  611: # Call: cas_hashref_array(Rvalue, index1, index2, ...) where Rvalue is a hash returned by Rreturn.
  612: # If an invalid key is given, it returns undef.
  613: #
  614: sub cas_hashref_array {
  615:     return &Rarray(@_);
  616: }
  617: 
  618: sub tex {
  619:     if ( $external::target eq "tex" ) {
  620: 	return $_[0];
  621:     } else {
  622: 	return $_[1];
  623:     }
  624: }
  625: 
  626: sub var_in_tex {
  627:     if ( $external::target eq "tex" ) {
  628: 	return $_[0];
  629:     } else {
  630: 	return "";
  631:     }
  632: }
  633: 
  634: sub web {
  635:     if ( $external::target eq "tex" ) {
  636: 	return $_[1];
  637:     } else {
  638: 	if ( $external::target eq "web" || $external::target eq "answer") {
  639: 	    return $_[2];
  640: 	} else {
  641: 	    return $_[0];
  642: 	}
  643:     }
  644: }
  645: 
  646: sub html {
  647:     if ( $external::target eq "web" ) {
  648: 	return shift;
  649:     }
  650: }
  651: 
  652: sub hinton {
  653:     return 0;
  654: }
  655: 
  656: sub random {
  657:     my ($start,$end,$step)=@_;
  658:     if ( ! $hidden::RANDOMINIT ) {
  659:         if ($external::randomseed == 0) { $external::randomseed=1; }
  660:         if ($external::randomseed =~/,/) {
  661:             my ($num1,$num2) = map { abs($_); } split(/,/,$external::randomseed);
  662:             if ((!$num1) || ($num1 > 2147483398)) {
  663:                 &random_set_seed_from_phrase($external::randomseed);
  664:             } else {
  665:                 &random_set_seed(1,$num1);
  666:             }
  667:         } elsif ($external::randomseed =~/:/) {
  668:             my ($num1,$num2) = map { abs($_); } split(/:/,$external::randomseed);
  669:             if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
  670:                 &random_set_seed_from_phrase($external::randomseed);
  671:             } else {
  672:                 &random_set_seed($num1,$num2);
  673:             }
  674:         } else {
  675:             my $num1 = int(abs($external::randomseed));
  676:             if ((!$num1) || ($num1 > 2147483398)) {
  677:                 &random_set_seed_from_phrase($external::randomseed);
  678:             } else {
  679:                 &random_set_seed(1,$num1);
  680:             }
  681:         }
  682: 	&math_random_uniform();
  683: 	$hidden::RANDOMINIT=1;
  684:     }
  685:     if (!defined($step)) { $step=1; }
  686:     my $num=1+int(($end-$start)/$step);
  687:     my $result=$start + int(&math_random_uniform() * $num)*$step;
  688:     return $result;
  689: }
  690: 
  691: sub random_normal {
  692:     my ($item_cnt,$seed,$av,$std_dev) = @_;
  693:     my @oldseed=&random_get_seed();
  694:     my @retArray;
  695:     &random_set_seed_from_phrase($seed);
  696:     @retArray=&math_random_normal($item_cnt,$av,$std_dev);
  697:     &random_set_seed(@oldseed);
  698:     return @retArray;
  699: }
  700: 
  701: sub random_beta {
  702:     my ($item_cnt,$seed,$aa,$bb) = @_;
  703:     my @oldseed=&random_get_seed();
  704:     my @retArray;
  705:     &random_set_seed_from_phrase($seed);
  706:     @retArray=&math_random_beta($item_cnt,$aa,$bb);
  707:     &random_set_seed(@oldseed);
  708:     return @retArray;
  709: }
  710: 
  711: sub random_gamma {
  712:     my ($item_cnt,$seed,$a,$r) = @_;
  713:     my @oldseed=&random_get_seed();
  714:     my @retArray;
  715:     &random_set_seed_from_phrase($seed);
  716:     @retArray=&math_random_gamma($item_cnt,$a,$r);
  717:     &random_set_seed(@oldseed);
  718:     return @retArray;
  719: }
  720: 
  721: sub random_exponential {
  722:     my ($item_cnt,$seed,$av) = @_;
  723:     my @oldseed=&random_get_seed();
  724:     my @retArray;
  725:     &random_set_seed_from_phrase($seed);
  726:     @retArray=&math_random_exponential($item_cnt,$av);
  727:     &random_set_seed(@oldseed);
  728:     return @retArray;
  729: }
  730: 
  731: sub random_poisson {
  732:     my ($item_cnt,$seed,$mu) = @_;
  733:     my @oldseed=&random_get_seed();
  734:     my @retArray;
  735:     &random_set_seed_from_phrase($seed);
  736:     @retArray=&math_random_poisson($item_cnt,$mu);
  737:     &random_set_seed(@oldseed);
  738:     return @retArray;
  739: }
  740: 
  741: sub random_chi {
  742:     my ($item_cnt,$seed,$df) = @_;
  743:     my @oldseed=&random_get_seed();
  744:     my @retArray;
  745:     &random_set_seed_from_phrase($seed);
  746:     @retArray=&math_random_chi_square($item_cnt,$df);
  747:     &random_set_seed(@oldseed);
  748:     return @retArray;
  749: }
  750: 
  751: sub random_noncentral_chi {
  752:     my ($item_cnt,$seed,$df,$nonc) = @_;
  753:     my @oldseed=&random_get_seed();
  754:     my @retArray;
  755:     &random_set_seed_from_phrase($seed);
  756:     @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
  757:     &random_set_seed(@oldseed);
  758:     return @retArray;
  759: }
  760: 
  761: sub random_f {
  762:     my ($item_cnt,$seed,$dfn,$dfd) = @_;
  763:     my @oldseed=&random_get_seed();
  764:     my @retArray;
  765:     &random_set_seed_from_phrase($seed);
  766:     @retArray=&math_random_f($item_cnt,$dfn,$dfd);
  767:     &random_set_seed(@oldseed);
  768:     return @retArray;
  769: }
  770: 
  771: sub random_noncentral_f {
  772:     my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
  773:     my @oldseed=&random_get_seed();
  774:     my @retArray;
  775:     &random_set_seed_from_phrase($seed);
  776:     @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
  777:     &random_set_seed(@oldseed);
  778:     return @retArray;
  779: }
  780: 
  781: sub random_multivariate_normal {
  782:     my ($item_cnt,$seed,$mean,$covar) = @_;
  783:     my @oldseed=&random_get_seed();
  784:     &random_set_seed_from_phrase($seed);
  785:     my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
  786:     &random_set_seed(@oldseed);
  787:     return @retArray;
  788: }
  789: 
  790: sub random_multinomial {
  791:     my ($item_cnt,$seed,@p) = @_;
  792:     my @oldseed=&random_get_seed();
  793:     my @retArray;
  794:     &random_set_seed_from_phrase($seed);
  795:     my @retArray=&math_random_multinomial($item_cnt,@p);
  796:     &random_set_seed(@oldseed);
  797:     return @retArray;
  798: }
  799: 
  800: sub random_permutation {
  801:     my ($seed,@inArray) = @_;
  802:     my @oldseed=&random_get_seed();
  803:     my @retArray;
  804:     &random_set_seed_from_phrase($seed);
  805:     @retArray=&math_random_permutation(@inArray);
  806:     &random_set_seed(@oldseed);
  807:     return @retArray;
  808: }
  809: 
  810: sub random_uniform {
  811:     my ($item_cnt,$seed,$low,$high) = @_;
  812:     my @oldseed=&random_get_seed();
  813:     my @retArray;
  814:     &random_set_seed_from_phrase($seed);
  815:     @retArray=&math_random_uniform($item_cnt,$low,$high);
  816:     &random_set_seed(@oldseed);
  817:     return @retArray;
  818: }
  819: 
  820: sub random_uniform_integer {
  821:     my ($item_cnt,$seed,$low,$high) = @_;
  822:     my @oldseed=&random_get_seed();
  823:     my @retArray;
  824:     &random_set_seed_from_phrase($seed);
  825:     @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
  826:     &random_set_seed(@oldseed);
  827:     return @retArray;
  828: }
  829: 
  830: sub random_binomial {
  831:     my ($item_cnt,$seed,$nt,$p) = @_;
  832:     my @oldseed=&random_get_seed();
  833:     my @retArray;
  834:     &random_set_seed_from_phrase($seed);
  835:     @retArray=&math_random_binomial($item_cnt,$nt,$p);
  836:     &random_set_seed(@oldseed);
  837:     return @retArray;
  838: }
  839: 
  840: sub random_negative_binomial {
  841:     my ($item_cnt,$seed,$ne,$p) = @_;
  842:     my @oldseed=&random_get_seed();
  843:     my @retArray;
  844:     &random_set_seed_from_phrase($seed);
  845:     @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
  846:     &random_set_seed(@oldseed);
  847:     return @retArray;
  848: }
  849: 
  850: sub abs { CORE::abs(shift) }
  851: sub sin { CORE::sin(shift) }
  852: sub cos { CORE::cos(shift) }
  853: sub exp { CORE::exp(shift) }
  854: sub int { CORE::int(shift) }
  855: sub log { CORE::log(shift) }
  856: sub ln { CORE::log(shift) }
  857: sub atan2 { CORE::atan2($_[0],$_[1]) }
  858: sub sqrt { CORE::sqrt(shift) }
  859: 
  860: sub tan  { CORE::sin($_[0]) / CORE::cos($_[0]) }
  861: #sub atan { atan2($_[0], 1); }
  862: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
  863: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) );  }
  864: 
  865: sub log10 { CORE::log($_[0])/CORE::log(10); }
  866: 
  867: sub factorial {
  868:     my $input = CORE::int(shift);
  869:     return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
  870:     return "Error - factorial result is greater than system limit ($input)" if $input > 170;
  871:     return 1 if $input == 0;
  872:     my $result = 1; 
  873:     for (my $i=2; $i<=$input; $i++) { $result *= $i }
  874:     return $result;
  875: }
  876: 
  877: sub sgn {
  878:     return -1 if $_[0] < 0;
  879:     return 0 if $_[0] == 0;
  880:     return 1 if $_[0] > 0;
  881: }
  882: 
  883: sub min {
  884:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  885:     return shift @sorted;
  886: }
  887: 
  888: sub max {
  889:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  890:     return pop @sorted;
  891: }
  892: 
  893: sub roundto {
  894:     my ($input,$n) = @_;
  895:     return sprintf('%.'.$n.'f',$input);
  896: }
  897: 
  898: sub to_string {
  899:     my ($input,$n) = @_;
  900:     return sprintf($input) if $n eq "";
  901:     $n = '.'.$n if $n !~ /^\./;
  902:     return sprintf('%'.$n,$input) if $n ne "";
  903: }
  904: 
  905: sub sub_string {
  906:     my ($str,$start,$len) = @_;
  907:     return substr($str,$start-1,$len);
  908: }
  909: 
  910: sub pow   {return $_[0] ** $_[1]; }
  911: sub ceil  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
  912: sub floor  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
  913: #sub floor {return int($_[0]); }
  914: 
  915: sub format {
  916:     my ($value,$fmt)=@_;
  917:     my ($dollarmode,$commamode,$alwaysperiod,$options);
  918:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
  919:     #if ($options =~ /\$/) { $dollamode=1; }
  920:     #if ($options =~ /,/)  { $commamode=1; }
  921:     if ($options =~ /\./) { $alwaysperiod=1; }
  922:     my $result;
  923:     if ($fmt=~/s$/i) {
  924: 	$result=&format_significant_figures($value,$fmt);
  925:     } else {
  926: 	$fmt=~s/e/E/g;
  927: 	$result=sprintf('%.'.$fmt,$value);
  928: 	if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
  929: 	$result=~s/(E[+-]*)0/$1/;
  930:     }
  931:     #if ($dollarmode) {$result=&dollarformat($result);}
  932:     #if ($commamode) {$result=&commaformat($result);}
  933:     return $result;
  934: }
  935: 
  936: sub chemparse {
  937:     my ($reaction) = @_;
  938:     my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
  939:     my $formula = '';
  940:     foreach my $token (@tokens) {
  941: 	if ($token eq '->' ) {
  942:             if ($external::target eq 'web') {
  943:                 $formula .= '&rarr; ';
  944:             } else {
  945:                 $formula .= '<m>\ensuremath{\rightarrow}</m> ';
  946: 	    }
  947: 	    next;
  948: 	}
  949: 	if ($token eq '<-' ) {
  950:             if ($external::target eq 'web') {
  951:                 $formula .= '&larr; ';
  952:             } else {
  953:                 $formula .= '<m>\ensuremath{\leftarrow}</m> ';
  954: 	    }
  955: 	    next;
  956: 	}  
  957: 	if ($token eq '<=>') {
  958: 	    if ($external::target eq 'web' &&
  959: 		&EXT('request.browser.unicode')) {
  960: 		$formula .= '&#8652; ';
  961: 	    } else {
  962: 		$formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
  963: 				 '&lt;=&gt; ');
  964: 	    }
  965: 	    next;
  966: 	}
  967: 	if ($token eq '.') {
  968: 	  $formula =~ s/(\&nbsp\;| )$//;
  969: 	  $formula .= '&middot;';
  970: 	  next;
  971: 	}
  972: 	$token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
  973:         $formula .= $1 if ($1 ne '1');  # stoichiometric coefficient
  974: 	
  975: 	my $molecule = $2;
  976: 	# subscripts
  977: 	$molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
  978: 	# superscripts
  979: 	$molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
  980: 	# strip whitespace
  981: 	$molecule =~ s/\s*//g;
  982: 	# forced space
  983: 	$molecule =~ s/_/ /g;
  984: 	$molecule =~ s/-/&minus;/g;
  985: 	$formula .= $molecule.'&nbsp;';
  986:     }
  987:     # get rid of trailing space
  988:     $formula =~ s/(\&nbsp\;| )$//;
  989:     return &xmlparse($formula);
  990: }
  991: 
  992: sub conv_eng_format {
  993:     my ($ans,$baseunit)=@_;
  994:     my ($value,$answer,$unit);
  995:     $baseunit =~ s{[^\w/\-\.]}{}g; 
  996:     eval {
  997:            $value = &number_format_pref($ans);
  998:     };
  999:     my ($answer,$prefix) = ($value=~ /^(.+)(\w)$/);
 1000:     my $unit = $prefix.$baseunit;
 1001:     return($answer,$unit);
 1002: } 
 1003: 
 1004: sub prettyprint {
 1005:     my ($value,$fmt,$target)=@_;
 1006:     my $result;
 1007:     if (!$target) { $target = $external::target; }
 1008:     if ($fmt =~ /chem/i) { return(&chemparse($value)); }
 1009:     my ($dollarmode,$commamode,$alwaysperiod,$options);
 1010:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
 1011:     if ($options =~ /\$/) { $dollarmode=1; }
 1012:     if ($options =~ /,/)  { $commamode=1; }
 1013:     if ($options =~ /\./) { $alwaysperiod=1; }
 1014:     if ($fmt=~/s$/i) {
 1015: 	$value=&format_significant_figures($value,$fmt);
 1016:     } elsif ($fmt) {
 1017: 	$value=sprintf('%.'.$fmt,$value);
 1018:     }
 1019:     if ($alwaysperiod && $fmt eq '0f') {
 1020: 	if ($target eq 'tex') {
 1021: 	    $value .='\\ensuremath{.}';
 1022: 	} else {
 1023: 	    $value .='.';
 1024: 	}
 1025:     }
 1026:     if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
 1027: 	my $frac=$1;
 1028: 	if ($dollarmode) { $frac=&dollarformat($frac); }
 1029: 	if ($commamode) { $frac=&commaformat($frac); }
 1030: 	my $exponent=$2;
 1031: 	$exponent=~s/^\+0*//;
 1032: 	$exponent=~s/^-0*/-/;
 1033: 	$exponent=~s/^-0*/-/;
 1034: 	if ($exponent eq '-') { undef($exponent); }
 1035: 	if ($exponent) {
 1036: 	    if ($target eq 'web') {
 1037: 		$result=$frac.'&#215;10<sup>'.$exponent.'</sup>';
 1038: 	    } elsif ($target eq 'tex') {
 1039: 		$result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
 1040: 	    } else {
 1041: 		$result=$value;
 1042: 	    }
 1043: 	} else {
 1044: 	    $result=$frac;
 1045: 	}
 1046:     } else {
 1047: 	$result=$value;
 1048: 	if    ($dollarmode) { $result=&dollarformat($result,$target); }
 1049: 	elsif ($commamode)  { $result=&commaformat($result,$target); }
 1050:     }
 1051:     return $result;
 1052: }
 1053: 
 1054: sub commaformat {
 1055:     my ($number,$target) = @_;
 1056:     if ($number =~ /\./) {
 1057: 	while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
 1058: 	    $number = $1.$2.','.$3.$4;
 1059: 	}
 1060:     } else {
 1061: 	while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
 1062: 	    $number = $1.$2.','.$3.$4;
 1063: 	}
 1064:     }
 1065:     return $number;
 1066: }
 1067: 
 1068: sub dollarformat {
 1069:     my ($number,$target) = @_;
 1070:     if (!$target) { $target = $external::target; }
 1071:     $number=&commaformat($number,$target);
 1072:     if ($target eq 'tex') {
 1073: 	$number='\$'.$number; #' stupid emacs
 1074:     } else {
 1075: 	$number='$'.$number; #' stupid emacs
 1076:     }
 1077:     return $number; 
 1078: }
 1079: 
 1080: # format of form ns or nS where n is an integer
 1081: sub format_significant_figures {
 1082:     my ($number,$format) = @_; 
 1083:     return '0' if ($number == 0);
 1084:     # extract number of significant figures needed
 1085:     my ($sig) = ($format =~ /(\d+)s/i);
 1086:     # arbitrary choice - suggestions ?? or throw error message?
 1087:     $sig = 3 if ($sig eq '');
 1088:     # save the minus sign
 1089:     my $sign = ($number < 0) ? '-' : '';
 1090:     $number = abs($number);
 1091:     # needed to correct for a number greater than 1 (or
 1092:     my $power = ($number < 1) ? 0 : 1;
 1093:     # could round up. Take the integer part of log10.
 1094:     my $x10 = int(log($number)/log(10));
 1095:     # find number with values left of decimal pt = # of sign figs.
 1096:     my $xsig = $number*10**($sig-$x10-$power);
 1097:     # get just digits left of decimal pt - also rounds off correctly
 1098:     my $xint  = sprintf('%.0f',$xsig);
 1099:     # save any trailing zero's
 1100:     my ($zeros) = ($xint =~ /(0+)$/);
 1101:     # return number to original magnitude
 1102:     my $numSig = $xint*10**($x10-$sig+$power);
 1103:     if ($numSig =~ /^(\d+)\.(\d+)/) {
 1104:         # insert trailing zero's if have decimal point
 1105:         my @digarray = split('',$1.$2);
 1106:         my $sigcount;
 1107:         while (@digarray > 0) {
 1108:             my $item = shift(@digarray);
 1109:             if ($item) {
 1110:                 $sigcount = 1 + @digarray;
 1111:                 last;
 1112:             }
 1113:         }
 1114:         if (($sigcount) && ($sig >= $sigcount)) {
 1115:             $zeros = substr($zeros,0,($sig - $sigcount));
 1116:         }
 1117:         $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
 1118:     } else {
 1119:         if ($numSig =~ /^(\d+)e([\+\-]\d+)$/i) {
 1120:             my $pre_exp = $1;
 1121:             my $exponent = $2;
 1122:             $numSig = $pre_exp.'.'.$zeros.'E'.$exponent;
 1123:         } elsif ($numSig =~ /0$/) {
 1124:             # add decimal pt for number ending with 0 and length == # of sig figs
 1125:             if (length($numSig) == $sig) {
 1126:                 $numSig.='.';
 1127:             } elsif (length($numSig) > $sig) {
 1128:                 # exponential form for number ending with 0 and length > # of sig figs
 1129:                 my $fmtsig = $sig-1;
 1130:                 if ($fmtsig) {
 1131:                     $numSig = sprintf('%.'.$fmtsig.'E',$numSig);
 1132:                 }
 1133:             } elsif (length($numSig) < $sig) {
 1134:                 $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
 1135:             }
 1136:         } else {
 1137:             if (length($numSig) < $sig) {
 1138:                 $numSig.='.'.substr($zeros,0,($sig-length($numSig)));
 1139:             }
 1140:         }
 1141:     }
 1142:     # return number with sign
 1143:     return $sign.$numSig;
 1144: }
 1145: 
 1146: sub map {
 1147:     my ($phrase,$dest,$source)=@_;
 1148:     my @oldseed=&random_get_seed();
 1149:     my @seed = &random_seed_from_phrase($phrase);
 1150:     &random_set_seed(@seed);
 1151:     my $destct = scalar(@$dest);
 1152:     if (!$source) {
 1153: 	my @output;
 1154: 	my @idx = &math_random_permuted_index($destct);
 1155: 	my $ctr = 0;
 1156: 	while ($ctr < $destct) {
 1157: 	    $output[$ctr] = $$dest[$idx[$ctr]];
 1158: 	    $ctr++;
 1159: 	}
 1160:         &random_set_seed(@oldseed);
 1161: 	return @output;
 1162:     } else {
 1163: 	my $num = scalar(@$source);
 1164: 	my @idx = &math_random_permuted_index($num);
 1165: 	my $ctr = 0;
 1166: 	my $tot = $num;
 1167: 	$tot = $destct if $destct < $num;
 1168: 	if (ref($$dest[0])) {
 1169: 	    while ($ctr < $tot) {
 1170: 		${$$dest[$ctr]} = $$source[$idx[$ctr]];
 1171: 	        $ctr++;
 1172:             }
 1173:         } else {
 1174: 	    while ($ctr < $tot) {
 1175: 		$$dest[$ctr] = $$source[$idx[$ctr]];
 1176: 		$ctr++;
 1177: 	    }
 1178: 	}
 1179:     }
 1180:     &random_set_seed(@oldseed);
 1181:     return '';
 1182: }
 1183: 
 1184: sub rmap {
 1185:     my ($phrase,$dest,$source)=@_;
 1186:     my @oldseed=&random_get_seed();
 1187:     my @seed = &random_seed_from_phrase($phrase);
 1188:     &random_set_seed(@seed);
 1189:     my $destct = scalar(@$dest);
 1190:     if (!$source) {
 1191: 	my @idx = &math_random_permuted_index($destct);
 1192: 	my $ctr = 0;
 1193: 	my @r_idx;
 1194: 	while ($ctr < $destct) {
 1195: 	    $r_idx[$idx[$ctr]] = $ctr;
 1196: 	    $ctr++;
 1197: 	}
 1198: 	my @output;
 1199: 	$ctr = 0;
 1200: 	while ($ctr < $destct) {
 1201: 	    $output[$ctr] = $$dest[$r_idx[$ctr]];
 1202: 	    $ctr++;
 1203: 	}
 1204:         &random_set_seed(@oldseed);
 1205: 	return @output;
 1206:     } else {
 1207: 	my $num = scalar(@$source);
 1208: 	my @idx = &math_random_permuted_index($num);
 1209: 	my $ctr = 0;
 1210: 	my $tot = $num;
 1211: 	$tot = $destct if $destct < $num;
 1212: 	my @r_idx;
 1213: 	while ($ctr < $tot) {
 1214: 	    $r_idx[$idx[$ctr]] = $ctr;
 1215: 	    $ctr++;
 1216: 	}
 1217: 	$ctr = 0;
 1218: 	if (ref($$dest[0])) {
 1219: 	    while ($ctr < $tot) {
 1220: 		${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
 1221: 	        $ctr++;
 1222:             }
 1223:         } else {
 1224: 	    while ($ctr < $tot) {
 1225: 		$$dest[$ctr] = $$source[$r_idx[$ctr]];
 1226: 		$ctr++;
 1227: 	    }
 1228: 	}
 1229:     }
 1230:     &random_set_seed(@oldseed);
 1231:     return '';
 1232: }
 1233: 
 1234: sub capa_id { return }
 1235: 
 1236: sub problem { return }
 1237: 
 1238: sub name{
 1239:     my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
 1240:     $fullname = "" if $fullname eq ",  ";
 1241:     $fullname =~ s/\%2d/-/g;
 1242:     return $fullname;
 1243: }
 1244: 
 1245: sub student_number { 
 1246:     my $id = &EXT('environment.id');
 1247:     $id = '' if $id eq "";
 1248:     return $id;
 1249: }
 1250: 
 1251: sub class {
 1252:     my $course = &EXT('course.description');
 1253:     $course = '' if $course eq "";
 1254:     return $course;
 1255: }
 1256: 
 1257: sub classid {
 1258:     my $courseid = &EXT('request.course.id');
 1259:     $courseid = '' if $courseid eq "";
 1260:     return $courseid;
 1261: }
 1262: 
 1263: sub firstname {
 1264:     my $firstname = &EXT('environment.firstname');
 1265:     $firstname = '' if $firstname eq "";
 1266:     return $firstname;
 1267: }
 1268: 
 1269: sub middlename {
 1270:     my $middlename = &EXT('environment.middlename');
 1271:     $middlename = '' if $middlename eq "";
 1272:     return $middlename;
 1273: }
 1274: 
 1275: sub lastname {
 1276:     my $lastname = &EXT('environment.lastname');
 1277:     $lastname = '' if $lastname eq "";
 1278:     return $lastname;
 1279: }
 1280: 
 1281: sub sec { 
 1282:     my $sec = &EXT('request.course.sec');
 1283:     $sec = '' if $sec eq "";
 1284:     return $sec;
 1285: }
 1286: 
 1287: sub submission {
 1288:    my ($partid,$responseid,$subnumber,$encode,$cleanupnum,$mapalias)=@_;
 1289:    my $sub='';
 1290:    if ($subnumber) { $sub=$subnumber.':'; }
 1291:    my $output =
 1292:        &EXT('user.resource.'.$sub.'resource.'.$partid.'.'.$responseid.'.submission',$mapalias);
 1293:    if (ref($output) eq 'ARRAY') {
 1294:        my @items = @{$output};
 1295:        if ($encode) {
 1296:            @items = map { &encode_response($_); } @items;
 1297:        }
 1298:        if (ref($cleanupnum) eq 'HASH') {
 1299:            @items = map { &cleanup_numerical_response($cleanupnum,$_); } @items;
 1300:        }
 1301:        return \@items;
 1302:    } else {
 1303:        if ($encode) {
 1304:            $output = &encode_response($output);
 1305:        }
 1306:        if (ref($cleanupnum) eq 'HASH') {
 1307:            $output = &cleanup_numerical_response($cleanupnum,$output);
 1308:        }
 1309:        return $output;
 1310:    }
 1311: }
 1312: 
 1313: sub encode_response {
 1314:     my ($value) = @_;
 1315:     $value =~ s/&/&amp;/g;
 1316:     $value =~ s/</&lt;/g;
 1317:     $value =~ s/>/&gt;/g;
 1318:     $value =~ s/"/&quot;/g;
 1319:     return $value;
 1320: }
 1321: 
 1322: sub cleanup_numerical_response {
 1323:     my ($cleanupnum,$value) = @_;
 1324:     if (ref($cleanupnum) eq 'HASH') {
 1325:         if ($cleanupnum->{exponent}) {
 1326:             if ($value =~ m{^(.*)[\*xX]\s*10\s*\^\s*(\+|\-)?\s*(\d+)(.*)$}) {
 1327:                 my $pre_exp = $1;
 1328:                 my $sign = $2;
 1329:                 my $exponent = $3;
 1330:                 my $post_exp = $4;
 1331:                 if ($pre_exp !~ /\./) {
 1332:                     $pre_exp .= '.';
 1333:                 }
 1334:                 if ($sign eq '') {
 1335:                     $sign = '+';
 1336:                 }
 1337:                 $value = $pre_exp.'E'.$sign.$exponent.$post_exp;
 1338:             }
 1339:         }
 1340:         if ($cleanupnum->{comma}) {
 1341:             $value =~ s{(\d+),(\d+)}{$1$2};
 1342:         }
 1343:         if ($cleanupnum->{letterforzero}) {
 1344:             $value =~ s/^\s*o(\.\d+)/0$1/i;
 1345:         }
 1346:         if ($cleanupnum->{spaces}) {
 1347:             $value =~ s{^\s+|\s+$}{}g;
 1348:             if ($value =~ m{^(.*)\.\s+(\d+)(.*)$}) {
 1349:                 my $pre_pt = $1;
 1350:                 my $decimal = $2;
 1351:                 my $post_dec = $3;
 1352:                 $value = $pre_pt.'.'.$decimal.$post_dec;
 1353:             }
 1354:         }
 1355:         if ($cleanupnum->{format} =~ /^\d+s$/i) {
 1356:             $value = &format_significant_figures($value,$cleanupnum->{format});
 1357:         }
 1358:     }
 1359:     return $value;
 1360: }
 1361: 
 1362: sub currentpart {
 1363:    return $external::part;
 1364: }
 1365: 
 1366: sub eval_time {
 1367:    my ($timestamp)=@_;
 1368:    unless ($timestamp) { return ''; }
 1369:    return &locallocaltime($timestamp);
 1370: }
 1371: 
 1372: sub open_date { 
 1373:     my ($partid)=@_;
 1374:     unless ($partid) { $partid=0; }
 1375:     return &eval_time(&EXT('resource.'.$partid.'.opendate'));
 1376: }
 1377: 
 1378: sub due_date {
 1379:     my ($partid)=@_;
 1380:     unless ($partid) { $partid=0; } 
 1381:     return &eval_time(&EXT('resource.'.$partid.'.duedate'));
 1382: }
 1383: 
 1384: sub answer_date { 
 1385:     my ($partid)=@_;
 1386:     unless ($partid) { $partid=0; }
 1387:     return &eval_time(&EXT('resource.'.$partid.'.answerdate'));
 1388: }
 1389: 
 1390: sub open_date_epoch {
 1391:     my ($partid)=@_;
 1392:     unless ($partid) { $partid=0; }
 1393:     return &EXT('resource.'.$partid.'.opendate');
 1394: }
 1395: 
 1396: sub due_date_epoch {
 1397:     my ($partid)=@_;
 1398:     unless ($partid) { $partid=0; }
 1399:     return &EXT('resource.'.$partid.'.duedate');
 1400: }
 1401: 
 1402: sub answer_date_epoch {
 1403:     my ($partid)=@_;
 1404:     unless ($partid) { $partid=0; }
 1405:     return &EXT('resource.'.$partid.'.answerdate');
 1406: }
 1407: 
 1408: sub parameter_setting {
 1409:     my ($which,$partid)=@_;
 1410:     unless ($partid) { $partid=0; }
 1411:     return &EXT('resource.'.$partid.'.'.$which);
 1412: }
 1413: 
 1414: sub stored_data {
 1415:     my ($which,$partid)=@_;
 1416:     unless ($partid) { $partid=0; }
 1417:     return &EXT('user.resource.resource.'.$partid.'.'.$which);
 1418: }
 1419: 
 1420: sub wrong_bubbles {
 1421:     my ($correct,$lower,$upper,$step,@given)=@_;
 1422:     my @array=();
 1423:     my %hash=();
 1424:     foreach my $new (@given) {
 1425:         $hash{$new}=1;
 1426:     }
 1427:     my $num=int(&parameter_setting('numbubbles',&currentpart()));
 1428:     unless ($num) { $num=8; }
 1429:     if ($num>1) {
 1430:         for (my $i=0;$i<=500;$i++) {
 1431:             my $new=&random($lower,$upper,$step);
 1432:             if ($hash{$new}) { next; }
 1433:             if (abs($new-$correct)<$step) { next; }
 1434:             $hash{$new}=1;
 1435:             @array=keys(%hash);
 1436:             if ($#array+2>=$num) { last; }
 1437:         }
 1438:     }
 1439:     return @array;
 1440: }
 1441: 
 1442: sub array_moments {
 1443:     my @input=@_;
 1444:     my (@output,$N);
 1445:     $N=scalar (@input);
 1446:     $output[0]=$N;
 1447:     if ($N <= 1) {
 1448: 	$output[1]=$input[0];
 1449: 	$output[1]="Input array not defined" if ($N == 0);
 1450: 	$output[2]="variance undefined for N<=1";
 1451: 	$output[3]="skewness undefined for N<=1";
 1452: 	$output[4]="kurtosis undefined for N<=1";
 1453: 	return @output;
 1454:     }
 1455:     my $sum=0;
 1456:     foreach my $line (@input) {
 1457: 	$sum+=$line;
 1458:     }
 1459:     $output[1] = $sum/$N;
 1460:     my ($x,$sdev,$var,$skew,$kurt) = 0;
 1461:     foreach my $line (@input) {
 1462: 	$x=$line-$output[1];
 1463: 	$var+=$x**2;
 1464: 	$skew+=$x**3;
 1465: 	$kurt+=$x**4;
 1466:     }
 1467:     $output[2]=$var/($N-1);
 1468:     $sdev=CORE::sqrt($output[2]);
 1469:     if ($sdev == 0) {
 1470: 	$output[3]="inf-variance=0";
 1471: 	$output[4]="inf-variance=0";
 1472: 	return @output;
 1473:     }
 1474:     $output[3]=$skew/($sdev**3*$N);
 1475:     $output[4]=$kurt/($sdev**4*$N)-3;
 1476:     return @output;
 1477: }
 1478: 
 1479: sub choose {
 1480:     my $num = $_[0];
 1481:     return $_[$num];
 1482: }
 1483: 
 1484: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
 1485: #sub sum1 {
 1486: #    my ($start,$end,$sub)=@_;
 1487: #    my $sum=0;
 1488: #    for (my $i=$start;$i<=$end;$i++) {
 1489: #        $sum+=&$sub($i);
 1490: #    }
 1491: #    return $sum
 1492: #}
 1493: 
 1494: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
 1495: #sub sum2 {
 1496: #    my ($varname,$start,$end,$line)=@_;
 1497: #    my $sum=0;
 1498: #    for (my $i=$start;$i<=$end;$i++) {
 1499: #	my $func=sub {
 1500: #	    eval("\$".$varname."=$i");
 1501: #	    eval($line);
 1502: #	};
 1503: #        $sum+=&$func($i);
 1504: #    }
 1505: #    return $sum
 1506: #}
 1507: 
 1508: # expiremental idea
 1509: sub proper_path {
 1510:     my ($path)=@_;
 1511:     if ( $external::target eq "tex" ) {
 1512: 	return '/home/httpd/html'.$path;
 1513:     } else {
 1514: 	return $path;
 1515:     }
 1516: }
 1517: 
 1518: sub input_id {
 1519:     my ($part_id, $response_id, $textline_id) = @_;
 1520:     return 'HWVAL_'.$part_id.'_'.$response_id.'_'.$textline_id;
 1521: }
 1522: 

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