NomarScript 3.63

Users Manual and Function Reference

 

Introduction

Run modes and starting Nomar

Variables and Data types

Program flow

Accessing and indexing arrays

Functions, macros and function call syntax

Objects and methods

Creating Graphics

Function table reference

Functions alphabetical reference

 


Users Manual

Introduction

Nomar

Nomar is a web application development and runtime environment with a focus on probabilistic modelling, statistical analysis and the handling of multi dimensional data. Nomar can be used as a standalone web server or as a module working together with other web servers or programs, which can interface to it. For this mode Nomar has a broad spectrum of data input/output facilities and its API can be accessed via a variety of interfaces.

Nomar is built in a modular fashion using the Sun Java 2 Platform relying only on Platform 2 Standard Edition features in most run modes. When running in Servlet mode, some Java Enterprise features are required.

Nomars architecture can best be understood by looking at the following diagram:

 

Figure 1: Nomar architecture

 

The core of the system is a JavaScript engine enhanced with special capabilities to handle multi demsional data, probabilistic modelling and statistics.

This core is surrounded by special modules to handle control, input/output and data transformation. In NomarScript each of this modules is represented by a dedicated set of functions.

NomarScript

Nomar's scripting language closely resembles Netscapes JavaScripttm, but enhanced by the following features, some of which are re- implementations of Analytica's Visual Modelling Tool software. It also leverages the rich variety of Java API's in the realm of Internet programming and Internet based standards.

- Namespaces, modules

This feature allows the partition of NomarScript source code into different modules/packages, each of which have there own namespaces for user defined functions and variables.

- Array abstraction

This feature, which originated in the Analytica Modelling software tool, goes far beyond the single dimension array abstraction as used in Perl or other scripting languages. As in Analytica, NomarScript does multi dimensional array abstractions on most of it's built in functions including those which are not inherited from Analytica. This facilitates greatly modelling and general programming, avoiding the programming of loops or nested loops, which run over indices.

- Modern object oriented notation of functions, parameters

Most general purpose functions in NomarScript work like their counterparts in standard ECMA JavaScript. Some changes where made to handle name conflicts with Analytica. All of Analytica's modelling and simulation functions carry the same name in NomarScript. In a few cases the parameter order has been changed to accomodate JavaScripts object.method() form of function calls. In NomarScript both forms can be used e.g.:

var str = "hello";

str.length() => 5

length(str) => 5

Both forms evaluate to 5. Because of NomarScript's flexibility in function call notation the syntax for creating objects is slightly different from standard JavaScript (See chapter about Objects and methods).

- Interfaces

While JavaScript is in most of its applications a client-side web-page embedded language, NomarScript can be used as a freestanding scripting/programming language or as web-page embedded server-side scripting language. In the latter case NomarScript itself can act as a HTTP (web-) server processing tagged NomarScript code in HTML pages and up serving pages, images etc. just like a normal web server. In server mode NomarScript processes GET/POST requests like function calls. The called functions may haven been preloaded in to the NomarScript server or are embedded in webpages. This makes NomarScript an ideal web application building tool.

NomarScript also offers a ODBC interface to access databases and a POP3 and SMTP client interface for generating/receiving email. Because NomarScript is written in Java and can load and instantiate Java classes at runtime, it is easily expanded with custom written Java modules.

- Object orientation

NomarScript's compilation/execution model is object oriented. Each built in function constitutes a Java class which gets instantiated at compile time into a Java object, which directly executes during runtime. This way no NomarScript specific 'VM' is necessary as in traditional Interpreters. Once NomarScript is compiled into evaluatable Java objects, those can be executed directly by a Java runtime environment.

NomarScript is implemented in 100% Java Platform 2 Standard Edition, using features available in Java 2 version 1.2.2. as a minimum. It has been tested on Win32 and Linux platforms running the standard Sun Java VM and Sun Hotspot Server VM.

 

Font types and conventions used in this manual

Whenever NomarScript code is cited, it is formatted in a fixed size Couier font:

var x = 123;

For learning purposes the code can be cut and pasted into the console window for trying it out. When evaluating an expression or inspecting the contents of a variable the => sign is used to illustrate this in the manual. => should not be typed, but rather means 'evaluates to'. E.g. entering x will produce the output 123:

x => 123

 

Run modes, starting Nomar

NomarScript has different modes of operation: while the console modes are usefull for developing applications and for learning the language, the HTTP server mode is the main applications mode when running web applications.

Shortcuts of batch files can be built with the commands shown in the examples below. When building a shortcuts under Windows instead of java, javaw can be used for the windowing and http modes. javaw.exe avoids a Win32 console window being created, which is not necessary when running NomarScript in it's own Java window or in HTTP server mode.

 

Console modes

NomarScript can be started as a console or shell application:

java -jar nomar.jar -console

or in its own window using:

java -jar nomar.jar

or listening on the telnet port 23 to be accessible through the Internet using a telnet client application:

java -jar nomar.jar -telnet

 

HTTP server mode

In this mode NomarScript acts as a web server capable to deliver normal webpages, imagefiles etc. via GET requests from client as web browsers. This mode gets initiated starting NomarScript as follows:

java -jar NomarScript.jar -http

Additionally NomarScript can serve CGI query GET and POST requests by transforming the GET/POST query into function call to a NomarScript function. This is completely transparent to the web page initiating the GET/POST query. The following example shows the HTML code of a webpage with embedded NomarScript code to answer a POST query request:

<HTML>
<HEAD>
<TITLE>POST demo</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
</HEAD>
<!--
<%

function welcome(params)
	{
	writeln('<H1>Welcome ' + params.nameField + '</H1>')
	}
''
%>
-->

<BODY BGCOLOR="#FFFFFF">
<FORM METHOD="post" ACTION="welcome">
  <DIV ALIGN="center">enter your name: 
    <INPUT TYPE="text" NAME="nameField">
    <BR>
    <BR>
    <INPUT TYPE="submit" NAME="Submit" VALUE="Submit">
  </DIV>
</FORM>
</BODY>
</HTML>

 

When the "Submit" button is pressed and the named entered was John Doe, then the browser will generate a POST request to the server running NomarScript resulting in a function call to welcome().

params is an array indexed by the names of the form elements in the HTML form, wich makes it easy to reference those in the NomarScript source code.

The special tags <% and %> are recognized by most HTML-page editors, so pages can be built and edited using familiar tools and without compromising the embedded script code.

Server Side NomarScript code can be easily mixed with client side original JavaScript on the same HTML page. JavaScript functions can trigger NomarScript functions by means of the HTTP to NomarScript function call interface.

 

Servlet Mode

Nomar can run as a servlet hosted by a Servlet API 2.2 conformant container as for example Apache Tomcat 3.1, which is Sun Micsosystem's reference implementation of the s.s Servlet API. Running Nomar as a Servlet adds cookie and session management capabilities to Nomar. It also allows Nomar to run in a Java Server Pages (JSP) based in environment.

To run Nomar as a Serlet its underlying classes are packaged is packaged in a .war (Web Application Archive) file. This file can be directly installed in Tomcats tomcat/webapps directory.

A second file tomcat/bin/servlet.nomar is installed in the tomcat/bin directory. This file contains the Servlet dispatch routines doGet and doPut which invoke other application specific Nomar modules and functions. This file has to be modified depending on the application

A third file, which is part of the Nomar.war file must be modified. The file web.xml is found in the tomcat/webapps/nomar/WEB-INF directory and contains mappings of Nomar servlet requests to Nomar classes and URLs from client request.

For a more detailed discussion of servlet installation and treatment of the web.xml file see the Apache documentation of Tomcat.

 

Alternative Class Path

When Nomar is running certain functions like DB.driver() or register() look for Java classes in .jar files or in directories structured following the Java package hirarchy. Nomar looks for Java classes in the usual archives and directories of the Java runtime environment and addtionally in the following places:

- the startup directory of nomar.jar

- the Java archives AlternateJdbcDriver.jar or AlternateJdbcDriver.zip (see DB.driver()) in the startup directory

An alternate way of starting Nomar can be used to specify additional class paths, e.g.:

java -cp /nomar/nomar.jar;/nomar/myclasses.jar;/nomar/myClassDir gc.script.Script -http

The example shows an additional class file path and an addtional directory path. gc.script.Script is the main class to be executed when starting Nomar. See the Java Platform 2 documentation for more details on the Java class path.

 

Variables and Datatypes

 

Variables

Variables in NomarScript are case sensitive as in JavaScript or Java and must start with a letter a-z,A-Z or the underscrore _ character or the characters @, $ and can contain all these characters and number digits.

x, X, Var1, Name, Telephone_2, $address, @var, _special

Are alll valid variable names, x and X are different variables.

As in other scripting languages and specifically JavaScript, the same variable can be used to hold any data type. Often a specific data type is interpreted as a different one in a different context:

4 + "3" ==> 7

but

"4" + 3 ==> "43"

Variables have to be declared before using them, i.e.:

var myVar, x, y, z;

Declares four variables myVar, x, y and z. Variables may be intitialized to a value during declaration, but only one per declaration:

var age = 0;

var name = 'John Doe';

var vector = [1, 2, 3, 4];

var something = (x + y)/z;

The three statements declare variables and initialize them with a number, a string and an array and the result of evaluating an expression. Variable declarations must end with a semicolon. A variable initialized using one data type may be used to hold other data types later. E.g. the following sequence of statements is legal:

var any = "hello"
any = 3 * 4;
any = ['a', 'b', 'c'];

Although the variable any is introduced holding a string, it is later used for holding a number or an array of strings.

Uninitialized varaibles contain the special data type nil and can be tested for this using isUndefined(), i.e.:

var aVar;

aVar.isUndefined() ==> true

or equivalent

isUndefined(aVar) ==> true

Another possibility to test for nil is to test for true or false in a boolean context:

var xVar;

or

var Xvar = [];

if(xVar)
    writeln("Xvar has a value=" xVar);
else
    writeln("Xvar is not intialized or contains an empty array");

Note, that in this case xVar containing an empty array [] would also be interpreted as false, but isUndefined(aVar) would return also false as the aVar is defined as containing an empty array.

 

Number

Numbers are internally represented as 64bit IEEE 754 double floating point numbers. Numbers without a fractional part are displayed without the decimal period and are internally handled as integers when required (i.e.: loops, indices).

Scientific notation is not supported on the commandline or in program source but a function parseFloat() is available to parse floating point numbers in a variety of formats i.e.:

A function parseInt() is available for parsing integers of any number base ie.: hexadecimal, octal or binary numbers:

The directives numberFormat() and format can be used to format() numbers for output, including special characters for currencies, scientific units etc..

The special number constants NaN (not a number) and Infinity (division by zero) are generated as the result of unallowed operations on numbers or overflow/underflow conditions. The functions isNaN() and isInfinity() can be used to test for these conditions.

 

String

Strings are sequence of text characters. Internally NomarScript stores strings as Java Unicode characters. Depending on the current locale of the underlying OS platform and Java virtual machine any foreign language character part of the 65,000 charcater Unicode set can be part of a string. String constants must be delimited by double or single quotes.

"this is a string"

'this is also a string'

'this is an "embedded" string'

The quote not used for delimiting the string can be used inside a string. This is specially useful in HTML tags, i.e.

'<table border="1">'

When using ' or " inside string constants already delimited by the same characters, they have to be escaped by the '\' back slash character:

"<table border=\"1\">"

Some non-visible ASCII characters and other special characters can be encoded using '\' escape character as follows:

\t tab character
\n line feed
\r cariage return
\" " double quote
\' ' single quote
\\ back slash

 

Numerous string functions are available to select sub portions of strings, do pattern matching or convert to different case in an international language-safe manner, and to convert into other data types.


Array

Arrays are internally represented as vectors of any other data type or a mix of them. Arrays which contain other arrays are interpreted as multi dimensional if they are indexed on relevant dimensions. Array elements may also contain expressions, function calls or blocks of script statements.

Many functions use a mechanism called 'Array Abstraction' which will result in multiple function calls or operations working on all array elements in a synchronized or permuted fashion depending on the context of evaluation and depending on the indices used to index arrays.

Array constants are written using square brackets [,]. For example:

[1,2,3,4,5]

or

['a','b','c']

or

[(x+y), z, "hello"]

or arrays within an array:

[[1,2,3],[10,20,30],[100,200,300]

Elements or portions of arrays may be accessed in a variety of ways. See the chapter about Accessing and indexing arrays


Boolean

In a boolean context, as in if and while statements or as a result of a logical comparison, other datatypes may be interpreted as boolean dependent on the data contents. For example the empty string '' or "", the empty array [] or the number 0 are interpreted as false.

The boolean constants are true and false

 

Variant

This may be any of the before mentioned datatypes or expressions composed of these.

 

nil

This is a special datatype which is used to indicate the 'absence' of any data. For example an array could be initialized to contain nil's. As a return value nil is used in many functions to indicate that an unexpected condition has occurred which should be handled by the program, i.e. time-outs on Internet connections or failing parsing numbers caused by incorrect formatted numbers in strings. The predicate isUndefined() can be used to check if a data value is nil. A variable containing an ampty array [] is still a defined variable and would return false when using isUndefined()

 

Program flow

All program flow constructs in NomarScript work like in JavaScript.

 

Block

Blocks are used in function declarations and if, for, while and switch expressions but can be used anywhere else to group a sequence of statements. With the exception of function and functionMacro declarations, blocks do not have an own variable scope (lexical closure):

myProc :=
  {
  doThis();
  doThat();
  }

myProc.eval()

In this example the statments enclosed by {,} braces constitute a block. Blocks may be assigned to variables for later evaluation as shown in the example. Note, that this form of assignment with := is different from an assignment using =. The first form stores the block in an unevaluated form, while the latter form using = evaluates the block first, than stores the result. When translating Analytica models the first form is the preferred one.



If and if else

if and if ... else are the most basic way to control programflow:

if(x > 100)
   writeln('big');

if(x > 100)
   writeln('big');
else
   writeln('small');

The if key word is followed by a condition enclosed in parenthesis, which evaluates to true or false. Depending on outcome the statement after the condition is executed, or in case of if ... else the statement after the else key word is executed.

If the body in an if statement or if else stemement consists of more than one statements, they have to bee enclosed in curly braces to form a block. The same is true when nesting several if or if else expressions:

if(x > 100)
  {
  if(x > 1000)

    writeln('huge');
  else
    writeln('big');
  }
else
   writeln('small');


Note, that there is no elseif as in some other programming languages. Use nested if statements instead.

When enclosing the if-ellse statement in braces it's return value can be directly used eg.: in an issignemt;

var x = 200;

var result = { if(x > 100) 'big' else 'small'; };

result => big

When using arrays in this functional form and array abstraction is required on the condition and 'then' and 'else' values, than cond() should be used.

For loop

The for loop works just like in regular JavaScript or as in Java, 'C', 'C++' or many other programming languages:

for(var idx = 0; idx < 10; idx += 1)
 
write(idx);

will produce the following output:

0123456789

Note, that the variables idx and sq are not local in scope to the body of the for(...) expression, once a variable is introduced in a for loop or block it can be used anywhere else. Only functions and objects (introduced later) allow the declaration of local variables. Including the variable definition var in a statement is just a shortcut. Note also, that NomarScript does not the have the position dependent ++ / -- increment/decrement operators as standard JavaScript does. Instead the expressions += 1 or -= 1 should be used when incrementing or decrementing by one.

When the body of the for-loop consists of more than one statement, these have to be enclosed in {} braces:

for(var i = 0; i < 5; i += 1)
  {
  var sq = i * i;
  writeln("i=", i, "i^2=", sq);
  }

This example would produce the output:

i=0 i^2=0
i=1 i^2=1
i=2 i^2=4
i=3 i^2=9
i=4 i^2=16

The for loop can also be used to iterate over objects:

function person(name, age, phone);
var someOne = new person("John Doe", 25, "555-1212");

for(var i = 0; i < someOne.size(); i += 1)
   writeln(someOne[i]);

John Doe
25
555-1212

This would be equivalent to:

someOne.name.writeln();
someOne.age.writeln();
someOne.phone.writeln();

 

For in loop

The for in loop works just like in JavaScript on arrays and objects. In case of arrays it iterates over the array members, in case of an object it iterates over the object data members (variables) :

var myArray = [5,3,6,2,4];

for(var i in myArray)
  {
  writeln(i);
  }

whill produce the output:

5
3
6
2
4

Or in case of objects:

function person(name, age, phone);
var someOne = new person("John Doe", 25, "555-1212");

for(var field in someOne)
   writeln(field);

John Doe
25
555-1212

Note, that no curly braces are required for the body of the for ... in loop, as it only consists of one statement.

 

while

Using the while loop a statement of block of statements can be repeatedly excuted depending on the outcome of a condition:

var x = 0;
var y = 5;

while(x < y)
  {
  write(x);
  x += 1;
  }

would produce the output:

01234

To write a loop, which runs forever:

while(true)
    {
    doSomething();
    }

The loop in the last example will never finish.

 

break and continue

break and continue can be used to change the flow inside a for or for ... in or while loop. break leaves a loop and continue skips the rest of the body and jumps to the beginning.

for(var i = 0; i < 20; i += 1)
  {
  if(i == 2 or i == 4) continue;
  if(i == 10) break;

  write(i);
  }

would produce the output:

01356789

The following 'infinite' loop will exit when  someCondition() returns the boolean value true:

while(true)
    {
    if(someCondition()) break;
    }

This could be written shorter as:

while(not someCondition()) {};

The function someCondition() will be executed until it returns true. Note, that the empty statement block {} cannot be omitted (like in C or C++);

 

Switch

Often collection of many if's like in:

if(x == 1) doThis();
if(x == 2) doThat();
if(x == 3) doOther();

can be replaced with the switch statement:

switch(x)
  {
  case 1:
    doThis();
    break;
  case 2:
    doThat();
    break;
  case 3:
    doOther();
    break;
  default:
    someThingDifferent();
  }

NomarScript will check each case for x and execute the statement or statements following it. The break key word makes the program flow leave the switch statement. if the none of the case 's apply the statement or statements in the default section are executed. The default section may be empty, but the default keyword should no be missing. switch can also work on string constants:

switch(color)
  {
  case 'green':
    ...
    ...
    break;
  case 'blue':
    ...
    ...
    break;
  case 'red':
  case 'black':
  case 'white':
    doForRedBlackWhite();
    break;
  default:
    doDefaultStuff();

  }

More than one case statement may appear. In the example the three colors 'red', 'black' and 'white' will cause the function doForRedBlackWhite() to be executed. break statements are needed in each case section to avoid the program flow 'falling thru' to the next case.

 

Accessing and indexing arrays

Indexing arrays with known order of indices

An array can be used as an index for another array. If an array is not specifically indexed it is indexed by 'itself', which is the base for content-addressing. For example:

var region = ['east','west','north','south'];

var fruits = ['apples','oranges','bananas'];

var inventory = table(region, fruits, 0);

In this example region and fruits are just normal arrays which also serve as indices for inventory. The table inventory is initialized with zeros.

an array may be indexed after it was created:

var x = [10,29,30,50];

x.setIndex(region)

The x - array can now be accessed using the region index i.e.:

x.east

Arrays are associative addressable when using indices.

inventory constitutes a vector of four elements initialized to 0 in this example. The individual elements of this vector could be addressed associatively as:

inventory.east, inventory.est, inventory.north, inventory.south

or

inventory[0], inventory[1], inventory[2], inventory[3]

Arrays may be addressed by its content:

var colors = ['red', 'green', 'blue']

colors[0] => 'red'

colors.red => red

colors['red'] => 'red'

While the previous lines don't have much practical value, they show how NomarScripts internal mechanism of indexing works. This content-addressable mechanism is the basis of array indexing. When an array is not explicitly indexed then it is indexed by itself and content. Another example:

var x = ['red','green','blue'];

x.red = 'orange'

x is now:

['orange','green','blue;]

and x.red would be an invalid reference. The index specification may be an arrray by itself:

var x = [1,2,3,4];

then

x[[0,3]]

results in

[1,4]

Multidimensional arrays are constructed using multiple indices. For example:

var region = ['east','west','north','south'];

var fruits = ['apples','oranges','bananas'];

var inventory = table(region, fruits,
              [[0, 1, 2], [10, 11, 12], [20, 21, 22], [30, 31, 32]]);

would create a two dimensional array. The inventory of apples in the south region could be addressed as follows:

inventory.south.apples

or

inventory[3][0]

or

inventory[3].apples

Note, that:

inventory.apples.south     // wrong order

would result in an error as the indices are in wrong order. For order independent indexing see the next chapter.

Array abstraction can now be used to iterate over specific dimensions of the table at once:

inventory.sum(region)

inventory.sum(fruits)

The first expression would give us a sum for each fruit over all regions. The second yields the sum over all fruits in each region.

 

Accessing indexed arrays with position independent indices.

All multidimensional arrays are created with and index order following the order the indices where created. The above methods of accessing elements in an array are fast but rely on the correct order of the indices. Indices occur in an array in the order they where created.

Using the following method, arrays can be indexed without knowing the internal order of indices:

inventory[region, 'west']

returns an array slice of all fruits in west and would be equivalent to:

inventory[region, 1]

because 'west' is at offset position 1 in index region

inventory[region, ['east','south']]

would return a two dimensional array of fruits in two regions:

inventor[fruits, 'oranges'][region,'west']

singles out the inventory of oranges in the region west and is equivalent to:

inventory[region,'west'][fruits, 'oranges']

NomarScript will apply indices in an correct order. Multi dimensional sub areas or cubes can be extracted:

inventory[fruits, ['apples','bananas']][region, ['west','south']]

The resulting array will be indexed by the sub indices ['apples','bananas'] and ['west','south'].

 

Accessing arrays with boolean indices.

Indexed arrays can be accessed using boolean indices. This is useful for accessing subsets of arrays:

if

var x = [1, 200, 20, 25, 300, 5]

then

x < 100

results in:

[true, false, true, true, false, true]

the function index() can be used to transform boolean vectors into index positions of their true values:

index(x<100) ==> [0,2,3,5]

and now

x[index(x<100)]

x[[0,2,3,5]]

x[ x < 100 ]

all result in:

[1, 20, 25, 5]

or

x[ x < 100 or x > 200]

results in:

[1, 20, 25, 300, 5]

When using a boolean array as a subscript it is automatically converted to index positions. Note, that the boolean array must always be one dimensional.

Boolean indexing and position independent indexing as explained above can be combined:

inventory[index(region != 'west')] =>

[[0, 1, 2], [20, 21, 22], [30, 31, 32]]

or shorter

inventory[region != 'west']

In order for this to work the boolean array (region != 'west' in th exanple) must be indexed by one of the indices of the subscripted array. In the above example the array inventory and the boolean array region != 'west' are both indexed by region.

 

Arrays as stacks and queues

Although NomarScript arrays are implemented using Java Vectors, they can also be used as stacks or queues:

var myStack = [];   
myStack.push(1);   
myStack.push(2);
myStack.push(3);

This will result in an array with 3 elements:

myStack => [1,2,3]

Arrays may also be popped:

var top = myStack.pop();

top => 3

myStack => [1,2]

Arrays can also be used as queues:

var myQueue = [1, 2, 3, 4, 5, 6, 7, 8];

myQueue.first() => 1

myQueue.last() => 8

myQueue.insert('I am the first', 0);

myQueue => ['I am the first', 1, 2, 3, 4, 5, 6, 7, 8];

myQueue.insert('in the middle', 4);

myQueue => ['I am the first', 1, 2, 3, 'in the middle', 4, 5, 6, 7, 8]

To remove elements from the end of the queue use pop() or use remove() to extract elements from any position:

var myQueue = [1, 2, 3, 4, 5, 6, 7, 8];

myQueue.pop() ==> 8

myQueue.remove(2) ==> 3

myQueue ==> [1, 2, 4, 5, 6, 7]

Simple array abstraction on one dimension

Array abstraction is a process by which NomarScript iterates over the elements of arrays implicitly without having to write for or while loops. This allows re-using formulas which where built for scalar entities for arrays without rewriting them:

var x = 3;

z = x * 2;

z => 6

now x will be defined as an array:

var x = [1,2,3,4,5,6];

z = x * 2;

z => [2,4,6,8,10,12]

The same assignment z = x * 2 now produces an array, because x, which was a scalar value before, now has changed to an array of numbers. The operation of * 2 has been applied to each member element of array x.

The mechanism works on most functions available in NomarScript and not only on functions which work on numbers e.g.:

var colors = ['red', 'green', 'blue']

colors.toUpperCase() => ['RED', 'GREEN', 'BLUE']

'I like ' + colors => ['I like red', 'I like green', 'I like blue']

The function toUpperCase() is working on all elements of the array colors. Sometimes a function is applied on another function which produces an array:

var sentence = "array abstraction is a nice thing to have";

sentence.split().toUpperCase() =>

    ['ARRAY', 'ABSTRACTION', 'IS', 'A', 'NICE', 'THING', 'TO', 'HAVE']

or:

sentence.split().length() => [5, 11, 2, 1, 4, 5, 2, 4]

The function summary tables contain a '*' asterix for all functions which can use array abstraction. If the array contains elements of different datatypes, the result will be the same as when applying the abstrcated operator or function individually:

var x = [1, 2 ,3 , 'A'];

x * 3 ==> [2, 6, 9, NaN];

x + 3 ==> [4, 5, 6, 'A3'];

 

Multi dimensional array abstraction

In order to ake array abstraction work on multidimensional arrays, these arrays must be indexed on all of it's dimensions. The array created in the following stement is not indexed well, as it is index only by itself:

var inventory = [[0, 1, 2], [10, 11, 12], [20, 21, 22], [30, 31, 32]]);

inventory.indexNames() => ['inventory']

The function indexNames()can be used to determine the indices an array is indexed on. The example shows that the array is only indexed by itself. When multiplying inventory by a number it will not give the expected result. NomarScript sees a one dimensional array whose elements are other arrays but not numbers which can be multiplied:

inventory * 3 => [NaN, NaN, NaN, NaN]

NaN stands for: 'Not a number' and is used in NomarScript whenever an arithmetic operation is tried on the wrong data type.

To make the example work, we have to index inventory. This is best done by creating it differently:

var region = ['east','west','north','south'];

var fruits = ['apples','oranges','bananas'];

var inventory = table(region, fruits,
              [[0, 1, 2], [10, 11, 12], [20, 21, 22], [30, 31, 32]]);

now inquiring about the indices of inventory gives a different response:

inventory.indexNames() =>  ['region', 'fruits']

Now multiplying inventory by 3 will work:

inventory * 3 =>
    
[[0, 3, 6], [30, 33, 36], [60, 63, 66], [90, 93, 96]]

But now let's assume we want to increase the inventory by a different factor in each of the four regions. In order for this to work, we need to index our four multipliers by region:

var invIncrease = table(region, [2,2,3,5]);

inventory * invIncrease =>
    [[0, 2, 4], [20, 22, 24], [60, 63, 66], [150, 155, 160]]

Array abstraction will take care of matching the right dimensions and applying arithmetic operator or functions accordingly. Although the dimensionality of inventory or invIncrease may change the basic expression inventory * invIncrease can always stay the same.

If invIncrease is not indexed by region, array abstraction will assume we want to multiply inventory four times, each with a different factor. Let us demonstrate this on a smaller example with less dimensions, so it is easier to understand:

var inventory = table(fruits, [10,20,30]);

var invIncrease = [2,3,3];

inventory * invIncrease => [[20, 20, 30], [40, 40, 60], [60, 60, 90]]

If we index invIncrease on fruits we get a different result:

invIncrease.setIndex(fruits);

inventory * invIncrease => [20, 40, 90]

the size of an index and the array to be indexed need not to be the same, but when accessing elements out of an existing range an error will occur:

fruits.push('lemons')

inventory.lemons ==> index out of bounds error

Note, that internally NomarScript stores arrays ordering dimensions in the order these dimensions or their indices where created. When using position independent indexing, this is transparent to the user, but when using position dependent indexing the internal order of dimensions must be kept in mind. When all dimensions in an array are indexed the function indexNames() can be used to find out about the internal order as shown previously.

 

Functions, macros and function call syntax

Functions

Functions or functionMacros can be defined to hide functionality inside a function call. All variables names in parameters and function internal variable declarations are of local scope to the function:

function myFunc(x, y, z)
  {
  var result
;

  result = (x + y) * z;

  return result;
  }

The variables x, y, and z and the variable result are all local to myfunc() and will not conflict with same names of variables in the calling program or inside other functions

 

Macros

When evaluating functions, NomarScript will evaluate its arguments first as shown in the following example:

function printMe(x)
  {
  writeln(x);
  }

printMe(3 + 4) => 7;

But we can define printMe as a macro:

functionMacro printMe(x)
  {
  writeln(x);
  }

printMe(3 + 4) => (3+4);
printMe(y) => y;

NomarScript will now pass the expression (3 + 4) unaltered inside the macro. Defining function macros can be useful when creating specialized functions with special evaluation rules, where evaluation of function arguments wants to be under control of the function itself.

 

Calling functions or macros

There are two ways to write function calls in NomarScript. One is the usual 'JavScript' way or the way many other object oriented languages write a function call. The other way is the more traditional way of older functional and procedural languages. For example, one could write:

months.sum(region)

or

sum(months, region)

or

if(isEqual(answer, 'yes')) doThat();

or

if(answer.isEqual('yes')) doThat();

In all functions the first argument can either be inside the parenthesis or a object.method() notation can be used. Both methods can be combinded:

numbers = [1, 345, 20, 1234]
numbers.toString().length()

would convert an array of numbers into an array of sizes of the string representation of those numbers. This could alo be written as:

length(numbers.toString())

or

length(toString(numbers))

all forms would result in:

[1, 3, 2, 4]

 

Anonymous Functions

Anonymous functions are functions without a name. They are used to when a function is only used once but for reason of better readability one wants to enclose the code in a function:

function doit(func, data)
  {
  func(data);
  }

doit(function (x) {3 * x;}, 10) => 30

In this example a function (x) {3 * x;} is defined on the fly without a name. The function takes a value x and returns it multiplied by 3.

 

Objects and Methods

Objects

The built in directive function is mostly used to build user defined procedures, but can also be used to package several variables in to one object:

function account(name, balance);

account can now be used as a template to create a number of account objects using the keyword new:

var acc01 = new account("John Doe", 0);
var acc02 = new account("Jane Johnson", 120);

The new created objects can now be used like any other variables assigning values to it or using them in formulas etc.:

acc01.balance = 123.00;
acc01.balance + acc02.balance => 243;

acc02.name.toUpperCase() => 'JANE JOHNSON'

The original template account can be used to supply default values to the objects, which are created with it, by assigning names to its members:

account.name = "No Name";
account.balance = 0.0;

Now when creating new accounts without specifying initial names or balances the defaults will be applied instead:

var acnt3 = new account();

As there are no name or balance specified, the account someAccount is created with default values:

acnt3.name => 'No Name';
acnt3.balance => 0;

There is a different method for accessing the elements of an object than the object.name method:

acc01[0] => 'John Doe';
acc01[1] => 123

Although the second method of treating the object like an indexed array is slightly more speed efficient, it is recommended to use the normal object.name method as it is mor descriptive.

Objects created with NomarScript can be treated just like any other objects. They can be assigned to variables or be elements in an array:

var thisAccount = acc01;

or

var manyAccounts = [acc01, acc02, acnt3];

Now it is possible to iterate through several object:

for(var acc in manyAccounts)
    {
    writeln(acc.name, acc.balance);
    }

This would write a report about account namesd and their balances.


Methods

Objects may have special user defined functions made for them called methods . For the object account previously defined we could create functions deposit() and withdraw() in the following manner:

function deposit(self, amount)
    {
    self.balance += amount;
    }

and for withdraws:

function withdraw(self, amount)
    {
    self.balance += amount;
    }

Now we can write:

var myAccount = new account("John Doe", 0);

myAccount.deposit(1000);
myAccount.withdrawals(150);

The variable self, we used in the definitions of the functions deposit(self, amount) and withdraw(self, amount) automatically refers to the object name before the dot . , in the example the object myAccount.


Creating Graphics

Graphics in Nomar rely on the underlying 2D Graphics technology in Java. The Java 2D Graphics module offers antialiased line drawing and fonts, rotation scaling and transforms of shapes and text. Nomar can draw graphics onto two different media:

 

Graphics in their own window

In this mode Nomar ctreates a special window on the computer where Nomar is running. The window can be titled and sized and serves as a canvas to draw on. This mode is usefull when developing graphics routines interactively and whenever is is necessary to watch graphics output immedeately:

Graph.createwindow("My Graphics", 300, 200);
Graph.setColor(255, 0, 0);
Graph.fillOval(50,50,200,100);

The example will create a window with the title My Graphics and a size of 300 by 200 pixels. Note, that covering the window and uncovering the window (e.h. by moving it to the margin of the monitor) will detroy the graphics. To avoid this the paint rountines can be put into a special symbol name Graph.paint:

Graph.paint :=
    {
    Graph.setColor(255, 0, 0);
    Graph.fillOval(50,50,200,100);
    }

Now, whenever the window is covered and uncovered the Graph.paint routine will be automatically called and redraw the graphics on the window.

 

Graphics in an image file

In this mode Nomar creates a PNG (Portable Network Graphics) image file. This fileformat can be handled by most Web browsers and image graphics manipulating programs. PNG is a free and open format standard not restricted by Licenses (as GIF) and combining the advantages of GIF and JPG image files. This mode is usefull whe creating graphic files on the fly for displaying on web pages, when running Nomar as a HTTP server.

Note, that the underlying OS must have a graphics context available for the user running Nomar. E.g. on UNIX/Linux Nomar should be started in a shell which can start programs using the OS's X-windowing system and library. This is may not be the case when Nomar is initiated from a telnet console or Nomar is started before the OS's X-window system is running.

When creating image files with Nomar all panting routines should be assigned to a specific symbol:

myGraphicsDemo :=
    {
    Graph.setColor(255, 0, 0);
    Graph.fillOval(50,50,200,100);
    }

Graph.createImage("/images/myImage.png", 300,200, myGraphicsDemo);

The example creates an image file called myImage.png in the directory images on the current drive. As soon as the function Graph.createImage() is evaluated an image with the specified dimensions of 300 by 200 pixels is drawn and saved in an image file.

 

The coordinate system

By default the koordinate system for drawing has it's origin at the top left corner of the graphics canvas, which could be the window created using Graph.createWindow() or the image created using Graph.createImage(). By default koordinates of points and width and height of shapes are measured in pixels. If a window is created using Graph.createWindow('aTitle', 300, 200), then by default the X,Y koordinates 0,0 would specify the top left corner and the koordinates 300,200 the bottomroght corener of the canvas.

The functions Graph.scale() and Graph.translate() can be used to scale koordinates and move the origin of the koordinate system. After using Graph.scale() each koordinate in Graph functions will be multiplied by the scale values gicen for X and Y, e.g.:

Graph.createWindow('scale demo', 300, 200);
Graph.setColor(255, 0, 0); // red
Graph.fillRect(0, 0, 300, 200);

Graph.scale(3, 2);
Graph.setColor(0, 255, 0); // green
Graph.fillrect(0, 0, 50, 50);

Graph.translate(50, 50);
Graph.setColor(0, 0, 255); // blue
Graph.fillRect(0, 0, 50, 50);

While the red rectangle will fill the entire window the green rectangle will extend from the top left corner only to the middle of the window. The function Graph.scale(3, 2) scaled the coordinate system to 0,0 - 100, 100 from 0,0, - 300,200.

The third blue rectangle extends from the middle of the window to the right, bottom corner. The function Graph.translate(50, 50) has moved the coordinate origin 50 units to the right and bottom. The coordinate system now extends from -50, -50 at the top left corner to 50,50 at the right bottom corner. Stiil the horizontal and vertical space is divided into 100 units.

Bteween the size of the window in pixels, the number of units and the scaling factors exist the following relation:

scale = pixels / units

For a 100 units along the graphics canvas's X coordinate in a window of 300 pixels wide we would need a scale factor of 300/100 = 3 for the X-axis and a scale factor of 200/100 = 2 for the Y-axis.

Note, that Graph.scale() and Graph.translate() work cumulative when used repeatedly. Graph.reset() can be used to set the defaults of 1,1 for the scale and 0,0 for the top left corner.

For more complex coordinate space mappings see Graph.rotate() and Graph.transform(). Graph.rotate() can also produve rotated text. Graph.transform() can be used to produce nonlinear (curved) mappings of the coordinate space.

 

Colors

Colors are specified using a RGB (Red, Green, Blue) 24bit color space and model. For each of the three components the value can vary between 0 and 255, yielding a total of 16,777,216 (~16 million) colors.

Two different type of colors can be specified: Graph.setBackground() is used to set the background color of the canvas, Graph.setColor() is used to set the color for the next draw or fill command for shapes and for text drawing. Note, that the default background color in a window is always white (R,G,B = 255,255,255) but should be explicetely set when creating image files.

 

Fonts

The availability of fonts for drawing text depends on the OS underlying the Java runtime environment and on the specifics of the runtime environment itself. The function Graph.getFonts() can be used to retrive an array of names of all available fonts on the system:

Graph.getFonts() => ['Default', 'Dialog','Times New']

The list may have very few or many dozens of entries. In Nomar fonts can be specified in a different point size and style (normal, bold, italic).

 


 

Function Reference

 

The Function Reference presents all functions in tabular form and ordered in different groups. A second section contains all functions in alphabetical order and with detailed explanations of parameters and an example how to use it.

Abbreviations used in the reference

The following section describes abbreviations and terms used in the reference section.

variant

An number, string or array or an expression resulting in a number, string or array

number

A 64bit IEEE 754 double floating point number with or without decimal point

string

A sequence of characters or an expression resulting in a sequence of text characters.

boolean

The boolean constants true or false or a boolean expression resulting in true or false.

array

An array of any of the mentioned data types or an expression resulting in an array.

index

A one dimensional used as an index into another array or an expression resulting in an index.

function

Function is a user-defined function or functionMacro i.e.

expression

Expression is an aggregate of data types and operators or functions into a form, which can be evaluated by the interpreter.

block

block is a sequence of expression of expressions, function or variable declarations enclosed in curly braces {,}.

reference

This is an array reference or a variable reference as used when doing assignments, i.e.:

symbol

A variable name which can hold a variant and an array of properties. Variable names start with a letter followed by numbers, characters or the special characters _, @, $ . There is no limitation for the length of a symbol.

[,]

If a parameter typename appears in brackets [,], that parameter is optional. For example:

array, [index]

this means that the function may take optionally a second parameter of type index. An index is just an array used for indexing.

|

The vertical bar | between parameters tells that any of the two type parameters before and after it can be used as an argument. For example:

string | number

...

Three dots ... indicate that the preceding parameter may be repeated one or more times.

number, ...

indicates that one or more number parameters are required.

num, str and exp

These are just abbreviations used in the reference part of the manual to abbreviate number, string and expression.

 

 

Core functions and reserved words

Functions carrying a '*' in the last column do array abstraction on all or some of their parameters. Parameters may be arrays of noted types.

Name Parameters Description  
!, !=, <, <=, <>, ==, >, >=,
&&, ||,

variant-1, variant-2

or

variant-1

Logical operators for comparing numbers strings and boolean data or any other expression in a boolean context. *
% number-1, number-2 Returns the modulo number-1 divided by number-2. *
+, -, *, /

number-1, number-2

Arithmetic functions, + also concatenates strings. *
:= reference, variant Non-evaluating assignment (macro assignment).  
= reference, variant Normal assignment.  
+=, -=, *=, /= reference, number Assignment with arithmetic operation.  
and variant-1, variant-2 Logical operator equal to &&. *
apply function, array Applies a function to an array of parameters. *
args
-
Returns an array of command line parameters.  
array number, [variant] Creates and array and initializes it.  
break
-
Breaks out of a for, switch or while block.  
case
-
Case label in switch statement.  
char number Returns the string representation of a character. *
collectGarbage
-
Forces garbage collection in the Java VM.  
cond boolean, expression-1, expression-2 Works like if but evaluates both expressions and does array abstraction. *
contains string-1, string-2 Checks for containment of string-2 in string-1. *
continue
-
Jumps to the top of while or for loop.  
count
array
Counts all boolean true elements in an array. *
date number [number, number, string] Format a textual date/time from a number of seconds since epoch. Optionally date/time styles and a time zone can be specified. *
end
-
Ends execution of a script.  
endsWith string-1, string-2 Checks if string-1 ends with string-2. *
eval expression Evaluates an expression (used in macros). *
evalString string Parses/compiles/evaluates script source. *
evalTagged string Evaluates all portions of a string enclosed in <%,%> tags for embedding scripts in HTML. *
exec string Launch a host OS specific application *
exit number Exits a script and returns a result code.  
fileLength string Returns the size of a file. *
fileList string Returns array of filenames in directory spec in string *
filter array-1, array-2 Filters an array using an array of boolean values.  
first array, [index] Accesses the first element in an array. *
flatten array Reformats a multidimensional array in to a vector  
for see also For loop for(...) {...} iterates through a block of statements .  
for in see also For in loop    
format number, string Format a number for output. *
function see also Functions Declares a user defined function.  
functionMacro see also Macros Declares a user defined function macro.  
getDimensions array Returns the number of dimensions in an array.  
getIndex array Returns the primary index of an array.  
getProperty symbol Returns the property list of a symbol. *
if see also if and if else Procedural if(...) {...} else {...} changes path of execution.  
index array Translates a boolean vector into subscript positions..  
indexOf string-1, string-2 Returns position of string-2 in string-1. *
insert array, variant, number Inserts a an element into an array.  
isDirectory string Checks if a file system entry is a directory. *
isFile string Checks if a file system entry exists. *
isIndexed array Checks if an array is indexed.  
isInfinite number Checks if a number is infinite.  
isNaN number Checks is a number is valid.  
isUndefined variant Checks for nil  
join array, [string], [index] Concatenates and array of strings inserting string. *
last array, [index] Returns the last element of an array. *
lastError
-
Returns the last occurred error and line no..  
lastIndexOf string-1, string-2 Returns last position of string-2 in string-1. *
length string Returns the length of a string. *
load string Loads/runs a script from a URL or file system. *
lookupIP string Returns hostname of IP string. *
match string-1, string-2 Pattern string match producing arrays. *
max array, [index] Returns the maximum value from an array of numbers *
min array, [index] Returns the minimum value from an array of numbers. *
module symbol Creates or switches to a different name space (module).  
new function Creates a new object instance of a function object.  
not variant Reverses the boolean value of its argument (same as ! ). *
numberFormat string Sets the default format pattern for numbers.  
or varian-1, variant-2 Returns the boolean value of variant-1 or'd to variant-2. *
parseDate string Parses a date-time string of standrad UTC format and returns a UTC number value (seconds since 1-1-1970). *
parseDateJDBC string Parses a date-time string as formatted in database access and returns a UTC number value (seconds since 1-1-1970). *
parseFloat string Parses a floating point nuber string. *
parseInt string, [number] Parses a string and returns a value, optionally a number base can be specified. *
path
-
Returns the current file system path.  
pop array Pops the last position of an array (shortens the array).  
push array, variant Appends a variant to the end of the array (making the array longer) .  
quit
-
Quits the NomarScript interpreter.  
random [number] Returns an equally distributed value or array of values.  
register string Registers a new function supplied by an sxternal Java class.  
remove array, number Removes an element from an array.  
rename string-1, string-2 Renames file from string-1 to string-2. *
replace string-1, string-2, string-3 Replaces all ocurrences of string-2 in string-1 with string-3. *
resolveIP string Returns the host name of an IP number string of the dotted form #.#.#.# *
return
-
Returns from a function call.  
resize array, [variant] Resizes an array to grown indices and optionally initializes.  
reverse array, [index] Returns an array with all elements in reverse order. *
seed number Starts the random generator random() with a new sequence.  
sequence number-1, number-2, [number-3] Generates a sequence of numbers from number-1 to and including number-2 and an optional step-size number-3;  
setDimensions array, number only used for debugging, will go away  
setIndex array, index only used for debugging, will go away  
setProperty symbol, array Provides a symbol (ie. variable) with a property table.  
size variant Returns the number of elements in an array  
sort array, [index, array-number] Sorts a one or two dimensional array of numbers or strings over multiple columns (offset)  
split string-1,[string-2] Splits a string-1 into elements separated by a string-2, returns an array of strings. *
startsWith string-1, string-2 Checks if a string-1 starts with string-2. *
string variant Returns the string representation of variant.  
substring number-1, [number-2] Extracts a string starting at position number-2 and length number-2 . *
sum array, [index] Calculates the sum of an array of values. *
switch
<see text>
switch() {...} statement changes path of execution  
symbols symbol Returns all symbols in a name space, which may be a function or module.  
table index, [index ....], variant] Constructs an array dimensioned by one or more indices index and initialized by variant.  
systemTime
-
Returns the number of seconds since epoc (1-1-1970)  
toLowerCase string Converts a string to lowercase. *
toString variant Converts contents of variant to a string. *
toUpperCase string Converts a string to uppercase. *
trim string Trims leading and trailing whitespace from a string. *
typeOf variant Returns a type string from a variant.  
unlink string Deletes a file from the file system. *
urlRead string

Reads from a URL or local filesystem or network file system, currently the protocols HTTP, FTP and FILE are supported In case of HTTP URLs and depending on the format, HTTP GET requests can be made, resulting in function calls if they go to another NomarScript compute server or resulting in CGI request if they go to a traditional web server.

 
urlReadParallel array Same as urlRead but threaded in parallel, function returns when all threads are completed.  
urlWrite string Same as urlRead but for writing.  
var symbol, [symbol ...] Declares variables.  
versionName
-
Returns the version name and number of NomarScript.  
wait number Waits a number of milli seconds.  
while <see text> while(...) {...} conditional loop  
windowFont string Sets the font style and size of the NomarScript window console.  
write variant [variant ...] Write arguments to the currrent output device.  
writeln variant [variant ...] Write arguments to the currrent output device with a OS specific line terminator .  

 

Math functions

Following the JavaScript conventions the following functions are kept in a separate name space Math. When using these functions they must be prefixed with Math, i.e.: Math.sqrt(x).

abs number Returns the absolute value of a number. *
acos number Returns the arc cosine of an angle, in the range of 0.0 through pi. *
asin number Returns the arc sine of an angle number, in the range of -pi/2 through pi/2. *
atan number Returns the arc tangent of an angle number, in the range of -pi/2 through pi/2. *
beta number-1, number-2 Returns the beta function of values number-1 and number-2 *
ceil number Returns the smallest (closest to negative infinity) number that is not less than number and is equal to a mathematical integer. *
combinations num-k, num-n calculates the number combinations of k items out of n. *
cos number Returns the trigonometric cosine of an angle. *
critChi2 num-p, num-df Calculates critical Chi-square from probability p and degrees of freedom.  
cumNormal num-x, [num-mean, num-stddev] Returns the cumulative density for a normal distribution. Mean and stdev are 0.0 and 1.0 by default. *
E
-
returns the constant e = 2.718... *
exp number Returns the exponential number e (i.e., 2.718...) raised to the power of number. *
floor number Returns the largest (closest to positive infinity) number that is not greater than number and is equal to a mathematical integer. *
gamma number Returns the gamma function of number. *
gammaLn number Returns the log gamma function of number. *
log number Returns the natural logarithm (base e) of number. *
permutations num-k, num-n calculates the number permutations of k items out of n. *
PI
-
Returns the constant pi = 3.141... *
pow number-1, number-2 Returns of value of number-1 raised to the power of number-2. *
probZ num-z Calculates cumulated probability of normal distributed z. *
probChi2 num-chi2, num-df calculates cumulated probability of Chi-square for degrees of freedom df.  
round number Returns the closest long to number. *
sin number Returns the trigonometric sine of an angle. *
sqrt number Returns the square root of number. *
tan number Returns the trigonometric tangent of an angle. *
toDegrees number Converts an angle measured in number radians to the equivalent angle measured in degrees. *
toRadians number Converts an angle measured in number degrees to the equivalent angle measured in radians. *

 

Functions for modelling and simulating

area array, index, [number-1, number-2] Calculates the area (integral) over and index in array of increasing numbers. A lower and higher limit of index are optional. *
argmax array, index Returns the corresponding value of index for which the value in array is maximum. For a minimum use -array. *
beta number-1, number-2, [number-low, number-high] Returns the beta distribution of numbers-1 and numbers-2. Optionally a low and high limit may be specified. *
bernoulli number-prob Creates a discrete probability distribution with number-prob of results 1 and (1 - number-prob) of result 0. *
chancedist array-1, array-2, index Generates Samplesize samples of elements in array-2 as of probabilities given in array-1 both indexed by index. *
concat array-1, array-2, [index-1,index-2,index-new] Appends array-2 to array-1 along indexes index-1 and index-2 returning a new array indexed by index-new *
cumdist array-probs, array-data, index Specifies a continuos probability distribution by an array of cumulative probabilities of outcomes in array-data. *
cumproduct array, index Returns an array of successive products along index. *
cumulate array | number, index Returns a successive accumulated array or number along index. *
dynamic variant-1,[ variant-2...variant-n], expression Evaluates expression for each element of TimeIndex initializing the first instance(s) with variant-1 ... (see also Self) *
fractiles array Specifies a continuous distribution by an array of evenly spaced fractiles for an uncertain quantity x in a one dimensional array. Uses interpolation for values between the specified fractiles.  
frequency array-1, array-2 Counts elements of array-2 in array-1. *
getfract array, number-prob Returns an estimate of the fractile in number-prob. Such that the value has a probability of number-prob beeing less than the value. *
indexNames array Returns a list of index names of array or the array name if self indexed *
integrate array, index Returns an array of integrated values of array along index. *
linearinterp number, array-x, array-fx, index Linearly interpolates the value of number by the function described by array-x and array-fx indexed by index. array-fx. *
lognormal num-median, num-gstdev Returns an array of lognormal distributed numbers  
MDArrayToTable array, index-row, index-col Tranforms a multi-dimensional array into a two-dimensional array indexed by index_row and index_col  
MDTable array, index-row, index-col, array-vars, string-congl, var-missing Transforms a two dimensional table into a multidimensional table as a reverse operation to MDArrayToTable.  
normal number-mean, number-sdev Returns a number or an array normal distributed numbers with mean number-mean and standard deviation number-sdev. *
normalize array, index Returns an array that is normalized, so the area across index is 1 *
probability array-boolean Returns the probability of of an element in array-boolean having the value true. *
probdist array-probs, array-data, index Specifies a continuous probability distribution as an array of probability density values. *
product array, index Returns the product of all elements in array along index *
rank array, index Returns an array of its rank values or array across index. *
RunIndex
-
System variable containing a sequence of numbers from 1 to Samplesize. All distribution generating functions are index by this index.  
SampleSize
-
System variable containing the number of samples to be generated by probabilistic distributions.  
Self
-
Holds an array of evaluated expressions in dynamic() along TimeIndex  
setSampleSize number Sets the system variables SampleSize and RunIndex.  
setTimeIndex array Sets up the TimeIndex vector for iterating with dynamic.  
sortindex array, [index] Returns elements of index in order of sorted array. *
stepinterp number, array-x, array-fx, index Interpolates to the smallest value equal or greater number. *
subindex array, variant, index Returns the corresponding index value of variant in array or nil if not found. *
Time   System variable containing current position into TimeIndex  
TimeIndex
-
System variable contains elements along time for dynamic() simulations  
triangular number-min, number-mode, number-max Returns a triangular distribution of numbers between number-min, number-max and a modal value at number-mode. *
uncumulate array, index, [number] Returns an uncumulated array optionally the first value can be set to a different value than the first element of array. *
uniform number-min, number-max Returns a uniform distribution of number between number-min and number-max. *
unique array, [index] Returns a subset of index such that the slice of array along index is unique.  
       

 

Statistical functions

cluster array-x, num-clust, num-iter, sym-centroids, sym-ssqs, sym-clustIdx, sym-criteria Calculates a KMEANS cluster analysis over the data points in array-x for num-clust clusters with maximum num-iter iteration. results are in the variable symbols for centroids, intra-cluster SSQs and D-criteria.  
correl array-x, array-y, [index] Return Spearman's r between array-x and array-y along optional index. *
kurtosis array-x, index Returns the kurtosis of a data distribution in array-x. Optionally an index over which to calculate can be specified. *
mean array-x, [index] Returns the average value from an array-x of numbers. Optionally an index over which to calculate can be specified. *
median array-x, [index] Returns the median value from araay-x of numbers. *
rankcorrel array-x, array-y, [index] Returns Spearman's rank correlation between vectors in array-x and array-y optionally indexed by index. *
skewness array-x, [index]   *
statistics array-x, [index] Returns an array of basics statistics and moments of a data distribution in array-x. Optionally and index can be specified. Returns: min, max, mean, median, variance, standard deviation, skewness, kurtosis. *
sdeviation array-x, [index] Returns the standard deviation of a data distribution in array-x. Optionally an index over which to calculate can be specified. *
variance array-x, [index] Returns the variance of a data distribution in array-x. Optionally an index over which to calculate can be specified. *

 

Financial functions

cumipmt num-rate, num-nper, num-pv, num-start, num-end, [num-type] Returns the cumulative interest paid on an annuitiy, between and including start - and end periods. *
cumprinc num-rate, num-nper, num-pv, num-start, num-end, [num-type] Returns the cumulative principal paid on an annuitiy, between and including start - and end periods. *
fv num-rate, num-nper, num-pmt, num-pv, [num-type] Returns the future value of an annuity investment with constant payments and fixed interest rates. *
ipmt num-rate, num-per, num-nper, num-pv, [num-fv, num-type] Returns the interest portion of a payment on an annuity. *
irr array-values, index, num-guess Calculates the internal rate of return of a series of periodic payments (negative values) and inflows (positive values). *
nper num-rate, num-pmt, num-pv, num-fv, [num-type] Returns the number of periods of an annuity. *
npv array-values, [index], num-rate Calculates the net-present value of a cashflow of equally spaced periods over optional index with discount rate in num-rate. *
pmt num-rate, num-per, num-nper, num-pv, [num-fv, num-type] Returns the payment per period for an annuity with constant payments and fixed interest. *
ppmt num-rate, num-per, num-nper, num-pv, num-fv, [num-type] Returns the interest portion of a payment on an annuity. *
pv num-rate, num-nper, num-pmt, [num-fv, num-type] Returns the present value of an annuity. *
rate num-nper, num-pmt, num-pv, [num-fv, num-type, num-guess] Returns the interest rate for an annuity. *
xirr array-values, array-dates, index, [num-guess] Returns the annual internal rate of return for a series of payments (negative values) and inflows (positive values) that on occur on non-periodic (array-dates) intervals. *
xnpv num-rate, array-values, array-dates, index Retruns the net present value of a non-periodic cash flow. *

 

Graphics functions

Graphics functions are kept in a separate name space called Graph.

clearRect num-X, num-Y, num-width, num-height Clear rectangle to background color.  
closeWindow
-
Close window.  
createImage string, num-width, num-height, symbol Create an image file  
createWindow string, num-width, num-height Create a window for graphics.  
draw3DRect num-X, num-Y, num-width, num-height, boolean Draw a 3D rectangle  
drawArc num-X, num-Y, num-width, num-height, num-st, num-arc Draw an arc.  
drawImage string, num-X, num-Y, num-width, num-height Draw an image file on the graphics window.  
drawLine num-X1, num-Y1, num-X2, num-Y2 Draw a line between two points.  
drawOval num-X, num-Y, num-width, num-height Draw an oval in enclosing rectangle.  
drawRect num-X, num-Y, num-width, num-height Draw a rectangle.  
drawRoundRect num-X, num-Y, num-width, num-height, num-XS, num-YS Draw rectangle with round corners.  
drawText string, num-X, num-Y Draw text at position.  
fill3DRect num-X, num-Y, num-width, num-height, boolean Fill a 3D rectangle with current color.  
fillArc num-X, num-Y, num-width, num-height, num-st, num-arc Fill and arc with current color.  
fillOval num-X, num-Y, num-width, num-height Fill an oval with current color.  
fillRect num-X, num-Y, num-width, num-height Fill an rectangle with current color.  
fillRoundRect num-X, num-Y, num-width, num-height, num-XS, num-YS Fill a round rectangle with current color.  
getFonts
-
Get an array of all available font names.  
reset
-
Reset graphics context to defaults.  
rotate num-angle Rotate all operations by angle.  
scale num-X, num-Y Scale the coordinate system.  
setBackground number-R, number-G, number-B Set the background color.  
setColor number-R, number-G, number-B Set color for drawing and filling.  
setFont string, num-style, num-size Set the current font for drawing text.  
setStroke num-width, num-cap, num-join Set line width and style for drawing.  
setTransform num-c00, num-c01, num-c02, num-c10, num-c11, num-c12 Set cosine transform parameters.  
setXORMode num-mask Set graph combination mask.  
translate num-X, num-Y Move coordinate system origin.  

 

Database functions

These functions for JDBC/ODBC access are kept in a specal module named DB.

close
-
Close open database  
connect string-table, [string-user], [string-pass] Connect to an ODBC database server.  
driver string Load a ODBC driver  
lastError
-
Return last DB error  
query string-SQL, [symbol-row, symbol-col] Make a SQL - query request. optionally creates indices in the variables specified for symbol-row and symbol-col.  
update string-SQL Make a SQL - update, create or delete, etc. request  

 

XML functions

These functions are used to translate XML into Nomar array structures or translate XML structures into XML.

createDocument array-xml-node Creates a string containing XML.
getAttribute array-xml-node, string-name Gets the value for a given attribute from an XML node.
getAttributeNames array-xml-node Returns an array of all attribute names in a XML node.
getChildren array-xml-node Get an array of all children or a XML node.
getText array-xml-node Gets the text from a XML text node or comment node.
lastError
-
Returns a string with a description of the last error when parsing a XML document.
parseDocument string-xml-node Translates a string conatining XML into a Nomar array structure.

 

Mail functions

These functions implement and POP3 client for sending and receiving e-mail. Functions are kept in a module named Mail.

check string-usr, string-passw, string-server Return mail status.  
delete string-usr, string-passw, string-server, array Delete mail entries.  
headers string-usr, string-passw, string-server, array Getmail headers.  
lastError
-
Return last mail API error.  
receive

string-usr, string-passw, string-server array

Receive mails from POP3 server.  
send string-from, string-to, string-subj, string-body Send mail vial SMTP.  

 

Proxy server functions

These functions allow NomarScript to act as a proxy server delegating and load balancing client requests to multiple NomarScript compute servers. All functions are kept in a module Proxy.

add num-proxy-port Add proxy service port.  
addService num-proxy, str-hostname, num-hostname-port Add hostname-service to proxy port.  
balance number-port, boolean Set load balancing or overflow mode.  
log boolean Set logging true/false to console  
remove number-port Remove a proxy service port.  
removeService str-service-url, num-servivce-port Remove service from proxy port.  
start number-proxy-port Start listening on proxy port.  
status [number-proxy-port] Report status of one or all proxies.  
timeout number-milli-sec Set timeout for fallen connections.  

 

HTTP read only variables and functions

These variables are filled in with data from HTTP client requests. Data can be used to write logs or modify the script behavior in any other way. Use a prefix of HTTP to address these variables. Other less volatile HTTP related variables can be set or read in the system properites.

clientIP
-
Return client's IP.  
clientName
-
Return client's hostname.  
cookies
-
Return contents of HTTP - 'Cookies:' header  
referer
-
Return referers URL.  
hostIP
-
Returns the net device IP on multi-honed servers.  
userAgent
-
Return client type string.  
setHeader string set a HTTP response header  

 

Servlet functions

All servlet functions are part of a module called Servlet use the prefix Servlet when using these functions.

Header management
getContent
-
   
getContentLength
-
   
getContentType
-
   
getHeader string-name    
getHeaderNames      
getMethod
-
   
getRemoteAddress
-
   
getRemodeHost
-
   
getRemoteUser
-
   
setHeader string-name, string-value    
setIntHeader string-name, number-value    
Request
getParameter string-name    
getParameterNames
-
   
getServletName
-
   
Session management
-
   
getSession
-
   
getSessionCreationTime
-
   
setSessionInvalid
-
   
SetSessionInvalidInterval number-seconds    
Cookie management
getCookies
-
   
getCookieMaxAge string-name    
getCookiePath string-name    
getCookieValue string-name    
setCookieMaxAge string-name, number-seconds    
setCookiePath string-name, string-path    
setCookieValue string-name    

 

System functions and variables

 

The following symbols are conatined in the module System. errorHandler can be used to set up uer defined error handlers. setProperty and getProperty are used to set system wide properties as those mentioned in the next table.

errorHandler symbol Define user error handler.  
getProperty [string] Get a system property  
setProperty string-key, string-value Set a system property  

 

System properties

Most of the system properties are OS and Java environment settings like Java VM or OS Platform specific parameters. A few system properties are introduced by NomarScript and set to default values at startup of the interpreter. These are the following:

Property Default setting Description
http.acceptIP <none specified (the empty string)> Only IP numbers starting with the specified in this property will be accepted. All others return HTTP error 404
http.debug false The setting true would force a complete log of transmissions to standard out (console)
http.defaultPage index.htm The default page delivered when no page is specified.
http.directory <none specified (the empty string)> A string for the current directory, which is normally the startup directory of NomarScript. This should be set to the root of the web directory i.e.: /www
http.port  80 Default HTTP listen port.
http.resolveIP false The setting true would DNS resolve client IP's for access through the variable HTTP.clientIP and set HTTP.clientName
html.scriptStartTag  <% Tag used to start a script in a HTML page.
html.scriptEndTag  %> Tag used to finish a script in a HTML page.
mail.host <none specified (the empty string)> Default SMTP mail host name i.e.: mail.mydomain.com.
telnet.port  23 Default Telnet port for remote console operation of NomarScript.

 


 

Function alphabetical reference

 

!, !=, <, <=, <>, ==, >, >=, &&, ||

Logical and comparitive operators are used most of the time in logical expressions controlling program flow. A logical expressions always returns a boolean value of true or false.

Operator precedence in complex logical expressions follows other programming languages. All logical and comparitive operators have a lower precedence than the arithmetik operators +,-,*,/. The logical operators && (or and) and || (or or) have a lower precedence than the comparitive operators. This helps building complex logical expressions without too much parenthesis, e.g.:

if(a + b < x * y and q - p >= k/l)
     {
     ...
     };

is the same as:

if(((a + b) < (x * y)) and ((q - p) >= (k/l)))
     {
     ...
     };

The operators !, &&, || have equivalents verbose representations with not, and and or. While !, &&, and || are compatible with logic operators in other programming languages not, and and or make for more readable source code.

In a logical context nil returns false all values not nil return true. The empty array is false in a boolean context.

Like all other operators logical operators can work over arrays:

3 > [1,2,3,4,5,6] => [true, true, false, false, false, false]


 

%

The modulo operation returns the remainder of the division of two numbers, and also works on floating point numbers e.g.:

10 % 3 => 1

4.5 % 2 => 0.500

10.5 % 3.3 => 0.600

5 % [1, 2, 3, 4, 5] => [0, 1, 2, 1, 0]


 

+, -, *, /

All arithmetik operators work on numbers, except for +, which also works as a string concatenation operator. * and / have precedence over + and - in complex expressions:

3 * 4 + 2 * 5 => 22

Arithmetik operators can work on arrays:

1 + [1, 2, 3, 4, 5] => [2, 3, 4, 5, 6]

String concatenation uses also the + operator:

'a' + 'b' + 'c' => 'abc'

'#' + ['a', 'b', 'c'] => ['-a', '-b', '-c']

If + is interpreted as a numerical add or a string concatenator depends on the context:

1 + 'a' => NaN

'a' + 1 => 'a1'

The data type to the left of the + operator defines if a numerical or string operation is performed.


:=

This non-evaluating assign operator stores the expression on the right side of it in to the variable on the left side. While the normal = assign operator would evaluate the right expression before assigning it, := will not evaluate the expression until evaluation is forced using the eval function or until another function depending on the current := expression is evaluated:

var x = 3 + 4;

x => 7

but:

var x := 3 + 4;

x => (3 + 4)

x.eval() => 7

if an expression is evaluated, which depends on x then x will get evaluated too:

var y := x + 3;

y => (x+3)

y.eval() => 10

Note, that both types of assignments should not be mixed:

y = x + 3 => NaN

instead write:

y = x.eval() + 3;

or y = eval(x) + 3;

Assignment with := can also be done to arrays:

var x = [0, 0 ,0];

x[0] := 3 + 4;

x => [(3+4), 0, 0]

Note, that assignments are not allowed to index position independent array references, only to absolute array references.


 

=

The assignment operator evaluates it's right operand and assigns it to a variable or an array reference:

var x = 3 + 4;

x => 7

var ar = [1,2,3,4];

ar[1] = 'hello';

ar => [1, 'hello', 3, 4]

Note, that assignments are not allowed to index position independent array references, only to absolute array references.


+=, -=, *=, /=

An assignment can be combined with an arithmetik operation:

var x = 10;

x *= 3;

x => 20;

In loops incrementing by one is often used:

for(var i = 0; i < 10; i += 1)
    write(i);

=> 0123456789

Note, that the ++ and -- operators, popular in other programming languages, are not available in NomarSript.


and

The and operator is equivalent to the && operator.


apply (functor, array)

Applies a built in function or user defined function to an array of parameters:

apply(contains, ['programming is fun', 'fun']) => true

is equivalent to:

contains('programming is fun', 'fun') => true

and:

apply(contains, ['abc',['a','b','x']]) => [true, true, false]

is equivalent to

contains('abc', ['a', 'b', 'x']) => [true, true, false]

Note that apply only array-abstracts on the second parameter, not on the first.


args ()

If NomarScript has been started in console/shell or console/window mode (see Useres Manual about Run modes ) the args() function returns an array with all command line parameters:

java -jar gc.jar myProg x y z

args() => ['myProg', 'x', 'y', 'z']

Note, that NomarScript treats the first command line parameter, which does not start with a hyphen - as a source file to be loaded. args() can be used when using NomarScript to write shell scripts or commandline utilities.


array (number-size, [ variant ])

The function array() is used to create and initialize arrays. The first parameter number-size defines the number of elements in the array the second optional parameter variant specifies an initializer. When no initializer is specified, nil will be put into every position in the array created.

var myArray = array(5);

myArray => [nil, nil, nil, nil, nil]

var myArray = array(6, 0);

myArray => [0, 0, 0, 0, 0, 0]

For creating indexed arrays use table.


break

Breaks out of a for or while loop:

for(var i = 0; i < 10; i += 1)
    {
    if(i == 5) break;
    write(i);
    }

=> 1234

See also the section in Users Manual about Program flow.


case

Used to mark sections in a switch statement:

switch(x)
  {
  case 1:
    doThis();
    break;
  case 2:
    doThat();
    break;
  case 3:
    doOther();
    break;
  default:
    someThingDifferent();
  }

See also section switch.


char (number)

Returns the string presentation of a ASCII character code in number:

char(65) => 'A'


collectGarbage ()

Collects unused memory in the Java virtual machine. Normally there should be no need for using this function, but situations may occur where it is useful to force garbage collection before the Java VM decides to do so. For example to get rid of a huge array, which will not be used any more:

var huge = array(1000000, nil);
... // do work with huge
huge = nil;
collectGarbage();

After huge is dereferenced setting it to nil the Java VM would collect the unused memory eventually, but can be forced to do so using collectGarbage().


 

cond (boolean, variant-then, variant-else)

Evaluates the variant-then and variant-else and returns values depending on the outcome of a condition in boolean. cond works similar to if  but evaluates both the then and else parts and also can work on arrays:

var x = [1, 2, 3, 4, 5, 6]

cond(x > 3, 'big', 'small') => ['small', 'small', 'small', 'big', 'big', 'big']

cond(x > 3, 'big', x) => [1, 2, 3, 'big', 'big', 'big']

cond(x == 2 or x == 4, x * 100, x) => [1, 200, 3, 400, 5, 6]


contains (string-1, string-2)

Checks for occurrence of string-2 in string-1:

contains('Nov-30-1947', '19') => true

contains('Nov-30-1947', [1,2,3,4] => [true, false, true, true]


continue

Interrupts a for or while statement. See also the Users Manual chapter: break and continue .

for(var i = 0; i < 10; i += 1)
  {
  if(i == 2 or i == 4) continue;
  write(i);
  }

=> 1356789


count (array)

Counts all elements in an array, which not evaluate to a boolean false.

var x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

count(x > 6) => 4;

var i = ['a', 'b', 'c'];
var j = ['x', 'y'];
var x = table(i, j, [[1, 2], [3, 4], [5, 6]]);

count(x > 3) => [0, 1, 2]


date (number, [num-style-date, num-style-time, str-timezone])

Returns a date string from the number of milli seconds passed since the UNIX UTC epoch (1-1-1970 Greenwich Time).

date(systemTime()) => 'Nov 7, 2000 11:05:27 AM'

date(0) => 'Dec 31, 1969 4:00:00 PM' // when executed in California USA

date(0) => 'Jan 1, 1970 12:00:00 AM' // when executed in Greenwich UK

Optionally syle constants (0 to 3) can be specifield for the date and time parts and a time zone string can be specified.

date(0, 0, 0, "PST") => 'Wednesday, December 31, 1969 4:00:00 PM PST'
date(0, 0, 0, "GMT") => 'Thursday, January 1, 1970 12:00:00 AM GMT'
date(0, 1, 0, "GMT") => 'January 1, 1970 12:00:00 AM GMT'
date(0, 2, 0, "GMT") => 'Jan 1, 1970 12:00:00 AM GMT'
date(0, 3, 0, "GMT") => '1/1/70 12:00:00 AM GMT'
date(0, 3, 2, "GMT") => '1/1/70 12:00:00 AM'
date(0, 3, 3, "GMT") => '1/1/70 12:00 AM'

The first example returns the current time and date, because systemTime() returns the number of milli seconds passed since 1-1-1970. The second example was executed in a time zone 8 hours behind Greenwich Time. In Greenwich this example would produce 'Jan 1, 1970 12:00:00 AM'. See also parseDate() for parsing date strings.

The last example shows the usage of different formats and timezones when formatting dates.


DB.close()

Closes an existing database connection.


DB.connect(string-database, [ string-user, string-password ])

Connects to a database specified in string-database. Optionally a user and password can be specified in string-user and string-password. If the connection is successfully made a string is returned detailing connection/driver specific information. On failure DB.connect retursn nil and DB.lastError() can be used to inspect an error message.

DB.driver();
DB.connect('jdbc:odbc:MyDdata', 'admin', 'secret') =>
  'Driver: JDBC-ODBC Bridge (odbcjt32.dll), Version: 2.0001 (03.50.3428.00)'

Before a database connection can be made a JDBC driver (Java DataBase Connector) has to be loaded using DB.driver(), which loads a Sun JDBC-ODBC bridge by default.


DB.driver([ string-driver ] )

Loads a JDBC driver (Java DataBase Connector) used to make connections to a local or networked database. When string-driver is not specified, the Nomar loods the built in default Sun JDBC-ODBC bridge driver by default. This driver is capable to connect to local or networked databases via ODBC. The local machine must have a compatible driver manager installed (e.g. ODBC applet in MS Windows control panel or UNIX-ODBC on unix and linuz machines.

Alternative drivers in Java class files or Java .jar or .zip archive files can be specified. If a JDBC driver is available, it should be preferred to the built in JDBC-ODBC bridge for better performance. E.g. on Oracle:

DB.driver('oracle.jdbc.driver.OracleDriver')
DB.connect('jdbc:oracle:thin:@adbserver.com:1234:MyDB','johndoe','secret')

The example connects to a Oracle database MyDB on the server machine adbserver.com on port number 1234.

The driver loaded should be in a Java class path accessable by Nomar, which can be any of the following:

- the start up directory of nomar.jar (the driver class is found in a package directory structure inder it)

- an archive file called AlternateJdbcDriver.jar or AlternateJdbcDriver.zip in the start up directory

On UNIX machines AlternateJdbcDriver.jar or AlternateJdbcDriver.zip could be a symbolic link to the real driver Java archives in a different directory than the Nomar start up directory.


DB.lastError()

Returns a string conatining an error message explaining the last database error occurred. Successful DB functions will reset the this string to an empty string. Failing DB functions return nil.


DB.query(string-sql, [ symbol-rows, symbol-columns ])

Executes a SQL query in string-sql on a connected database and returns the resulting rows set in an array. Optionally to previously declared variable symbols can be specified to hold resulting row and column indices (Nomar indexes).

In case no indices are specified, the first row in the resulting array will contain the label strings of the column headers and each subsequent row is indexed on this label row.

When index names in symbol-rows and symbol-columnss are specified than one index is created for the rows, containing the number 1 ... N where N is the numbers of rows in the result set. symbol-columns will contain an index built using the column labels of the result array. In this case the first row of the result set is data and not and not the index labels.

DB.driver();
DB.connect('jdbc:odbc:MyDB');
var rows, cols;
var db = DB.query('select * from persons', rows, cols);
DB.close();

All data in the table persons, whih is part of the database MyDB are selected from the database and returned in the variable db. rows will contain numbers from 1 .. N, the number of rows in persons. cols will contain the column labels of the selected columns in persons and each rows in persons will be indexed on cols.


DB.update(string-sql)

Executes a SQL query in string-sql updating (modifying or deleting) records in the connected database.

DB.driver();
DB.connect('jdbc:odbc:MyDB');

var query = "Insert into persons values ('John Doe', '555-1212')";
DB.update(query);
DB.close();

The example connects to the database MyDB and then inserts a new data record in to the table persons.


end

Ends the execution of a script. Normally Nomar will stop execution of a script when the end of it's source file is reached. end is usefull when the script should stop execution before.


endsWith (string-1, string-2)

Checks if string-2 ends with string-2 and returns a true or false depending on the result.

endsWith('programming', 'g') => true


eval (expression)

Evaluates an expression previously assigned to a variable/symbol using the the special := non-evaluating assignment operator and all the dependent expressions

var x := 3 + 4;

var y := x + 3;

x => (3+4)

y => (x+3)

x.eval() => 7

y.eval() => 10

eval permits writing script code in a pure functional manner without the side effects of the = assignment operator, and where every expressions only gets evaluated when evaluating dependents. See also := assignment.


evalString (string)

Evaluates a string containing NomarScript code and returns the result:

evalString('3 + 4') => 7

This permits dynamic creation of script programs during runtime.


evalTagged (string)

Similar to eval(), but evaluates only portions of code in string, which are tagged by special evaluation tags, which are <% and %> by default.

evalTagged('the result is <% 3 + 4 %> !') => 'the result is 7 !'

evalTagged is used frequently when embedding script code in HTML pages before pushing those pages to a client browser via HTTP:

write(evalTagged(urlLoad("htttp://mysite.com/results.html")));

The last example shows evalTagged() used in server mode running NomarScript. A HTML page 'results.html' is loaded from the website 'mysite.com'. All tagged script portions in that HTML page are evaluated and written back to the client browser using write().

Note, that in case code is contained with parsing or evaluation errors, those error messages are part of the resulting string returned:

evalTagged('<% a + b %>') => 'Parse error: Unknown Identifier: 'a' in line 1 nil'

Like eval() evalTagged() allows the creation of scripts dynamically during runtime, but in a safe un interrupted way in case of errors and embedding script results into toher textual content.

The script tags <% and %> can be changed using System.setProperty('html.scriptStartTag', '...') and System.setProperty('html.scriptEndTag', '...'), where '...' are the start- and end- tags.


exec (string)

Executes a shell command from the host operating system and returns true or false depending on successfull execution.

exec("notepad.exe")

The example would start up the Notepad on on MS Windows platforms.


exit (number)

Exists a script with a result code specified in number.


fileLength (string)

Returns the length of a file specified in string:

fileLength("afile.txt") => 365

fileLength(fileList()) => [2837, 0, 467, 189376, 987]

The first example assumes that afile.txt has a length of 365 bytes. fileLength() is applied to an array of directory names produces by fileList(). The entries with 0 (zero) indicate sub directories.


fileList ([string])

Returns a list of file and directory names in the path specified by string or in the current directory if the string parameter is omitted:

fileList() ;

fileList('/java/gc/docs');

The first example returns a list of file names in the current directory, the second example returns file in the direcory /java/gc/docs on the current drive.


filter (array-1, array-2)

Filters array-1 as of boolean values true and false found in array-2:

var x = [1, 2, 3, 4, 5, 6];

filter(x, x > 3) => [4, 5, 6];

array-1 and array-2 must have one dimension only.


first (array, [index])

Returns the first element in array. When array is multi dimensional an optional index can be specified over which to extract the first elements:

var i = ['a', 'b', 'c'];
var j = ['x', 'y'];
var x = table(i, j, [[1, 2], [3, 4], [5, 6]]);

x.first() => [1, 2]

x.first(i) => [1, 2]

first(x, j) => [1, 3, 5]


flatten (array)

Flattens a multi dimensionsonal array into one dimension:

var i = ['a', 'b', 'c'];
var j = ['x', 'y'];
var x = table(i, j, [[1, 2], [3, 4], [5, 6]]);

x.flatten() => [1, 2, 3, 4, 5, 6]; // equivalent to flatten(x)

In case of a multi dimensional array the inner most index (the last one created) will run fastest.


for

Loops over a statement or a block of statements:

for(var idx = 0; idx < 10; idx += 1)
 
write(idx);

will produce the following output:

0123456789

See the Users Manual chapter For loop for a more detailed discussion.


for in

Loops over the elements of an array

var x = ['a','b','c'];

for(var i in x)
  write(i);

will produce the following output:

abc

See the Users Manual chapter For in loop for a more detailed discussion.


format (number, string-pattern)

Format a number with a format description given in string-pattern. The following characteres may be specified in string-pattern:

character description
# a digit, zero shows as absent
0 a digit, zero shows
. the decimal point separator
, the thousands separator
; format separator for a second pattern for negative numbers
E separates mantissa and exponent for exponential formats
% multiply by 100 and show as percentage

 

var x = 123.45
var y = -123.45
var p = 12345.678
var q = 0.45

x.format('##0.00;(##0.00)') => '123.45'

y.format('##0.00;(##0.00)') => '(123.45)'

p.format('###,##0.0000') => '12,345.6780'

p.format('#0E000') => '1.2E004'

p.format('##0E000') => '12.3E003'

q.format('##0.0%') => 45.0%

q.format('The price is ##0.00$') => 'The price is 0.45$'

The first two examples show how two formats can be specified for positive and negative numbers. The last example shows how normal text can be embedded before and after the format. See the Sun Java 1.3 SDK documentation Class DecimalFormat for more details.


function symbol-functor ( [symbol-param, ...]) { block }

Defines a new function with a name in symbol-functor and zero one or more paramerets in symbol-para,. block contains one or more script statements. Parameter names in symbol_param are treated as local variables in the statement block, as are variables declarations with var used in block. the return functions can be used to return a value from a function. If return is omitted then the return value of the last statement executed is the return value of the function.

function double(x)
  {
  return (2 * x);
  }

doubl(10) => 20

The function returns the double of a number passed in the parameter x. See also the Users Manual chapter Functions.


functionMacro symbol-functor ( [symbol-param, ...]) { block }

Defines a new function symbol-functor as a macro. When called, macros will not evaluate their arguments. See also the Users Manual chapter Macros for a more detailed explanation.


getDimensions (array)

Returns the number of dimensions in an array. If array has more than one dimensions, only indexed dimensions are counted.

var i = ['a','b','c'];
var j = ['x','y'];

var x = [[1,2],[3,4],[5,6]];
var y = table(i, j, x);

x.getDimensions() => 1

y.getDimensions() => 2

Onlye one dimension is counted on array x but two in y, where both dimensions are indexed.


getIndex (array)

Returns the primary index of an array. The primary index of an array is always the one with which has been created earliest comparing to it's other indices.

var i = ['a','b','c'];
var j = ['x','y'];

var x = table(i, j,[[1,2],[3,4],[5,6]]);

x.getIndex() => ['a','b','c']

x[0].getIndex() => ['x','y'];

If an array is indexed by TimeIndex or RunIndex than those indices are first. An array indexed by both, the timeIndex and the RunIndex has TimeIndex as it's primary index followed by RunIndex. See also the function indexNames().


getProperty (symbol)

An array of properties can be set for a variable or function symbol. This can be used to store special information about a symbol, like a description or other information. The property of a symbols should not be confused with it's value, but is an additional slot, where to hold information about the symbol.

var x = 123;

x.getProperty() => nil

x.setProperty(['Price', 'variable holding the price', '$']);

x => 123

x.getProperty() => ['Price', 'variable holding the price', '$']

The example uses the poperty array to store the title, description and unit of a variable. See also setProperty().


Graph.clearRect(num-X, num-Y, num-width, num-height)

Clear rectangle to background color.


Graph.closeWindow()

Close window.


Graph.createImage( string, num-width, num-height, symbol)

Create an image file.


Graph.createWindow( string, num-width, num-height)

Create a window for graphics.


Graph.draw3DRect(num-X, num-Y, num-width, num-height, boolean)

Draw a 3D rectangle.


Graph.drawArc(num-X, num-Y, num-width, num-height, num-st, num-arc)

Draw an arc.


Graph.drawImage(string, num-X, num-Y, num-width, num-height)

Draw an image file on the graphics window.


Graph.drawLine( num-X1, num-Y1, num-X2, num-Y2)

Draw a line between two points.


Graph.drawOval(num-X, num-Y, num-width, num-height)

Draw an oval in enclosing rectangle.


Graph.drawRect(num-X, num-Y, num-width, num-height)

Draw a rectangle.


Graph.drawRoundRect(num-X, num-Y, num-width, num-height, num-XS, num-YS)

Draw rectangle with round corners.


Graph.drawText( string, num-X, num-Y)

Draw text at position.


Graph.fill3DRect(num-X, num-Y, num-width, num-height, boolean)

Fill a 3D rectangle with current color.


Graph.fillArc(num-X, num-Y, num-width, num-height, num-st, num-arc)

Fill and arc with current color.


Graph.fillOval(num-X, num-Y, num-width, num-height)

Fill an oval with current color.


Graph.fillRect(num-X, num-Y, num-width, num-height)

Fill an rectangle with current color.


Graph.fillRoundRect(num-X, num-Y, num-width, num-height, num-XS, num-YS)

Fill a round rectangle with current color.


Graph.getFonts()

Get an array of all available font names.


Graph.reset()

Reset graphics context to defaults.


Graph.rotate(num-angle)

Rotate all operations by angle.


Graph.scale(num-X, num-Y)

Scale the coordinate system.


Graph.setBackground(number-R, number-G, number-B)

Set the background color.


Graph.setColor(number-R, number-G, number-B)

number-R, number-G, number-B


Graph.setFont(string, num-style, num-size)

Set the current font for drawing text.


Graph.setStroke(num-width, num-cap, num-join)

Set line width and style for drawing.


Graph.setTransform(num-c00, num-c01, num-c02, num-c10, num-c11, num-c12)

Set cosine transform parameters.


Graph.setXORMode(num-mask)

Set graph combination mask.


Graph.translate( num-X, num-Y)

Move coordinate system origin.


HTTP.clientIP

Variabe set by Nomar when running as a HTTP server. On each HTTP request this variable is changed to the conected clients IP number in string dottted number form:

HTTP.clientIP => '192.168.0.4'

The variable can be used to write logfiles or to mainntain session ids.


HTTP.clientName

Variable set by Nomar when running as a HTTP server. On each HTTP request this variable is changed to the hostname of the connected client. Nomar uses a reverse DNS lookup to to find the host name for a given client IP number. This reverse DNS lookup must be enabled setting the system property http.resolveIP. This system proerty is set to false by default. An should be enabled in the Nomar startup file ini.gc using:

System.setProperty('http.resolveIP', true)

If this system property is not enabled HTTP.clientName will contain the same as HTTP.clientIP, which is the unresolved IP number.

HTTP.clientName => 'lospadres.lumina.com'

The is example assumes a HTTP request from a computer with the hostname lospadres.lumina.com and the enabled system property http.resolveIP.


HTTP.cookies

If the last request header received from a client contains a cookie entry, this variable contains the value of the 'Cookie:' HTTP header. HTTP.setHeader() can be used to set cookies in the client browser when sendign responses.

HTTP.setHeader('Set-Cookie: customerID=12345');

The above statement when processed in a HTML page send to a client will set a cookie in the client browser. When the client makes a new request for a page the variable HTTP.cookies can be used to access the cookie contents.

HTTP.cookies => 'customerID=12345'


 

HTTP.hostIP

This variable is set by Nomar when running as a HTTP server and receiving a HTTP request. The variable contains a string of the IP number in dotted form. Normally this will be the same on every request, but could be different, if the server listens on more than one devices (IP numbers), or when requests are made from the same machineas localhost with IP number 129.0.0.1.


HTTP.referer

This variable is set by Nomar when running as a HTTP server and receiving a HTTP request. The information is extracted from the HTTP header infi REFERER and put into the Nomar variable HTTP.referer. Depending on the client who configured this header it may be contain an empty string or contain the URL of the refering page.

HTTP.referer => 'http://asite.com/index.shtml'

The referring page for this request was index.shtml.


HTTP.setHeader (string)

This function can be used to set response headers when answering a HTTP request.

HTTP.setHeader("Expires: Mon, 06 Nov 2000 12:00:00 GMT");

In this example an expiration date is set for the page returned to the client. This function can also be used to set cookies. See the HTTP 1.1 spec RFC2616 at www.w3c.org for a complete list and syntax for HTTP response headers.

HTTP.setHeader('Set-Cookie: customerID=12345');

The second example sets a cookie in the clients browser. See the 'HTTP State Management Mechanism RFC 2965' specification for a more detailed diskussion on cookie headers.


HTTP.userAgent

This variable is set by Nomar when running as a HTTP server and receiving a HTTP request. The information is exatracted from the HTTP header variable USER-AGENT and placed into the Nomar variable HTTP.userAgent. The content of this information can be used to identify the type and brand of user client, e.g.: MS Explorer versus Netscape browsers etc..

HTTP.userAgent => 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)'
HTTP.userAgent => 'Mozilla/4.5 [en] (X11; U; SunOS 5.5.1 sun4u)'


if (boolean) body-1 [else body-2]

if and if ... else are the most basic way to control programflow. Depending on the outcome of an expression in boolean program flow is changed.

if(x > 100)
   writeln('big');

if(x > 100)
   writeln('big');
else
   writeln('small');

See also if and if else for a more detailed discussion. See cond() for an array abstracting if.


index (array-boolean)

Translates an array-boolean containing the values true and false into the an array showing the index offsets of all true values:

var b= [true, false, true, false];

index(b) => [1, 3];

When using boolean vectors as indices of arrays the index() function is used implicitely:

var x = [11, 4, 15, 8];

var b = x > 10;

b => [true, false, true, false];

x[b] => [11, 15]

or equivalent

x[index(b)] => [11, 15]

or shortest

x[x > 10] => [11, 15]


indexOf (string-1, string-2)

Returns the offset position of string-2 in string-1 or nil if string-2 is not contained in string-1:

var x = 'programming is fun';

x.indexOf('is') => 12

x.indexOf(['is', 'fun']) => [12, 15]

The second examples shows an application of indexOf on arrays. See also lastIndexOf().


insert (array, variant, number-offset)

Inserts a object in variant in to an array at offset number-offset.

var x = [1,2,3,4,5];

x.insert(10, 0);

x => [10,1,2,3,4,5]

See also the function remove().


isDirectory (string)

Checks is a file system in entry specified in string is a directory:

isDirectory('d:/winnt') => true

isDirectory('d:\\winnt') => true

Note that forward slashes can be used for composite path names. When using back slashes '\', they have to be preceded by an escape character, which in itself is a bask slash, resulting in a double back slash '\\':


isIndexed (array)

Checks if an array is indexed by an index other than itsef:

var x = [1,2,3,4];

x.isIndexed() => false

var i = ['a','b','c','d'];

x = table(i, x);

x.isIndexed<> => true


isInfinite (number)

Checks if a number is infinite. Infinitte numbers may result when dividing by zero or dividing by a number very close to zero and the result is outside the script number spectrum.

isInfinite(1/0) => true

isInfinite(Math.log(0)) => true


isFile (string)

Checks the existence of a file in the path/filenname specified in string.

isFile('/usr/home/john/myfile.txt')

isFile('c:/autoexec.bat')

Note, that on MS Windows platforms the forward slash can be used in NomarScript as well. When using the backslash '\' it has do be prefixed with the escape character '\' resukting in a double '\\' :

isFile('c:\\autoexec.bat')

For better platform independence ther forward slash is recommended.


isNaN (number)

Checks if a number is valid. Infinite numbers may result when applying operations with a wrong datatype to a number.

var x = [1,2,3,'hi',4,5];

x * 3 => [3, 6, 9, NaN, 12, 15]

isUndefined (symbol)

Checks if a variable or function in symbol is defined (does not contain nil):

var x;

x.isUndefuned() => true

x = 123;

x.isUndefined() => false


join (array-string, [string], [index])

Joins strings in an array by concatenating them and optionally inserting a string. When array-string has more than one dimensions, index specifies the dimension over which to join.

var x = ['a','b','c','d'];

x.join() => 'abcd'

x.join('-') => 'a-b-c-d'

In case the array does not contain strings it's elements are transormed into string first:

var x = [1, 2, 3, 4, 5];

x.join() => '12345];

x.join('xx') => '1xx2xx3xx4xx5'


last (array, [index])

Returns the last element in an array. In case the array has more than one dimensions index specifies the relevant dimension:

var x = [1,2,3,4,5];

x.last() => 5

See also the function first().


lastError ()

Returns the last error message and line number which occurred in an array.

evalTagged('<% blah blah %>')

=> 'Parse error: Unknown Identifier: 'blah' in line 1 nil'

lastError() => ['Unknown Identifier: 'blah\'', 1]


lastIndexOf (string-1, string-2)

Returns the position of the last occurence of string-2 in string-1 or nil if string-2 is not part of string-1.

var x = 'wer sucht, der findet'

x.lastIndexOf('der') => 11

See also indexOf().


length (string | number)

Returns the lenght of a string in string:

length('hello') => 5;

length(123) => 3

var x = [1, 123, 6, 15]

x.length() => [1, 3, 1, 2]

If the argument supplied, is a number than the length of it's string representation is returned.


load (string)

Loads script code from a path/file name or from an URL in string and parses/evaluates it.

load('myScript')
load('http://www.mysite.com/myNomarScript.nomar')

The result of the last expression evaluated is returned. If load fails because of parse errors or evaluation errors than load() returns nil and the function lastError() can be used to inquire about the last error parsing/evaluating the script.


lookupIP (string)

Looks up the IP number of a host name in string and returns the IP number as a string. In case no DNS entry can be found nil is returned.

lookupIP('eff.org') => '204.253.162.2'

See resolveIP() which is the reverse function.


Mail.check(string-user, string-password, string-server)

Returns the status of a POP3 mailbox with user id string-user and password string-password on a POP3 mailserver string-server. The status is returned in an array of three numbers for: total number of messages, last read message and total number of bytes in mailbox.

Mail.check('JohnDoe', 'secret', 'pop.isp.com') => [16, 12, 60357]

In the example the mailbox conatins 16 messages the last message read is number 12 and there are a total of 60357 bytes held in the mailbox.

The data from Mail.check() can be used in other mail commands to retrieve or delete messages.


Mail.delete(string-user, string-password, string-server, array-numbers)

Deletes messages in a POP3 mailbox of string-user with string-password on mail server string-server. The array-numbers contains an array of messages numbers to be deleted.

var status = Mail.check('JohnDoe', 'secret', 'pop.isp.com');
var oldMsgs = sequence(1, status[1]);

Mail.delete(('JohnDoe', 'secret', 'pop.isp.com', oldsMsgs);

The example retrieves the number of messages in the mailbox and the number of the last read message using Mail.check(). oldMsgs gets created as an array of numbers of read messages and those messages are deleted. On sucess Mail.delete() returns true else returns nil and Mail.lastError() can be used to retriev the error text.


Mail.headers(string-user, string-password, string-server, array-numbers)

Retrieves the mail headers of messages specified by their numbers in array-numbers for string-user with password string-password on the POP3 mailserver string-server.

var status = Mail.check('JohnDoe', 'secret', 'pop.isp.com');
var newMsgs = sequence(status[1] + 1, status[0]);

if(newMsgs)
  {
  var newHeaders = Mail.headers(('JohnDoe', 'secret', 'pop.isp.com', newMsgs);
  if(not newHeaders)
    {
    writeln('there was a problem retriving mail headers');
    writeln(Mail.lastError());
    }
  }

 

The code in the example retrieves the headers of all unread messages in the mailbox and stores them in an array named newHeaders. On failure Mail.headers() returns nil and Mail.lastError() is used to get the error text.


Mail.lastError()

When Mail functions faiul they return nil and a message string is saved which can be retrievd using Mail.lastError().

Mail.check('JohnDoe', 'blahblah', 'pop.isp.com');

Mail.lastError() =>

    'Error in pop3 client: Password supplied for "JohnDoe" is incorrect.'


Mail.receive(string-user, string-password, string-server, array-numbers)

Retrieves mail for a user string-user and string-password on the POP3 mailserver string-server. The numbers of the messages to be retrieved are specified in array-numbers. On failure nil is returned and Mail.lastError() can be used to inspect the error message.

var status = Mail.check('JohnDoe', 'secret', 'pop.isp.com');
var newMsgs = sequence(status[1] + 1, status[0]);

if(newMsgs)
  {

  var messages= Mail.receive(('JohnDoe', 'secret', 'pop.isp.com', newMsgs);
  if(not messages)

    {
    writeln('there was a problem retriving');
    writeln(Mail.lastError());
    }
  }

The example retrieves unread messages and reports an error message on failure.


Mail.send(string-from, string-to, string-subject, string-body)

Sends an email messages to the email address specified in string-to with the subject line string-subject and a message body string-body. The mail server must be specified in the system property 'mail.host' and is one of the system properties found in the Java Runtime Environment.

System.setProperty('mail.host', 'smtp.myisp.com');

Mail.send('johnDoe@myisp.com', 'jane@acompany.com', 'Greetings', 'Hello from John');

The second parameter string-to may be an array of addresses, to send the same mail to more than one recipient.


match (string-1, string-2)

Looks for a pattern described in string-2 in string-1 and returns a list of matched pattern parts. The following characters can be specified.

character description
* matches any zero or more characters
? matches exactly one character
# matches a number digit

 

All other characters match to iself. All '*'-parts and the parts in between are returned as array elements. If nothing matches, nil is returned.

match('find the needle in the hay', '*needle*')
=> ['find the ', 'needle', ' in the hay']

match('Aug-12-2000', '*-*-*') => ['Aug', '-', '12', '-', '2000']

var str = "tel: 555-1212 ssn: 564-92-0145 age: 35";

var ssn = match(str, "*???-??-????*")[1]

ssn => '564-92-0145'

Note, how the result from the last match is sub-indexed directly pulling out the second (offset 1) from three resulting array elements.


max (array, [index])

Returns the maximum value in an array of numbers or strings. In case of strings the string last in the sort order is of the highest value. Optionally an index can be specified when dealing with multidimensional arrays.

var i = ['a', 'b', 'c', 'd', 'e'];
var j = ['x', 'y', 'z'];
var tab = table(i, j,
   [[1, 2, 3],[4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]);

tab.max(i) => [13, 14, 15]

tab.max(j) => [3, 6, 9, 12, 15]

max(['a', 'b', 'c']) => 'c'


min (array, [index])

Returns the minimum value in an array of numbers or strings. In case of strings the string first in the sort order is of the lowest value. Optionally an index can be specified when dealing with multidimensional arrays.

var i = ['a', 'b', 'c', 'd', 'e'];
var j = ['x', 'y', 'z'];
var tab = table(i, j,
   [[1, 2, 3],[4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]);

tab.min(i) => [1, 2, 3]

tab.min(j) => [1, 4, 7, 10, 13]

min([ 'a', 'b', 'c']) => 'a'


module symbol;

Switches to a different name space or creates it, if it doesn't exists. module should be the first directive in a file. All script code parsed after this directive will create variables and functions in a name space named in symbol. If variables or functions are created al readfy existing in the main default name space, then those get overwritten.

The following modules already exist, when starting NomarScript:

Module Description
DB database functions for JDBC access
Graph functions for drawing graphics and creating graphics files
HTTP special variable in use by the built in httpd server
Mail functions for sending and retrieving mail via SMTP and POP3
Math special math functions and constants
System functions manipulating system properties and the error handler
XML functions for translating and generating XML data

When accessing functions or variables in module other than the default module Main, those functions and variables have to be prefixed by the module name separated by a period:

module myMod;

var x = 123;

function double(num)
  {
  return(num + num);
  }

symbols() => [x, double]

module Main;

myMod.x => 123

myMod.double(10) => 20

myMod.symbols() => [x, double]

Modules allow a project to be splitted in different parts without accidental name clashes. This enables collaborative working on bigger programs. The functions symbols() can be used to retrieve a list of all functions and variables contained in a module.


Math.abs (number)

Returns the absolute value of a number.

Math.abs(-1.234) => 1.234


Math.acos (number)

Returns the arc cosine of an angle in radians, in the range of 0.0 through pi.

Math.acos(0) => 1.571


Math.toDegrees(Math.acos(0)) => 90


Math.asin (number)

Returns the arc sine of an angle number in radians, in the range of -pi/2 through pi/2.

Math.asin(1) => 1.571


Math.atan (number)

Returns the arc tangent of an angle radian number, in the range of -pi/2 through pi/2.

Math.atan(Math.toRadians(45)) => 0.666


Math.beta (number-1, number-2)

Returns the beta function of values number-1 and number-2

Math.beta(3, 4) => 0.017


Math.ceil (number)

Returns the smallest (closest to negative infinity) number that is not less than number and is equal to a mathematical integer.

Math.ceil(-1.234) => -1

Math.ceil(1.234) => 2


Math.combinations (number-k, number-n)

Calculates the number combinations of number-k items out of number-n.

Math.combinations(6, 49) => 13983816

Math.combinations(2, 3) => 3

See also Math.permuations(), which will count also count all repetions in combinations.


Math.cos (number)

Returns the trigonometric cosine of an angle in radians in number.

Math.cos(0) => 1


Math.critChi2(number-prob, number-df)

Calculates critical Chi-square from probability p in number-prob and degrees of freedom in number-df.

Math.critCh2(0.01, 8) => 20.090

See also Math.probChi2() for looking up the probability of a given Chi-square.


Math.cumNormal (number-x, [number-mean, number-stddev])

Returns the cumulative density for a normal distribution. Mean and stdev are 0.0 and 1.0 by default.

Math.CumNormal(1) - Math.cumNormal(-1) => 0.683

68.3% of the area under a normal distribution are conatineed within one standard deviation of a mean.


Math.E ()

returns the mathematical constant e = 2.718...

Math.E() => 2.718

Math.E().format('#.000000000000000') => '2.718281828459045'


Math.exp (number)

Returns the exponential number e (i.e., 2.718...) raised to the power of number.

Math.exp(1) => 2.718


Math.floor (number)

Returns the largest (closest to positive infinity) number that is not greater than number and is equal to a mathematical integer.

Math.floor(-1.234) => -2

Math.floor(1.234) => 1


Math.gamma (number)

Returns the gamma function of number.

Math.gamma(0) => infinity

Math.gamma(1)=> 1

Math.gamma(10) => 362,880.000


Math.gammaLn (number)

Returns the log gamma function of number.

Math.gammaLn(1) => 0

Math.gammaLn(10) => 12.802


Math.log (number)

Returns the natural logarithm (base e) of number.

Math.log(Math.E()) => 1


Math.permutations (number-k, number-n)

Calculates the number permutations of number-k items out of number-n.

Math.permutations(2,3) => 6

similar to Math.combinations() but with repetitions e.g. 1 2 and 2 1 are counted both in Math.permuations() but only once in Math.combinations().


Math.PI ()

Returns the constant pi = 3.141...

Math.PI() => 3.141

Math.PI().format('#.000000000000000') => '3.141592653589793'


Math.pow (number, number-exp)

Returns of value of number-1 raised to the power of number-2.

Math.pow(10, 2) => 100


Math.probChi2(number-chi2, number-df)

Calculates the probability of Chi-square in number-chi2 with degrees of freedom in number-df.

Math.probChi2(20, 8) => 0.010

See also Math.critChi2() for calculating the critical Chi-square for a given probability.


Math.probZ(number-z)

Calculates the probability of a given normal distributed z in number-z. z is assumed to be distributed with a median of 0.0 and a standard deviation 1.0.

Math.probZ(0.0) => 0.500


Math.round (number)

Returns the closest long integer (64 bit) to number.

Math.round(12.34) => 12

Math.round(1.5) => 2


Math.sin (number)

Returns the trigonometric sine of an angle in radians in number.

Math.sin(Math.toRadians(180)) => 0.000


Math.sqrt (number)

Returns the square root of number.

Mat.sqrt(64) => 8


Math.tan (number)

Returns the trigonometric tangent of an angle in radians in number.

Math.tan(Math.PI()/4) => 1.000


Math.toDegrees (number)

Converts an angle measured in number radians to the equivalent angle measured in degrees.

Math.toDegrees(Math.PI()) => 180


Math.toRadians (number)

Converts an angle measured in number degrees to the equivalent angle measured in radians.

Math.toRadian(180) => 3.142

Math.toRadians(180) - Math.PI() => 0


new function([variant], ...)

Creates a new object using a template in function and initializing object variables with the intitializers in variant:

function address(streetAddress, city, zip, country, telefone, email)

var somebody = new address
  
('100 Main Ave', 'Anycity', '12345', 'USA', '555-1212', 'jane@email.com');

The new composite data object can now be manipulated the following way:

somebody.city => 'Anycity'

somebody.telefone = '123-4567'

Special functions called methods can be written to access data fields in object. For a more detailed discussion see the Useres Manual chapter Objects and methods .


not variant

Reverses the boolean value of variant from true to or false to true. not is used in conditional expressions in if else, while and for expressions:

while(not (x > 10))
  {
  doSomething();
  }

See also and and or.


numberFormat ([string])

Sets or retrieves the default format for displaying and writing numbers. If string is not sepcified numberFormat() returns the current default format string, otherwise string defines a new default number format.

var x = 123.456

numberFormat() => '#,##0.000'

x => 123.456

numberFormat('#,##0,0');

x => 123.5

The first statement displays the default number format after starting the script interpreter. The second statement sets the new default foprmat to display less decimals. See also the function format() .


or

Performs a logical or operation. or is used to build complex conditional expressions in if else, while and for expressions:

if(year > 1980 or year < 1970)
  doSomething();

The function doSomething() is perfomed when at least one of the two conditions is true. See also and and not.


parseDate (string)

Parses a date string returning the number of milliseconds passed between 1-1-1970 (Greenwich time) and the date in string.

parseDate('Aug 1, 2000 2:36:20 PM') => 965,165,780,000.000

The time is optional:

parseDate('Aug 1, 2000') => 965,113,200,000.000

date(965113200000) = > 'Aug 1, 2000 12:00:00 AM'

See function date() for converting time numbers back to strings. See also systemTime().


parseDateJDBC (string)

Parses a date string of ther form 'yyyy-mm-dd ' or 'yyyy-mm-dd hh:mm:ss' and returns the number of milliseconds passed after 1970-1-1 12:00 AM.

parseDateJDBC('2000-08-01') => 965,113,200,000.000

parseDateJDBC('2010-01-01 20:30:00') => 1,262,435,400,000.000

parseDateJDBC('2010-01-01 20:30:00.124') => 1,262,435,400,124.000

The time must be specified in 24 hour format. If the time is specified Greenwich time is assumed. See also the functions parseDate(), systemTime() and date().


parseFloat (string)

Parses floating point data in different formats in string. If the number in string is invalid, NaN is returned. Leading or trailing spaces and the - or + sign are legal.

parseFloat('123.456') => 123.456

parseFloat('1.3e3') => 1300

parseFloat() is frequently used when parsing the string content of fields in HTML forms to extract number values. See also parseInt().


parseInt (string,[number-base])

Parses integer numbers formatted in string. Optionally a number-base can be specified.

parseInt('1234') => 1234

parseInt('FFFF', 16) => 65535

parseInt('777', 8) => 511

parseInt ('100', 2) => 4

Any number base between 2 (0,1) and 36 (0-9,A-Z) can be specified. Invalid formats return NaN. parseInt() is frequently used when parsing the string content of fields in HTML forms to extract number values. See also parseFloat().


path

Returns the current directory path.

path() => 'D:\java'


pop (array)

Removes the last element from an array and returns it's value. Together with the push() function pop can be used to treat arrays as stacks.

var x = [1,2,3,4,5];

x.pop() => 5

x.pop() => 4


push (array, variant)

Appends a new element in variant to an array and returns it's value. Together with the pop() function push can be used to treat arrays as stacks.

var x = [];

x.push(1);

x => [1];

x.push(2) => [1, 2]

x.push('hello');

x => [1, 2, 'hello']


Proxy.add(number-proxy-port)

Adds proxy service port number-proxy-port. A proxy service port receives requests and redirects these requests to other Nomar servers running on the same computer or on other machines on the network. One service port can be redirected to multiple Nomar services, in effect distributing requests to multiple servers for handling. The response of the service machine will go back through the same proxy port on the proxy server.

The proxy serer adds as a gate for other multiple Nomar servers. This can be useful to shield machines from direct access from the outside and to serve a large number of requests on a single service port.

Although Nomar can run as a proxy server and normal HTTP server at the same time, it is recommended to dedicate one Nomar server as a proxy for maximum efficiency.

Depending on memory requirements of the applications runnning and the speed of the machine, multiple Nomaer servers can be run on the same machine and together with the Nomar proxy server. Usage of the Nomar proxy server is not limited to serving other Nomar servers or to server HTTP requests. The proxy server can be used as a general redirector for IP packets for different servers or protocols.

Proxy.add(80)

This will configure Nomar for listening for requests on the local machine on port 80. Nomar will not start listening until the services are added with Proxy.addServive() and until the Proxy.start() command is given. Mor than one ports can be added for listening on one proxy server.

For specifying port numbers smaller than 1000 root permissions are necessary on most UNIX/LINUX machines.

See also http.acceptIP for limiting acces to certain sources.

 


Proxy.addService(number-proxy, string-hostname, number-hostname-port)

Add service string-hostname with port number-hostname-port to the proxy port number-proxy. After setting a proxy port with Proxy.add() services can be added for redirection.

Proxy.add(80);
Proxy.addService(80, '192.168.0.3', 8081);
Proxy.addService(80, '192.168.0.3', 8082);
Proxy.addService(80, 'job.myserv.com', 8081);
Proxy.start(80);

The example established a proxy port 80 to listen on, on the local host. Incoming requests will be redirected to two other machines (assuming that port 80 is on a third machine). The machine specified by IP-number 192.168.0.3 has two services running on ports 8081 and 8082. A second machine is specified by its hostname job.myserv.com is running a service on port 8081.

It would be possible to run all four tasks on the same machine using the following configuration:

Proxy.add(80);
Proxy.addService(80, 'localhost', 8081);
Proxy.addService(80, 'localhost', 8082);
Proxy.addService(80, 'localhost', 8083);
Proxy.start(80);

In this cas the address of the third service had to be changed to 8083, not to conflict with a service already running on port 8081. On successful configuration true is retunred.


Proxy.balance(number-port, [boolean] )

Set load balancing or overflow mode for proxy port number-port depending on expression in boolean. When redirecting request to several service addresses two different policies are posssible for balancing load. If nothing is specified in boolean returns the current configuration (true or false).

As a default each proxy port is configured for overflow mode (boolean set to false). In overflow mode the proxy server will try to redirect to the last machine used, if that machine is not free (still serving a previous request) then the next machine will be tried in a round robin fashion. In overflow mode the system tries to use the least number of servers, but fully load them. Under a low load only the first server in the row of servers would be used at all.

In balanced mode (boolean set to true) the proxy server will try the next available machine after the one last used, thus balancing the load between several servers. In balanced mode the proxy tries to spread the load between all configured machines. Even under a low load each server machine would get an equal number of requests.

Proxy.balance(80) => false

Proxy.balance(80, true)

The first exampler inquires the balance mode on proxy server 80, which turn out to be set to the default overflow mode. The second example sets the balance policy to balanced.


Proxy.log(boolean)

Enables logging to the output console (console window or shell) of the proxy server depending on boolean.

Proxy.log(true)

This turns logging on and the following output might be generated:

Proxy listening on: 80
Sep 13, 2000 10:33:43 AM localhost/127.0.0.1 ===> localhost:8888
Sep 13, 2000 10:33:43 AM localhost/127.0.0.1 ===> localhost:8888

The log can be captured to a file by redirecting standard I/O to a file when starting up Nomar:

java -jar nomar.jar -console > log.txt

Note, that this precludes issuing Proxy.status() statements as standad I/O is redirected in this mode.

 


Proxy.remove(number-port)

Remove a proxy service port. This remove port number-port as a listening port on the proxy server.

Proxy.remove(80) => true

All services on port 80 are stopped and removed. To reinstate services port 80 and all its services would have to be added again and the proxy started.


Proxy.removeService(string-hostname, number-hostname-port)

Removes a service specified by string-hostname and number-hostname-port.

Proxy.remove('localhost', 8888)

The service on localhost port 8888 is removed from the proxy.


Proxy.start(number-proxy-port)

Start listening on number-proxy-ort.

Proxy.start(80) =>true

On sucess returns true and prints a log message. See Proxy.addService() for a more comprehensive example.


Proxy.status([number-proxy-port])

Report status of one or all proxies. This will report for each of the paths, which have been set up for redirection.

Proxy.status()

[[80, 'localhost', 8888, 'idle', 2]]

The data are reported in a Nomar array. The last number indicates the number of connections made on the specified path.


Proxy.timeout(number-port, [number-milli-sec] )

Set timeout for fallen connections. Requests which do not have an response after a default timeout of 10 seconds will cause the connection to be closed. The default timeout of 10,000 msec can be changed using this function. When not specififying number-milli-sec the current setting is returned.

Proxy.timeout(80) => 10000

Proxy.timeout(80, 20000) => true

The first example inquires the current timeout etting on port 80. The second example sets a new timeout of 20,000 msec.


quit

Exits the script interpreter. See also the exit() function.


random ([number])

Generates one random number or an array of number random numbers with values continuosly equally distributed between 0 and 1. The internal random number generator can be seeded using the seed() function.

random() => 0.372

random(10) => [0.862, 0.730, 0.031, 0.031, 0.729]

mean(random(1000000)) => 0.500

Note, that in a context of Monte Carlo simulation the uniform() function should rather be used, as it plays together with other simulating and modelling functions.


register (string-name, string-class-name)

Registers an external Java function (class). The function class has to be written using special wrapper (See example file myfuncs/funcMyTest.java ). string-name is the name of the function as used in script source, string-class-name is the Java path and class name of the function but without the class suffix.

register('foo', 'myfuncs.funcMyTest')

foo("an external function", 123)

See the example file myfuncs/funcMyTest.java on how to pass parameters to external Java functions.


remove (array, number)

Removes and element from an array at the specified offset in number and returns the value of that element.

var x = [1,2,3,4,5];

x.remove(1) => 2

x => [1, 3, 4, 5]


rename (string-1, string-2)

Renames a file with name string-1 to string-2. Returns true or false depending on succcess.

rename('afile.txt', 'otherfile.txt');


replace (string-1, string-2, string-3)

Searches for all occurrences of string-2 in string-1 and returns a new string with all string-2 replaced by string-3. The original string-1 remains unchanged.

replace('abcabcabc' , 'b', '--') => 'a--ca--ca--c'

replace('abcabcabc', 'b', '') => 'acacac'

The original and the replacement may be of different length. If the replacement is an emoty string the original is only removed in the resulting string.


resolveIP (string)

Looks up an IP number from and IP-number and returns the host name string.

resolveIP('207.25.71.246') => 'www20.cnn.com'

See also the reverse operation using the lookupIP() function.


return (variant)

Returns from the current function. Optionally a return value can be specified in variant.

function foo(a, b, c)
  {
  var result;
  ...
  ...
  return(result);
  }

See also the Users Manual chapter about Functions .


resize (array, [variant])

Resizes and array to changed indices and optionally initializes new empty cells with variant.

var i = ['a', 'b', 'c', 'd'];

var j = ['x','y'];

var x = table(i, j, [[1,2], [3,4], [5,6], [7,8]]);

i.push('e');

x.resize(0);

x => [[1,2], [3,4], [5,6], [7,8], [0, 0]]


reverse (array, [index] )

Returns an array with the order of elements reversed. The original array is not changed. On multi deminsional indexed arrays an index can be specified for reversing on the correct dimension.

var x = [1, 2, 3, 4, 5];

x.reverse() => [5, 4, 3, 2, 1];


seed ([number])

Resets and seeds the internal random number generator. when using without the optional number parameter the value of systemTime() is used to iniatilize. When using a specific number the same random number sequence can be generated repeatedly. The function return the new set seed.

seed(1234);

random(3) => [0.647, 0.951, 0.858]
random(3) => [0.458, 0.336, 0.204]

seed(1234);

random(3) => [0.647, 0.951, 0.858]


sequence (nunber-from, number-to, [number-step])

Returns an array of numbers from number-from to number-to. Optionally a step size number-step can be given.

sequence(1, 10) => ]1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

sequence(1, 2, 0.3) => [1, 1.300, 1.600, 1.900]


setProperty (symbol, array)

An array of properties can be set for a variable or functions symbol. This get be used to store special information about a symbols like a description are other information. The property of a symbols should not be confused with it's value, but is an additional space where to hold information about the symbol.

var x = 123;

x.getProperty() => nil

x.setProperty(['Price', 'variable holding the price', '$']);

x => 123

x.getProperty() => ['Price', 'variable holding the price', '$']

The example uses the poperty array to store the title, description and unit of a variable. See also getProperty() .


size (array)

Returns the number of elements in an array. If an array is multi demensional and indexed the size is the product of all index sizes.

var i = ['a', 'b', 'c', 'd'];

var j = ['x','y'];

var x = table(i, j, [[1,2], [3,4], [5,6], [7,8]]);

x.size() => 8


sort (array, [index, array-columns])

Sorts and array in ascending order. Optionally an index can be specified and one or more column offsets to sort on specific columns in array-columns.

var i = ['a', 'b', 'c', 'd', 'e'];

var j = ['x','y'];

var x = table(i, j, [[2,1], [5,8], [5,4], [4,1], [7,0]]);

x.sort(i) => [[2, 1], [4, 1], [5, 8], [5, 4], [7, 0]]

Rows are now sorted only by their first element (offset 0 default). The rows [5,8] and [5,4] are still in wrong order if looking to the second elements 8 and 4.

x.sort(i,[0,1]) => [[2, 1], [4, 1], [5, 4], [5, 8], [7, 0]]

Rows are now fully sorted on all elements.

x.sort(j) => [[1, 2], [8, 5], [4, 5], [1, 4], [0, 7]]

The two j columns are swapped comparing the first (offset 0 default) elements in the column (numbers 2 and 1).


split (string-1, [string-2])

Splits a string-1 into elements separated by a string-2, returns an array of strings. When string-2 is not specified string-1 is split using the Java StringTokenizer class, which splits strings at white space boundaries like spaces line feeds and tabs.

split('splitting a sentence at the spaces')

=> ['splitting', 'a', 'sentence', 'at', 'the', 'spaces']

split('30/11/47', '/') => ['30', '11', '47']

sort returns new sorted data, the original array keeps unchanged.


startsWith (string-1, string-2)

Checks if a string-1 starts with string-2. Returns

startsWith('Nomar', 'Nom') => true

See also the function endsWith() .


string (variant)

Returns a string representation of variant. string is different from the function toString(), which would array abstract into arrays.

string(x) => '[1, 2, 3, 4]'

but

toString(x) => ['1', '2', '3', '4']

See also toString().


substring (string, number-start, [number-length])

Returns a string starting at position number-start and length number-length . If number-length is not specified, the returned string goes to the end of string. The original string is left unchanged.

substring('Nomar scripting with strings', 6) => 'scripting with strings'

substring('Nomar scripting with strings', 6, 9) => 'scripting'

If the offset in number-start is longer than string itself, an empty string gets returned.


sum (array, [index])

Calculates the sum(s) of an array of values. An optional index can be specified when using sum on multi dimensional arrays.

var i = ['a', 'b', 'c', 'd', 'e'];
var j = ['x', 'y'];
var x = table(i, j, [[1,2],[3,4],[5,6],[7,8],[9,10]]);

x.sum(i) => [25, 30]

x.sum(j) => [3, 7, 11, 15, 19]


switch

switch(x)
  {
  case 1:
    doThis();
    break;
  case 2:
    doThat();
    break;
  case 3:
    doOther();
    break;
  default:
    someThingDifferent();
  }

NomarScript will check each case for x and execute the statement or statements following it. The break key word makes the program flow leave the switch statement. if the none of the case 's apply the statement or statements in the default section are executed. The default section may be empty, but the default keyword should no be missing. switch can also work on string constants. For a more detailed discussion see the chapter Switch in the Users Manual.


symbols ([symbols])

Shows a list of symbols in the current module or the module specified in symbol.

symbols() => [subindex, insert, endsWith, .... lastIndexOf, evalTagged]

module MyMod;

var x, y z;

module Main;

symbols(myMod) => [x, z, y]

Symbols are returned in order of there internal hash values.


System.errorHandler

This system variable can be set up to point to a user defined error handler. In that error handler the function lastError() can be used to retrieve information about the error occurred:

System.errorHandler :=
  {
  writeln("an error has ocurred: " lastError());
  }

Weheneve an error occures in Nomar the procedure defined in System.errorHandler will be called.


System.getProperty([string-name, string-value])

Nomar maintains a variety of system variables in the Java System properties. Some of this variables control the behavior of Nomar other variables given information about certain system aspects and configuration.

When using this function without arguments Nomar will return a long string conatining the definiotion of all system properties. These include Nomar specific properties but also properties set by the Java Runtime Environ ment or the underlying operating system.

System.getProperty('os.name') => 'Windows NT'
System.getProperty('java.version') => '1.3.0'
System.getProperty('user.name') => 'lutz'

System.getProperty('http.port') => '8888'
System.getProperty('http.directory') = '/www/'

The first three examples illustrate retrieving system properties of the Java Runtime Environment and OS. The last two examples retrieve Nomar specific system properties. See also system properties for other Nomar specific system properties.


System.setProperty(string-name)

Changes the contents of system property variables. See system properties for a variety of property variables and their purpose.

System.setProperty('http.debug', true);
System.setProperty(http.acceptIP', '127.0.0.1');

The first example puts Nomar, when run as a HTTP server in debug mode. In this mode all incoming and outcoming data gets logged to the console. The second example limits incoming traffic to request coming from the localhost machine, all other request will receive an error response page.


table (index-1, [index-2 ...], variant)

Creates a one or multi dimensional indexed array and initializes it with data in variant. The indices must be existing one dimensional arrays. If the initializer in variant is an array than it's data should be in the same order as the indices are shown in the table statement. Nomar may format the new created array in a different index order, putting the oldest index first.

var i = ['a', 'b', 'c', 'd', 'e'];

var j = ['x', 'y'];

var x = table(i, j, [[1, 2], [3, 4] ,[5, 6], [7, 8], [9, 10]]);

x => [[1, 2], [3, 4] ,[5, 6], [7, 8], [9, 10]];

If the initializer in variant is an array than it's data should be in the same order as the indices are shown in the table statement. Nomar may format the new created array in a different index order, putting the oldest index first.

var z = table(j, i, [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]);

z => [[1, 2], [3, 4] ,[5, 6], [7, 8], [9, 10]];


systemTime ()

Returns the number of milli seconds since the UNIX epoch Jan 1st, 1970.

systemTime() => 965,668,167,666.000

date(965668167666) => 'Aug 7, 2000 10:09:27 AM'

See also the function date() .


toLowerCase (string)

Returns a string with all characters in string translated to lower case.

toLowerCase('ABCDEfg123') => 'abcdefg123'

See also toUpperCase() for the reverse operation.


toString (variant)

Returns a string representation of variant .

toString(123) => '123'

toString((3+4)) => '7'

toString([1,2,3,4]) => ['1', '2', '3', '4']

Note, that Nomar in many cases does an implicit conversion to strings:

'#' + [1,2,3,4] => ['#1', '#2', '#3', '#4']


toUpperCase (string)

Returns a string with all characters in string converted to upper case characters.

toUpperCase('aBcdefg123') => 'ABCDEFG123'

See also toLowerCase() for the reverse operation.


trim (string)

Strips off all leading and ending white space from a string. White space include spaces, tabs and line feed chracaters.

trim(' trim me    \n') => 'trim me'

trim is useful when parsing data from HTML input fields.


typeOf (variant)

Returns the string indicating the type of variant.

var x = 123;

var y = 'hello';

var z := 3 + 4;

var q = trim;

typeof(x) => 'number'
typeof(y) => 'string'
typeof(z) => 'expression')
typeof(q) => 'primitive'
typeof([1,2,3]) => 'array'


unlink (string)

Removes a file, whose path/name is given in string from the file system. Returns true ore false depeneing on success.

isFile('junkFile') => false

urlWrite('junkFile', 'dsfgsdfgsdfg');

isFile('junkFile') => true

unlink('junkFile') => true

isFile('junkFile') => false


urlRead (string)

Reads from a URL or local filesystem or network file system, currently the protocols HTTP, FTP and FILE are supported. In case of HTTP URLs and depending on the format, HTTP- GET or POST request can be made, resulting in function calls if they go to another NomarScript compute server or resulting in an CGI request if they go to a traditional web server. urlRead returns a string with the contents read.

In it's simplest form urlRead reads from the local file system at the current directory.

urlWrite('myFile', 'this gets written to a file')

urlRead('myFile') => 'this gets written to a file'

A different path can be specified:

urlRead('c:/Nomar/aFile.txt')

Note, that on Win32 system the forward slash can be used in Nomar as a path/filename speration character. This helps in producing more platform independent path/file names. Whenusaing the backslash, the backslash would have to be prefixed by the '\' escape character resulting in a double backslash '\\'.

The file:// URL prefix can also be used to read from the local file system:

urlRead('file://c:/Nomar/aFile.txt')

A file may be requested from a remote webserver:

urlRead('http://www.asite.com/index.html')

A HTTP GET request can be placed to a web server with an embedded query string;

urlRead('http://www.asite.com/doSomething?name=John+Doe&city=Anycity')

Note, that the query string must be formatted in a correct manner translating the space character to '+' and translating other special characters in to '%xx' form, where xx is the hexadecimal representaions of an ASCII character.

When a GET or POST request is sent to a Nomar web server, than this requenst is treated like a function call. All parameter/value pairs are passed as an index array to the function. The previous example GET requenst could be handles the following way:

function doSomething(params)
    {
    writeln('<H2>Welcome ' + params.name + ' in ' params.city '!</H2>');
    }

The Nomar webserver would send back a simple HTML page containing:

Welcome John Doe in Anycity !

When Nomar runs in HTTP mode all write() or writeln() operationsd are directed to the internet connected client browser. See also the Users Manual chapter about HTTP mode .


urlReadParallel(array-url)

Similar as urlRead, but HTPP and FTP modes only and the possibility to make multiple reads in parallel by specifying and array of URLs . For each URL to read a seperate thread is started waiting for data from the remote web server. If the remote servers are Nomar servers, urlReadParallel becomes a parallel function call to mutliple Nomar servers. urelReadParallel will return when all threads have finished receving data/results from their URLs.

array-url contains an array of url strings. For each URL a thread is started waiting for the data or function process request to succeed. The return value is an array of strings containing the result data of each HTTP request or nil if the request fails.

urlReadParallel(['http://siteA.org/calculate?start=1&end=100',
                                  'http://siteB.org/calculate?start=101&end=200']);

The example shows how a Nomar function calculate is called at 2 different sites siteA.org and siteB.org with different parameters. start and end sould be the ranges of some calculation to perform in parallel.


urlWrite (string-url, string)

urlWrite can be used to write to the local file system or to transfer information to another web site via a HTTP or FTP request.

In it's simplest form urlWrite writes to the local file system at the current directory.

var myText = urlRead('myFile');

urlWrite('myFile', myText);

Or via FTP

urlWrite('ftp://ftp.anywhere.com/newFile.txt', myText);


var

Declares vraibles for subsequent use in Nomar script. optionally variables can be initialized with a value or expression:

var x, y, z;

declares 3 variables with the names x, y anx z. All three variables conatins initially nil.

var x = 123;
var y= 'a new variable';
var z = [10,20,30];

The last three examples show, how variable declarations are combined with a assgiment for initialization. The data type a variable holds during initialization, does not need to be the same data type the variable is holding at a later time.

Variables may be tested for beeing initilized or containing data not nil using the function isUndefined() .

var x;

isUndefined(x) => true

x = 456;

isUndefined(x) => false

The scope of variables defined inside a function is local to that function. The scope of a variable defined in a module other than the default module Main is local to that module.

Variables cannot only carry values assigned to them but can additionally carry an array of poperties. See the functions getProperty() and setProperty().


versionName ()

Returns the current version number and name of the NomarScript interpreter:

versionName() => 'NomarScript v3.31'


wait (number-ms)

Pauses Nomart execution for the number of milli seconds specified in number-ms then returns true.

wait(2000);

waits 2 seconds.


while

Using the while loop a statement of block of statements can be repeatedly excuted depending on the outcome of a condition:

var x = 0;
var y = 5;

while(x < y)
  {
  write(x);
  x += 1;
  }

would produce the output:

01234

See also the chaper in the Useres manual while loop .


windowFont (string, number-type, number-size)

Changes the font in the console window to the font name in string with a style specified in number-type and a point-size as specified in number-size.

windowFont('Arial', 0, 20)

Use number-type 1 for bold, 2 for italic and 3 for bold with italic.


write (variant-1, [variant-2 ...])

writes the content of variant-1 and optional variant-2 etc. to the current output device. The current output device is different in different run modes of write. In console mode the output is standard out (stdio) of the underlying opersting system. In console window mode the output is directed to the window. In HTTP mode and in telnet mode the output is sent to the connected client, which in most cases is a browser.

In case more than one argument is specified, a space is printed after each argument. write returns nil.

write(1, 2, 3, 'hello');

will produce:

1 2 3 hello

var x = [1,2,3];

write(x);

produces the output:

[1, 2, 3]


writeln (variant-1, [variant-2 ...])

Like write() but outputs a line feed character after each writeln().


XML.createDocument(array-xml-node)

Returnes a string containing a XML document created from the contents of array-xml-node.

var xmlNode =
     ['element', 'person', [['name', 'John Doe'],['telefone','555-1212']], nil];
XML.createDocument(xmlNode) =>

'<?xml version="1.0"?> <person name="John Doe" telefone="555-1212"/>'

XML nodes in Nomar may have the following different forms:

Node type From
comment ['comment' string-comment]
text ['text' string-text]
cdata ['cdata' string-cdata]
element ['element' string-tag-name, array-attributes, array-child-nodes]

- example comment node:

['comment' 'this is a comment']

- example text node:

['text' 'this is some text']

The text may not contain string which could be interpreted as XML. The translations &lgt; and &gt; can be used for the characters < and >.

- example CDATA node:

['cdata' 'this text can have special characters like tags: <,>']

CDATA text may contain special characters normally use in XML as tags with exception of the character sequence 'cdata]]>', which would signal the end of the character data string.

- example element node:

['element', 'person', [['name', 'John Doe'],['telefone','555-1212']], nil];

When a node doesn't contain any children nil holds the place for array-child-nodes. In this case XML in form of a closed tag is generated:

<person name="John Doe" telefone="555-1212"/>

If the empty array [] is specified, then a seperate close tag is generated:

['element', 'person', [['name', 'John Doe'],['telefone','555-1212']], []];

<person name="John Doe" telefone="555-1212"></person>


XML.getAttribute(array-xml-node, string-name)

Returns the attribute string for a parameter specified in string-name of an element node with attributes in array-xml-node.

var p =
     ['element', 'person', [['name', 'John Doe'],['telefone','555-1212']], nil];

XML.getAttribute(p, 'name') => 'John'
XML.getAttribute(p, 'telefone'] => '555-1212'


XML.getAttributeNames(array-xml-node)

Returns an array of parameter names from an element node with attributes array-xml-node.

var p =
     ['element', 'person', [['name', 'John Doe'],['telefone','555-1212']], nil];

XML.getAttributeNames(p) => ['name','telefone']


XML.getChildren(array-xm-node)

Returns an array of child nodes from an element node with attributes array-xml-node.

var p =
     ['element', 'person', [['name', 'John Doe'],['telefone','555-1212']],
    
[['text' 'a nice person']]];

XML.getChildren(p) => [['text' 'a nice person']]

In this eample the node p has one child node with is a text node. The original XML for p is:

XML.createDocument(p) =>

'<?xml version="1.0"?>
<person name="John Doe" telefone="555-1212">a nice person</person>'


XML.getText(array-xml-node)

Returns the text of a xml text node in array-xml-node.

var node = ['text' 'a nice person'];

XML.getText(node) => 'a nice person'


XML.lastError()

Returns an error string conatining a description of the last error ocurred when pasing a XML string using XML.parseDocument().


 

XML.parseDocument(string-xml)

Parses a XML document in string-xml and returns an array of xml nodes. The XML document is checked for well formed XML but DTDs (Document Type Declarations) are skipped as well as processing instruction in <?, ?> tags. In case of an error nil is returned and the function XML.lastError() can be used to identify the error caused by bad formed XML.

var str = '<person name="John Doe" telefone="555-1212">a nice person</person>'

XML.parseDocument(str) =>

['element', 'person', [['name', 'John Doe'], ['telefone', '555-1212']],
    
[['text', ';a nice person']]]


 

 

 


Copyright Lutz Mueller and Lumina Decision Systems Inc, 1999 - 2000