File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.107: download - view: text, annotated - select for diffs
Tue Jun 13 14:57:54 2006 UTC (17 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- moving code from modules into main

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

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