SkySpark by SkyFoundry

ext core

abs

abs(val)

Return absolute value of a number, if null return null

add

add(val, item)

Add item to the end of a list and return a new list.

addAll

addAll(val, items)

Add all the items to the end of a list and return a new list.

addCol

addCol(grid, col, fn)

Add a column to a grid by mapping each row to a new cell value. The col parameter may be a simple String name or may be a dictionary which must have a "name" tag (any other tags become column meta-data). The mapping function takes (row) and returns the new cell values for the column.

addColMeta

addColMeta(grid, name, meta)

Return a new grid with additional column meta-data.

addMeta

addMeta(grid, meta)

Add grid level meta-data tags.

addRow

addRow(grid, newRow)

Add an additional Dict row to the end of a grid.

addRows

addRows(grid, newRows)

Add an list of rows to the end of a grid. The newRows may be expressed as list of Dict or a Grid.

all

all(val, fn)

Return if all the items in a list, dict, or grid match the given test function. If the collection is empty, then return true.

If working with a list, the function takes (val) or (val, index) and returns true or false.

If working with a dict, the function takes (val) or (val, name) and returns true or false.

If working with a grid, the function takes (row) or (row, index) and returns true or false.

Examples:

[1, 3, 5].all v => v.isOdd  >>  true
[1, 3, 6].all(isOdd)        >>  false
any

any(val, fn)

Return if any the items in a list, dict, or grid match the given test function. If the collection is empty, then return false.

If working with a list, the function takes (val) or (val, index) and returns true or false.

If working with a dict, the function takes (val) or (val, name) and returns true or false.

If working with a grid, the function takes (row) or (row, index) and returns true or false.

Examples:

[1, 3, 5].any v => v.isOdd  >>  true
[2, 4, 6].any(isOdd)        >>  false
as

as(val, unit)

Set the unit of a number. Unlike to no conversion of the scalar of the number is performed. The target unit can be a unit string or a number in which case the scalar value of the unit parameter is ignored (by convention should be 1).

avg

avg(val, acc)

Fold multiple values into their standard average or arithmetic mean. This function is the same as math::mean. Null values are ignored. Return null if no values.

capitalize

capitalize(val)

Return this string with the first character converted to uppercase. The case conversion is for ASCII only.

chart

chart(val)

Set the grid visualization view to chart.

checkSyntax

checkSyntax(src)

Given an axon expression, validate the syntax. If there are no errors then return an empty grid. If there are errors then return a grid with the "err" tag and a "line" and "dis" column for each error found.

col

col(grid, name, checked: true)

Get a column by its name. If not resolved then return null or throw UnknownNameErr based on checked flag.

colNames

colNames(grid)

Get the column names a list of strings.

colToList

colToList(grid, col)

Get a column as a list of the cell values ordered by row.

cols

cols(grid)

Get the columns from a grid as a list.

colsToLocale

colsToLocale(grid)

Map each col display string to its localized tag name if the col does not already have a display string. Also see Grid.colsToLocale and Localization.

commit

commit(diffs)

Commit a diff or list of diffs to the folio database.

If one diff is passed, return the new record. If a list of diffs is passed return a list of new records.

Examples:

// add new record
newRec: commit(diff(null, {dis:"New Rec!"}, {add}))

// add someTag to some group of records
readAll(filter).toRecList.map(r => diff(r, {someTag})).commit

Side effects:

  • writes to folio database
  • clears context read cache
concat

concat(list, sep: "")

Concatenate a list of items into a string.

Examples:

[1, 2, 3].concat       >>  "123"
[1, 2, 3].concat(",")  >>  "1,2,3"
contains

contains(val, x)

Return if val contains x:

  • if val is Str, then x is substring.
  • if val is List, then x is item to search.
  • if val is Range, then is x inside the range inclusively
  • if val is DateSpan, then is x a date in the span
context

context()

Get the current context as a Dict with the following tags:

  • username for current user
  • userRef if user maps to a rec in current project
  • projName if evaluating in context of a project
  • ruleRef if evaluating in context of a spark engine rule
  • locale current locale
coord

coord(lat, lng)

Construct a Coord from two Numbers in decimal degrees

coordDist

coordDist(c1, c2)

Given a two Coords, compute the great-circle distance between them in meters using the haversine forumula.

coordLat

coordLat(coord)

Latitude of a Coord as a Number

coordLng

coordLng(coord)

Longitude of a Coord as a Number

count

count(val, acc)

Fold multiple values into their total count Return zero if no values.

curFunc

curFunc()

Get the current top-level function's tags.

date

date(val, month: null, day: null)

If val is a DateTime: get date portion of the timestamp. If val is a Number: construct a date instance from year, month, day

Examples:

now().date         // same as today()
date(2010, 12, 1)  // same as 2010-12-01
dateTime

dateTime(d, t, tz: null)

Construct a DateTime from a date, time, and timezone name. If timezone is null, use system default.

day

day(d)

Get day of month as integer between 1 to 31 from date or datetime.

debugType

debugType(val)

Return a string of the given value's type. No guarantee is made for the string's format. Applications must not assume any specific format, this function if for human consumption only.

decapitalize

decapitalize(val)

Return this string with the first character converted to lowercase. The case conversion is for ASCII only.

diff

diff(orig, changes, flags: null)

Construct a modification "diff" used by commit. The orig should be the instance which was read from the project, or it may be null only if the add flag is passed. Any tags to add/set/remove should be included in the changes dict.

The following flags are supported:

  • add: indicates diff is adding new record
  • remove: indicates diff is removing record (in general you should add trash tag instead of removing)
  • transient: indicate that this diff should not be flushed to persistent storage (it may or may not be persisted).
  • force: indicating that changes should be applied regardless of other concurrent changes which may be been applied after the orig version was read (use with caution!)

Examples:

// create new record
diff(null, {dis:"New Rec", someMarker}, {add})

// create new record with explicit id like Diff.makeAdd
diff(null, {id:151bd3c5-6ce3cb21, dis:"New Rec"}, {add})

// set/add dis tag and remove oldTag
diff(orig, {dis:"New Dis", -oldTag})

// set/add val tag transiently
diff(orig, {val:123}, {transient})
dis

dis(dict, name: null, def: "")

Get display string for dict or the given tag. If name is null, then return display text for the entire dict using Etc.dictToDis. If name is non-null then format the tag value using its appropiate toLocale method. Also see Dict.dis.

dst

dst(dt)

Given a DateTime in a specific timezone, return true if the time is in daylight savings time or false if standard time.

each

each(val, fn)

Iterate the items of a collection:

  • Grid: iterate the rows as (row, index)
  • List: iterate the items as (value, index)
  • Dict: iterate the name/value pairs (value, name)
  • Range: iterate the integer range (integer)
eachDay

eachDay(dates, f)

Iterate the days for where dates may be any object converted into a date range by toDateSpan. The given function is called with a Date argument for each iterated day.

Example:

f: day => echo(day)
eachDay(2010-07-01..2010-07-03, f) >> iterate Jul 1st, 2nd, 3rd
eachDay(2010-07, f)                >> iterate each day of July 2010
eachDay(pastWeek, f)               >> iterate last 7 days
eachMonth

eachMonth(dates, f)

Iterate the months for where dates may be any object converted into a date range by toDateSpan. The given function is called with a DateSpan argument for each interated month.

Examples:

// iterate each month in 2010, and echo data range
eachMonth(2010) d => echo(d)

// call f once for current method
eachMonth(today(), f)
eachWhile

eachWhile(val, fn)

Iterate the items of a collection until the given function returns non-null, then break the iteration and return the resulting object. Return null if the function returns null for every item.

  • Grid: iterate the rows as (row, index)
  • List: iterate the items as (value, index)
  • Dict: iterate the name/value pairs (value, name)
  • Range: iterate the integer range (integer)
echo

echo(x)

Write the string represenation of x to standard out. Return x as result.

Side effects:

  • performs I/O to stdout
end

end(val)

End value of a DateSpan, DateTimeSpan, or a range.

endsWith

endsWith(val, sub)

Return if Str ends with the specified Str.

eval

eval(expr)

Evaluate the given expression formatted as a string.

exts

exts(opts: null)

List the extensions available for the system. Return grid with following columns:

  • name: programatic unique name for extension
  • dis: display name of extension (based on opts->locale)
  • extStatus: ok, disabled, unlicenced, licFault, warn
  • extStatusMsg: description of status error
  • enabled: marker tag for extensions currently enabled on cur project
  • id: record id if enabled
  • app: qualified type of Fantom app if extension publishes a UI app
  • settings: qualified type of Fantom pane if extension publishes a settings UI
  • admin: marker if app requires admin permissions
  • icon24: uri to 24x24 icon
  • icon72: uri to 72x72 icon
  • iconTable: uri to 16x16 icon to use in tabular displays
  • depends: list of extension names separated by comma

The options parameter supports following tags:

  • locale: language locale formatted as Locale.toStr
fandoc

fandoc(text)

Construct view which renders text formatted as fandoc

filterToFunc

filterToFunc(filterExpr)

Convert a filter expression to a function which may be used with findAll or find. The returned function accepts one parameter of Dicts and returns true/false if the Dict is matched by the filter. Also see parseFilter.

Examples:

// filter for dicts with 'equip' tag
list.findAll(filterToFunc(equip))

// filter rows with an 'area' tag over 10,000
grid.findAll(filterToFunc(area > 10_000))
find

find(val, fn)

Find the first matching item in a list or grid by applying the given filter function. If no match is found return null.

If working with a list, the filter should be a function that takes (val) or (val, index). It should return true to match and return the item.

If working with a dict, the filter should be a function that takes (val) or (val, name). It should return true to match and return the item.

If working with a grid, the filter function takes (row) or (row, index) and returns true to match and return the row.

findAll

findAll(val, fn)

Find all the items in a list, dict, or grid by applying the given filter function. Also see find.

If working with a list, the filter should be a function that takes (val) or (val, index). It should return true to keep the item.

If working with a dict, the filter should be a function that takes (val) or (val, name). It should return the true to keep the name/value pair.

If working with a grid, the filter function takes (row) or (row, index) and returns true to keep the row. The resulting grid shares the original's grid meta and columns.

first

first(val)

Get the first item from an ordered collection or return null if the collection is empty:

  • list: item at index 0
  • grid: first frow
fold

fold(list, fn)

Fold a list into a single value using a folding function with the signature of (val, acc) where val is the items being folded, and acc is an accumulator used to maintain state between interations. Lifecycle of a fold:

  1. Call fn(foldStart, null), return initial accumulator state
  2. Call fn(item, acc) for every item, return new accumulator state
  3. Call fn(foldEnd, acc) return final result

The fold will short-circuit and halt immediately if the folding function returns na for the accumulator state. The result of the fold is na in this case. A folding function should document its behavior when a collection contains na.

Example:

[1, 2, 3, 4].fold(max)  // fold list into its max value
[1, 2, 3, 4].fold(avg)  // fold list into its average value
[1, 2, na(), 3].fold(sum) // => na()

Example of writing your own custom fold function that used start/end values and has support for na():

average: (val, acc) => do
  if (val == foldStart()) return {sum:0, count:0}
  if (val == foldEnd()) return acc->sum / acc->count
  if (val == na()) return na()
  return {sum: acc->sum + val, count: acc->count + 1}
end
foldCol

foldCol(grid, colName, fn)

Fold the values of the given column into a single value using a folding function using same semantics as fold.

foldCols

foldCols(grid, colSelector, newColName, fn)

Fold a set of columns in each row into a new folded column and return a new grid. The columns to fold are selected by the colSelector function and removed from the result. The selector may be a list of string names or a function which takes a Col and returns true to select it. The folding function uses same semantics as fold.

Example:

// consider grid 'g' with the following structure:
a    b    c
---  ---  ---
1    10   100
2    20   200

// foldCols, add b and c together to create new bc column
g.foldCols(["b", "c"], "bc", sum)

// yields this grid:
a    bc
---  ---
1    110
2    220

// we could also replace list of col names with a function
colSel: col => col.name == "b" or col.name == "c"
g.foldCols(colSel, "bc", sum)
foldEnd

foldEnd()

The fold end marker value TODO: this API is subject to change

foldStart

foldStart()

The fold start marker value TODO: this API is subject to change

folioCompact

folioCompact()

Asynchronously kick off a database compaction operation for current project. Requires super user permission. See Proj.compact. To run a compaction in a background job use jobFolioCompact.

folioEmptyTrash

folioEmptyTrash()

Delete all the records marked with trash tag. See Proj.emptyTrash

folioRestore

folioRestore(ts, opts: null)

Restore snapshot identified by given timestamp Requires super user permission. See Proj.restore

folioSetMode

folioSetMode(mode)

Set folio database mode: "ro", "rw", "disabled" Requires super user permission. See Proj.mode

folioSnapshot

folioSnapshot()

Asynchronously kick off a new snapshot for current project. Requires super user permission. See Proj.snapshot To run a snapshot a background job use jobFolioSnapshot.

folioSnapshotDelete

folioSnapshotDelete(ts)

Delete a snapshot file by its timestamp. Return true if snapshot found and deleted of false otherwise. Requires super user permission.

folioSnapshots

folioSnapshots()

List all the snapshots for the current project:

  • ts: timestamp of snapshot
  • size: size in bytes of snapshot
format

format(val, pattern: "")

Format an object using the current locale and specified format pattern. Formatting patterns follow Fantom toLocale conventions:

fromJavaMillis

fromJavaMillis(millis, tz: null)

Given Number of milliseconds since Unix epoch of 1-Jan-1970 UTC, return a DateTime in given timezone. If timezone is null, use system default. Also see toJavaMillis.

func

func(name, checked: true)

Find a top-level function by name and return its tags. If not found throw exception or return null based on checked flag.

funcs

funcs(filterExpr: null)

Find all the top-levels functions in the current project which match the given filter. If the filter is omitted then return all the functions declared in the current project. The function tags are returned. This function automatically removes tags which would be expensive to send over the network like doc and src. An override column is added to indicate if the function if a rec function which overrides a core/extension function.

Examples:

funcs()                // all functions
funcs(ext == "hvac")   // match filter
get

get(val, key)

Get an item from a collection:

  • str(num): get character at index as int (same semanatics as Fantom)
  • str(range): get string slice (same semanatics as Fantom)
  • list(num): get item at given index (same semanatics as Fantom)
  • list(range): get list slice at given index (same semanatics as Fantom)
  • dict(key): get item with given key or return null
  • grid(num): get row at given index
  • grid(range): Grid.getRange

The get function maybe be accessed using the [] shortcut operator:

list[3]  >>  list.get(3)

See Axon Language.

getSafe

getSafe(val, key)

Get an item from a str, list, or grid safely when an index is out of bounds:

  • str(num): get a character at index or null if index invalid
  • str(range): get safe slice or "" if entire range invalid
  • list(num): get item at given index or null is index invalid
  • list(range): get list slice with safe index
  • grid(num): get row at given index or null if index invalid
  • grid(range): Grid.getRange with safe range
gridColKinds

gridColKinds(grid)

Given a grid return the types used in each column as a grid with the following:

  • name: string name of the column
  • kind: all the different value kinds in the column separated by "|"
  • count: total number of rows with column with a non-null value Also see readAllTagNames.
gridColsToDict

gridColsToDict(grid, colToKey, colToVal)

Convert a grid into a dict of name/val pairs which are derived from each column using the given functions. The functions take (col, index)

gridFormats

gridFormats()

Return grid formats installed. See GridFormat

gridRowsToDict

gridRowsToDict(grid, rowToKey, rowToVal)

Convert a grid into a dict of name/val pairs which are derived from each row using the given functions. The functions take (row, index)

has

has(val, name)

If val is a Grid return if it has the given column name. If val is a Dict return if the given name is mapped to a non-null value.

heading

heading(text)

Construct heading view

hour

hour(t)

Get hour of day as integer between 0 to 23 from time or datetime

hoursInDay

hoursInDay(dt)

Given a DateTime in a specific timezone, return the number of hours in the day. Dates which transition to DST will be 23 hours and days which transition back to standard time will be 25 hours.

index

index(val, x, offset: 0)

Return the first match of x in val searching forward, starting at the specified offset index. A negative offset may be used to access from the end of string. Return null if no occurences are found:

  • if val is Str, then x is substring.
  • if val is List, then x is item to search.
indexr

indexr(val, x, offset: Number.negOne)

Return the last match of x in val searching backward, starting at the specified offset index. A negative offset may be used to access from the end of string. Return null if no occurences are found:

  • if val is Str, then x is substring.
  • if val is List, then x is item to search.
insert

insert(val, index, item)

Insert an item into a list at the given index and return a new list.

insertAll

insertAll(val, index, items)

Insert a list of items at the given index and return a new list.

invoke

invoke(rec, action, args: {})

Invoke an action on the given rec (any value supported by toRec). The record must have a valid actions grid configured with a dis string matching the the action parameter. See Actions.

isAlpha

isAlpha(num)

Is number an ASCII alpha char: isUpper||isLower

isAlphaNum

isAlphaNum(num)

Is number an ASCII alpha-numeric char: isAlpha||isDigit

isBool

isBool(val)

Return if an object is a boolean type

isDate

isDate(val)

Return if an object is a Date type

isDateTime

isDateTime(val)

Return if an object is a DateTime type

isDict

isDict(val)

Return if an object is a dict type

isDigit

isDigit(num, radix: 10)

Is number a digit in the specified radix. A decimal radix of ten returns true for 0-9. A radix of 16 also returns true for a-f and A-F.

isEmpty

isEmpty(val)

Return if a collection is empty: str, list, dict, or grid

isEven

isEven(val)

Return if an integer is an even number.

isFunc

isFunc(val)

Return if an object is a function type

isGrid

isGrid(val)

Return if an object is a grid type

isKeyword

isKeyword(val)

Return if given string is an Axon keyword

isList

isList(val)

Return if an object is a list type

isLower

isLower(num)

Is number an ASCII lowercase alphabetic char: a-z

isMetric

isMetric(val: null)

Given an optional value return true if the SI metric system should be used or false if the United States customary unit system should be used. The following rules are used:

  • if val is a dict with geoCountry return return false if "US"
  • if number or rec with unit and unit is known to be a US customary unit return false (right now we only check for °F and Δ°F)
  • fallback to locale of hosting server, see Locale

Examples:

isMetric({geoCountry:"US"})  >>  false
isMetric({geoCountry:"FR"})  >>  true
isMetric(75°F)               >>  false
isMetric({unit:"Δ°C"})       >>  true
isMetric()                   >>  fallback to server locale
isNaN

isNaN(val)

Return if val is the Number representation of not-a-number

isNumber

isNumber(val)

Return if an object is a number type

isOdd

isOdd(val)

Return if an integer is an odd number.

isRef

isRef(val)

Return if an object is a ref type

isSpace

isSpace(num)

Is number is whitespace char: space \t \n \r \f

isStr

isStr(val)

Return if an object is a str type

isTagName

isTagName(n)

Return if the given string is legal tag name - see Etc.isTagName

isTime

isTime(val)

Return if an object is a Time type

isUpper

isUpper(num)

Is number an ASCII uppercase alphabetic char: A-Z

isUri

isUri(val)

Return if an object is a Uri type

isWeekday

isWeekday(t)

Does the given Date or DateTime fall on Mon, Tue, Wed, Thu, or Fri

isWeekend

isWeekend(t)

Does the given Date or DateTime fall on Sat or Sun

join

join(a, b, joinColName)

Join two grids by column name. Current implementation requires:

  • grids cannot have conflicting col names (other than join col)
  • each row in both grids must have a unique value for join col
  • grid level meta is merged
  • join column meta is merged
joinAll

joinAll(grids, joinColName)

Join a list of grids into a single grid. See join.

keepCols

keepCols(grid, cols)

Return a new grid with keeps the given columns, but removes all the others. Columns can be Str names or Col instances.

last

last(val)

Get the last item from an ordered collection or return null if the collection is empty:

  • list: item at index -1
  • grid: item at index -1
lastMonth

lastMonth()

DateSpan for month previous to this month 1..28-31

lastWeek

lastWeek()

DateSpan for week previous to this week sun..sat (uses locale start of week)

lastYear

lastYear()

DateSpan for year previous to this year Jan-1..Dec-31

log

log(level, category, msg, err: null)

Submit a log record to the logging subsystem:

  • level: must be "err", "warn", "info" (same as LogLevel).
  • category: grouping name of log, must be valid tag name
  • msg: short single line summary of message to log
  • err: exception from catch block that includes errTrace tag

Logs are stored on a per project basis in the "logs/" directory of each project's top-level directory. Host level logs are stored in "logs/" of the SkySpark installation directory.

Fantom logging using the Log API is automically mapped into project logging. When the current actor can be associated with a specific project, then it logged into the appropiate project, otherwise it is logged at the host level. To ensure logging with the correct project, use Proj.log instead of Log.get.

If this function is called within the context of a job run then we also sent this message to the job's runtime log.

In general you should prefer logErr, logWarn, and logInfo. Also see logRead.

logDebug

logDebug(category, msg, err: null)

Log at the "debug" level - see log.

logErr

logErr(category, msg, err: null)

Log at the "err" level - see log.

logInfo

logInfo(category, msg, err: null)

Log at the "info" level - see log.

logRead

logRead(dates)

Read the log file for the given dates range and optional filter. Dates can be any object supported by toDateSpan. Result is returned as grid with these cols:

  • ts: timestamp of the log record (in host's current timezone)
  • level: "err", "warn", "info"
  • category: grouping name of log items
  • msg: short single line summary
  • errTrace: error trace string or null

Also see log.

logWarn

logWarn(category, msg, err: null)

Log at the "warn" level - see log.

lower

lower(val)

Convert a char number or str to lower case

map

map(val, fn)

Map list, dict, or grid by applying the given mapping function.

If mapping a list, the mapping should be a function that takes (val) or (val, index). It should return the new value for that index.

If mapping a dict, the mapping should be a function that takes (val) or (val, name). It should return the new value for that name.

If mapping a grid, the mapping function takes (row) or (row,index) and returns a new dictionary to use for the row. The resulting grid shares the original's grid level meta. Columns left intact share the old meta-data, new columns have no meta-data. If the mapping function returns null, then that row is removed from the resulting grid (not mapped).

If mapping a range, then the mapping function takes (integer), and returns a list for each mapped integer inte the range.

marker

marker()

Get the marker value singleton Marker.val

max

max(val, acc)

Compare two numbers and return the larger one. This function may also be used with fold to return the largest number (or null if no values).

Examples:

max(7, 4)            >>  7
[7, 2, 4].fold(max)  >>  7
merge

merge(a, b)

Merge two Dicts together and return a new Dict. Any tags in b are added to a. If b defines a tag already in a, then it is overwritten by b. If a tag in b is mapped to Remove.val, then that tag is removed from the result.

meta

meta(val)

Get the meta-data from a grid or col as a dict.

min

min(val, acc)

Compare two numbers and return the smaller one. This function may also be used with fold to return the smallest number (or null if no values).

Examples:

min(7, 4)            >>  4
[7, 2, 4].fold(min)  >>  2
minute

minute(t)

Get minutes of the time as integer between 0 to 59 from time or datetime

missing

missing(val, name)

If val is a Grid return if it does not have given column name. If val is a Dict, return if the given name is not mapped to a non-null value.

month

month(d)

Get month as integer between 1 to 12 from date or datetime

moveTo

moveTo(list, item, toIndex)

Find the given item in a list, and move it to the given index. All the other items are shifted accordingly. Negative indexes may used to access an index from the end of the list. If the item is not found then this is a no op. Return new list.

Examples:

[10, 11, 12].moveTo(11, 0)  >>  [11, 10, 12]
[10, 11, 12].moveTo(11, -1) >>  [10, 12, 11]
na

na()

Get NA not-available singleton NA.val

name

name(val)

If val is a Col, get the column name. If val is a Uri, get the last name in the path.

names

names(dict)

Get the list of names used by a given dict

nan

nan()

Return the Number representation of not-a-number

navChildren(treeName, base: null, opts: null)

Return a grid of the given base records navigation direct children. If base is null, then return the top-level navigation records.

Parameters:

  • treeName: string key of which tree to navigate such as "equip"
  • base: Ref or record Dict of base to navigate to
  • opts: null or Dict of options

Options:

  • stop: stop tag, example "site" if searching "equip" tree for just sites

Resulting grid as sames columns as navLevels. Also see NavTrees.

TODO: this function is subject to change

navCommonAncestor(treeName, recs)

Given a navigation tree name and list of records (anything supported by toRecList), return the common ancestor base record that they all share. For example given a list of points under an equip, then the parent equip is returned. But a set of points in different equipment, but same site will return the site record. Return result as Dict or null if no common ancestor is found.

TODO: this function is subject to change

navFilter(treeName, bases, opts: null)

Return a grid used to represent a navigation filter under one or more base recs. The filter defines the meta tag navFilter to distinguish it from other types of grids. The grid defines a single id column for the identifier and display name of each record in the filter.

If the base is null, then we assume the root of the entire tree. If the string literal "default", then a user specific or project specific default filter is used.

Options:

  • targetTag: tag name for all recs in tree we are looking for, or if omitted, then all recs in tree under base
  • auxFilter: string with filter auxiliary applied to each level of the tree

Also see NavTrees.

TODO: this function is subject to change

navLevels(treeName, base: null, opts: null)

Return a grid to populate a navigation multi-pane dialog. Given a base record return a list of records at each level of the tree above the base as well as the direct children of the base.

Parameters:

  • treeName: string key of which tree to navigate such as "equip"
  • base: Ref or record Dict of base to navigate to
  • opts: null or Dict of options

Options:

  • stop: stop tag, example "site" if searching "equip" tree for just sites
  • search: search string, if defined then return any record in the navigation tree that contains the case insensitive search string in its dis string
  • auxFilter: string with filter auxiliary applied to each level of the tree
  • limit: search limit (defaults to 1000)

Resulting grid has following columns:

  • level: 0 for for top level, down to level n based on navigation depth
  • id: Ref of record
  • indent: if level is organized as sub-tree (equip containing equips)
  • icon16: URI to best 16x16 icon to use
  • selected: if this is selected record in navigation path
  • children: if use can "dive down" into this record

Also see NavTrees.

TODO: this function is subject to change

navTrees()

List the navigation trees available for the current project. Return grid with following columns:

  • treeName: programmatic name of tree
  • dis: display name of the tree
  • path: Str path syntax
  • depend: tree name if this tree is dependent
  • builder: Marker if this tree should show up in Builder

TODO: this function is subject to change

negInf

negInf()

Return the Number representation negative infinity

now

now()

Return current DateTime according to context's time zone

nowTicks

nowTicks()

Return current time as nanosecond ticks since 1 Jan 2000 UTC. Note that the 64-bit floating point representations of nanosecond ticks will loose accuracy below the microsecond.

numDaysInMonth

numDaysInMonth(month: null)

Get the number of days in a given month. The month parameter may be:

  • Date: returns number of days in given month (uses month/year, ignores day)
  • Number 1-12: returns days in month for current year
  • null: returns day in current month

Examples:

numDaysInMonth()            >>>  days in current month
numDaysInMonth(1)           >>>  31day (days in January)
numDaysInMonth(6)           >>>  30day (days in June)
numDaysInMonth(2)           >>>  28day or 29day (days for Feb this year)
numDaysInMonth(2012-02-13)  >>>  29day (days in Feb for leap year)
occurred

occurred(ts, range)

Return if a timestamp is contained within a Date range. Range may be any value supported by toDateSpan. Timestamp may be either a Date or a DateTime. Also see contains.

Examples:

ts.occurred(thisWeek)
ts.occurred(pastMonth())
ts.occurred(2010-01-01..2010-01-15)
padl

padl(val, width, char: " ")

Pad string to the left. If size is less than width, then add the given char to the left to achieve the specified width.

Examples:

"3".padl(3, "0")    >>  "003"
"123".padl(2, "0")  >>  "123"
padr

padr(val, width, char: " ")

Pad string to the right. If size is less than width, then add the given char to the left to acheive the specified with.

Examples:

"xyz".padr(2, ".")  >>  "xyz"
"xyz".padr(5, "-")  >>  "xyz--"
params

params(fn)

Given a function name reflect its parameters as rows with the following columns:

  • name: programtic name of the parameter
  • def: default value if available otherwise null

Example:

hisRead.params
parseBool

parseBool(val, checked: true)

Parse a Str into a Bool, legal formats are "true" or "false. If invalid format and checked is false return null, otherwise throw ParseErr.

parseDate

parseDate(val, pattern: "YYYY-MM-DD", checked: true)

Parse a Str into a Date. If the string cannot be parsed into a valid Date and checked is false then return null, otherwise throw ParseErr. See Date.toLocale for pattern.

parseDateTime

parseDateTime(val, pattern: "YYYY-MM-DD'T'hh:mm:SS.FFFFFFFFFz zzzz", tz: now().tz, checked: true)

Parse a Str into a DateTime. If the string cannot be parsed into a valid DateTime and checked is false then return null, otherwise throw ParseErr. See DateTime.toLocale for pattern.

parseFilter

parseFilter(val, checked: true)

Parse a string into a Filter expr which may be used with the read or readAll function. Also see filterToFunc. This function must be used directly as the parameter to read or readAll (it cannot be assigned to a temporary variable).

Example:

str: "point and kw"
readAll(parseFilter(str))
parseFloat

parseFloat(val, checked: true)

Parse a Str into a Float. Representations for infinity and not-a-number are "-INF", "INF", "NaN". If invalid format and checked is false return null, otherwise throw ParseErr. This string value cannot include a unit (see parseNumber).

parseInt

parseInt(val, radix: 10, checked: true)

Parse a Str into a integer number using the specified radix. If invalid format and checked is false return null, otherwise throw ParseErr. This string value cannot include a unit (see parseNumber).

parseNumber

parseNumber(val, checked: true)

Parse a Str into a number with an option unit. If invalid format and checked is false return null, otherwise throw ParseErr. Also see parseInt and parseFloat to parse basic integers and floating point numbers without a unit.

parseRef

parseRef(val, checked: true)

Parse a Str into a Ref. If the string is not a valid Ref identifier then raise ParseErr or return null based on checked flag.

parseTime

parseTime(val, pattern: "hh:mm:SS", checked: true)

Parse a Str into a Time. If the string cannot be parsed into a valid Time and checked is false then return null, otherwise throw ParseErr. See Time.toLocale for pattern.

parseUnit

parseUnit(val, checked: true)

Parse a Str into a standardized unit name. If the val is not a valid unit name from the standard database then return null or raise exception based on checked flag.

parseUri

parseUri(val, checked: true)

Parse a string into a Uri instance. If the string cannot be parsed into a valid Uri and checked is false then return null, otherwise throw ParseErr. This function converts an URI from standard form. Use uriDecode to convert a string from escaped form. See Uri for a detailed discussion on standard and escaped forms.

Examples:

"foo bar".parseUri     >>  `foo bar`
"foo%20bar".uriDecode  >>  `foo bar`
passwordGenSalt

passwordGenSalt()

Generate a new, unique random string to use for the userSalt tag. See PasswordManager.genSalt.

passwordHmac

passwordHmac(user, pass, salt)

Generate SHA-1 HMAC which is "user:salt".hmac(pass). Result is base64 encoded. See PasswordManager.hmac.

passwordSet

passwordSet(key, val)

Store a password key/val pair into current project's password manager. The key is typically a Ref of the associated record and val is either a HMAC or plaintext password. See Proj.passwords.

Current behavior allows both su and admins to set any password.

pastMonth

pastMonth()

DateSpan for last 30days today-30days..today

pastWeek

pastWeek()

DateSpan for last 7 days as today-7days..today

pastYear

pastYear()

DateSpan for this past today-365days..today

posInf

posInf()

Return the Number representation positive infinity

reFind

reFind(regex, s)

Find the first match of regular expression in s or return null if no matches. See AxonUsage.

Examples:

reFind(r"\d+", "x123y")  >>  "123"
reFind(r"\d+", "xyz")    >>  null
reGroups

reGroups(regex, s)

Return a list of the substrings captured by matching the given regular operation against s. Return null if no matches. The first item in the list is the entire match, and each additional item is matched to () arguments in the regex pattern. See AxonUsage.

Examples:

re: r"(RTU|AHU)-(\d+)"
reGroups(re, "AHU")    >> null
reGroups(re, "AHU-7")  >> ["AHU-7", "AHU", "7"]
reMatches

reMatches(regex, s)

Return if regular expression matches entire region of s. See AxonUsage.

Examples:

reMatches(r"\d+", "x123y")  >>  false
reMatches(r"\d+", "123")    >>  true
read

read(filterExpr, checked: true)

Read from database first record which matches filter. If no matches found throw UnknownRecErr or null based on checked flag. See readAll for how filter works.

readAll

readAll(filterExpr)

Reall all records from the database which match filter. The filter must an expression which matches the filter structure. String values may parsed into a filter using parseFilter function.

readAllTagNames

readAllTagNames(filterExpr)

Return the intersection of all tag names used by all the records matching the given filter. The results are returned as a grid with following columns:

  • name: string name of the tag
  • kind: all the different value kinds separated by "|"
  • count: total number of recs with the tag Also see readAllTagVals and gridColKinds.
readAllTagVals

readAllTagVals(filterExpr, tagName)

Return the range of all the values mapped to a given tag name used by all the records matching the given filter. This method is capped to 200 results. The results are returned as a grid with a single val column. Also see readAllTagNames.

readById

readById(id, checked: true)

Read a record from database by id. If not found throw UnknownRecErr or return null based on checked flag.

readByIds

readByIds(ids, checked: true)

Read a list of record ids into a grid. The rows in the result correspond by index to the ids list. If checked is true, then every id must be found in the project or UnknownRecErr is thrown. If checked is false, then an unknown record is returned as a row with every column set to null (including the id tag).

readByName

readByName(name, checked: true)

Read a record from database by name. If not found throw UnkownRecErr or return null based on checked flag.

readCount

readCount(filterExpr)

Return the number of records which match the given filter expression.

readLink(id)

Read a record Dict by its id for hyperlinking in a UI. Unlike other reads which return a Dict, this read returns the columns ordered in the same order as reads which return a Grid.

readProjStatus

readProjStatus(projName: null)

Read status and meta-data information for given project, or if name is null then read for current project. Requires super user permission if project name is specified.

refGen

refGen()

Generate a new unique Ref identifier

remove

remove(val, key)

Remove an item from a collection and return a new collection.

If val is a list, then key is index to remove at.

If val is a dict, then item is name key.

removeCol

removeCol(grid, name)

Return a new grid with the given column removed. If the column doesn't exist, then return given grid.

removeCols

removeCols(grid, cols)

Return a new grid with all the given columns removed. Columns can be Str names or Col instances.

removeMarker

removeMarker()

Get the remove value singleton Remove.val

renameCol

renameCol(grid, oldName, newName)

Return a new grid with the given column renamed.

renameId

renameId(from, to)

Convenience for renameIds with one id pair.

Example:

renameId(@19a683ac-145e5a69, @SiteA)

TODO: this feature is experimental

renameIds

renameIds(mapping)

Rename every occurance of a given set of ids where the keys are the from id and the vals are the to id. This swizzles the id tag of the records as well as any Ref tags that point to that record. Raise an exception if any record to rename has a Bin tag. Also see Proj.renameIds.

This function takes a Dict where the keys are from id strings and the values are to Refs. Or the mapping may be a Grid with a from and to column and all the cells are Refs.

Examples:

renameIds({"a.old":@a.new, "b.old":@b.new})
renameIds([{from:@a.old, to:@a.new}, {from: @b.old to: @b.new}].toGrid)

TODO: this feature is experimental

reorderCols

reorderCols(grid, colNames)

Return a new grid with the columns reordered. The given list of names represents the new order and must contain the same current column names. Also see colNames and moveTo.

Example:

// move name to first col, and foo to last col
cols: grid.colNames.moveTo("name", 0).moveTo("foo", -1)
return grid.reorderCols(cols)
replace

replace(val, from, to)

String replace of all occurrences of from with to. All three parameters must be strings.

Examples:

"hello".replace("hell", "t")  >>  "to"
"aababa".replace("ab", "-")   >>  "a--a"
second

second(t)

Get seconds of the time as integer between 0 to 59 from time or datetime

set

set(val, key, item)

Set a collection item and return a new collection.

If val is a list, then set item by index key.

If val is a dict, then set item by key name.

size

size(val)

Return number of items in str, list, or grid

sort

sort(val, sorter: null)

Sort a list or grid.

If sorting a list, the sorter should be a function that takes two list items and returns -1, 0, or 1 (typicaly done with the <=> operator. If no sorter is passed, then the list is sorted by its natural ordering.

If sorting a grid, the sorter can be a column name or a function. If a function, it should take two rows and return -1, 0, or 1.

sortr

sortr(val, sorter: null)

Reverse sort a list or grid. This function works just like sort except sorts in reverse.

split

split(val, sep)

Split a string by the given separator and trim whitespace. If sep is a space then by whitespace. Sep must be exactly one char.

spread

spread(val, acc)

Fold multiple values to compute the difference between the max and min value (the range b/w min and max). Return null if no values.

start

start(val)

Start value of a DateSpan, DateTimeSpan or a range.

startsWith

startsWith(val, sub)

Return if Str starts with the specified Str.

sum

sum(val, acc)

Fold multiple values into their numeric sum. Return null if no values.

swizzleRefs

swizzleRefs(grid)

Given a grid of records, assign new ids and swizzle all internal ref tags. Each row of the grid must have an id tag. A new id is generated for each row, and any Ref tags which used one of the old ids is replaced with the new id. This function is handy for copying graphs of recs such as site/equip/point trees.

table

table(val)

Set the grid visualization view to table.

tags

tags(filterExpr: null)

Find all the tags in the current project which match the given filter. If the filter is omitted then return all the tags declared in the current project.

Examples:

tags()                // all tags
tags(lib == "hvac")   // match filter
thisMonth

thisMonth()

DateSpan for this month as 1st..28-31

thisWeek

thisWeek()

DateSpan for this week as sun..sat (uses locale start of week)

thisYear

thisYear()

DateSpan for this year Jan-1..Dec-31

time

time(val, minutes: null, secs: 0)

If val is a DateTime: get time portion of the timestamp. If val is a Number: construct a time instance from hour, minutes, secs (truncated to nearest second).

Examples:

now().time      // current time
time(20, 45)    // same as 20:45
times

times(times, f)

Call the specified function the given number of times passing the counter.

to

to(val, unit)

Convert a number to the given unit. If the units are not of the same dimension then an exception is raised. The target unit can be a string or a Number. If target unit is a Number, then the scalar value is ignored, but by convention should be 1.

toAxonCode

toAxonCode(val)

Convert a scalar, list, or dict value to its Axon code representation

toChar

toChar(num)

Convert a unicode char number into a single char string

toDateSpan

toDateSpan(r)

Convert the following objects into a DateSpan:

  • Date..Date: starting and ending date
  • Date..Number: starting date and num of days (day unit required)
  • Date: one day range
  • Number: convert as year
  • Func: function which evaluates to date range
  • DateTime..DateTime: use starting/ending dates; if end is midnight, then use previous date
  • Str: evaluates to DateSpan.fromStr
  • null: use projMeta dateSpanDefault or default to today

Examples:

toDateSpan(2010-07-01..2010-07-03)  >>  01-Jul-2010..03-Jul-2010
toDateSpan(2010-07-01..4)           >>  01-Jul-2010..04-Jul-2010
toDateSpan(2010-07-01..60day)       >>  01-Jul-2010..29-Aug-2010
toDateSpan(2010-07)                 >>  01-Jul-2010..31-Jul-2010
toDateSpan(2010)                    >>  01-Jan-2010..31-Dec-2010
toDateSpan(pastWeek) // on 9 Aug    >>  02-Aug-2010..09-Aug-2010
toDateTimeSpan

toDateTimeSpan(a, b: null)

Convert the following objects into a DateTimeSpan:

  • DateSpan,tz: anything accepted by toDateSpan plus a Timezone string
  • DateTime..DateTime: range of two DateTimes
toGrid

toGrid(val, opts: null)

Given an arbitrary object, translate it to a Grid via Etc.toGrid:

  • if grid just return it
  • if row in grid of size, return row.grid
  • if scalar return 1x1 grid
  • if dict return grid where dict is only
  • if list of dict return grid where each dict is row
  • if list of non-dicts, return one col grid with rows for each item

Example:

// create simple grid with dis,age cols and 3 rows:
[{dis:"Bob", age:30},
 {dis:"Ann", age:40},
 {dis:"Dan", age:50}].toGrid
toHex

toHex(val)

Convert a number to a hexadecimal string

toJavaMillis

toJavaMillis(dt)

Given a DateTime return Number of milliseconds since Unix epoch of 1-Jan-1970 UTC Also see fromJavaMillis.

toLocale

toLocale(key)

Get the localized string for the given tag name or qualified name. If the key is formatted as "pod::name" then route to Env.locale, otherwise to Etc.tagToLocale.

toRec

toRec(val, checked: true)

Given any of the following, return a Dict:

  • null always return null
  • Null Ref always returns null
  • Row or Dict
  • Ref will make a call to read database
toRecId

toRecId(val)

Given any of the following, return a Ref:

  • Ref
  • Row or Dict, return id tag
toRecIdList

toRecIdList(val)

Given any of the following, return a Ref[]:

  • Ref
  • Ref[]
  • Dict return id tag
  • Dict[] return id tags
  • Grid return id column
toRecList

toRecList(val)

Given any of the following, return a Dict[] of records:

  • null return empty list
  • Ref or Ref[] (will make a call to read database)
  • Row or Row[]
  • Dict or Dict[]
  • Grid
toStr

toStr(val)

Convert an obj to its string representation

toTagName

toTagName(n)

Given arbitrary string, convert to a safe tag name - see Etc.toTagName

toTimeZone

toTimeZone(dt, tz)

Convert a DateTime to another timezone:

now().toTimeZone("Chicago")
now().toTimeZone("UTC")
today

today()

Return today's Date according to context's time zone

trap

trap(val, name)

If the given value is a dict, then get a value by name, or throw UnknownNameErr if name not mapped. If the value is a Ref, then perform a checked readById, then perform the name lookup.

The trap function maybe be accessed using the -> shortcut operator:

dict->foo  >>>  dict.trap("foo")

See Axon Language.

trim

trim(val)

Trim whitespace from the beginning and end of the string. For the purposes of this function, whitespace is defined as any character equal to or less than the 0x20 space character (including , \r, \n, and \t).

trimEnd

trimEnd(val)

Trim whitespace only from the end of the string. See trim for definition of whitespace.

trimStart

trimStart(val)

Trim whitespace only from the beginning of the string. See trim for definition of whitespace.

tz

tz(dt)

Get timezone as city name string in tzinfo database from datetime

tzdb

tzdb()

Return the installed timezone database as Grid with following columns:

  • name: name of the timezone
  • fullName: qualified name used by Olson database
unique

unique(val, key: null)

Return the unique items in a collection. If val is a List then return List.unique. If val is a Grid then return Grid.unique where key must be a column name or list of column names.

Examples:

[1, 1, 2, 2].unique                 >> [1, 2]
grid.unique("geoState")             >> unique states
grid.unique(["geoCity", geoState"]) >> city,state combos
unit

unit(val)

Given a number return its unit string or null. If the val is null, then return null.

unitdb

unitdb()

Return the installed unit database as Grid with following columns:

  • quantity: dimension of the unit
  • name: full name of the unit
  • symbol: the abbreviated Unicode name of the unit
unitsEq

unitsEq(a, b)

Return if the two numbers have the same unit. If either of the numbers if null return false.

upper

upper(val)

Convert a char number or str to upper case

uriBasename

uriBasename(val)

Get the basename (last name in path without extension) of a Uri as a string.

uriDecode

uriDecode(val, checked: true)

Parse an ASCII percent encoded string into a Uri according to RFC 3986. All %HH escape sequences are translated into octects, and then the octect sequence is UTF-8 decoded into a Str. The + character in the query section is unescaped into a space. If checked if true then throw ParseErr if the string is a malformed URI or if not encoded correctly, otherwise return null. Use parseUri to parse from standard form. See Uri for a detailed discussion on standard and encoded forms.

Examples:

"foo bar".parseUri     >>  `foo bar`
"foo%20bar".uriDecode  >>  `foo bar`
uriEncode

uriEncode(val)

Return the percent encoded string for this Uri according to RFC 3986. Each section of the Uri is UTF-8 encoded into octects and then percent encoded according to its valid character set. Spaces in the query section are encoded as +.

Examples:

`foo bar`.uriEncode  >>  "foo%20bar"
uriExt

uriExt(val)

Get the URI extension of a Uri as a string or null.

uriHost

uriHost(val)

Get the host Uri as a string or null

uriIsDir

uriIsDir(val)

Return if the URI path ends in a slash.

uriName

uriName(val)

Get the name Str of a Uri (last item in path).

uriPath

uriPath(val)

Get the path segments of a Uri as a list of Strs.

uriPathStr

uriPathStr(val)

Get the path a Uri as a string.

uriPort

uriPort(val)

Get the port of a Uri as a Number or null

uriScheme

uriScheme(val)

Get the scheme of a Uri as a string or null

vals

vals(dict)

Get the list of values used by a given dict

watchAdd

watchAdd(watchId, grid)

Add a grid of recs to an existing watch. Return the grid passed in.

watchClose

watchClose(watchId)

Close an open watch by id. If the watch does not exist or has expired then this is a no op. Also see Watch.close and Watches.

watchOpen

watchOpen(grid, dis)

Open a new watch on a grid of records. The dis parameter is used for the watch's debug display string. Update and return the grid with a meta watchId tag. Also see Proj.watchOpen and Watches.

Example:

readAll(myPoints).watchOpen("MyApp|Points")
watchPoll

watchPoll(watchId)

Poll an open watch and return all the records which have changed since the last poll. Note that this grid does not have display strings for Ref tags. Raise exception if watchId doesn't exist or has expired. Also see Watch.poll and Watches.

watchRemove

watchRemove(watchId, grid)

Remove a grid of recs from an existing watch. Return the grid passed in.

weekday

weekday(t)

Get weekday as integer from 0 to 6 of Date or DateTime, where 0 indicates Sunday and 6 indicates Saturday

year

year(d)

Get year as integer such as 2010 from date or datetime

yesterday

yesterday()

Return yesterday's Date according to context's time zone