File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.105: download - view: text, annotated - select for diffs
Wed Nov 16 23:17:39 2005 UTC (18 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- complains intellignetly when a user submits 2,3,4 and 2,3 was expected

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

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