File:  [LON-CAPA] / loncom / homework / default_homework.lcpm
Revision 1.102: download - view: text, annotated - select for diffs
Tue Aug 2 18:47:24 2005 UTC (18 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: version_2_0_X, version_2_0_2, version_2_0_1, version_2_0_0, version_1_99_3, HEAD
- was doing -123 -> -,123 BUG#4110

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

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