File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.109: download - view: text, annotated - select for diffs
Wed Jul 5 19:01:44 2006 UTC (17 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: version_2_1_99_0, HEAD
- formula fixups should only be applied when it's a formula BUG#4910

    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.109 2006/07/05 19:01:44 albertel 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: 
   37: sub check_commas {
   38:     my ($response)=@_;
   39:     #print("$response ");
   40:     my @numbers=split(',',$response);
   41:     #print(" numbers ".join('-',@numbers)." ");
   42:     if (scalar(@numbers) > 1) {
   43:         #print(" numbers[0] ".$numbers[0]." "); 
   44: 	if (length($numbers[0]) > 3 || length($numbers[0]) == 0) { return -1; }
   45: 	shift(@numbers);
   46: 	#print(" numbers ".scalar(@numbers)." ");
   47: 	while (scalar(@numbers) > 1) {
   48: 	    #print(" numbers ".join('-',@numbers)." ");
   49: 	    if (length($numbers[0]) != 3) { return -2; }
   50: 	    shift(@numbers);
   51: 	}
   52: 	my ($number)=split('\.',$numbers[0]);
   53: 	#print(" number ".$number." ");
   54: 	#print(" numbers[0] ".$numbers[0]." ");
   55: 	if (length($number) != 3) { return -3; }
   56:     } else {
   57: 	my ($number)=split('\.',$numbers[0]);
   58: 	if (length($number) > 3) { return -4; }
   59:     }
   60:     return 1;
   61: }
   62: 
   63: sub caparesponse_check {
   64:     my ($answer,$response)=@_;
   65:     #not properly used yet: calc
   66:     #not to be used: $ans_fmt
   67:     my $type=$LONCAPA::CAPAresponse_args{'type'};
   68:     my $tol=$LONCAPA::CAPAresponse_args{'tol'};
   69:     my $sig=$LONCAPA::CAPAresponse_args{'sig'};
   70:     my $ans_fmt=$LONCAPA::CAPAresponse_args{'format'};
   71:     my $unit=$LONCAPA::CAPAresponse_args{'unit'};
   72:     my $calc=$LONCAPA::CAPAresponse_args{'calc'};
   73:     my $samples=$LONCAPA::CAPAresponse_args{'samples'};
   74:     
   75:     my $tol_type=''; # gets it's value from whether tol has a % or not done
   76:     my $sig_lbound=''; #done
   77:     my $sig_ubound=''; #done
   78: 
   79: 
   80:     #type's definitons come from capaParser.h
   81:     my $message='';
   82:     #remove leading and trailing whitespace
   83:     if (!defined($response)) {
   84: 	$response='';
   85:     }
   86:     if ($response=~ /^\s|\s$/) {
   87: 	$response=~ s:^\s+|\s+$::g;
   88: 	$message .="Removed ws now :$response:\n";
   89:     } else {
   90: 	$message .="no ws in :$response:\n";
   91:     }
   92:     &LONCAPA_INTERNAL_DEBUG(" type is $type ");
   93:     if ($type eq 'cs' || $type eq 'ci') {
   94: 	#for string answers make surec all places spaces occur, there is 
   95:         #really only 1 space, in both the answer and the response
   96: 	$answer=~s/ +/ /g;
   97: 	$response=~s/ +/ /g;
   98:     } elsif ($type eq 'mc') {
   99: 	$answer=~s/[\s,]//g;
  100: 	$response=~s/[\s,]//g;
  101:     }
  102:     if ($type eq 'float' && $unit=~/\$/) {
  103: 	if ($response!~/^\$/)  { return "NO_UNIT: Missing \$ "; }
  104: 	$response=~s/\$//g;
  105:     }
  106:     if ($type eq 'float' && $unit=~/\,/ && (&check_commas($response)<0)) {
  107: 	return "COMMA_FAIL:";
  108:     }
  109:     $ans_fmt=~s/\W//g;
  110:     $unit=~s/[\$,]//g;
  111:     if ($type eq 'float') { $response=~s/,//g; }
  112: 
  113:     if (length($response) > 500) { return "TOO_LONG: Answer too long"; }
  114: 
  115:     if ($type eq '' ) {
  116: 	$message .= "Didn't find a type :$type: defaulting\n";
  117: 	if ( $answer eq ($answer *1.0)) { $type = 2;
  118: 				      } else { $type = 3; }
  119:     } else {
  120: 	if    ($type eq 'cs')    { $type = 4; }
  121: 	elsif ($type eq 'ci')    { $type = 3 }
  122: 	elsif ($type eq 'mc')    { $type = 5; }
  123: 	elsif ($type eq 'fml')   { $type = 8; }
  124:         elsif ($type eq 'math')  { $type = 9; }
  125: 	elsif ($type eq 'subj')  { $type = 7; }
  126: 	elsif ($type eq 'float') { $type = 2; }
  127: 	elsif ($type eq 'int')   { $type = 1; }
  128: 	else { return "ERROR: Unknown type of answer: $type" }
  129:     }
  130: 
  131:     my $points;
  132:     my $id_list;
  133:     #formula type setup the sample points
  134:     if ($type eq '8') {
  135: 	($id_list,$points)=split(/@/,$samples);
  136: 	$message.="Found :$id_list:$points: points in $samples\n";
  137:     }
  138:     if ($tol eq '') {
  139: 	$tol=0.0;
  140: 	$tol_type=1; #TOL_ABSOLUTE
  141:     } else {
  142: 	if ($tol =~ /%$/) {
  143: 	    chop $tol;
  144: 	    $tol_type=2; #TOL_PERCENTAGE
  145: 	} else {
  146: 	    $tol_type=1; #TOL_ABSOLUTE
  147: 	}
  148:     }
  149: 
  150:     ($sig_ubound,$sig_lbound)=&LONCAPA_INTERNAL_get_sigrange($sig);
  151: 
  152:     my $reterror="";
  153:     my $result;
  154:     if ($type eq '9') {
  155:       $result = &maxima_check(&maxima_cas_formula_fix($response),&maxima_cas_formula_fix($answer),\$reterror);
  156:     } else {
  157: 	if ($type eq '8') { # fml type
  158: 	    $response = &capa_formula_fix($response);
  159: 	    $answer   = &capa_formula_fix($answer);
  160: 	}
  161:        $result = &caparesponse_capa_check_answer($response,$answer,$type,
  162: 						 $tol_type,$tol,
  163: 						 $sig_lbound,$sig_ubound,
  164: 						 $ans_fmt,$unit,$calc,$id_list,
  165: 						 $points,$external::randomseed,
  166: 						 \$reterror);
  167:     }
  168:     if    ($result == '1') { $result='EXACT_ANS'; } 
  169:     elsif ($result == '2') { $result='APPROX_ANS'; }
  170:     elsif ($result == '3') { $result='SIG_FAIL'; }
  171:     elsif ($result == '4') { $result='UNIT_FAIL'; }
  172:     elsif ($result == '5') { $result='NO_UNIT'; }
  173:     elsif ($result == '6') { $result='UNIT_OK'; }
  174:     elsif ($result == '7') { $result='INCORRECT'; }
  175:     elsif ($result == '8') { $result='UNIT_NOTNEEDED'; }
  176:     elsif ($result == '9') { $result='ANS_CNT_NOT_MATCH'; }
  177:     elsif ($result =='10') { $result='SUB_RECORDED'; }
  178:     elsif ($result =='11') { $result='BAD_FORMULA'; }
  179:     elsif ($result =='12' && !$response) { $result='MISSING_ANSWER'; }
  180:     elsif ($result =='12') { $result='WANTED_NUMERIC'; }
  181:     elsif ($result =='13') { $result='UNIT_INVALID_INSTRUCTOR'; }
  182:     elsif ($result =='141') { $result='UNIT_INVALID_STUDENT'; }
  183:     elsif ($result =='142') { $result='UNIT_INVALID_STUDENT'; }
  184:     elsif ($result =='143') { $result='UNIT_INVALID_STUDENT'; }
  185:     elsif ($result =='15') { $result='UNIT_IRRECONCIBLE'; }
  186:     else  {$result = "ERROR: Unknown Result:$result:$@:";}
  187: 
  188:     return ("$result:\nRetError $reterror:\nAnswer $answer:\nResponse $response:\n type-$type|$tol|$tol_type|$sig:$sig_lbound:$sig_ubound|$unit|\n$message",$reterror);
  189: }
  190: 
  191: sub maxima_cas_formula_fix {
  192:    my ($expression)=@_;
  193:    return &implicit_multiplication($expression);
  194: }
  195: 
  196: sub capa_formula_fix {
  197:    my ($expression)=@_;
  198:    return &implicit_multiplication($expression);
  199: }
  200: 
  201: sub implicit_multiplication {
  202:     my ($expression)=@_;
  203:     $expression=~s/\s+/\*/g;
  204:     $expression=~s/(\d)([a-zA-Z\(])/$1\*$2/g;
  205:     $expression=~s/\)(\w)/\)\*$1/g;
  206:     return $expression;
  207: }
  208: 
  209: sub caparesponse_check_list {
  210:     my $response=$LONCAPA::CAPAresponse_args{'response'};
  211:     my $result="Got response :".join(':',@LONCAPA::CAPAresponse_answer).":\n";
  212:     &LONCAPA_INTERNAL_DEBUG("args ".join(':',%LONCAPA::CAPAresponse_args));
  213:     my @responselist;
  214:     my $type = $LONCAPA::CAPAresponse_args{'type'};
  215:     $result.="Got type :$type:\n";
  216:     if ($type ne '' && $#LONCAPA::CAPAresponse_answer > 0) {
  217: 	(@responselist)=split(/,/,$response);
  218: 	if (@responselist < @LONCAPA::CAPAresponse_answer) {
  219: 	    return 'MISSING_ANSWER';
  220: 	}
  221: 	if (@responselist > @LONCAPA::CAPAresponse_answer) {
  222: 	    return 'EXTRA_ANSWER';
  223: 	}
  224:     } else {
  225: 	(@responselist)=($response);
  226:     }
  227:     $result.="Initial final response :$responselist['-1']:\n";
  228:     my $unit;
  229:     if ($type eq '' || $type eq 'float') {
  230: 	#for numerical problems split off the unit
  231: 	if ( $responselist['-1']=~ /(.*[^\s])\s+([^\s]+)/ ) {
  232: 	    $responselist['-1']=$1;
  233: 	    $unit=$2;
  234: 	}
  235:     }
  236:     $result.="Final final response :$responselist['-1']:$unit:\n";
  237:     $unit=~s/\s//;
  238: 
  239:     my ($awards, @msgs, $i);
  240:     foreach my $thisanswer (@LONCAPA::CAPAresponse_answer) {
  241: 	my ($msg,$aresult);
  242: 	$result.="trying answer :$thisanswer:\n";
  243: 	if (defined($thisanswer)) {
  244: 	    if ($unit eq '') {
  245: 		($aresult,$msg)=&caparesponse_check($thisanswer,
  246: 						    $responselist[$i]);
  247: 	    } else {
  248: 		($aresult,$msg)=&caparesponse_check($thisanswer,
  249: 						    $responselist[$i]." $unit");
  250: 	    }
  251: 	} else {
  252: 	    $aresult='ERROR';
  253: 	    $msg='answer was undefined';
  254: 	}
  255: 	&LONCAPA_INTERNAL_DEBUG("after if $aresult -- $msg");
  256: 	my ($temp)=split(/:/, $aresult);
  257: 	$awards.="$temp,";
  258: 	$result.=$aresult;
  259: 	push(@msgs,$msg);
  260: 	$i++;
  261:     }
  262:     chop($awards);
  263:     return ("$awards:\n$result",@msgs);
  264: }
  265: 
  266: sub tex {
  267:     if ( $external::target eq "tex" ) {
  268: 	return $_[0];
  269:     } else {
  270: 	return $_[1];
  271:     }
  272: }
  273: 
  274: sub var_in_tex {
  275:     if ( $external::target eq "tex" ) {
  276: 	return $_[0];
  277:     } else {
  278: 	return "";
  279:     }
  280: }
  281: 
  282: sub web {
  283:     if ( $external::target eq "tex" ) {
  284: 	return $_[1];
  285:     } else {
  286: 	if ( $external::target eq "web" || $external::target eq "answer") {
  287: 	    return $_[2];
  288: 	} else {
  289: 	    return $_[0];
  290: 	}
  291:     }
  292: }
  293: 
  294: sub html {
  295:     if ( $external::target eq "web" ) {
  296: 	return shift;
  297:     }
  298: }
  299: 
  300: sub hinton {
  301:     return 0;
  302: }
  303: 
  304: sub random {
  305:     my ($start,$end,$step)=@_;
  306:     if ( ! $hidden::RANDOMINIT ) {
  307: 	if ($external::randomseed == 0) { $external::randomseed=1; }
  308: 	if ($external::randomseed =~/,/) {
  309: 	    my ($num1,$num2)=split(/,/,$external::randomseed);
  310: 	    &random_set_seed(1,abs($num1));
  311: 	} elsif ($external::randomseed =~/:/) {
  312: 	    my ($num1,$num2)=split(/:/,$external::randomseed);
  313: 	    &random_set_seed(abs($num1),abs($num2));
  314: 	} else {
  315: 	    &random_set_seed(1,int(abs($external::randomseed)));
  316: 	}
  317: 	&math_random_uniform();
  318: 	$hidden::RANDOMINIT=1;
  319:     }
  320:     if (!defined($step)) { $step=1; }
  321:     my $num=1+int(($end-$start)/$step);
  322:     my $result=$start + int(&math_random_uniform() * $num)*$step;
  323:     return $result;
  324: }
  325: 
  326: sub random_normal {
  327:     my ($item_cnt,$seed,$av,$std_dev) = @_;
  328:     my @oldseed=&random_get_seed();
  329:     my @retArray;
  330:     &random_set_seed_from_phrase($seed);
  331:     @retArray=&math_random_normal($item_cnt,$av,$std_dev);
  332:     &random_set_seed(@oldseed);
  333:     return @retArray;
  334: }
  335: 
  336: sub random_beta {
  337:     my ($item_cnt,$seed,$aa,$bb) = @_;
  338:     my @oldseed=&random_get_seed();
  339:     my @retArray;
  340:     &random_set_seed_from_phrase($seed);
  341:     @retArray=&math_random_beta($item_cnt,$aa,$bb);
  342:     &random_set_seed(@oldseed);
  343:     return @retArray;
  344: }
  345: 
  346: sub random_gamma {
  347:     my ($item_cnt,$seed,$a,$r) = @_;
  348:     my @oldseed=&random_get_seed();
  349:     my @retArray;
  350:     &random_set_seed_from_phrase($seed);
  351:     @retArray=&math_random_gamma($item_cnt,$a,$r);
  352:     &random_set_seed(@oldseed);
  353:     return @retArray;
  354: }
  355: 
  356: sub random_exponential {
  357:     my ($item_cnt,$seed,$av) = @_;
  358:     my @oldseed=&random_get_seed();
  359:     my @retArray;
  360:     &random_set_seed_from_phrase($seed);
  361:     @retArray=&math_random_exponential($item_cnt,$av);
  362:     &random_set_seed(@oldseed);
  363:     return @retArray;
  364: }
  365: 
  366: sub random_poisson {
  367:     my ($item_cnt,$seed,$mu) = @_;
  368:     my @oldseed=&random_get_seed();
  369:     my @retArray;
  370:     &random_set_seed_from_phrase($seed);
  371:     @retArray=&math_random_poisson($item_cnt,$mu);
  372:     &random_set_seed(@oldseed);
  373:     return @retArray;
  374: }
  375: 
  376: sub random_chi {
  377:     my ($item_cnt,$seed,$df) = @_;
  378:     my @oldseed=&random_get_seed();
  379:     my @retArray;
  380:     &random_set_seed_from_phrase($seed);
  381:     @retArray=&math_random_chi_square($item_cnt,$df);
  382:     &random_set_seed(@oldseed);
  383:     return @retArray;
  384: }
  385: 
  386: sub random_noncentral_chi {
  387:     my ($item_cnt,$seed,$df,$nonc) = @_;
  388:     my @oldseed=&random_get_seed();
  389:     my @retArray;
  390:     &random_set_seed_from_phrase($seed);
  391:     @retArray=&math_random_noncentral_chi_square($item_cnt,$df,$nonc);
  392:     &random_set_seed(@oldseed);
  393:     return @retArray;
  394: }
  395: 
  396: sub random_f {
  397:     my ($item_cnt,$seed,$dfn,$dfd) = @_;
  398:     my @oldseed=&random_get_seed();
  399:     my @retArray;
  400:     &random_set_seed_from_phrase($seed);
  401:     @retArray=&math_random_f($item_cnt,$dfn,$dfd);
  402:     &random_set_seed(@oldseed);
  403:     return @retArray;
  404: }
  405: 
  406: sub random_noncentral_f {
  407:     my ($item_cnt,$seed,$dfn,$dfd,$nonc) = @_;
  408:     my @oldseed=&random_get_seed();
  409:     my @retArray;
  410:     &random_set_seed_from_phrase($seed);
  411:     @retArray=&math_random_noncentral_f($item_cnt,$dfn,$dfd,$nonc);
  412:     &random_set_seed(@oldseed);
  413:     return @retArray;
  414: }
  415: 
  416: sub random_multivariate_normal {
  417:     my ($item_cnt,$seed,$mean,$covar) = @_;
  418:     my @oldseed=&random_get_seed();
  419:     &random_set_seed_from_phrase($seed);
  420:     my @retArray=&math_random_multivariate_normal($item_cnt,@$mean,@$covar);
  421:     &random_set_seed(@oldseed);
  422:     return @retArray;
  423: }
  424: 
  425: sub random_multinomial {
  426:     my ($item_cnt,$seed,@p) = @_;
  427:     my @oldseed=&random_get_seed();
  428:     my @retArray;
  429:     &random_set_seed_from_phrase($seed);
  430:     my @retArray=&math_random_multinomial($item_cnt,@p);
  431:     &random_set_seed(@oldseed);
  432:     return @retArray;
  433: }
  434: 
  435: sub random_permutation {
  436:     my ($seed,@inArray) = @_;
  437:     my @oldseed=&random_get_seed();
  438:     my @retArray;
  439:     &random_set_seed_from_phrase($seed);
  440:     @retArray=&math_random_permutation(@inArray);
  441:     &random_set_seed(@oldseed);
  442:     return @retArray;
  443: }
  444: 
  445: sub random_uniform {
  446:     my ($item_cnt,$seed,$low,$high) = @_;
  447:     my @oldseed=&random_get_seed();
  448:     my @retArray;
  449:     &random_set_seed_from_phrase($seed);
  450:     @retArray=&math_random_uniform($item_cnt,$low,$high);
  451:     &random_set_seed(@oldseed);
  452:     return @retArray;
  453: }
  454: 
  455: sub random_uniform_integer {
  456:     my ($item_cnt,$seed,$low,$high) = @_;
  457:     my @oldseed=&random_get_seed();
  458:     my @retArray;
  459:     &random_set_seed_from_phrase($seed);
  460:     @retArray=&math_random_uniform_integer($item_cnt,$low,$high);
  461:     &random_set_seed(@oldseed);
  462:     return @retArray;
  463: }
  464: 
  465: sub random_binomial {
  466:     my ($item_cnt,$seed,$nt,$p) = @_;
  467:     my @oldseed=&random_get_seed();
  468:     my @retArray;
  469:     &random_set_seed_from_phrase($seed);
  470:     @retArray=&math_random_binomial($item_cnt,$nt,$p);
  471:     &random_set_seed(@oldseed);
  472:     return @retArray;
  473: }
  474: 
  475: sub random_negative_binomial {
  476:     my ($item_cnt,$seed,$ne,$p) = @_;
  477:     my @oldseed=&random_get_seed();
  478:     my @retArray;
  479:     &random_set_seed_from_phrase($seed);
  480:     @retArray=&math_random_negative_binomial($item_cnt,$ne,$p);
  481:     &random_set_seed(@oldseed);
  482:     return @retArray;
  483: }
  484: 
  485: sub abs { CORE::abs(shift) }
  486: sub sin { CORE::sin(shift) }
  487: sub cos { CORE::cos(shift) }
  488: sub exp { CORE::exp(shift) }
  489: sub int { CORE::int(shift) }
  490: sub log { CORE::log(shift) }
  491: sub atan2 { CORE::atan2($_[0],$_[1]) }
  492: sub sqrt { CORE::sqrt(shift) }
  493: 
  494: sub tan  { CORE::sin($_[0]) / CORE::cos($_[0]) }
  495: #sub atan { atan2($_[0], 1); }
  496: #sub acos { atan2(sqrt(1 - $_[0] * $_[0]), $_[0] ); }
  497: #sub asin { atan2($_[0], sqrt(1- $_[0] * $_[0]) );  }
  498: 
  499: sub log10 { CORE::log($_[0])/CORE::log(10); }
  500: 
  501: sub factorial {
  502:     my $input = CORE::int(shift);
  503:     return "Error - unable to take factorial of an negative number ($input)" if $input < 0;
  504:     return "Error - factorial result is greater than system limit ($input)" if $input > 170;
  505:     return 1 if $input == 0;
  506:     my $result = 1; 
  507:     for (my $i=2; $i<=$input; $i++) { $result *= $i }
  508:     return $result;
  509: }
  510: 
  511: sub sgn {
  512:     return -1 if $_[0] < 0;
  513:     return 0 if $_[0] == 0;
  514:     return 1 if $_[0] > 0;
  515: }
  516: 
  517: sub min {
  518:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  519:     return shift @sorted;
  520: }
  521: 
  522: sub max {
  523:     my @sorted = sort { $a <=> $b || $a cmp $b } @_;
  524:     return pop @sorted;
  525: }
  526: 
  527: sub roundto {
  528:     my ($input,$n) = @_;
  529:     return sprintf('%.'.$n.'f',$input);
  530: }
  531: 
  532: sub to_string {
  533:     my ($input,$n) = @_;
  534:     return sprintf($input) if $n eq "";
  535:     $n = '.'.$n if $n !~ /^\./;
  536:     return sprintf('%'.$n,$input) if $n ne "";
  537: }
  538: 
  539: sub sub_string {
  540:     my ($str,$start,$len) = @_;
  541:     return substr($str,$start-1,$len);
  542: }
  543: 
  544: sub pow   {return $_[0] ** $_[1]; }
  545: sub ceil  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? (CORE::int($_[0])+ 1) : CORE::int($_[0])); }
  546: sub floor  {return (($_[0]-CORE::int($_[0]))== 0.0) ? $_[0] : (($_[0] > 0) ? CORE::int($_[0]) : (CORE::int($_[0])-1)); }
  547: #sub floor {return int($_[0]); }
  548: 
  549: sub format {
  550:     my ($value,$fmt)=@_;
  551:     my ($dollarmode,$commamode,$alwaysperiod,$options);
  552:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
  553:     #if ($options =~ /\$/) { $dollamode=1; }
  554:     #if ($options =~ /,/)  { $commamode=1; }
  555:     if ($options =~ /\./) { $alwaysperiod=1; }
  556:     my $result;
  557:     if ($fmt=~/s$/i) {
  558: 	$result=&format_significant_figures($value,$fmt);
  559:     } else {
  560: 	$fmt=~s/e/E/g;
  561: 	$result=sprintf('%.'.$fmt,$value);
  562: 	if ($alwaysperiod && $fmt eq '0f') { $result .='.'; }
  563: 	$result=~s/(E[+-]*)0/$1/;
  564:     }
  565:     #if ($dollarmode) {$result=&dollarformat($result);}
  566:     #if ($commamode) {$result=&commaformat($result);}
  567:     return $result;
  568: }
  569: 
  570: sub chemparse {
  571:     my ($reaction) = @_;
  572:     my @tokens = split(/(\s\+|\->|<=>|<\-|\.)/,$reaction);
  573:     my $formula = '';
  574:     foreach my $token (@tokens) {
  575: 	if ($token eq '->' ) {
  576: 	    $formula .= '<m>\ensuremath{\rightarrow}</m> ';
  577: 	    next;
  578: 	}
  579: 	if ($token eq '<-' ) {
  580: 	    $formula .= '<m>\ensuremath{\leftarrow}</m> ';
  581: 	    next;
  582: 	}  
  583: 	if ($token eq '<=>') {
  584: 	    if ($external::target eq 'web' &&
  585: 		&EXT('request.browser.unicode')) {
  586: 		$formula .= '&#8652; ';
  587: 	    } else {
  588: 		$formula .= &web('<=> ','<m>\ensuremath{\rightleftharpoons}</m> ',
  589: 				 '&lt;=&gt; ');
  590: 	    }
  591: 	    next;
  592: 	}
  593: 	if ($token eq '.') {
  594: 	  $formula =~ s/(\&nbsp\;| )$//;
  595: 	  $formula .= '&middot;';
  596: 	  next;
  597: 	}
  598: 	$token =~ /^\s*([\d|\/]*(?:&frac\d\d)?)(.*)/;
  599:         $formula .= $1 if ($1 ne '1');  # stoichiometric coefficient
  600: 	
  601: 	my $molecule = $2;
  602: 	# subscripts
  603: 	$molecule =~ s|(?<=[a-zA-Z\)\]\s])(\d+)|<sub>$1</sub>|g;
  604: 	# superscripts
  605: 	$molecule =~ s|\^(\d*[+\-]*)|<sup>$1</sup>|g;
  606: 	# strip whitespace
  607: 	$molecule =~ s/\s*//g;
  608: 	# forced space
  609: 	$molecule =~ s/_/ /g;
  610: 	$molecule =~ s/-/&minus;/g;
  611: 	$formula .= $molecule.'&nbsp;';
  612:     }
  613:     # get rid of trailing space
  614:     $formula =~ s/(\&nbsp\;| )$//;
  615:     return &xmlparse($formula);
  616: }
  617: 
  618: sub prettyprint {
  619:     my ($value,$fmt,$target)=@_;
  620:     my $result;
  621:     if (!$target) { $target = $external::target; }
  622:     if ($fmt =~ /chem/i) { return(&chemparse($value)); }
  623:     my ($dollarmode,$commamode,$alwaysperiod,$options);
  624:     if ($fmt =~ /^([^\d]*)(.*)/) { $options=$1; $fmt=$2; } 
  625:     if ($options =~ /\$/) { $dollarmode=1; }
  626:     if ($options =~ /,/)  { $commamode=1; }
  627:     if ($options =~ /\./) { $alwaysperiod=1; }
  628:     if ($fmt=~/s$/i) {
  629: 	$value=&format_significant_figures($value,$fmt);
  630:     } elsif ($fmt) {
  631: 	$value=sprintf('%.'.$fmt,$value);
  632:     }
  633:     if ($alwaysperiod && $fmt eq '0f') {
  634: 	if ($target eq 'tex') {
  635: 	    $value .='\\ensuremath{.}';
  636: 	} else {
  637: 	    $value .='.';
  638: 	}
  639:     }
  640:     if ($value =~ /([0-9\.\-\+]+)E([0-9\-\+]+)/i ) {
  641: 	my $frac=$1;
  642: 	if ($dollarmode) { $frac=&dollarformat($frac); }
  643: 	if ($commamode) { $frac=&commaformat($frac); }
  644: 	my $exponent=$2;
  645: 	$exponent=~s/^\+0*//;
  646: 	$exponent=~s/^-0*/-/;
  647: 	$exponent=~s/^-0*/-/;
  648: 	if ($exponent eq '-') { undef($exponent); }
  649: 	if ($exponent) {
  650: 	    if ($target eq 'web') {
  651: 		$result=$frac.'&#215;10<sup>'.$exponent.'</sup>';
  652: 	    } elsif ($target eq 'tex') {
  653: 		$result='\ensuremath{'.$frac.'\times 10^{'.$exponent.'}}';
  654: 	    } else {
  655: 		$result=$value;
  656: 	    }
  657: 	} else {
  658: 	    $result=$frac;
  659: 	}
  660:     } else {
  661: 	$result=$value;
  662: 	if    ($dollarmode) { $result=&dollarformat($result,$target); }
  663: 	elsif ($commamode)  { $result=&commaformat($result,$target); }
  664:     }
  665:     return $result;
  666: }
  667: 
  668: sub commaformat {
  669:     my ($number,$target) = @_;
  670:     if ($number =~ /\./) {
  671: 	while ($number =~ /([^0-9]*)([0-9]+)([^\.,][^\.,][^\.,])([,0-9]*\.[0-9]*)$/) {
  672: 	    $number = $1.$2.','.$3.$4;
  673: 	}
  674:     } else {
  675: 	while ($number =~ /^([^0-9]*)([0-9]+)([^,][^,][^,])([,0-9]*)$/) {
  676: 	    $number = $1.$2.','.$3.$4;
  677: 	}
  678:     }
  679:     return $number;
  680: }
  681: 
  682: sub dollarformat {
  683:     my ($number,$target) = @_;
  684:     if (!$target) { $target = $external::target; }
  685:     $number=&commaformat($number,$target);
  686:     if ($target eq 'tex') {
  687: 	$number='\$'.$number; #' stupid emacs
  688:     } else {
  689: 	$number='$'.$number; #' stupid emacs
  690:     }
  691:     return $number; 
  692: }
  693: 
  694: # format of form ns or nS where n is an integer
  695: sub format_significant_figures {
  696:     my ($number,$format) = @_; 
  697:     return '0' if ($number == 0);
  698:     # extract number of significant figures needed
  699:     my ($sig) = ($format =~ /(\d+)s/i);
  700:     # arbitrary choice - suggestions ?? or throw error message?
  701:     $sig = 3 if ($sig eq '');
  702:     # save the minus sign
  703:     my $sign = ($number < 0) ? '-' : '';
  704:     $number = abs($number);
  705:     # needed to correct for a number greater than 1 (or
  706:     my $power = ($number < 1) ? 0 : 1;
  707:     # could round up. Take the integer part of log10.
  708:     my $x10 = int(log($number)/log(10));
  709:     # find number with values left of decimal pt = # of sign figs.
  710:     my $xsig = $number*10**($sig-$x10-$power);
  711:     # get just digits left of decimal pt - also rounds off correctly
  712:     my $xint  = sprintf('%.0f',$xsig);
  713:     # save any trailing zero's
  714:     my ($zeros) = ($xint =~ /(0+)$/);
  715:     # return number to original magnitude
  716:     my $numSig = $xint*10**($x10-$sig+$power);
  717:     # insert trailing zero's if have decimal point
  718:     $numSig =~ s/^(\d+)\.(\d+)(\e?(.*)?)$/$1\.$2$zeros$3/;
  719:     # put a decimal pt for number ending with 0 and length = # of sig fig
  720:     $numSig.='.' if (length($numSig) == $sig && $numSig =~ /0$/);
  721:     if (length($numSig) < $sig) {
  722: 	$numSig.='.'.substr($zeros,0,($sig-length($numSig)));
  723:     }
  724:     # return number with sign
  725:     return $sign.$numSig;
  726: 
  727: }
  728: 
  729: sub map {
  730:     my ($phrase,$dest,$source)=@_;
  731:     my @oldseed=&random_get_seed();
  732:     my @seed = &random_seed_from_phrase($phrase);
  733:     &random_set_seed(@seed);
  734:     my $destct = scalar(@$dest);
  735:     if (!$source) {
  736: 	my @output;
  737: 	my @idx = &math_random_permuted_index($destct);
  738: 	my $ctr = 0;
  739: 	while ($ctr < $destct) {
  740: 	    $output[$ctr] = $$dest[$idx[$ctr]];
  741: 	    $ctr++;
  742: 	}
  743:         &random_set_seed(@oldseed);
  744: 	return @output;
  745:     } else {
  746: 	my $num = scalar(@$source);
  747: 	my @idx = &math_random_permuted_index($num);
  748: 	my $ctr = 0;
  749: 	my $tot = $num;
  750: 	$tot = $destct if $destct < $num;
  751: 	if (ref($$dest[0])) {
  752: 	    while ($ctr < $tot) {
  753: 		${$$dest[$ctr]} = $$source[$idx[$ctr]];
  754: 	        $ctr++;
  755:             }
  756:         } else {
  757: 	    while ($ctr < $tot) {
  758: 		$$dest[$ctr] = $$source[$idx[$ctr]];
  759: 		$ctr++;
  760: 	    }
  761: 	}
  762:     }
  763:     &random_set_seed(@oldseed);
  764:     return '';
  765: }
  766: 
  767: sub rmap {
  768:     my ($phrase,$dest,$source)=@_;
  769:     my @oldseed=&random_get_seed();
  770:     my @seed = &random_seed_from_phrase($phrase);
  771:     &random_set_seed(@seed);
  772:     my $destct = scalar(@$dest);
  773:     if (!$source) {
  774: 	my @idx = &math_random_permuted_index($destct);
  775: 	my $ctr = 0;
  776: 	my @r_idx;
  777: 	while ($ctr < $destct) {
  778: 	    $r_idx[$idx[$ctr]] = $ctr;
  779: 	    $ctr++;
  780: 	}
  781: 	my @output;
  782: 	$ctr = 0;
  783: 	while ($ctr < $destct) {
  784: 	    $output[$ctr] = $$dest[$r_idx[$ctr]];
  785: 	    $ctr++;
  786: 	}
  787:         &random_set_seed(@oldseed);
  788: 	return @output;
  789:     } else {
  790: 	my $num = scalar(@$source);
  791: 	my @idx = &math_random_permuted_index($num);
  792: 	my $ctr = 0;
  793: 	my $tot = $num;
  794: 	$tot = $destct if $destct < $num;
  795: 	my @r_idx;
  796: 	while ($ctr < $tot) {
  797: 	    $r_idx[$idx[$ctr]] = $ctr;
  798: 	    $ctr++;
  799: 	}
  800: 	$ctr = 0;
  801: 	if (ref($$dest[0])) {
  802: 	    while ($ctr < $tot) {
  803: 		${$$dest[$ctr]} = $$source[$r_idx[$ctr]];
  804: 	        $ctr++;
  805:             }
  806:         } else {
  807: 	    while ($ctr < $tot) {
  808: 		$$dest[$ctr] = $$source[$r_idx[$ctr]];
  809: 		$ctr++;
  810: 	    }
  811: 	}
  812:     }
  813:     &random_set_seed(@oldseed);
  814:     return '';
  815: }
  816: 
  817: sub capa_id { return }
  818: 
  819: sub problem { return }
  820: 
  821: sub name{
  822:     my $fullname = &EXT('environment.lastname').', '.&EXT('environment.firstname').' '.&EXT('environment.middlename');
  823:     $fullname = "" if $fullname eq ",  ";
  824:     $fullname =~ s/\%2d/-/g;
  825:     return $fullname;
  826: }
  827: 
  828: sub student_number { 
  829:     my $id = &EXT('environment.id');
  830:     $id = '' if $id eq "";
  831:     return $id;
  832: }
  833: 
  834: sub class {
  835:     my $course = &EXT('course.description');
  836:     $course = '' if $course eq "";
  837:     return $course;
  838: }
  839: 
  840: sub sec { 
  841:     my $sec = &EXT('request.course.sec');
  842:     $sec = '' if $sec eq "";
  843:     return $sec;
  844: }
  845: 
  846: sub open_date { 
  847:     my @dc = split(/\s+/,localtime(&EXT('resource.0.opendate')));
  848:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
  849:     my @hm = split(/:/,$dc[3]);
  850:     my $ampm = " am";
  851:     if ($hm[0] > 12) {
  852: 	$hm[0]-=12;
  853: 	$ampm = " pm";
  854:     }
  855:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
  856: }
  857: 
  858: sub due_date { 
  859:     my @dc = split(/\s+/,localtime(&EXT('resource.0.duedate')));
  860:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
  861:     my @hm = split(/:/,$dc[3]);
  862:     my $ampm = " am";
  863:     if ($hm[0] > 12) {
  864: 	$hm[0]-=12;
  865: 	$ampm = " pm";
  866:     }
  867:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
  868: }
  869: 
  870: sub answer_date { 
  871:     my @dc = split(/\s+/,localtime(&EXT('resource.0.answerdate')));
  872:     return '' if ($dc[0] eq "Wed" and $dc[2] == 31 and $dc[4] == 1969);
  873:     my @hm = split(/:/,$dc[3]);
  874:     my $ampm = " am";
  875:     if ($hm[0] > 12) {
  876: 	$hm[0]-=12;
  877: 	$ampm = " pm";
  878:     }
  879:     return $dc[0].', '.$dc[1].' '.$dc[2].', '.$dc[4].' at '.$hm[0].':'.$hm[1].$ampm;
  880: }
  881: 
  882: sub array_moments {
  883:     my @input=@_;
  884:     my (@output,$N);
  885:     $N=scalar (@input);
  886:     $output[0]=$N;
  887:     if ($N <= 1) {
  888: 	$output[1]=$input[0];
  889: 	$output[1]="Input array not defined" if ($N == 0);
  890: 	$output[2]="variance undefined for N<=1";
  891: 	$output[3]="skewness undefined for N<=1";
  892: 	$output[4]="kurtosis undefined for N<=1";
  893: 	return @output;
  894:     }
  895:     my $sum=0;
  896:     foreach my $line (@input) {
  897: 	$sum+=$line;
  898:     }
  899:     $output[1] = $sum/$N;
  900:     my ($x,$sdev,$var,$skew,$kurt) = 0;
  901:     foreach my $line (@input) {
  902: 	$x=$line-$output[1];
  903: 	$var+=$x**2;
  904: 	$skew+=$x**3;
  905: 	$kurt+=$x**4;
  906:     }
  907:     $output[2]=$var/($N-1);
  908:     $sdev=CORE::sqrt($output[2]);
  909:     if ($sdev == 0) {
  910: 	$output[3]="inf-variance=0";
  911: 	$output[4]="inf-variance=0";
  912: 	return @output;
  913:     }
  914:     $output[3]=$skew/($sdev**3*$N);
  915:     $output[4]=$kurt/($sdev**4*$N)-3;
  916:     return @output;
  917: }
  918: 
  919: sub choose {
  920:     my $num = $_[0];
  921:     return $_[$num];
  922: }
  923: 
  924: #&sum1(1,$x,sub { &sum1($_[0],2*$_[0], sub { fact($_[0])**2 })});
  925: #sub sum1 {
  926: #    my ($start,$end,$sub)=@_;
  927: #    my $sum=0;
  928: #    for (my $i=$start;$i<=$end;$i++) {
  929: #        $sum+=&$sub($i);
  930: #    }
  931: #    return $sum
  932: #}
  933: 
  934: #&sum2('a',1,$x,'&sum2(\'b\',$a,2*$a, \'&factorial($b)**2\')');
  935: #sub sum2 {
  936: #    my ($varname,$start,$end,$line)=@_;
  937: #    my $sum=0;
  938: #    for (my $i=$start;$i<=$end;$i++) {
  939: #	my $func=sub {
  940: #	    eval("\$".$varname."=$i");
  941: #	    eval($line);
  942: #	};
  943: #        $sum+=&$func($i);
  944: #    }
  945: #    return $sum
  946: #}
  947: 
  948: # expiremental idea
  949: sub proper_path {
  950:     my ($path)=@_;
  951:     if ( $external::target eq "tex" ) {
  952: 	return '/home/httpd/html'.$path;
  953:     } else {
  954: 	return $path;
  955:     }
  956: }
  957: 

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