Search


Ploticus > Scripts >
functions


Categories of available functions:

plotting
arithmetic
strings
commalists
shell
sql
dates
times
misc




HOW TO USE FUNCTIONS

A number of functions are available for use in ploticus scripts and proc getdata filters , for a wide range of purposes including processing of arithmetic, strings dates, times, commalists , and so on. Functions usually take one or more arguments and return a value. Functions may be used with #set , #call or as operands in #if/#elseif conditional expressions .

Custom functions may be coded and added to the file custom.c, and accessed like any of the built in functions, except that the names of custom functions should begin with a double dollar sign ($$) when invoked from scripts.




FUNCTION SYNTAX

Function names always start with a dollar sign ($). Function arguments are enclosed by parentheses and if more than one argument, separated by commas (,). For example:
    $formatfloat( @NUM, "%7.2f" )

Function calls may not be nested, ie. function arguments may not be functions.


In the following summaries, the function name appears along with a template for arguments that must be supplied.




PLOTTING

Note: the functions in this section may be used with a double dollar sign ($$) for faster function name search. Because of the way ploticus script files are parsed, #endproc should be used to terminate any #proc previous to these function calls, so that the proc executes before the function call.

$inrange( value, axis ) or
$inrange( value, axis, min, max )

    Return 1 if value within a range on the given axis. min and max are optional; if given they determine the range. If they are not given the range is the range of the axis within the plotting area.

$icolor( i )

    Return one of 20 preselected colors. The color sequence was selected to give good contrast between nearby entries. i allowable range is 1 to 20; values out of this range are modulo into range.
    Example: #set COLOR = $icolor( 2 )

$fieldname( n )

    Return the field name assigned to field n. First is 1. If no field name was defined, noname is returned.

$dataitem( row, field )

    Return the contents of the item in row and field of the current data set. row is a number, first is 1. field is either a number or an assigned name.

$defaultinc( min, max )

    Return a reasonable increment given numeric min and max, using the same algorithm used with axis stub increments.
    Example: #set inc = $defaultinc( 0, 200 )

$changeunits( axis, newunitspec )

    Change the scaling units associated with an existing axis.
    Example: #call $changeunits( x, "date nqyy" )

$squelch_display( mode )

    #call $squelch_display( 1 ) .. will squelch all drawing activity.
    #call $squelch_display( 0 ) .. will resume drawing activity.
    Note that #endproc must terminate any #proc previous to these function calls. (version 2.30+)

$boundingbox( mode )

    #call $boundingbox( 0 ) .. subsequent drawing does not influence the bounding box and hence the crop
    #call $boundingbox( 1 ) .. restore to normal mode of operation.
    Note that #endproc must terminate any #proc previous to these function calls. (version 2.30+)

$data_to_absolute( axis, val )

    Given a data location va in either X or Y space (specified by axis), return the absolute location.

$sleep( n )

    Delay for n seconds. Occasionally useful when viewing plots interactively.

$getclick()

    Produce a "More.." button and wait for user to click on it. Upon the click, return. Occasionally useful when viewing plots interactively.

$errmsgpre( tag )

    Allows developer to set the first portion of all ploticus error messages to tag (it will stay in effect until explicitly set again). For example, where a web page generates multiple plots it may be useful in identifying which plot had the error.

$textwidth( text, font, size)

    Return horizontal width of freetype bounding box. Useful only with freetype fonts, otherwise it returns 0. Suggested/contributed by Erik Zachte.

$rewritenums( f )

    takes a numeric quantity f and returns it rewritten for display purposes, applying numbernotation (as specified in your proc settings or config file).






ARITHMETIC AND NUMBERS

$arith( exp, format )

    Simplistic arithmetic expression evaluator. exp is an expression made up of numbers and the arithmetic operators + - * /. No embedded spaces nor parentheses are allowed within the expression. Evaluation is strictly left to right. Unary plus/minus are allowed. In versions 2.30+ scientific notation eg. 3.74e-07 is supported. format is an optional printf(3) display format specifier controlling the format of the result, eg. %.0f. Default format is %g, which should suffice for all but very large or very small values. For more on format specifiers see your manual page on printf(3).
    Example: #set RESULT = $arith(2+8/5) (result: 2)
    Example: #set RESULT = $arith(2+-8) (result: -6)
    Example: #set RESULT = $arith( 18*1000000000 , "%.f" )
    Example:
    #set RESULT = $arith( 18*.0000001 , "%.9f" )

$arithl(exp)

    Same as $arith() except lazy, i.e. non-numeric operands are accepted and treated as if they were 0.

$isnumber(s)

    Returns 1 if s is a valid number, 0 if not. In versions 2.30+ scientific notation is supported.
    Example: #set RESULT = $isnumber(-0.24) (result: 1)
    Example: #set RESULT = $isnumber(=) (result: 0)

$formatfloat(x,fmt)

    Format x using printf-style format string fmt. May also be used to format integers by using a fmt such as %03.0f.
    Example: #set RESULT = $formatfloat( 3.4425, "%3.2f" ) (result: 3.44)

$inr(n,lo,hi)

    See if n is within the numeric range of lo to hi. Returns 1 if so, 0 if not. Non-numeric n always returns 0.

$numgroup( val, h, mode )

    Convert val to a nearby multiple of h. Useful in grouping a set of numbers into bins. mode may be either low, mid, or high. For example, if f is 73 and h is 10, function returns 70, 75, or 80 for modes low, mid, high respectively.

$autoround(val,d)

    Round val to a reasonable precision. Use a value of 0 for d for normal behavior. Increase d to get more precision, reduce d to get less precision.
    Example: #set X = $autoround( @X, 0 )

$math(what,a,b)

    Various mathematical functions. a and b can be integer or floating point unless otherwise noted below.
    what	returns
    ----    -------
    abs	absolute value of a 
    mod	a modulo b 
    div	integer division a / b (a and b must be integers)
    pow	a raised to b 
    mag	a multiplied by 10 to the b
    log+1	the natural log of a, plus 1.0
    exp-1	the exponential of a, minus 1.0
    sqrt	the square root of a
    

    Example: #set X = $math(abs,-57) would return 57.
    Example: #set X = $math(mod,10,6) would return 4.

$random()

    Returns a random number between 0.0 and 1.0.

$ranger( rangespec )

    Convert an integer range specification to an enumerated list of all integers covered. Range specifications can contain integers separated by commas or dashes, with no embedded spaces. Example:
    #set RANGE = "5,8,11-15"
    #set LIST = $ranger( @RANGE )

    LIST would then contain 5,8,11,12,13,14,15




STRINGS

$len(s)

    Return the length of s.

$change(s1,s2,string)

    Change all occurances of s1 to s2 in string.
    Example: #set T = $change( "<", "<sup>", @T )

$expand( s )

    Expand all @variables present in s. Example:
    #set B = "@A world"
    #set A = hello
    #set C = $expand( @B )
    
    Variable C would then contain hello world.

$substring(s,n,len)

    Return a substring of s. Substring begins at character n (first is 1) for a maximum length of len. This function may also be used to count back from the end of the string and take a substring-- to do this, specify a negative n (see 2nd example below).
    Example: $substring( "abcde", 3, 99 ) would give cde
    Example: $substring( "abcde", -2, 99 ) would give de

$changechars( clist, teststring, newchar )

    The result will be teststring, with each instance of any char in clist changed to newchar. clist is either a single character or it may be one of these special symbols: not_alnum (change all non-alphanumeric chars); not_print (change all chars decimal ascii < 32 or > 127)l whitespace (change all whitespace chars).
    Example: #set RESULT = $changechars("*'", @S, "_" )

$deletechars( clist, teststring )

    The result will be teststring, with each instance of any char in clist deleted. clist may be a string of one or more characters, or one of these special symbols: not_alnum (delete all non-alphanumeric chars); not_print (delete all chars decimal ascii < 32 or > 127)l whitespace (delete all whitespace chars).
    Example: #set RESULT = $deletechars("*'",@S)

$stripws( s, mode )

    Remove whitespace characters from s. If mode is "any", all whitespace characters are removed. Otherwise only leading and trailing whitespace is stripped off.

$contains(clist,s)

    If string s contains any of chars in clist, return position (first=1) of the first occurance. Return 0 if none found. clist may be passed as the word comma to represent a comma (,).
    Example: #set RESULT = $contains( "*'", @S )
    Example: #set RESULT = $contains( ",", @S )

$lowerc(string)

    Return the lower-case equivalent of string.
    Example: #set RESULT = $lowerc(HELLO) (result: hello)

$upperc(string)

    Return the upper-case equivalent of string
    Example: #set RESULT = $upperc(Hello) (result: HELLO)

$capit(string)

    Return the string with first letter capitalized. (added 5/15/08).
    Example: #set RESULT = $upperc(hello) (result: Hello)

$strcmp(s,t)

    Return an integer representation of the difference in magnitude of s and t, using ascii order.
    Note: don't use this for #if statement equality comparisons; simple = and != should be used instead.
    Example: #set RESULT = $strcmp(ABC,XY) (result will be a negative integer)
    Example: #set RESULT = $strcmp(XY,ABC) (result will be a positive integer)

$strcat(s,t)

    Return the concatenatation of strings s and t
    Example: #set RESULT = $strcat(ABC,XY) (result: ABCXY)

$ntoken( n, s [,c] )

    Return the nth whitespace-delimited token in s. Or if c is specified as a single character, it is used as the delimiter... return the nth field in s (added 3/28/08).

$counttokens( s [,c] )

    Return the number of whitespace-delimited tokens in s. Or if c is specified as a single character, it is used as the delimiter... return the nth field in s (added 5/15/08).

$extractnum( s )

    Extract the first numeric entity embedded anywhere in s and return it.

$wildcmp( s1, s2 )

    Return the result of a wildcard-enabled match s1 vs. s2. s2 can contain wild cards. Return value is 0 on a match, -1 if s1 is "less than" s2, and 1 if s1 is "greater than" s2.

$encrypt( s, salt )

    Returns the result of one-way encryption of s. Uses crypt(3C). salt is optional 2 character perturbation string.

$urlencode( s )

    Returns the url-encoded version of s.

$urldecode( s )

    Returns the url-decoded version of s.




COMMALISTS

These functions operate on a string which is in the form of a commalist .

$count(str,list)

    Count the number of times str appears in list. If str is passed as * then this function will count the number of members in the list.
    Example: #if $count( "*", "a,b,c" ) = 3 (true)
    Example: #set RESULT = $count( "hello", "aba,gabba,jabba" ) (result: 0)
    Example: #set RESULT = $count( "x", "x,y,x,y,y,z,x" ) (result: 3)

$addmember(newmem,list)

    Append a new member newmem to end of list. If list is empty before call, result will have one member.
    Example: #set RESULT = $addmember( "red", @MYLIST )

$deletemember(mem,list)

    Remove a member mem from list.
    Example: #set RESULT = $deletemember( "red", @MYLIST )

$nmember(n,list)

    Get the nth member of list.
    Example: #set RESULT = $nmember( 2, "a,b,c,d,e" ) (result: b)

$commonmembers( list1, list2, mode )

    Detect if list1 and list2 have any members in common. Returns 0 if no members in common. If mode is "count", then the number in common is returned (for a,b,c vs. c,d,e this would be 1; for a,a,a vs a,b,c it would be 3). Otherwise, when a match is found 1 is returned immediately.
    Example: #set MATCH = $commonmembers( "a,b,c,d,e", "c,d,ee", "count" ) (result: 2)

$homogenous( list )

    Return 1 if all members of list are the same, 0 if there are any differences among members. If list has only 1 member, 1 is returned. If list is empty, 0 is returned.

$makelist( s )

    Convert s, a list of items separated by commas and/or whitespace, and return a commalist. Useful for building commalists from user input.
    Example: #set LIST = $makelist( "1101 1102 1103" ) (result: 1101,1102,1103)
    Example: #set LIST = $makelist( "1101, 1102, 1103" ) (result: 1101,1102,1103)




SHELL COMMAND INTERFACE

Functions related to the shell interface are described on the #shell manual page .




SQL DATABASE INTERFACE

Functions related to SQL interface are described on the #sql manual page .




DATES

These functions work with dates in various notations.

The default date format is mmddyy. Unless otherwise specified, these functions expect date arguments to be in the "current date format".

$setdatefmt(format)

    Set the current date format.
    Example: #call $setdatefmt( "yyyymmdd" )

$formatdate(date,newformat)

    Return date, formatted to newformat. Use to convert dates to different notations, to extract year, month, day components, or to get weekday equivalent. Available formats are described here
    Example: #set RESULT = $formatdate( @D, "yyyymmmdd" )

$datevalid(date)

    Return 1 if date is a valid one in the current date format; return 0 if it is not.
    Example: #if $datevalid(@apptdate) != 1

$todaysdate()

    Return the current date. It will be in the date format currently in effect.
    Example: #set RESULT = $todaysdate()

$daysdiff(date1,date2)

    Return the difference in days between date1 and date2.
    Example: #set RESULT = $daysdiff( 011298, 010198 ) (result: 11)

$julian(date)

    Return the julian (number of days since Jan 1, 1970) equivalent of date. date should be a date in current format, or the special symbol today.

$jultodate(jul)

    Return the date (in current format) that is equivalent to julian value jul.

$dateadd(date,ndays)

    Return the date resulting when ndays are added to date.
    Example: #set RESULT = $dateadd( 010198, 11 ) (result: 011298)

$dategroup( interval, mode, input )

    Take date, datetime, or time input value, and adjust it for grouping purposes. For example, after a set of dates are processed using $dategroup( week, mid, .. ), the result can be tabulated to get a weekly distribution. Allowable interval values are week month quarter year day hour. Allowable mode values are mid and first. First character is sufficient for these two args.

$yearsold(birthdate,testdate)

    Return the integer age in years as of testdate of a person born on birthdate.
    Example: #set RESULT = $yearsold( 062661, 022098 ) (result: 36)

$setdateparms(parmname,value)

    Set a date parameter. You can set the pivotyear, strictdatelengths, or lazydates attributes. See the config file documentation for descriptions of these parameters.
    Example of setting the pivot year: #set STATUS = $setdateparms(Pivotyear,90)
    Example of allowing lazy days: #set STATUS = $setdateparms(Lazydates,days)
    Example of allowing lazy days and months: #set STATUS = $setdateparms(Lazydates,both)




TIMES

These functions work with time values in various notations.

$settimefmt(fmt)

    Set the current time notation to fmt. Available notations are HH:MM:SS, HH:MM, and MM:SS. (A leading HH can handle single digit hour values; a leading MM can handle single digit minute values).
    Example: #set RESULT = $settimefmt(MM:SS) These functions work with time values.

$time()

    Return the current time in hh:mm:ss format.
    Example: #set RESULT = $time()

$timevalid(time)

    Return 1 if time is valid in the current time format; return 0 if it is not.
    Example: #if $timevalid(@appttime) != 1

$formattime(time,newformat)

    Take time, which is in the current time format, and reformat it using newformat.
    Example: #set t2 = $formattime( "14:22", "hh:mma" )

$timesec()

    Get number of seconds since midnight for the current time.
    Example: #set RESULT = $timesec()

$tomin(t)

    Take t (a value in the current time notation) and return the equivalent, expressed in # of minutes since 0:00:00. Result is float, with any seconds expressed as the decimal portion of a minute.
    Example: #set RESULT = $tomin( "3:45" )

$frommin(m)

    Inverse of $tomin(), where m is a float minutes value. Result is equivalent time in current notation.
    Example: #set RESULT = $frommin( 3.75 )

$timediff(t1,t2)

    Find the difference between two times t1 and t2 (both in current notation). Result is expressed in float minutes (any seconds expressed as fraction of a minute)
    Example: #set RESULT = $timediff( "3:43", "2:28" )




CHECKSUMS

Checksum routines use an odd-even algorithm that takes an integer and computes a checksum digit 0 - 9 or x. This checksum digit may be used to guard against key errors and transposed digits.

$checksumvalid(s)

    Returns 1 if s is a valid number with checksum. 0 if not.
    Example: #if $checksumgood(39) = 1 (result: true)

$checksumencode(i)

    Result is integer i with a checksum digit appended.
    Example: #set CHECKNUM = $checksumencode(29) (result: 294)

$checksumnext(s)

    Take s which is a number including trailing checksum digit, and increment the number and recompute new checksum digit. Result is returned. Example: #set RESULT = $checksumnext(39) = 1 (result: 41)




MISCELLANEOUS

$getenv(varname)

    Return the contents of environment variable varname.

$whoami()

    Return a string containing euid,egid, where euid is the current effective user id, and egid is the current effective group id.

$errormode( mode )

    Control the display of error messages. Allowable values for mode are stderr and stdout. For command line applications the default is generally stderr; for CGI applications it is stdout, so that messages are visible. To hide error messages in CGI applications, set mode to stderr.

$uniquename()

    Return a short identifier generated using the current date, time to the current second, and process id. The name will be unique on a per-host basis.

$tmpfilename(tag)

    Generate a unique (on a per-host basis) temporary file name, suitable for use in shell commands. Uses tmpdir as specified in project config file . Format of the name is tmpdir/tag.uniquename where uniquename is a short name generated using the current date, current time to the second, and process id. tag may be passed as a zero length string if desired.

$fileexists( dir, name )

    Return 1 if the requested file can be opened, 0 otherwise. dir indicates the directory that name is relative to and may be one of /, scriptdir, tmpdir. dir may also be datadir if using shSQL.
    Example: #set A = $fileexists( tmpdir, "mytmp" )

$rename( pathname, newpathname )

    Rename a file.

$unlink( pathname )

    Remove a file.

$chmod( pathname, mode )

    Do a chmod on pathname, setting it's file permissions to mode. Allowable modes are: 644, 664, 666, 444, 640, and 660.

$chdir( dirpath )

$mkdir( newdirpath )

    Initially sets the mode to 755; do a subsequent $chmod() for other protection modes.

$cleanname( name )

    Strip out any punctuation and control characters from name, leaving only letters, digits, and underscores.
    Example: #set name = $cleanname( @name )

$ref( varname )

    Return the contents of varname. May be useful when a variable contains the name of another variable, to extract the value of the other variable. Example:
     #set A = "hello"
     #set B = "A"
     #set C = $ref(@B)
    

    C would then contain hello.

$def( varname )

    Return 1 if varname has been set to a value (even if the value is ""). Return 0 otherwise.

$isleep( n )

    Delay for n seconds.

$showvars(mode)

    For debug purposes. Writes a list of every existing internal variable name to standard output, along with a count. If mode is given as "values" variable contents are also written.

$fflush()

    Flush standard output buffer. With quisp this can be used to immediately display all content available so far.

 


Ploticus 2.42 ... May 2013 Terms of use /