Annotation of loncom/homework/default_homework.lcpm, revision 1.172.2.1

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

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