外观
Axon 语言教程与参考(axon)
原文: https://finproducts.atlassian.net/wiki/spaces/JIDD3/pages/34793357714/FIN+5.3.1+axon 中文整理基于 FIN 5.3.1
Axon 语言教程与参考(axon)
Axon scripting engine
mixins
| CellDef | CellDef data flow component cell and its metadata |
| Comp | Comp is an instance of CompDef. |
classes
| AbstractComp | AbstractComp is base class for Fantom components. |
| AxonContext | AxonContext manages the environment of an Axon evaluation |
| CompDef | CompDef data flow component definition |
| CoreLib | System library |
| Expr | Expr is the base class for Axon AST nodes. |
| Fn | Fn is a function definition |
| Loc | Source code location. |
| TopFn | Top level function in the namespace |
facets
| Axon | Facet applied to methods which should be exposed as Axon functions. |
| Cell | Cell facet to apply to AbstractComp slots |
errs
| AxonErr | AxonErr is the base class of SyntaxErr and EvalErr. |
| EvalErr | EvalErr is thrown during the evaluation phase. |
| SyntaxErr | SyntaxErr is thrown during parse phase. |
AbstractComp
@Js abstract class AbstractComp : Obj, Comp
AbstractComp 是 Fantom 组件的基类。参见 Comps。
Constructors
| make | All components must implement single arg constructor |
Methods
| def | Get the definition |
| get | Get a cell value by name or raise error if not a valid cell |
| getCell | Get a cell value by its cell definition |
| onRecompute | Callback to recompute the cells |
| recompute | Recompute the component's cells |
| reflect | Reflect the given type |
| set | Set a cell value by name or raise error if not a valid cell |
| setCell | Set a cell value by its cell definition |
| toStr | Debug string |
插槽详情
def
override CompDef def()
Get the definition
get
@操作员 override Obj? get(Str name)
通过名称获取单元格的值,如果不是有效单元格则引发错误
getCell
override Obj? getCell(CellDef cd)
通过其单元格定义获取单元格的值
make
new make(Obj init)
所有组件必须实现单参数构造函数
onRecompute
protected abstract Void onRecompute(AxonContext cx)
Callback to recompute the cells
recompute
重写 This recompute(AxonContext cx)
Recompute the component's cells
reflect
static CompDef reflect(Type type, Dict meta)
Reflect the given type
set
@操作员 override This set(Str name, Obj? val)
通过名称设置单元格值,如果不是有效单元格则引发错误
setCell
override This setCell(CellDef cd, Obj? val)
通过其单元格定义设置单元格的值
toStr
override Str toStr()
Debug string
Axon
@Js @Serializable facet class Axon : Obj, Facet
用于应该作为 Axon 函数暴露的方法的 Facet。
Fields
| admin | Marks a function as admin-only. |
| meta | Meta data for the function encoded as a Trio string |
| su | Mark a function as superuser only. |
插槽详情
admin
const Bool admin := false
将函数标记为仅管理员可用。任何修改数据库或执行临时输入/输出的函数都应将此字段设置为 true。具有副作用的函数应清楚地记录其副作用内容。
meta
const Obj? meta
作为 Trio 字符串编码的函数元数据
su
const Bool su := false
Mark a function as superuser only.
AxonContext
@Js abstract class AxonContext : Obj, HaystackContext, CompContext
AxonContext 管理 Axon 评估的环境
Methods
| call | Lookup and call a function with the given arguments. |
| eval | Evaluate an Axon expression within this context. |
| evalExpr | Evaluate an expression |
| evalToFunc | Evaluate expression to a function expression |
| now | CompContext current time |
| ns | Definition namespace |
| parse | Parse Axon expression |
| stash | Stash allows you to stash objects on the Context object during an Axon evaluation. |
| xeto | Xeto namespace |
插槽详情
call
Obj? call(Str funcName, Obj?[] args)
查找并调用具有给定参数的函数。参数必须是完全求值的值,例如数字、字典、网格等。
eval
Obj? eval(Str src, Loc loc := Loc.eval)
Evaluate an Axon expression within this context. Convenience for evalExpr(parse(src, loc))
evalExpr
Evaluate an expression
evalToFunc
将表达式求值为函数表达式
now
virtual override DateTime now()
CompContext current time
ns
abstract Namespace ns()
Definition namespace
parse
Expr parse(Str src, Loc loc := Loc.eval)
Parse Axon expression
stash
Stash 允许你在 Axon 评估期间将对象存储在 Context 对象上。你应该使用你的 pod 名称来限定你的字符串键,以避免命名冲突。
xeto
virtual LibNamespace xeto()
Xeto namespace
AxonErr
@Js 抽象常量类 AxonErr : Err
AxonErr is the base class of SyntaxErr and EvalErr.
Constructors
| make |
Fields
| loc |
Methods
| toStr |
插槽详情
loc
const Loc loc
make
new make(Str? msg, Loc loc, Err? cause := null)
toStr
virtual override Str toStr()
Cell
@Js @Serializable facet class Cell : Obj, Facet
应用于 AbstractComp 插槽的单元面
Fields
| meta | Meta data for the cell encoded as a Trio string |
插槽详情
meta
const Obj? meta
作为 Trio 字符串编码的单元元数据
CellDef
@Js const mixin CellDef : Dict
CellDef 数据流组件单元及其元数据
Methods
| name | Cell name |
| parent | Parent component def |
插槽详情
name
abstract Str name()
Cell name
parent
abstract CompDef parent()
Parent component def
Comp
@Js 混入 Comp
Comp 是 CompDef 的一个实例。参见 Comps。
Methods
| def | Definition of the component |
| get | Get a cell value by name or raise error if not a valid cell |
| getCell | Get a cell value by its cell definition |
| recompute | Recompute cells |
| set | Set a cell value by name or raise error if not a valid cell |
| setCell | Set a cell value by its cell definition |
插槽详情
def
abstract CompDef def()
Definition of the component
get
@操作员 abstract Obj? get(Str name)
通过名称获取单元格的值,如果不是有效单元格则引发错误
getCell
abstract Obj? getCell(CellDef cd)
通过其单元格定义获取单元格的值
recompute
摘要 这个 recompute(AxonContext cx)
Recompute cells
set
@操作员 abstract This set(Str name, Obj? val)
通过名称设置单元格值,如果不是有效单元格则引发错误
setCell
abstract This setCell(CellDef cd, Obj? val)
通过其单元格定义设置单元格的值
CompDef
@Js 抽象常量类 CompDef : TopFn
CompDef 数据流组件定义
Methods
| cell | Lookup a cell by name or raise UnknownCellErr |
| cells | List data cells for component |
| instantiate | Create instance of this component definition |
插槽详情
cell
abstract CellDef? cell(Str name, Bool checked := true)
按名称查找单元格或引发 UnknownCellErr
cells
abstract CellDef[] cells()
List data cells for component
instantiate
abstract Comp instantiate()
创建此组件定义的实例
CoreLib
@Js const class CoreLib : Obj
System library
Methods
| _as | Set the unit of a number. |
| _echo | Write the str represenation of x to stdout and return x. |
| _equals | Return if two values are equivalent. |
| _toStr | Convert an obj to its string representation |
| _trap | Function for the -> operator. |
| abs | Return absolute value of a number, if null return null |
| add | Add item to the end of a list and return a new list. |
| addAll | Add all the items to the end of a list and return a new list. |
| addCol | Add a column to a grid by mapping each row to a new cell value. |
| addColMeta | Return a new grid with additional column meta-data. |
| addCols | Add grid b as a new set of columns to grid a. |
| addMeta | Return new grid with additional grid level meta-data tags. |
| addRow | Add an additional Dict row to the end of a grid. |
| addRows | Add an list of rows to the end of a grid. |
| all | Return if all the items in a list, dict, or grid match the given test function. |
| any | Return if any the items in a list, dict, or grid match the given test function. |
| avg | Fold multiple values into their standard average or arithmetic mean. |
| call | Reflectively call a function with the given arguments. |
| capitalize | Return this string with the first character converted to uppercase. |
| clamp | Clamp the number val between the min and max. |
| col | Get a column by its name. |
| colNames | Get the column names a list of strings. |
| colToList | Get a column as a list of the cell values ordered by row. |
| collect | Collect stream into a in-memory list or grid. |
| cols | Get the columns from a grid as a list. |
| colsToLocale | Localize column display names. |
| compDef | Return component definition. |
| concat | Concatenate a list of items into a string. |
| conjuncts | List conjunct definitions in the context namespace as Def[]. |
| contains | Return if val contains x |
| coord | Construct a Coord from two Numbers in decimal degrees |
| coordDist | Compute the great-circle distance between two Coords. |
| coordLat | Latitude of a Coord as a Number |
| coordLng | Longitude of a Coord as a Number |
| count | Fold multiple values into their total count Return zero if no values. |
| curFunc | Get the current top-level function's tags. |
| date | If val is a DateTime: get date portion of the timestamp. |
| dateTime | Construct a DateTime from a date, time, and timezone name. |
| day | Get day of month as integer between 1 to 31 from date or datetime. |
| dayOfYear | Given a DateTime or Date, return the day of the year. |
| debugType | Return a string of the given value's type. |
| decapitalize | Return this string with the first character converted to lowercase. |
| def | Lookup a def by its symbol name (Str or Symbol). |
| defs | List all definitions in the context namespace as Def[]. |
| dis | Get display string for dict or the given tag. |
| dst | Return if a DateTime is in daylight saving time. |
| each | Iterate the items of a collection |
| eachDay | Iterate the days of a span. |
| eachMonth | Iterate the months of a span. |
| eachWhile | Iterate the items of a collection until the given function returns non-null. |
| end | End value of a DateSpan, Span, or a range. |
| endsWith | Return if Str ends with the specified Str. |
| eval | Evaluate an Axon string expression. |
| evalToFunc | Evalate an Axon string expression to a function. |
| filter | Apply a filter expression to a collection of dicts. |
| filterToFunc | Convert a filter expression to a function which maybe used with findAll or find. |
| find | Find the first matching item in a list or grid by applying the given filter function. |
| findAll | Find all the items in a list, dict, or grid by applying the given filter function. |
| first | Get the first item from an ordered collection or return null if the collection is empty |
| firstOfMonth | Get the first day of given date's month. |
| flatMap | Map each item in a list or grid to zero or more new items as a flattened result. |
| flatten | Flatten a list to a single level. |
| fold | Fold a list or stream into a single value using given folding function. |
| foldCol | Fold the values of the given column into a single value. |
| foldCols | Fold a set of columns in each row into a new folded column and return a new grid. |
| foldEnd | The fold end marker value |
| foldStart | The fold start marker value |
| format | Format an object using the current locale and specified format pattern. |
| fromJavaMillis | Given Number of milliseconds since Unix epoch return a DateTime. |
| func | Find a top-level function by name or by reference and return its tags. |
| funcs | Find all the top-levels functions in the current project which match the given filter. |
| get | Get an item from a collection |
| getSafe | Get an item from a str, list, or grid safely when an index is out of bounds |
| gridColKinds | Given a grid return the types used in each column as a grid with the following |
| gridColsToDict | Convert grid columns into a dict of name/val pairs. |
| gridReplace | Replace every grid cell with the given from value with the to value. |
| gridRowsToDict | Convert grid rows into a dict of name/val pairs. |
| has | If val is a Grid return if it has the given column name. |
| hour | Get hour of day as integer between 0 to 23 from time or datetime |
| hoursInDay | Given a DateTime in a specific timezone, return the number of hours in the day. |
| index | Return the first match of x in val searching forward, starting at the specified offset index. |
| indexr | Return the last match of x in val searching backward, starting at the specified offset index. |
| insert | Insert an item into a list at the given index and return a new list. |
| insertAll | Insert a list of items at the given index and return a new list. |
| isAlpha | Is number an ASCII alpha char: isUpper |
| isAlphaNum | Is number an ASCII alpha-numeric char: isAlpha |
| isBool | Return if an object is a boolean type |
| isDate | Return if an object is a Date type |
| isDateTime | Return if an object is a DateTime type |
| isDict | Return if an object is a dict type |
| isDigit | Is number a digit in the specified radix. |
| isDuration | Return if an object is a number type with a time unit |
| isEmpty | Return if a collection is empty: str, list, dict, or grid |
| isEven | Return if an integer is an even number. |
| isFunc | Return if an object is a function type |
| isGrid | Return if an object is a grid type |
| isHisGrid | Return if an object is a grid that conforms to the history grid shape |
| isKeyword | Return if given string is an Axon keyword |
| isLeapYear | Return if a year is a leap year. |
| isList | Return if an object is a list type |
| isLower | Is number an ASCII lowercase alphabetic char: a-z |
| isMetric | Given an optional value return true if the SI metric system should be used. |
| isNaN | Return if val is the Number representation of not-a-number |
| isNonNull | Return if an object is not null |
| isNull | Return if an object is null |
| isNumber | Return if an object is a number type |
| isOdd | Return if an integer is an odd number. |
| isRef | Return if an object is a ref type |
| isSpace | Is number is whitespace char: space \t \n \r \f |
| isSpan | Return if an object is a span |
| isStr | Return if an object is a str type |
| isTagName | Return if the given string is legal tag name - see Etc.isTagName |
| isTime | Return if an object is a Time type |
| isUpper | Is number an ASCII uppercase alphabetic char: A-Z |
| isUri | Return if an object is a Uri type |
| isWeekday | Does the given Date or DateTime fall on Mon, Tue, Wed, Thu, or Fri |
| isWeekend | Does the given Date or DateTime fall on Sat or Sun |
| join | Join two grids by column name. |
| joinAll | Join a list of grids into a single grid. |
| keepCols | Return a new grid with keeps the given columns, but removes all the others. |
| last | Get the last item from an ordered collection or return null if the collection is empty |
| lastMonth | DateSpan for month previous to this month 1..28-31 |
| lastOfMonth | Get the last day of the date's month. |
| lastQuarter | DateSpan for 3 month quarter previous to this quarter |
| lastWeek | DateSpan for week previous to this week sun..sat (uses locale start of week) |
| lastYear | DateSpan for year previous to this year Jan-1..Dec-31 |
| libs | List the lib definitions in the context namespace as Def[]. |
| limit | Truncate stream after given limit is reached. |
| localeUse | Evaluate an expression within a specific locale. |
| lower | Convert a char number or str to ASCII lower case. |
| map | Map list, dict, or grid by applying the given mapping function. |
| marker | Get the marker value singleton Marker.val |
| max | Compare two numbers and return the larger one. |
| merge | Merge two Dicts together and return a new Dict. |
| meta | Get the meta-data from a grid or col as a dict. |
| min | Compare two numbers and return the smaller one. |
| minute | Get minutes of the time as integer between 0 to 59 from time or datetime |
| missing | If val is a Grid return if it does not have given column name. |
| month | Get month as integer between 1 to 12 from date or datetime |
| moveTo | Find the given item in a list, and move it to the given index. |
| na | Get NA not-available singleton NA.val |
| name | If val is a Col, get the column name. |
| names | Get the list of names used by a given dict |
| nan | Return the Number representation of not-a-number |
| negInf | Return the Number representation negative infinity |
| now | Return current DateTime according to context's time zone. |
| nowTicks | Return current time as nanosecond ticks since 1 Jan 2000 UTC. |
| nowUtc | Return current DateTime in UTC. |
| numDays | Number of whole days in a span |
| numDaysInMonth | Get the number of days in a given month. |
| occurred | Return if a timestamp is contained within a Date range. |
| padl | Pad string to the left. |
| padr | Pad string to the right. |
| parseAst | Parse Axon source code into an abstract syntax tree modeled as a tree of dicts. |
| parseBool | Parse a Str into a Bool, legal formats are "true" or "false. |
| parseDate | Parse a Str into a Date. |
| parseDateTime | Parse a Str into a DateTime. |
| parseFilter | Parse a filter string into a Filter instance. |
| parseFloat | Parse a Str into a Float. |
| parseInt | Parse a Str into a integer number using the specified radix. |
| parseNumber | Parse a Str into a number with an option unit. |
| parseRef | Parse a Str into a Ref. |
| parseSearch | Parse a search string into a Filter instance. |
| parseSymbol | Parse a Str into a Symbol. |
| parseTime | Parse a Str into a Time. |
| parseUnit | Parse a Str into a standardized unit name. |
| parseUri | Parse a string into a Uri instance. |
| pastMonth | DateSpan for last 30days today-30days..today |
| pastWeek | DateSpan for last 7 days as today-7days..today |
| pastYear | DateSpan for this past today-365days..today |
| posInf | Return the Number representation positive infinity |
| reFind | Find the first match of regular expression in s or return null if no matches. |
| reFindAll | Find all matches of the regular expression in s. |
| reGroups | Return a list of the substrings captured by matching the given regular operation against s. |
| reMatches | Return if regular expression matches entire region of s. |
| reduce | Reduce a collection to a single value with the given reducer function. |
| refDis | Given a ref return Ref.dis |
| refGen | Generate a new unique Ref identifier |
| refProjName | Given an absolute ref, return its project name. |
| relDis | Get a relative display name. |
| remove | Remove an item from a collection and return a new collection. |
| removeCol | Return a new grid with the given column removed. |
| removeCols | Return a new grid with all the given columns removed. |
| removeMarker | Get the remove value singleton Remove.val |
| renameCol | Return a new grid with the given column renamed. |
| renameCols | Return a new grid with multiple columns renamed. |
| reorderCols | Return a new grid with the columns reordered. |
| replace | String replace of all occurrences of from with to. |
| rowToList | Get a grid row as a list of cells. |
| second | Get seconds of the time as integer between 0 to 59 from time or datetime |
| set | Set a collection item and return a new collection. |
| setColMeta | Return a new grid with column meta-data replaced by given meta dict. |
| setMeta | Return new grid with grid level meta-data replaced by given meta Dict. |
| size | Return number of items in str, list, or grid |
| skip | Skip the given number of items in a stream. |
| sort | Sort a list or grid. |
| sortDis | Sort a grid by row display name - see Grid.sortDis |
| sortr | Reverse sort a list or grid. |
| split | Split a string by the given separator and trim whitespace. |
| spread | Fold multiple values to compute the difference between the max and min value. |
| start | Start value of a DateSpan, Span or a range. |
| startOfWeek | Return current locale's start of weekday. |
| startsWith | Return if Str starts with the specified Str. |
| stream | Create new stream from given collection |
| streamCol | Create a new stream for the cell values of the given column. |
| sum | Fold multiple values into their numeric sum. |
| swizzleRefs | Given a grid of records, assign new ids and swizzle all internal ref tags. |
| tags | List tag definitions in the context namespace as Def[]. |
| terms | List term definitions (tags and conjuncts) in the context namespace as Def[]. |
| thisMonth | DateSpan for this month as 1st..28-31 |
| thisQuarter | DateSpan for this 3 month quarter |
| thisWeek | DateSpan for this week as sun..sat (uses locale start of week) |
| thisYear | DateSpan for this year Jan-1..Dec-31 |
| time | If val is a DateTime: get time portion of the timestamp. |
| times | Call the specified function the given number of times passing the counter. |
| to | Convert a number to the given unit. |
| toAxonCode | Convert a scalar, list, or dict value to its Axon code representation. |
| toChar | Convert a unicode char number into a single char string |
| toDateSpan | Convert the following objects into a DateSpan |
| toGrid | Given an arbitrary object, translate it to a Grid via Etc.toGrid |
| toHex | Convert a number to a hexadecimal string. |
| toJavaMillis | Given a DateTime return Number of milliseconds since Unix epoch. |
| toList | If val is a list return it, otherwise return [val]. |
| toLocale | Get the localized string for the given tag name or qualified name. |
| toRadix | Convert a number to its string representation in the given radix (base). |
| toSpan | Convert the following objects into a Span |
| toTagName | Given arbitrary string, convert to a safe tag name - see Etc.toTagName |
| toTimeZone | Convert a DateTime or Span to another timezone |
| today | Return today's Date according to context's time zone |
| transpose | Perform a matrix transpose on the grid. |
| trim | Trim whitespace from the beginning and end of the string. |
| trimEnd | Trim whitespace only from the end of the string. |
| trimStart | Trim whitespace only from the beginning of the string. |
| tz | Get timezone as city name string in tzinfo database from datetime. |
| unique | Return the unique items in a collection. |
| unit | Given a number return its unit string or null. |
| unitsEq | Return if the two numbers have the same unit. |
| upper | Convert a char number or str to ASCII upper case. |
| uriBasename | Get the basename (last name in path without extension) of a Uri as a string. |
| uriDecode | Parse an ASCII percent encoded string into a Uri according to RFC 3986. |
| uriEncode | Return the percent encoded string for this Uri according to RFC 3986. |
| uriExt | Get the URI extension of a Uri as a string or null. |
| uriFrag | Return if the fragment identifier portion of the a URI after hash symbol |
| uriHost | Get the host Uri as a string or null |
| uriIsDir | Return if the URI path ends in a slash. |
| uriName | Get the name Str of a Uri (last item in path). |
| uriPath | Get the path segments of a Uri as a list of Strs. |
| uriPathStr | Get the path a Uri as a string. |
| uriPlusSlash | Adding trailing slash to the URI. |
| uriPort | Get the port of a Uri as a Number or null |
| uriQueryStr | Return if the query portion of the a URI after question mark |
| uriScheme | Get the scheme of a Uri as a string or null |
| vals | Get the list of values used by a given dict |
| weekOfYear | Given a DateTime or Date, return the week number of the year. |
| weekday | Get weekday as integer from 0 to 6 of Date or DateTime. |
| xstr | Construct decoded XStr instance |
| year | Get year as integer such as 2010 from date or datetime |
| yesterday | Return yesterday's Date according to context's time zone |
插槽详情
_作为
@Axonstatic Number? _as(Number? val, Obj? unit)
设置一个数字的单位。与 to() 函数不同,不会对数字的标量进行转换。目标单位可以是一个单位字符串或一个数字,此时会忽略单位参数的标量值(按惯例应为 1)。
Examples:
75°F.as(1°C)
75°F.as("°C")_回声
@Axon { admin=true } static Obj? _echo(Obj? x)
将 x 的字符串表示写入标准输出并返回 x。
_等于
@Axonstatic Obj? _equals(Obj? a, Obj? b)
如果两个值相等则返回。与标准的 == 运算符不同,此函数将比较集合值(例如列表、字典和网格)的内容。对于非集合值,结果与 == 运算符相同。此函数不适用于懒加载网格,例如 hisRead 结果。
_到字符串
@Axonstatic Obj? _toStr(Obj? val)
将对象转换为其字符串表示
_trap
@Axonstatic Obj? _trap(Obj? val, Str name)
-> 操作符的函数。如果给定的值是一个字典,则按名称获取值,如果名称未映射,则抛出 UnknownNameErr。如果值是一个 Ref,则执行检查后的 readById,然后执行名称查找。
可以使用 -> 快捷操作符访问 trap 函数:
dict->foo >>> dict.trap("foo")参见 Axon 语言。
abs
@Axonstatic Obj? abs(Number? val)
返回一个数的绝对值,如果为 null 则返回 null
add
@Axonstatic Obj? add(Obj? val, Obj? item)
将项目添加到列表末尾并返回一个新的列表。
addAll
@Axonstatic Obj? addAll(Obj? val, Obj? items)
将所有项目添加到列表的末尾并返回一个新列表。
addCol
@Axonstatic Grid addCol(Grid grid, Obj? col, Fn fn)
通过将每一行映射到一个新的单元格值,为网格添加一列。col 参数可以是一个简单的字符串名称,也可以是一个字典,该字典必须包含一个“name”标记(任何其他标记将成为列的元数据)。映射函数接收 (row) 并返回该列的新单元格值。
Examples:
// add new column named areaMeter
readAll(site).addCol("areaMeters") s => s->area.to(1m²)
// add new column named areaMeter with dis meta
readAll(site).addCol({name:"areaMeters", dis:"Area Meters"}) s => s->area.to(1m²)addColMeta
@Axonstatic Obj addColMeta(Obj grid, Str name, Dict meta)
返回一个带有额外列元数据的新网格。如果未找到列,则返回给定的网格。列元数据是使用合并约定添加的。另请参见 setColMeta 和 Streams。
addCols
@Axonstatic Grid addCols(Grid a, Grid b)
将网格 b 作为一组新的列添加到网格 a。如果 b 包含重复的列名,则它们会被自动生成唯一名称。如果 b 的行数少于 a,则缺失的单元格将填充为 null。
Examples:
[{a:0, b:2}, {a:1, b:3}].toGrid.addCols({c:4}.toGrid)
readAll(rtu).addCols(readAll(meter))addMeta
@Axonstatic Obj addMeta(Obj grid, Dict meta)
返回带有附加网格级别元数据标签的新网格。标签是使用合并约定添加的。另请参见 setMeta 和 Streams。
Example:
read(temp).hisRead(today).addMeta({view:"table"})addRow
@Axonstatic Grid addRow(Grid grid, Dict newRow)
在网格的末尾添加一个额外的字典行。
Example:
readAll(site).addRow({dis:"New Row"})addRows
@Axonstatic Grid addRows(Grid grid, Obj newRows)
将一列行添加到网格的末尾。newRows 可以表示为字典列表或网格。
Example:
readAll(site).addRows(readAll(equip))all
@Axonstatic Obj? all(Obj val, Fn fn)
如果列表、字典或网格中的所有项目都符合给定的测试函数,则返回。如果集合为空,则返回真。
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.
If working with a string, the function takes (char) or (char, index) and returns true or false.
如果处理一个流,那么函数接受 (val) 并返回 true 或 false。参见流。
Examples:
[1, 3, 5].all v => v.isOdd >> true
[1, 3, 6].all(isOdd) >> falseany
@Axonstatic Obj? any(Obj val, Fn fn)
如果列表、字典或网格中的任何项目与给定的测试函数匹配,则返回。如果集合为空,则返回假。
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.
If working with a string, the function takes (char) or (char, index) and returns true or false.
如果处理的是流,那么函数接受 (val) 并返回 true 或 false。请参阅流。
Examples:
[1, 3, 5].any v => v.isOdd >> true
[2, 4, 6].any(isOdd) >> falseavg
@Axon { meta=["foldOn":"Number"] } static Obj? avg(Obj? val, Obj? acc)
将多个值折叠为它们的标准平均值或算术平均值。此函数与 math::mean 相同。忽略空值。如果没有值,则返回空值。
Example:
[7, 2, 3].fold(avg) >> 4call
@Axonstatic Obj? call(Obj func, Obj?[]? args := null)
使用反射方式调用一个函数并传入给定的参数。func 可以是一个字符串名称或一个求值为函数的表达式。Args 是每个参数的按位置排列的列表。示例:
call("today")
call("replace", ["hi there", "hi", "hello"])
call("parseDate", ["2021-03-15"])
call("parseDate", ["15-Mar-21", "DD-MMM-YY"])
call(parseDate, ["15-Mar-21", "DD-MMM-YY"])
call(parseDate(_, "DD-MMM-YY"), ["15-Mar-21"])capitalize
@Axonstatic Str capitalize(Str val)
将此字符串的第一个字符转换为大写。大小写转换仅适用于 ASCII。另请参见 decapitalize() 和 upper()。
Examples:
capitalize("apple") >> "Apple"clamp
@Axonstatic Number clamp(Number val, Number min, Number max)
将数值 val 限制在最小值和最大值之间。如果它小于最小值,则返回最小值;如果它大于最大值,则返回最大值;否则返回 val 本身。最小值和最大值必须具有相同的单位或无单位。结果始终与 val 的单位相同。
Examples:
14.clamp(10, 20) >> 14 // is between 10 and 20
3.clamp(10, 20) >> 10 // clamps to min 10
73.clamp(10, 20) >> 20 // clamps to max 20
45°F.clamp(60, 80) >> 60°F // min/max can be unitlesscol
@Axonstatic Col? col(Grid grid, Str name, Bool checked := true)
通过名称获取列。如果未找到,则根据检查标志返回 null 或抛出 UnknownNameErr。
Example:
// get meta data for given columm
read(temp).hisRead(today).col("ts").metacolNames
@Axonstatic Str[] colNames(Grid grid)
获取列名的字符串列表。
Example:
readAll(site).colNamescolToList
@Axonstatic Obj?[] colToList(Grid grid, Obj col)
将一列作为按行排序的单元格值列表获取。另请参见 rowToList()。
Example:
readAll(site).colToList("dis")collect
@Axonstatic Obj collect(Obj? stream, Fn? to := null)
将流收集到内存中的列表或网格中。参见 Streams。
cols
@Axonstatic Col[] cols(Grid grid)
从网格中获取列作为列表。
Example:
// get name of first column
readAll(site).cols.first.namecolsToLocale
@Axonstatic Grid colsToLocale(Grid grid)
Localize column display names. For each col which does not have an explicit dislay name, add a dis tag based on the column name. Also see Grid.colsToLocale and Localization.
compDef
@Axonstatic Grid? compDef(Obj name, Bool checked := true)
返回组件定义。结果是一个网格,每一行对应一个单元格及其相关的元数据。网格元数据是函数级别的元数据。
Example:
compDef("compName")concat
@Axonstatic Str concat(List list, Str sep := "")
将一系列项目连接成一个字符串。
Examples:
[1, 2, 3].concat >> "123"
[1, 2, 3].concat(",") >> "1,2,3"conjuncts
在上下文命名空间中将 conjunction 定义列为 Def[]。
contains
@Axonstatic Bool contains(Obj val, Obj? x)
Return if val contains x:
- if
valis Str, thenxis substring. - if
valis List, thenxis item to search. - if
valis Range, then isxinside the range inclusively - if
valis DateSpan, then isxa date in the span
coord
@Axonstatic Coord coord(Number lat, Number lng)
从两个十进制度数构建一个坐标
coordDist
@Axonstatic Number coordDist(Coord c1, Coord c2)
计算两个坐标之间的大圆距离。结果是使用哈弗辛公式得到的以米为单位的距离。
coordLat
@Axonstatic Number coordLat(Coord coord)
Latitude of a Coord as a Number
coordLng
@Axonstatic Number coordLng(Coord coord)
Longitude of a Coord as a Number
count
@Axon { meta=["foldOn":"Obj"] } static Obj? count(Obj val, Obj? acc)
将多个值合并为它们的总计数,如果没有值则返回零。
curFunc
获取当前顶级函数的标签。
date
@Axonstatic Obj? date(Obj val, Number? month := null, Number? day := null)
如果 val 是 DateTime:获取时间戳的日期部分。如果 val 是数字:从年、月、日构造一个日期实例
Examples:
now().date // same as today()
date(2010, 12, 1) // same as 2010-12-01dateTime
@Axonstatic Obj? dateTime(Date d, Time t, Str? tz := null)
根据日期、时间和时区名称构造一个日期时间。如果时区为 null,则使用系统默认值。
day
从日期或日期时间中获取作为1到31之间整数的月份中的天数。
dayOfYear
@Axonstatic Number dayOfYear(Obj val)
给定一个日期时间或日期,返回一年中的第几天。结果是1到365之间的数字(如果是闰年,则为1到366)。
debugType
@Axonstatic Str debugType(Obj? val)
返回给定值类型的字符串。对字符串的格式不作任何保证。应用程序不得假设任何特定格式,此函数仅供人工使用。
decapitalize
@Axonstatic Str decapitalize(Str val)
返回此字符串,并将第一个字符转换为小写。大小写转换仅适用于 ASCII 字符。另请参见 capitalize() 和 lower()。
Examples:
decapitalize("Apple") >> "apple"def
@Axonstatic Def? def(Obj symbol, Bool checked := true)
通过符号名称(Str 或 Symbol)查找定义。如果未找到,根据 checked 标志返回 null 或引发 UnknownDefErr。结果以定义的标准化字典表示形式返回。
defs
将上下文命名空间中的所有定义列出为 Def[]。
dis
@Axonstatic Str dis(Dict? dict, Str? name := null, Str? 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
@Axonstatic Bool dst(DateTime dt)
返回一个日期时间是否处于夏令时。对于给定的日期时间及其特定时区,如果时间处于夏令时返回 true,如果处于标准时间返回 false。
each
@Axonstatic Obj? each(Obj val, Fn 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)
- Str: iterate the characters as numbers (char, index)
- Range: iterate the integer range (integer)
- Stream: iterate items as (val); see Streams
eachDay
@Axonstatic Obj? eachDay(Obj dates, Fn fn)
迭代一个时间跨度中的每一天。dates 参数可以是任何通过 toDateSpan 转换为日期范围的对象。对于每个迭代的日期,将使用 Date 参数调用给定的函数。
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 dayseachMonth
@Axonstatic Obj? eachMonth(Obj dates, Fn fn)
迭代一个时间跨度的各个月份。dates 参数可以是通过 toDateSpan 转换为日期范围的任何对象。给定的函数会使用每个迭代月份的 DateSpan 参数调用。
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
@Axonstatic Obj? eachWhile(Obj val, Fn fn)
遍历集合中的每一项,直到给定函数返回非空值。一旦返回非空值,则中断迭代并返回结果对象。如果函数对每一项都返回空值,则返回空。
- Grid: iterate the rows as (row, index)
- List: iterate the items as (val, index)
- Dict: iterate the name/value pairs (val, name)
- Str: iterate the characters as numbers (char, index)
- Range: iterate the integer range (integer)
- Stream: iterate items as (val); see Streams
end
@Axonstatic Obj? end(Obj? val)
DateSpan、Span 或范围的结束值。
endsWith
@Axonstatic Bool endsWith(Str val, Str sub)
如果 Str 以指定的 Str 结尾则返回。
Examples:
"hi there".endsWith("there") >> true
"hi there".endsWith("hi") >> falseeval
@Axonstatic Obj? eval(Str expr)
评估一个 Axon 字符串表达式。评估发生在一个新的作用域中,无法访问当前局部变量的作用域。另请参见 call() 和 toAxonCode()。
Examples:
eval("2 + 2")
eval("now()")evalToFunc
@Axonstatic Fn evalToFunc(Str expr)
将 Axon 字符串表达式求值为一个函数。通常表达式只是一个函数名,但它可以是任何求值为函数的表达式。如果表达式无法求值为函数,则抛出异常。注意,此调用会在运行时求值给定的表达式,因此必须谨慎使用——永远不要使用来自不可信来源的字符串。
Examples:
evalToFunc("now").call
evalToFunc("(x, y)=>x+y").call([3, 4])
(evalToFunc("(x, y)=>x+y"))(3, 4)
evalToFunc("""replace(_, "x", "_")""").call(["xyz"])filter
@Axonstatic Obj filter(Expr val, Expr filterExpr)
将过滤表达式应用于字典集合。集合值可以是以下任何一种:
- Grid: returns new grid with filtered rows
- Dict[]: returns list of filtered dicts (nulls are filtered out)
- Col[]: returns list of columns filtered by their meta
- Stream: filters stream of Dicts - see Streams
过滤器参数可以是以下之一:
- Axon expression which maps to a filter
- Filter from
parseFilter() - Filter from
parseSearch()
Examples:
// apply to a list of dicts
[{v:1}, {v:2}, {v:3}, {v:4}].filter(v >= 3)
// apply to a grid and return new grid with matching rows
readAll(equip).filter(meter)
// apply to a list of columns
read(ahu).toPoints.hisRead(yesterday).cols.filter(kind=="Bool")
// apply to a stream of dicts
readAllStream(equip).filter(siteMeter and elec and meter).collect
// apply search filter
readAll(equip).filter(parseSearch("RTU-1"))filterToFunc
@Axonstatic Fn filterToFunc(Expr filterExpr)
Convert a filter expression to a function which maybe used with findAll or find. The returned function accepts one Dict parameter and returns true/false if the Dict is matched by the filter. Also see filter() and 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
@Axonstatic Obj? find(Obj val, Fn fn)
通过应用给定的过滤函数,在列表或网格中查找第一个匹配的项目。如果未找到匹配项,则返回 null。
如果处理的是列表,筛选器应该是一个接受 (val) 或 (val, index) 的函数。它应返回 true 来匹配并返回该项。
如果处理的是字典,过滤器应该是一个接受 (val) 或 (val, name) 的函数。它应返回 true 来匹配并返回该项。
如果使用网格,过滤函数接受 (row) 或 (row, index) 并返回 true 以匹配并返回该行。
如果使用流,过滤器接受 (val) 并返回 true 以匹配。参见流。
Examples:
// find first string longer than 3 chars
["ape", "bat", "charlie", "dingo"].find(x => x.size > 3)
// find first odd number
[10, 4, 3, 7].find(isOdd)findAll
@Axonstatic Obj? findAll(Obj val, Fn fn)
通过应用给定的过滤函数,在列表、字典或网格中查找所有项目。另请参见 find。
如果处理的是列表,则过滤器应为一个函数,接受 (val) 或 (val, index) 参数。它应返回 true 以保留该项。
如果处理字典,过滤器应该是一个接受 (val) 或 (val, name) 的函数。它应该返回 true 来保留该名称/值对。
如果使用网格,过滤函数接受 (row) 或 (row, index) 并返回 true 以保留该行。生成的网格共享原始网格的元数据和列。
如果使用流,过滤器接受 (val) 并返回 true 以匹配。参见流。
Examples:
// find all the strings longer than 3 chars
["ape", "bat", "charlie", "dingo"].findAll(x => x.size > 3)
// find even numbers
[0, 1, 2, 3, 4].findAll(isEven)
// find all the sites greater than 10,000ft from grid
readAll(site).findAll(s => s->area > 10_000ft²)first
@Axonstatic Obj? first(Obj? val)
从有序集合中获取第一个元素,如果集合为空则返回 null:
- list: item at index 0
- grid: first frow
- stream: first item; see Streams
firstOfMonth
@Axon 静态 方法 Date firstOfMonth(Date date)
获取给定日期所在月份的第一天。另请参见 lastOfMonth()。
Example:
2009-10-28.firstOfMonth >> 2009-10-01flatMap
@Axonstatic Obj? flatMap(Obj val, Fn fn)
将列表或网格中的每个项映射到零个或多个新项作为扁平化结果。
If mapping a list, the mapping should be a function that takes (val) or (val, index). It should return the a list of zero or more new values. See List.flatMap.
If mapping a grid, the mapping function takes (row) or (row,index) and returns a list of zero or more new Dict rows. See Grid.flatMap.
如果映射一个流,映射函数接受 (val)。参见流。
Examples:
[1, 2, 3].flatMap(v => [v, v+10]) >> [1, 11, 2, 12, 3, 13]flatten
@Axonstatic Obj flatten(List list)
Flatten a list to a single level. If given a list of grids, then flatten rows to a single grid. Also see List.flatten and Etc.gridFlatten.
Examples:
// flatten a list of numbers
[1, [2, 3], [4, [5, 6]]].flatten >> [1, 2, 3, 4, 5, 6]
// flatten a list of grids
["Carytown", "Gaithersburg"].map(n=>readAll(siteRef->dis==n)).flattenfold
@Axonstatic Obj? fold(Obj? val, Fn fn)
使用给定的折叠函数将列表或流折叠为单个值。折叠函数的签名必须是 (val, acc),其中 val 是正在折叠的项目,acc 是用于在迭代之间保持状态的累加器。折叠的生命周期:
- Call
fn(foldStart, null), return initial accumulator state - Call
fn(item, acc)for every item, return new accumulator state - Call
fn(foldEnd, acc)return final result
请参阅 Streams 以获取流媒体详细信息。
如果折叠函数为累加器状态返回 na(),折叠将会短路并立即停止。在这种情况下,折叠的结果是 na()。折叠函数应当记录其在集合包含 na() 时的行为。
内置折叠功能包括:
Examples:
[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()编写你自己的自定义折叠函数的示例,该函数使用起始/结束值并支持 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另请参见 reduce(),如果你自己做简单的汇总计算,它更容易使用。
foldCol
@Axonstatic Obj? foldCol(Grid grid, Str colName, Fn fn)
将给定列的值归并为单一值。归并函数使用与 fold 相同的语义。
Example:
readAll(site).foldCol("area", sum)foldCols
@Axonstatic Grid foldCols(Grid grid, Obj colSelector, Str newColName, Fn fn)
将每行中的一组列折叠成一个新的折叠列,并返回一个新的网格。要折叠的列由 colSelector 函数选择,并从结果中移除。选择器可以是字符串名称列表,也可以是一个接收列(Col)并返回 true 来选择它的函数。折叠函数使用与 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
The fold end marker value
foldStart
The fold start marker value
format
@Axonstatic Str format(Obj? val, Str? pattern := null)
使用当前区域设置和指定的格式模式格式化对象。格式模式遵循Fantom的toLocale约定:
Bool.toLocaleNumber.toLocaleDate.toLocaleTime.toLocaleDateTime.toLocaleIftoLocalemethod is found, then returnval.toStr
Examples:
123.456kW.format >> 123kW
123.456kW.format("#.0") >> 123.5kW
today().format("D-MMM-YYYY") >> 8-Feb-2023
today().format("DDD MMMM YYYY") >> 8th February 2023
now().format("D-MMM hh:mm") >> 08-Feb 14:50
now().format("DD/MM/YY k:mmaa") >> 08/02/23 2:50pmfromJavaMillis
@Axonstatic DateTime fromJavaMillis(Number millis, Str? tz := null)
Given Number of milliseconds since Unix epoch return a DateTime. The epic is defined as 1-Jan-1970 UTC. If timezone is null, use system default. Also see toJavaMillis.
func
@Axonstatic Dict? func(Obj name, Bool checked := true)
通过名称或引用查找顶级函数并返回其标签。如果未找到,根据检查标志抛出异常或返回空值。
Example:
func("readAll")
func(readAll)funcs
@Axonstatic Grid funcs(Expr filterExpr := Literal.nullVal)
查找当前项目中与给定过滤器匹配的所有顶级函数。如果未提供过滤器,则返回当前项目中声明的所有函数。返回函数的标签。
Examples:
funcs() // all functions
funcs(sparkRule) // match filterget
@Axonstatic Obj? get(Obj? val, Obj? key)
Get an item from a collection:
- str(num): get character at index as int (same semantics as Fantom)
- str(range): get string slice (same semantics as Fantom)
- list(num): get item at given index (same semantics as Fantom)
- list(range): get list slice at given index (same semantics as Fantom)
- dict(key): get item with given key or return null
- grid(num): get row at given index
- grid(range):
Grid.getRange
可以使用 [] 快捷操作符访问 get 函数:
list[3] >> list.get(3)参见 Axon 语言。
getSafe
@Axonstatic Obj? getSafe(Obj? val, Obj? key)
当索引越界时,从字符串、列表或网格中安全地获取一个项目:
- 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.getRangewith safe range
gridColKinds
@Axonstatic Grid gridColKinds(Grid grid)
给定一个网格,返回每列中使用的类型作为一个网格,如下所示:
name: string name of the columnkind: all the different value kinds in the column separated by "|"count: total number of rows with column with a non-null value Also seereadAllTagNames().
Example:
readAll(site).gridColKindsgridColsToDict
@Axonstatic Dict gridColsToDict(Grid grid, Fn colToKey, Fn colToVal)
将网格列转换为名称/值对的字典。名称/值对是使用给定函数从每列派生的。函数接受 (col, index) 参数
Example:
// create dict of column name to column dis
read(temp).hisRead(today).gridColsToDict(c=>c.name, c=>c.meta.dis)gridReplace
@Axonstatic Grid gridReplace(Grid grid, Obj? from, Obj? to)
将每个网格单元中给定的 from 值替换为 to 值。生成的网格具有相同的网格和列元数据。替换比较通过 == 运算符进行,因此它只会替换标量值或 null。
Example:
grid.gridReplace(null, 0) // replace all null cells with zero
grid.gridReplace(na(), 0) // replace all NA cells with zerogridRowsToDict
@Axonstatic Dict gridRowsToDict(Grid grid, Fn rowToKey, Fn rowToVal)
将网格行转换为名称/值对的字典。名称/值对由每一行使用给定的函数生成。函数接受 (row, index)
Example:
// create dict of sites with dis:area pairs
readAll(site).gridRowsToDict(s=>s.dis.toTagName, s=>s->area)has
@Axonstatic Obj? has(Obj? val, Str name)
如果 val 是一个 Grid,则返回它是否具有给定的列名。如果 val 是一个字典,则返回给定的名称是否映射到非空值。
hour
从时间或日期时间中获取介于 0 到 23 的小时整数
hoursInDay
@Axonstatic Number hoursInDay(DateTime dt)
给定某个特定时区的日期时间,返回当天的小时数。进入夏令时的日期将为23小时,而回到标准时间的日期将为25小时。
index
@Axonstatic Obj? index(Obj val, Obj x, Number offset := Number.zero)
在 val 中向前搜索 x 的第一个匹配项,从指定的偏移索引开始。可以使用负偏移从字符串末尾访问。如果未找到任何匹配项,则返回 null:
- if
valis Str, thenxis substring. - if
valis List, thenxis item to search.
indexr
@Axonstatic Obj? indexr(Obj val, Obj x, Number offset := Number.negOne)
在 val 中向后搜索 x 的最后一次匹配,从指定的偏移索引开始。可以使用负偏移从字符串末尾访问。如果未找到任何匹配项,则返回 null:
- if
valis Str, thenxis substring. - if
valis List, thenxis item to search.
insert
@Axonstatic Obj? insert(Obj? val, Number index, Obj? item)
在给定索引处向列表中插入一个项目并返回一个新列表。
insertAll
@Axonstatic Obj? insertAll(Obj? val, Number index, Obj? items)
在给定的索引处插入一个项目列表并返回一个新列表。
isAlpha
@Axonstatic Bool isAlpha(Number num)
数字是ASCII字母字符吗:isUpper||isLower
Examples:
isAlpha("A".get(0)) >> true
isAlpha("a".get(0)) >> true
isAlpha("8".get(0)) >> false
isAlpha(" ".get(0)) >> false
isAlpha("Ã".get(0)) >> falseisAlphaNum
@Axonstatic Bool isAlphaNum(Number num)
数字是 ASCII 字母数字字符吗:isAlpha||isDigit
Examples:
isAlphaNum("A".get(0)) >> true
isAlphaNum("a".get(0)) >> true
isAlphaNum("8".get(0)) >> true
isAlphaNum(" ".get(0)) >> false
isAlphaNum("Ã".get(0)) >> falseisBool
@Axonstatic Bool isBool(Obj? val)
返回对象是否为布尔类型
isDate
@Axonstatic Bool isDate(Obj? val)
Return if an object is a Date type
isDateTime
@Axonstatic Bool isDateTime(Obj? val)
返回对象是否为 DateTime 类型
isDict
@Axonstatic Bool isDict(Obj? val)
Return if an object is a dict type
isDigit
@Axonstatic Bool isDigit(Number num, Number radix := Number.ten)
数字是否是指定进制中的一位。十进制返回 0-9 为真。十六进制也返回 a-f 和 A-F 为真。
Examples:
isDigit("5".get(0)) >> true
isDigit("A".get(0)) >> false
isDigit("A".get(0), 16) >> trueisDuration
@Axonstatic Bool isDuration(Obj? val)
返回对象是否是带时间单位的数字类型
isEmpty
@Axonstatic Obj? isEmpty(Obj? val)
返回集合是否为空:字符串、列表、字典或网格
isEven
@Axonstatic Obj? isEven(Number val)
返回一个整数是否为偶数。
isFunc
@Axonstatic Bool isFunc(Obj? val)
返回对象是否为函数类型
isGrid
@Axonstatic Bool isGrid(Obj? val)
Return if an object is a grid type
isHisGrid
@Axonstatic Bool isHisGrid(Obj? val)
如果一个对象是符合历史网格形状的网格,则返回
isKeyword
@Axonstatic Bool isKeyword(Str val)
返回给定字符串是否是 Axon 关键字
isLeapYear
@Axonstatic Bool isLeapYear(Number year)
返回某年是否为闰年。年份必须是四位数,如2020。
isList
@Axonstatic Bool isList(Obj? val)
Return if an object is a list type
isLower
@Axonstatic Bool isLower(Number num)
数字是 ASCII 小写字母字符吗:a-z
Examples:
isUpper("a".get(0)) >> true
isUpper("A".get(0)) >> false
isUpper("5".get(0)) >> falseisMetric
@Axonstatic Bool isMetric(Obj? val := null)
给定一个可选值,如果应该使用国际单位制返回 true。如果应该使用美国惯用单位制返回 false。使用以下规则:
- if val is a dict with
geoCountryreturn return false if "US" - if number or rec with
unitand 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 localeisNaN
@Axonstatic Bool isNaN(Obj? val)
如果 val 是非数字的数值表示则返回
isNonNull
@Axonstatic Bool isNonNull(Obj? val)
Return if an object is not null
isNull
@Axonstatic Bool isNull(Obj? val)
Return if an object is null
isNumber
@Axonstatic Bool isNumber(Obj? val)
返回对象是否为数字类型
isOdd
@Axonstatic Obj? isOdd(Number val)
返回一个整数是否是奇数。
isRef
@Axonstatic Bool isRef(Obj? val)
Return if an object is a ref type
isSpace
@Axonstatic Bool isSpace(Number num)
数字是否是空白字符:空格
Examples:
isSpace("x".get(0)) >> false
isSpace(" ".get(0)) >> true
isSpace("\n".get(0)) >> trueisSpan
@Axonstatic Bool isSpan(Obj? val)
Return if an object is a span
isStr
@Axonstatic Bool isStr(Obj? val)
Return if an object is a str type
isTagName
@Axonstatic Bool isTagName(Str n)
返回给定的字符串是否是合法的标签名 - 参见 Etc.isTagName
isTime
@Axonstatic Bool isTime(Obj? val)
Return if an object is a Time type
isUpper
@Axonstatic Bool isUpper(Number num)
数字是 ASCII 大写字母字符吗:A-Z
Examples:
isUpper("A".get(0)) >> true
isUpper("a".get(0)) >> false
isUpper("5".get(0)) >> falseisUri
@Axonstatic Bool isUri(Obj? val)
Return if an object is a Uri type
isWeekday
@Axonstatic Obj? isWeekday(Obj t)
给定的日期或日期时间是否落在周一、周二、周三、周四或周五
isWeekend
@Axonstatic Obj? isWeekend(Obj t)
给定的日期或日期时间是否落在星期六或星期日
join
@Axonstatic Grid join(Grid a, Grid b, Str joinColName)
通过列名连接两个网格。当前实现要求:
- 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
@Axonstatic Grid joinAll(Grid[] grids, Str joinColName)
将多个网格列表合并为一个网格。参见 join。
keepCols
@Axonstatic Obj keepCols(Obj grid, Obj[] cols)
Return a new grid with keeps the given columns, but removes all the others. Columns can be Str names or Col instances. Also see Streams.
Example:
readAll(site).keepCols(["id", "area"])last
@Axonstatic Obj? last(Obj? val)
从有序集合中获取最后一项,如果集合为空则返回 null:
- list: item at index -1
- grid: item at index -1
- stream: last item; see Streams
lastMonth
@Axonstatic DateSpan lastMonth()
本月前一个月的日期范围 1..28-31
lastOfMonth
@Axon 静态 方法 Date lastOfMonth(Date date)
获取日期所在月份的最后一天。另请参见 firstOfMonth()。
Example:
2009-10-28.lastOfMonth >> 2009-10-31lastQuarter
@Axonstatic DateSpan lastQuarter()
本季度前的三个月季度的日期范围
lastWeek
@Axonstatic DateSpan lastWeek()
本周前一周的日期范围,周日到周六(使用本地化的周起始日)
lastYear
@Axonstatic DateSpan lastYear()
去年期间的日期范围 1月1日..12月31日
libs
在上下文命名空间中将 lib 定义列为 Def[]。
limit
@Axonstatic Obj limit(Obj? stream, Number limit)
在达到给定限制后截断流。参见流。
localeUse
@Axonstatic Obj? localeUse(Expr locale, Expr expr)
在特定区域设置中评估表达式。这使得可以使用与当前上下文默认值不同的区域设置来格式化和解析本地化文本。
Examples:
// format Date in German
localeUse("de", today().format)
// parse Date in German
localeUse("de", parseDate("01 Mär 2021", "DD MMM YYYY"))lower
@Axonstatic Obj? lower(Obj val)
将字符数字或字符串转换为 ASCII 小写。也可参见 upper() 和 decapitalize()。
Examples:
lower("CAT") >> "cat"
lower("Cat") >> "cat"
lower(65).toChar >> "a"map
@Axonstatic Obj? map(Obj val, Fn fn)
通过应用给定的映射函数来映射列表、字典或网格。
如果映射一个列表,映射应该是一个接收 (val) 或 (val, index) 的函数。它应该返回该索引的新值。
如果映射一个字典,映射函数应该是一个接受 (val) 或 (val, name) 的函数。它应该返回该名称的新值。
如果在映射网格时,映射函数接受(行)或(行,索引)并返回一个用于该行的新字典。生成的网格共享原始网格的网格级元数据。保持不变的列共享旧的元数据,新列没有元数据。如果映射函数返回 null,则该行将在生成的网格中被移除(不进行映射)。
如果映射一个范围,则映射函数接受(整数),并为范围内的每个映射整数返回一个列表。
如果映射一个流,映射函数接受 (val)。参见流。
Examples:
// create list adding ten to each number
[1, 2, 3].map(v => v+10) >> [11, 12, 13]
// create new list that turns strings into uppercase
["ape", "bee", "cat"].map(upper) // ["APE, "BEE", "CAT"]
// create dict adding ten to each value
{a:1, b:2, c:3}.map(v => v+10) >> {a:11, b:12, c:13}
// create grid with just dis, area column
readAll(site).map(s => {dis:s->dis, area:s->area})marker
获取标记值单例 Marker.val
max
@Axon { meta=["foldOn":"Number"] } static Obj? max(Obj? val, Obj? acc)
比较两个数字并返回较大的一个。此函数也可以与 fold 一起使用以返回最大数字(如果没有值则返回 null)。注意,数字的单位不会被检查或用于比较。
Examples:
max(7, 4) >> 7
[7, 2, 4].fold(max) >> 7merge
@Axonstatic Obj? merge(Obj? a, Obj? b)
将两个字典合并并返回一个新的字典。b 中的任何标签都会被添加到 a 中。如果 b 定义了 a 中已有的标签,那么该标签将被 b 覆盖。如果 b 中的某个标签映射到 Remove.val,则该标签将从结果中移除。
meta
@Axonstatic Dict meta(Obj? val)
从网格或列获取元数据作为字典。
Examples:
read(temp).hisRead(today).meta // grid meta
read(temp).hisRead(today).col("ts").meta // column metamin
@Axon { meta=["foldOn":"Number"] } static Obj? min(Obj? val, Obj? acc)
比较两个数字并返回较小的一个。此函数也可与 fold 一起使用以返回最小的数字(如果没有值,则返回 null)。请注意,数字单位 不会 被检查或考虑在此比较中。
Examples:
min(7, 4) >> 4
[7, 2, 4].fold(min) >> 2minute
@Axonstatic Obj? minute(Obj t)
从时间或日期时间中获取分钟数,作为 0 到 59 之间的整数
missing
@Axonstatic Obj? missing(Obj? val, Str name)
如果 val 是一个 Grid,则当它没有给定的列名时返回。如果 val 是一个 Dict,则当给定的名称没有映射到非空值时返回。
month
从日期或日期时间获取介于1到12之间的月份整数
moveTo
@Axonstatic Obj[] moveTo(Obj[] list, Obj? item, Number toIndex)
在列表中找到指定的项,并将其移动到给定的索引。所有其他项会相应地移动。可以使用负索引从列表末尾访问索引。如果未找到该项,则不执行任何操作。返回新列表。
Examples:
[10, 11, 12].moveTo(11, 0) >> [11, 10, 12]
[10, 11, 12].moveTo(11, -1) >> [10, 12, 11]na
获取 NA 不可用单例 NA.val
name
@Axonstatic Str name(Obj? val)
如果 val 是一个列,获取列名。
Example:
// get name of first column
readAll(site).cols.first.namenames
@Axonstatic Obj? names(Dict dict)
获取给定字典使用的名称列表
nan
返回非数字的数字表示
negInf
返回数字表示的负无穷
now
根据上下文的时区返回当前日期时间。此函数将使用缓存版本,该版本的精确度仅在250毫秒以内(详情请参见 DateTime.now)。另请参见 nowTicks() 和 nowUtc()。
nowTicks
以自 2000 年 1 月 1 日 UTC 起的纳秒计数返回当前时间。注意,纳秒计数的 64 位浮点表示在微秒以下会失去精度。另请参见 now()。
nowUtc
返回当前的 UTC 日期时间。此函数将使用一个缓存版本,其精确度仅在 250 毫秒以内(详情请参见 DateTime.nowUtc)。另请参见 now() 和 nowTicks()。
numDays
@Axonstatic Number numDays(Obj? span)
Number of whole days in a span
numDaysInMonth
@Axonstatic Number numDaysInMonth(Obj? month := null)
获取给定月份的天数。月份参数可以是:
- 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
@Axonstatic Obj? occurred(Obj? ts, Obj? range)
返回一个时间戳是否包含在一个日期范围内。范围可以是 toDateSpan 支持的任何值。时间戳可以是日期或日期时间。另请参见 contains。
Examples:
ts.occurred(thisWeek)
ts.occurred(pastMonth())
ts.occurred(2010-01-01..2010-01-15)padl
@Axonstatic Str padl(Str val, Number width, Str char := " ")
将字符串左侧填充。如果长度小于宽度,则在左侧添加指定字符以达到指定宽度。
Examples:
"3".padl(3, "0") >> "003"
"123".padl(2, "0") >> "123"padr
@Axonstatic Str padr(Str val, Number width, Str char := " ")
将字符串向右填充。如果大小小于宽度,则在左侧添加给定字符以达到指定宽度。
Examples:
"xyz".padr(2, ".") >> "xyz"
"xyz".padr(5, "-") >> "xyz--"parseAst
@Axonstatic Dict parseAst(Str src)
将 Axon 源代码解析为一个抽象语法树,以字典树的形式建模。每个节点都有一个类型标签,用于指定节点类型。常见的 AST 结构:
123 => {type:"literal", val:123}
a => {type:"var", name:"a"}
not a => {type:"not", operand:{type:"var", name:"a"}}
a + b => {type:"add", lhs:{type:"var", name:"a"}, rhs:{type:"var", name:"b"}}注意:AST 的键和值的结构可能会随着时间而变化。
parseBool
@Axonstatic Bool? parseBool(Str val, Bool checked := true)
将字符串解析为布尔值,合法格式为“true”或“false”。如果格式无效且 checked 为 false,则返回 null,否则抛出 ParseErr。
Examples:
parseBool("true")
parseBool("bad", false)parseDate
@Axonstatic Date? parseDate(Str val, Str pattern := "YYYY-MM-DD", Bool 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.
Examples:
parseDate("7-Feb-23", "D-MMM-YY")
parseDate("07/02/23", "DD/MM/YY")
parseDate("7 february 2023", "D MMMM YYYY")
parseDate("230207", "YYMMDD")parseDateTime
@Axonstatic DateTime? parseDateTime(Str val, Str pattern := "YYYY-MM-DD'T'hh:mm:SS.FFFFFFFFFz zzzz", Str tz := TimeZone.cur().name(), Bool 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:
YY Two digit year 07
YYYY Four digit year 2007
M One/two digit month 6, 11
MM Two digit month 06, 11
MMM Three letter abbr month Jun, Nov
MMMM Full month June, November
D One/two digit day 5, 28
DD Two digit day 05, 28
DDD Day with suffix 1st, 2nd, 3rd, 24th
WWW Three letter abbr weekday Tue
WWWW Full weekday Tuesday
V One/two digit week of year 1,52
VV Two digit week of year 01,52
VVV Week of year with suffix 1st,52nd
h One digit 24 hour (0-23) 3, 22
hh Two digit 24 hour (0-23) 03, 22
k One digit 12 hour (1-12) 3, 11
kk Two digit 12 hour (1-12) 03, 11
m One digit minutes (0-59) 4, 45
mm Two digit minutes (0-59) 04, 45
s One digit seconds (0-59) 4, 45
ss Two digit seconds (0-59) 04, 45
SS Optional seconds (only if non-zero)
f* Fractional secs trailing zeros
F* Fractional secs no trailing zeros
a Lower case a/p for am/pm a, p
aa Lower case am/pm am, pm
A Upper case A/P for am/pm A, P
AA Upper case AM/PM AM, PM
z Time zone offset Z, +03:00 (ISO 8601, XML Schema)
zzz Time zone abbr EST, EDT
zzzz Time zone name New_York
'xyz' Literal characters
'' Single quote literalExamples:
parseDateTime("2023-02-07 14:30", "YYYY-MM-DD hh:mm")
parseDateTime("2023-02-07 14:30", "YYYY-MM-DD hh:mm", "Paris")
parseDateTime("7/2/23 2:30pm", "D/M/YY k:mma")
parseDateTime("2023-02-07T14:30:00", "YYYY-MM-DD'T'hh:mm:ss")parseFilter
@Axonstatic Obj? parseFilter(Str val, Bool checked := true)
将过滤器字符串解析为 Filter 实例。生成的过滤器随后可以与 read()、readAll()、filter() 或 filterToFunc() 一起使用。
Example:
str: "point and kw"
readAll(parseFilter(str))parseFloat
@Axonstatic Number? parseFloat(Str val, Bool 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).
Examples:
parseFloat("123.456").format("0.000")
parseFloat("NaN")
parseFloat("INF")parseInt
@Axonstatic Number? parseInt(Str val, Number radix := Number.ten, Bool 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).
Examples:
parseInt("123")
parseInt("afe8", 16)
parseInt("10010", 2)parseNumber
@Axonstatic Number? parseNumber(Str val, Bool 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.
Examples:
parseNumber("123")
parseNumber("123kW")
parseNumber("123.567").format("#.000")parseRef
@Axonstatic Ref? parseRef(Str val, Obj? dis := null, Bool checked := true)
将一个字符串解析为引用。如果该字符串不是有效的引用标识符,则根据检查标志抛出 ParseErr 或返回 null。如果字符串前有 "@",则在解析前会去掉它。
Examples:
parseRef("abc-123")
parseRef("@abc-123")parseSearch
@Axonstatic Filter parseSearch(Str val)
将搜索字符串解析为 Filter 实例。生成的过滤器然后可以与 read()、readAll()、filter() 或 filterToFunc() 一起使用。
搜索字符串是以下自由模式之一:
*<glob>*case insensitive glob with ? and * wildcards (default)re:<regex>regular expressionf:<filter>haystack filter
请参阅导航了解搜索语法的更多详细信息。
Examples:
readAll(parseSearch("RTU-1"))
readAll(point).filter(parseSearch("RTU* Fan"))parseSymbol
@Axonstatic Symbol? parseSymbol(Str val, Bool checked := true)
将字符串解析为符号。如果字符串不是有效的符号标识符,则根据 checked 标志抛出 ParseErr 或返回 null。字符串 不得 包含前导 "^"。
Examples:
parseSymbol("func:now")parseTime
@Axonstatic Time? parseTime(Str val, Str pattern := "hh:mm:SS", Bool 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.
Examples:
parseTime("14:30", "h:mm")
parseTime("2:30pm", "k:mma")
parseTime("2:30:00pm", "k:mm:ssa")parseUnit
@Axonstatic Str? parseUnit(Str val, Bool checked := true)
将字符串解析为标准化的单位名称。如果值不是标准数据库中的有效单位名称,则根据检查标志返回 null 或引发异常。
Examples:
parseUnit("%")
parseUnit("percent")parseUri
@Axonstatic Uri? parseUri(Str val, Bool 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`pastMonth
@Axonstatic DateSpan pastMonth()
最近30天的日期范围 今天-30天..今天
pastWeek
@Axonstatic DateSpan pastWeek()
过去7天的日期范围为 today-7days..today
pastYear
@Axonstatic DateSpan pastYear()
过去今天到今日的日期范围-365天..今天
posInf
返回数字表示的正无穷
reFind
@Axonstatic Str? reFind(Obj regex, Str s)
在 s 中查找正则表达式的第一个匹配项,如果没有匹配项则返回 null。参见 AxonUsage。
Examples:
reFind(r"\d+", "x123y") >> "123"
reFind(r"\d+", "xyz") >> nullreFindAll
@Axonstatic Str[] reFindAll(Obj regex, Str s)
在 s 中查找正则表达式的所有匹配项。如果没有匹配项,则返回空列表。
Examples:
reFindAll(r"-?\d+\.?\d*", "foo, 123, bar, 456.78, -9, baz")
>> ["123", "456.78", "-9"]
reFindAll(r"\d+", "foo, bar, baz")
>> [,]reGroups
@Axonstatic Obj? reGroups(Obj regex, Str s)
返回一个列表,该列表包含将给定的正则操作与 s 匹配时捕获的子字符串。如果没有匹配,则返回 null。列表中的第一个项目是整个匹配,每个额外的项目与正则模式中的 () 参数匹配。参见 AxonUsage。
Examples:
re: r"(RTU|AHU)-(\d+)"
reGroups(re, "AHU") >> null
reGroups(re, "AHU-7") >> ["AHU-7", "AHU", "7"]reMatches
@Axonstatic Bool reMatches(Obj regex, Str s)
如果正则表达式匹配 s 的整个区域则返回。参见 AxonUsage。
Examples:
reMatches(r"\d+", "x123y") >> false
reMatches(r"\d+", "123") >> truereduce
@Axonstatic Obj? reduce(Obj val, Obj? init, Fn fn)
使用给定的归约函数将集合减少到单个值。给定的函数会对集合中的每个项调用,同时传入当前的累积值。累积值在第一个项时初始化为 init,对于每个后续项,它是前一项的结果。返回最终的累积值。另请参见 fold,如果进行标准汇总(如求和或平均)时,优先使用 fold。
如果处理的是列表,函数接收 (acc, val, index) 并返回累积值
如果使用网格,函数接受 (acc, row, index) 并返回累积值
如果处理流,则函数接受 (acc, val) 并返回累积值。参见流。
Examples:
[2, 5, 3].reduce(0, (acc, val)=>acc+val) >> 10
[2, 5, 3].reduce(1, (acc, val)=>acc*val) >> 30refDis
@Axonstatic Str refDis(Ref ref)
给定一个 ref 返回 Ref.dis
refGen
生成一个新的唯一引用标识符
refProjName
@Axonstatic Str? refProjName(Ref ref, Bool checked := true)
给定一个绝对引用,返回其项目名称。如果引用的格式不是 "p:proj:r:xxx",则根据检查标志引发异常或返回空值:
Examples:
refProjName(@p:demo:r:xxx) >> "demo"
refProjName(@r:xxx) >> raises exception
refProjName(@r:xxx, false) >> nullrelDis
@Axonstatic Str relDis(Obj parent, Obj child)
获取相对显示名称。如果子显示名称以父显示名称开头,那么我们可以将其作为公共后缀去掉。父项和子项必须是字典或字符串。
remove
@Axonstatic Obj? remove(Obj? val, Obj? key)
从集合中移除一个项并返回一个新的集合。
- List: key is index to remove at
- Dict: key is tag name
removeCol
@Axonstatic Obj removeCol(Obj grid, Obj col)
返回一个删除指定列的新网格。如果该列不存在,则返回给定的网格。另请参见 Streams。
removeCols
@Axonstatic Obj removeCols(Obj grid, Obj[] cols)
Return a new grid with all the given columns removed. Columns can be Str names or Col instances. Also see Streams.
removeMarker
@Axonstatic Remove removeMarker()
获取移除值单例 Remove.val
renameCol
@Axonstatic Grid renameCol(Grid grid, Str oldName, Str newName)
返回一个新的网格,并将给定的列重命名。
Example:
readAll(site).renameCol("dis", "title")renameCols
@Axonstatic Grid renameCols(Grid grid, Dict mapping)
返回一个新的网格,其中多个列已重命名。映射必须是旧名称到新名称的字典。未找到的旧列名称将被忽略。
Example:
readAll(site).renameCols({dis:"title", geoAddr:"subtitle"})reorderCols
@Axonstatic Obj reorderCols(Obj grid, Str[] colNames)
返回一个新网格,其中列已重新排序。给定的名称列表表示新的顺序,必须包含相同的当前列名。未指定的任何列将被删除。另请参阅 colNames、moveTo 和 Streams。
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
@Axonstatic Str replace(Str val, Str from, Str to)
将所有出现的 from 替换为 to。三个参数都必须是字符串。
Examples:
"hello".replace("hell", "t") >> "to"
"aababa".replace("ab", "-") >> "a--a"rowToList
@Axonstatic Obj?[] rowToList(Row row)
将网格行作为单元格列表获取。稀疏单元格会以 null 包含。另请参见 colToList()。
Example:
readAll(equip).first.rowToListsecond
@Axonstatic Obj? second(Obj t)
从时间或日期时间中获取以整数表示的秒数,范围为0到59
set
@Axonstatic Obj? set(Obj? val, Obj? key, Obj? item)
设置集合项并返回一个新的集合。
- List: set item by index key
- Dict: set item by key name
setColMeta
@Axonstatic Obj setColMeta(Obj grid, Str name, Dict meta)
返回一个新的表格,其中列的元数据被给定的元数据字典替换。如果未找到列,则返回给定的表格。另请参见 addColMeta 和 Streams。
setMeta
@Axonstatic Obj setMeta(Obj grid, Dict meta)
Return new grid with grid level meta-data replaced by given meta Dict. Also see addMeta and Streams.
Example:
read(temp).hisRead(today).setMeta({view:"table"})size
@Axonstatic Number size(Obj? val)
返回 str、列表或网格中的项目数量
skip
@Axonstatic Obj skip(Obj? stream, Number count)
跳过流中的给定数量的项。参见流。
sort
@Axonstatic Obj? sort(Obj val, Obj? sorter := null)
Sort a list or grid.
如果对列表进行排序,排序器应该是一个接受两个列表项并返回 -1、0 或 1 的函数(通常使用 <=> 运算符完成)。如果没有传递排序器,则列表将按其自然顺序排序。
如果对网格进行排序,排序器可以是列名或函数。如果是函数,它应该接受两行并返回 -1、0 或 1。
Examples:
// sort string list
["bear", "cat", "apple"].sort
// sort string list by string size
["bear", "cat", "apple"].sort((a,b) => a.size <=> b.size)
// sort sites by area
readAll(site).sort((a, b) => a->area <=> b->area)sortDis
@Axonstatic Obj? sortDis(Grid val)
Sort a grid by row display name - see Grid.sortDis
Examples:
// read all sites and sort by display name
readAll(site).sortDissortr
@Axonstatic Obj? sortr(Obj val, Obj? sorter := null)
将列表或网格进行逆向排序。此函数的作用与排序相同,只是按相反的顺序排序。
split
@Axonstatic Obj? split(Str val, Str? sep := null, Dict? opts := null)
Split a string by the given separator and trim whitespace. If sep is null then split by any whitespace char; otherwise it must be exactly one char long. See Str.split for detailed behavior.
Options:
- noTrim: disable auto-trim of whitespace from start and end of tokens
Examples:
"a b c".split >> ["a", "b", "c"]
"a,b,c".split(",") >> ["a", "b", "c"]
"a, b, c".split(",") >> ["a", "b", "c"]
"a, b, c".split(",", {noTrim}) >> ["a", " b", " c"]spread
@Axon { meta=["foldOn":"Number"] } static Obj? spread(Obj? val, Obj? acc)
折叠多个值以计算最大值和最小值之间的差值。如果没有值,则返回 null。
Example:
[7, 2, 3].fold(spread) >> 5start
@Axonstatic Obj? start(Obj? val)
DateSpan、Span 或范围的起始值。
startOfWeek
@Axonstatic Number startOfWeek()
Return current locale's start of weekday. Weekday is returned as integer from 0 (Sunday) to 6 (Saturday).
startsWith
@Axonstatic Bool startsWith(Str val, Str sub)
如果 Str 以指定的 Str 开头,则返回。
Examples:
"hi there".startsWith("hi") >> true
"hi there".startsWith("foo") >> falsestream
@Axonstatic Obj stream(Obj? val)
从给定集合创建新流:
- Grid: stream the rows
- List: stream the items
- Range: stream inclusive range of integers See Streams.
streamCol
@Axonstatic Obj streamCol(Grid grid, Obj col)
为给定列的单元格值创建一个新流。请参阅流。
sum
@Axon { meta=["foldOn":"Number"] } static Obj? sum(Obj? val, Obj? acc)
将多个值折叠为它们的数字总和。如果没有值,则返回 null。
swizzleRefs
@Axonstatic Grid swizzleRefs(Grid grid)
给定一个记录网格,为其分配新的 ID,并重排所有内部引用标签。网格的每一行都必须有一个 ID 标签。每一行都会生成一个新的 ID,任何使用旧 ID 的引用标签都会被新的 ID 替换。这个函数对于复制记录图(例如站点/设备/点树)非常有用。
tags
在上下文命名空间中将标签定义列为 Def[]。
terms
List term definitions (tags and conjuncts) in the context namespace as Def[].
thisMonth
@Axonstatic DateSpan thisMonth()
本月的日期范围为1日到28-31日
thisQuarter
@Axonstatic DateSpan thisQuarter()
DateSpan for this 3 month quarter
thisWeek
@Axonstatic DateSpan thisWeek()
本周的日期范围为周日..周六(使用本地星期开始日)
thisYear
@Axonstatic DateSpan thisYear()
今年的日期范围 1月1日..12月31日
time
@Axonstatic Obj? time(Obj val, Number? minutes := null, Number secs := Number.zero)
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:45times
@Axonstatic Obj? times(Number times, Fn fn)
调用指定的函数给定次数,同时传递计数器。
to
@Axonstatic Number? to(Number? val, Obj? 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. Also see as() function to set a unit without conversion.
Examples:
10kWh.to(1BTU)
10kWh.to("BTU")
75°F.to(1°C)
to(75°F, 1°C)toAxonCode
@Axonstatic Obj? toAxonCode(Obj? val)
将标量、列表或字典值转换为其 Axon 代码表示。例如:
toAxonCode(123) => "123"
toAxonCode([1, 2, 3]) => "[1, 2, 3]"
toAxonCode({x:123}) => "{x:123}"toChar
@Axonstatic Str toChar(Number num)
将一个 Unicode 字符编号转换为单个字符字符串
Examples:
toChar(65) >> "A"toDateSpan
@Axonstatic DateSpan toDateSpan(Obj? x)
将以下对象转换为日期跨度:
Func: function which evaluates to date rangeDateSpan: return itselfDate: one day rangeSpan: returnSpan.toDateSpanStr: evaluates toDateSpan.fromStrDate..Date: starting and ending date (inclusive)Date..Number: starting date and num of days (day unit required)DateTime..DateTime: use starting/ending dates; if end is midnight, then use previous dateNumber: convert as year- null: use projMeta dateSpanDefault or default to today (deprecated)
Examples:
toDateSpan(2010-07-01..2010-07-03) >> 01-Jul-2010..03-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-2010toGrid
@Axonstatic Grid toGrid(Obj? val, Dict? meta := 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}].toGridtoHex
@Axonstatic Obj? toHex(Number val)
将一个数字转换为十六进制字符串。
toJavaMillis
@Axonstatic Number toJavaMillis(DateTime dt)
Given a DateTime return Number of milliseconds since Unix epoch. The epic is defined as 1-Jan-1970 UTC. Also see fromJavaMillis.
toList
@Axonstatic Obj?[] toList(Obj? val)
如果 val 是列表,则返回它,否则返回 [val]。
toLocale
@Axonstatic Str toLocale(Str key)
获取给定标签名或限定名的本地化字符串。如果键的格式为 "pod::name",则路由到 Env.locale,否则路由到 Etc.tagToLocale。
toRadix
@Axonstatic Obj? toRadix(Number val, Number radix, Number? width := null)
将一个数字转换为给定基数(进制)的字符串表示。如果宽度不为空,则在前面加上前导零以确保指定的宽度。
Example:
6.toRadix(2) => "110"
255.toRadix(16, 4) => "00ff"toSpan
@Axonstatic Span toSpan(Obj? x, Str? tz := null)
将以下对象转换为 Span:
Span: return itselfSpan+tz: update timezone using same dates only if aligned to midnightStr: returnSpan.fromStrusing current timezoneStr+tz: returnSpan.fromStrusing given timezoneDateTime..DateTime: range of two DateTimesDate..DateTime: start day for date until the end timestampDateTime..Date: start timestamp to end of day for end dateDateTime: span of a single timestampDateSpan: anything accepted bytoDateSpanin current timezoneDateSpan+tz: anything accepted bytoDateSpanusing given timezone
toTagName
@Axonstatic Str toTagName(Str n)
给定任意字符串,转换为安全的标签名称 - 参见 Etc.toTagName
toTimeZone
@Axonstatic Obj? toTimeZone(Obj val, Str tz)
将日期时间或时间间隔转换到另一个时区:
now().toTimeZone("Chicago")
now().toTimeZone("UTC")today
根据上下文的时区返回今天的日期
transpose
@Axonstatic Grid transpose(Grid grid)
对网格执行矩阵转置。第一列的单元格成为新列的显示名称。列 1..n 成为新的行。
Example:
readAll(site).transposetrim
从字符串的开头和结尾修剪空白字符。对于此函数,空白字符定义为任何小于或等于 0x20 空格字符的字符(包括 , \r, \n 和 \t)。
Examples:
" abc ".trim >> "abc"
"abc".trim >> "abc"trimEnd
@Axonstatic Str trimEnd(Str val)
仅从字符串末尾修剪空白。有关空白的定义,请参阅 trim。
Examples:
" abc ".trimEnd >> " abc"
"abc".trimEnd >> "abc"trimStart
@Axonstatic Str trimStart(Str val)
仅从字符串的开头去除空白。有关空白的定义,请参见 trim。
Examples:
" abc ".trimStart >> "abc "
"abc".trimStart >> "abc"tz
@Axonstatic Obj? tz(DateTime? dt := null)
从 datetime 获取 tzinfo 数据库中的城市名称字符串形式的时区。如果 datetime 为 null,则返回环境默认时区。
unique
@Axonstatic Obj? unique(Obj val, Obj? 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 combosunit
@Axonstatic Str? unit(Number? val)
给定一个数字,返回它的单位字符串或 null。如果值为 null,则返回 null。
unitsEq
@Axonstatic Bool unitsEq(Number? a, Number? b)
如果两个数字具有相同的单位,则返回。 如果任一数字为 null,则返回 false。
upper
@Axonstatic Obj? upper(Obj val)
将字符数字或字符串转换为 ASCII 大写。另请参见 lower() 和 capitalize()。
Examples:
upper("cat") >> "CAT"
upper("Cat") >> "CAT"
upper(97).toChar >> "A"uriBasename
@Axonstatic Str? uriBasename(Uri val)
将 Uri 的基本名称(路径中的最后一个名称,不包括扩展名)作为字符串获取。
uriDecode
@Axonstatic Uri uriDecode(Str val, Bool 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
@Axonstatic Str uriEncode(Uri val)
根据 RFC 3986 返回此 Uri 的百分号编码字符串。Uri 的每个部分都以 UTF-8 编码为字节,然后根据其有效字符集进行百分号编码。查询部分的空格编码为 +。
Examples:
`foo bar`.uriEncode >> "foo%20bar"uriExt
@Axonstatic Str? uriExt(Uri val)
将 Uri 的 URI 扩展作为字符串或 null 获取。
uriFrag
@Axonstatic Str? uriFrag(Uri val)
返回 URI 中哈希符号后的片段标识部分
uriHost
@Axonstatic Str? uriHost(Uri val)
将主机 Uri 获取为字符串或 null
uriIsDir
@Axonstatic Bool uriIsDir(Uri val)
如果 URI 路径以斜杠结尾,则返回。
uriName
@Axonstatic Str? uriName(Uri val)
Get the name Str of a Uri (last item in path).
uriPath
@Axonstatic Obj? uriPath(Uri val)
将 Uri 的路径段作为字符串列表获取。
uriPathStr
@Axonstatic Str? uriPathStr(Uri val)
Get the path a Uri as a string.
uriPlusSlash
@Axonstatic Uri uriPlusSlash(Uri val)
Adding trailing slash to the URI. See Uri.plusSlash
uriPort
@Axonstatic Number? uriPort(Uri val)
获取 Uri 的端口号,返回数字或 null
uriQueryStr
@Axonstatic Str? uriQueryStr(Uri val)
返回 URI 中问号之后的查询部分
uriScheme
@Axonstatic Str? uriScheme(Uri val)
以字符串形式获取 Uri 的方案,或返回 null
vals
@Axonstatic Obj? vals(Dict dict)
获取给定字典使用的值的列表
weekOfYear
@Axonstatic Number weekOfYear(Obj val, Number? startOfWeek := null)
给定一个 DateTime 或 Date,返回该年的周数。结果是一个介于 1 到 53 之间的数字,使用指定的周起始日(作为 0-6 的数字,默认为当前语言环境的周起始日)。
weekday
@Axonstatic Number weekday(Obj t)
获取日期或日期时间的星期几作为从 0 到 6 的整数。0 表示星期日,6 表示星期六
xstr
@Axonstatic Obj xstr(Str type, Str val)
构造解码的 XStr 实例
year
从日期或日期时间获取年份作为整数,例如 2010
yesterday
根据上下文的时区返回昨天的日期
EvalErr
@Js const class EvalErr : AxonErr
EvalErr 在评估阶段被抛出。
Constructors
| make |
Fields
| axonTrace | Axon trace of call stack and scope variables |
插槽详情
axonTrace
const Str axonTrace
调用堆栈和作用域变量的轴迹
make
new make(Str? msg, AxonContext cx, Loc loc, Err? cause := null)
Expr
@Js abstract const class Expr : Obj
Expr 是 Axon AST 节点的基类。所有表达式都是不可变类,一旦解析完成,就可以在多个线程之间安全共享。
Methods
| encode | Encode the AST into a tree of dicts. |
| eval | Evaluate this expression. |
| loc | Location of this expression in source code or Loc.unknown. |
| toStr | Print to string |
插槽详情
encode
Dict encode()
将 AST 编码为字典树。参见 parseAst()。
eval
abstract Obj? eval(AxonContext cx)
Evaluate this expression.
loc
abstract Loc loc()
此表达式在源代码中的位置或位置未知。
toStr
virtual override Str toStr()
Print to string
Fn
@Js 常量 类 Fn : 表达式
Fn is a function definition
Fields
| name | Top-level name or debug name if closure |
Methods
| call | Invoke this function with the given arguments. |
| eval | Return this |
| isTop | |
| meta | |
| walk |
插槽详情
call
Obj? call(AxonContext cx, Obj?[] args)
使用给定的参数调用此函数。注意:args 参数必须是可变的,并且可能会被修改
eval
virtual override Obj? eval(AxonContext cx)
Return this
isTop
virtual Bool isTop()
meta
virtual Dict meta()
name
const Str name
顶级名称或闭包的调试名称
walk
virtual override Void walk(|Str,Obj?| f)
Loc
@Js const class Loc : Obj
Source code location.
Constructors
| make | Constructor |
Fields
| eval | Generic eval location |
| file | File or func record name |
| line | Line number (one based) |
| unknown | Unknown location |
Methods
| isUnknown | Is this the unknown location |
| toStr | Location string |
插槽详情
eval
const static Loc eval := Loc.<ctor>("eval", 0)
Generic eval location
file
const Str file
File or func record name
isUnknown
Bool isUnknown()
Is this the unknown location
line
const Int line
Line number (one based)
make
new make(Str file, Int line := 0)
Constructor
toStr
virtual override Str toStr()
Location string
unknown
const static Loc unknown := Loc.<ctor>("unknown", 0)
Unknown location
SyntaxErr
@Js const class SyntaxErr : AxonErr
在解析阶段会抛出 SyntaxErr。
Constructors
| make |
插槽详情
make
new make(Str? msg, Loc loc, Err? cause := null)
TopFn
@Js const class TopFn : Fn
命名空间中的顶层函数
Constructors
| make |
Fields
| isAdmin | Is this function tagged as admin-only |
| isDeprecated | Return if this function has been deprecated |
| isSu | Is this function tagged as superuser-only |
| meta | Func def metadata |
Methods
| isLazy | Is this a lazy function that accepts un-evaluated arguments |
| isTop | Return true |
| toStr | Return only name |
插槽详情
isAdmin
virtual const override Bool isAdmin
这个功能被标记为仅限管理员使用吗
isDeprecated
virtual const override Bool isDeprecated
返回此函数是否已被弃用
isLazy
virtual Bool isLazy()
这是一个接受未求值参数的惰性函数吗
isSu
virtual const override Bool isSu
这个功能是否标记为仅限超级用户
isTop
virtual override Bool isTop()
Return true
make
new make(Loc loc, Str name, Dict meta, FnParam[] params, Expr body := Literal.nullVal)
meta
virtual const override Dict meta
Func def metadata
toStr
virtual override Str toStr()
Return only name