17. The rest

  Namespace predef::


Method sin

float sin(float f)

Description

Returns the sine value for f . f should be specified in radians.

See also

asin() , cos() , tan()


Method asin

float asin(float f)

Description

Return the arcus sine value for f . The result will be in radians.

See also

sin() , acos()


Method cos

float cos(float f)

Description

Return the cosine value for f . f should be specified in radians.

See also

acos() , sin() , tan()


Method acos

float acos(float f)

Description

Return the arcus cosine value for f . The result will be in radians.

See also

cos() , asin()


Method tan

float tan(float f)

Description

Returns the tangent value for f . f should be specified in radians.

See also

atan() , sin() , cos()


Method atan

float atan(float f)

Description

Returns the arcus tangent value for f . The result will be in radians.

See also

tan() , asin() , acos() , atan2()


Method atan2

float atan2(float f1, float f2)

Description

Returns the arcus tangent value for f1 /f2 , and uses the signs of f1 and f2 to determine the quadrant. The result will be in radians.

See also

tan() , asin() , acos() , atan()


Method sinh

float sinh(float f)

Description

Returns the hyperbolic sine value for f .

See also

asinh() , cosh() , tanh()


Method asinh

float asinh(float f)

Description

Return the hyperbolic arcus sine value for f .

See also

sinh() , acosh()


Method cosh

float cosh(float f)

Description

Return the hyperbolic cosine value for f .

See also

acosh() , sinh() , tanh()


Method acosh

float acosh(float f)

Description

Return the hyperbolic arcus cosine value for f .

See also

cosh() , asinh()


Method tanh

float tanh(float f)

Description

Returns the hyperbolic tangent value for f .

See also

atanh() , sinh() , cosh()


Method atanh

float atanh(float f)

Description

Returns the hyperbolic arcus tangent value for f .

See also

tanh() , asinh() , acosh()


Method sqrt

float sqrt(float f)
int sqrt(int i)
mixed sqrt(object o)

Description

Returns the square root of f , or in the integer case, the square root truncated to the closest lower integer. If the argument is an object, the lfun _sqrt in the object will be called.

See also

pow() , log() , exp() , floor() , lfun::_sqrt


Method log

float log(float f)

Description

Return the natural logarithm of f . exp( log(x) ) == x for x > 0.

See also

pow() , exp()


Method exp

float exp(float|int f)

Description

Return the natural exponential of f . log( exp( x ) ) == x as long as exp(x) doesn't overflow an int.

See also

pow() , log()


Method pow

int|float pow(float|int n, float|int x)
mixed pow(object n, float|int|object x)

Description

Return n raised to the power of x . If both n and x are integers the result will be an integer. If n is an object its pow method will be called with x as argument.

See also

exp() , log()


Method floor

float floor(float f)

Description

Return the closest integer value less or equal to f .

Note

floor() does not return an int, merely an integer value stored in a float.

See also

ceil() , round()


Method ceil

float ceil(float f)

Description

Return the closest integer value greater or equal to f .

Note

ceil() does not return an int, merely an integer value stored in a float.

See also

floor() , round()


Method round

float round(float f)

Description

Return the closest integer value to f .

Note

round() does not return an int, merely an integer value stored in a float.

See also

floor() , ceil()


Method min

int|float|object min(int|float|object ... args)
string min(string ... args)
int(0..0) min()

Description

Returns the smallest value among args . Compared objects must implement the lfun::`< method.

See also

max()


Method max

int|float|object max(int|float|object ... args)
string max(string ... args)
int(0..0) max()

Description

Returns the largest value among args . Compared objects must implement the lfun::`< method.

See also

min()


Method abs

float abs(float f)
int abs(int f)
object abs(object f)

Description

Return the absolute value for f . If f is an object it must implement lfun::`< and unary lfun::`- .


Method sgn

int sgn(mixed value)
int sgn(mixed value, mixed zero)

Description

Check the sign of a value.

Returns

Returns -1 if value is less than zero , 1 if value is greater than zero and 0 (zero) otherwise.

See also

abs()


Method file_stat

Stdio.Stat file_stat(string path, void|int(0..1) symlink)

Description

Stat a file.

If the argument symlink is 1 symlinks will not be followed.

Returns

If the path specified by path doesn't exist 0 (zero) will be returned.

Otherwise an object describing the properties of path will be returned.

Note

In Pike 7.0 and earlier this function returned an array with 7 elements. The old behaviour can be simulated with the following function:

array(int) file_stat(string path, void|int(0..1) symlink) { File.Stat st = predef::file_stat(path, symlink); if (!st) return 0; return (array(int))st; }

See also

Stdio.Stat , Stdio.File->stat()


Method file_truncate

int file_truncate(string file, int length)

Description

Truncates the file file to the length specified in length .

Returns

Returns 1 if ok, 0 if failed.


Method filesystem_stat

mapping(string:int) filesystem_stat(string path)

Description

Returns a mapping describing the properties of the filesystem containing the path specified by path .

Returns

If a filesystem cannot be determined 0 (zero) will be returned.

Otherwise a mapping(string:int) with the following fields will be returned:

"blocksize" : int

Size in bytes of the filesystem blocks.

"blocks" : int

Size of the entire filesystem in blocks.

"bfree" : int

Number of free blocks in the filesystem.

"bavail" : int

Number of available blocks in the filesystem. This is usually somewhat less than the "bfree" value, and can usually be adjusted with eg tunefs(1M).

"files" : int

Total number of files (aka inodes) allowed by this filesystem.

"ffree" : int

Number of free files in the filesystem.

"favail" : int

Number of available files in the filesystem. This is usually the same as the "ffree" value, and can usually be adjusted with eg tunefs(1M).

"fsname" : string

Name assigned to the filesystem. This item is not available on all systems.

"fstype" : string

Type of filesystem (eg "nfs"). This item is not available on all systems.


Note

Please note that not all members are present on all OSs.

See also

file_stat()


Method werror

void werror(string msg, mixed ... args)

Description

Write to standard error.


Method rm

int rm(string f)

Description

Remove a file or directory.

Returns

Returns 0 (zero) on failure, 1 otherwise.

See also

mkdir() , Stdio.recursive_rm()


Method mkdir

int mkdir(string dirname, void|int mode)

Description

Create a directory.

If mode is specified, it's will be used for the new directory after being &'ed with the current umask (on OS'es that support this).

Returns

Returns 0 (zero) on failure, 1 otherwise.

See also

rm() , cd() , Stdio.mkdirhier()


Method get_dir

array(string) get_dir(string dirname)

Description

Returns an array of all filenames in the directory dirname , or 0 (zero) if the directory does not exist.

See also

mkdir() , cd()


Method cd

int cd(string s)

Description

Change the current directory for the whole Pike process.

Returns

Returns 1 for success, 0 (zero) otherwise.

See also

getcwd()


Method getcwd

string getcwd()

Description

Returns the current working directory.

See also

cd()


Method exece

int exece(string file, array(string) args)
int exece(string file, array(string) args, mapping(string:string) env)

Description

This function transforms the Pike process into a process running the program specified in the argument file with the arguments args .

If the mapping env is present, it will completely replace all environment variables before the new program is executed.

Returns

This function only returns if something went wrong during exece(2), and in that case it returns 0 (zero).

Note

The Pike driver _dies_ when this function is called. You must either use fork() or Process.create_process() if you wish to execute a program and still run the Pike runtime.

This function is not available on all platforms.

See also

Process.create_process() , fork() , Stdio.File->pipe()


Method mv

int mv(string from, string to)

Description

Rename or move a file or directory.

If the destination already exists, it will be replaced. Replacement often only works if to is of the same type as from , i.e. a file can only be replaced by another file and so on. Also, a directory will commonly be replaced only if it's empty.

On some OSs this function can't move directories, only rename them.

Returns

Returns 0 (zero) on failure, 1 otherwise. Call errno() to get more error info on failure.

See also

rm()


Method strerror

string strerror(int errno)

Description

This function returns a description of an error code. The error code is usually obtained from eg Stdio.File->errno() .

Note

On some platforms the string returned can be somewhat nondescriptive.


Method errno

int errno()

Description

This function returns the system error from the last file operation.

Note

Note that you should normally use Stdio.File->errno() instead.

See also

Stdio.File->errno() , strerror()


Method sprintf

string sprintf(string format, mixed ... args)

Description

Print formated output to string.

The format string is a string containing a description of how to output the data in args . This string should generally speaking have one %<modifiers><operator> format specifier (examples: %s, %0d, %-=20s) for each of the arguments.

The following modifiers are supported:

'0'

Zero pad numbers (implies right justification).

'!'

Toggle truncation.

' '

Pad positive integers with a space.

'+'

Pad positive integers with a plus sign.

'-'

Left adjust within field size (default is right).

'|'

Centered within field size.

'='

Column mode if strings are greater than field size.

'/'

Rough line break (break at exactly field size instead of between words).

'#'

Table mode, print a list of '\n' separated word (top-to-bottom order).

'$'

Inverse table mode (left-to-right order).

'n'

(Where n is a number or *) field size specifier.

'.n'

Precision specifier.

':n'

Field size precision specifier.

';n'

Column width specifier.

'*'

If n is a * then next argument is used for precision/field size.

"'"

Set a pad string. ' cannot be a part of the pad string (yet).

'~'

Get pad string from argument list.

'<'

Use same argument again.

'^'

Repeat this on every line produced.

'@'

Repeat this format for each element in the argument array.

'>'

Put the string at the bottom end of column instead of top.

'_'

Set width to the length of data.

'[n]'

Select argument number n. Use * to use the next argument as selector.


The following operators are supported:

'%'

Percent.

'b'

Signed binary integer.

'd'

Signed decimal integer.

'u'

Unsigned decimal integer.

'o'

Signed octal integer.

'x'

Lowercase signed hexadecimal integer.

'X'

Uppercase signed hexadecimal integer.

'c'

Character. If a fieldsize has been specified this will output the low-order bytes of the integer in network (big endian) byte order. To get little endian byte order, negate the field size.

'f'

Float. (Locale dependent formatting.)

'g'

Heuristically chosen representation of float. (Locale dependent formatting.)

'G'

Like %g, but uses uppercase E for exponent.

'e'

Exponential notation float. (Locale dependent output.)

'E'

Like %e, but uses uppercase E for exponent.

'F'

Binary IEEE representation of float (%4F gives single precision, %8F gives double precision.)

's'

String.

'O'

Any value, debug style. Do not rely on the exact formatting; how the result looks can vary depending on locale, phase of the moon or anything else the _sprintf method implementor wanted for debugging.

'n'

No operation (ignore the argument).

't'

Type of the argument.

'{'

Perform the enclosed format for every element of the argument array.

'}'

Most modifiers and operators are combinable in any fashion, but some combinations may render strange results.

If an argument is an object that implements lfun::_sprintf() , that callback will be called with the operator as the first argument, and the current modifiers as the second. The callback is expected to return a string.

Example

Pike v7.4 release 13 running Hilfe v3.5 (Incremental Pike Frontend) > sprintf("The unicode character %c has character code %04X.", 'A', 'A'); (1) Result: "The unicode character A has character code 0041." > sprintf("#%@02X is the HTML code for purple.", Image.Color.purple->rgb()); (2) Result: "#A020F0 is the HTML code for purple." > int n=4711; > sprintf("%d = hexadecimal %x = octal %o = %b binary", n, n, n, n); (3) Result: "4711 = hexadecimal 1267 = octal 11147 = 1001001100111 binary"

Note

sprintf style formatting is applied by many formatting functions, such write() and werror .

Example

> write(#"Formatting examples: Left adjusted [%-10d] Centered [%|10d] Right adjusted [%10d] Zero padded [%010d] ", n, n, n, n); Formatting examples: Left adjusted [4711 ] Centered [ 4711 ] Right adjusted [ 4711] Zero padded [0000004711] (5) Result: 142 int screen_width=70; > write("%-=*s\n", screen_width, >> "This will wordwrap the specified string within the "+ >> "specified field size, this is useful say, if you let "+ >> "users specify their screen size, then the room "+ >> "descriptions will automagically word-wrap as appropriate.\n"+ >> "slosh-n's will of course force a new-line when needed.\n"); This will wordwrap the specified string within the specified field size, this is useful say, if you let users specify their screen size, then the room descriptions will automagically word-wrap as appropriate. slosh-n's will of course force a new-line when needed. (6) Result: 355 > write("%-=*s %-=*s\n", screen_width/2, >> "Two columns next to each other (any number of columns will "+ >> "of course work) independantly word-wrapped, can be useful.", >> screen_width/2-1, >> "The - is to specify justification, this is in addherence "+ >> "to std sprintf which defaults to right-justification, "+ >> "this version also supports centre and right justification."); Two columns next to each other (any The - is to specify justification, number of columns will of course this is in addherence to std work) independantly word-wrapped, sprintf which defaults to can be useful. right-justification, this version also supports centre and right justification. (7) Result: 426 > write("%-$*s\n", screen_width, >> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+ >> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+ >> "be forced\nby specifying a\npresision.\nThe most obvious\n"+ >> "use is for\nformatted\nls output."); Given a list of slosh-n separated 'words', this option creates a table out of them the number of columns be forced by specifying a presision. The most obvious use is for formatted ls output. (8) Result: 312 > write("%-#*s\n", screen_width, >> "Given a\nlist of\nslosh-n\nseparated\n'words',\nthis option\n"+ >> "creates a\ntable out\nof them\nthe number of\ncolumns\n"+ >> "be forced\nby specifying a\npresision.\nThe most obvious\n"+ >> "use is for\nformatted\nls output."); Given a creates a by specifying a list of table out presision. slosh-n of them The most obvious separated the number of use is for 'words', columns formatted this option be forced ls output. (9) Result: 312 > sample = ([ "align":"left", "valign":"middle" ]); (10) Result: ([ /* 2 elements */ "align":"left", "valign":"middle" ]) > write("<td%{ %s='%s'%}>\n", (array)sample); <td valign='middle' align='left'> (11) Result: 34 > write("Of course all the simple printf options "+ >> "are supported:\n %s: %d %x %o %c\n", >> "65 as decimal, hex, octal and a char", >> 65, 65, 65, 65); Of course all the simple printf options are supported: 65 as decimal, hex, octal and a char: 65 41 101 A (12) Result: 106 > write("%[0]d, %[0]x, %[0]X, %[0]o, %[0]c\n", 75); 75, 4b, 4B, 113, K (13) Result: 19 > write("%|*s\n",screen_width, "THE END"); THE END (14) Result: 71

See also

lfun::_sprintf()


Method getgrgid

array(int|string|array(string)) getgrgid(int gid)

Description

Get the group entry for the group with the id gid using the systemfunction getgrid(3).

Parameter gid

The id of the group

Returns

An array with the information about the group

Array
string 0

Group name

string 1

Group password (encrypted)

int 2

ID of the group

array 3..

Array with UIDs of group members


See also

getgrent() getgrnam()


Method getgrnam

array(int|string|array(string)) getgrnam(string str)

Description

Get the group entry for the group with the name str using the systemfunction getgrnam(3).

Parameter str

The name of the group

Returns

An array with the information about the group

Array
string 0

Group name

string 1

Group password (encrypted)

int 2

ID of the group

array 3..

Array with UIDs of group members


See also

getgrent() getgrgid()


Method getpwnam

array(int|string) getpwnam(string str)

Description

Get the user entry for login str using the systemfunction getpwnam(3).

Parameter str

The login name of the user whos userrecord is requested.

Returns

An array with the information about the user

Array
string 0

Users username (loginname)

string 1

User password (encrypted)

int 2

Users ID

int 3

Users primary group ID

string 4

Users real name an possibly some other info

string 5

Users home directory

string 6

Users shell


See also

getpwuid() getpwent()


Method getpwuid

array(int|string) getpwuid(int uid)

Description

Get the user entry for UID uid using the systemfunction getpwuid(3).

Parameter uid

The uid of the user whos userrecord is requested.

Returns

An array with the information about the user

Array
string 0

Users username (loginname)

string 1

User password (encrypted)

int 2

Users ID

int 3

Users primary group ID

string 4

Users real name an possibly some other info

string 5

Users home directory

string 6

Users shell


See also

getpwnam() getpwent()


Method get_all_users

array(array(int|string)) get_all_users()

Description

Returns an array with all users in the system.

Returns

An array with arrays of userinfo as in getpwent .

See also

getpwent() getpwnam() getpwuid()


Method get_all_groups

array(array(int|string|array(string))) get_all_groups()

Description

Returns an array of arrays with all groups in the system groups source. Each element in the returned array has the same structure as in getgrent function.

Note

The groups source is system dependant. Refer to your system manuals for information about how to set the source.

Returns
Array
array(int|string|array(string)) 0..

Array with info about the group


See also

getgrent()


Method get_groups_for_user

array(int) get_groups_for_user(int|string user)

Description

Gets all groups which a given user is a member of.

Parameter user

UID or loginname of the user

Returns
Array
array 0..

Information about all the users groups


See also

get_all_groups() getgrgid() getgrnam() getpwuid() getpwnam()


Method equal

int equal(mixed a, mixed b)

Description

This function checks if the values a and b are equal.

For all types but arrays, multisets and mappings, this operation is the same as doing a  == b . For arrays, mappings and multisets however, their contents are checked recursively, and if all their contents are the same and in the same place, they are considered equal.

See also

copy_value()


Method aggregate

array aggregate(mixed ... elements)

Description

Construct an array with the arguments as indices.

This function could be written in Pike as:

array aggregate(mixed ... elems) { return elems; }

Note

Arrays are dynamically allocated there is no need to declare them like int a[10]=allocate(10); (and it isn't possible either) like in C, just array(int) a=allocate(10); will do.

See also

sizeof() , arrayp() , allocate()


Method hash_7_4

int hash_7_4(string s)
int hash_7_4(string s, int max)

Description

Return an integer derived from the string s . The same string will always hash to the same value, also between processes.

If max is given, the result will be >= 0 and < max , otherwise the result will be >= 0 and <= 0x7fffffff.

Note

This function is provided for backward compatibility reasons.

This function is byte-order dependant for wide strings.

See also

hash() , hash_7_0()


Method hash_7_0

int hash_7_0(string s)
int hash_7_0(string s, int max)

Description

Return an integer derived from the string s . The same string always hashes to the same value, also between processes.

If max is given, the result will be >= 0 and < max , otherwise the result will be >= 0 and <= 0x7fffffff.

Note

This function is provided for backward compatibility reasons.

This function is not NUL-safe, and is byte-order dependant.

See also

hash() , hash_7_4()


Method hash

int hash(string s)
int hash(string s, int max)

Description

Return an integer derived from the string s . The same string always hashes to the same value, also between processes, architectures, and Pike versions (see compatibility notes below, though).

If max is given, the result will be >= 0 and < max , otherwise the result will be >= 0 and <= 0x7fffffff.

Note

The hash algorithm was changed in Pike 7.5. If you want a hash that is compatible with Pike 7.4 and earlier, use hash_7_4() . The difference only affects wide strings.

The hash algorithm was also changed in Pike 7.1. If you want a hash that is compatible with Pike 7.0 and earlier, use hash_7_0() .

See also

hash_7_0() , hash_7_4() , hash_value


Method hash_value

int hash_value(mixed value)

Description

Return a hash value for the argument. It's an integer in the native integer range.

The hash will be the same for the same value in the running process only (the memory address is typically used as the basis for the hash value).

If the value is an object with an lfun::__hash , that function is called and its result is returned.

Note

This is the hashing method used by mappings.

See also

hash


Method copy_value

mixed copy_value(mixed value)

Description

Copy a value recursively.

If the result value is changed destructively (only possible for multisets, arrays and mappings) the copied value will not be changed.

The resulting value will always be equal to the copied (as tested with the function equal() ), but they may not the the same value (as tested with `==() ).

See also

equal()


Method lower_case

string lower_case(string s)
int lower_case(int c)

Description

Convert a string or character to lower case.

Returns

Returns a copy of the string s with all upper case characters converted to lower case, or the character c converted to lower case.

Note

Assumes the string or character to be coded according to ISO-10646 (aka Unicode). If they are not, Locale.Charset.decoder can do the initial conversion for you.

Note

Prior to Pike 7.5 this function only accepted strings.

See also

upper_case() , Locale.Charset.decoder


Method upper_case

string upper_case(string s)
int upper_case(int c)

Description

Convert a string or character to upper case.

Returns

Returns a copy of the string s with all lower case characters converted to upper case, or the character c converted to upper case.

Note

Assumes the string or character to be coded according to ISO-10646 (aka Unicode). If they are not, Locale.Charset.decoder can do the initial conversion for you.

Note

Prior to Pike 7.5 this function only accepted strings.

See also

lower_case() , Locale.Charset.decoder


Method random_string

string random_string(int len)

Description

Returns a string of random characters 0-255 with the length len .


Method random_seed

void random_seed(int seed)

Description

This function sets the initial value for the random generator.

See also

random()


Method query_num_arg

int query_num_arg()

Description

Returns the number of arguments given when the previous function was called.

This is useful for functions that take a variable number of arguments.

See also

call_function()


Method search

int search(string haystack, string|int needle, int|void start)
int search(array haystack, mixed needle, int|void start)
mixed search(mapping haystack, mixed needle, mixed|void start)
mixed search(object haystack, mixed needle, mixed|void start)

Description

Search for needle in haystack . Return the position of needle in haystack or -1 if not found.

If the optional argument start is present search is started at this position.

haystack can have any of the following types:
string

When haystack is a string needle must be a string or an int, and the first occurrence of the string or int is returned.

array

When haystack is an array, needle is compared only to one value at a time in haystack .

mapping

When haystack is a mapping, search() tries to find the index connected to the data needle . That is, it tries to lookup the mapping backwards. If needle isn't present in the mapping, zero is returned, and zero_type() will return 1 for this zero.

object

When haystack is an object implementing lfun::_search() , the result of calling lfun::_search() with needle will be returned.

If haystack is an object that doesn't implement lfun::_search() it is assumed to be an Iterator , and implement Iterator()->index() , Iterator()->value() , and Iterator()->next() . search() will then start comparing elements with `==() until a match with needle is found. If needle is found haystack will be advanced to the element, and the iterator index will be returned. If needle is not found, haystack will be advanced to the end (and will thus evaluate to false), and a zero with zero_type 1 will be returned.


Note

If start is supplied to an iterator object without an lfun::_search() , haystack will need to implement Iterator()->set_index() .

See also

indices() , values() , zero_type()


Method has_prefix

int has_prefix(string s, string prefix)

Description

Returns 1 if the string s starts with prefix , returns 0 (zero) otherwise.


Method has_suffix

int has_suffix(string s, string suffix)

Description

Returns 1 if the string s ends with suffix , returns 0 (zero) otherwise.


Method has_index

int has_index(string haystack, int index)
int has_index(array haystack, int index)
int has_index(mapping|multiset|object|program haystack, mixed index)

Description

Search for index in haystack .

Returns

Returns 1 if index is in the index domain of haystack , or 0 (zero) if not found.

This function is equivalent to (but sometimes faster than):

search(indices(haystack), index) != -1

Note

A negative index in strings and arrays as recognized by the index operators `[]() and `[]=() is not considered a proper index by has_index()

See also

has_value() , indices() , search() , values() , zero_type()


Method has_value

int has_value(string haystack, string value)
int has_value(string haystack, int value)
int has_value(array|mapping|object|program haystack, mixed value)

Description

Search for value in haystack .

Returns

Returns 1 if value is in the value domain of haystack , or 0 (zero) if not found.

This function is in all cases except when both arguments are strings equivalent to (but sometimes faster than):

search(values(haystack ), value ) != -1

If both arguments are strings, has_value() is equivalent to:

search(haystack , value ) != -1

See also

has_index() , indices() , search() , values() , zero_type()


Method add_constant

void add_constant(string name, mixed value)
void add_constant(string name)

Description

Add a new predefined constant.

This function is often used to add builtin functions. All programs compiled after the add_constant() function has been called can access value by the name name .

If there is a constant called name already, it will be replaced by by the new definition. This will not affect already compiled programs.

Calling add_constant() without a value will remove that name from the list of constants. As with replacing, this will not affect already compiled programs.

See also

all_constants()


Method combine_path
Method combine_path_unix
Method combine_path_nt
Method combine_path_amigaos

string combine_path(string absolute, string ... relative)
string combine_path_unix(string absolute, string ... relative)
string combine_path_nt(string absolute, string ... relative)
string combine_path_amigaos(string absolute, string ... relative)

Description

Concatenate a relative path to an absolute path and remove any "//", "/.." or "/." to produce a straightforward absolute path as result.

combine_path_nt() concatenates according to NT-filesystem conventions, while combine_path_unix() concatenates according to UNIX-style. combine_path_amigaos() concatenates according to AmigaOS filesystem conventions.

combine_path() is equvivalent to combine_path_unix() on UNIX-like operating systems, and equivalent to combine_path_nt() on NT-like operating systems, and equivalent to combine_path_amigaos() on AmigaOS-like operating systems.

See also

getcwd() , Stdio.append_path()


Method zero_type

int zero_type(mixed a)

Description

Return the type of zero.

There are many types of zeros out there, or at least there are two. One is returned by normal functions, and one returned by mapping lookups and find_call_out() when what you looked for wasn't there. The only way to separate these two kinds of zeros is zero_type() .

Returns

When doing a find_call_out() or mapping lookup, zero_type() on this value will return 1 if there was no such thing present in the mapping, or if no such call_out could be found.

If the argument to zero_type() is a destructed object or a function in a destructed object, 2 will be returned.

In all other cases zero_type() will return 0 (zero).

See also

find_call_out()


Method string_to_unicode

string string_to_unicode(string s)

Description

Converts a string into an UTF16 compliant byte-stream.

Note

Throws an error if characters not legal in an UTF16 stream are encountered. Valid characters are in the range 0x00000 - 0x10ffff, except for characters 0xfffe and 0xffff.

Characters in range 0x010000 - 0x10ffff are encoded using surrogates.

See also

Locale.Charset.decoder() , string_to_utf8() , unicode_to_string() , utf8_to_string()


Method unicode_to_string

string unicode_to_string(string s)

Description

Converts an UTF16 byte-stream into a string.

Note

This function did not decode surrogates in Pike 7.2 and earlier.

See also

Locale.Charset.decoder() , string_to_unicode() , string_to_utf8() , utf8_to_string()


Method string_to_utf8

string string_to_utf8(string s)
string string_to_utf8(string s, int extended)

Description

Converts a string into an UTF8 compliant byte-stream.

Note

Throws an error if characters not valid in an UTF8 stream are encountered. Valid characters are in the range 0x00000000 - 0x7fffffff.

If extended is 1, characters in the range 0x80000000-0xfffffffff will also be accepted, and encoded using a non-standard UTF8 extension.

See also

Locale.Charset.encoder() , string_to_unicode() , unicode_to_string() , utf8_to_string()


Method utf8_to_string

string utf8_to_string(string s)
string utf8_to_string(string s, int extended)

Description

Converts an UTF8 byte-stream into a string.

Note

Throws an error if the stream is not a legal UFT8 byte-stream.

Accepts and decodes the extension used by string_to_utf8() , if extended is 1.

See also

Locale.Charset.encoder() , string_to_unicode() , string_to_utf8() , unicode_to_string()


Method __parse_pike_type

string __parse_pike_type(string t)


Method all_constants

mapping(string:mixed) all_constants()

Description

Returns a mapping containing all global constants, indexed on the name of the constant, and with the value of the constant as value.

See also

add_constant()


Method allocate

array allocate(int size)
array allocate(int size, mixed init)

Description

Allocate an array of size elements. If init is specified then each element is initialized by copying that value recursively.

See also

sizeof() , aggregate() , arrayp()


Method this_object

object this_object(void|int level)

Description

Returns the object we are currently evaluating in.

level might be used to access the object of a surrounding class: The object at level 0 is the current object, the object at level 1 is the one belonging to the class that surrounds the class that the object comes from, and so on.

Note

As opposed to a qualified this reference such as global::this, this function doesn't always access the objects belonging to the lexically surrounding classes. If the class containing the call has been inherited then the objects surrounding the inheriting class are accessed.


Method throw

void throw(mixed value)

Description

Throw value to a waiting catch .

If no catch is waiting the global error handling will send the value to master()->handle_error() .

If you throw an array with where the first index contains an error message and the second index is a backtrace, (the output from backtrace() ) then it will be treated exactly like a real error by overlying functions.

See also

catch


Method exit

void exit(int returncode, void|string fmt, mixed ... extra)

Description

Exit the whole Pike program with the given returncode .

Using exit() with any other value than 0 (zero) indicates that something went wrong during execution. See your system manuals for more information about return codes.

The arguments after the returncode will be used for a call to werror to output a message on stderr.

See also

_exit()


Method _exit

void _exit(int returncode)

Description

This function does the same as exit , but doesn't bother to clean up the Pike interpreter before exiting. This means that no destructors will be called, caches will not be flushed, file locks might not be released, and databases might not be closed properly.

Use with extreme caution.

See also

exit()


Method time

int time()
int time(int(1..1) one)
float time(int(2..) t)

Description

This function returns the number of seconds since 00:00:00 UTC, 1 Jan 1970.

The second syntax does not query the system for the current time. Instead the latest done by the pike process is returned again. That's slightly faster but can be wildly inaccurate. Pike queries the time internally when a thread has waited for something, typically in sleep or in a backend (see Pike.Backend ).

The third syntax can be used to measure time more preciely than one second. It return how many seconds has passed since t . The precision of this function varies from system to system.

See also

ctime() , localtime() , mktime() , gmtime() , System.gettimeofday , gethrtime


Method crypt

string crypt(string password)
int(0..1) crypt(string typed_password, string crypted_password)

Description

This function crypts and verifies a short string (only the first 8 characters are significant).

The first syntax crypts the string password into something that is hopefully hard to decrypt.

The second syntax is used to verify typed_password against crypted_password , and returns 1 if they match, and 0 (zero) otherwise.


Method destruct

void destruct(void|object o)

Description

Mark an object as destructed.

Calls o->destroy(), and then clears all variables in the object. If no argument is given, the current object is destructed.

All pointers and function pointers to this object will become zero. The destructed object will be freed from memory as soon as possible.


Method indices

array indices(string|array|mapping|multiset|object x)

Description

Return an array of all valid indices for the value x .

For strings and arrays this is simply an array of ascending numbers.

For mappings and multisets, the array may contain any value.

For objects which define lfun::_indices() that return value will be used.

For other objects an array with all non-static symbols will be returned.

See also

values()


Method values

array values(string|array|mapping|multiset|object x)

Description

Return an array of all possible values from indexing the value x .

For strings an array of int with the ISO10646 codes of the characters in the string is returned.

For a multiset an array filled with ones (1) is returned.

For arrays a single-level copy of x is returned.

For mappings the array may contain any value.

For objects which define lfun::_values() that return value will be used.

For other objects an array with the values of all non-static symbols will be returned.

See also

indices()


Method next_object

object next_object(object o)
object next_object()

Description

Returns the next object from the list of all objects.

All objects are stored in a linked list.

Returns

If no arguments have been given next_object() will return the first object from the list.

If o has been specified the object after o on the list will be returned.

Note

This function is not recomended to use.

See also

destruct()


Method object_program

program|function object_program(mixed o)

Description

Return the program from which o was instantiated. If the object was instantiated from a class using parent references the generating function will be returned.

If o is not an object or has been destructed 0 (zero) will be returned.


Method reverse

string reverse(string s)
array reverse(array a)
int reverse(int i)

Description

Reverses a string, array or int.

This function reverses a string, char by char, an array, value by value or an int, bit by bit and returns the result. It's not destructive on the input value.

Reversing strings can be particularly useful for parsing difficult syntaxes which require scanning backwards.

See also

sscanf()


Method replace

string replace(string s, string from, string to)
string replace(string s, array(string) from, array(string) to)
string replace(string s, mapping(string:string) replacements)
array replace(array a, mixed from, mixed to)
mapping replace(mapping a, mixed from, mixed to)

Description

Generic replace function.

This function can do several kinds replacement operations, the different syntaxes do different things as follows:

If all the arguments are strings, a copy of s with every occurrence of from replaced with to will be returned. Special case: to will be inserted between every character in s if from is the empty string.

If the first argument is a string, and the others array(string), a string with every occurrance of from [i] in s replaced with to [i] will be returned. Instead of the arrays from and to a mapping equvivalent to mkmapping (from , to ) can be used.

If the first argument is an array or mapping, the values of a which are `==() with from will be replaced with to destructively. a will then be returned.

Note

Note that replace() on arrays and mappings is a destructive operation.


Method compile

program compile(string source, object|void handler, int|void major, int|void minor, program|void target, object|void placeholder)

Description

Compile a string to a program.

This function takes a piece of Pike code as a string and compiles it into a clonable program.

The optional argument handler is used to specify an alternative error handler. If it is not specified the current master object will be used.

The optional arguments major and minor are used to tell the compiler to attempt to be compatible with Pike major .minor .

Note

Note that source must contain the complete source for a program. It is not possible to compile a single expression or statement.

Also note that compile() does not preprocess the program. To preprocess the program you can use compile_string() or call the preprocessor manually by calling cpp() .

See also

compile_string() , compile_file() , cpp() , master()


Method set_weak_flag

array|mapping|multiset set_weak_flag(array|mapping|multiset m, int state)

Description

Set the value m to use weak or normal references in its indices and/or values (whatever is applicable). state is a bitfield built by using | between the following flags:

Pike.WEAK_INDICES

Use weak references for indices. Only applicable for multisets and mappings.

Pike.WEAK_VALUES

Use weak references for values. Only applicable for arrays and mappings.

Pike.WEAK

Shorthand for Pike.WEAK_INDICES|Pike.WEAK_VALUES.


If a flag is absent, the corresponding field will use normal references. state can also be 1 as a compatibility measure; it's treated like Pike.WEAK .

Returns

m will be returned.


Method objectp

int objectp(mixed arg)

Description

Returns 1 if arg is an object, 0 (zero) otherwise.

See also

mappingp() , programp() , arrayp() , stringp() , functionp() , multisetp() , floatp() , intp()


Method functionp

int functionp(mixed arg)

Description

Returns 1 if arg is a function, 0 (zero) otherwise.

See also

mappingp() , programp() , arrayp() , stringp() , objectp() , multisetp() , floatp() , intp()


Method callablep

int callablep(mixed arg)

Description

Returns 1 if arg is a callable, 0 (zero) otherwise.

See also

mappingp() , programp() , arrayp() , stringp() , objectp() , multisetp() , floatp() , intp()


Method sleep

void sleep(int|float s, void|int abort_on_signal)

Description

This function makes the program stop for s seconds.

Only signal handlers can interrupt the sleep, and only when abort_on_signal is set. If more than one thread is running the signal must be sent to the sleeping thread. Other callbacks are not called during sleep.

If s is zero then this thread will yield to other threads but not sleep otherwise. Note that Pike yields internally at regular intervals so it's normally not necessary to do this.

See also

signal() , delay()


Method delay

void delay(int|float s)

Description

This function makes the program stop for s seconds.

Only signal handlers can interrupt the sleep. Other callbacks are not called during delay. Beware that this function uses busy-waiting to achieve the highest possible accuracy.

See also

signal() , sleep()


Method gc

int gc()

Description

Force garbage collection.

This function checks all the memory for cyclic structures such as arrays containing themselves and frees them if appropriate. It also frees up destructed objects and things with only weak references.

Normally there is no need to call this function since Pike will call it by itself every now and then. (Pike will try to predict when 20% of all arrays/object/programs in memory is 'garbage' and call this routine then.)

Returns

The amount of garbage is returned. This is the number of arrays, mappings, multisets, objects and programs that had no nonweak external references during the garbage collection. It's normally the same as the number of freed things, but there might be some difference since destroy() functions are called during freeing, which can cause more things to be freed or allocated.

See also

Pike.gc_parameters , Debug.gc_status


Method programp

int programp(mixed arg)

Description

Returns 1 if arg is a program, 0 (zero) otherwise.

See also

mappingp() , intp() , arrayp() , stringp() , objectp() , multisetp() , floatp() , functionp()


Method intp

int intp(mixed arg)

Description

Returns 1 if arg is an int, 0 (zero) otherwise.

See also

mappingp() , programp() , arrayp() , stringp() , objectp() , multisetp() , floatp() , functionp()


Method mappingp

int mappingp(mixed arg)

Description

Returns 1 if arg is a mapping, 0 (zero) otherwise.

See also

intp() , programp() , arrayp() , stringp() , objectp() , multisetp() , floatp() , functionp()


Method arrayp

int arrayp(mixed arg)

Description

Returns 1 if arg is an array, 0 (zero) otherwise.

See also

intp() , programp() , mappingp() , stringp() , objectp() , multisetp() , floatp() , functionp()


Method multisetp

int multisetp(mixed arg)

Description

Returns 1 if arg is a multiset, 0 (zero) otherwise.

See also

intp() , programp() , arrayp() , stringp() , objectp() , mappingp() , floatp() , functionp()


Method stringp

int stringp(mixed arg)

Description

Returns 1 if arg is a string, 0 (zero) otherwise.

See also

intp() , programp() , arrayp() , multisetp() , objectp() , mappingp() , floatp() , functionp()


Method floatp

int floatp(mixed arg)

Description

Returns 1 if arg is a float, 0 (zero) otherwise.

See also

intp() , programp() , arrayp() , multisetp() , objectp() , mappingp() , stringp() , functionp()


Method sort

array sort(array(mixed) index, array(mixed) ... data)

Description

Sort arrays destructively.

This function sorts the array index destructively. That means that the array itself is changed and returned, no copy is created.

If extra arguments are given, they are supposed to be arrays of the same size as index . Each of these arrays will be modified in the same way as index . I.e. if index 3 is moved to position 0 in index index 3 will be moved to position 0 in all the other arrays as well.

The sort order is as follows:

  • Integers and floats are sorted in ascending order.

  • Strings are sorted primarily on the first characters that are different, and secondarily with shorter strings before longer. Different characters are sorted in ascending order on the character value. Thus the sort order is not locale dependent.

  • Arrays are sorted recursively on the first element. Empty arrays are sorted before nonempty ones.

  • Multisets are sorted recursively on the first index. Empty multisets are sorted before nonempty ones.

  • Objects are sorted in ascending order according to `<() , `>() and `==() .

  • Other types aren't reordered.

  • Different types are sorted in this order: Arrays, mappings, multisets, objects, functions, programs, strings, types, integers and floats. Note however that objects can control their ordering wrt other types with `< , `> and `== , so this ordering of types only applies to objects without those functions.

Returns

The first argument is returned.

Note

The sort is stable, i.e. elements that are compare-wise equal aren't reordered.

See also

Array.sort_array , reverse()


Method rows

array rows(mixed data, array index)

Description

Select a set of rows from an array.

This function is en optimized equivalent to:

map(index , lambda(mixed x) { return data [x]; })

That is, it indices data on every index in the array index and returns an array with the results.

See also

column()


Method gmtime

mapping(string:int) gmtime(int timestamp)

Description

Convert seconds since 00:00:00 UTC, Jan 1, 1970 into components.

This function works like localtime() but the result is not adjusted for the local time zone.

See also

localtime() , time() , ctime() , mktime()


Method localtime

mapping(string:int) localtime(int timestamp)

Description

Convert seconds since 00:00:00 UTC, 1 Jan 1970 into components.

Returns

This function returns a mapping with the following components:

"sec" : int(0..60)

Seconds over the minute.

"min" : int(0..59)

Minutes over the hour.

"hour" : int(0..23)

Hour of the day.

"mday" : int(1..31)

Day of the month.

"mon" : int(0..11)

Month of the year.

"year" : int(0..)

Year since 1900.

"wday" : int(0..6)

Day of week (0 = Sunday).

"yday" : int(0..365)

Day of the year.

"isdst" : int(0..1)

Is daylight savings time.

"timezone" : int

Offset from UTC, including daylight savings time adjustment.


An error is thrown if the localtime(2) call failed on the system. It's platform dependent what time ranges that function can handle, e.g. Windows doesn't handle a negative timestamp .

Note

Prior to Pike 7.5 the field "timezone" was sometimes not present, and was sometimes not adjusted for daylight savings time.

See also

Calendar , gmtime() , time() , ctime() , mktime()


Method mktime

int mktime(mapping(string:int) tm)
int mktime(int sec, int min, int hour, int mday, int mon, int year, int|void isdst, int|void tz)

Description

This function converts information about date and time into an integer which contains the number of seconds since 00:00:00 UTC, Jan 1, 1970.

You can either call this function with a mapping containing the following elements:

"sec" : int(0..60)

Seconds over the minute.

"min" : int(0..59)

Minutes over the hour.

"hour" : int(0..23)

Hour of the day.

"mday" : int(1..31)

Day of the month.

"mon" : int(0..11)

Month of the year.

"year" : int(0..)

Year since 1900.

"isdst" : int(0..1)

Is daylight savings time.

"timezone" : int

The timezone offset from UTC in seconds. If left out, the time will be calculated in the local timezone.


Or you can just send them all on one line as the second syntax suggests.

Note

On some operating systems (notably AIX), dates before 00:00:00 UTC, Jan 1, 1970 are not supported.

On most systems, the supported range of dates are Dec 13, 1901 20:45:52 UTC through Jan 19, 2038 03:14:07 UTC (inclusive).

See also

time() , ctime() , localtime() , gmtime()


Method glob

int(0..1) glob(string glob, string str)
array(string) glob(string glob, array(string) arr)

Description

Match strings against globs.

In a glob string a question sign matches any character and an asterisk matches any string.

When the second argument is a string and str matches the glob glob 1 will be returned, 0 (zero) otherwise.

If the second array is an array and array containing the strings in arr that match glob will be returned.

See also

sscanf() , Regexp


Method _next

mixed _next(mixed x)

Description

Find the next object/array/mapping/multiset/program or string.

All objects, arrays, mappings, multisets, programs and strings are stored in linked lists inside Pike. This function returns the next item on the corresponding list. It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.

See also

next_object() , _prev()


Method _prev

mixed _prev(mixed x)

Description

Find the previous object/array/mapping/multiset or program.

All objects, arrays, mappings, multisets and programs are stored in linked lists inside Pike. This function returns the previous item on the corresponding list. It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.

Note

Unlike _next() this function does not work on strings.

See also

next_object() , _next()


Method _refs

int _refs(string|array|mapping|multiset|function|object|program o)

Description

Return the number of references o has.

It is mainly meant for debugging the Pike runtime, but can also be used to control memory usage.

Note

Note that the number of references will always be at least one since the value is located on the stack when this function is executed.

See also

_next() , _prev()


Method _typeof

type(mixed) _typeof(mixed x)

Description

Return the runtime type of x .

See also

typeof()


Method replace_master

void replace_master(object o)

Description

Replace the master object with o .

This will let you control many aspects of how Pike works, but beware that master.pike may be required to fill certain functions, so it is usually a good idea to have your master inherit the original master and only re-define certain functions.

FIXME: Tell how to inherit the master.

See also

master()


Method master

object master()

Description

Return the current master object.

See also

replace_master()


Method gethrvtime

int gethrvtime(void|int nsec)

Description

Return the CPU time that has been consumed by this process or thread. -1 is returned if the system couldn't determine it. The time is normally returned in microseconds, but if the optional argument nsec is nonzero it's returned in nanoseconds.

The CPU time includes both user and system time, i.e. it's approximately the same thing you would get by adding together the "utime" and "stime" fields returned by System.getrusage (but perhaps with better accuracy). It's however system dependent whether or not it's the time consumed in all threads or in the current one only; System.CPU_TIME_IS_THREAD_LOCAL tells which.

Note

The actual accuracy on many systems is significantly less than milliseconds or nanoseconds.

Note

The garbage collector might run automatically at any time. The time it takes is not included in the figure returned by this function, so that normal measurements aren't randomly clobbered by it. Explicit calls to gc are still included, though.

Note

The special function gauge is implemented with this function.

See also

System.CPU_TIME_IS_THREAD_LOCAL , gauge() , System.getrusage() , gethrtime()


Method gethrtime

int gethrtime(void|int nsec)

Description

Return the real time since some arbitrary event in the past. The time is normally returned in microseconds, but if the optional argument nsec is nonzero it's returned in nanoseconds.

Note

The actual accuracy on many systems is significantly less than milliseconds or nanoseconds.

See also

time() , System.gettimeofday() , gethrvtime()


Method get_profiling_info

array(int|mapping(string:array(int))) get_profiling_info(program prog)

Description

Get profiling information.

Returns

Returns an array with two elements.

Array
int num_clones

The first element is the number of times the program prog has been instantiated.

mapping(string:array(int)) fun_prof_info

The second element is mapping from function name to an array with three elements.

Array
int num_calls

The first element is the number of times the function has been called.

int total_time

The second element is the total time (in milliseconds) spent executing this function, and any functions called from it.

int self_time

The third element is the time (in milliseconds) actually spent in this function so far.



Note

This function is only available if the runtime was compiled with the option --with-profiling.


Method object_variablep

int(0..1) object_variablep(object o, string var)

Description

Find out if an object identifier is a variable.

Returns

This function returns 1 if var exists as a non-static variable in o , and returns 0 (zero) otherwise.

See also

indices() , values()


Method map

mixed map(mixed arr, void|mixed fun, mixed ... extra)

Description

Applies fun to the elements in arr and collects the results.

arr is treated as a set of elements, as follows:

array
multiset
string

fun is applied in order to each element. The results are collected, also in order, to a value of the same type as arr , which is returned.

mapping

fun is applied to the values, and each result is assigned to the same index in a new mapping, which is returned.

program

The program is treated as a mapping containing the identifiers that are indexable from it and their values.

object

If there is a lfun::cast method in the object, it's called to try to cast the object to an array, a mapping, or a multiset, in that order, which is then handled as described above.

fun is applied in different ways depending on its type:

function

fun is called for each element. It gets the current element as the first argument and extra as the rest. The result of the call is collected.

object

fun is used as a function like above, i.e. the lfun::`() method in it is called.

multiset
mapping

fun is indexed with each element. The result of that is collected.

zero or left out

Each element that is callable is called with extra as arguments. The result of the calls are collected. Elements that aren't callable gets zero as result.

string

Each element is indexed with the given string. If the result of that is zero then a zero is collected, otherwise it's called with extra as arguments and the result of that call is collected.

This is typically used when arr is a collection of objects, and fun is the name of some function in them.

Note

The function is never destructive on arr .

See also

filter() , enumerate() , foreach()


Method filter

mixed filter(mixed arr, void|mixed fun, mixed ... extra)

Description

Filters the elements in arr through fun .

arr is treated as a set of elements to be filtered, as follows:

array
multiset
string

Each element is filtered with fun . The return value is of the same type as arr and it contains the elements that fun accepted. fun is applied in order to each element, and that order is retained between the kept elements.

If fun is an array, it should have the same length as arr . In this case, the elements in arr are kept where the corresponding positions in fun are nonzero. Otherwise fun is used as described below.

mapping

The values are filtered with fun , and the index/value pairs it accepts are kept in the returned mapping.

program

The program is treated as a mapping containing the identifiers that are indexable from it and their values.

object

If there is a lfun::cast method in the object, it's called to try to cast the object to an array, a mapping, or a multiset, in that order, which is then filtered as described above.

Unless something else is mentioned above, fun is used as filter like this:

function

fun is called for each element. It gets the current element as the first argument and extra as the rest. The element is kept if it returns true, otherwise it's filtered out.

object

The object is used as a function like above, i.e. the lfun::`() method in it is called.

multiset
mapping

fun is indexed with each element. The element is kept if the result is nonzero, otherwise it's filtered out.

zero or left out

Each element that is callable is called with extra as arguments. The element is kept if the result of the call is nonzero, otherwise it's filtered out. Elements that aren't callable are also filtered out.

string

Each element is indexed with the given string. If the result of that is zero then the element is filtered out, otherwise the result is called with extra as arguments. The element is kept if the return value is nonzero, otherwise it's filtered out.

This is typically used when arr is a collection of objects, and fun is the name of some predicate function in them.

Note

The function is never destructive on arr .

See also

map() , foreach()


Method enumerate

array(int) enumerate(int n)
array enumerate(int n, void|mixed step, void|mixed start, void|function operator)

Description

Create an array with an enumeration, useful for initializing arrays or as first argument to map() or foreach() .

The defaults are: step = 1, start = 0, operator = `+

See also

map() , foreach()



Method cpp

string cpp(string data, string|void current_file, int|string|void charset, object|void handler, void|int compat_major, void|int compat_minor, void|int warn_if_constant_throws)

Description

Run a string through the preprocessor.

Preprocesses the string data with Pike's builtin ANSI-C look-alike preprocessor. If the current_file argument has not been specified, it will default to "-". charset defaults to "ISO-10646".

See also

compile()


Method load_module

program load_module(string module_name)

Description

Load a binary module.

This function loads a module written in C or some other language into Pike. The module is initialized and any programs or constants defined will immediately be available.

When a module is loaded the C function pike_module_init() will be called to initialize it. When Pike exits pike_module_exit() will be called. These two functions must be available in the module.

Note

The current working directory is normally not searched for dynamic modules. Please use "./name.so" instead of just "name.so" to load modules from the current directory.


Method encode_value

string encode_value(mixed value, object|void codec)

Description

Code a value into a string.

This function takes a value, and converts it to a string. This string can then be saved, sent to another Pike process, packed or used in any way you like. When you want your value back you simply send this string to decode_value() and it will return the value you encoded.

Almost any value can be coded, mappings, floats, arrays, circular structures etc.

To encode objects, programs and functions, a codec object must be provided.

Note

When only simple types like int, floats, strings, mappings, multisets and arrays are encoded, the produced string is very portable between pike versions. It can at least be read by any later version.

The portability when objects, programs and functions are involved depends mostly on the codec. If the byte code is encoded, i.e. when Pike programs are actually dumped in full, then the string can probably only be read by the same pike version.

See also

decode_value() , sprintf() , encode_value_canonic()


Method encode_value_canonic

string encode_value_canonic(mixed value, object|void codec)

Description

Code a value into a string on canonical form.

Takes a value and converts it to a string on canonical form, much like encode_value() . The canonical form means that if an identical value is encoded, it will produce exactly the same string again, even if it's done at a later time and/or in another Pike process. The produced string is compatible with decode_value() .

Note

Note that this function is more restrictive than encode_value() with respect to the types of values it can encode. It will throw an error if it can't encode to a canonical form.

See also

encode_value() , decode_value()


Method decode_value

mixed decode_value(string coded_value, void|Codec codec)

Description

Decode a value from the string coded_value .

This function takes a string created with encode_value() or encode_value_canonic() and converts it back to the value that was coded.

If codec is specified, it's used as the codec for the decode. If no codec is specified, the current master object will be used.

See also

encode_value() , encode_value_canonic()


Method `()
Method call_function

mixed `()(function fun, mixed ... args)
mixed call_function(function fun, mixed ... args)

Description

Call a function.

Calls the function fun with the arguments specified by args .

See also

lfun::`()()


Method aggregate_mapping

mapping aggregate_mapping(mixed ... elems)

Description

Construct a mapping.

Groups the arguments together two and two in key-index pairs and creates a mapping of those pairs. Generally, the mapping literal syntax is handier: ([ key1:val1, key2:val2, ... ])

See also

sizeof() , mappingp() , mkmapping()


Method `!=

int(0..1) `!=(mixed arg1, mixed arg2, mixed ... extras)

Description

Inequality test.

Every expression with the != operator becomes a call to this function, i.e. a!=b is the same as predef::`!=(a,b).

This is the inverse of `==() ; see that function for further details.

Returns

Returns 1 if the test is successful, 0 otherwise.

See also

`==()


Method `==

int(0..1) `==(mixed arg1, mixed arg2, mixed ... extras)

Description

Equality test.

Every expression with the == operator becomes a call to this function, i.e. a==b is the same as predef::`==(a,b).

If more than two arguments are given, each argument is compared with the following one as described below, and the test is successful iff all comparisons are successful.

If the first argument is an object with an lfun::`==() , that function is called with the second as argument, and the test is successful iff its result is nonzero (according to `! ).

Otherwise, if the second argument is an object with an lfun::`==() , that function is called with the first as argument, and the test is successful iff its result is nonzero (according to `! ).

Otherwise, if the arguments are of different types, the test is unsuccessful. Function pointers to programs are automatically converted to program pointers if necessary, though.

Otherwise the test depends on the type of the arguments:

int

Successful iff the two integers are numerically equal.

float

Successful iff the two floats are numerically equal or if both are NaN.

string

Successful iff the two strings are identical, character for character. (Since all strings are kept unique, this is actually a test whether the arguments point to the same string, and it therefore run in constant time.)

array|mapping|multiset|object|function|program|type(mixed)

Successful iff the two arguments point to the same instance.


Returns

Returns 1 if the test is successful, 0 otherwise.

Note

Floats and integers are not automatically converted to test against each other, so e.g. 0==0.0 is false.

Note

Programs are not automatically converted to types to be compared type-wise.

See also

`!() , `!=()


Method `<

int(0..1) `<(mixed arg1, mixed arg2, mixed ... extras)

Description

Less than test.

Every expression with the < operator becomes a call to this function, i.e. a<b is the same as predef::`<(a,b).

Returns

Returns 1 if the test is successful, 0 otherwise.

See also

`<=() , `>() , `>=()


Method `<=

int(0..1) `<=(mixed arg1, mixed arg2, mixed ... extras)

Description

Less than or equal test.

Every expression with the <= operator becomes a call to this function, i.e. a<=b is the same as predef::`<=(a,b).

Returns

Returns 1 if the arguments are not strictly decreasing, and 0 (zero) otherwise.

This is the inverse of `>() .

See also

`<() , `>() , `>=()


Method `>

int(0..1) `>(mixed arg1, mixed arg2, mixed ... extras)

Description

Greater than test.

Every expression with the > operator becomes a call to this function, i.e. a>b is the same as predef::`>(a,b).

Returns

Returns 1 if the arguments are strictly decreasing, and 0 (zero) otherwise.

See also

`<() , `<=() , `>=()


Method `>=

int(0..1) `>=(mixed arg1, mixed arg2, mixed ... extras)

Description

Greater than or equal test.

Every expression with the >= operator becomes a call to this function, i.e. a>=b is the same as predef::`>=(a,b).

Returns

Returns 1 if the arguments are not strictly increasing, and 0 (zero) otherwise.

This is the inverse of `<() .

See also

`<=() , `>() , `<()


Method `+

mixed `+(mixed arg)
mixed `+(object arg, mixed ... more)
int `+(int arg, int ... more)
float `+(float|int arg, float|int ... more)
string `+(string|float|int arg, string|float|int ... more)
array `+(array arg, array ... more)
mapping `+(mapping arg, mapping ... more)
multiset `+(multiset arg, multiset ... more)

Description

Addition/concatenation.

Every expression with the + operator becomes a call to this function, i.e. a+b is the same as predef::`+(a,b). Longer + expressions are normally optimized to one call, so e.g. a+b+c becomes predef::`+(a,b,c).

Returns

If there's a single argument, that argument is returned.

If arg is an object with only one reference and an lfun::`+=() , that function is called with the rest of the arguments, and its result is returned.

Otherwise, if arg is an object with an lfun::`+() , that function is called with the rest of the arguments, and its result is returned.

Otherwise, if any of the other arguments is an object that has an lfun::``+() , the first such function is called with the arguments leading up to it, and `+() is then called recursively with the result and the rest of the arguments.

Otherwise, if arg is UNDEFINED and the other arguments are either arrays, mappings or multisets, the first argument is ignored and the remaining are added together as described below. This is useful primarily when appending to mapping values since m[x] += ({foo}) will work even if m[x] doesn't exist yet.

Otherwise the result depends on the argument types:

int|float

The result is the sum of all the arguments. It's a float if any argument is a float.

string|int|float

If any argument is a string, all will be converted to strings and concatenated in order to form the result.

array

The array arguments are concatened in order to form the result.

mapping

The result is like arg but extended with the entries from the other arguments. If the same index (according to hash_value and `== ) occur in several arguments, the value from the last one is used.

multiset

The result is like arg but extended with the entries from the other arguments. Subsequences with orderwise equal indices (i.e. where `< returns false) are concatenated into the result in argument order.


The function is not destructive on the arguments - the result is always a new instance.

Note

In Pike 7.0 and earlier the addition order was unspecified.

The treatment of UNDEFINED was new in Pike 7.0.

See also

`-() , lfun::`+() , lfun::``+()


Method `-

mixed `-(mixed arg1)
mixed `-(mixed arg1, mixed arg2, mixed ... extras)
mixed `-(object arg1, mixed arg2)
mixed `-(mixed arg1, object arg2)
int `-(int arg1, int arg2)
float `-(float arg1, int|float arg2)
float `-(int|float arg1, float arg2)
string `-(string arg1, string arg2)
array `-(array arg1, array arg2)
mapping `-(mapping arg1, array arg2)
mapping `-(mapping arg1, mapping arg2)
mapping `-(mapping arg1, multiset arg2)
multiset `-(multiset arg1, multiset arg2)

Description

Negation/subtraction/set difference.

Every expression with the - operator becomes a call to this function, i.e. -a is the same as predef::`-(a) and a-b is the same as predef::`-(a,b). Longer - expressions are normally optimized to one call, so e.g. a-b-c becomes predef::`-(a,b,c).

Returns

If there's a single argument, that argument is returned negated. If arg1 is an object with an lfun::`-() , that function is called without arguments, and its result is returned.

If there are more than two arguments the result is: `-(`-(arg1 , arg2 ), @extras ).

Otherwise, if arg1 is an object with an lfun::`-() , that function is called with arg2 as argument, and its result is returned.

Otherwise, if arg2 is an object with an lfun::``-() , that function is called with arg1 as argument, and its result is returned.

Otherwise the result depends on the argument types:

arg1 can have any of the following types:
int|float

The result is arg1  - arg2 , and is a float if either arg1 or arg2 is a float.

string

The result is arg1 with all nonoverlapping occurrences of the substring arg2 removed. In cases with two overlapping occurrences, the leftmost is removed.

array|mapping|multiset

The result is like arg1 but without the elements/indices that match any in arg2 (according to `== and, in the case of mappings, hash_value ).


The function is not destructive on the arguments - the result is always a new instance.

Note

In Pike 7.0 and earlier the subtraction order was unspecified.

See also

`+()


Method `&

mixed `&(mixed arg1)
mixed `&(mixed arg1, mixed arg2, mixed ... extras)
mixed `&(object arg1, mixed arg2)
mixed `&(mixed arg1, object arg2)
int `&(int arg1, int arg2)
string `&(string arg1, string arg2)
array `&(array arg1, array arg2)
mapping `&(mapping arg1, mapping arg2)
mapping `&(mapping arg1, array arg2)
mapping `&(mapping arg1, multiset arg2)
multiset `&(multiset arg1, multiset arg2)
type(mixed) `&(type(mixed)|program arg1, type(mixed)|program arg2)

Description

Bitwise and/intersection.

Every expression with the & operator becomes a call to this function, i.e. a&b is the same as predef::`&(a,b).

Returns

If there's a single argument, that argument is returned.

If there are more than two arguments the result is: `&(`&(arg1 , arg2 ), @extras ).

Otherwise, if arg1 is an object with an lfun::`&() , that function is called with arg2 as argument, and its result is returned.

Otherwise, if arg2 is an object with an lfun::``&() , that function is called with arg1 as argument, and its result is returned.

Otherwise the result depends on the argument types:

arg1 can have any of the following types:
int

Bitwise and of arg1 and arg2 .

string

The result is a string where each character is the bitwise and of the characters in the same position in arg1 and arg2 . The arguments must be strings of the same length.

array|mapping|multiset

The result is like arg1 but only with the elements/indices that match any in arg2 (according to `== and, in the case of mappings, hash_value ).

type(mixed)|program

Type intersection of arg1 and arg2 .


The function is not destructive on the arguments - the result is always a new instance.

See also

`|() , lfun::`&() , lfun::``&()


Method `|

mixed `|(mixed arg1)
mixed `|(mixed arg1, mixed arg2, mixed ... extras)
mixed `|(object arg1, mixed arg2)
mixed `|(mixed arg1, object arg2)
int `|(int arg1, int arg2)
string `|(string arg1, string arg2)
array `|(array arg1, array arg2)
mapping `|(mapping arg1, mapping arg2)
multiset `|(multiset arg1, multiset arg2)
type(mixed) `|(program|type(mixed) arg1, program|type(mixed) arg2)

Description

Bitwise or/union.

Every expression with the | operator becomes a call to this function, i.e. a|b is the same as predef::`|(a,b).

Returns

If there's a single argument, that argument is returned.

If there are more than two arguments, the result is: `|(`|(arg1 , arg2 ), @extras ).

Otherwise, if arg1 is an object with an lfun::`|() , that function is called with arg2 as argument, and its result is returned.

Otherwise, if arg2 is an object with an lfun::``|() , that function is called with arg1 as argument, and its result is returned.

Otherwise the result depends on the argument types:

arg1 can have any of the following types:
int

Bitwise or of arg1 and arg2 .

string

The result is a string where each character is the bitwise or of the characters in the same position in arg1 and arg2 . The arguments must be strings of the same length.

array

The result is an array with the elements in arg1 concatenated with those in arg2 that doesn't occur in arg1 (according to `== ). The order between the elements that come from the same argument is kept.

Every element in arg1 is only matched once against an element in arg2 , so if arg2 contains several elements that are equal to each other and are more than their counterparts in arg1 , the rightmost remaining elements in arg2 are kept.

mapping

The result is like arg1 but extended with the entries from arg2 . If the same index (according to hash_value and `== ) occur in both, the value from arg2 is used.

multiset

The result is like arg1 but extended with the entries in arg2 that doesn't already occur in arg1 (according to `== ). Subsequences with orderwise equal entries (i.e. where `< returns false) are handled just like the array case above.

type(mixed)|program

Type union of arg1 and arg2 .


The function is not destructive on the arguments - the result is always a new instance.

See also

`&() , lfun::`|() , lfun::``|()


Method `^

mixed `^(mixed arg1)
mixed `^(mixed arg1, mixed arg2, mixed ... extras)
mixed `^(object arg1, mixed arg2)
mixed `^(mixed arg1, object arg2)
int `^(int arg1, int arg2)
string `^(string arg1, string arg2)
array `^(array arg1, array arg2)
mapping `^(mapping arg1, mapping arg2)
multiset `^(multiset arg1, multiset arg2)
type(mixed) `^(program|type(mixed) arg1, program|type(mixed) arg2)

Description

Exclusive or.

Every expression with the ^ operator becomes a call to this function, i.e. a^b is the same as predef::`^(a,b).

Returns

If there's a single argument, that argument is returned.

If there are more than two arguments, the result is: `^(`^(arg1 , arg2 ), @extras ).

Otherwise, if arg1 is an object with an lfun::`^() , that function is called with arg2 as argument, and its result is returned.

Otherwise, if arg2 is an object with an lfun::``^() , that function is called with arg1 as argument, and its result is returned.

Otherwise the result depends on the argument types:

arg1 can have any of the following types:
int

Bitwise exclusive or of arg1 and arg2 .

string

The result is a string where each character is the bitwise exclusive or of the characters in the same position in arg1 and arg2 . The arguments must be strings of the same length.

array

The result is an array with the elements in arg1 that doesn't occur in arg2 concatenated with those in arg2 that doesn't occur in arg1 (according to `== ). The order between the elements that come from the same argument is kept.

Every element is only matched once against an element in the other array, so if one contains several elements that are equal to each other and are more than their counterparts in the other array, the rightmost remaining elements are kept.

mapping

The result is like arg1 but with the entries from arg1 and arg2 whose indices are different between them (according to hash_value and `== ).

multiset

The result is like arg1 but with the entries from arg1 and arg2 that are different between them (according to hash_value and `== ). Subsequences with orderwise equal entries (i.e. where `< returns false) are handled just like the array case above.

type(mixed)|program

The result is a type computed like this: (arg1 &~arg2 )|(~arg1 &arg2 ).


The function is not destructive on the arguments - the result is always a new instance.

See also

`&() , `|() , lfun::`^() , lfun::``^()


Method `<<

int `<<(int arg1, int arg2)
mixed `<<(object arg1, int|object arg2)
mixed `<<(int arg1, object arg2)

Description

Left shift.

Every expression with the << operator becomes a call to this function, i.e. a<<b is the same as predef::`<<(a,b).

If arg1 is an object that implements lfun::`<<() , that function will be called with arg2 as the single argument.

If arg2 is an object that implements lfun::``<<() , that function will be called with arg1 as the single argument.

Otherwise arg1 will be shifted arg2 bits left.

See also

`>>()


Method `>>

int `>>(int arg1, int arg2)
mixed `>>(object arg1, int|object arg2)
mixed `>>(int arg1, object arg2)

Description

Right shift.

Every expression with the >> operator becomes a call to this function, i.e. a>>b is the same as predef::`>>(a,b).

If arg1 is an object that implements lfun::`>>() , that function will be called with arg2 as the single argument.

If arg2 is an object that implements lfun::``>>() , that function will be called with arg1 as the single argument.

Otherwise arg1 will be shifted arg2 bits right.

See also

`<<()


Method `*

mixed `*(mixed arg1)
mixed `*(object arg1, mixed arg2, mixed ... extras)
mixed `*(mixed arg1, object arg2)
array `*(array arg1, int arg2)
array `*(array arg1, float arg2)
string `*(string arg1, int arg2)
string `*(string arg1, float arg2)
string `*(array(string) arg1, string arg2)
array `*(array(array) arg1, array arg2)
float `*(float arg1, int|float arg2)
float `*(int arg1, float arg2)
int `*(int arg1, int arg2)
mixed `*(mixed arg1, mixed arg2, mixed ... extras)

Description

Multiplication/repetition/implosion.

Every expression with the * operator becomes a call to this function, i.e. a*b is the same as predef::`*(a,b). Longer * expressions are normally optimized to one call, so e.g. a*b*c becomes predef::`*(a,b,c).

Returns

If there's a single argument, that argument will be returned.

If the first argument is an object that implements lfun::`*() , that function will be called with the rest of the arguments.

If there are more than two arguments, the result will be `*(`*(arg1 , arg2 ), @extras ).

If arg2 is an object that implements lfun::``*() , that function will be called with arg1 as the single argument.

Otherwise the result will be as follows:

arg1 can have any of the following types:
arrayarg2 can have any of the following types:
int|float

The result will be arg1 concatenated arg2 times.

string|array

The result will be the elements of arg1 concatenated with arg2 interspersed.


string

The result will be arg1 concatenated arg2 times.

int|float

The result will be arg1  * arg2 , and will be a float if either arg1 or arg2 is a float.


Note

In Pike 7.0 and earlier the multiplication order was unspecified.

See also

`+() , `-() , `/() , lfun::`*() , lfun::``*()


Method `/

mixed `/(object arg1, mixed arg2)
mixed `/(mixed arg1, object arg2)
array(string) `/(string arg1, int arg2)
array(string) `/(string arg1, float arg2)
array(array) `/(array arg1, int arg2)
array(array) `/(array arg1, float arg2)
array(string) `/(string arg1, string arg2)
array(array) `/(array arg1, array arg2)
float `/(float arg1, int|float arg2)
float `/(int arg1, float arg2)
int `/(int arg1, int arg2)
mixed `/(mixed arg1, mixed arg2, mixed ... extras)

Description

Division/split.

Every expression with the / operator becomes a call to this function, i.e. a/b is the same as predef::`/(a,b).

Returns

If there are more than two arguments, the result will be `/(`/(arg1 , arg2 ), @extras ).

If arg1 is an object that implements lfun::`/() , that function will be called with arg2 as the single argument.

If arg2 is an object that implements lfun::``/() , that function will be called with arg1 as the single argument.

Otherwise the result will be as follows:

arg1 can have any of the following types:
stringarg2 can have any of the following types:
int|float

The result will be and array of arg1 split in segments of length arg2 . If arg2 is negative the splitting will start from the end of arg1 .

string

The result will be an array of arg1 split at each occurrence of arg2 . Note that the segments that matched against arg2 will not be in the result.


arrayarg2 can have any of the following types:
int|float

The result will be and array of arg1 split in segments of length arg2 . If arg2 is negative the splitting will start from the end of arg1 .

array

The result will be an array of arg1 split at each occurrence of arg2 . Note that the elements that matched against arg2 will not be in the result.


float|int

The result will be arg1  / arg2 . If both arguments are int, the result will be truncated to an int. Otherwise the result will be a float.


Note

Unlike in some languages, the function f(x) = x/n (x and n integers) behaves in a well-defined way and is always rounded down. When you increase x, f(x) will increase with one for each n:th increment. For all x, (x + n) / n = x/n + 1; crossing zero is not special. This also means that / and % are compatible, so that a = b*(a/b) + a%b for all a and b.

See also

`%


Method `%

mixed `%(object arg1, mixed arg2)
mixed `%(mixed arg1, object arg2)
string `%(string arg1, int arg2)
array `%(array arg1, int arg2)
float `%(float arg1, float|int arg2)
float `%(int arg1, float arg2)
int `%(int arg1, int arg2)

Description

Modulo.

Every expression with the % operator becomes a call to this function, i.e. a%b is the same as predef::`%(a,b).

Returns

If arg1 is an object that implements lfun::`%() then that function will be called with arg2 as the single argument.

If arg2 is an object that implements lfun::``%() then that function will be called with arg2 as the single argument.

Otherwise the result will be as follows:

arg1 can have any of the following types:
string|array

If arg2 is positive, the result will be the last `%(sizeof (arg1 ), arg2 ) elements of arg1 . If arg2 is negative, the result will be the first `%(sizeof (arg1 ), -arg2 ) elements of arg1 .

int|float

The result will be arg1  - arg2 *floor (arg1 /arg2 ). The result will be a float if either arg1 or arg2 is a float, and an int otherwise.


For numbers, this means that

  1. a % b always has the same sign as b (typically b is positive; array size, rsa modulo, etc, and a varies a lot more than b).

  2. The function f(x) = x % n behaves in a sane way; as x increases, f(x) cycles through the values 0,1, ..., n-1, 0, .... Nothing strange happens when you cross zero.

  3. The % operator implements the binary "mod" operation, as defined by Donald Knuth (see the Art of Computer Programming, 1.2.4). It should be noted that Pike treats %-by-0 as an error rather than returning 0, though.

  4. / and % are compatible, so that a = b*(a/b) + a%b for all a and b.

See also

`/


Method `!

int(0..1) `!(object|function arg)
int(1..1) `!(int(0..0) arg)
int(0..0) `!(mixed arg)

Description

Logical not.

Every expression with the ! operator becomes a call to this function, i.e. !a is the same as predef::`!(a).

It's also used when necessary to test truth on objects, i.e. in a statement if (o) ... where o is an object, the test becomes the equivalent of !!o so that any lfun::`!() the object might have gets called.

Returns

If arg is an object that implements lfun::`!() , that function will be called.

If arg is 0 (zero), a destructed object, or a function in a destructed object, 1 will be returned.

Otherwise 0 (zero) will be returned.

Note

No float is considered false, not even 0.0.

See also

`==() , `!=() , lfun::`!()


Method `~

mixed `~(object arg)
int `~(int arg)
float `~(float arg)
type(mixed) `~(type(mixed)|program arg)
string `~(string arg)

Description

Complement/inversion.

Every expression with the ~ operator becomes a call to this function, i.e. ~a is the same as predef::`~(a).

Returns

The result will be as follows:

arg can have any of the following types:
object

If arg implements lfun::`~() , that function will be called.

int

The bitwise inverse of arg will be returned.

float

The result will be -1.0 - arg .

type(mixed)|program

The type inverse of arg will be returned.

string

If arg only contains characters in the range 0 - 255 (8-bit), a string containing the corresponding 8-bit inverses will be returned.


See also

`!() , lfun::`~()


Method `[]

mixed `[](object arg, mixed index)
mixed `[](object arg, string index)
mixed `[](int arg, string index)
mixed `[](array arg, int index)
mixed `[](array arg, mixed index)
mixed `[](mapping arg, mixed index)
int(0..1) `[](multiset arg, mixed index)
int `[](string arg, int index)
mixed `[](program arg, string index)
mixed `[](object arg, mixed start, mixed end)
string `[](string arg, int start, int end)
array `[](array arg, int start, int end)

Description

Index/subrange.

Every non-lvalue expression with the [] operator becomes a call to this function, i.e. a[i] is the same as predef::`[](a,i) and a[i..j] is the same as predef::`[](a,i,j). If the lower limit i is left out, 0 is passed to the function. If the upper limit j is left out, Int.NATIVE_MAX is passed to the function, but that might be changed to an even larger number in the future.

Returns

If arg is an object that implements lfun::`[]() , that function will be called with the rest of the arguments.

If there are 2 arguments the result will be as follows:

arg can have any of the following types:
object

The non-static (ie public) symbol named index will be looked up in arg .

int

The bignum function named index will be looked up in arg .

array

If index is an int, index number index of arg will be returned. Otherwise an array of all elements in arg indexed with index will be returned.

mapping

If index exists in arg the corresponding value will be returned. Otherwise UNDEFINED will be returned.

multiset

If index exists in arg , 1 will be returned. Otherwise UNDEFINED will be returned.

string

The character (int) at index index in arg will be returned.

program

The non-static (ie public) constant symbol index will be looked up in arg .


Otherwise if there are 3 arguments the result will be as follows:

arg can have any of the following types:
string

A string with the characters between start and end (inclusive) in arg will be returned.

array

An array with the elements between start and end (inclusive) in arg will be returned.


Note

An indexing expression in an lvalue context, i.e. where the index is being assigned a new value, uses `[]= instead of this function.

See also

`->() , lfun::`[]() , `[]=


Method `->

mixed `->(object arg, string index)
mixed `->(int arg, string index)
mixed `->(array arg, string index)
mixed `->(mapping arg, string index)
int(0..1) `->(multiset arg, string index)
mixed `->(program arg, string index)

Description

Arrow index.

Every non-lvalue expression with the -> operator becomes a call to this function. a->b is the same as predef::`^(a,"b") where "b" is the symbol b in string form.

This function behaves like `[] , except that the index is passed literally as a string instead of being evaluated.

Returns

If arg is an object that implements lfun::`->() , that function will be called with index as the single argument.

Otherwise the result will be as follows:

arg can have any of the following types:
object

The non-static (ie public) symbol named index will be looked up in arg .

int

The bignum function named index will be looked up in arg .

array

An array of all elements in arg arrow indexed with index will be returned.

mapping

If index exists in arg the corresponding value will be returned. Otherwise UNDEFINED will be returned.

multiset

If index exists in arg , 1 will be returned. Otherwise UNDEFINED will be returned.

program

The non-static (ie public) constant symbol index will be looked up in arg .


Note

In an expression a->b, the symbol b can be any token that matches the identifier syntax - keywords are disregarded in that context.

Note

An arrow indexing expression in an lvalue context, i.e. where the index is being assigned a new value, uses `->= instead of this function.

See also

`[]() , lfun::`->() , ::`->() , `->=


Method `[]=

mixed `[]=(object arg, mixed index, mixed val)
mixed `[]=(object arg, string index, mixed val)
mixed `[]=(array arg, int index, mixed val)
mixed `[]=(mapping arg, mixed index, mixed val)
int(0..1) `[]=(multiset arg, mixed index, int(0..1) val)

Description

Index assignment.

Every lvalue expression with the [] operator becomes a call to this function, i.e. a[b]=c is the same as predef::`[]=(a,b,c).

If arg is an object that implements lfun::`[]=() , that function will be called with index and val as the arguments.

arg can have any of the following types:
object

The non-static (ie public) variable named index will be looked up in arg , and assigned val .

array|mapping

Index index in arg will be assigned val .

multiset

If val is 0 (zero), one occurrance of index in arg will be removed. Otherwise index will be added to arg if it is not already there.


Returns

val will be returned.

Note

An indexing expression in a non-lvalue context, i.e. where the index is being queried instead of assigned, uses `[] instead of this function.

See also

`->=() , lfun::`[]=() , `[]


Method `->=

mixed `->=(object arg, string index, mixed val)
mixed `->=(mapping arg, string index, mixed val)
int(0..1) `->=(multiset arg, string index, int(0..1) val)

Description

Arrow index assignment.

Every lvalue expression with the -> operator becomes a call to this function, i.e. a->b=c is the same as predef::`->=(a,"b",c) where "b" is the symbol b in string form.

This function behaves like `[]= , except that the index is passed literally as a string instead of being evaluated.

If arg is an object that implements lfun::`->=() , that function will be called with index and val as the arguments.

arg can have any of the following types:
object

The non-static (ie public) variable named index will be looked up in arg , and assigned val .

array|mapping

Index index in arg will be assigned val .

multiset

If val is 0 (zero), one occurrance of index in arg will be removed. Otherwise index will be added to arg if it is not already there.


Returns

val will be returned.

Note

In an expression a->b=c, the symbol b can be any token that matches the identifier syntax - keywords are disregarded in that context.

Note

An arrow indexing expression in a non-lvalue context, i.e. where the index is being queried instead of assigned, uses `-> instead of this function.

See also

`[]=() , lfun::`->=() , `->


Method sizeof

int sizeof(string arg)
int sizeof(array arg)
int sizeof(mapping arg)
int sizeof(multiset arg)
int sizeof(object arg)

Description

Size query.

Returns

The result will be as follows:

arg can have any of the following types:
string

The number of characters in arg will be returned.

array|multiset

The number of elements in arg will be returned.

mapping

The number of key-value pairs in arg will be returned.

object

If arg implements lfun::_sizeof() , that function will be called. Otherwise the number of non-static (ie public) symbols in arg will be returned.


See also

lfun::_sizeof()


Constant UNDEFINED

constant UNDEFINED

Description

The undefined value; ie a zero for which zero_type() returns 1.


Constant this

constant this

Description

Builtin read only variable that evaluates to the current object.

See also

this_program , this_object()


Constant this_program

constant this_program

Description

Builtin constant that evaluates to the current program.

See also

this , this_object()


Constant __null_program

constant __null_program

Description

Program used internally by the compiler.

See also

__placeholder_object


Constant __placeholder_object

constant __placeholder_object

Description

Object used internally by the compiler.

See also

__null_program


Method signal

void signal(int sig, function(int|void:void) callback)
void signal(int sig)

Description

Trap signals.

This function allows you to trap a signal and have a function called when the process receives a signal. Although it IS possible to trap SIGBUS, SIGSEGV etc. I advice you not to. Pike should not receive any such signals and if it does it is because of bugs in the Pike interpreter. And all bugs should be reported, no matter how trifle.

The callback will receive the signal number as its only argument.

See the documentation for kill() for a list of signals.

If no second argument is given, the signal handler for that signal is restored to the default handler.

If the second argument is zero, the signal will be completely ignored.

See also

kill() , signame() , signum()


Method signum

int signum(string sig)

Description

Get a signal number given a descriptive string.

This function is the inverse of signame() .

See also

signame() , kill() , signal()


Method signame

string signame(int sig)

Description

Returns a string describing the signal sig .

See also

kill() , signum() , signal()


Method set_priority

int set_priority(string level, int|void pid)


Method fork

object fork()

Description

Fork the process in two.

Fork splits the process in two, and for the parent it returns a pid object for the child. Refer to your Unix manual for further details.

Note

This function can cause endless bugs if used without proper care.

This function is disabled when using threads.

This function is not available on all platforms.

The most common use for fork is to start sub programs, which is better done with Process.create_process() .

See also

Process.create_process()


Method kill

void kill(int pid, int signal)

Description

Send a signal to another process. Returns nonzero if it worked, zero otherwise. errno may be used in the latter case to find out what went wrong.

Some signals and their supposed purpose:

SIGHUP

Hang-up, sent to process when user logs out.

SIGINT

Interrupt, normally sent by ctrl-c.

SIGQUIT

Quit, sent by ctrl-\.

SIGILL

Illegal instruction.

SIGTRAP

Trap, mostly used by debuggers.

SIGABRT

Aborts process, can be caught, used by Pike whenever something goes seriously wrong.

SIGEMT

Emulation trap.

SIGFPE

Floating point error (such as division by zero).

SIGKILL

Really kill a process, cannot be caught.

SIGBUS

Bus error.

SIGSEGV

Segmentation fault, caused by accessing memory where you shouldn't. Should never happen to Pike.

SIGSYS

Bad system call. Should never happen to Pike.

SIGPIPE

Broken pipe.

SIGALRM

Signal used for timer interrupts.

SIGTERM

Termination signal.

SIGUSR1

Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library.

SIGUSR2

Signal reserved for whatever you want to use it for. Note that some OSs reserve this signal for the thread library.

SIGCHLD

Child process died. This signal is reserved for internal use by the Pike run-time.

SIGPWR

Power failure or restart.

SIGWINCH

Window change signal.

SIGURG

Urgent socket data.

SIGIO

Pollable event.

SIGSTOP

Stop (suspend) process.

SIGTSTP

Stop (suspend) process. Sent by ctrl-z.

SIGCONT

Continue suspended.

SIGTTIN

TTY input for background process.

SIGTTOU

TTY output for background process.

SIGVTALRM

Virtual timer expired.

SIGPROF

Profiling trap.

SIGXCPU

Out of CPU.

SIGXFSZ

File size limit exceeded.

SIGSTKFLT

Stack fault


Note

Note that you have to use signame to translate the name of a signal to its number.

Note that the kill function is not available on platforms that do not support signals. Some platforms may also have signals not listed here.

See also

signal() , signum() , signame() , fork()


Method getpid

int getpid()

Description

Returns the process ID of this process.

See also

System.getppid() , System.getpgrp()


Method alarm

int alarm(int seconds)

Description

Set an alarm clock for delivery of a signal.

alarm() arranges for a SIGALRM signal to be delivered to the process in seconds seconds.

If seconds is 0 (zero), no new alarm will be scheduled.

Any previous alarms will in any case be canceled.

Returns

Returns the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.

Note

This function is only available on platforms that support signals.

See also

ualarm() , signal() , call_out()


Method ualarm

int ualarm(int useconds)

Description

Set an alarm clock for delivery of a signal.

alarm() arranges for a SIGALRM signal to be delivered to the process in useconds microseconds.

If useconds is 0 (zero), no new alarm will be scheduled.

Any previous alarms will in any case be canceled.

Returns

Returns the number of microseconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.

Note

This function is only available on platforms that support signals.

See also

alarm() , signal() , call_out()


Method atexit

void atexit(function callback)

Description

This function puts the callback in a queue of callbacks to call when pike exits.

Note

Please note that atexit callbacks are not called if Pike exits abnormally.

See also

exit() , _exit()


Method sscanf

int sscanf(string data, string format, mixed ... lvalues)

Description

The purpose of sscanf is to match a string data against a format string and place the matching results into a list of variables. The list of lvalues are destructively modified (which is only possible because sscanf really is an opcode, rather than a pike function) with the values extracted from the data according to the format specification. Only the variables up to the last matching directive of the format string are touched.

The format string can contain strings separated by special matching directives like %d, %s%c and %f. Every such directive corresponds to one of the lvalues , in order they are listed. An lvalue is the name of a variable, a name of a local variable, an index in an array, mapping or object. It is because of these lvalues that sscanf can not be implemented as a normal function.

Whenever a percent character is found in the format string, a match is performed, according to which operator and modifiers follow it:

"%b"

Reads a binary integer ("0101" makes 5)

"%d"

Reads a decimal integer ("0101" makes 101).

"%o"

Reads an octal integer ("0101" makes 65).

"%x"

Reads a hexadecimal integer ("0101" makes 257).

"%D"

Reads an integer that is either octal (leading zero), hexadecimal (leading 0x) or decimal. ("0101" makes 65).

"%c"

Reads one character and returns it as an integer ("0101" makes 48, or '0', leaving "101" for later directives). Using the field width and endianness modifiers, you can decode integers of any size and endianness. For example "%-2c" decodes "0101" into 12592, leaving "01" fot later directives. The sign modifiers can be used to modify the signature of the data, making "%+1c" decode "ä" into -28.

"%f"

Reads a float ("0101" makes 101.0).

"%F"

Reads a float encoded according to the IEEE single precision binary format ("0101" makes 6.45e-10, approximately). Given a field width modifier of 8 (4 is the default), the data will be decoded according to the IEEE double precision binary format instead. (You will however still get a float, unless your pike was compiled with the configure argument --with-double-precision.)

"%s"

Reads a string. If followed by %d, %s will only read non-numerical characters. If followed by a %[], %s will only read characters not present in the set. If followed by normal text, %s will match all characters up to but not including the first occurrence of that text.

"%[set]"

Matches a string containing a given set of characters (those given inside the brackets). %[^set] means any character except those inside brackets. Ranges of characters can be defined by using a minus character between the first and the last character to be included in the range. Example: %[0-9H] means any number or 'H'. Note that sets that includes the character - must have it first in the brackets to avoid having a range defined. Sets including the character ']' must list this first (even before -) too, for natural reasons.

"%{format%}"

Repeatedly matches 'format' as many times as possible and assigns an array of arrays with the results to the lvalue.

"%O"

Match a Pike constant, such as string or integer (currently only integer, string and character constants are functional).

"%%"

Match a single percent character (hence this is how you quote the % character to just match, and not start an lvalue matcher directive).


Similar to sprintf , you may supply modifiers between the % character and the operator, to slightly change its behaviour from the default:

"*"

The operator will only match its argument, without assigning any variable.

number

You may define a field width by supplying a numeric modifier. This means that the format should match that number of characters in the input data; be it a number characters long string, integer or otherwise ("0101" using the format %2c would read an unsigned short 12337, leaving the final "01" for later operators, for instance).

"-"

Supplying a minus sign toggles the decoding to read the data encoded in little-endian byte order, rather than the default network (big-endian) byte order.

"+"

Interpret the data as a signed entity. In other words, "%+1c" will read "\xFF" as -1 instead of 255, as "%1c" would have.


Note

Sscanf does not use backtracking. Sscanf simply looks at the format string up to the next % and tries to match that with the string. It then proceeds to look at the next part. If a part does not match, sscanf immediately returns how many % were matched. If this happens, the lvalues for % that were not matched will not be changed.

Example

// a will be assigned "oo" and 1 will be returned sscanf("foo", "f%s", a);

// a will be 4711 and b will be "bar", 2 will be returned sscanf("4711bar", "%d%s", a, b);

// a will be 4711, 2 will be returned sscanf("bar4711foo", "%*s%d", a);

// a will become "test", 2 will be returned sscanf(" \t test", "%*[ \t]%s", a);

// Remove "the " from the beginning of a string // If 'str' does not begin with "the " it will not be changed sscanf(str, "the %s", str);

// It is also possible to declare a variable directly in the sscanf call; // another reason for sscanf not to be an ordinary function:

sscanf("abc def", "%s %s", string a, string b);

Returns

The number of directives matched in the format string. Note that a string directive (%s or %[]) counts as a match even when matching just the empty string (which either may do).

See also

sprintf , array_sscanf


Method array_sscanf

array array_sscanf(string data, string format)

Description

This function works just like sscanf() , but returns the matched results in an array instead of assigning them to lvalues. This is often useful for user-defined sscanf strings.

See also

sscanf() , `/()


Method _disable_threads

_disable_threads _disable_threads()

Description

This function first posts a notice to all threads that it is time to stop. It then waits until all threads actually *have* stopped, and then then returns a lock object. All other threads will be blocked from running until that object has been freed/destroyed.

It's mainly useful to do things that require a temporary uid/gid change, since on many OS the effective user and group applies to all threads.

Note

You should make sure that the returned object is freed even if some kind of error is thrown. That means in practice that it should only have references (direct or indirect) from function local variables. Also, it shouldn't be referenced from cyclic memory structures, since those are only destructed by the periodic gc. (This advice applies to mutex locks in general, for that matter.)


Method version

string version()

Description

Report the version of Pike. Does the same as

sprintf("Pike v%d.%d release %d", __REAL_VERSION__, __REAL_MINOR__, __REAL_BUILD__);

See also

__VERSION__ , __MINOR__ , __BUILD__ , __REAL_VERSION__ , __REAL_MINOR__ , __REAL_BUILD__ ,


Method call_out
Method _do_call_outs
Method find_call_out
Method remove_call_out
Method call_out_info

mixed call_out(function f, float|int delay, mixed ... args)
void _do_call_outs()
int find_call_out(function f)
int find_call_out(mixed id)
int remove_call_out(function f)
int remove_call_out(function id)
array(array) call_out_info()

Description

These are aliases for the corresponding functions in Pike.DefaultBackend .

See also

Pike.Backend()->call_out() , Pike.Backend()->_do_call_outs() , Pike.Backend()->find_call_out() , Pike.Backend()->remove_call_out() , Pike.Backend()->call_out_info()


Method basetype

string basetype(mixed x)

Description

Same as sprintf("%t",x);

See also

sprintf()


Method column

array column(array data, mixed index)

Description

Extract a column from a two-dimensional array.

This function is exactly equivalent to:

map(data , lambda(mixed x,mixed y) { return x[y]; }, index )

Except of course it is a lot shorter and faster. That is, it indices every index in the array data on the value of the argument index and returns an array with the results.

See also

rows()


Method mkmultiset

multiset mkmultiset(array a)

Description

This function creates a multiset from an array.

See also

aggregate_multiset()


Method trace

int trace(int level, void|string facility, void|int all_threads)

Description

This function changes the trace level for the subsystem identified by facility to level . If facility is zero or left out, it changes the global trace level which affects all subsystems.

Enabling tracing causes messages to be printed to stderr. A higher trace level includes the output from all lower levels. The lowest level is zero which disables all trace messages.

See the -t command-line option for more information.

Parameter level

If facility is specified then there is typically only one trace level for it, i.e. it's an on-or-off toggle. The global trace levels, when facility isn't specified, are:

1

Trace calls to Pike functions and garbage collector runs.

2

Trace calls to builtin functions.

3

Trace every interpreted opcode.

4

Also trace the opcode arguments.


Parameter facility

Valid facilities are:

"gc"

Trace the start and end of each run of the garbage collector. The setting is never thread local.


Parameter all_threads

Trace levels are normally thread local, so changes affect only the current thread. To change the level in all threads, pass a nonzero value in this argument.

Returns

The old trace level in the current thread is returned.


Method ctime

string ctime(int timestamp)

Description

Convert the output from a previous call to time() into a readable string containing the current year, month, day and time.

Like localtime , this function might throw an error if the ctime(2) call failed on the system. It's platform dependent what time ranges that function can handle, e.g. Windows doesn't handle a negative timestamp .

See also

time() , localtime() , mktime() , gmtime()


Method mkmapping

mapping mkmapping(array ind, array val)

Description

Make a mapping from two arrays.

Makes a mapping ind[x] :val[x] , 0 <= x < sizeof(ind).

ind and val must have the same size.

This is the inverse operation of indices() and values() .

See also

indices() , values()


Method m_delete

mixed m_delete(object|mapping map, mixed index)

Description

If map is an object that implements lfun::_m_delete() , that function will be called with index as its single argument.

Otherwise if map is a mapping the entry with index index will be removed from map destructively.

If the mapping does not have an entry with index index , nothing is done.

Returns

The value that was removed will be returned.

Note

Note that m_delete() changes map destructively.

See also

mappingp()


Method get_weak_flag

int get_weak_flag(array|mapping|multiset m)

Description

Returns the weak flag settings for m . It's a combination of Pike.WEAK_INDICES and Pike.WEAK_VALUES .


Method __empty_program

program __empty_program(int|void line, string|void file)


Method function_name

string function_name(function f)

Description

Return the name of the function f .

If f is a global function defined in the runtime 0 (zero) will be returned.

See also

function_object()


Method function_object

object function_object(function f)

Description

Return the object the function f is in.

If f is a global function defined in the runtime 0 (zero) will be returned.

Zero will also be returned if f is a constant in the parent class. In that case function_program() can be used to get the parent program.

See also

function_name() , function_program()


Method function_program

program function_program(function|program f)

Description

Return the program the function f is in.

If f is a global function defined in the runtime 0 (zero) will be returned.

See also

function_name() , function_object()


Method random

mixed random(object o)

Description

If random is called with an object, lfun::random will be called in the object.

See also

lfun::_random


Method random

int random(int max)
float random(float max)

Description

This function returns a random number in the range 0 - max -1.

See also

random_seed()


Method random

mixed random(array|multiset x)

Description

Returns a random element from x .


Method random

array random(mapping m)

Description

Returns a random index-value pair from the mapping.


Method backtrace

array(Pike.BacktraceFrame) backtrace()

Description

FIXME: This documentation is not up to date!

Get a description of the current call stack.

The description is returned as an array with one entry for each call frame on the stack.

Each entry has this format:

Array
string file

A string with the filename if known, else zero.

int line

An integer containing the linenumber if known, else zero.

function fun

The function that was called at this level.

mixed|void ... args

The arguments that the function was called with.


The current call frame will be last in the array.

Note

Please note that the frame order may be reversed in a later version (than 7.1) of Pike to accommodate for deferred backtraces.

Note that the arguments reported in the backtrace are the current values of the variables, and not the ones that were at call-time. This can be used to hide sensitive information from backtraces (eg passwords).

See also

catch() , throw()


Method get_iterator

Iterator get_iterator(object|array|mapping|multiset|string data)

Description

Creates and returns a canonical iterator for data .

Returns
data can have any of the following types:
object

If data is an object with lfun::_get_iterator defined then it's called in it to create the iterator.

If data is an object that lacks lfun::_get_iterator then it's assumed to already be an iterator object, and is simply returned.

array

If data is an array, an Array.Iterator object will be returned.

mapping

If data is a mapping, a Mapping.Iterator object will be returned

multiset

If data is a multiset, a Multiset.Iterator object will be returned

string

If data is a string, a String.Iterator object will be returned


Note

This function is used by foreach to get an iterator for an object.

See also

Iterator , lfun::_get_iterator


Method error

void error(string f, mixed ... args)

Description

Throws an error. A more readable version of the code throw( ({ sprintf(f, @args), backtrace() }) ).


Method is_absolute_path

int is_absolute_path(string p)

Description

Check if a path p is fully qualified (ie not relative).

Returns

Returns 1 if the path is absolute, 0 otherwise.


Method explode_path

array(string) explode_path(string p)

Description

Split a path p into its components.

This function divides a path into its components. This might seem like it could be done by dividing the string on <tt>"/"</tt>, but that will not work on some operating systems. To turn the components back into a path again, use combine_path() .


Method dirname

string dirname(string x)

Description

Returns all but the last segment of a path. Some example inputs and outputs:

ExpressionValue
dirname("/a/b")"/a"
dirname("/a/")"/a"
dirname("/a")"/"
dirname("/")"/"
dirname("")""

See also

basename() , explode_path()


Method basename

string basename(string x)

Description

Returns the last segment of a path.

See also

dirname() , explode_path()


Method compile_string

program compile_string(string source, void|string filename, object|void handler, void|program p, void|object o, void|int _show_if_constant_errors)

Description

Compile the Pike code in the string source into a program. If filename is not specified, it will default to "-".

Functionally equal to compile (cpp (source , filename )).

See also

compile() , cpp() , compile_file()


Method getenv

string getenv(string varname)
mapping(string:string) getenv()

Description

When called with no arguments, a mapping with all current environment variables will be returned. Destructive opreations on the mapping will not affect the internal environment representation.

If the varname argument has been given, the value of the environment variable with the name varname will be returned. If no such environment variable exists, 0 (zero) will be returned.

On NT the environment variable name is case insensitive.


Method compile_file

program compile_file(string filename, object|void handler, void|program p, void|object o)

Description

Compile the Pike code contained in the file filename into a program.

This function will compile the file filename to a Pike program that can later be instantiated. It is the same as doing compile_string (Stdio.read_file (filename ), filename ).

See also

compile() , compile_string() , cpp()


Method putenv

void putenv(string varname, string value)

Description

Sets the environment variable varname to value .

On NT the environment variable name is case insensitive.

See also

getenv()


Method normalize_path

string normalize_path(string path)

Description

Replaces "\" with "/" if runing on MS Windows. It is adviced to use System.normalize_path instead.


Method strlen

int strlen(string|multiset|array|mapping|object thing)

Description

Alias for sizeof .

Deprecated

Method write

int write(string fmt, mixed ... args)

Description

Writes a string on stdout. Works just like Stdio.File.write on Stdio.stdout .


Method describe_backtrace

string describe_backtrace(array|object trace, void|int linewidth)

Description

Return a readable message that describes where the backtrace trace was made (by backtrace ).

It may also be an error object or array (typically caught by a catch ), in which case the error message also is included in the description.

See also

backtrace() , describe_error() , catch() , throw()


Method describe_error

string describe_error(mixed err)

Description

Return the error message from an error object or array (typically caught by a catch ). The type of the error is checked, hence err is declared as mixed and not object|array.

If an error message couldn't be obtained, a fallback message describing the failure is returned. No errors due to incorrectness in err are thrown.

See also

describe_backtrace() , get_backtrace


Method get_backtrace

array get_backtrace(object|array err)

Description

Return the backtrace array from an error object or array (typically caught by a catch ), or zero if there is none. Errors are thrown on if there are problems retrieving the backtrace.

See also

describe_backtrace() , describe_error()

  CLASS MasterObject


Inherit CompilationHandler

inherit CompilationHandler : CompilationHandler

Description

The master object acts as fallback compilation handler for compile() and cpp() .


Method get_compilation_handler

CompilationHandler get_compilation_handler(int major, int minor)

Description

Get compilation handler for simulation of Pike vmajor .minor .

This function is called by cpp() when it encounters #pike directives.

Parameter major

Major version.

Parameter minor

Minor version.

Returns

Returns a compilation handler for Pike >= major .minor .


Method decode_charset

string decode_charset(string raw, string charset)

Description

Convert raw from encoding charset to UNICODE.

This function is called by cpp() when it encounters #charset directives.

Parameter raw

String to convert.

Parameter charset

Name of encoding that raw uses.

Returns

raw decoded to UNICODE, or 0 (zero) if the decoding failed.

See also

Locale.Charset


Inherit Codec

inherit Codec : Codec

Description

The master object is used as a fallback codec by encode_value() and decode_value() if no codec was given.

It will also be used as a codec if decode_value() encounters old-style encode_value() 'ed data.


Method describe_backtrace

string describe_backtrace(mixed exception)

Description

Called by various routines to format a readable description of an exception.

Parameter exception

Something that was thrown. Usually an Error.Generic object, or an array with the following content:

Array
string msg

Error message.

array(backtrace_frame|array(mixed)) backtrace

Backtrace to the point where the exception occurred.


Returns

Returns a string describing the exeception.

Note

Usually added by the initialization code the global name space with add_constant() .

See also

predef::describe_backtrace()


Method runtime_warning

void runtime_warning(string subsystem, string msg, mixed|void data)

Description

Called by the Pike runtime to warn about data inconsistencies.

Parameter subsystem

Runtime subsystem where the warning was generated. Currently the following subsystems may call this function:

"gc"

The garbage collector.


Parameter msg

Warning message. Currently the following messages may be generated:

"bad_cycle"

A cycle where the destruction order isn't deterministic was detected by the garbage collector.

data will in this case contain an array of the elements in the cycle.


Parameter data

Optional data that further describes the warning specified by msg .


Method handle_error

void handle_error(mixed exception)

Description

Called by the Pike runtime if an exception isn't caught.

Parameter exception

Value that was throw() 'n.

See also

describe_backtrace()


Method cast_to_object

object cast_to_object(string str, string|void current_file)

Description

Called by the Pike runtime to cast strings to objects.

Parameter str

String to cast to object.

Parameter current_file

Filename of the file that attempts to perform the cast.

Returns

Returns the resulting object.

See also

cast_to_program()


Method cast_to_program

program cast_to_program(string str, string|void current_file)

Description

Called by the Pike runtime to cast strings to programs.

Parameter str

String to cast to object.

Parameter current_file

Filename of the file that attempts to perform the cast.

Returns

Returns the resulting program.

See also

cast_to_object()


Method unregister

void unregister(program p)

Description

Unregister a program that was only partially compiled.

Called by compile() to clean up references to partially compiled programs.

Parameter p

Partially compiled program that should no longer be referenced.

FIXME

Shouldn't this function be in the compilation handler?

  CLASS CompilationHandler


Method compile_error

void compile_error(string filename, int line, string msg)

Description

Called by compile() and cpp() when they encounter errors in the code they compile.

Parameter filename

File where the error was detected.

Parameter line

Line where the error was detected.

Parameter msg

Description of error.

See also

compile_warning() .


Method compile_exception

void compile_exception(mixed exception)

Description

Called by compile() and cpp() if they trigger exceptions.


Method get_predefines

mapping(string:mixed) get_predefines()

Description

Called by cpp() to get the set of global symbols.

Returns

Returns a mapping from symbol name to symbol value. Returns zero on failure.

See also

resolv() , get_default_module()


Method resolv

mixed resolv(string symbol, string filename, CompilationHandler handler)

Description

Called by compile() and cpp() to resolv module references.

Returns

Returns the resolved value, or UNDEFINED on failure.

See also

get_predefines()


Method handle_import

mixed handle_import(string path, string filename, CompilationHandler handler)

Description

Called by compile() and cpp() to handle import directives specifying specific paths.

Returns

Returns the resolved value, or UNDEFINED on failure.


Method handle_include

string handle_include(string header_file, string current_file, int(0..1) is_local_ref)

Description

Called by cpp() to resolv #include and #string directives.

Parameter header_file

File that was requested for inclusion.

Parameter current_file

File where the directive was found.

Parameter is_local_ref

Specifies reference method.

0

Directive was #include <header_file>.

1

Directive was #include "header_file".


Returns

Returns the filename to pass to read_include() if found, and 0 (zero) on failure.

See also

read_include()


Method read_include

string read_include(string filename)

Description

Called by cpp() to read included files.

Parameter filename

Filename as returned by handle_include() .

Returns

Returns a string with the content of the header file on success, and 0 (zero) on failure.

See also

handle_include()


Method get_default_module

mapping(string:mixed)|object get_default_module()

Description

Returns the default module from which global symbols will be fetched.

Returns

Returns the default module, or 0 (zero).

If 0 (zero) is returned the compiler use the mapping returned by all_constants() as fallback.

See also

get_predefines()


Method compile_warning

void compile_warning(string filename, int line, string msg)

Description

Called by compile() to report warnings.

Parameter filename

File which triggered the warning.

Parameter line

Line which triggered the warning.

Parameter msg

Warning message.

See also

compile_error()

  CLASS Codec

Description

Codec objects are used by encode_value() and decode_value() to encode and decode objects, functions and programs.

Note

encode_value() and decode_value() will use the current master object as fallback codec object if no codec was specified.


Method nameof

mixed nameof(object|function|program x)

Description

Called by encode_value() to encode objects, functions and programs.

Returns

Returns something encodable on success, typically a string. The returned value will be passed to the corresponding objectof() , functionof() or programof() by decode_value() .

Returns UNDEFINED on failure.

Note

encode_value() has fallbacks for some classes of objects, functions and programs.

See also

objectof() , functionof() , objectof()


Method objectof

object objectof(string data)

Description

Decode object encoded in data .

This function is called by decode_value() when it encounters encoded objects.

Parameter data

Encoding of some object as specified by nameof() .

Parameter minor

Minor version.

Returns

Returns the decoded object.

See also

functionof() , programof()


Method functionof

function functionof(string data)

Description

Decode function encoded in data .

This function is called by decode_value() when it encounters encoded functions.

Parameter data

Encoding of some function as specified by nameof() .

Parameter minor

Minor version.

Returns

Returns the decoded function.

See also

objectof() , programof()


Method programof

program programof(string data)

Description

Decode program encoded in data .

This function is called by decode_value() when it encounters encoded programs.

Parameter data

Encoding of some program as specified by nameof() .

Parameter minor

Minor version.

Returns

Returns the decoded program.

See also

functionof() , objectof()


Method __register_new_program

object __register_new_program(program p)

Description

Called by decode_value() to register the program that is being decoded. Might get called repeatedly with several other programs that are being decoded recursively. The only safe assumption is that when the top level thing being decoded is a program, then the first call will be with the unfinished embryo that will later become that program.

Returns

Returns either zero or a placeholder object. A placeholder object must be a clone of __null_program . When the program is finished, the placeholder object will be converted to a clone of it. This is used for pike module objects.

  CLASS string_assignment


Method `[]

int `[](int i, int j)

Description

String index operator.


Method `[]=

int `[]=(int i, int j)

Description

String assign index operator.

  CLASS Iterator

Description

This is the interface for iterator objects. They implement an interface to a collection or stream of data items and a cursor that can be used to iterate over and examine individual items in the data set.

Iterators are typically created to access a data set in some specific object, array, mapping, multiset or string. An object can have several iterators that access different data sets in it, or the same in different ways. E.g. strings have both an iterator for access char-by-char (String.Iterator ), and another for access over splitted substrings (String.SplitIterator ). lfun::_get_iterator may be defined in an object to get an instance of the canonical iterator type for it. It's used by e.g. foreach to iterate over objects conveniently.

It's not an error to advance an iterator past the beginning or end of the data set; `!() will only return true then, and index and value will return UNDEFINED . An iterator in that state need not keep track of positions, so it's undefined what happens if it's "moved back" into the set of items.

Backward movement for iterators is optional. It's supported if and only if `-() is defined, but even then it's undefined how far back the iterator can move. Therefore iterators may support only a limited amount of backward movement, e.g. when they access a stream through a limited buffer. If such an iterator is moved back past the limit then it'll behave as if it's pointing entirely outside the data set (see above).

An iterator that doesn't support backward movement at all should throw an error if it's attempted.

See also

predef::get_iterator , lfun::_get_iterator , Array.Iterator , Mapping.Iterator , Multiset.Iterator , String.Iterator , String.SplitIterator .


Method create

void Iterator(void|mixed data)

Description

Initialize this iterator to access a data set in data . The type of data is specific to the iterator implementation. An iterator may also access some implicit data set, in which case data isn't specified at all.

The iterator initially points to the first item in the data set, if there is any.

The iterator need not support being reused, so this function is typically static.


Method `!

int(0..1) `!()

Description

Returns 0 (zero) when the iterator points to an item, 1 otherwise.


Method `+

Iterator `+(int steps)

Description

Returns a clone of this iterator which is advanced the specified number of steps. The amount may be negative to move backwards. If the iterator doesn't support backward movement it should throw an exception in that case.


Method `+=

Iterator `+=(int steps)

Description

Advance this iterator the specified number of steps and return it. The amount may be negative to move backwards. If the iterator doesn't support backward movement it should throw an exception in that case.

foreach calls this function with a step value of 1.

Note

foreach will call this function even when the the iterator has more than one reference. If you want to loop over a copy of the iterator, you can create a copy by adding 0 (zero) to it:

Iterator iterator; ... foreach(iterator+0; mixed index; mixed value) { ... }

Note

Even though this function is an lfun, it is often beneficial to not declare it static, since code might want to advance the iterator by hand.


Method `-

Iterator `-(int steps)

Description

This lfun should be defined if and only if the iterator supports backward movement to some degree. It should back up the specified number of steps. The amount may be negative to move forward.


Method index

mixed index()

Description

Returns the current index, or UNDEFINED if the iterator doesn't point to any item.

If there's no obvious index set then the index is the current position in the data set, counting from 0.


Method value

mixed value()

Description

Returns the current value, or UNDEFINED if the iterator doesn't point to any item.


Method _sizeof

int _sizeof()

Description

Returns the total number of items in the data set according to this iterator. If the size of the data set is unlimited or unknown then this function shouldn't be defined.


Method _random

void _random()

Description

If this function is defined then it sets the iterator to point to a random item in the accessible set. The random distribution should be rectangular within that set, and the pseudorandom sequence provided by random should be used.


Method first

int(0..1) first()

Description

If this function is defined then it resets the iterator to point to the first item.

Returns

Returns zero if there are no items at all in the data set, one otherwise.

Note

It's not enough to set the iterator to the earliest accessible item. If the iterator doesn't support backing up to the original start position then this function should not be implemented.


Method next

int next()

Description

If this function is defined it should advance the iterator one step, just like `+= (1) would do.

Returns

Returns 1 if it succeeded in advancing, and 0 (zero) at end of iterator.


Method set_index

void set_index(zero index)

Description

If this function is defined it should set the iterator at the specified index.

Note

It should be possible to set the index at the end of the iterator.

  CLASS master


Inherit CompatResolver

inherit CompatResolver : CompatResolver


Inherit Codec

inherit Codec : Codec


Constant bt_max_string_len

constant bt_max_string_len

Description

This constant contains the maximum length of a function entry in a backtrace. Defaults to 200 if no BT_MAX_STRING_LEN define has been given.


Constant out_of_date_warning

constant out_of_date_warning

Description

Should Pike complain about out of date compiled files. 1 means yes and 0 means no. Controlled by the OUT_OF_DATE_WARNING define.


Variable want_warnings

int want_warnings

Description

If not zero compilation warnings will be written out on stderr.


Variable compat_major

int compat_major


Variable compat_minor

int compat_minor


Variable show_if_constant_errors

int show_if_constant_errors


Method master_read_file

string master_read_file(string file)


Variable environment

mapping(string:array(string)) environment

Description

Mapping containing the environment variables.

The mapping currently has the following structure:

index : array(string)

Note that the index is lower_case() 'd on NT.

Array
string varname

Variable name with case intact.

string value

Variable value.



Note

This mapping should not be accessed directly; use getenv() and putenv() instead.

Note

This mapping is not compatible with Process.create_process() ; use the mapping returned from calling getenv() without arguments instead.


Variable programs

mapping(string:program|NoValue) programs

Description

Mapping containing the cache of currently compiled files.

This mapping currently has the following structure:

filename : program

The filename path seperator is / on both NT and UNIX.

Note

As a special case the current master program is available under the name "/master".


Method programs_reverse_lookup

string programs_reverse_lookup(program prog)

Description

Returns the path for prog in programs , if it got any.


Method objects_reverse_lookup

program objects_reverse_lookup(object obj)

Description

Returns the program for obj in objects , if it got any.


Method fc_reverse_lookup

string fc_reverse_lookup(object obj)

Description

Returns the path for obj in fc , if it got any.


Method cast_to_program

program cast_to_program(string pname, string current_file, object|void handler)

Description

This function is called when the driver wants to cast a string to a program, this might be because of an explicit cast, an inherit or a implict cast. In the future it might receive more arguments, to aid the master finding the right program.


Method handle_error

void handle_error(array|object trace)

Description

This function is called when an error occurs that is not caught with catch().


Method handle_inherit

program handle_inherit(string pname, string current_file, object|void handler)

Description

This function is called whenever a inherit is called for. It is supposed to return the program to inherit. The first argument is the argument given to inherit, and the second is the file name of the program currently compiling. Note that the file name can be changed with #line, or set by compile_string, so it can not be 100% trusted to be a filename. previous_object(), can be virtually anything in this function, as it is called from the compiler.


Method cast_to_object

object cast_to_object(string oname, string current_file, object|void current_handler)

Description

This function is called when the drivers wants to cast a string to an object because of an implict or explicit cast. This function may also receive more arguments in the future.


string _pike_file_name
string _master_file_name

Description

These are useful if you want to start other Pike processes with the same options as this one was started with.


Method asyncp

int(0..1) asyncp()

Description

Returns 1 if we´re in async-mode, e.g. if the main method has returned a negative number.


Method backend_thread

object backend_thread()

Description

The backend_thread() function is useful to determine if you are the backend thread - important when doing async/sync protocols. This method is only available if thread_create is present.


Method _main

void _main(array(string) orig_argv, array(string) env)

Description

This function is called when all the driver is done with all setup of modules, efuns, tables etc. etc. and is ready to start executing _real_ programs. It receives the arguments not meant for the driver and an array containing the environment variables on the same form as a C program receives them.


Method compile_error

void compile_error(string file, int line, string err)

Description

This function is called whenever a compile error occurs. line is zero for errors that aren't associated with any specific line. err is not newline terminated.


Method compile_warning

void compile_warning(string file, int line, string err)

Description

This function is called whenever a compile warning occurs. line is zero for warnings that aren't associated with any specific line. err is not newline terminated.


Method compile_exception

int compile_exception(array|object trace)

Description

This function is called when an exception is catched during compilation. Its message is also reported to compile_error if this function returns zero.


Method runtime_warning

void runtime_warning(string where, string what, mixed ... args)

Description

Called for every runtime warning. The first argument identifies where the warning comes from, the second identifies the specific message, and the rest depends on that. See code below for currently implemented warnings.


Method decode_charset

string decode_charset(string data, string charset)

Description

This function is called by cpp() when it wants to do character code conversion.


Method program_path_to_name

string program_path_to_name(string path, void|string module_prefix, void|string module_suffix, void|string object_suffix)

Description

Converts a module path on the form "Foo.pmod/Bar.pmod" or "/path/to/pike/lib/modules/Foo.pmod/Bar.pmod" to a module identifier on the form "Foo.Bar".

If module_prefix or module_suffix are given, they are prepended and appended, respectively, to the returned string if it's a module file (i.e. ends with ".pmod" or ".so"). If object_suffix is given, it's appended to the returned string if it's an object file (i.e. ends with ".pike").


Method describe_module

string describe_module(object|program mod, array(object)|void ret_obj)

Description

Describe the path to the module mod .

Parameter mod

If mod is a program, attempt to describe the path to a clone of mod .

Parameter ret_obj

If an instance of mod is found, it will be returned by changing element 0 of ret_obj .

Returns

The a description of the path.

Note

The returned description will end with a proper indexing method currently either "." or "->".


Method describe_object

string describe_object(object o)


Method describe_program

string describe_program(program|function p)


Method describe_function

string describe_function(function f)


Variable currentversion

Version currentversion

Description

Version information about the current Pike version.

  CLASS master.dirnode

Description

Module node representing a single directory.

See also

joinnode

  CLASS master.joinnode

Description

Module node holding possibly multiple directories, and optionally falling back to another level.

See also

dirnode

  CLASS master.CompatResolver


Variable root_module

joinnode root_module

Description

Actual resolver


Variable handler_root_modules

mapping(object:joinnode) handler_root_modules

Description

Lookup from handler module to corresponding root_module.


Variable system_module_path

array(string) system_module_path

Description

The pike system module path, not including any set by the user.


Variable pike_module_path

array(string) pike_module_path

Description

The complete module search path


Variable pike_include_path

array(string) pike_include_path

Description

The complete include search path


Variable pike_program_path

array(string) pike_program_path

Description

The complete program search path


Variable fallback_resolver

CompatResolver fallback_resolver

Description

If we fail to resolv, try the fallback.

Typical configuration:

0.6->7.0->7.2->7.4->master


Method create

void master.CompatResolver(mixed version, CompatResolver|void fallback_resolver)

Description

The CompatResolver is initialized with a value that can be casted into a "%d.%d" string, e.g. a version object.

It can also optionally be initialized with a fallback resolver.


Method add_include_path

void add_include_path(string tmp)

Description

Add a directory to search for include files.

This is the same as the command line option -I.

Note

Note that the added directory will only be searched when using < > to quote the included file.

See also

remove_include_path()


Method remove_include_path

void remove_include_path(string tmp)

Description

Remove a directory to search for include files.

This function performs the reverse operation of add_include_path() .

See also

add_include_path()


Method add_module_path

void add_module_path(string tmp)

Description

Add a directory to search for modules.

This is the same as the command line option -M.

See also

remove_module_path()


Method remove_module_path

void remove_module_path(string tmp)

Description

Remove a directory to search for modules.

This function performs the reverse operation of add_module_path() .

See also

add_module_path()


Method add_program_path

void add_program_path(string tmp)

Description

Add a directory to search for programs.

This is the same as the command line option -P.

See also

remove_program_path()


Method remove_program_path

void remove_program_path(string tmp)

Description

Remove a directory to search for programs.

This function performs the reverse operation of add_program_path() .

See also

add_program_path()


Method add_predefine

void add_predefine(string name, string value)

Description

Add a define (without arguments) which will be implicitly defined in cpp calls.


Method remove_predefine

void remove_predefine(string name)

Description

Remove a define from the set that are implicitly defined in cpp calls.


Method get_predefines

mapping get_predefines()

Description

Returns a mapping with the current predefines.


Method instantiate_static_modules

mapping(string:mixed) instantiate_static_modules(object|mapping static_modules)

Description

Instantiate static modules in the same way that dynamic modules are instantiated.


Method get_default_module

mapping get_default_module()


Method resolv_base

mixed resolv_base(string identifier, string|void current_file, object|void current_handler)


Method resolv_or_error

mixed resolv_or_error(string identifier, string|void current_file, void|object current_handler)

Description

Same as resolv , but throws an error instead of returning UNDEFINED if the resolv failed.


Method resolv

mixed resolv(string identifier, string|void current_file, object|void current_handler)


Method handle_include

string handle_include(string f, string current_file, int local_include)

Description

This function is called whenever an #include directive is encountered. It receives the argument for #include and should return the file name of the file to include


Method read_include

string read_include(string f)

  CLASS master.Pike06Resolver


Inherit CompatResolver

inherit CompatResolver : CompatResolver


Method resolv_base

mixed resolv_base(string identifier, string|void current_file, object|void current_handler)

Description

In Pike 0.6 the current directory was implicitly searched.

  CLASS master.Encoder

Description

Codec for use with encode_value . It understands all the standard references to builtin functions and pike modules.

The format of the produced identifiers are documented here to allow extension of this class:

The produced names are either strings or arrays. The string variant specifies the thing to look up according to the first character:

'c' Look up in all_constants(). 's' Look up in _static_modules. 'r' Look up with resolv(). 'p' Look up in programs. 'o' Look up in programs, then look up the result in objects. 'f' Look up in fc.

In the array format, the first element is a string as above and the rest specify a series of things to do with the result:

A string Look up this string in the result. 'm' Get module object in dirnode. 'p' Do object_program(result).

All lowercase letters and the symbols ':', '/' and '.' are reserved for internal use in both cases where characters are used above.


Method nameof

string|array nameof(mixed what, void|array(object) module_object)

Description

When module_object is set and the name would end with an object_program step (i.e. 'p'), then drop that step so that the name corresponds to the object instead. module_object [0] will receive the found object.


Method create

void master.Encoder(void|mixed encoded)

Description

Creates an encoder instance. If encoded is specified, it's encoded instead of being reverse resolved to a name. That's necessary to encode programs.

  CLASS master.Decoder

Description

Codec for use with decode_value . This is the decoder corresponding to Encoder . See that one for more details.


syntax

void|string fname
void|int mkobjvoid master.Decoder(void|string fname, void|int mkobj)

  CLASS master.Codec

Description

Encoder and Decoder rolled into one. This is for mainly compatibility; there's typically no use combining encoding and decoding into the same object.


Inherit Encoder

inherit Encoder : Encoder


Inherit Decoder

inherit Decoder : Decoder


Method create

void master.Codec(void|mixed encoded)

Description

The optional argument is the thing to encode; it's passed on to Encoder .

  CLASS master.Version

Description

Contains version information about a Pike version.


int major
int minor

Description

The major and minor parts of the version.


Method create

void master.Version(int major, int minor)

Description

Set the version in the object.


Method `<
Method `>
Method `==
Method _hash

int `<(mixed v)
int `>(mixed v)
int `==(mixed v)
int _hash()

Description

Methods define so that version objects can be compared and ordered.


Method cast

mixed cast(string type)

Description

The version object can be casted into a string.

  Module Bz2

Description

The Bz2 module contains functions to compress and uncompress strings using the same algorithm as the program bzip2. Compressing and decompressing can be done in streaming mode feeding the compress and decompress objects with arbitrarily large pieces of data. The Bz2 module consists of three classes; Bz2.Deflate,Bz2.Inflate. and Bz2.File Bz2.Deflate is used to compress data and Bz2.Inflate is used to uncompress data. (Think "inflatable boat") Bz2.File is used to handle Bzip2 files.

Note

Note that this module is only available if libbzip2 was available when Pike was compiled.

Note that although the functions in Inflate and Deflate use the same algorithm as bzip2, they do not use the exact same format, so you can not directly zip files or unzip zip-files using those functions. That is why there exists a third class for files.

  CLASS Bz2.Deflate

Description

Bz2.Deflate is a builtin program written in C. It interfaces the packing routines in the bzlib library.

Note

This program is only available if libz was available and found when Pike was compiled.

See also

Bz2.Inflate()


Method create

void Bz2.Deflate(int(1..9)|void block_size)

Description

If given, block_size should be a number from 1 to 9 indicating the block size used when doing compression. The actual block size will be a 100000 times this number. Low numbers are considered 'fast', higher numbers are considered 'slow' but give better packing. The parameter is set to 9 if it is omitted.

This function can also be used to re-initialize a Bz2.Deflate object so it can be re-used.


Method feed

void feed(string data)

Description

This function feeds the data to the internal buffers of the Deflate object. All data is buffered until a read or a finish is done.

See also

Bz2.Deflate->read() Bz2.Deflate->finish()


Method read

string read(string data)

Description

This function feeds the data to the internal buffers of the Deflate object. Then it compresses all buffered data and returns the compressed data as a string

See also

Bz2.Deflate->feed() Bz2.Deflate->finish()


Method finish

string finish(string data)

Description

This method feeds the data to the internal buffers of the Deflate object. Then it compresses all buffered data adds a end of data marker ot it, returns the compressed data as a string, and reinitializes the deflate object.

See also

Bz2.Deflate->feed() Bz2.Deflate->read()


Method deflate

string deflate(string data, int(0..2)|void flush_mode)

Description

This function performs bzip2 style compression on a string data and returns the packed data. Streaming can be done by calling this function several times and concatenating the returned data.

The optional argument flush_mode should be one of the following:

Bz2.BZ_RUN

Runs Bz2.Deflate->feed()

Bz2.BZ_FLUSH

Runs Bz2.Deflate->read()

Bz2.BZ_FINISH

Runs Bz2.Deflate->finish()


See also

Bz2.Inflate->inflate()

  CLASS Bz2.Inflate

Description

Bz2.Inflate is a builtin program written in C. It interfaces the unpacking routines in the libz library.

Note

This program is only available if bzlib was available and found when Pike was compiled.

See also

Deflate


Method create

void Bz2.Inflate()


Method inflate

string inflate(string data)

Description

This function performs bzip2 style decompression. It can do decompression with arbitrarily large pieces of data. When fed with data, it decompresses as much as it can and buffers the rest.

Example

while(..){ foo = compressed_data[i..i+9]; uncompressed_concatenated_data += inflate_object->inflate(foo); i = i+10; }

See also

Bz2.Deflate->deflate()

  CLASS Bz2.File

Description

Low-level implementation of read/write support for Bzip2 files


Method close

int(0..1) close()

Description

closes the file


Method create

void Bz2.File()

Description

Creates a Bz2.File object


Method read_open

int(0..1) read_open(string file)

Description

Opens a file for reading.

Parameter file

The name of the file to be opened


Method write_open

int(0..1) write_open(string file)

Description

Opens a file for writing.

Parameter file

The name of the file to be opened


Method open

int(0..1) open(string file, void|string mode)

Description

Opens a file for I/O.

Parameter file

The name of the file to be opened

Parameter mode

Mode for the file operations. Can be either "r" (read) or "w". Read is default.


Method write

int write(string data)

Description

Writes the data to the file.

Returns

the number of bytes written to the file.


Method read

int|string read(int len)

Description

Reads len (uncompressed) bytes from the file. If len is omitted the whole file is read. If read is unsuccessful, 0 is returned.


Method eof

int(0..1) eof()

Returns

1 if EOF has been reached, 0 otherwise

  Module Nettle

Description

Low level crypto functions used by the Crypto module. Unless you are doing something very special, you would want to use the Crypto module instead.


Method crypt_md5

string Nettle.crypt_md5(string password, string salt)

Description

Does the crypt_md5 abrakadabra (MD5 + snakeoil). It is assumed that salt does not contain "$".

  CLASS Nettle.CipherInfo

Description

Represents information about a cipher algorithm, such as name, key size, and block size.


Method name

string name()

Returns

A human readable name for the algorithm.


Method key_size

string key_size()

Returns

The recommended key size for the cipher.


Method block_size

string block_size()

Returns

The block size of the cipher (1 for stream ciphers).

  CLASS Nettle.CipherState

Description

Base class for hashing contexts.


Method set_encrypt_key

CipherState set_encrypt_key(string key, void|int force)

Description

Initializes the object for encryption.

See also

set_decrypt_key , crypt


Method set_decrypt_key

CipherState set_decrypt_key(string key, void|int force)

Description

Initializes the object for decryption.

See also

set_encrypt_key , crypt


Method make_key

string make_key()

Description

Generate a key by calling Crypto.Random.random_string and initialize this object for encryption with that key.

Returns

The generated key.

See also

set_encrypt_key


Method crypt

string crypt(string data)

Description

Encrypts or decrypts data, using the current key.

Parameter data

For block ciphers, data must be an integral number of blocks.

Returns

The encrypted or decrypted data.


Method key_size

string key_size()

Returns

The actual key size for this cipher.

  CLASS Nettle.AES_Info

Description

Internal mixin class, intended to be multiply inherited together with CipherInfo.

  CLASS Nettle.AES_State

Description

State for AES encyption

  CLASS Nettle.ARCFOUR_Info

Description

Internal mixin class, intended to be multiply inherited together with CipherInfo.

  CLASS Nettle.ARCFOUR_State

Description

State for ARCFOUR encyption

  CLASS Nettle.BLOWFISH_Info

Description

Internal mixin class, intended to be multiply inherited together with CipherInfo.

  CLASS Nettle.BLOWFISH_State

Description

State for Blowfish encyption

  CLASS Nettle.CAST128_Info

Description

Internal mixin class, intended to be multiply inherited together with CipherInfo.

  CLASS Nettle.CAST128_State

Description

State for CAST128 encyption

  CLASS Nettle.DES_Info

Description

Internal mixin class, intended to be multiply inherited together with CipherInfo.


Method fix_parity

string fix_parity(string key)

Description

Sets the last bit in every byte in key to reflect the parity. If a seven byte key is used, it will be expanded into eight bytes. If a key longer than eight characters is used, it will be truncated to eight characters.

  CLASS Nettle.DES_State

Description

State for DES encyption

  CLASS Nettle.DES3_Info

Description

Internal mixin class, intended to be multiply inherited together with CipherInfo.


Method fix_parity

string fix_parity(string key)

Description

Sets the last bit in every byte in key to reflect the parity. If a 21 byte key is used, it will be expanded into 24 bytes. If a key longer than 24 characters is used, it will be truncated to 24 characters.

  CLASS Nettle.DES3_State

Description

State for DES3 encyption

  CLASS Nettle.Serpent_Info

Description

Internal mixin class, intended to be multiply inherited together with CipherInfo.

  CLASS Nettle.Serpent_State

Description

State for Serpent encyption

  CLASS Nettle.Twofish_Info

Description

Internal mixin class, intended to be multiply inherited together with CipherInfo.

  CLASS Nettle.Twofish_State

Description

State for Twofish encyption

  CLASS Nettle.IDEA_Info

Description

Internal mixin class, intended to be multiply inherited together with CipherInfo.

  CLASS Nettle.IDEA_State

Description

State for IDEA encyption

  CLASS Nettle.HashInfo

Description

Represents information about a hash algorithm, such as name, digest size, and internal block size.


Method name

string name()

Description

Returns a human readable name for the algorithm.


Method digest_size

string digest_size()

Description

Returns the size of a hash digests.


Method block_size

string block_size()

Description

Returns the internal block size of the hash algorithm.

  CLASS Nettle.HashState

Description

Base class for hashing contexts.


Method update

HashState update(string data)

Description

Hashes more data.


Method digest

string digest(int|void length)

Description

Generates a digests, and resets the hashing contents.

Parameter length

If the length argument is provided, the digest is truncated to the given length.

Returns

The digest.

  CLASS Nettle.MD5_Info

Description

Internal mixin class, intended to be multiply inherited together with HashInfo.

  CLASS Nettle.MD5_State

Description

State for MD5 hashing.

  CLASS Nettle.MD4_Info

Description

Internal mixin class, intended to be multiply inherited together with HashInfo.

  CLASS Nettle.MD4_State

Description

State for MD4 hashing.

  CLASS Nettle.MD2_Info

Description

Internal mixin class, intended to be multiply inherited together with HashInfo.

  CLASS Nettle.MD2_State

Description

State for MD2 hashing.

  CLASS Nettle.SHA1_Info

Description

Internal mixin class, intended to be multiply inherited together with HashInfo.

  CLASS Nettle.SHA1_State

Description

State for SHA1 hashing.

  CLASS Nettle.SHA256_Info

Description

Internal mixin class, intended to be multiply inherited together with HashInfo.

  CLASS Nettle.SHA256_State

Description

State for SHA256 hashing.

  CLASS Nettle.Yarrow

Description

Yarrow is a family of pseudo-randomness generators, designed for cryptographic use, by John Kelsey, Bruce Schneier and Niels Ferguson. Yarrow-160 is described in a paper at http://www.counterpane.com/yarrow.html, and it uses SHA1 and triple-DES, and has a 160-bit internal state. Nettle implements Yarrow-256, which is similar, but uses SHA256 and AES to get an internal state of 256 bits.


Method create

void Nettle.Yarrow(void|int sources)

Description

The number of entropy sources that will feed entropy to the random number generator is given as an argument to Yarrow during instantiation.

See also

update


Method seed

Yarrow seed(string data)

Description

The random generator needs to be seeded before it can be used. The seed must be at least 32 characters long. The seed could be stored from a previous run by inserting the value returned from get_seed .

Returns

Returns the called object.

See also

min_seed_size , get_seed , is_seeded


Method min_seed_size

int(0..) min_seed_size()

Description

Returns the minimal number of characters that the seed needs to properly seed the random number generator.

See also

seed


Method get_seed

string get_seed()

Description

Returns part of the internal state so that it can be saved for later seeding.

See also

seed


Method is_seeded

int(0..1) is_seeded()

Description

Returns 1 if the random generator is seeded and ready to generator output. 0 otherwise.

See also

seed


Method force_reseed

void force_reseed()

Description

By calling this function entropy is moved from the slow pool to the fast pool. Read more about Yarrow before using this.


Method update

int(0..1) update(string data, int source, int entropy)

Description

Inject additional entropy into the random number generator.

See also

create


Method needed_sources

int(0..) needed_sources()

Description

The number of sources that must reach the threshold before a slow reseed will happen.


Method random_string

string random_string(int length)

Description

Returns a pseudo-random string of the requested length .

  Module Crypto

Description

Various cryptographic classes and functions.

Hash functions These are based on the Hash API; MD2 , MD4 , MD5 , SHA1 , SHA256 .

Stream cipher functions These are based on the Cipher API; AES , Arcfour , Blowfish , CAST , DES , DES3 , IDEA , Serpent , Twofish . The Substitution program is compatible with the CipherState. Also conforming to the API are the helper programs Buffer , CBC and Pipe .


Method make_crypt_md5

string Crypto.make_crypt_md5(string password, void|string salt)

Description

Hashes a password together with a salt with the crypt_md5 algorithm and returns the result.

See also

verify_crypt_md5


Method verify_crypt_md5

int(0..1) Crypto.verify_crypt_md5(string password, string hash)

Description

Verifies the password against the crypt_md5 hash.

Throws

May throw an exception if the hash value is bad.

See also

make_crypt_md5

  CLASS Crypto.Pipe

Description

A wrapper class that connects several cipher algorithms into one algorithm. E.g. triple DES can be emulated with Crypto.Pipe(Crypto.DES, Crypto.DES, Crypto.DES).

  CLASS Crypto.Hash

Description

Abstract class for hash algorithms. Contains some tools useful for all hashes.


Inherit HashInfo

inherit Nettle.HashInfo : HashInfo


Method `()

HashState `()()

Description

Calling `() will return a Nettle.HashState object.


Method hash

string hash(string data)

Description

Works as a shortcut for obj->update(data)->digest().

See also

HashState()->update() and HashState()->digest() .

  CLASS Crypto.Cipher

Description

Abstract class for crypto algorithms. Contains some tools useful for all ciphers.


Inherit CipherInfo

inherit Nettle.CipherInfo : CipherInfo


Method `()

CipherState `()()

Description

Calling `() will return a Nettle.CipherState object.


Method encrypt

string encrypt(string key, string data)

Description

Works as a shortcut for obj->set_encrypt_key(key)->crypt(data)


Method decrypt

string decrypt(string key, string data)

Description

Works as a shortcut for obj->set_decrypt_key(key)->crypt(data)

  CLASS Crypto.DSA

Description

The Digital Signature Algorithm (aka DSS, Digital Signature Standard).


Method get_p

Gmp.mpz get_p()

Description

Returns the modulo.


Method get_q

Gmp.mpz get_q()

Description

Returns the group order.


Method get_g

Gmp.mpz get_g()

Description

Returns the generator.


Method get_y

Gmp.mpz get_y()

Description

Returns the public key.


Method get_x

Gmp.mpz get_x()

Description

Returns the private key.


Method set_public_key

this_program set_public_key(Gmp.mpz p_, Gmp.mpz q_, Gmp.mpz g_, Gmp.mpz y_)

Description

Sets the public key in this DSA object.


Method set_private_key

this_program set_private_key(Gmp.mpz secret)

Description

Sets the private key in this DSA object.


Method set_random

this_program set_random(function(int:string) r)

Description

Sets the random function, used to generate keys and parameters, to the function r . Default is Crypto.Random.random_string .


Method hash

Gmp.mpz hash(string msg)

Description

Makes a DSA hash of the messge msg .


Method raw_sign

array(Gmp.mpz) raw_sign(Gmp.mpz h, void|Gmp.mpz k)

Description

Sign the message h . Returns the signature as two Gmp.mpz objects.


Method raw_verify

int(0..1) raw_verify(Gmp.mpz h, Gmp.mpz r, Gmp.mpz s)

Description

Verify the signature r ,s against the message h .


Method sign_rsaref

string sign_rsaref(string msg)

Description

Make a RSA ref signature of message msg .


Method verify_rsaref

int(0..1) verify_rsaref(string msg, string s)

Description

Verify a RSA ref signature s of message msg .


Method sign_ssl

string sign_ssl(string msg)

Description

Make an SSL signatrue of message msg .


Method verify_ssl

int(0..1) verify_ssl(string msg, string s)

Description

Verify an SSL signature s of message msg .


Method nist_primes

array(Gmp.mpz) nist_primes(int l)

Description

The (slow) NIST method of generating a DSA prime pair. Algorithm 4.56 of Handbook of Applied Cryptography.


Method generate_parameters

this_program generate_parameters(int bits)

Description

Generate key parameters using nist_primes .


Method generate_key

this_program generate_key()

Description

Generates a public/private key pair. Needs the public parameters p, q and g set, either through set_public_key or generate_parameters .


Method public_key_equal

int(0..1) public_key_equal(.DSA dsa)

Description

Compares the public key in this object with that in the provided DSA object.


Method name

string name()

Description

Returns the string "DSA".

  CLASS Crypto.HMAC

Description

HMAC, defined by RFC-2104


Method create

void Crypto.HMAC(.Hash h, int|void b)

Parameter h

The hash object on which the HMAC object should base its operations. Typical input is Crypto.MD5 .

Parameter b

The block size of one compression block, in octets. Defaults to 64.


Method raw_hash

string raw_hash(string s)

Description

Calls the hash function given to create and returns the hash value of s .


Method pkcs_digest

string pkcs_digest(string s)

Description

Makes a PKCS-1 digestinfo block with the message s .

See also

Standards.PKCS.Signature.build_digestinfo

  CLASS Crypto.HMAC.`()

Description

Calling the HMAC object with a password returns a new object that can perform the actual HMAC hashing. E.g. doing a HMAC hash with MD5 and the password "bar" of the string "foo" would require the code Crypto.HMAC(Crypto.MD5)("bar")("foo").


Method create

void Crypto.HMAC.`()(string passwd)

Parameter passwd

The secret password (K).


Method `()

string `()(string text)

Description

Hashes the text according to the HMAC algorithm and returns the hash value.


Method digest_info

string digest_info(string text)

Description

Hashes the text according to the HMAC algorithm and returns the hash value as a PKCS-1 digestinfo block.

  CLASS Crypto.RSA


Method get_n

Gmp.mpz get_n()

Description

Returns the RSA modulo.


Method get_e

Gmp.mpz get_e()

Description

Returns the RSA public exponent.


Method get_d

Gmp.mpz get_d()

Description

Returns the RSA private exponent (if known).


Method get_p

Gmp.mpz get_p()

Description

Returns the first RSA prime (if known).


Method get_q

Gmp.mpz get_q()

Description

Returns the second RSA prime (if known).


Method cooked_get_n

string cooked_get_n()

Description

Returns the RSA modulo as a binary string.


Method cooked_get_e

string cooked_get_e()

Description

Returns the RSA public exponent as a binary string.


Method cooked_get_d

string cooked_get_d()

Description

Returns the RSA private exponent (if known) as a binary string.


Method cooked_get_p

string cooked_get_p()

Description

Returns the first RSA prime (if known) as a binary string.


Method cooked_get_q

string cooked_get_q()

Description

Returns the second RSA prime (if known) as a binary string.


Method set_public_key

this_program set_public_key(Gmp.mpz|int modulo, Gmp.mpz|int pub)

Description

Sets the public key.


Method set_private_key

this_program set_private_key(Gmp.mpz|int priv, array(Gmp.mpz|int)|void extra)

Description

Sets the private key.

Parameter extra
Array
Gmp.mpz|int 0

The first prime.

Gmp.mpz|int 1

The second prime.



Method query_blocksize

int query_blocksize()

Description

Returns the crypto block size, or zero if not yet set.


Method rsa_pad

Gmp.mpz rsa_pad(string message, int(1..2) type, function(int:string)|void random)

Description

Pads the message to the current block size with method type and returns the result as an integer.

Parameter type
1

The message is padded with 0xff bytes.

2

The message is padded with random data, using the random function if provided. Otherwise Crypto.Random.random_string will be used.



Method rsa_unpad

string rsa_unpad(Gmp.mpz block, int type)

Description

Reverse the effect of rsa_pad .


Method raw_sign

Gmp.mpz raw_sign(string digest)

Description

Pads the digest with rsa_pad type 1 and signs it.


Method cooked_sign

string cooked_sign(string digest)

Description

Signs digest as raw_sign and returns the signature as a byte string.


Method raw_verify

int(0..1) raw_verify(string digest, Gmp.mpz s)

Description

Verifies the digest against the signature s , assuming pad type 1.

See also

rsa_pad , raw_sign


Method encrypt

string encrypt(string s, function(int:string)|void r)

Description

Pads the message s with rsa_pad type 2, signs it and returns the signature as a byte string.

Parameter r

Optional random function to be passed down to rsa_pad .


Method decrypt

string decrypt(string s)

Description

Decrypt a message encrypted with encrypt .


Method rsa_size

int(0..) rsa_size()

Description

Returns the size of the key in terms of number of bits.


Method public_key_equal

int(0..1) public_key_equal(this_program rsa)

Description

Compares the public key of this RSA object with another RSA object.


Method sign

Gmp.mpz sign(string message, .Hash h)

Description

Signs the message with a PKCS-1 signature using hash algorithm h .


Method verify

int(0..1) verify(string msg, .Hash h, Gmp.mpz sign)

Description

Verify PKCS-1 signature sign of message msg using hash algorithm h .


Method sha_sign

string sha_sign(string message, mixed|void r)

FIXME

Document this function.


Method sha_verify

int sha_verify(string message, string signature)

FIXME

Document this function.


Method md5_sign

string md5_sign(string message, mixed|void r)

FIXME

Document this function.


Method md5_verify

int md5_verify(string message, string signature)

FIXME

Document this function.


Method get_prime

Gmp.mpz get_prime(int bits, function(int:string) r)

Description

Generate a prime with bits number of bits using random function r .


Method generate_key

this_program generate_key(int(128..) bits, function(int:string)|void r)

Description

Generate a valid RSA key pair with the size bits . A random function may be provided as arguemnt r , otherwise Crypto.Random.random_string will be used. Keys must be at least 128 bits.


Method set_encrypt_key

this_program set_encrypt_key(array(Gmp.mpz) key)

Description

Sets the public key to key and the mode to encryption.

See also

set_decrypt_key , crypt


Method set_decrypt_key

this_program set_decrypt_key(array(Gmp.mpz) key)

Description

Sets the public key to key and the mod to decryption.

See also

set_encrypt_key , crypt


Method crypt

string crypt(string s)

Description

Encrypt or decrypt depending on set mode.

See also

set_encrypt_key , set_decrypt_key


Method name

string name()

Description

Returns the string "RSA".

  CLASS Crypto.Substitution

Description

Implements a simple substitution crypto, ie. one of the first crypto systems ever invented and thus one of the least secure ones available.


Method set_key

this_program set_key(mapping(string:string|array(string)) key)

Description

Sets the encryption and decryption key. The decryption key is derived from the encryption key by reversing the mapping. If one index maps to an array of strings, one element from the array will be chosen at random in such substitution.

Throws

An error is thrown if the encryption key can not be made reversible.


Method set_null_chars

this_program set_null_chars(int|float p, array(string) chars)

Description

Set null characters (fillers). Characters from chars will be inserted into the output stream with a probability p .

Parameter p

A float between 0.0 and 1.0 or an integer between 0 and 100.

Parameter chars

An array of one character strings.


Method set_rot_key

this_program set_rot_key(void|int steps, void|array(string) alphabet)

Description

Sets the key to a ROT substitution system. steps defaults to 13 and alphabet defaults to A-Z, i.e. this function defaults to set the substitution crypto to be ROT13. If no alphabet is given the key will be case insensitive, e.g. the key will really be two ROT13 alphabets, one a-z and one A-Z, used simultaneously.


Method set_ACA_K1_key

this_program set_ACA_K1_key(string key, void|int offset, void|array(string) alphabet)

Description

Sets the key according to ACA K1 key generation. The plaintext alphabet is prepended with a keyword key that shifts the alphabet positions compared to the cryptogram alphabet. The plaintext alphabet is then reduced with the characters in the keyword. It is also optionally rotated offset number of steps.


Method set_ACA_K2_key

this_program set_ACA_K2_key(string key, void|int offset, void|array(string) alphabet)

Description

Sets the key according to ACA K2 key generation. The cryptogram alphabet is prepended with a keyword key that shifts the alphabet positions compared to the plaintext alphabet. The cryptogram alphabet is then reduced with the characters in the keyword. It is als optionally reotated offset number of steps.


Method set_ACA_K3_key

this_program set_ACA_K3_key(string key, int offset, void|array(string) alphabet)

Description

Sets the key according to ACA K3 key generation. Both the plaintext and the cryptogram alphabets are prepended with a keyword key , which characters are removed from the rest of the alphabet. The plaintext alphabet is then rotated offset number of steps.


Method set_ACA_K4_key

this_program set_ACA_K4_key(string key1, string key2, void|int offset, void|array(string) alphabet)

Description

Sets the key according to ACA K4 key generation. Both the plaintext and the cryptogram alphabets are prepended with the keywords key1 and key2 . The plaintext alphabet is then rotated offset number of steps.


Method encrypt

string encrypt(string m)

Description

Encrypts the message m .


Method decrypt

string decrypt(string c)

Description

Decrypts the cryptogram c .


Method filter

string filter(string m, void|multiset(int) save)

Description

Removes characters not in the encryption key or in the save multiset from the message m .

  CLASS Crypto.CBC

Description

Implementation of the cipher block chaining mode (CBC). Works as a wrapper for the cipher algorithm put in create.


Method create

void Crypto.CBC(program|object|function cipher, mixed ... args)

Description

Initialize the CBC wrapper with a cipher algorithm. If it is a program, an object will be instantiated with args as arguments. If it is an object that doesn't conform to the cipher API, but has an LFUN::`() , that LFUN will be called. If it is a function, that function will be called with args as arguments.


Method name

string name()

Description

Returns the string "CBC(x)" where x is the encapsulated algorithm.


Method block_size

int block_size()

Description

Reurns the block size of the encapsulated cipher.


Method key_size

int key_size()

Description

Returns the key size of the encapsulated cipher.


Method set_encrypt_key

this_program set_encrypt_key(string key)

Description

Prepare the cipher and the wrapper for encrypting with the given key .


Method set_decrypt_key

this_program set_decrypt_key(string key)

Description

Prepare the cipher and the wrapper for decrypting with the given key .


Method set_iv

this_program set_iv(string iv)

Description

Set the initialization vector to iv .


Method crypt

string crypt(string data)

Description

Encrypt/decrypt data and return the result. data must be an integral number of blocks.

  CLASS Crypto.Buffer

Description

Acts as a buffer so that data can be fed to a cipher in blocks that doesn't correspond to cipher block sizes.


Method create

void Crypto.Buffer(program|object|function cipher, mixed ... args)

Description

Initialize the Proxy wrapper with a cipher algorithm. If it is a program, an object will be instantiated with args as arguments. If it is an object that doesn't conform to the cipher API, but has an LFUN::`() , that LFUN will be called. If it is a function, that function will be called with args as arguments.


Method name

string name()

Description

Returns the string "CBC(x)" where x is the encapsulated algorithm.


Method block_size

int block_size()

Description

Get the block size of the contained block crypto.


Method key_size

int key_size()

Description

Get the key size of the contained block crypto.


Method set_encrypt_key

this_program set_encrypt_key(string key)

Description

Set the encryption key.

Note

As a side-effect any buffered data will be cleared.


Method set_decrypt_key

this_program set_decrypt_key(string key)

Description

Set the decryption key.

Note

As a side-effect any buffered data will be cleared.


Method crypt

string crypt(string data)

Description

Encrypt some data.

Adds data to be encrypted to the buffer. If there's enough data to en/decrypt a block, that will be done, and the result returned. Any uncrypted data will be left in the buffer.


Method pad

string pad()

Description

Pad and de/encrypt any data left in the buffer.

See also

unpad()


Method unpad

string unpad(string data)

Description

De/encrypt and unpad a block of data.

This performs the reverse operation of pad() .

See also

pad()

  Module Crypto.NT

  CLASS Crypto.NT.CryptContext

Description

Class representing an HCRYPTPROV handle.


Method create

void Crypto.NT.CryptContext(string name, string csp, int type, int flags)

Parameter name

Key container name. When flags is set to CRYPT_VERIFYCONTEXT the name must be 0.

Parameter csp

The name of the Crypto Service Provider to use. If set to 0 the user default CSP will be used.


Method read

string read(int size, string|void init)

Description

Retreive some random data. Calls CryptGenRandom in the NT API.

  Module Crypto.AES

Description

AES (American Encryption Standard) is a quite new block cipher, specified by NIST as a replacement for the older DES standard. The standard is the result of a competition between cipher designers. The winning design, also known as RIJNDAEL, was constructed by Joan Daemen and Vincent Rijnmen.

Like all the AES candidates, the winning design uses a block size of 128 bits, or 16 octets, and variable key-size, 128, 192 and 256 bits (16, 24 and 32 octets) being the allowed key sizes. It does not have any weak keys.


Inherit AES_Info

inherit Nettle.AES_Info : AES_Info


Inherit Cipher

inherit .Cipher : Cipher

  Module Crypto.Arcfour

Description

Arcfour is a stream cipher, also known under the trade marked name RC4, and it is one of the fastest ciphers around. A problem is that the key setup of Arcfour is quite weak, you should never use keys with structure, keys that are ordinary passwords, or sequences of keys like "secret:1", "secret:2", ..... If you have keys that don't look like random bit strings, and you want to use Arcfour, always hash the key before feeding it to Arcfour.


Inherit ARCFOUR_Info

inherit Nettle.ARCFOUR_Info : ARCFOUR_Info


Inherit Cipher

inherit .Cipher : Cipher

  Module Crypto.Blowfish

Description

BLOWFISH is a block cipher designed by Bruce Schneier. It uses a block size of 64 bits (8 octets), and a variable key size, up to 448 bits. It has some weak keys.


Inherit BLOWFISH_Info

inherit Nettle.BLOWFISH_Info : BLOWFISH_Info


Inherit Cipher

inherit .Cipher : Cipher

  Module Crypto.CAST

Description

CAST-128 is a block cipher, specified in RFC 2144. It uses a 64 bit (8 octets) block size, and a variable key size of up to 128 bits.


Inherit CAST128_Info

inherit Nettle.CAST128_Info : CAST128_Info


Inherit Cipher

inherit .Cipher : Cipher

  Module Crypto.DES

Description

DES is the old Data Encryption Standard, specified by NIST. It uses a block size of 64 bits (8 octets), and a key size of 56 bits. However, the key bits are distributed over 8 octets, where the least significant bit of each octet is used for parity. A common way to use DES is to generate 8 random octets in some way, then set the least significant bit of each octet to get odd parity, and initialize DES with the resulting key.

The key size of DES is so small that keys can be found by brute force, using specialized hardware or lots of ordinary work stations in parallel. One shouldn't be using plain DES at all today, if one uses DES at all one should be using DES3 or "triple DES".

DES also has some weak keys.


Inherit DES_Info

inherit Nettle.DES_Info : DES_Info


Inherit Cipher

inherit .Cipher : Cipher

  Module Crypto.DES3

Description

The inadequate key size of DES has already been mentioned. One way to increase the key size is to pipe together several DES boxes with independent keys. It turns out that using two DES ciphers is not as secure as one might think, even if the key size of the combination is a respectable 112 bits.

The standard way to increase DES's key size is to use three DES boxes. The mode of operation is a little peculiar: the middle DES box is wired in the reverse direction. To encrypt a block with DES3, you encrypt it using the first 56 bits of the key, then decrypt it using the middle 56 bits of the key, and finally encrypt it again using the last 56 bits of the key. This is known as "ede" triple-DES, for "encrypt-decrypt-encrypt".

The "ede" construction provides some backward compatibility, as you get plain single DES simply by feeding the same key to all three boxes. That should help keeping down the gate count, and the price, of hardware circuits implementing both plain DES and DES3.

DES3 has a key size of 168 bits, but just like plain DES, useless parity bits are inserted, so that keys are represented as 24 octets (192 bits). As a 112 bit key is large enough to make brute force attacks impractical, some applications uses a "two-key" variant of triple-DES. In this mode, the same key bits are used for the first and the last DES box in the pipe, while the middle box is keyed independently. The two-key variant is believed to be secure, i.e. there are no known attacks significantly better than brute force.


Inherit DES3_Info

inherit Nettle.DES3_Info : DES3_Info


Inherit Cipher

inherit .Cipher : Cipher

  Module Crypto.IDEA

Description

The IDEA(tm) block cipher is covered by patents held by ETH and a Swiss company called Ascom-Tech AG. The Swiss patent number is PCT/CH91/00117, the European patent number is EP 0 482 154 B1, and the U.S. patent number is US005214703. IDEA(tm) is a trademark of Ascom-Tech AG. There is no license fee required for noncommercial use.


Inherit IDEA_Info

inherit Nettle.IDEA_Info : IDEA_Info


Inherit Cipher

inherit .Cipher : Cipher

  Module Crypto.MD2

Description

MD2 is a message digest function constructed by Burton Kaliski, and is described in RFC 1319. It outputs message digests of 128 bits, or 16 octets.


Inherit MD2_Info

inherit Nettle.MD2_Info : MD2_Info


Inherit Hash

inherit .Hash : Hash

  Module Crypto.MD4

Description

MD4 is a message digest function constructed by Ronald Rivest, and is described in RFC 1320. It outputs message digests of 128 bits, or 16 octets.


Inherit MD4_Info

inherit Nettle.MD4_Info : MD4_Info


Inherit Hash

inherit .Hash : Hash

  Module Crypto.MD5

Description

MD5 is a message digest function constructed by Ronald Rivest, and is described in RFC 1321. It outputs message digests of 128 bits, or 16 octets.


Inherit MD5_Info

inherit Nettle.MD5_Info : MD5_Info


Inherit Hash

inherit .Hash : Hash

  Module Crypto.PGP

Description

PGP stuff. See RFC 2440.


Method decode

mapping(string:string|mapping) Crypto.PGP.decode(string s)

Description

Decodes PGP data.


Method verify_signature

int Crypto.PGP.verify_signature(string text, string sig, string pubkey)

Description

Verify text against signature sig with the public key pubkey .


Method encode_radix64

string Crypto.PGP.encode_radix64(string data, string type, void|mapping(string:string) extra)

Description

Encode PGP data with ASCII armour.


Method decode_radix64

mapping(string:mixed) Crypto.PGP.decode_radix64(string data)

Description

Decode ASCII armour.

  Module Crypto.Random

Description

This module contains stuff to that tries to give you the best possible random generation.


Method random_string

string Crypto.Random.random_string(int len)

Description

Returns a string of length len with random content. The content is generated by a Yarrow random generator that is constantly updated with output from /dev/random on UNIX and CryptGenRandom on NT. The Yarrow random generator is fed at least the amount of random data from its sources as it outputs, thus doing its best to give at least good pseudo- random data on operating systems with bad /dev/random.


Method random

Gmp.mpz Crypto.Random.random(int top)

Description

Returns a Gmp.mpz object with a random value between 0 and top . Uses random_string .


Method blocking_random_string

string Crypto.Random.blocking_random_string(int len)

Description

Works as random_string , but may block in order to gather enough entropy to make a truely random output. Using this function is probably overkill for about all applications.


Method add_entropy

void Crypto.Random.add_entropy(string data, int entropy)

Description

Inject additional entropy into the random generator.

Parameter data

The random string.

Parameter entropy

The number of bits in the random string that is truely random.

  Module Crypto.SHA256

Description

SHA256 is another hash function specified by NIST, intended as a replacement for SHA , generating larger digests. It outputs hash values of 256 bits, or 32 octets.


Inherit SHA256_Info

inherit Nettle.SHA256_Info : SHA256_Info


Inherit Hash

inherit .Hash : Hash

  Module Crypto.Serpent

Description

SERPENT is one of the AES finalists, designed by Ross Anderson, Eli Biham and Lars Knudsen. Thus, the interface and properties are similar to AES '. One peculiarity is that it is quite pointless to use it with anything but the maximum key size, smaller keys are just padded to larger ones.


Inherit Serpent_Info

inherit Nettle.Serpent_Info : Serpent_Info


Inherit Cipher

inherit .Cipher : Cipher

  Module Crypto.Twofish

Description

Another AES finalist, this one designed by Bruce Schneier and others.


Inherit Twofish_Info

inherit Nettle.Twofish_Info : Twofish_Info


Inherit Cipher

inherit .Cipher : Cipher

  Module Crypto.SHA1

Description

SHA1 is a hash function specified by NIST (The U.S. National Institute for Standards and Technology). It outputs hash values of 160 bits, or 20 octets.


Inherit SHA1_Info

inherit Nettle.SHA1_Info : SHA1_Info


Inherit Hash

inherit .Hash : Hash

  Module Crypto.Koremutake

Description

Quote from Koremutake home page http://shorl.com/koremutake:

In an attempt to temporarily solve the fact that human beings seem to be inable to remember important things (such as their names, car keys and seemingly random numbers with fourteen digits in 'em), we invented Koremutake.

It is, in plain language, a way to express any large number as a sequence of syllables. The general idea is that word-sounding pieces of information are a lot easier to remember than a sequence of digits.


Method encrypt

string Crypto.Koremutake.encrypt(int m)

Description

Encode an integer as a koremutake string.


Method decrypt

int Crypto.Koremutake.decrypt(string c)

Description

Decode a koremutake string into an integer.

  Module SDL

Description

SDL or Simple DirectMedia Layer is a cross-platform multimedia library designed to provide fast access to the graphics framebuffer, audio device, input and other devices. This module implements a wrapper for SDL and other relevant libraries like SDL_mixer. The interface is similar to the C one, but using generally accepted Pike syntax.

This means that classes are used when appropriate and that method names use all lowercase letters with words separated by _. For example SDL_SetVideoMode is named SDL.set_video_mode. Also note that unless otherwise noted, errors result in an error being thrown rather than returning -1 or 0, as commonly done in SDL methods.


Method init

void SDL.init(int flags)

Description

Initializes SDL. This should be called before all other SDL functions.

Parameter flags

The flags parameter specifies what part(s) of SDL to initialize. It can be one of many of the following ORed together.

SDL.INIT_TIMER

Initializes the timer subsystem.

SDL.INIT_AUDIO

Initializes the audio subsystem.

SDL.INIT_VIDEO

Initializes the video subsystem.

SDL.INIT_CDROM

Initializes the cdrom subsystem.

SDL.INIT_JOYSTICK

Initializes the joystick subsystem.

SDL.INIT_EVERYTHING

Initialize all of the above.

SDL.INIT_NOPARACHUTE

Prevents SDL from catching fatal signals.

SDL.INIT_EVENTTHREAD

Run event polling in a separate thread. Not always supported.

See also

SDL.quit() , SDL.init_sub_system() , SDL.quit_sub_system()


Method get_error

void|string SDL.get_error()

Description

Get the last internal SDL error.

Returns

The error string, or zero if there was no error.


Method init_sub_system

void SDL.init_sub_system(int flags)

Description

After SDL has been initialized with init() you may initialize uninitialized subsystems with this method.

Parameter flags

The same as what is used in SDL.init() .


Method init_sub_system

void SDL.init_sub_system(int flags)

Description

After SDL has been initialized with SDL.init() you may initialize uninitialized subsystems with this method.

Parameter flags

a bitwise OR'd combination of the subsystems you wish to check (see SDL.init() for a list of subsystem flags).

See also

SDL.init() , SDL.quit() , SDL.quit_sub_system()


Method was_init

int SDL.was_init(int flags)

Description

This method allows you to see which SDL subsytems have been initialized.

Parameter flags

a bitwise OR'd combination of the subsystems you wish to check (see SDL.init() for a list of subsystem flags).

Returns

a bitwised OR'd combination of the initialized subsystems

See also

SDL.init() , SDL.init_sub_system()


Method quit

void SDL.quit()

Description

Shuts down all SDL subsystems and frees the resources allocated to them. This should always be called before you exit.

Note

You can use the atexit() method to ensure that this method is always called when Pike exits normally.

See also

SDL.init() , SDL.init_sub_system() , SDL.quit_sub_system()


Method enable_unicode

int SDL.enable_unicode(int enable)

Description

Enables/Disables UNICODE keyboard translation.

If you wish to translate a keysym to it's printable representation, you need to enable UNICODE translation using this function and then look in the unicode member of the SDL.Keysym class. This value will be zero for keysyms that do not have a printable representation. UNICODE translation is disabled by default as the conversion can cause a slight overhead.

Parameter enable

A value of 1 enables Unicode translation, 0 disables it and -1 leaves it unchanged (useful for querying the current translation mode).

Returns

The previous translation mode (1 enabled, 0 disabled). If enable is -1, the return value is the current translation mode.

See also

SDL.Keysym


Method get_mod_state

int SDL.get_mod_state()

Description

Returns the current state of the modifier keys (CTRL, ALT, etc.).

Returns

The return value can be an OR'd combination of the following: SDL.KMOD_NONE, SDL.KMOD_LSHIFT, SDL.KMOD_RSHIFT, SDL.KMOD_LCTRL, SDL.KMOD_RCTRL, SDL.KMOD_LALT, SDL.KMOD_RALT, SDL.KMOD_LMETA, SDL.KMOD_RMETA, SDL.KMOD_NUM, SDL.KMOD_CAPS, and SDL.KMOD_MODE. For convenience the following are also defined: SDL.KMOD_CTRL, SDL.KMOD_SHIFT, SDL.KMOD_ALT and SDL.KMOD_META

See also

SDL.get_key_state()


Method get_key_state

string SDL.get_key_state()

Description

Gets a snapshot of the current keyboard state. The current state is return as a string. The string is indexed by the SDL.K_* symbols. A value of 1 means the key is pressed and a value of 0 means its not.

Note

SDL.pump_events() to update the state array.


Method video_mode_ok

int SDL.video_mode_ok(int width, int height, int bpp, int flags)

FIXME

Document this function


Method flip

int SDL.flip(SDL.Surface|void screen)

Description

On hardware that supports double-buffering, this function sets up a flip and returns. The hardware will wait for vertical retrace, and then swap video buffers before the next video surface blit or lock will return. On hardware that doesn't support double-buffering, this is equivalent to calling SDL.update_rect(screen, 0, 0, 0, 0)

The SDL.DOUBLEBUF flag must have been passed to SDL_SetVideoMode, when setting the video mode for this function to perform hardware flipping.

Parameter screen

The screen object to flip. If missing, the default screen is used.

Returns

This function returns 1 if successful, or 0 if there was an error.

See also

SDL.update_rect()


Method update_rect

void SDL.update_rect(int x, int y, int w, int h, SDL.Surface|void screen)

Description

Makes sure the given area is updated on the given screen. The rectangle must be confined within the screen boundaries (no clipping is done).

If 'x', 'y', 'w' and 'h' are all 0, SDL_UpdateRect will update the entire screen.

This function should not be called while 'screen' is locked.

Parameter x
Parameter y

Top left corner of the rectangle to update.

Parameter w
Parameter h

Width and height of the rectangle to update.

Parameter screen

The screen object to flip. If missing, the default screen is used.

See also

SDL.flip()


Method set_gamma

int SDL.set_gamma(float red, float green, float blue)

FIXME

Document this function


Method get_video_surface

void|object SDL.get_video_surface()

FIXME

Document this function


Method get_video_info

void|object SDL.get_video_info()

FIXME

Document this function


Method gl_set_attribute

void SDL.gl_set_attribute(int attribute, int value)

FIXME

Document this function


Method gl_get_attribute

void SDL.gl_get_attribute(int attribute)

FIXME

Document this function


Method show_cursor

int SDL.show_cursor(int show)

FIXME

Document this function


Method warp_mouse

void SDL.warp_mouse(int xpos, int ypos)

FIXME

Document this function


Method gl_swap_buffers

void SDL.gl_swap_buffers()

FIXME

Document this function


Method set_video_mode

object SDL.set_video_mode(int width, int height, int bpp, int flags)

FIXME

Document this function


Method blit_surface

int SDL.blit_surface(SDL.Surface src, SDL.Surface dst, SDL.Rect srcrect, SDL.Rect dstrect)

FIXME

Document this function


Method video_driver_name

void|string SDL.video_driver_name()

FIXME

Document this function


Method set_caption

void SDL.set_caption(string title, string icon)

FIXME

Document this function


Method get_caption

array(string) SDL.get_caption()

FIXME

Document this function


Method iconify_window

int SDL.iconify_window()

FIXME

Document this function


Method toggle_fullscreen

int SDL.toggle_fullscreen(void|SDL.Surface screen)

FIXME

Document this function


Method grab_input

int SDL.grab_input(int mode)

FIXME

Document this function


Method num_joysticks

int SDL.num_joysticks()

FIXME

Document this function


Method joystick_name

string SDL.joystick_name(int device_index)

FIXME

Document this function


Method joystick_opened

int SDL.joystick_opened(int device_index)

FIXME

Document this function


Method joystick_update

void SDL.joystick_update()

FIXME

Document this function


Method joystick_event_state

int SDL.joystick_event_state(int state)

FIXME

Document this function


Method cd_num_drivers

int SDL.cd_num_drivers()

FIXME

Document this function


Method cd_name

string|void SDL.cd_name(int drive)

FIXME

Document this function


Method open_audio

void SDL.open_audio(int frequency, int format, int channels, int bufsize)

FIXME

Document this function

  CLASS SDL.Rect

Description

Used in SDL to define a rectangular area. It is sometimes also used to specify only points or sizes (i.e only one of the position and dimension is used).


int x
int y

Description

Position of the upper-left corner of the rectangle.


int w
int h

Description

The width and height of the rectangle.


Method cast

mixed cast(string type)

Description

It is possible to cast a Rect object to an array or to a mapping. The array will have the values in the x, y, w, h order and the mapping will have the values associated with those names.

  CLASS SDL.Keysym

Description

The Keysym class is used to report key presses and releases. It's available from the SDL.Event class for keyboard events.

The scancode field should generally be left alone - it is the hardware dependent scancode returned by the keyboard. The sym field is extremely useful. It is the SDL-defined value of the key. This field is very useful when you are checking for certain key presses.

mod stores the current state of the keyboard modifiers as explained in SDL.get_mod_state() . The unicode field is only used when UNICODE translation is enabled with SDL.enable_unicode() . If unicode is non-zero then this a the UNICODE character corresponding to the keypress. If the high 9 bits of the character are 0, then this maps to the equivalent ASCII character.

Note

UNICODE translation does have a slight overhead so don't enable it unless its needed.


Variable scancode

int scancode

Description

Hardware specific scancode


Variable sym

int sym

Description

SDL virtual keysym


Variable mod

int mod

Description

Current key modifiers


Variable unicode

int unicode

Description

Translated character

  CLASS SDL.PixelFormat

Description

This describes the format of the pixel data stored at the pixels field of a SDL.Surface . Every surface stores a PixelFormat in the format field.


Variable bits_per_pixel

int bits_per_pixel

Description

The number of bits used to represent each pixel in a surface. Usually 8, 16, 24 or 32.


Variable bytes_per_pixel

int bytes_per_pixel

Description

The number of bytes used to represent each pixel in a surface. Usually one to four.


int rmask
int gmask
int bmask
int amask

Description

Binary mask used to retrieve individual color values.


int rloss
int gloss
int bloss
int aloss

Description

Precision loss of each color component.


int rshift
int gshift
int bshift
int ashift

Description

Binary left shift of each color component in the pixel value.


Variable colorkey

int colorkey

Description

Pixel value of transparent pixels.


Variable alpha

int alpha

Description

Overall surface alpha value.


Method losses

array(int) losses()

Description

Convenience method returning the RGBA precision loss as an array.


Method masks

array(int) masks()

Description

Convenience method returning the RGBA masks as an array.


Method shifts

array(int) shifts()

Description

Convenience method returning the RGBA shifts as an array.


Method map_rgb

int map_rgb(int r, int g, int b)
int map_rgb(Image.Color.Color color)

Description

Maps the RGB color value to the specified pixel format and returns the pixel value as an integer.

If the format has a palette (8-bit) the index of the closest matching color in the palette will be returned.

If the pixel format has an alpha component it will be returned as all 1 bits (fully opaque).

Parameter r
Parameter g
Parameter b

The red, green and blue components specified as an integer between 0 and 255.

Parameter color

The color as represented by an Image.Color.Color object.

Returns

A pixel value best approximating the given RGB color value for a given pixel format.

See also

map_rgba() , get_rgb() , get_rgba()


Method map_rgba

int map_rgba(int r, int g, int b, int a)
int map_rgba(Image.Color.Color color, int a)

Description

Maps the RGBA color value to the specified pixel format and returns the pixel value as an integer.

If the format has a palette (8-bit) the index of the closest matching color in the palette will be returned.

If the pixel format has an alpha component it will be returned as all 1 bits (fully opaque).

Parameter r
Parameter g
Parameter b
Parameter a

The red, green and blue components specified as an integer between 0 and 255.

Parameter color

The color as represented by an Image.Color.Color object.

Returns

A pixel value best approximating the given RGB color value for a given pixel format.

See also

map_rgb() , get_rgb() , get_rgba()


Method get_rgb

Image.Color.Color get_rgb(int pixel)

Description

Get RGB component values from a pixel stored in this pixel format.

Parameter pixel

A pixel retrieved from a surface with this pixel format or a color previously mapped with map_rgb() or map_rgba() .

Returns

A Image.Color.Color object with the RGB components of the pixel.

See also

map_rgb() , map_rgba() , get_rgba()


Method get_rgba

mapping(string:Image.Color.Color|int) get_rgba(int pixel)

Description

Get RGB component values from a pixel stored in this pixel format.

Parameter pixel

A pixel retrieved from a surface with this pixel format or a color previously mapped with map_rgb() or map_rgba() .

Returns

A mapping containing with the RGBA components of the pixel as described below.

color : Image.Color.Color

The RGB color value of the pixel.

alpha : int

The alpha value of the pixel in the range 0-255.


See also

map_rgb() , map_rgba() , get_rgb()

  CLASS SDL.VideoInfo

Description

This (read-only) class is returned by SDL.get_video_info() . It contains information on either the 'best' available mode (if called before SDL.set_video_mode() ) or the current video mode.


Variable blit_hw_cc

int blit_hw_cc

Description

Are hardware to hardware colorkey blits accelerated?


Variable blit_hw_a

int blit_hw_a

Description

Are hardware to hardware alpha blits accelerated?


Variable blit_sw

int blit_sw

Description

Are software to hardware blits accelerated?


Variable blit_sw_cc

int blit_sw_cc

Description

Are software to hardware colorkey blits accelerated?


Variable blit_sw_a

int blit_sw_a

Description

Are software to hardware alpha blits accelerated?


Variable blit_fill

int blit_fill

Description

Are color fills accelerated?


Variable video_mem

int video_mem

Description

Total amount of video memory in KB.


Variable format

SDL.PixelFormat format

Description

Pixel format of the video device.

  CLASS SDL.Surface

Description

Surface's represent areas of "graphical" memory, memory that can be drawn to. The video framebuffer is returned as a SDL.Surface by SDL.set_video_mode() and SDL.get_video_surface() .


int w
int h

Description

The width and height of the surface in pixels.


Variable clip_rect

SDL.Rect clip_rect

Description

This is the clipping rectangle as set by set_clip_rect() .


Variable flags

int flags

Description

The following are supported in the flags field.

SDL.SWSURFACE

Surface is stored in system memory

SDL.HWSURFACE

Surface is stored in video memory

SDL.ASYNCBLIT

Surface uses asynchronous blits if possible.

SDL.ANYFORMAT

Allows any pixel-format (Display surface).

SDL.HWPALETTE

Surface has exclusive palette.

SDL.DOUBLEBUF

Surface is double buffered (Display surface).

SDL.FULLSCREEN

Surface is full screen (Display Sur face).

SDL.OPENGL

Surface has an OpenGL context (Display Surface).

SDL.OPENGLBLIT

Surface supports OpenGL blitting (Display Surface).

SDL.RESIZABLE

Surface is resizable (Display Surface).

SDL.HWACCEL

Surface blit uses hardware acceleration.

SDL.SRCCOLORKEY

Surface use colorkey blitting.

SDL.RLEACCEL

Colorkey blitting is accelerated with RLE.

SDL.SRCALPHA

Surface blit uses alpha blending.

SDL.PREALLOC

Surface uses preallocated memory.


Variable format

SDL.PixelFormat format

Description

The pixel format of this surface.


Method get_pixel

int get_pixel(int x, int y)

Description

Get the value of the specified pixel. The surface needs to be locked before this method can be used.

Parameter x
Parameter y

Pixel coordinate to get.

Returns

The value of the specified pixel.

See also

set_pixel() , unlock() , lock()


Method set_pixel

int set_pixel(int x, int y, int pixel)

Description

Set the value of the specified pixel. The surface needs to be locked before this method can be used.

Parameter x
Parameter y

Pixel coordinate to modify.

Parameter pixel

Pixel value to set to the specified pixel.

Returns

A reference to the surface itself.

See also

get_pixel() , unlock() , lock()


Method lock

int lock()

Description

This methods locks the surface to allow direct access to the pixels using the get_pixel() and set_pixel() methods. Note that although all surfaces in SDL don't require locking, you still need to call this method to enable the set/get pixel methods. You should unlock the surface when you're doing modifying it.

Note

Calling this method multiple times means that you need to call unlock an equal number of times for the surface to become unlocked.

Returns

1 for success or 0 if the surface couldn't be locked.

See also

unlock() , set_pixel() , get_pixel()


Method unlock

void unlock()

Description

Surfaces that were previously locked using lock() must be unlocked with unlock() . Surfaces should be unlocked as soon as possible.

See also

lock()


Method init

SDL.Surface init(int flags, int width, int height, int depth, int Rmask, int Gmask, int Bmask, int Amask)

Description

This (re)initializes this surface using the specified parameters. Any previously allocated data will be freed. If depth is 8 bits an empty palette is allocated for the surface, otherwise a 'packed-pixel' SDL.PixelFormat is created using the [RGBA]mask's provided. width and height specifies the desired size of the image. The flags specifies the type of surface that should be created. It is an OR'd combination of the following possible values:

SDL.SWSURFACE

SDL will create the surface in system memory. This improves the performance of pixel level access, however you may not be able to take advantage of some types of hardware blitting.

SDL.HWSURFACE

SDL will attempt to create the surface in video memory. This will allow SDL to take advantage of Video->Video blits (which are often accelerated).

SDL.SRCCOLORKEY

This flag turns on colourkeying for blits from this surface. If SDL.HWSURFACE is also specified and colourkeyed blits are hardware-accelerated, then SDL will attempt to place the surface in video memory. Use set_color_key() to set or clear this flag after surface creation.

SDL.SRCALPHA

This flag turns on alpha-blending for blits from this surface. If SDL.HWSURFACE is also specified and alpha blending blits are hardware-accelerated, then the surface will be placed in video memory if possible. Use set_alpha() to set or clear this flag after surface creation.

Note

If an alpha-channel is specified (that is, if Amask is nonzero), then the SDL.SRCALPHA flag is automatically set. You may remove this flag by calling set_alpha() after surface creation.

Returns

A reference to itself.

Note

If this method fails, the surface will become uninitialized.

See also

set_image()


Method set_image

SDL.Surface set_image(Image.Image image, int|void flags)
SDL.Surface set_image(Image.Image image, Image.Image alpha, int|void flags)

Description

This (re)initializes this surface from the Image.Image in image. Any previously allocated data will be freed. If initialization is successful, this surface will use RGBA8888 format. For good blitting performance, it should be converted to the display format using display_format() .

Parameter image

The source image.

Parameter alpha

Optional alpha channel. In Pike, the alpha channel can have different alpha values for red, green and blue. Since SDL doesn't support this, only the alpha value of the red color is used in the conversion. When this calling convention is used, the surface alpha value of image is ignored.

Parameter flags

When present this specifies the type of surface that should be created. It is an OR'd combination of the following possible values:

SDL.SWSURFACE

SDL will create the surface in system memory. This improves the performance of pixel level access, however you may not be able to take advantage of some types of hardware blitting.

SDL.HWSURFACE

SDL will attempt to create the surface in video memory. This will allow SDL to take advantage of Video->Video blits (which are often accelerated).

SDL.SRCCOLORKEY

This flag turns on colourkeying for blits from this surface. If SDL.HWSURFACE is also specified and colourkeyed blits are hardware-accelerated, then SDL will attempt to place the surface in video memory. Use set_color_key() to set or clear this flag after surface creation.

SDL.SRCALPHA

This flag turns on alpha-blending for blits from this surface. If SDL.HWSURFACE is also specified and alpha blending blits are hardware-accelerated, then the surface will be placed in video memory if possible. Note that if this surface has an alpha value specified, this flag is enabled automatically. Use set_alpha() to modify this flag at a later point.

Note

If this method fails, the surface will become uninitialized.

Returns

A reference to itself.

See also

init()


Method display_format

SDL.Surface display_format()

Description

This function takes a surface and copies it to a new surface of the pixel format and colors of the video framebuffer, suitable for fast blitting onto the display surface. It calls convert_surface() .

If you want to take advantage of hardware colorkey or alpha blit acceleration, you should set the colorkey and / or alpha value before calling this function.

If you want an alpha channel, see display_format_alpha() .

Returns

The new surface. An error is thrown if the conversion fails.


Method display_format_alpha

SDL.Surface display_format_alpha()

Description

This function takes a surface and copies it to a new surface of the pixel format and colors of the video framebuffer, suitable for fast blitting onto the display surface. It calls convert_surface() .

If you want to take advantage of hardware colorkey or alpha blit acceleration, you should set the colorkey and / or alpha value before calling this function.

This function can be used to convert a colourkey to an alpha channel, if the SDL.SRCCOLORKEY flag is set on the surface. The generated surface will then be transparent (alpha=0) where the pixels match the colourkey, and opaque (alpha=255) elsewhere.

Returns

The new surface. An error is thrown if the conversion fails.


Method blit

object blit(SDL.Surface dst, SDL.Rect|void srcrect, SDL.Rect|void dstrect)

FIXME

Document this function


Method fill_rect

object fill_rect(int color, SDL.Rect dstrect)

FIXME

Document this function


Method fill

object fill(int color)

FIXME

Document this function


Method set_color_key

object set_color_key(int flag, int key)

FIXME

Document this function


Method set_alpha

object set_alpha(int flag, int alpha)

FIXME

Document this function


Method set_clip_rect

object set_clip_rect(SDL.Rect rect)

FIXME

Document this function


Method convert_surface

object convert_surface(SDL.PixelFormat fmt, int flags)

FIXME

Document this function

  CLASS SDL.Joystick


Method create

void SDL.Joystick(int device_index)

FIXME

Document this function


Method index

int index()

FIXME

Document this function


Method num_axes

int num_axes()

FIXME

Document this function


Method num_balls

int num_balls()

FIXME

Document this function


Method num_hats

int num_hats()

FIXME

Document this function


Method num_buttons

int num_buttons()

FIXME

Document this function


Method get_axis

float get_axis(int axis)

FIXME

Document this function


Method get_hat

int get_hat(int hat)

FIXME

Document this function


Method get_ball

array(int) get_ball(int ball)

FIXME

Document this function


Method get_button

int get_button(int button)

FIXME

Document this function


Method name

string name()

FIXME

Document this function

  CLASS SDL.CDTrack


int id
int length
int offset
int type

FIXME

Document this variable

  CLASS SDL.CD


Method create

void SDL.CD(int drive)

FIXME

Document this function


int current_frame
int current_track
int id
int numtracks

FIXME

Document this variable


Method track

CDTrack track(int track)

FIXME

Document this function


Method status

int status()

FIXME

Document this function


Method play

int play(int start, int length)

FIXME

Document this function


Method play_tracks

int play_tracks(int start_track, int start_frame, int ntracks, int nframes)

FIXME

Document this function


Method pause

int pause()

FIXME

Document this function


Method resume

int resume()

FIXME

Document this function


Method stop

int stop()

FIXME

Document this function


Method eject

int eject()

FIXME

Document this function

  CLASS SDL.Music


Method create

void SDL.Music(string fname)

FIXME

Document this function


Method pause

object pause()

FIXME

Document this function


Method halt

object halt()

FIXME

Document this function


Method resume

object resume()

FIXME

Document this function


Method rewind

object rewind()

FIXME

Document this function


Method paused

int paused()

FIXME

Document this function


Method playing

int playing()

FIXME

Document this function


Method fading

int fading()

FIXME

Document this function


Method play

object play(int|void loops)

FIXME

Document this function


Method fade_in

object fade_in(int ms, int|void loops)

FIXME

Document this function


Method fade_out

object fade_out(int ms)

FIXME

Document this function


Method set_volume

float set_volume(float vol)

FIXME

Document this function


Method volume

float volume()

FIXME

Document this function

  CLASS SDL.Event


Method get

int get()

FIXME

Document this function


Method wait

int wait()

FIXME

Document this function


Method poll

int poll()

FIXME

Document this function


int axis
int ball
int button
int code
int gain
int h
int hat
Keysym keysym
int state
int type
int value
int w
int which
int x
int xrel
int y
int yrel

  Module Shuffler


constant Shuffler.INITIAL
constant Shuffler.RUNNING
constant Shuffler.PAUSED
constant Shuffler.DONE
constant Shuffler.WRITE_ERROR
constant Shuffler.READ_ERROR
constant Shuffler.USER_ABORT

  CLASS Shuffler.Throttler

Note

This is an interface that all Throttler s must implement. It's not an actual class in this module.


Method request

void request(Shuffle shuffle, int amount, function(int:void) callback)

Description

This function is called when the Shuffle wants to send some data to a client.

When data can be sent, the callback function should be called with the amount of data that can be sent as the argument.


Method give_back

void give_back(Shuffle shuffle, int amount)

Description

This function will be called by the Shuffle object to report that some data assigned to it by this throttler was unusued, and can be given to another Shuffle object instead.

  CLASS Shuffler.Shuffle

Description

This class contains the state for one ongoing data shuffling operation. To create a Shuffle instance, use the Shuffler()->shuffle method.


Variable shuffler

Shuffler shuffler

Description

The Shuffler that owns this Shuffle object


Variable throttler

Throttler throttler

Description

The Throttler that is associated with this Shuffle object, if any.


Method set_throttler

void set_throttler(Throttler t)

Description

Calling this function overrides the Shuffler global throttler.


Method sent_data

int sent_data()

Description

Returns the amount of data that has been sent so far.


Method state

int state()

Description

Returns the current state of the shuffler. This is one of the following: INITIAL , RUNNING , PAUSED , DONE , WRITE_ERROR , READ_ERROR and USER_ABORT


Method set_done_callback

void set_done_callback(function(Shuffle:void) cb)

Description

Sets the done callback. This function will be called when all sources have been processed, or if an error occurs.


Method set_request_arg

void set_request_arg(mixed arg)

Description

Sets the extra argument sent to Throttler()->request() and Throttler()->give_back .


Method send_more_callback

void send_more_callback(int amount)


Method write_callback

void write_callback(mixed|void x)


Method create

void Shuffler.Shuffle(object fd, object shuffler, mixed throttler, mixed backend)


Method start

void start()

Description

Start sending data from the sources.


Method pause

void pause()

Description

Temporarily pause all data transmission


Method stop

void stop()

Description

Stop all data transmission, and then call the done callback


Method add_source

void add_source(mixed source, int|void start, int|void length)

Description

Add a new source to the list of data sources. The data from the sources will be sent in order.

If start and length are not specified, the whole source will be sent, if start but not length is specified, the whole source, excluding the first start bytes will be sent.

Currently supported sources

String

An ordinary 8-bit wide pike string.

Memory

An initialized instance of the System.Memory class.

NormalFile

Stdio.File instance pointing to a normal file.

Stream

Stdio.File instance pointing to a stream of some kind (network socket, named pipe, stdin etc).

Pike-stream

Stdio.File lookalike with read callback support (set_read_callback and set_close_callback).

  CLASS Shuffler.Shuffler

Description

A data shuffler. An instance of this class handles a list of Shuffle objects. Each Shuffle object can send data from one or more sources to a destination in the background.


Method set_backend

void set_backend(Pike.Backend b)

Description

Set the backend that will be used by all Shuffle objects created from this shuffler.


Method set_throttler

void set_throttler(Throttler t)

Description

Set the throttler that will be used in all Shuffle objects created from this shuffler, unless overridden in the Shuffle objects.


Method pause

void pause()

Description

Pause all Shuffle objects associated with this Shuffler


Method start

void start()

Description

Unpause all Shuffle objects associated with this Shuffler


Method shuffle

Shuffle shuffle(Stdio.File destination)

Description

Create a new Shuffle object.

  Module Unicode


Method split_words

array(string) Unicode.split_words(string input)

Description

Splits the input string into an array of words, on the boundaries between the different kinds of word characters as defined by is_wordchar . The result is an array of words, with the non-word characters between them thrown away.


Method split_words_and_normalize

array(string) Unicode.split_words_and_normalize(string input)

Description

A less wasteful equivalent of split_words (normalize (input )).


Method normalize

string Unicode.normalize(string data, string method)

Description

Normalize the given unicode string according to the specified method.

The methods are:

NFC, NFD, NFKC and NFKD.

The methods are described in detail in the UAX #15 document, which can currently be found at http://www.unicode.org/unicode/reports/tr15/tr15-21.html

A short description:

C and D specifies whether to decompose (D) complex characters to their parts, or compose (C) single characters to complex ones.

K specifies whether or not do a canonical or compatibility conversion. When K is present, compatibility transformations are performed as well as the canonical transformations.

In the following text, 'X' denotes the single character 'X', even if there is more than one character inside the quotation marks. The reson is that it's somewhat hard to describe unicode in iso-8859-1.

The Unicode Standard defines two equivalences between characters: canonical equivalence and compatibility equivalence. Canonical equivalence is a basic equivalency between characters or sequences of characters.

'Å' and 'A' '° (combining ring above)' are canonically equivalent.

For round-trip compatibility with existing standards, Unicode has encoded many entities that are really variants of existing nominal characters. The visual representations of these character are typically a subset of the possible visual representations of the nominal character. These are given compatibility decompositions in the standard. Because the characters are visually distinguished, replacing a character by a compatibility equivalent may lose formatting information unless supplemented by markup or styling.

Examples of compatibility equivalences:

  • Font variants (thin, italic, extra wide characters etc)

  • Circled and squared characters

  • super/subscript ('²' -> '2')

  • Fractions ('½' -> '1/2')

  • Other composed characters ('fi' -> 'f' 'i', 'kg' -> 'k' 'g')


Method is_wordchar

int Unicode.is_wordchar(int c)

Description

Returns whether a unicode character c is a word, part of a word or not.

Returns
2

The character is an ideograph (a CJK single-word character)

1

The character is a letter, number or non-spacing mark, as defined by its unicode (general category) specification

0

Any other character (such as symbols, punctuation and separators)


  Module CommonLog

Description

The CommonLog module is used to parse the lines in a www server's logfile, which must be in "common log" format -- such as used by default for the access log by Roxen, Caudium, Apache et al.


Method read

int CommonLog.read(function(array(int|string):void) callback, Stdio.File|string logfile, void|int offset)

Description

Reads the log file and calls the callback function for every parsed line. For lines that fails to be parsed the callback is not called not is any error thrown. The number of bytes read are returned.

Parameter callback

The callbacks first argument is an array with the different parts of the log entry.

Array
string remote_host 
int(0..0)|string ident_user 
int(0..0)|string auth_user 
int year 
int month 
int day 
int hours 
int minutes 
int seconds 
int timezone 
int(0..0)|string method

One of "GET", "POST", "HEAD" etc.

int(0..0)|string path 
string protocol

E.g. "HTTP/1.0"

int reply_code

One of 200, 404 etc.

int bytes 

The second callback argument is the current offset to the end of the current line.

Parameter offset

The position in the file where the parser should begin.

  Module DVB

Description

Implements Digital Video Broadcasting interface

Note

Only Linux version is supported.

  CLASS DVB.dvb

Description

Main class.


Method create

void DVB.dvb(int card_number)

Description

Create a DVB object.

Parameter card_number

The number of card equipment.

Note

The number specifies which device will be opened. Ie. /dev/ost/demux0, /dev/ost/demux1 ... for DVB v0.9.4 or /dev/dvb/demux0, /dev/dvb/demux1 ... for versions 2.0+


Method fe_status

mapping|int fe_status()

Description

Return status of a DVB object's frondend device.

Returns

The resulting mapping contains the following fields:

"power" : string

If 1 the frontend is powered up and is ready to be used.

"signal" : string

If 1 the frontend detects a signal above a normal noise level

"lock" : string

If 1 the frontend successfully locked to a DVB signal

"carrier" : string

If 1 carrier dectected in signal

"biterbi" : string

If 1 then lock at viterbi state

"sync" : string

If 1 then TS sync byte detected

"tuner_lock" : string

If 1 then tuner has a frequency lock



Method fe_info

mapping fe_info()

Description

Return info of a frondend device.

Note

The information heavily depends on driver. Many fields contain dumb values.


Method tune

int tune(int(0..3) lnb, int freq, int(0..1)|string pol, int sr)

Description

Tunes to apropriate transponder's parameters.

Parameter lnb

DiSeQc number of LNB.

Parameter freq

Frequency divided by 1000.

Parameter pol

Polarization. 0 or "v" for vertical type, 1 or "h" for horizontal one.

Parameter sr

The service rate parameter.


Method get_pids

mapping|int get_pids()

Description

Returns mapping with info of currently tuned program's pids.

See also

tune()


Method analyze_pat

mapping analyze_pat()

Description

Return mapping of all PMT.

sid:prognum


Method analyze_pmt

array(mapping)|int analyze_pmt(int sid, int prognum)

Description

Parse PMT table.

See also

analyze_pat()


Method stream

DVB.Stream stream(int pid, int|function rcb, int ptype)
DVB.Stream stream(int pid, int|function rcb)
DVB.Stream stream(int pid)

Description

Create a new stream reader object for PID.

Parameter pid

PID of stream.

Parameter rcb

Callback function called whenever there is the data to read from stream. Only for nonblocking mode.

Parameter ptype

Type of payload data to read. By default, audio data is fetched.

Note

Setting async callback doesn't set the object to nonblocking state.

See also

DVB.Stream()->read()

  CLASS DVB.Stream

Description

Represents an elementary data stream (PES).


Method destroy

int destroy()

Description

Purge a stream reader.

See also

DVB.dvb()->stream() , read()


Method read

string|int read()

Description

Read data from a stream. It reads up to read buffer size data.

Note

Read buffer size is 4096 by default.

See also

DVB.dvb()->stream() , close()


Method close

void close()

Description

Closes an open stream.

See also

read()

  CLASS DVB.Audio

Description

Object for controlling an audio subsystem on full featured cards.


Method create

void DVB.Audio(int card_number)
void DVB.Audio()

Description

Create a Audio object.

Parameter card_number

The number of card equipment.


Method mute

int mute(int mute)
int mute()

Description

Mute or unmute audio device.


Method status

mapping status()

Description

Returns mapping of current audio device status.


Method mixer

int mixer(int left, int right)
int mixer(int both)

Description

Sets output level on DVB audio device.

  Module Locale

Description

The functions and classes in the top level of the Locale module implements a dynamic localization system, suitable for programs that needs to change locale often. It is even possible for different threads to use different locales at the same time.

The highest level of the locale system is called projects. Usually one program consists of only one project, but for bigger applications, or highly modular applications it is possible for several projects to coexist.

Every project in turn contains several unique tokens, each one representing an entity that is different depending on the currently selected locale.

Example

// The following line tells the locale extractor what to // look for. // <locale-token project="my_project">LOCALE</locale-token>

// The localization macro. #define LOCALE(X,Y) Locale.translate("my_project", \ get_lang(), X, Y)

string get_lang() { return random(2)?"eng":"swe"; }

int(0..0) main() { write(LOCALE(0, "This is a line.")+"\n"); write(LOCALE(0, "This is another one.\n"); return 0; }


Method register_project

void Locale.register_project(string name, string path, void|string path_base)

Description

Make a connection between a project name and where its localization files can be found. The mapping from project name to locale file is stored in projects.


Method set_default_project_path

void Locale.set_default_project_path(string path)

Description

In the event that a translation is requested in an unregistered project, this path will be used as the project path. %P will be replaced with the requested projects name.


Method list_languages

array(string) Locale.list_languages(string project)

Description

Returns a list of all registered languages for a specific project.


Method get_objects

mapping(string:object) Locale.get_objects(string lang)

Description

Reads in and returns a mapping with all the registred projects' LocaleObjects in the language 'lang'


Method translate

string Locale.translate(string project, string lang, string|int id, string fallback)

Description

Returns a translation for the given id, or the fallback string


Method call

function Locale.call(string project, string lang, string name, void|function|string fb)

Description

Returns a localized function If function not found, tries fallback function fb, or fallback language fb instead

  CLASS Locale.DeferredLocale

Description

This class simulates a multi-language "string". The actual language to use is determined as late as possible.


syntax

static string project
static function(:string) get_lang
static string|int key
static string fallbackvoid Locale.DeferredLocale(string project, function(:string) get_lang, string|int key, string fallback)


Method get_identifier

array get_identifier()

Description

Return the data nessesary to recreate this "string".

  Module Locale.Gettext

Description

This module enables access to localization functions from within Pike.


Method gettext

string Locale.Gettext.gettext(string msg)
string Locale.Gettext.gettext(string msg, string domain)
string Locale.Gettext.gettext(string msg, string domain, int category)

Parameter msg

Message to be translated.

Parameter domain

Domain from within the message should be translated. Defaults to the current domain.

Parameter category

Category from which the translation should be taken. Defaults to Locale.Gettext.LC_MESSAGES .

Return a translated version of msg within the context of the specified domain and current locale. If there is no translation available, msg is returned.

Note

Prior to Pike 7.3 this function only accepted one argument, and the other functionality was provided by dgettext() and dcgettext() .

See also

bindtextdomain , textdomain , setlocale , localeconv


Method dgettext

string Locale.Gettext.dgettext(string domain, string msg)

Description

Return a translated version of msg within the context of the specified domain and current locale. If there is no translation available, msg is returned.

Note

Obsoleted by gettext() in Pike 7.3.

See also

bindtextdomain , textdomain , gettext , setlocale , localeconv


Method dcgettext

string Locale.Gettext.dcgettext(string domain, string msg, int category)

Description

Return a translated version of msg within the context of the specified domain and current locale for the specified category . Calling dcgettext with category Locale.Gettext.LC_MESSAGES gives the same result as dgettext.

If there is no translation available, msg is returned.

Note

Obsoleted by gettext() in Pike 7.3.

See also

bindtextdomain , textdomain , gettext , setlocale , localeconv


Method textdomain

string Locale.Gettext.textdomain(void|string domain)

Description

The textdomain() function sets or queries the name of the current domain of the active LC_MESSAGES locale category. The domain argument is a string that can contain only the characters allowed in legal filenames.

The domain argument is the unique name of a domain on the system. If there are multiple versions of the same domain on one system, namespace collisions can be avoided by using bindtextdomain() . If textdomain() is not called, a default domain is selected. The setting of domain made by the last valid call to textdomain() remains valid across subsequent calls to setlocale() , and gettext() .

Returns

The normal return value from textdomain() is a string containing the current setting of the domain. If domainname is void, textdomain() returns a string containing the current domain. If textdomain() was not previously called and domainname is void, the name of the default domain is returned.

See also

bindtextdomain , gettext , setlocale , localeconv


Method bindtextdomain

string Locale.Gettext.bindtextdomain(string|void domainname, string|void dirname)

Description

Binds the path predicate for a message domainname domainname to the directory name specified by dirname . If domainname is a non-empty string and has not been bound previously, bindtextdomain() binds domainname with dirname .

If domainname is a non-empty string and has been bound previously, bindtextdomain() replaces the old binding with dirname . The dirname argument can be an absolute or relative pathname being resolved when gettext() , dgettext() or dcgettext() are called. If domainname is zero or an empty string, bindtextdomain() returns 0.

User defined domain names cannot begin with the string "SYS_". Domain names beginning with this string are reserved for system use.

Returns

The return value from bindtextdomain() is a string containing dirname or the directory binding associated with domainname if dirname is unspecified. If no binding is found, the default locale path is returned. If domainname is unspecified or is an empty string, bindtextdomain() takes no action and returns a 0.

See also

textdomain , gettext , setlocale , localeconv


Method setlocale

int Locale.Gettext.setlocale(int category, string locale)

Description

The setlocale() function is used to set the program's current locale. If locale is "C" or "POSIX", the current locale is set to the portable locale.

If locale is "", the locale is set to the default locale which is selected from the environment variable LANG.

The argument category determines which functions are influenced by the new locale are LC_ALL , LC_COLLATE , LC_CTYPE , LC_MONETARY , LC_NUMERIC and LC_TIME .

Returns

Returns 1 if the locale setting successed, 0 for failure

See also

bindtextdomain , textdomain , gettext , dgettext , dcgettext , localeconv


Method localeconv

mapping Locale.Gettext.localeconv()

Description

The localeconv() function returns a mapping with settings for the current locale. This mapping contains all values associated with the locale categories LC_NUMERIC and LC_MONETARY .

"decimal_point" : string

The decimal-point character used to format non-monetary quantities.

"thousands_sep" : string

The character used to separate groups of digits to the left of the decimal-point character in formatted non-monetary quantities.

"int_curr_symbol" : string

The international currency symbol applicable to the current locale, left-justified within a four-character space-padded field. The character sequences should match with those specified in ISO 4217 Codes for the Representation of Currency and Funds.

"currency_symbol" : string

The local currency symbol applicable to the current locale.

"mon_decimal_point" : string

The decimal point used to format monetary quantities.

"mon_thousands_sep" : string

The separator for groups of digits to the left of the decimal point in formatted monetary quantities.

"positive_sign" : string

The string used to indicate a non-negative-valued formatted monetary quantity.

"negative_sign" : string

The string used to indicate a negative-valued formatted monetary quantity.

"int_frac_digits" : int

The number of fractional digits (those to the right of the decimal point) to be displayed in an internationally formatted monetary quantity.

"frac_digits" : int

The number of fractional digits (those to the right of the decimal point) to be displayed in a formatted monetary quantity.

"p_cs_precedes" : int(0..1)

Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a non-negative formatted monetary quantity.

"p_sep_by_space" : int(0..1)

Set to 1 or 0 if the currency_symbol respectively is or is not separated by a space from the value for a non-negative formatted monetary quantity.

"n_cs_precedes" : int(0..1)

Set to 1 or 0 if the currency_symbol respectively precedes or succeeds the value for a negative formatted monetary quantity.

"n_sep_by_space" : int(0..1)

Set to 1 or 0 if the currency_symbol respectively is or is not separated by a space from the value for a negative formatted monetary quantity.

"p_sign_posn" : int(0..4)

Set to a value indicating the positioning of the positive_sign for a non-negative formatted monetary quantity. The value of p_sign_posn is interpreted according to the following:

0

Parentheses surround the quantity and currency_symbol.

1

The sign string precedes the quantity and currency_symbol.

2

The sign string succeeds the quantity and currency_symbol.

3

The sign string immediately precedes the currency_symbol.

4

The sign string immediately succeeds the currency_symbol.


"n_sign_posn" : int

Set to a value indicating the positioning of the negative_sign for a negative formatted monetary quantity. The value of n_sign_posn is interpreted according to the rules described under p_sign_posn.


See also

bindtextdomain , textdomain , gettext , dgettext , dcgettext , setlocale


Constant LC_ALL

constant Locale.Gettext.LC_ALL

Description

Locale category for all of the locale.


Constant LC_COLLATE

constant Locale.Gettext.LC_COLLATE

Description

Locale category for the functions strcoll() and strxfrm() (used by pike, but not directly accessible).


Constant LC_CTYPE

constant Locale.Gettext.LC_CTYPE

Description

Locale category for the character classification and conversion routines.


Constant LC_MESSAGES

constant Locale.Gettext.LC_MESSAGES

FIXME

Document this constant.

Note

This category isn't available on all platforms.


Constant LC_MONETARY

constant Locale.Gettext.LC_MONETARY

Description

Locale category for localeconv().


Constant LC_NUMERIC

constant Locale.Gettext.LC_NUMERIC

Description

Locale category for the decimal character.


Constant LC_TIME

constant Locale.Gettext.LC_TIME

Description

Locale category for strftime() (currently not accessible from Pike).

  Module Locale.Language

  CLASS Locale.Language.abstract

Description

Abstract language locale class, inherited by all the language locale classes.


Constant months

constant months

Description

Array(string) with the months of the year, beginning with January.


Constant days

constant days

Description

Array(string) with the days of the week, beginning with Sunday.


Constant iso_639_1

constant iso_639_1

Description

String with the language code in ISO-639-1 (two character code). Note that all languages does not have a ISO-639-1 code.


Constant iso_639_2

constant iso_639_2

Description

String with the language code in ISO-639-2/T (three character code).


Constant iso_639_2B

constant iso_639_2B

Description

String with the language code in ISO-639-2/B (three character code). This is usually the same as the ISO-639-2/T code (iso_639_2 ).


Constant english_name

constant english_name

Description

The name of the language in english.


Constant name

constant name

Description

The name of the langauge. E.g. "svenska" for Swedish.


Constant languages

constant languages

Description

Mapping(string:string) that maps an ISO-639-2/T id code to the name of that language.


Method month

string month(int(1..12) num)

Description

Returns the name of month number num .


Method day

string day(int(1..7) num)

Description

Returns the name of weekday number num .


Method number

string number(int i)

Description

Returns the number i as a string.


Method ordered

string ordered(int i)

Description

Returns the ordered number i as a string.


Method date

string date(int timestamp, string|void mode)

Description

Returns the date for posix time timestamp as a textual string.

Parameter mode

Determines what kind of textual string should be produced.

"time"

I.e. "06:36"

"date"

I.e. "January the 17th in the year of 2002"

"full"

I.e. "06:37, January the 17th, 2002"


Example

> Locale.Language.eng()->date(time()); Result: "today, 06:36"

  Module Locale.Language.cat

Description

Catalan language locale.


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.ces

Description

Czech language locale by Jan Petrous 16.10.1997, based on Slovenian language module by Iztok Umek.


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.deu

Description

German language locale by Tvns Böker.


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.eng

Description

English language locale.


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.fin

Description

Finnish language locale created by Janne Edelman, Turku Unix Users Group ry, Turku, Finland


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.fra

Description

French language locale by Patrick Kremer.


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.hrv

Description

Croatian language locale by Klara Makovac 1997/07/02


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.hun

Description

Hungarian language locale by Zsolt Varga.


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.ita

Description

Italian language locale by Francesco Chemolli


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.jpn

Description

Japanese language locale.


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.mri

Description

Maaori (New Zealand) language locale by Jason Rumney


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.nld

Description

Dutch language locale by Stephen R. van den Berg


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.nor

Description

Norwegian language locale


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.pol

Description

Polish language locale by Piotr Klaban.


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.por

Description

Portuguese language locale


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.rus

Description

Russian language locale


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.slv

Description

Slovenian language locale by Iztok Umek 7. 8. 1997


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.spa

Description

Spanish language locale


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.srp

Description

Serbian language locale by Goran Opacic 1996/12/11


Inherit "abstract"

inherit "abstract"

  Module Locale.Language.swe

Description

Swedish language locale


Inherit "abstract"

inherit "abstract"

  Module Locale.Charset

Description

The Charset module supports a wide variety of different character sets, and it is flexible in regard of the names of character sets it accepts. The character case is ignored, as are the most common non-alaphanumeric characters appearing in character set names. E.g. "iso-8859-1" works just as well as "ISO_8859_1". All encodings specified in RFC 1345 are supported.

First of all the Charset module is capable of handling the following encodings of Unicode:

  • utf7, utf8, utf16, utf16be, utf16le, utf75 and utf7½

    UTF encodings

  • shiftjis, euc-kr, euc-cn and euc-jp

Most, if not all, of the relevant code pages are represented, as the following list shows. Prefix the numbers as noted in the list to get the wanted codec:

  • 037, 038, 273, 274, 275, 277, 278, 280, 281, 284, 285, 290, 297, 367, 420, 423, 424, 437, 500, 819, 850, 851, 852, 855, 857, 860, 861, 862, 863, 864, 865, 866, 868, 869, 870, 871, 880, 891, 903, 904, 905, 918, 950 and 1026

    These may be prefixed with "cp" or "ibm".

  • 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257 and 1258

    These may be prefixed with "cp", "ibm" or "windows".

+359 more.


Method decoder

Decoder Locale.Charset.decoder(string name)

Description

Returns a charset decoder object.

Parameter name

The name of the character set to decode from. Supported charsets include (not all supported charsets are enumerable): "iso_8859-1:1987", "iso_8859-1:1998", "iso-8859-1", "iso-ir-100", "latin1", "l1", "ansi_x3.4-1968", "iso_646.irv:1991", "iso646-us", "iso-ir-6", "us", "us-ascii", "ascii", "cp367", "ibm367", "cp819", "ibm819", "iso-2022" (of various kinds), "utf-7", "utf-8" and various encodings as described by RFC1345.

Throws

If the asked-for name was not supported, an error is thrown.


Method encoder

Encoder Locale.Charset.encoder(string name, string|void replacement, function(string:string)|void repcb)

Description

Returns a charset encoder object.

Parameter name

The name of the character set to encode to. Supported charsets include (not all supported charsets are enumerable): "iso_8859-1:1987", "iso_8859-1:1998", "iso-8859-1", "iso-ir-100", "latin1", "l1", "ansi_x3.4-1968", "iso_646.irv:1991", "iso646-us", "iso-ir-6", "us", "us-ascii", "ascii", "cp367", "ibm367", "cp819", "ibm819", "iso-2022" (of various kinds), "utf-7", "utf-8" and various encodings as described by RFC1345.

Parameter replacement

The string to use for characters that cannot be represented in the charset. It's used when repcb is not given or when it returns zero. If no replacement string is given then an error is thrown instead.

Parameter repcb

A function to call for every character that cannot be represented in the charset. If specified it's called with one argument - a string containing the character in question. If it returns a string then that one will replace the character in the output. If it returns something else then the replacement argument will be used to decide what to do.

Throws

If the asked-for name was not supported, an error is thrown.


Method decoder_from_mib

Decoder Locale.Charset.decoder_from_mib(int mib)

Description

Returns a decoder for the encoding schema denoted by MIB mib .


Method encoder_from_mib

Encoder Locale.Charset.encoder_from_mib(int mib, string|void replacement, function(string:string)|void repcb)

Description

Returns an encoder for the encoding schema denoted by MIB mib .

  CLASS Locale.Charset.Decoder

Description

Virtual base class for charset decoders.

Example

string win1252_to_string( string data ) { return Locale.Charset.decoder("windows-1252")->feed( data )->drain(); }


Method feed

this_program feed(string s)

Description

Feeds a string to the decoder.

Parameter s

String to be decoded.

Returns

Returns the current object, to allow for chaining of calls.


Method drain

string drain()

Description

Get the decoded data, and reset buffers.

Returns

Returns the decoded string.


Method clear

this_program clear()

Description

Clear buffers, and reset all state.

Returns

Returns the current object to allow for chaining of calls.

  CLASS Locale.Charset.Encoder

Description

Virtual base class for charset encoders.


Inherit Decoder

inherit Decoder : Decoder

Description

An encoder only differs from a decoder in that it has an extra function.


Method set_replacement_callback

void set_replacement_callback(function(string:string) rc)

Description

Change the replacement callback function.

Parameter rc

Function that is called to encode characters outside the current character encoding.

  Module Gmp

Description

GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. http://www.swox.com/gmp/


Method fac

Gmp.mpz Gmp.fac(int x)

Description

Returns the factorial of x (x !).

  CLASS Gmp.bignum

Description

This program is used by the internal auto-bignum conversion. It can be used to explicitly type integers that are too big to be INT_TYPE. Best is however to not use this program unless you really know what you are doing.

  CLASS Gmp.mpz

Description

Gmp.mpz implements very large integers. In fact, the only limitation on these integers is the available memory. The mpz object implements all the normal integer operations.


Method create

void Gmp.mpz()
void Gmp.mpz(string|int|float|object value)
void Gmp.mpz(string value, int(2..36)|int(256..256) base)

Description

Create and initialize a Gmp.mpz object.

Parameter value

Initial value. If no value is specified, the object will be initialized to zero.

Parameter base

Base the value is specified in. The default base is base 10. The base can be either a value in the range [2..36] (inclusive), in which case the numbers are taken from the ASCII range 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ (case-insensitive), or the value 256, in which case value is taken to be the binary representation in network byte order.

Note

Leading zeroes in value are not significant. In particular leading NUL characters are not preserved in base 256 mode.


Method cast_to_int

int cast_to_int()


Method __hash

int __hash()


Method cast_to_float

float cast_to_float()


Method cast_to_string

string cast_to_string()


Method digits

string digits(void|int(2..36)|int(256..256) base)

Description

This function converts an mpz to a string. If a base is given the number will be represented in that base. Valid bases are 2-36 and 256. The default base is 10.

See also

cast_to_string


Method _sprintf

string _sprintf(int ind, mapping opt)


Method _is_type

int(0..1) _is_type(string type)


Method size

int size(void|int base)

Description

This function returns how long the mpz would be represented in the specified base . The default base is 2.


Method cast

mixed cast(string type)

Description

It is possible to cast an mpz to a string, int or float.

See also

cast_to_int , cast_to_float , cast_to_string


Method `+

Gmp.mpz `+(int|float|Gmp.mpz ... x)


Method ``+

Gmp.mpz ``+(int|float|Gmp.mpz ... x)


Method `+=

Gmp.mpz `+=(int|float|Gmp.mpz ... x)


Method `*

Gmp.mpz `*(int|float|Gmp.mpz ... x)


Method ``*

Gmp.mpz ``*(int|float|Gmp.mpz ... x)


Method `*=

Gmp.mpz `*=(int|float|Gmp.mpz ... x)


Method gcd

Gmp.mpz gcd(object|int|float|string arg)

Description

This function returns the greatest common divisor for arg and mpz.


Method `-

Gmp.mpz `-(int|float|Gmp.mpz ... x)


Method ``-

Gmp.mpz ``-(int|float|Gmp.mpz ... x)


Method `/

Gmp.mpz `/(int|float|Gmp.mpz ... x)


Method ``/

Gmp.mpz ``/(int|float|Gmp.mpz ... x)


Method `%

Gmp.mpz `%(int|float|Gmp.mpz ... x)


Method ``%

Gmp.mpz ``%(int|float|Gmp.mpz ... x)


Method gcdext

array(Gmp.mpz) gcdext(int|float|Gmp.mpz x)


Method gcdext2

array(Gmp.mpz) gcdext2(int|float|Gmp.mpz x)


Method invert

Gmp.mpz invert(int|float|Gmp.mpz x)


Method `&

Gmp.mpz `&(int|float|Gmp.mpz ... x)


Method `|

Gmp.mpz `|(int|float|Gmp.mpz ... x)


Method `^

Gmp.mpz `^(int|float|Gmp.mpz ... x)


Method `~

Gmp.mpz `~()


Method `>

int(0..1) `>(mixed with)


Method `<

int(0..1) `<(mixed with)


Method `>=

int(0..1) `>=(mixed with)


Method `<=

int(0..1) `<=(mixed with)


Method `==

int(0..1) `==(mixed with)


Method `!=

int(0..1) `!=(mixed with)


Method probably_prime_p

int(0..1) probably_prime_p()

Description

This function returns 1 if mpz is a prime, and 0 most of the time if it is not.


Method small_factor

int small_factor(void|int(1..) limit)


Method next_prime

Gmp.mpz next_prime(void|int count, void|int limit)


Method sgn

int sgn()


Method sqrt

Gmp.mpz sqrt()

Description

This function return the the truncated integer part of the square root of the value of mpz.


Method sqrtrem

array(Gmp.mpz) sqrtrem()


Method `<<

Gmp.mpz `<<(int|float|Gmp.mpz x)


Method `>>

Gmp.mpz `>>(int|float|Gmp.mpz x)


Method ``<<

Gmp.mpz ``<<(int|float|Gmp.mpz x)


Method ``>>

Gmp.mpz ``>>(int|float|Gmp.mpz x)


Method powm

Gmp.mpz powm(int|string|float|Gmp.mpz a, int|string|float|Gmp.mpz b)

Description

This function returns ( mpz ** a ) % b.


Method pow

Gmp.mpz pow(int|float|Gmp.mpz x)


Method `!

int(0..1) `!()


Method popcount

int popcount()

Description

For values >= 0, returns the population count (the number of set bits). For negative values (who have an infinite number of leading ones in a binary representation), -1 is returned.


Method _random

Gmp.mpz _random()

  CLASS Gmp.mpf

Description

GMP floating point number.

The mantissa of each float has a user-selectable precision, limited only by available memory. Each variable has its own precision, and that can be increased or decreased at any time.

The exponent of each float is a fixed precision, one machine word on most systems. In the current implementation the exponent is a count of limbs, so for example on a 32-bit system this means a range of roughly 2^-68719476768 to 2^68719476736, or on a 64-bit system this will be greater.

Each variable keeps a size for the mantissa data actually in use. This means that if a float is exactly represented in only a few bits then only those bits will be used in a calculation, even if the selected precision is high.

All calculations are performed to the precision of the destination variable. Each function is defined to calculate with "infinite precision" followed by a truncation to the destination precision, but of course the work done is only what's needed to determine a result under that definition.

The precision selected for a variable is a minimum value, GMP may increase it a little to facilitate efficient calculation. Currently this means rounding up to a whole limb, and then sometimes having a further partial limb, depending on the high limb of the mantissa. But applications shouldn't be concerned by such details.

The mantissa in stored in binary, as might be imagined from the fact precisions are expressed in bits. One consequence of this is that decimal fractions like 0.1 cannot be represented exactly. The same is true of plain IEEE double floats. This makes both highly unsuitable for calculations involving money or other values that should be exact decimal fractions. (Suitably scaled integers, or perhaps rationals, are better choices.)

mpf functions and variables have no special notion of infinity or not-a-number, and applications must take care not to overflow the exponent or results will be unpredictable. This might change in a future release.

Note that the mpf functions are not intended as a smooth extension to IEEE P754 arithmetic. In particular results obtained on one computer often differ from the results on a computer with a different word size.


Method create

void Gmp.mpf(void|int|string|float|object x, void|int(0..) precision)
void Gmp.mpf(string x, int(0..) precision, int(2..36) base)


Method __hash

int __hash()


Method get_int

int|object get_int()


Method get_float

float get_float()

Description

Returns the value of the object as a float.


Method get_string

string get_string()


Method _sprintf

string _sprintf(int c, mapping flags)


Method _is_type

int(0..1) _is_type(string arg)

Description

The Gmp.mpf object will claim to be a "float".

FIXME

Perhaps it should also return true for "object"?


Method cast

mixed cast(string to)


Method `+

Gmp.mpf `+(int|float|object ... a)


Method `+=

Gmp.mpf `+=(int|float|object ... a)


Method set_precision

Gmp.mpf set_precision(int(0..) prec)

Description

Sets the precision of the current object to be at least prec bits. The precision is limited to 128Kb. The current object will be returned.


Method get_precision

int(0..) get_precision()

Description

Returns the current precision, in bits.


Method `*

Gmp.mpf `*(int|float|object ... a)


Method ``*

Gmp.mpf ``*(int|float|object ... a)


Method `*=

Gmp.mpf `*=(int|float|object ... a)


Method `-

Gmp.mpf `-(int|float|object ... a)


Method ``-

Gmp.mpf ``-(int|float|object sv)


Method `/

Gmp.mpf `/(int|float|object ... a)


Method ``/

Gmp.mpf ``/(int|float|object sv)


Method `~

Gmp.mpf `~()


Method `>

int(0..1) `>(mixed q)


Method `<

int(0..1) `<(mixed q)


Method `>=

int(0..1) `>=(mixed q)


Method `<=

int(0..1) `<=(mixed q)


Method `==

int(0..1) `==(mixed q)


Method `!=

int(0..1) `!=(mixed q)


Method sgn

int sgn()


Method `!

int(0..1) `!()

  CLASS Gmp.mpq

Description

Rational number stored in canonical form. The canonical from means that the denominator and the numerator have no common factors, and that the denominator is positive. Zero has the unique representation 0/1. All functions canonicalize their result.


Method create

void Gmp.mpq(void|string|int|float|Gmp.mpz|Gmp.mpq x)
void Gmp.mpq(int numerator, int denominator)
void Gmp.mpq(string x, int base)


Method get_int

int get_int()


Method __hash

int __hash()


Method get_float

float get_float()


Method get_string

string get_string()


Method _sprintf

string _sprintf(int c, mapping flags)


Method _is_type

int(0..1) _is_type(string arg)


Method cast

int|string|float|object cast(string s)


Method `+

Gmp.mpq `+(int|float|object ... a)


Method ``+

Gmp.mpq ``+(int|float|object ... a)


Method `+=

Gmp.mpq `+=(int|float|object ... a)


Method `*

Gmp.mpq `*(int|float|object ... a)


Method ``*

Gmp.mpq ``*(int|float|object ... a)


Method `*=

Gmp.mpq `*=(int|float|object ... a)


Method `-

Gmp.mpq `-(int|float|object ... a)


Method ``-

Gmp.mpq ``-(int|float|object sv)


Method `/

Gmp.mpq `/(int|float|object ... a)


Method ``/

Gmp.mpq ``/(int|float|object sv)


Method `%

Gmp.mpq `%(int|float|object ... a)

Description

a%b =  a -  floor(a/b)*b 


Method ``%

Gmp.mpq ``%(int|float|object a)


Method invert

Gmp.mpq invert()


Method `~

Gmp.mpq `~()

Description

Defined as -1-x.


Method `>

int(0..1) `>(mixed q)


Method `<

int(0..1) `<(mixed q)


Method `>=

int(0..1) `>=(mixed q)


Method `<=

int(0..1) `<=(mixed q)


Method `==

int(0..1) `==(mixed q)


Method `!=

int(0..1) `!=(mixed q)


Method sgn

int(-1..1) sgn()


Method `!

int(0..1) `!(mixed q)

  Module Gz

Description

The Gz module contains functions to compress and uncompress strings using the same algorithm as the program gzip. Compressing can be done in streaming mode or all at once.

The Gz module consists of two classes; Gz.deflate and Gz.inflate. Gz.deflate is used to pack data and Gz.inflate is used to unpack data. (Think "inflatable boat")

Note

Note that this module is only available if the gzip library was available when Pike was compiled.

Note that although these functions use the same algorithm as gzip, they do not use the exact same format, so you cannot directly unzip gzipped files with these routines. Support for this will be added in the future.


Inherit "___"

inherit "___"


Method crc32

int Gz.crc32(string data, void|int start_value)

Description

This function calculates the standard ISO3309 Cyclic Redundancy Check.

  CLASS Gz._file

Description

Low-level implementation of read/write support for GZip files


Method open

int open(string|int|Stdio.Stream file, void|string mode)

Description

Opens a file for I/O.

Parameter file

The filename or an open filedescriptor or Stream for the GZip file to use.

Parameter mode

Mode for the fileoperations. Defaults to read only.

Note

If the object already has been opened, it will first be closed.


Method create

void Gz._file(void|string|Stdio.Stream gzFile, void|string mode)

Description

Opens a gzip file for reading.


Method close

int close()

Description

closes the file

Returns

1 if successful


Method read

int|string read(int len)

Description

Reads len (uncompressed) bytes from the file. If read is unsuccessful, 0 is returned.


Method write

int write(string data)

Description

Writes the data to the file.

Returns

the number of bytes written to the file.


Method seek

int seek(int pos, void|int type)

Description

Seeks within the file.

Parameter pos

Position relative to the searchtype.

Parameter type

SEEK_SET = set current position in file to pos SEEK_CUR = new position is current+pos SEEK_END is not supported.

Returns

New position or negative number if seek failed.


Method tell

int tell()

Returns

the current position within the file.


Method eof

int(0..1) eof()

Returns

1 if EOF has been reached.


Method setparams

int setparams(int level, int strategy)

Description

Sets the encoding level and strategy

Parameter level

Level of the compression. 0 is the least compression, 9 is max. 8 is default.

Parameter strategy

Set strategy for encoding to one of the following: DEFAULT_STRATEGY FILTERED HUFFMAN_ONLY

  CLASS Gz.File

Description

Allows the user to open a Gzip archive and read and write it's contents in an uncompressed form, emulating the Stdio.File interface.

Note

An important limitation on this class is that it may only be used for reading or writing, not both at the same time. Please also note that if you want to reopen a file for reading after a write, you must close the file before calling open or strange effects might be the result.


Inherit _file

inherit _file : _file


Method create

void Gz.File(void|string|int|Stdio.Stream file, void|string mode)

Parameter file

Filename or filedescriptor of the gzip file to open, or an already open Stream.

Parameter mode

mode for the file. Defaults to "rb".

See also

open Stdio.File


Method open

int open(string|int|Stdio.Stream file, void|string mode)

Parameter file

Filename or filedescriptor of the gzip file to open, or an already open Stream.

Parameter mode

mode for the file. Defaults to "rb". May be one of the following:

rb

read mode

wb

write mode

ab

append mode

For the wb and ab mode, additional parameters may be specified. Please se zlib manual for more info.

Returns

non-zero if successful.


Method read

int|string read(void|int length)

Description

Reads data from the file. If no argument is given, the whole file is read.

  CLASS Gz.deflate

Description

Gz_deflate is a builtin program written in C. It interfaces the packing routines in the libz library.

Note

This program is only available if libz was available and found when Pike was compiled.

See also

Gz.inflate()


Method create

void Gz.deflate(int(0..9)|void level, int|void strategy)

Description

If given, level should be a number from 0 to 9 indicating the packing / CPU ratio. Zero means no packing, 2-3 is considered 'fast', 6 is default and higher is considered 'slow' but gives better packing.

This function can also be used to re-initialize a Gz.deflate object so it can be re-used.

If the argument is negative, no headers will be emitted. This is needed to produce ZIP-files, as an example. The negative value is then negated, and handled as a positive value.

strategy , if given, should be one of DEFAULT_STRATEGY, FILTERED or HUFFMAN_ONLY.


Method deflate

string deflate(string data, int|void flush)

Description

This function performs gzip style compression on a string data and returns the packed data. Streaming can be done by calling this function several times and concatenating the returned data.

The optional argument flush should be one of the following:

Gz.NO_FLUSH

Only data that doesn't fit in the internal buffers is returned.

Gz.PARTIAL_FLUSH

All input is packed and returned.

Gz.SYNC_FLUSH

All input is packed and returned.

Gz.FINISH

All input is packed and an 'end of data' marker is appended.


See also

Gz.inflate->inflate()

  CLASS Gz.inflate

Description

Gz_deflate is a builtin program written in C. It interfaces the unpacking routines in the libz library.

Note

This program is only available if libz was available and found when Pike was compiled.

See also

deflate


Method create

void Gz.inflate(int|void window_size)

Parameter magic

The window_size value is passed down to inflateInit2 in zlib.

If the argument is negative, no header checks are done, and no verification of the data will be done either. This is needed for uncompressing ZIP-files, as an example. The negative value is then negated, and handled as a positive value.

Positive arguments set the maximum dictionary size to an exponent of 2, such that 8 (the minimum) will cause the window size to be 256, and 15 (the maximum, and default value) will cause it to be 32Kb. Setting this to anything except 15 is rather pointless in Pike.

It can be used to limit the amount of memory that is used to uncompress files, but 32Kb is not all that much in the great scheme of things.

To decompress files compressed with level 9 compression, a 32Kb window size is needed. level 1 compression only requires a 256 byte window.


Method inflate

string inflate(string data)

Description

This function performs gzip style decompression. It can inflate a whole file at once or in blocks.

Example

// whole file write(Gz_inflate()->inflate(stdin->read(0x7fffffff));

// streaming (blocks) function inflate=Gz_inflate()->inflate; while(string s=stdin->read(8192)) write(inflate(s));

See also

Gz.deflate->deflate()


Method end_of_stream

string end_of_stream()

Description

This function returns 0 if the end of stream marker has not yet been encountered, or a string (possibly empty) containg any extra data received following the end of stream marker if the marker has been encountered. If the extra data is not needed, the result of this function can be treated as a logical value.

  Module MIME

Description

RFC1521, the Multipurpose Internet Mail Extensions memo, defines a structure which is the base for all messages read and written by modern mail and news programs. It is also partly the base for the HTTP protocol. Just like RFC822, MIME declares that a message should consist of two entities, the headers and the body. In addition, the following properties are given to these two entities:

Headers
  • A MIME-Version header must be present to signal MIME compatibility

  • A Content-Type header should be present to describe the nature of the data in the message body. Seven major types are defined, and an extensive number of subtypes are available. The header can also contain attributes specific to the type and subtype.

  • A Content-Transfer-Encoding may be present to notify that the data of the body is encoded in some particular encoding.

Body
  • Raw data to be interpreted according to the Content-Type header

  • Can be encoded using one of several Content-Transfer-Encodings to allow transport over non 8bit clean channels

The MIME module can extract and analyze these two entities from a stream of bytes. It can also recreate such a stream from these entities. To encapsulate the headers and body entities, the class MIME.Message is used. An object of this class holds all the headers as a mapping from string to string, and it is possible to obtain the body data in either raw or encoded form as a string. Common attributes such as message type and text char set are also extracted into separate variables for easy access.

The Message class does not make any interpretation of the body data, unless the content type is multipart. A multipart message contains several individual messages separated by boundary strings. The Message->create method of the Message class will divide a multipart body on these boundaries, and then create individual Message objects for each part. These objects will be collected in the array Message->body_parts within the original Message object. If any of the new Message objects have a body of type multipart, the process is of course repeated recursively.


Method decode_base64

string MIME.decode_base64(string encoded_data)

Description

This function decodes data encoded using the base64 transfer encoding.

See also

MIME.encode_base64() , MIME.decode()


Method encode_base64

string MIME.encode_base64(string data, void|int no_linebreaks)

Description

This function encodes data using the base64 transfer encoding.

If a nonzero value is passed as no_linebreaks , the result string will not contain any linebreaks.

See also

MIME.decode_base64() , MIME.encode()


Method decode_qp

string MIME.decode_qp(string encoded_data)

Description

This function decodes data encoded using the quoted-printable (a.k.a. quoted-unreadable) transfer encoding.

See also

MIME.encode_qp() , MIME.decode()


Method encode_qp

string MIME.encode_qp(string data, void|int no_linebreaks)

Description

This function encodes data using the quoted-printable (a.k.a. quoted-unreadable) transfer encoding.

If a nonzero value is passed as no_linebreaks , the result string will not contain any linebreaks.

Note

Please do not use this function. QP is evil, and there's no excuse for using it.

See also

MIME.decode_qp() , MIME.encode()


Method decode_uue

string MIME.decode_uue(string encoded_data)

Description

This function decodes data encoded using the x-uue transfer encoding. It can also be used to decode generic UUEncoded files.

See also

MIME.encode_uue() , MIME.decode()


Method encode_uue

string MIME.encode_uue(string encoded_data, void|string filename)

Description

This function encodes data using the x-uue transfer encoding.

The optional argument filename specifies an advisory filename to include in the encoded data, for extraction purposes.

This function can also be used to produce generic UUEncoded files.

See also

MIME.decode_uue() , MIME.encode()


Method tokenize

array(string|int) MIME.tokenize(string header)

Description

A structured header field, as specified by RFC822, is constructed from a sequence of lexical elements.

These are:

individual special characters

quoted-strings

domain-literals

comments

atoms

This function will analyze a string containing the header value, and produce an array containing the lexical elements.

Individual special characters will be returned as characters (i.e. ints).

Quoted-strings, domain-literals and atoms will be decoded and returned as strings.

Comments are not returned in the array at all.

Note

As domain-literals are returned as strings, there is no way to tell the domain-literal [127.0.0.1] from the quoted-string "[127.0.0.1]". Hopefully this won't cause any problems. Domain-literals are used seldom, if at all, anyway...

The set of special-characters is the one specified in RFC1521 (i.e. "<", ">", "@", ",", ";", ":", "\", "/", "?", "="), and not the set specified in RFC822.

See also

MIME.quote() , tokenize_labled() , decode_words_tokenized_remapped() .


Method tokenize_labled

array(array(string|int)) MIME.tokenize_labled(string header)

Description

Similar to tokenize() , but labels the contents, by making arrays with two elements; the first a label, and the second the value that tokenize() would have put there, except for that comments are kept.

The following labels exist:

"encoded-word"

Word encoded according to =?...

"special"

Special character.

"word"

Word.

"domain-literal"

Domain literal.

"comment"

Comment.


See also

MIME.quote() , tokenize() , decode_words_tokenized_labled_remapped()


Method quote

string MIME.quote(array(string|int) lexical_elements)

Description

This function is the inverse of the MIME.tokenize function.

A header field value is constructed from a sequence of lexical elements. Characters (ints) are taken to be special-characters, whereas strings are encoded as atoms or quoted-strings, depending on whether they contain any special characters.

Note

There is no way to construct a domain-literal using this function. Neither can it be used to produce comments.

See also

MIME.tokenize()


Method quote_labled

string MIME.quote_labled(array(array(string|int)) tokens)

Description

This function performs the reverse operation of tokenize_labled() .

See also

MIME.quote() , MIME.tokenize_labled()


Inherit ___MIME

inherit ___MIME : ___MIME


Method generate_boundary

string MIME.generate_boundary()

Description

This function will create a string that can be used as a separator string for multipart messages. The generated string is guaranteed not to appear in base64, quoted-printable, or x-uue encoded data. It is also unlikely to appear in normal text. This function is used by the cast method of the Message class if no boundary string is specified.


Method decode

string MIME.decode(string data, string encoding)

Description

Extract raw data from an encoded string suitable for transport between systems.

The encoding can be any of

"7bit"
"8bit"
"base64"
"binary"
"quoted-printable"
"x-uue"
"x-uuencode"

The encoding string is not case sensitive.

See also

MIME.encode()


Method encode

string MIME.encode(string data, string encoding, void|string filename, void|int no_linebreaks)

Description

Encode raw data into something suitable for transport to other systems.

The encoding can be any of

"7bit"
"8bit"
"base64"
"binary"
"quoted-printable"
"x-uue"
"x-uuencode"

The encoding string is not case sensitive. For the x-uue encoding, an optional filename string may be supplied.

If a nonzero value is passed as no_linebreaks , the result string will not contain any linebreaks (base64 and quoted-printable only).

See also

MIME.decode()


Method decode_word

array(string) MIME.decode_word(string word)

Description

Extracts the textual content and character set from an encoded word as specified by RFC1522. The result is an array where the first element is the raw text, and the second element the name of the character set. If the input string is not an encoded word, the result is still an array, but the char set element will be set to 0.

Note

Note that this function can only be applied to individual encoded words.

See also

MIME.encode_word()


Method encode_word

string MIME.encode_word(string|array(string) word, string encoding)

Description

Create an encoded word as specified in RFC1522 from an array containing a raw text string and a char set name.

The text will be transfer encoded according to the encoding argument, which can be either "base64" or "quoted-printable" (or either "b" or "q" for short).

If either the second element of the array (the char set name), or the encoding argument is 0, the raw text is returned as is.

See also

MIME.decode_word()


Method decode_words_text

array(array(string)) MIME.decode_words_text(string txt)

Description

Separates a header value containing text into units and calls MIME.decode_word() on them. The result is an array where each element is a result from decode_word() .

See also

MIME.decode_words_tokenized MIME.decode_words_text_remapped


Method decode_words_text_remapped

string MIME.decode_words_text_remapped(string txt)

Description

Like MIME.decode_words_text() , but the extracted strings are also remapped from their specified character encoding into UNICODE, and then pasted together. The result is thus a string in the original text format, without RFC1522 escapes, and with all characters in UNICODE encoding.

See also

MIME.decode_words_tokenized_remapped


Method decode_words_tokenized

array(array(string)|int) MIME.decode_words_tokenized(string phrase)

Description

Tokenizes a header value just like MIME.tokenize() , but also converts encoded words using MIME.decode_word() . The result is an array where each element is either an int representing a special character, or an array as returned by decode_word() representing an atom or a quoted string.

See also

MIME.decode_words_tokenized_labled MIME.decode_words_tokenized_remapped MIME.decode_words_text


Method decode_words_tokenized_remapped

array(string|int) MIME.decode_words_tokenized_remapped(string phrase)

Description

Like MIME.decode_words_tokenized() , but the extracted atoms are also remapped from their specified character encoding into UNICODE. The result is thus identical to that of MIME.tokenize() , but without RFC1522 escapes, and with all characters in UNICODE encoding.

See also

MIME.decode_words_tokenized_labled_remapped MIME.decode_words_text_remapped


Method decode_words_tokenized_labled

array(array(string|int|array(array(string)))) MIME.decode_words_tokenized_labled(string phrase)

Description

Tokenizes and labels a header value just like MIME.tokenize_labled() , but also converts encoded words using MIME.decode_word() . The result is an array where each element is an array of two or more elements, the first being the label. The rest of the array depends on the label:

"special"

One additional element, containing the character code for the special character as an int.

"word"

Two additional elements, the first being the word, and the second being the character set of this word (or 0 if it did not originate from an encoded word).

"domain-literal"

One additional element, containing the domain literal as a string.

"comment"

One additional element, containing an array as returned by MIME.decode_words_text() .


See also

MIME.decode_words_tokenized_labled_remapped


Method decode_words_tokenized_labled_remapped

array(array(string|int)) MIME.decode_words_tokenized_labled_remapped(string phrase)

Description

Like MIME.decode_words_tokenized_labled() , but the extracted words are also remapped from their specified character encoding into UNICODE. The result is identical to that of MIME.tokenize_labled() , but without RFC1522 escapes, and with all characters in UNICODE encoding.


Method encode_words_text

string MIME.encode_words_text(array(string|array(string)) phrase, string encoding)

Description

The inverse of decode_words_text() , this function accepts an array of strings or pairs of strings which will each be encoded by encode_word() , after which they are all pasted together.

Parameter encoding

Either "base64" or "quoted-printable" (or either "b" or "q" for short).


Method encode_words_quoted

string MIME.encode_words_quoted(array(array(string)|int) phrase, string encoding)

Description

The inverse of decode_words_tokenized() , this functions accepts an array like the argument to quote() , but instead of simple strings for atoms and quoted-strings, it will also accept pairs of strings to be passed to encode_word() .

Parameter encoding

Either "base64" or "quoted-printable" (or either "b" or "q" for short).

See also

MIME.encode_words_quoted_labled()


Method encode_words_quoted_labled

string MIME.encode_words_quoted_labled(array(array(string|int|array(string|array(string)))) phrase, string encoding)

Description

The inverse of decode_words_tokenized_labled() , this functions accepts an array like the argument to quote_labled() , but "word" labled elements can optionally contain an additional string element specifying a character set, in which case an encoded-word will be used. Also, the format for "comment" labled elements is entirely different; instead of a single string, an array of strings or pairs like the first argument to encode_words_text() is expected.

Parameter encoding

Either "base64" or "quoted-printable" (or either "b" or "q" for short).

See also

MIME.encode_words_quoted()


Method guess_subtype

string MIME.guess_subtype(string type)

Description

Provide a reasonable default for the subtype field.

Some pre-RFC1521 mailers provide only a type and no subtype in the Content-Type header field. This function can be used to obtain a reasonable default subtype given the type of a message. (This is done automatically by the MIME.Message class.)

Currently, the function uses the following guesses:

"text"

"plain"

"message"

"rfc822"

"multipart"

"mixed"



Method parse_headers

array(mapping(string:string)|string) MIME.parse_headers(string message)
array(mapping(string:array(string))|string) MIME.parse_headers(string message, int(1..1) use_multiple)

Description

This is a low level function that will separate the headers from the body of an encoded message. It will also translate the headers into a mapping. It will however not try to analyze the meaning of any particular header. This means that the body is returned as is, with any transfer-encoding intact.

It is possible to call this function with just the header part of a message, in which case an empty body will be returned.

The result is returned in the form of an array containing two elements. The first element is a mapping containing the headers found. The second element is a string containing the body.

Headers that occurr multiple times will have their contents NUL separated, unless use_multiple has been specified, in which case the contents will be arrays.


Method reconstruct_partial

int|object MIME.reconstruct_partial(array(object) collection)

Description

This function will attempt to reassemble a fragmented message from its parts.

The array collection should contain MIME.Message objects forming a complete set of parts for a single fragmented message. The order of the messages in the array is not important, but every part must exist at least once.

Should the function succeed in reconstructing the original message, a new MIME.Message object will be returned.

If the function fails to reconstruct an original message, an integer indicating the reason for the failure will be returned:

0

Returned if empty collection is passed in, or one that contains messages which are not of type message/partial, or parts of different fragmented messages.

1..

If more fragments are needed to reconstruct the entire message, the number of additional messages needed is returned.

-1

If more fragments are needed, but the function can't determine exactly how many.


Note

Note that the returned message may in turn be a part of another, larger, fragmented message.

See also

MIME.Message->is_partial()


Method ext_to_media_type

string MIME.ext_to_media_type(string extension)

Description

Returns the MIME media type for the provided filename extension . Currently 469 file extensions are known to this method. Zero will be returned on unknown file extensions.

  CLASS MIME.Message

Description

This class is used to hold a decoded MIME message.



Variable headers

mapping(string:string) headers

Description

This mapping contains all the headers of the message.

The key is the header name (in lower case) and the value is the header value.

Although the mapping contains all headers, some particular headers get special treatment by the module and should not be accessed through this mapping. These fields are currently:

"content-type"
"content-disposition"
"content-length"
"content-transfer-encoding"

The contents of these fields can be accessed and/or modified through a set of variables and methods available for this purpose.

See also

type , subtype , charset , boundary , transfer_encoding , params , disposition , disp_params , setencoding() , setparam() , setdisp_param() , setcharset() , setboundary()


Variable body_parts

array(object) body_parts

Description

If the message is of type multipart, this is an array containing one Message object for each part of the message. If the message is not a multipart, this field is 0 (zero).

See also

type , boundary


Variable boundary

string boundary

Description

For multipart messages, this Content-Type parameter gives a delimiter string for separating the individual messages. As multiparts are handled internally by the module, you should not need to access this field.

See also

setboundary()


Variable charset

string charset

Description

One of the possible parameters of the Content-Type header is the charset attribute. It determines the character encoding used in bodies of type text.

If there is no Content-Type header, the value of this field is "us-ascii".

See also

type


Variable type

string type

Description

The Content-Type header contains a type, a subtype, and optionally some parameters. This field contains the type attribute extracted from the header.

If there is no Content-Type header, the value of this field is "text".

See also

subtype , params


Variable subtype

string subtype

Description

The Content-Type header contains a type, a subtype, and optionally some parameters. This field contains the subtype attribute extracted from the header.

If there is no Content-Type header, the value of this field is "plain".

See also

type , params


Variable transfer_encoding

string transfer_encoding

Description

The contents of the Content-Transfer-Encoding header.

If no Content-Transfer-Encoding header is given, this field is 0 (zero).

Transfer encoding and decoding is done transparently by the module, so this field should be interesting only to applications wishing to do auto conversion of certain transfer encodings.

See also

setencoding()


Variable params

mapping(string:string) params

Description

A mapping containing all the additional parameters to the Content-Type header.

Some of these parameters have fields of their own, which should be accessed instead of this mapping wherever applicable.

See also

charset , boundary , setparam()


Variable disposition

string disposition

Description

The first part of the Content-Disposition header, hinting on how this part of a multipart message should be presented in an interactive application.

If there is no Content-Disposition header, this field is 0.


Variable disp_params

mapping(string:string) disp_params

Description

A mapping containing all the additional parameters to the Content-Disposition header.

See also

setdisp_param() , get_filename()


Method get_filename

string get_filename()

Description

This method tries to find a suitable filename should you want to save the body data to disk.

It will examine the filename attribute of the Content-Disposition header, and failing that the name attribute of the Content-Type header. If neither attribute is set, the method returns 0.

Note

An interactive application should always query the user for the actual filename to use. This method may provide a reasonable default though.


Method is_partial

array(string|int) is_partial()

Description

If this message is a part of a fragmented message (i.e. has a Content-Type of message/partial), an array with three elements is returned.

The first element is an identifier string. This string should be used to group this message with the other fragments of the message (which will have the same id string).

The second element is the sequence number of this fragment. The first part will have number 1, the next number 2 etc.

The third element of the array is either the total number of fragments that the original message has been split into, or 0 of this information is not available.

If this method is called in a message that is not a part of a fragmented message, it will return 0.

See also

MIME.reconstruct_partial()


Method setdata

void setdata(string data)

Description

Replaces the body entity of the data with a new piece of raw data.

The new data should comply to the format indicated by the type and subtype attributes.

Note

Do not use this method unless you know what you are doing.

See also

getdata()


Method getdata

string getdata()

Description

This method returns the raw data of the message body entity.

The type and subtype attributes indicate how this data should be interpreted.

See also

getencoded()


Method getencoded

string getencoded()

Description

This method returns the data of the message body entity, encoded using the current transfer encoding.

You should never have to call this function.

See also

getdata()


Method setencoding

void setencoding(string encoding)

Description

Select a new transfer encoding for this message.

The Content-Transfer-Encoding header will be modified accordingly, and subsequent calls to getencoded will produce data encoded using the new encoding.

See MIME.encode() for a list of valid encodings.

See also

getencoded() , MIME.encode()


Method setparam

void setparam(string param, string value)

Description

Set or modify the named parameter of the Content-Type header.

Common parameters include charset for text messages, and boundary for multipart messages.

Note

It is not allowed to modify the Content-Type header directly, please use this function instead.

See also

setcharset() , setboundary() , setdisp_param()


Method setdisp_param

void setdisp_param(string param, string value)

Description

Set or modify the named parameter of the Content-Disposition header.

A common parameters is e.g. filename.

Note

It is not allowed to modify the Content-Disposition header directly, please use this function instead.

See also

setparam() , get_filename()


Method setcharset

void setcharset(string charset)

Description

Sets the charset parameter of the Content-Type header.

This is equivalent of calling setparam("charset", charset ).

See also

setparam()


Method setboundary

void setboundary(string boundary)

Description

Sets the boundary parameter of the Content-Type header.

This is equivalent of calling setparam("boundary", boundary ).

See also

setparam()


Method cast

string cast(string dest_type)

Description

Casting the message object to a string will yield a byte stream suitable for transmitting the message over protocols such as ESMTP and NNTP.

The body will be encoded using the current transfer encoding, and subparts of a multipart will be collected recursively. If the message is a multipart and no boundary string has been set, one will be generated using generate_boundary() .

See also

create()


Method create

void MIME.Message()
void MIME.Message(string message)
void MIME.Message(string message, mapping(string:string|array(string)) headers, array(object)|void parts)
void MIME.Message(string message, mapping(string:string|array(string)) headers, array(object)|void parts, int(0..1) guess)

Description

There are several ways to call the constructor of the Message class:

  • With zero arguments, you will get a dummy message with neither headers nor body. Not very useful.

  • With one argument, the argument is taken to be a byte stream containing a message in encoded form. The constructor will analyze the string and extract headers and body.

  • With two or three arguments, the first argument is taken to be the raw body data, and the second argument a desired set of headers. The keys of this mapping are not case-sensitive. If the given headers indicate that the message should be of type multipart, an array of Message objects constituting the subparts should be given as a third argument.

  • With the guess argument set to 1 (headers and parts may be 0 if you don't want to give any), you get a more forgiving MIME Message that will do its best to guess what broken input data really meant. It won't always guess right, but for applications like mail archives and similar where you can't get away with throwing an error at the user, this comes in handy. Only use the guess mode only for situations where you need to process broken MIME messages silently; the abuse of overly lax tools is what poisons standards.

See also

cast()

  Module Math


Constant pi

constant Math.pi

Description

The constant pi (3.14159265358979323846).


Constant e

constant Math.e

Description

The constant e (2.7182818284590452354).


Constant inf

constant Math.inf

Description

Floating point infinity.


Constant nan

constant Math.nan

Description

Floating point not-a-number (e.g. inf/inf).


Inherit "___"

inherit "___"


Method convert_angle

int|float Math.convert_angle(int|float angle, string from, string to)

Description

This function converts between degrees, radians and gons. The from and to arguments may be any of the follwoing strings: "deg", "rad", "gon" and "str" for degrees, radians, gon and streck respectivly. The output is not guaranteed to be within the first turn, e.g. converting 10 radians yields almost 573 degrees as output.


Method choose

int Math.choose(int n, int k)

Description

Calculate binomial koefficient n choose k .

This is equvivalent to n !/(k !*(n -k )!).


Method log10

float Math.log10(float x)

Description

The 10-logarithm of x .


Method factor

array(int) Math.factor(int x)

Description

Factorize the integer x . The returned list of factors will be sorted biggest to smallest factor.

Note

This function is only available when Pike has been compiled with bignums.

  CLASS Math.Matrix

Description

Matrix representation with double precision floating point values.


Method create

void Math.Matrix(array(array(int|float)) matrix_2d)
void Math.Matrix(array(int|float) matrix_1d)

Description

Initializes the matrix as a 1D or 2D matrix, e.g. Math.Matrix( ({({1,2}),({3,4})}) ).


Method create

void Math.Matrix(int n, int m)
void Math.Matrix(int n, int m, string type)
void Math.Matrix(int n, int m, float|int init)

Description

Initializes the matrix as to be a n *m matrix with init in every value. If no third argument is given, or the third argument is "identity", the matrix will be initialized with all zeroes except for the diagonal which will be 1.


Method create

void Math.Matrix(string type, int size)

Description

When type is "identity" the matrix is initializes as a square identity matrix.


Method create

void Math.Matrix(string type, int size, float rads, Matrix axis)
void Math.Matrix(string type, int size, float rads, float x, float y, float z)

Description

When type is "rotate" the matrix is initialized as a rotation matrix.


Method cast

array(array) cast(string to_what)
array(array) cast(string to_what)

Description

It is possible to cast the matrix to an array and get back a double array of floats with the matrix values.

See also

vect


Method vect

array vect()

Description

Return all the elements of the matrix as an array of numbers


Method transpose

Matrix transpose()

Description

Returns the transpose of the matrix as a new object.


Method norm
Method norm2
Method normv

float norm()
float norm2()
Matrix normv()

Description

Norm of the matrix, and the square of the norm of the matrix. (The later method is because you may skip a square root sometimes.)

This equals |A| or sqrt( A02 + A12 + ... + An2 ).

It is only usable with 1xn or nx1 matrices.

m->normv() is equal to m*(1.0/m->norm()), with the exception that the zero vector will still be the zero vector (no error).


Method `+
Method ``+
Method add

Matrix `+(object with)
Matrix ``+(object with)
Matrix add(object with)

Description

Add this matrix to another matrix. A new matrix is returned. The matrices must have the same size.


Method `-
Method ``-
Method sub

Matrix `-()
Matrix `-(object with)
Matrix ``-(object with)
Matrix sub(object with)

Description

Subtracts this matrix from another. A new matrix is returned. -m is equal to -1*m.


Method sum

Matrix sum()

Description

Produces the sum of all the elements in the matrix.


Method max
Method min

Matrix max()
Matrix min()

Description

Produces the maximum or minimum value of all the elements in the matrix.


Method `*
Method ``*
Method mult

Matrix `*(object with)
Matrix ``*(object with)
Matrix mult(object with)

Description

Matrix multiplication.


Method cross

Matrix cross(object with)

Description

Matrix cross-multiplication.


Method dot_product

float dot_product(object with)

Description

Matrix dot product.


Method convolve

Matrix convolve(object with)

Description

Convolve called matrix with the argument.

  CLASS Math.FMatrix

Description

Matrix representation with single precision floating point values.


Inherit Matrix

inherit Matrix : Matrix

  CLASS Math.LMatrix

Description

Matrix representation with 64 bit integer values.


Inherit Matrix

inherit Matrix : Matrix

  CLASS Math.IMatrix

Description

Matrix representation with 32 bit integer values.


Inherit Matrix

inherit Matrix : Matrix

  CLASS Math.SMatrix

Description

Matrix representation with 16 bit integer values.


Inherit Matrix

inherit Matrix : Matrix

  CLASS Math.Angle

Description

Represents an angle.


Variable angle

int|float angle

Description

The actual keeper of the angle value.


Variable type

string type

Description

The type of the angle value. Is either "deg", "rad", "gon" or "str".


Method create

void Math.Angle()
void Math.Angle(int|float radians)
void Math.Angle(int|float angle, string type)

Description

If an angle object is created without arguments it will have the value 0 radians.


Method clone_me

Angle clone_me()

Description

Returns a copy of the object.


Method get

int|float get(string type)

Description

Gets the value in the provided type.


Method set

Angle set(string type, int|float _angle)

Description

Sets the angle value and type to the given value and type.


Method normalize

void normalize()

Description

Normalizes the angle to be within one turn.


Method degree

int|float degree()

Description

Returns the number of degrees, including minutes and seconds as decimals.


Method minute

int minute()

Description

Returns the number of minute.


Method second

float second()

Description

Returns the number of seconds.


Method set_dms

Angle set_dms(int degrees)
Angle set_dms(int degrees, int minutes)
Angle set_dms(int degrees, int minutes, float seconds)

Description

Set degrees, minues and seconds. Returns the current angle object.


Method format_dms

string format_dms()

Description

Returns degrees, minutes and seconds as a string, e.g. 47°6'36.00".


Method set_degree

Angle set_degree(int|float degree)

Description

Sets the angle to the provided degree. Alters the type to degrees. Returns the current object.


Method gon

int|float gon()

Description

Returns the number of gons.


Method set_gon

Angle set_gon(int|float gon)

Description

Set the angle to the provided gons. Alters the type to gons. Returns the current angle object.


Method rad

float rad()

Description

Returns the number of radians.


Method set_rad

Angle set_rad(int|float rad)

Description

Set the angle to the provided radians. Alters the type to radians. Returns the current angle object.


Method streck

float|int streck()

Description

Returns the number of strecks.


Method set_streck

Angle set_streck(int|float str)

Description

Set the angle to the provided strecks. Alters the type to streck. Returns the current angle object.


Method about_face

void about_face()

Description

Turns the direction of the angle half a turn. Equal to add(180,"deg").


Method right_face

void right_face()

Description

Turns the direction of the angle a quarter of a turn to the right. Equal to subtract(90,"deg").


Method left_face

void left_face()

Description

Turns the direction of the angle a quarter of a turn to the left. Equal to add(90,"deg").


Method sin

float sin()

Description

Returns the sinus for the angle.


Method cos

float cos()

Description

Returns the cosinus for the angle.


Method tan

float tan()

Description

Returns the tangen for the angle.


Method cast

float|int|string cast(string to)

Description

An angle can be casted to float, int and string.


Method `+

float|int|Angle `+(float|int|Angle _angle)

Description

Returns the sum of this angle and what it is added with. If added with an angle, a new angle object is returnes.


Method add

Angle add(float|int angle)
Angle add(float|int angle, string type)
Angle add(Angle angle)

Description

Adds the provided angle to the current angle. The result is normalized within 360 degrees.


Method `-

float|int|Angle `-(float|int|Angle _angle)

Description

Returns the difference between this angle and the provided value. If differenced with an angle, a new angle object is returned.


Method subtract

Angle subtract(float|int angle)
Angle subtract(float|int angle, string type)
Angle subtract(Angle angle)

Description

Subtracts the provided angle from the current angle. The result is normalized within 360 degrees.


Method `*

float|int|Angle `*(float|int|Angle _angle)

Description

Returns the product between this angle and the provided value. If differenced with an angle, a new angle object is returned.


Method `/

float|int|Angle `/(float|int|Angle _angle)

Description

Returns the fraction between this angle and the provided value. If differenced with an angle, a new angle object is returned.


Method `%

float|int|Angle `%(float|int|Angle _angle)

Description

Returns this result of this angle modulo the provided value. If differenced with an angle, a new angle object is returned.


Method __hash

int __hash()


Method `==

int `==(Angle _angle)

Description

Compares the unnormalized angle of two Angle objects.


Method `<

int `<(Angle _angle)

Description

Compares the unnormalized angle of two Angle objects.


Method `>

int `>(Angle _angle)

Description

Compares the unnormalized angle of two Angle objects.

  Module Math.Transforms

  CLASS Math.Transforms.FFT


Method rFFT

array(array(float)) rFFT(array(int|float) real_input)

Description

Returns the FFT of the input array. The input must be real and the output is complex. The output consists of an array. It's first element is the amplitudes and the second element is the phases.

Parameter real_input

The array of floats and/or ints to transform.

Note

rIFFT(rFFT()) returns the input array scaled by n=sizeof(input array). This is due to the nature of the DFT algorithm.

See also

rIFFT()


Method rIFFT

array(float) rIFFT(array(array(float)) input)

Description

Returns the inverse FFT of the input array. The input must be complex and guaranteed to generate a real output.

The input is an array. It's first element is the amplitudes and the second element is the phases.

The output is an array of the real values for the iFFT.

Parameter real_input

The array of floats and/or ints to transform.

Note

rIFFT(rFFT()) returns the input array scaled by n=sizeof(input array). This is due to the nature of the DFT algorithm.

See also

rFFT()


Method create

void Math.Transforms.FFT(void|int n, void|int(0..1) exact)

Description

Creates a new transform object. If n is specified, a plan is created for transformations of n-size arrays.

Parameter n

Size of the transform to be preformed. Note that the transform object will be initialized for this size, but if an array of different size is sent to the object, it will be reinitialized. This can be used to gain preformace if all transforms will be of a given size.

Parameter exact

If exact is 1, a "better" plan for the transform will be created. This will take more time though. Use only if preformance is needed.

  Module Msql

Description

This is an interface to the mSQL database server. This module may or may not be availible on your Pike, depending whether the appropriate include and library files (msql.h and libmsql.a respectively) could be found at compile-time. Note that you do not need to have a mSQL server running on your host to use this module: you can connect to the database over a TCP/IP socket

Please notice that unless you wish to specifically connect to a mSQL server, you'd better use the Sql.Sql program instead. Using Sql.Sql ensures that your Pike applications will run with any supported SQL server without changing a single line of code.

Also notice that some functions may be mSQL/2.0-specific, and thus missing on hosts running mSQL/1.0.*

Note

The mSQL C API has some extermal dependencies. They take the form of certain environment variables which, if defined in the environment of the pike interpreter, influence the interface's behavior. Those are "MSQL_TCP_PORT" which forces the server to connect to a port other than the default, "MSQL_UNIX_PORT", same as above, only referring to the UNIX domain sockets. If you built your mSQL server with the default setttings, you shouldn't worry about these. The variable MINERVA_DEBUG can be used to debug the mSQL API (you shouldn't worry about this either). Refer to the mSQL documentation for further details.

Also note that THIS MODULE USES BLOCKING I/O to connect to the server. mSQL should be reasonably fast, but you might want to consider this particular aspect. It is thread-safe, and so it can be used in a multithread environment.

FIXME

Although it seems that mSQL/2.0 has some support for server statistics, it's really VERY VERY primitive, so it won't be added for now.

See also

Sql.Sql


Constant version

constant Msql.version

Description

Should you need to report a bug to the author, please submit along with the report the driver version number, as returned by this call.

  CLASS Msql.msql


Method shutdown

void shutdown()

Description

This function shuts a SQL-server down.


Method reload_acl

void reload_acl()

Description

This function forces a server to reload its ACLs.

Note

This function is not part of the standard interface, so it is not availible through the Sql.Sql interface, but only through Sql.msql and Msql.msql programs.

See also

create


Method create

void Msql.msql(void|string dbserver, void|string dbname, void|string username, void|string passwd)

Description

With one argument, this function tries to connect to the specified (use hostname or IP address) database server. To connect to a server running on the local host via UNIX domain sockets use "localhost". To connect to the local host via TCP/IP sockets you have to use the IP address "127.0.0.1". With two arguments it also selects a database to use on the server. With no arguments it tries to connect to the server on localhost, using UNIX sockets.

Throws

You need to have a database selected before using the sql-object, otherwise you'll get exceptions when you try to query it. Also notice that this function can raise exceptions if the db server doesn't respond, if the database doesn't exist or is not accessible by you.

Note

You don't need bothering about syncronizing the connection to the database: it is automatically closed (and the database is sync-ed) when the msql object is destroyed.

See also

select_db


Method list_dbs

array list_dbs(void|string wild)

Description

Returns an array containing the names of all databases availible on the system. Will throw an exception if there is no server connected. If an argument is specified, it will return only those databases whose name matches the given glob.


Method list_tables

array list_tables(void|string wild)

Description

Returns an array containing the names of all the tables in the currently selected database. Will throw an exception if we aren't connected to a database. If an argument is specified, it will return only those tables whose name matches the given glob.


Method select_db

void select_db(string dbname)

Description

Before querying a database you have to select it. This can be accomplished in two ways: the first is calling the create function with two arguments, another is calling it with one or no argument and then calling select_db . You can also use this function to change the database you're querying, as long as it is on the same server you are connected to.

Throws

This function CAN raise exceptions in case something goes wrong (for example: unexistant database, insufficient permissions, whatever).

See also

create , error


Method query

array(mapping(string:mixed)) query(string sqlquery)

Description

This is all you need to query the database. It takes as argument an SQL query string (i.e.: "SELECT foo,bar FROM baz WHERE name like '%kinkie%'" or "INSERT INTO baz VALUES ('kinkie','made','this')") and returns a data structure containing the returned values. The structure is an array (one entry for each returned row) of mappings which have the column name as index and the column contents as data. So to access a result from the first example you would have to do "results[0]->foo".

A query which returns no data results in an empty array (and NOT in a 0). Also notice that when there is a column name clash (that is: when you join two or more tables which have columns with the same name), the clashing columns are renamed to <tablename>+"."+<column name>. To access those you'll have to use the indexing operator '[] (i.e.: results[0]["foo.bar"]).

Throws

Errors (both from the interface and the SQL server) are reported via exceptions, and you definitely want to catch them. Error messages are not particularly verbose, since they account only for errors inside the driver. To get server-related error messages, you have to use the error function.

Note

Note that if the query is NOT a of SELECT type, but UPDATE or MODIFY, the returned value is an empty array. This is not an error. Errors are reported only via exceptions.

See also

error


Method server_info

string server_info()

Description

This function returns a string describing the server we are talking to. It has the form "servername/serverversion" (like the HTTP protocol description) and is most useful in conjunction with the generic SQL-server module.


Method host_info

string host_info()

Description

This function returns a string describing what host are we talking to, and how (TCP/IP or UNIX sockets).


Method error

string error()

Description

This function returns the textual description of the last server-related error. Returns 0 if no error has occurred yet. It is not cleared upon reading (can be invoked multiple times, will return the same result until a new error occurs).

See also

query


Method create_db

void create_db(string dbname)

Description

This function creates a new database with the given name (assuming we have enough permissions to do this).

See also

drop_db


Method drop_db

void drop_db(string dbname)

Description

This function destroys a database and all the data it contains (assuming we have enough permissions to do so). USE WITH CAUTION!

See also

create_db


Method list_fields

mapping(string:mapping(string:mixed)) list_fields(string table, void|string glob)

Description

Returns a mapping describing the fields of a table in the database. The returned value is a mapping, indexed on the column name, of mappings.The glob argument, if present, filters out the fields not matching the glob. These contain currently the fields:

"type" : string

Describes the field's mSQL data type ("char","integer",...)

"length" : int

It describes the field's length. It is only interesting for char() fields, in fact. Also notice that the strings returned by msql->query() have the correct length. This field only specifies the _maximum_ length a "char()" field can have.

"table" : string

The table this field is in. Added only for interface compliancy.

"flags" : multiset(string)

It's a multiset containing textual descriptions of the server's flags associated with the current field. Currently it can be empty, or contain "unique" or "not null".


Note

The version of this function in the Msql.msql() program is not sql-interface compliant (this is the main reason why using that program directly is deprecated). Use Sql.Sql instead.

See also

query


Method affected_rows

int affected_rows()

Description

This function returns how many rows in the database were affected by our last SQL query.

Note

This function is availible only if you're using mSQL version 2 or later. (That means: if the includes and library of version 2 of mSQL were availible when the module was compiled).

This function is not part of the standard interface, so it is not availible through the Sql.Sql interface, but only through Sql.msql and Msql.msql programs


Method list_index

array list_index(string tablename, string indexname)

Description

This function returns an array describing the index structure for the given table and index name, as defined by the non-standard SQL query 'create index' (see the mSQL documentation for further informations). More than one index can be created for a table. There's currently NO way to have a listing of the indexes defined for a table (blame it on the mSQL API).

Note

This function is availible if you're using mSQL version 2 or later.

This function is not part of the standard interface, so it is not availible through the Sql.Sql interface, but only through Sql.msql and Msql.msql programs.

  Module PDF


constant PDF.a0_width
constant PDF.a0_height
constant PDF.a1_width
constant PDF.a1_height
constant PDF.a2_width
constant PDF.a2_height
constant PDF.a3_width
constant PDF.a3_height
constant PDF.a4_width
constant PDF.a4_height
constant PDF.a5_width
constant PDF.a5_height
constant PDF.a6_width
constant PDF.a6_height
constant PDF.b5_width
constant PDF.b5_height
constant PDF.letter_width
constant PDF.letter_height
constant PDF.legal_width
constant PDF.legal_height
constant PDF.ledger_width
constant PDF.ledger_height
constant PDF.p11x17_width
constant PDF.p11x17_height

  CLASS PDF.PDFgen


Method open_file

int open_file(string filename)


Method close

PDF close()


Method begin_page

PDF begin_page()
PDF begin_page(float width, float height)

Description

note: Defaults to a4, portrait


Method end_page

PDF end_page()


Method get_value

float get_value(string key)
float get_value(string key, float modifier)


Method set_value

float set_value(string key, float value)


Method get_parameter

string get_parameter(string key)
string get_parameter(string key, float modifier)


Method set_parameter

float set_parameter(string key, string parameter)


Method set_info

float set_info(string key, string info)


Method findfont

int findfont(string fontname)
int findfont(string fontname, void|string encoding, void|int embed)


Method setfont

PDF setfont(int n, float size)


Method show

PDF show(string s)


Method showxy

PDF showxy(string s, float x, float y)


Method continue_text

PDF continue_text(string s)


Method show_boxed

int show_boxed(string text, float x, float y, float width, float height, string mode)
int show_boxed(string text, float x, float y, float width, float height, string mode, string feature)


Method stringwidth

float stringwidth(string text, int font, float size)


Method set_text_pos

object set_text_pos(float x, float y)


Method setdash

object setdash(float b, float w)


Method setflat

object setflat(float flatness)


Method setlinejoin

object setlinejoin(int linejoin)


Method setlinecap

object setlinecap(int linecap)


Method setmiterlimit

object setmiterlimit(float miter)


Method setlinewidth

object setlinewidth(float width)


Method translate

object translate(float tx, float ty)


Method scale

object scale(float sx, float sy)


Method rotate

object rotate(float phi)


Method skew

object skew(float alpha, float beta)


Method concat

object concat(float a, float b, float c, float d, float e, float f)


Method moveto

object moveto(float x, float y)


Method lineto

object lineto(float x, float y)


Method curveto

object curveto(float x1, float y1, float x2, float y2, float x3, float y3)


Method circle

object circle(float x, float y, float r)


Method arc

object arc(float x, float y, float r, float start, float end)


Method rect

object rect(float x, float y, float width, float height)


Method setgray_fill

object setgray_fill(float gray)


Method setgray_stroke

object setgray_stroke(float gray)


Method setgray

object setgray(float gray)


Method setrgbcolor_fill

object setrgbcolor_fill(float red, float green, float blue)


Method setrgbcolor_stroke

object setrgbcolor_stroke(float red, float green, float blue)


Method setrgbcolor

object setrgbcolor(float red, float green, float blue)


Method open_image_file

int open_image_file(string type, string filename)
int open_image_file(string type, string filename, void|string stringparam, void|int intparam)


Method open_CCITT

int open_CCITT(string filename, int width, int height, int BitReverse, int K, int BlackIs1)


Method open_image

int open_image(string type, string source, string data, int width, int height, int components, int bpc, string params)


Method close_image

object close_image(int image)


Method place_image

object place_image(int image, float x, float y, float scale)


Method add_bookmark

int add_bookmark(string text, int parent, int open)


Method attach_file

object attach_file(float llx, float lly, float urx, float ury, string filename, string description, string author, string mimetype, string icon)


Method add_pdflink

object add_pdflink(float llx, float lly, float urx, float ury, string filename, int page, string dest)


Method add_locallink

object add_locallink(float llx, float lly, float urx, float ury, int page, string dest)


Method add_launchlink

object add_launchlink(float llx, float lly, float urx, float ury, string filename)


Method add_weblink

object add_weblink(float llx, float lly, float urx, float ury, string url)


Method set_border_style

object set_border_style(string style, float width)


Method set_border_color

object set_border_color(float red, float green, float blue)


Method set_border_dash

object set_border_dash(float b, float w)

  Module Perl

Description

This module allows access to an embedded Perl interpreter, if a libperl.so (or equivalent) was found during the installation of Pike.

  CLASS Perl.Perl

Description

An object of this class is a Perl interpreter.


Method create

void Perl.Perl()

Description

Create a Perl interpreter object. There can only be one Perl interpreter object at the same time, unless Perl was compiled with the MULTIPLICITY option, and Pike managed to figure this out during installation. An error will be thrown if no Perl interpreter is available.


Method parse

int parse(array(string) args)
int parse(array(string) args, mapping(string:string) env)

Description

Parse a Perl script file and set up argument and environment for it. Returns zero on success, and non-zero if the parsing failed.

Parameter args

Arguments in the style of argv, i.e. with the name of the script first.

Parameter env

Environment mapping, mapping environment variable names to to their values.


Method run

int run()

Description

Run a previously parsed Perl script file. Returns a status code.


Method eval

mixed eval(string expression)

Description

Evalute a Perl expression in a scalar context, and return the result if it is a simple value type. Unsupported value types are rendered as 0.


Method eval_list

mixed eval_list(string expression)

Description

Evalute a Perl expression in a list context, and return the result if it is a simple value type, or an array of simple value types. Unsupported value types are rendered as 0.


Method call

mixed call(string name, mixed ... arguments)

Description

Call a Perl subroutine in a scalar context, and return the result if it is a simple value type. Unsupported value types are rendered as 0.

Parameter name

The name of the subroutine to call, as an 8-bit string.

Parameter arguments

Zero or more arguments to the function. Only simple value types are supported. Unsupported value types will cause an error to be thrown.


Method call_list

mixed call_list(string name, mixed ... arguments)

Description

Call a Perl subroutine in a list context, and return the result if it is a simple value type, or an array of simple value types. Unsupported value types are rendered as 0.

Parameter name

The name of the subroutine to call, as an 8-bit string.

Parameter arguments

Zero or more arguments to the function. Only simple value types are supported. Unsupported value types will cause an error to be thrown.


Method get_scalar

mixed get_scalar(string name)

Description

Get the value of a Perl scalar variable. Returns the value, or a plain 0 if the value type was not supported.

Parameter name

Name of the scalar variable, as an 8-bit string.


Method set_scalar

void set_scalar(string name, mixed value)

Description

Set the value of a Perl scalar variable.

Parameter name

Name of the scalar variable, as an 8-bit string.

Parameter value

The new value. Only simple value types are supported. Throws an error for unsupported value types.


Method get_array_item

mixed get_array_item(string name, int index)

Description

Get the value of an entry in a Perl array variable. Returns the value, or a zero-type value if indexing outside the array, or a plain zero if the value type was not supported.

Parameter name

Name of the array variable, as an 8-bit string.

Parameter index

Array index. An error is thrown if the index is negative, non-integer or a bignum.


Method set_array_item

void set_array_item(string name, int index, mixed value)

Description

Set the value of an entry in a Perl array variable. Only simple value types are supported. Throws an error for unsupported value types.

Parameter name

Name of the array variable, as an 8-bit string.

Parameter index

Array index. An error is thrown if the index is negative, non-integer or a bignum.

Parameter value

New value. Only simple value types are supported. An error is thrown for unsupported value types.


Method get_hash_item

mixed get_hash_item(string name, mixed key)

Description

Get the value of an entry in a Perl hash variable. Returns the value, or a zero-type value if the hash had no entry for the given key, or a plain 0 if the returned value type was not supported.

Parameter name

Name of the array variable, as an 8-bit string.

Parameter key

Hash key. Only simple value types are supported. An error is thrown for unsupported value types.


Method set_hash_item

void set_hash_item(string name, mixed key, mixed value)

Description

Set the value of an entry in a Perl hash variable.

Parameter name

Name of the hash variable, as an 8-bit string.

Parameter key

Hash key. Only simple value types are supported. An error is thrown for unsupported value types.

Parameter value

New value. Only simple value types are supported. An error is thrown for unsupported value types.


Method array_size

int array_size(string name)

Description

Get the size of the Perl array variable with the given name.

Parameter name

Name of the array variable, as an 8-bit string.


Method get_array

array get_array(string name)

Description

Get the contents of a Perl array variable as a Pike array. If the size of the array is larger than the specified array size limit, the returned Pike array will be truncated according to the limit.

Parameter name

Name of the array variable, as an 8-bit string.

See also

array_size_limit()


Method get_hash_keys

array get_hash_keys(string name)

Description

Get the keys (indices) of a Perl hash variable as a Pike array. If the size of the resulting array is larger than the specified array size limit, an error will be thrown.

Parameter name

Name of the hash variable, as an 8-bit string.

See also

array_size_limit()


Method array_size_limit

int array_size_limit()
int array_size_limit(int limit)

Description

Get (and optionally set) the array size limit for this interpreter instance. Without arguments, the current limit is returned. With an integer argument, the limit is set to that value, and the same value is returned.

The array size limit is mainly a way of ensuring that there isn't a sudden explosion in memory usage and data conversion time in this embedding interface. There is no particular limit other than available memory in Perl itself.

Note

The default array size limit is 500 elements, but this may change in future releases of Pike.

The maximum array size limit is the highest number representable as a non-bignum integer (which is typically 2147483647 on a traditional 32-bit architecture).

Parameter limit

The new array size limit.

  Module Regexp


Inherit "___"

inherit "___"


Method `()

SimpleRegexp Regexp.`()(void|string regexp)

Description

Convenience/compatibility method to get a SimpleRegexp object.


Method match

int(0..1) Regexp.match(string regexp, string data)

Description

Calls Regexp.PCRE.Plain.match in a temporary regexp object. Faster to type but slower to run...


Method split

array Regexp.split(string regexp, string data)

Description

Calls Regexp.PCRE.Plain.split in a temporary regexp object. Faster to type but slower to run...


Method split2

array Regexp.split2(string regexp, string data)

Description

Calls Regexp.PCRE.Plain.split2 in a temporary regexp object. Faster to type but slower to run...


Method replace

string Regexp.replace(string regexp, string data, string|function(string:string) transform)

Description

Calls Regexp.PCRE.Plain.replace in a temporary regexp object. Faster to type but slower to run...

  CLASS Regexp.SimpleRegexp

Description

This class implements the interface to a simple regexp engine with the following capabilities:

.Matches any character.
[abc]Matches a, b or c.
[a-z]Matches any character a to z inclusive.
[^ac]Matches any character except a and c.
(x)Matches x (x might be any regexp) If used with split, this also puts the string matching x into the result array.
x*Matches zero or more occurances of 'x' (x may be any regexp).
x+Matches one or more occurances of 'x' (x may be any regexp).
x|yMatches x or y. (x or y may be any regexp).
xyMatches xy (x and y may be any regexp).
^Matches beginning of string (but no characters).
$Matches end of string (but no characters).
\<Matches the beginning of a word (but no characters).
\>Matches the end of a word (but no characters).

Note that \ can be used to quote these characters in which case they match themselves, nothing else. Also note that when quoting these something in Pike you need two \ because Pike also uses this character for quoting.


Method create

void Regexp.SimpleRegexp(string re)

Description

When create is called, the current regexp bound to this object is cleared. If a string is sent to create(), this string will be compiled to an internal representation of the regexp and bound to this object for laters calls to e.g. match or split . Calling create() without an argument can be used to free up a little memory after the regexp has been used.


Method match

int match(string str)

Description

Returns 1 if str matches the regexp bound to the regexp object. Zero otherwise.


Method match

array(string) match(array(string) strs)

Description

Returns an array containing strings in strs that match the regexp bound to the regexp object.

Bugs

The current implementation doesn't support searching in strings containing the NUL character or any wide character.

See also

split


Method split

array(string) split(string s)

Description

Works as match , but returns an array of the strings that matched the subregexps. Subregexps are those contained in "( )" in the regexp. Subregexps that were not matched will contain zero. If the total regexp didn't match, zero is returned.

Bugs

You can currently only have 39 subregexps.

Bugs

The current implementation doesn't support searching in strings containing the NUL character or any wide character.

See also

match


Inherit _SimpleRegexp

inherit _SimpleRegexp : _SimpleRegexp


Method replace

string replace(string in, string|function(string:string) transform)


Method _encode
Method _decode

mixed _encode()
mixed _decode(string s)

Description

Regexp objects can be encoded and decoded.

See also

encode_value , decode_value

  Module Regexp.PCRE


Method split_subject

array(string) Regexp.PCRE.split_subject(string subject, array(int) previous_result)

Description

Convenience function that splits a subject string on the result from _pcre->exec()

equal to map(previous_result/2, lambda(array v) { return subject[v[0]..v[1]-1]; })


Constant buildconfig_UTF8

constant Regexp.PCRE.buildconfig_UTF8

Description

(from the pcreapi man-page) "The output is an integer that is set to one if UTF-8 support is available; otherwise it is set to zero." This constant is calculated when the module is initiated by using pcre_config(3).


Constant buildconfig_NEWLINE

constant Regexp.PCRE.buildconfig_NEWLINE

Description

(from the pcreapi man-page) "The output is an integer that is set to the value of the code that is used for the newline character. It is either linefeed (10) or carriage return (13), and should normally be the standard character for your operating system." This constant is calculated when the module is initiated by using pcre_config(3).


Constant buildconfig_LINK_SIZE

constant Regexp.PCRE.buildconfig_LINK_SIZE

Description

(from the pcreapi man-page) "The output is an integer that contains the number of bytes used for internal linkage in compiled regular expressions. The value is 2, 3, or 4. Larger values allow larger regular expressions to be compiled, at the expense of slower match- ing. The default value of 2 is sufficient for all but the most massive patterns, since it allows the compiled pattern to be up to 64K in size." This constant is calculated when the module is initiated by using pcre_config(3).


Constant buildconfig_POSIX_MALLOC_THRESHOLD

constant Regexp.PCRE.buildconfig_POSIX_MALLOC_THRESHOLD

Description

(from the pcreapi man-page) "The output is an integer that contains the threshold above which the POSIX interface uses malloc() for output vectors. Further details are given in the pcreposix documentation." This constant is calculated when the module is initiated by using pcre_config(3).


Constant buildconfig_MATCH_LIMIT

constant Regexp.PCRE.buildconfig_MATCH_LIMIT

Description

(from the pcreapi man-page) "The output is an integer that gives the default limit for the number of internal matching function calls in a pcre_exec() execution. Further details are given with pcre_exec() below." This constant is calculated when the module is initiated by using pcre_config(3).

  CLASS Regexp.PCRE._pcre


Method create

void Regexp.PCRE._pcre(string pattern, void|int options, void|object table)

Description

The option bits are:

OPTION.ANCHORED

Force pattern anchoring

OPTION.CASELESS

Do caseless matching

OPTION.DOLLAR_ENDONLY

$ not to match newline at end

OPTION.DOTALL

. matches anything including NL

OPTION.EXTENDED

Ignore whitespace and # comments

OPTION.EXTRA

PCRE extra features (not much use currently)

OPTION.MULTILINE

^ and $ match newlines within data

OPTION.NO_AUTO_CAPTURE

Disable numbered capturing parentheses (named ones available)

OPTION.UNGREEDY

Invert greediness of quantifiers

OPTION.UTF8

Run in UTF-8 mode



Method study

object study()

Description

(from the pcreapi man-page) "When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for match- ing."


Method _sprintf

string _sprintf(int c, mapping flags)


Method info

mapping info()

Description

Returns additional information about a compiled pattern. Only available if PCRE was compiled with Fullinfo.

Returns
"backrefmax" : int

Return the number of the highest back reference in the pattern. The fourth argument should point to an int variable. Zero is returned if there are no back references.

"capturecount" : int

Return the number of capturing subpatterns in the pattern. The fourth argument should point to an int variable.

"firstbyte" : int

Return information about the first byte of any matched string, for a non-anchored pattern. (This option used to be called PCRE_INFO_FIRSTCHAR; the old name is still recognized for backwards compatibility.)

If there is a fixed first byte, e.g. from a pattern such as (cat|cow|coyote), it is returned in the integer pointed to by where. Otherwise, if either

(a) the pattern was compiled with the PCRE_MULTILINE option, and every branch starts with "^", or

(b) every branch of the pattern starts with ".*" and PCRE_DOTALL is not set (if it were set, the pattern would be anchored),

-1 is returned, indicating that the pattern matches only at the start of a subject string or after any newline within the string. Otherwise -2 is returned. For anchored patterns, -2 is returned.

"lastliteral" : int

Return the value of the rightmost literal byte that must exist in any matched string, other than at its start, if such a byte has been recorded. The fourth argument should point to an int variable. If there is no such byte, -1 is returned. For anchored patterns, a last literal byte is recorded only if it follows something of variable length. For example, for the pattern /^a\d+z\d+/ the returned value is "z", but for /^a\dz\d/ the returned value is -1.

"namecount" : int 
"nameentrysize" : int 
"options" : int

Return a copy of the options with which the pattern was compiled. The fourth argument should point to an unsigned long int variable. These option bits are those specified in the call to pcre_compile(), modified by any top-level option settings within the pattern itself.

A pattern is automatically anchored by PCRE if all of its top-level alternatives begin with one of the following:

^unless PCRE_MULTILINE is set
\Aalways
\Galways
.*if PCRE_DOTALL is set and there are no back references to the subpattern in which .* appears

For such patterns, the PCRE_ANCHORED bit is set in the options returned.

"size" : int

Return the size of the compiled pattern, that is, the value that was passed as the argument to pcre_malloc() when PCRE was getting memory in which to place the compiled data. The fourth argument should point to a size_t variable.

"studysize" : int

Returns the size of the data block pointed to by the study_data field in a pcre_extra block. That is, it is the value that was passed to pcre_malloc() when PCRE was getting memory into which to place the data created by pcre_study(). The fourth argument should point to a size_t variable.



Method exec

int|array exec(string subject, void|int startoffset)

Description

match a regexp; will return an array of 2*n integers where n is the number of hits; returns an int upon failure

Error codes:

ERROR.NOMATCH

The subject string did not match the pattern.

ERROR.NULL

Either code or subject was passed as NULL, or ovector was NULL and oversize was not zero.

ERROR.BADOPTION

An unrecognized bit was set in the options argument.

ERROR.BADMAGIC

PCRE stores a 4-byte "magic number" at the start of the compiled code, to catch the case when it is passed a junk pointer. This is the error it gives when the magic number isn't present.

ERROR.UNKNOWN_NODE

While running the pattern match, an unknown item was encountered in the compiled pattern. This error could be caused by a bug in PCRE or by overwriting of the compiled pattern.

ERROR.NOMEMORY

If a pattern contains back references, but the ovector that is passed to pcre_exec() is not big enough to remember the referenced substrings, PCRE gets a block of memory at the start of matching to use for this purpose. If the call via pcre_malloc() fails, this error is given. The memory is freed at the end of matching.

ERROR.NOSUBSTRING

This error is used by the pcre_copy_substring(), pcre_get_substring(), and pcre_get_substring_list() functions (see below). It is never returned by pcre_exec().

ERROR.MATCHLIMIT

The recursion and backtracking limit, as specified by the match_limit field in a pcre_extra structure (or defaulted) was reached. See the description above.

ERROR.CALLOUT

This error is never generated by pcre_exec() itself. It is provided for use by callout functions that want to yield a distinctive error code. See the pcrecallout documentation for details.



Method get_stringnumber

int get_stringnumber(string stringname)

Description

returns the number of a named subpattern

  Module Regexp.PCRE.OPTION

Description

contains all option constants


Constant ANCHORED

constant Regexp.PCRE.OPTION.ANCHORED

Description

(from the pcreapi manpage) If this bit is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the first matching point in the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl.


Constant CASELESS

constant Regexp.PCRE.OPTION.CASELESS

Description

(from the pcreapi manpage) If this bit is set, letters in the pattern match both upper and lower case letters. It is equivalent to Perl's /i option, and it can be changed within a pattern by a (?i) option setting.


Constant DOLLAR_ENDONLY

constant Regexp.PCRE.OPTION.DOLLAR_ENDONLY

Description

(from the pcreapi manpage) If this bit is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this option, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). The PCRE_DOLLAR_ENDONLY option is ignored if PCRE_MULTILINE is set. There is no equivalent to this option in Perl, and no way to set it within a pattern.


Constant DOTALL

constant Regexp.PCRE.OPTION.DOTALL

Description

(from the pcreapi manpage) If this bit is set, a dot metacharater in the pattern matches all characters, including newlines. Without it, newlines are excluded. This option is equivalent to Perl's /s option, and it can be changed within a pattern by a (?s) option setting. A negative class such as [^a] always matches a newline character, independent of the setting of this option.


Constant EXTENDED

constant Regexp.PCRE.OPTION.EXTENDED

Description

(from the pcreapi manpage) If this bit is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class. Whitespace does not include the VT character (code 11). In addition, characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x option, and it can be changed within a pattern by a (?x) option setting.

This option makes it possible to include comments inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern.


Constant EXTRA

constant Regexp.PCRE.OPTION.EXTRA

Description

(from the pcreapi manpage) This option was invented in order to turn on additional functionality of PCRE that is incompatible with Perl, but it is currently of very little use. When set, any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this option. It can also be set by a (?X) option setting within a pattern.


Constant MULTILINE

constant Regexp.PCRE.OPTION.MULTILINE

Description

(from the pcreapi manpage) By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless PCRE_DOL- LAR_ENDONLY is set). This is the same as Perl.

When PCRE_MULTILINE it is set, the "start of line" and "end of line" constructs match immediately following or immediately before any new- line in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m option, and it can be changed within a pattern by a (?m) option setting. If there are no "\n" charac- ters in a subject string, or no occurrences of ^ or $ in a pattern, setting PCRE_MULTILINE has no effect.


Constant NO_AUTO_CAPTURE

constant Regexp.PCRE.OPTION.NO_AUTO_CAPTURE

Description

(from the pcreapi manpage) If this option is set, it disables the use of numbered capturing paren- theses in the pattern. Any opening parenthesis that is not followed by ? behaves as if it were followed by ?: but named parentheses can still be used for capturing (and they acquire numbers in the usual way). There is no equivalent of this option in Perl.


Constant UNGREEDY

constant Regexp.PCRE.OPTION.UNGREEDY

Description

(from the pcreapi manpage) This option inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by "?". It is not compatible with Perl. It can also be set by a (?U) option setting within the pattern.


Constant UTF8

constant Regexp.PCRE.OPTION.UTF8

Description

(from the pcreapi manpage) This option causes PCRE to regard both the pattern and the subject as strings of UTF-8 characters instead of single-byte character strings. However, it is available only if PCRE has been built to include UTF-8 support. If not, the use of this option provokes an error. Details of how this option changes the behaviour of PCRE are given in the section on UTF-8 support in the main pcre page.

  Module Regexp.PCRE.ERROR


constant Regexp.PCRE.ERROR.NOMATCH
constant Regexp.PCRE.ERROR.NULL
constant Regexp.PCRE.ERROR.BADOPTION
constant Regexp.PCRE.ERROR.BADMAGIC
constant Regexp.PCRE.ERROR.UNKNOWN_NODE
constant Regexp.PCRE.ERROR.NOMEMORY
constant Regexp.PCRE.ERROR.NOSUBSTRING
constant Regexp.PCRE.ERROR.MATCHLIMIT
constant Regexp.PCRE.ERROR.CALLOUT

Description

Documented in exec .

  Module Regexp.PCRE._Regexp_PCRE


Inherit "___"

inherit "___"


Method `()

GOOD Regexp.PCRE._Regexp_PCRE.`()(string pattern, void|int options, void|object table)

Description

Convenience function to create a suitable PCRE Regexp object; will create a StudiedWidestring from the arguments.

That means the result will be able to handle widestrings, and will produce fast matchings by studying the pattern, but the widestring wrapping will on the other hand add overhead.

If you need a faster regexp and doesn't use widestring, create a Regexp.PCRE.Studied instead.

Widestring support will not be used if the linked libpcre lacks UTF8 support. This can be tested with checking that the Regexp.PCRE.Widestring class exist.

  CLASS Regexp.PCRE._Regexp_PCRE.Plain

Description

The main regexp class. Will provide anything needed for matching regexps.

There are subclasses that adds wrappers for widestrings, and to optimize the regexp pattern.


Inherit _pcre

inherit _pcre : _pcre


Method split2

array(string)|int(0..0) split2(string subject, void|int startoffset)

Description

Matches a subject against the pattern, returns an array where the first element are the whole match, and the subsequent are the matching subpatterns. Returns 0 if there was no match.

example: > Regexp.PCRE.Plain("i\(.*\) is \(.*\)u")->split2("pike is fun"); Result: ({ "ike is fu", "ke", "f" })


Method split

array(string)|int(0..0) split(string subject, void|int startoffset)

Description

Matches a subject against the pattern, compatible with the old split method: returns an array of the subpatterns, or if there are no subpattern but still a match, ({0}). Returns 0 if there was no match.

example: > Regexp.PCRE.Plain("i\(.*\) is \(.*\)u")->split("pike is fun"); (1) Result: ({ "ke", "f" }) > Regexp.PCRE.Plain("is fun")->split("pike is fun"); (4) Result: ({ 0 })


Method match

int(0..1) match(string subject, void|int startoffset)

Description

returns true (1) if a match is found, false otherwise

example: > Regexp.PCRE.Plain("is fun")->match("pike is fun"); Result: 1 > Regexp.PCRE.Plain("is fun")->match("pike isn't fun"); Result: 0


Method replace

string replace(string subject, string|function(string:string) with)

Description

replace all occurances of a pattern in a subject; callbacks and replacements will be from the first occurance, not from the last as in Regexp.Builtin.replace.

example: > Regexp.PCRE("b[^-]*m")->replace("abam-boom-fooabadoom","gurka"); Result: "agurka-gurka-fooagurka" > Regexp.PCRE("b[^-]*m")->replace("abam-boom-fooabadoom", lambda(string s) { werror("%O\n",s); return "gurka"; }); "bam" "boom" "badoom" Result: "agurka-gurka-fooagurka"


Method replace1

string replace1(string subject, string|function(string:string) with)

Description

replace one (first) occurance of a pattern in a subject

example: > Regexp.PCRE("b[^-]*m")->replace1("abam-boom-fooabadoom","gurka"); Result: "agurka-boom-fooabadoom"


Method matchall

this_program matchall(string subject, function(array(string)|void:mixed|void) callback)

Description

Will give a callback for each match in a subject. Called arguments will be matching patterns and subpatterns in an array and as second argument the exec result array.

returns called object

example: > Regexp.PCRE("b(a*)([^-\1234]*)(\1234*)m") ->matchall("abam-boom-fooabado\1234m", lambda(mixed s) { werror("%O\n",s); return "gurka"; }); ({ /* 4 elements */ "bam", "a", "", "" }) ({ /* 4 elements */ "boom", "", "oo", "" }) ({ /* 4 elements */ "bado\1234m", "a", "do", "\1234" }) Result: Regexp.PCRE.StudiedWidestring("b(a*)([^-Ê\234]*)(Ê\234*)m")

  CLASS Regexp.PCRE._Regexp_PCRE.Studied

Description

Same as Plain, but will be studied to match faster; useful if you're doing many matches on the same pattern


Inherit Plain

inherit Plain : Plain

  CLASS Regexp.PCRE._Regexp_PCRE.Widestring

Description

Wrapper class around Plain, that will allow widestring patterns and subjects.

Widestring support and this class will not be implemented if the linked libpcre lacks UTF8 support.


Inherit Plain

inherit Plain : Plain


Method exec

array(int)|int exec(string subject, void|int startoffset)

Description

The exec function is wrapped to give the correct indexes for the widestring.

  CLASS Regexp.PCRE._Regexp_PCRE.StudiedWidestring

Description

Same as Widestring, but will be studied to match faster; useful if you're doing many matches on the same pattern


Inherit Widestring

inherit Widestring : Widestring

  Module SANE

Description

This module enables access to the SANE (Scanner Access Now Easy) library from pike


Method list_scanners

array(mapping) SANE.list_scanners()

Description

Returns an array with all available scanners.

Example

Pike v0.7 release 120 running Hilfe v2.0 (Incremental Pike Frontend) > SANE.list_scanners(); Result: ({ ([ "model":"Astra 1220S ", "name":"umax:/dev/scg1f", "type":"flatbed scanner", "vendor":"UMAX " ]), ([ "model":"Astra 1220S ", "name":"net:lain.idonex.se:umax:/dev/scg1f", "type":"flatbed scanner", "vendor":"UMAX " ]) })


constant SANE.FrameGray
constant SANE.FrameRGB
constant SANE.FrameRed
constant SANE.FrameGreen
constant SANE.FrameBlue

  CLASS SANE.Scanner


Method create

void SANE.Scanner(string name)


Method list_options

array(mapping) list_options()

Description

This method returns an array where every element is a mapping, layed out as follows.

"name" : string 
"title" : string 
"desc" : string 
"type" : string
"boolean"
"int"
"float"
"string"
"button"
"group"

"unit" : string
"none"
"pixel"
"bit"
"mm"
"dpi"
"percent"
"microsend"

"size" : int 
"cap" : multiset
"soft_select"
"hard_select"
"emulate"
"automatic"
"inactive"
"advanced"

"constraint" : int(0..0)|mapping

Constraints can be of three different types; range, word list or string list. Constraint contains 0 if there are no constraints.

"type" : string

Contains the value "range".

"max" : int 
"min" : int 
"quant" : int 

"type" : string

Contains the value "list".

"list" : array(float|int) 

"type" : string

Contains the value "list".

"list" : array(string) 



Method set_option

void set_option(string name, mixed new_value)
void set_option(string name)

Description

If no value is specified, the option is set to it's default value


Method get_option

mixed get_option(string name)


Method get_parameters

mapping(string:int) get_parameters()

Returns
"format" : int
"last_frame" : int
"lines" : int
"depth" : int
"pixels_per_line" : int
"bytes_per_line" : int


Method simple_scan

Image.Image simple_scan()


Method row_scan

void row_scan(function(Image.Image:void) callback)


Method nonblocking_row_scan

void nonblocking_row_scan(function(Image.Image:void) callback)


Method cancel_scan

void cancel_scan()

  Module Yp

Description

This module is an interface to the Yellow Pages functions. Yp is also known as NIS (Network Information System) and is most commonly used to distribute passwords and similar information within a network.


Inherit "___"

inherit "___"


Method default_domain

string Yp.default_domain()

Description

Returns the default yp-domain.

  CLASS Yp.Map

Description

Network Information Service aka YP map.


Method create

void Yp.Map(string map, string|void domain)

Description

Create a new YP-map object.

map is the YP-map to bind to. This may be a nickname, such as passwd instead of just passwd.byname.

If domain is not specified, the default domain will be used.

Note

If there is no YP server available for the domain, this function call will block until there is one. If no server appears in about ten minutes or so, an error will be returned. The timeout is not configurable.


Method match
Method `[]

string match(string key)
string `[](string key)

Description

Search for the key key . If there is no key in the map, 0 (zero) will be returned, otherwise the string matching the key will be returned.

Note

key must match exactly, no pattern matching of any kind is done.


Method all
Method cast_to_mapping

mapping(string:string) all()
mapping(string:string) cast_to_mapping()

Description

Returns the whole map as a mapping.


Method map

void map(function(string:void) fun)

Description

Call a function for each entry in the map.

For each entry in the map, call the function fun .

The function will be called like void fun(string key, string value).


Method server

string server()

Description

Return the server that provides this map.


Method order

int order()

Description

Return the order number for this map.


Method _sizeof

int _sizeof()

Description

Return the number of entries in this map.


Method _indices

array(string) _indices()

Description

Return the keys of the map.


Method _values

array(string) _values()

Description

Return the values of the map.

  CLASS Yp.Domain


Method server

string server(string map)

Description

Returns the hostname of the server serving the map map . map is the YP-map to search in. This must be the full map name. eg passwd.byname instead of just passwd.


Method create
Method bind

void Yp.Domain(string|void domain)
void bind(string domain)

Description

If domain is not specified , the default domain will be used. (As returned by Yp.default_domain() ).

If there is no YP server available for the domain, this function call will block until there is one. If no server appears in about ten minutes or so, an error will be returned. This timeout is not configurable.

See also

Yp.default_domain()


Method all

mapping(string:string) all(string map)

Description

Returns the whole map as a mapping.

map is the YP-map to search in. This must be the full map name, you have to use passwd.byname instead of just passwd.


Method map

void map(string map, function(string:void) fun)

Description

For each entry in map , call the function specified by fun .

fun will get two arguments, the first being the key, and the second the value.

map is the YP-map to search in. This must be the full map name. eg passwd.byname instead of just passwd.


Method order

int order(string map)

Description

Returns the 'order' number for the map map .

This is usually the number of seconds since Jan 1 1970 (see time() ). When the map is changed, this number will change as well.

map is the YP-map to search in. This must be the full map name. eg passwd.byname instead of just passwd.


Method match

string match(string map, string key)

Description

Search for the key key in the Yp-map map .

Returns

If there is no key in the map, 0 (zero) will be returned, otherwise the string matching the key will be returned.

Note

key must match exactly, no pattern matching of any kind is done.

  Module _Ffmpeg


constant _Ffmpeg.CODEC_ID_NONE
constant _Ffmpeg.CODEC_ID_AC3
constant _Ffmpeg.CODEC_ID_ADPCM_IMA_QT
constant _Ffmpeg.CODEC_ID_ADPCM_IMA_WAV
constant _Ffmpeg.CODEC_ID_ADPCM_MS
constant _Ffmpeg.CODEC_ID_H263
constant _Ffmpeg.CODEC_ID_H263I
constant _Ffmpeg.CODEC_ID_H263P
constant _Ffmpeg.CODEC_ID_MJPEG
constant _Ffmpeg.CODEC_ID_MPEG1VIDEO
constant _Ffmpeg.CODEC_ID_MPEG4
constant _Ffmpeg.CODEC_ID_MP2
constant _Ffmpeg.CODEC_ID_MP3LAME
constant _Ffmpeg.CODEC_ID_MSMPEG4V1
constant _Ffmpeg.CODEC_ID_MSMPEG4V2
constant _Ffmpeg.CODEC_ID_MSMPEG4V3
constant _Ffmpeg.CODEC_ID_PCM_ALAW
constant _Ffmpeg.CODEC_ID_PCM_MULAW
constant _Ffmpeg.CODEC_ID_PCM_S16BE
constant _Ffmpeg.CODEC_ID_PCM_S16LE
constant _Ffmpeg.CODEC_ID_PCM_S8
constant _Ffmpeg.CODEC_ID_PCM_U16BE
constant _Ffmpeg.CODEC_ID_PCM_U16LE
constant _Ffmpeg.CODEC_ID_PCM_U8
constant _Ffmpeg.CODEC_ID_RAWVIDEO
constant _Ffmpeg.CODEC_ID_RV10
constant _Ffmpeg.CODEC_ID_SVQ1
constant _Ffmpeg.CODEC_ID_VORBIS
constant _Ffmpeg.CODEC_ID_WMV1
constant _Ffmpeg.CODEC_ID_WMV2

Description

Various audio and video codecs.

Note

The list of supported codecs depends on Ffmpeg library.


constant _Ffmpeg.CODEC_TYPE_AUDIO
constant _Ffmpeg.CODEC_TYPE_VIDEO

Description

Type of codec.

  CLASS _Ffmpeg.ffmpeg

Description

Implements support of all codecs from a nice project Ffmpeg. You can find more info about it at http://ffmpeg.sf.net/.


Method create

void _Ffmpeg.ffmpeg(int codec_name, int encoder)

Description

Create decoder or encoder object.

Parameter codec_name

Internal number of codec, eg. CODEC_ID_MP2 .

Parameter encoder

If true, encoder object will be created, decoder object otherwise.


Method get_codec_info

mapping|int get_codec_info()

Description

Returns mapping with info of used codec.

See also

list_codecs()


Method set_codec_param

int set_codec_param(string name, mixed value)

Description

Sets one codec parameter

Parameter name

The name of parameter. One of "sample_rate", "bit_rate", "channels".

Returns

Returns 1 on success, 0 otherwise (parameter not known).

See also

get_codec_params()


Method get_codec_status

mapping|int get_codec_status()

Description

Returns a mapping with the actual codec parameters.

See also

set_codec_param()


Method decode

mapping|int decode(string data)

Description

Returns a mapping with the new decoded frame and lenght of data which was used for decoding.


Method decode

int decode(string data, function shuffler)

Description

Decode all data buffer and pass result to shuffler . Returns 1 on success, 0 otherwise.

Note

Shuffler variant isn't implemented, yet.

Note

Usable only in decoder.

See also

create()


Method list_codecs

array(mapping) list_codecs()

Description

Gets all supported codecs.

Returns

Array of mapping with codec features.

  Module spider


Method discdate

string spider.discdate(int time)


Method parse_accessed_database

array(mapping(string:int)|int) spider.parse_accessed_database(string database)


Method parse_html

string spider.parse_html(string html, mapping(string:function(string:string|array)) tag_callbacks, mapping(string:function(string:string|array)) container_callbacks, mixed ... extras)


Method parse_html_lines

string spider.parse_html_lines(string html, mapping(string:function(string:string|array)) tag_callbacks, mapping(string:function(string:string|array)) container_callbacks, mixed ... extras)


Method set_end_quote

void spider.set_end_quote(int quote)


Method set_start_quote

void spider.set_start_quote(int quote)


Method get_all_active_fds

array(int) spider.get_all_active_fds()


Method fd_info

string spider.fd_info(int fd)


Method _low_program_name

string spider._low_program_name(program prog)


Method _dump_obj_table

array(array(string|int)) spider._dump_obj_table()


Method stardate

string spider.stardate(int time, int precision)


Method parse_xml

array spider.parse_xml(string xml, function cb)

  Module System

Description

This module embodies common operating system calls, making them available to the Pike programmer.


Method RegGetValue

string|int|array(string) System.RegGetValue(int hkey, string key, string index)

Description

Get a single value from the register.

Parameter hkey

One of the following:

HKEY_CLASSES_ROOT
HKEY_LOCAL_MACHINE
HKEY_CURRENT_USER
HKEY_USERS

Parameter key

Registry key.

Parameter index

Value name.

Returns

Returns the value stored at the specified location in the register if any. Throws errors on failure.

Note

This function is only available on Win32 systems.

See also

RegGetValues() , RegGetKeyNames()


Method RegGetKeyNames

array(string) System.RegGetKeyNames(int hkey, string key)

Description

Get a list of value key names from the register.

Parameter hkey

One of the following:

HKEY_CLASSES_ROOT
HKEY_LOCAL_MACHINE
HKEY_CURRENT_USER
HKEY_USERS

Parameter key

A registry key.

Returns

Returns an array of value keys stored at the specified location if any. Throws errors on failure.

Example

> RegGetKeyNames(HKEY_CURRENT_USER, "Keyboard Layout"); (1) Result: ({ "IMEtoggle", "Preload", "Substitutes", "Toggle" })

Note

This function is only available on Win32 systems.

See also

RegGetValue() , RegGetValues()


Method RegGetValues

mapping(string:string|int|array(string)) System.RegGetValues(int hkey, string key)

Description

Get multiple values from the register.

Parameter hkey

One of the following:

HKEY_CLASSES_ROOT
HKEY_LOCAL_MACHINE
HKEY_CURRENT_USER
HKEY_USERS

Parameter key

Registry key.

Returns

Returns a mapping with all the values stored at the specified location in the register if any. Throws errors on failure.

Example

> RegGetValues(HKEY_CURRENT_USER, "Keyboard Layout\\Preload"); (5) Result: ([ "1":"0000041d" ])

Note

This function is only available on Win32 systems.

See also

RegGetValue() , RegGetKeyNames()


Method LogonUser

object System.LogonUser(string username, string|int(0..0) domain, string password, int|void logon_type, int|void logon_provider)

Description

Logon a user.

Parameter username

User name of the user to login.

Parameter domain

Domain to login on, or zero if local logon.

Parameter password

Password to login with.

Parameter logon_type

One of the following values:

LOGON32_LOGON_BATCH 
LOGON32_LOGON_INTERACTIVE 
LOGON32_LOGON_SERVICE 
LOGON32_LOGON_NETWORK

This is the default.


Parameter logon_provider

One of the following values:

LOGON32_PROVIDER_DEFAULT

This is the default.


Returns

Returns a login token object on success, and zero on failure.

Note

This function is only available on some Win32 systems.


Method NetUserGetInfo

string|array(string|int) System.NetUserGetInfo(string username, string|int(0..0) server, int|void level)

Description

Get information about a network user.

Parameter username

User name of the user to get information about.

Parameter server

Server the user exists on.

Parameter level

Information level. One of:

0
1
2
3
10
11
20

Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserEnum() , NetGroupEnum() NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()


Method NetUserEnum

array(string|array(string|int)) System.NetUserEnum(string|int(0..0)|void server, int|void level, int|void filter)

Description

Get information about network users.

Parameter server

Server the users exist on.

Parameter level

Information level. One of:

0
1
2
3
10
11
20

Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo() , NetGroupEnum() NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()


Method NetGroupEnum

array(string|array(string|int)) System.NetGroupEnum(string|int(0..0)|void server, int|void level)

Description

Get information about network groups.

Parameter server

Server the groups exist on.

Parameter level

Information level. One of:

0
1
2

Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo() , NetUserEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()


Method NetLocalGroupEnum

array(array(string|int)) System.NetLocalGroupEnum(string|int(0..0)|void server, int|void level)

Description

Get information about local network groups.

Parameter server

Server the groups exist on.

Parameter level

Information level. One of:

0
1

Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()


Method NetUserGetGroups

array(array(string|int)) System.NetUserGetGroups(string|int(0..0) server, string user, int|void level)

Description

Get information about group membership for a network user.

Parameter server

Server the groups exist on.

Parameter user

User to retrieve groups for.

Parameter level

Information level. One of:

0
1

Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()


Method NetUserGetLocalGroups

array(string) System.NetUserGetLocalGroups(string|int(0..0) server, string user, int|void level, int|void flags)

Description

Get information about group membership for a local network user.

Parameter server

Server the groups exist on.

Parameter user

User to retrieve groups for.

Parameter level

Information level. One of:

0

Parameter flags

Zero, of one of the following:

LG_INCLUDE_INDIRECT

Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()


Method NetGroupGetUsers

array(string|array(int|string)) System.NetGroupGetUsers(string|int(0..0) server, string group, int|void level)

Description

Get information about group membership for a network group.

Parameter server

Server the groups exist on.

Parameter group

Group to retrieve members for.

Parameter level

Information level. One of:

0
1

Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()


Method NetLocalGroupGetMembers

array(string|array(int|string)) System.NetLocalGroupGetMembers(string|int(0..0) server, string group, int|void level)

Description

Get information about group membership for a network group.

Parameter server

Server the groups exist on.

Parameter group

Group to retrieve members for.

Parameter level

Information level. One of:

0
1
2
3

Returns

Returns an array on success. Throws errors on failure.

FIXME

Document the return value.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetGetDCName() , NetGetAnyDCName()


Method NetGetDCName

string System.NetGetDCName(string|int(0..0) server, string domain)

Description

Get name of the domain controller from a server.

Parameter server

Server the domain exists on.

Parameter domain

Domain to get the domain controller for.

Returns

Returns the name of the domain controller on success. Throws errors on failure.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetAnyDCName()


Method NetGetAnyDCName

string System.NetGetAnyDCName(string|int(0..0) server, string domain)

Description

Get name of a domain controller from a server.

Parameter server

Server the domain exists on.

Parameter domain

Domain to get a domain controller for.

Returns

Returns the name of a domain controller on success. Throws errors on failure.

Note

This function is only available on some Win32 systems.

See also

NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName()


Method NetSessionEnum

array(int|string) System.NetSessionEnum(string|int(0..0) server, string|int(0..0) client, string|int(0..0) user, int level)

Description

Get session information.

Parameter level

One of

0
1
2
10
502

Note

This function is only available on some Win32 systems.


Method NetWkstaUserEnum

array(mixed) System.NetWkstaUserEnum(string|int(0..0) server, int level)

Parameter level

One of

0
1

Note

This function is only available on some Win32 systems.


Method normalize_path

string System.normalize_path(string path)

Description

Normalize an NT filesystem path.

The following transformations are currently done:

  • Trailing slashes are removed.

  • Extraneous empty extensions are removed.

  • Short filenames are expanded to their corresponding long variants.

  • Forward slashes ('/') are converted to backward slashes ('\').

  • Current- and parent-directory paths are removed ("." and "..").

  • Relative paths are expanded to absolute paths.

  • Case-information is restored.

Returns

A normalized absolute path without trailing slashes.

Throws errors on failure, e.g. if the file or directory doesn't exist.

Note

File fork information is currently not supported (invalid data).

See also

combine_path() , combine_path_nt()


Method GetFileAttributes

int System.GetFileAttributes(string filename)

Description

Get the file attributes for the specified file.

Note

This function is only available on Win32 systems.

See also

SetFileAttributes()


Method SetFileAttributes

int System.SetFileAttributes(string filename)

Description

Set the file attributes for the specified file.

Note

This function is only available on Win32 systems.

See also

GetFileAttributes()


Method LookupAccountName

array(mixed) System.LookupAccountName(string|int(0..0) sys, string account)

Note

This function is only available on some Win32 systems.


Method SetNamedSecurityInfo

array(mixed) System.SetNamedSecurityInfo(string name, mapping(string:mixed) options)

Note

This function is only available on some Win32 systems.

See also

GetNamedSecurityInfo()


Method GetNamedSecurityInfo

mapping(mixed:mixed) System.GetNamedSecurityInfo(string name, int|void type, int|void flags)

Note

This function is only available on some Win32 systems.

See also

SetNamedSecurityInfo()


Method setpwent

int System.setpwent()

Description

Resets the getpwent function to the first entry in the passwd source using the systemfunction setpwent(3).

Returns

Always 0 (zero)

See also

get_all_users() getpwent() endpwent()


Method endpwent

int System.endpwent()

Description

Closes the passwd source opened by getpwent function using the systemfunction endpwent(3).

Returns

Always 0 (zero)

See also

get_all_users() getpwent() setpwent()


Method getpwent

array(int|string) System.getpwent()

Description

When first called, the getpwent function opens the passwd source and returns the first record using the systemfunction getpwent(3). For each following call, it returns the next record until EOF.

Call endpwent when done using getpwent .

Returns

An array with the information about the user

Array
string 0

Users username (loginname)

string 1

User password (encrypted)

int 2

Users ID

int 3

Users primary group ID

string 4

Users real name an possibly some other info

string 5

Users home directory

string 6

Users shell


0 if EOF.

See also

get_all_users() getpwnam() getpwent() setpwent() endpwent()


Method setgrent

int System.setgrent()

Description

Rewinds the getgrent pointer to the first entry

See also

get_all_groups() getgrent() endgrent()


Method endgrent

int System.endgrent()

Description

Closes the /etc/groups file after using the getgrent function.

See also

get_all_groups() getgrent() setgrent()


Method getgrent

array(int|string|array(string)) System.getgrent()

Description

Get a group entry from /etc/groups file. getgrent interates thru the groups source and returns one entry per call using the systemfunction getgrent(3).

Always call endgrent when done using getgrent !

Returns

An array with the information about the group

Array
string 0

Group name

string 1

Group password (encrypted)

int 2

ID of the group

array 3..

Array with UIDs of group members


See also

get_all_groups() getgrnam() getgrgid()


Method openlog

void System.openlog(string ident, int options, facility)

Description

Initializes the connection to syslogd.

Parameter ident.

The ident argument specifies an identifier to tag all logentries with.

Parameter options

A bitfield specifying the behaviour of the message logging. Valid options are:

LOG_PID

Log the process ID with each message.

LOG_CONS

Write messages to the console if they can't be sent to syslogd.

LOG_NDELAY

Open the connection to syslogd now and not later.

LOG_NOWAIT

Do not wait for subprocesses talking to syslogd.


Parameter facility

Specifies what subsystem you want to log as. Valid facilities are:

LOG_AUTH

Authorization subsystem

LOG_AUTHPRIV 
LOG_CRON

Crontab subsystem

LOG_DAEMON

System daemons

LOG_KERN

Kernel subsystem (NOT USABLE)

LOG_LOCAL

For local use

LOG_LOCAL1
LOG_LOCAL2
LOG_LOCAL3
LOG_LOCAL4
LOG_LOCAL5
LOG_LOCAL6
LOG_LOCAL7
LOG_LPR

Line printer spooling system

LOG_MAIL

Mail subsystem

LOG_NEWS

Network news subsystem

LOG_SYSLOG 
LOG_USER 
LOG_UUCP

UUCP subsystem


Note

Only available on systems with syslog(3).

Bugs

LOG_NOWAIT should probably always be specified.

See also

syslog , closelog


Method syslog

void System.syslog(int a, string b)

FIXME

Document this function.


Method closelog

void System.closelog()

FIXME

Document this function.


Method hardlink

void System.hardlink(string from, string to)

Description

Create a hardlink named to from the file from .

Note

This function is not available on all platforms.

See also

symlink() , mv() , rm()


Method symlink

void System.symlink(string from, string to)

Description

Create a symbolic link named to that points to from .

Note

This function is not available on all platforms.

See also

hardlink() , readlink() , mv() , rm()


Method readlink

string System.readlink(string path)

Description

Returns what the symbolic link path points to.

Note

This function is not available on all platforms.

See also

symlink()


Method resolvepath

string System.resolvepath(string path)

Description

Resolve all symbolic links of a pathname.

Note

This function is not available on all platforms.

See also

readlink() , symlink()


Method umask

int System.umask(void|int mask)

Description

Set the current umask to mask .

If mask is not specified the current umask will not be changed.

Returns

Returns the old umask setting.


Method chmod

void System.chmod(string path, int mode)

Description

Sets the protection mode of the specified path.

Note

Throws errors on failure.

See also

Stdio.File->open() , errno()


Method chown

void System.chown(string path, int uid, int gid)

Description

Sets the owner and group of the specified path.

Note

Throws errors on failure.

This function is not available on all platforms.


Method utime

void System.utime(string path, int atime, int mtime)

Description

Set the last access time and last modification time for the path path to atime and mtime repectively.

Note

Throws errors on failure.

This function is not available on all platforms.


Method initgroups

void System.initgroups(string name, int base_gid)

Description

Initializes the supplemental group access list according to the system group database. base_gid is also added to the group access list.

Note

Throws errors on failure.

This function is not available on all platforms.

See also

setuid() , getuid() , setgid() , getgid() , seteuid() , geteuid() , setegid() , getegid() , getgroups() , setgroups()


Method cleargroups

void System.cleargroups()

Description

Clear the supplemental group access list.

Note

Throws errors on failure.

This function is not available on all platforms.

See also

setgroups() , initgroups() , getgroups()


Method setgroups

void System.setgroups(array(int) gids)

Description

Set the supplemental group access list for this process.

Note

Throws errors on failure.

This function is not available on all platforms.

See also

initgroups() , cleargroups() , getgroups() , getgid() , getgid() , getegid() , setegid()


Method getgroups

array(int) System.getgroups()

Description

Get the current supplemental group access list for this process.

Note

Throws errors on failure.

This function is not available on all platforms.

See also

setgroups() , cleargroups() , initgroups() , getgid() , getgid() , getegid() , setegid()


Method innetgr

int(0..1) System.innetgr(string netgroup, string|void machine, string|void user, string|void domain)

Description

Searches for matching entries in the netgroup database (usually /etc/netgroup). If any of the machine , user or domain arguments are zero or missing, those fields will match any value in the selected netgroup .

Note

This function isn't available on all platforms.


Method setuid

int System.setuid(int uid)

Description

Sets the real user ID, effective user ID and saved user ID to uid .

Returns

Returns the current errno.

Note

This function isn't available on all platforms.

See also

getuid() , setgid() , getgid() , seteuid() , geteuid() , setegid() , getegid()


Method setgid

int System.setgid(int gid)

Description

Sets the real group ID, effective group ID and saved group ID to gid . If gid is -1 the uid for "nobody" will be used.

Throws

Throws an error if no "nobody" user when gid is -1.

Returns

Returns the current errno.

Note

This function is not available on all platforms.

See also

getuid() , setuid() , getgid() , seteuid() , geteuid() , setegid() , getegid()


Method seteuid

int System.seteuid(int euid)

Description

Set the effective user ID to euid . If euid is -1 the uid for "nobody" will be used.

Returns

Returns the current errno.

Throws

Throws an error if there is no "nobody" user when euid is -1.

Note

This function isn't available on all platforms.


Method setegid

int System.setegid(int egid)

Description

Set the effective group ID to egid . If egid is -1 the uid for "nobody" will be used.

Returns

Returns the current errno.

Throws

Throws an error if there is no "nobody" user when egid is -1.

Note

This function isn't available on all platforms.


Method getpgrp

int System.getpgrp(int|void pid)

Description

Get the process group id for the process pid . With no argguments or with 'pid' equal to zero, returns the process group ID of this process.

Note

Not all platforms support getting the process group for other processes.

Not supported on all platforms.

See also

getpid , getppid


Method setpgrp

int System.setpgrp()

Description

Make this process a process group leader.

Note

Not supported on all platforms.


Method getsid

int System.getsid(int|void pid)

Description

Get the process session ID for the given process. If pid is not specified, the session ID for the current process will be returned.

Note

This function is not available on all platforms.

Throws

Throws an error if the system call fails.

See also

getpid , getpgrp , setsid


Method setsid

int System.setsid()

Description

Set a new process session ID for the current process, and return it.

Note

This function isn't available on all platforms.

Throws

Throws an error if the system call fails.

See also

getpid , setpgrp , getsid


Method dumpable

int(0..1) System.dumpable(int(0..1)|void val)

Description

Get and/or set whether this process should be able to dump core.

Parameter val

Optional argument to set the core dumping state.

0

Disable core dumping for this process.

1

Enable core dumping for this process.


Returns

Returns 1 if this process currently is capable of dumping core, and 0 (zero) if not.

Note

This function is currently only available on some versions of Linux.


Method setresuid

int System.setresuid(int ruid, int euid, int suid)

Description

Sets the real, effective and saved set-user-ID to ruid , euid and suid respectively.

Returns

Returns zero on success and errno on failure.


Method setresgid

int System.setresgid(int rgid, int egid, int sgid)

Description

Sets the real, effective and saved group ID to rgid , egid and sgid respectively.

Returns

Returns zero on success and errno on failure.


Method getuid

int System.getuid()

Description

Get the real user ID.

See also

setuid , setgid , getgid , seteuid , geteuid , setegid , getegid


Method getgid

int System.getgid()

Description

Get the real group ID.

See also

setuid , getuid , setgid , seteuid , geteuid , getegid , setegid


Method geteuid

int System.geteuid()

Description

Get the effective user ID.

See also

setuid , getuid , setgid , getgid , seteuid , getegid , setegid


Method getegid

int System.getegid()

Description

Get the effective group ID.

See also

setuid , getuid , setgid , getgid , seteuid , geteuid , setegid


Method getpid

int System.getpid()

Description

Returns the process ID of this process.

See also

getppid , getpgrp


Method getppid

int System.getppid()

Description

Returns the process ID of the parent process.

See also

getpid , getpgrp


Method chroot

int System.chroot(string newroot)
int System.chroot(Stdio.File newroot)

Description

Changes the root directory for this process to the indicated directory.

Returns

A nonzero value is returned if the call is successful. If there's an error then zero is returned and errno is set appropriately.

Note

Since this function modifies the directory structure as seen from Pike, you have to modify the environment variables PIKE_MODULE_PATH and PIKE_INCLUDE_PATH to compensate for the new root-directory.

This function only exists on systems that have the chroot(2) system call.

The second variant only works on systems that also have the fchroot(2) system call.


Method uname

mapping(string:string) System.uname()

Description

Get operating system information.

Returns

The resulting mapping contains the following fields:

"sysname" : string

Operating system name.

"nodename" : string

Hostname.

"release" : string

Operating system release.

"version" : string

Operating system version.

"machine" : string

Hardware architecture.

"architecture" : string

Basic instruction set architecture.

"isalist" : string

List of upported instruction set architectures. Usually space-separated.

"platform" : string

Specific model of hardware.

"hw provider" : string

Manufacturer of the hardware.

"hw serial" : string

Serial number of the hardware.

"srpc domain" : string

Secure RPC domain.


Note

This function only exists on systems that have the uname(2) or sysinfo(2) system calls.

Only the first five elements are always available.


Method gethostname

string System.gethostname()

Description

Returns a string with the name of the host.

Note

This function only exists on systems that have the gethostname(2) or uname(2) system calls.


Method gethostbyaddr

array(string|array(string)) System.gethostbyaddr(string addr)

Description

Returns an array with information about the specified IP address.

Returns

The returned array contains the same information as that returned by gethostbyname() .

Note

This function only exists on systems that have the gethostbyaddr(2) or similar system call.

See also

gethostbyname()


Method gethostbyname

array(string|array(string)) System.gethostbyname(string hostname)

Description

Returns an array with information about the specified host.

Returns

The returned array contains the following:

Array
string hostname

Name of the host.

array(string) ips

Array of IP numbers for the host.

array(string) aliases

Array of alternative names for the host.


Note

This function only exists on systems that have the gethostbyname(2) or similar system call.

See also

gethostbyaddr()


Method sleep

int System.sleep(int seconds)

Description

Call the system sleep() function.

This is not to be confused with the global function predef::sleep() that does more elaborate things and can sleep with better precision (although dependant on a normal functioning system clock).

Note

The system's sleep function often utilizes the alarm(2) call and might not be perfectly thread safe in combination with simultaneous sleep()'s or alarm()'s. It might also be interrupted by other signals.

If you don't need it to be independant of the system clock, use predef::sleep() instead.

May not be present; only exists if the function exists in the current system.

See also

predef::sleep() usleep() nanosleep()


Method usleep

void System.usleep(int usec)

Description

Call the system usleep() function.

This is not to be confused with the global function predef::sleep() that does more elaborate things and can sleep with better precision (although dependant on a normal functioning system clock).

Note

The system's usleep function often utilizes the alarm(2) call and might not be perfectly thread safe in combination with simultaneous sleep()'s or alarm()'s. It might also be interrupted by other signals.

If you don't need it to be independant of the system clock, use predef::sleep() instead.

May not be present; only exists if the function exists in the current system.

See also

predef::sleep() sleep() nanosleep()


Method nanosleep

float System.nanosleep(int|float seconds)

Description

Call the system nanosleep() function.

This is not to be confused with the global function predef::sleep() that does more elaborate things and can sleep with better precision (although dependant on a normal functioning system clock).

Returns the remaining time to sleep (as the system function does).

See also

predef::sleep() sleep() usleep()

Note

May not be present; only exists if the function exists in the current system.


Method getrlimit

array(int) System.getrlimit(string resource)

Description

Returns the current process limitation for the selected resource .

Parameter resource
cpu

The CPU time limit in seconds.

fsize

The maximum size of files the process may create.

data

The maximum size of the process's data segment.

stack

The maximum size of process stack, in bytes.

core 
rss

Specifies the limit of pages the process's resident set.

nproc

The maximum number of processes that can be created for the real user ID of the calling process.

nofile

The maximum number of file descriptors the process can open, +1.

memlock

The maximum number of bytes of virtual memory that may be locked into RAM.

as 
vmem 

Returns
Array
int 0

The soft limit for the resource. -1 means no limit.

int 1

The hard limit for the resource. -1 means no limit.


Note

This function nor all the resources are available on all systems.

See also

getrlimits , setrlimit


Method getrlimits

mapping(string:array(int)) System.getrlimits()

Description

Returns all process limits in a mapping.

See also

getrlimit , setrlimit


Method setrlimit

int(0..1) System.setrlimit(string resource, int soft, int hard)

Description

Sets the soft and the hard process limit on a resource .

See also

getrlimit , getrlimits


Constant ITIMER_REAL

constant System.ITIMER_REAL

Description

Identifier for a timer that decrements in real time.

See also

setitimer , getitimer


Constant ITIMER_VIRTUAL

constant System.ITIMER_VIRTUAL

Description

Identifier for a timer that decrements only when the process is executing.

See also

setitimer , getitimer


Constant ITIMER_PROF

constant System.ITIMER_PROF

Description

Identifier for a timer that decrements both when the process is executing and when the system is executing on behalf of the process.

See also

setitimer , getitimer


Method setitimer

float System.setitimer(int timer, int|float value)

Description

Sets the timer to the supplied value . Returns the current timer interval.

Parameter timer

One of ITIMER_REAL , ITIMER_VIRTUAL and ITIMER_PROF .


Method getitimer

array(float) System.getitimer(int timer)

Description

Shows the state of the selected timer .

Returns
Array
float 0

The interval of the timer.

float 1

The value of the timer.


Parameter timer

One of ITIMER_REAL , ITIMER_VIRTUAL and ITIMER_PROF .


Method get_netinfo_property

array(string) System.get_netinfo_property(string domain, string path, string property)

Description

Queries a NetInfo server for property values at the given path.

Parameter domain

NetInfo domain. Use "." for the local domain.

Parameter path

NetInfo path for the property.

Parameter property

Name of the property to return.

Returns

An array holding all property values. If the path or property cannot be not found 0 is returned instead. If the NetInfo domain is not found or cannot be queried an exception is thrown.

Example

system.get_netinfo_property(".", "/locations/resolver", "domain"); ({ "idonex.se" })

Note

Only available on operating systems which have NetInfo libraries installed.


Method rdtsc

int System.rdtsc()

Description

Executes the rdtsc (clock pulse counter) instruction and returns the result.


Method gettimeofday

array(int) System.gettimeofday()

Description

Calls gettimeofday(); the result is an array of seconds, microseconds, and possible tz_minuteswes, tz_dstttime as given by the gettimeofday(2) system call (read the man page).

See also

time() , gethrtime()


Variable CPU_TIME_IS_THREAD_LOCAL

string System.CPU_TIME_IS_THREAD_LOCAL

Description

This string constant tells whether or not the CPU time returned by gethrvtime is thread local or not. The value is "yes" if it is and "no" if it isn't. The value is also "no" if there is no thread support.


Method getrusage

mapping(string:int) System.getrusage()

Description

Return resource usage about the current process. An error is thrown if it isn't supported or if the system fails to return any information.

Returns

Returns a mapping describing the current resource usage:

"utime" : int

Time in milliseconds spent in user code.

"stime" : int

Time in milliseconds spent in system calls.

"maxrss" : int

Maximum used resident size in kilobytes. [1]

"ixrss" : int

Quote from GNU libc: An integral value expressed in kilobytes times ticks of execution, which indicates the amount of memory used by text that was shared with other processes. [1]

"idrss" : int

Quote from GNU libc: An integral value expressed the same way, which is the amount of unshared memory used for data. [1]

"isrss" : int

Quote from GNU libc: An integral value expressed the same way, which is the amount of unshared memory used for stack space. [1]

"minflt" : int

Minor page faults, i.e. TLB misses which required no disk I/O.

"majflt" : int

Major page faults, i.e. paging with disk I/O required.

"nswap" : int

Number of times the process has been swapped out entirely.

"inblock" : int

Number of block input operations.

"oublock" : int

Number of block output operations.

"msgsnd" : int

Number of IPC messsages sent.

"msgrcv" : int

Number of IPC messsages received.

"nsignals" : int

Number of signals received.

"nvcsw" : int

Number of voluntary context switches (usually to wait for some service).

"nivcsw" : int

Number of preemptions, i.e. context switches due to expired time slices, or when processes with higher priority were scheduled.

"sysc" : int

Number of system calls. [2]

"ioch" : int

Number of characters read and written. [2]

"rtime" : int

Elapsed real time (ms). [2]

"ttime" : int

Elapsed system trap (system call) time (ms). [2]

"tftime" : int

Text page fault sleep time (ms). [2]

"dftime" : int

Data page fault sleep time (ms). [2]

"kftime" : int

Kernel page fault sleep time (ms). [2]

"ltime" : int

User lock wait sleep time (ms). [2]

"slptime" : int

Other sleep time (ms). [2]

"wtime" : int

Wait CPU (latency) time (ms). [2]

"stoptime" : int

Time spent in stopped (suspended) state. [2]

"brksize" : int

Heap size. [3]

"stksize" : int

Stack size. [3]


Note

[1] Not if /proc rusage is used.

[2] Only from (Solaris?) /proc rusage.

[3] Only from /proc PRS usage.

On some systems, only utime will be filled in.

See also

gethrvtime()

  CLASS System.Memory

Description

A popular demand is a class representing a raw piece of memory or a mmap'ed file. This is usually not the most effective way of solving a problem, but it might help in rare situations.

Using mmap can lead to segmentation faults in some cases. Beware, and read about mmap before you try anything. Don't blame Pike if you shoot your foot off.


Method create

void System.Memory()
void System.Memory(string|Stdio.File filename_to_mmap)
void System.Memory(int shmkey, int shmsize, int shmflg)
void System.Memory(int bytes_to_allocate)

Description

Will call mmap() or allocate() depending on argument, either mmap'ing a file (in shared mode, writeable if possible) or allocating a chunk of memory.


Method mmap
Method mmap_private

int mmap(string|Stdio.File file)
int mmap(string|Stdio.File file, int offset, int size)
int mmap_private(string|Stdio.File file)
int mmap_private(string|Stdio.File file, int offset, int size)

Description

mmap a file. This will always try to mmap the file in PROT_READ|PROT_WRITE, readable and writable, but if it fails it will try once more in PROT_READ only.


Method allocate

void allocate(int bytes)
void allocate(int bytes, int(0..255) fill)


Method free

void free()

Description

Free the allocated or <tt>mmap</tt>ed memory.


Method _sizeof

int _sizeof()

Description

returns the size of the memory (bytes). note: throws if not allocated


Method valid

int(0..1) valid()

Description

returns 1 if the memory is valid, 0 if not allocated


Method writeable

int(0..1) writeable()

Description

returns 1 if the memory is writeable, 0 if not


Method cast

string|array cast(string to)

Description

Cast to string or array.

Note

Throws if not allocated.


Method pread
Method pread16
Method pread32
Method pread16i
Method pread32i
Method pread16n
Method pread32n

string pread(int(0..) pos, int(0..) len)
string pread16(int(0..) pos, int(0..) len)
string pread32(int(0..) pos, int(0..) len)
string pread16i(int(0..) pos, int(0..) len)
string pread32i(int(0..) pos, int(0..) len)
string pread16n(int(0..) pos, int(0..) len)
string pread32n(int(0..) pos, int(0..) len)

Description

Read a string from the memory. The 16 and 32 variants reads widestrings, 16 or 32 bits (2 or 4 bytes) wide, the i variants in intel byteorder, the normal in network byteorder, and the n variants in native byteorder.

len is the number of characters, wide or not. pos is the byte position (!).


Method pwrite
Method pwrite16
Method pwrite32
Method pwrite16i
Method pwrite32i

int pwrite(int(0..) pos, string data)
int pwrite16(int(0..) pos, string data)
int pwrite32(int(0..) pos, string data)
int pwrite16i(int(0..) pos, string data)
int pwrite32i(int(0..) pos, string data)

Description

Write a string to the memory (and to the file, if it's mmap()ed). The 16 and 32 variants writes widestrings, 16 or 32 bits (2 or 4 bytes) wide, the 'i' variants in intel byteorder, the other in network byteorder.

returns the number of bytes (not characters) written


Method `[]

int `[](int pos)
string `[](int pos1, int pos2)


Method `[]=

int `[]=(int pos, int char)
string `[]=(int pos1, int pos2, string str)

  CLASS System.Time

Description

The current time as a structure containing a sec and a usec member.


int sec
int usec

Description

The number of seconds and microseconds since the epoch and the last whole second, respectively. (See also predef::time() )

Please note that these variables will continually update when they are requested, there is no need to create new Time() objects.


Variable usec_full

int usec_full

Description

The number of microseconds since the epoch. Please note that pike has to have been compiled with bignum support for this variable to contain sensible values.


Method create

void System.Time(int fast)

Description

If fast is true, do not request a new time from the system, instead use the global current time variable.

This will only work in callbacks, but can save significant amounts of CPU.

  CLASS System.Timer


Method peek

float peek()

Description

Return the time in seconds since the last time get was called.


Method get

float get()

Description

Return the time in seconds since the last time get was called. The first time this method is called the time since the object was created is returned instead.


Method create

void System.Timer(int|void fast)

Description

Create a new timer object. The timer keeps track of relative time with sub-second precision.

If fast is specified, the timer will not do system calls to get the current time but instead use the one maintained by pike. This will result in faster but somewhat more inexact timekeeping. Also, if your program never utilizes the pike event loop the pike maintained current time never change.

  Module Error

  CLASS Error.Generic

Description

Class for exception objects for errors of unspecified type.


Method cast

array cast(string type)

Description

Cast operator.

Note

The only supported type to cast to is "array", which generates and old-style error.


Method `[]

array|string `[](int(0..1) index)

Description

Index operator.

Simulates an array

Array
string msg

Error message.

array backtrace

Backtrace as returned by backtrace() from where the error occurred.


Note

The error message is always terminated with a newline.

See also

backtrace()


Method describe

string describe()

Description

Return a readable error report that includes the backtrace.


Method message

string message()

Description

Return a readable message describing the error.


Method backtrace

array backtrace()

Description

Return the backtrace where the error occurred.

See also

predef::backtrace()


Method _sprintf

string _sprintf()


Method create

void Error.Generic(string message)

  Module Pike


constant Pike.WEAK_INDICES
constant Pike.WEAK_VALUES
constant Pike.WEAK

Description

Flags for use together with set_weak_flag and get_weak_flag . See set_weak_flag for details.


Method gc_parameters

mapping(string:float) Pike.gc_parameters(void|mapping(string:mixed) params)

Description

Set and get various parameters that control the operation of the garbage collector. The passed mapping contains the parameters to set. If a parameter is missing from the mapping, the current value will be filled in instead. The same mapping is returned. Thus an empty mapping, or no argument at all, causes a mapping with all current settings to be returned.

The following parameters are recognized:

"enabled" : int

If this is 1 then the gc is enabled as usual. If it's 0 then all automatically scheduled gc runs are disabled and the parameters below have no effect, but explicit runs through the gc function still works as usual. If it's -1 then the gc is completely disabled so that even explicit gc calls won't do anything.

"garbage_ratio_low" : float

As long as the gc time is less than gc_time_ratio, aim to run the gc approximately every time the ratio between the garbage and the total amount of allocated things is this.

"time_ratio" : float

When more than this fraction of the cpu time is spent in the gc, aim for gc_garbage_ratio_high instead of gc_garbage_ratio_low.

"garbage_ratio_high" : float

Upper limit for the garbage ratio - run the gc as often as it takes to keep it below this.

"average_slowness" : float

When predicting the next gc interval, use a decaying average with this slowness factor. It should be a value between 0.0 and 1.0 that specifies the weight to give to the old average value. The remaining weight up to 1.0 is given to the last reading.


See also

gc , Debug.gc_status

  CLASS Pike.Backend


Method call_out

mixed call_out(function f, float|int delay, mixed ... args)

Description

Make a delayed call to a function.

call_out() places a call to the function f with the argument args in a queue to be called in about delay seconds.

If f returns -1, no other call out or callback will be called by the backend in this round. I.e. `() will return right away. For the main backend that means it will immediately start another round and check files and call outs anew.

Returns

Returns a call_out identifier that identifies this call_out. This value can be sent to eg find_call_out() or remove_call_out() .

See also

remove_call_out() , find_call_out() , call_out_info()


Method _do_call_outs

int _do_call_outs()

Description

Do all pending call_outs.

This function runs all pending call_outs that should have been run if Pike returned to the backend. It should not be used in normal operation.

As a side-effect, this function sets the value returned by time(1) to the current time.

Returns

Zero if no call outs were called, nonzero otherwise.

See also

call_out() , find_call_out() , remove_call_out()


Method find_call_out

int find_call_out(function f)
int find_call_out(mixed id)

Description

Find a call out in the queue.

This function searches the call out queue. If given a function as argument, it looks for the first call out scheduled to that function.

The argument can also be a call out id as returned by call_out() , in which case that call_out will be found (Unless it has already been called).

Returns

find_call_out() returns the remaining time in seconds before that call_out will be executed. If no call_out is found, zero_type (find_call_out (f)) will return 1.

See also

call_out() , remove_call_out() , call_out_info()


Method remove_call_out

int remove_call_out(function f)
int remove_call_out(function id)

Description

Remove a call out from the call out queue.

This function finds the first call to the function f in the call_out queue and removes it. You can also give a call out id as argument (as returned by call_out).

Returns

The remaining time in seconds left to that call out will be returned. If no call_out was found, zero_type (remove_call_out (f )) will return 1.

See also

call_out_info() , call_out() , find_call_out()


Method call_out_info

array(array) call_out_info()

Description

Get info about all call_outs.

This function returns an array with one entry for each entry in the call out queue. The first in the queue will be at index 0. Each index contains an array that looks like this:

Array
int time_left

Time remaining in seconds until the call_out is to be performed.

object caller

The object that scheduled the call_out.

function fun

Function to be called.

mixed ... args

Arguments to the function.


See also

call_out() , find_call_out() , remove_call_out()


Method `()

float|int(0..0) `()(void|float|int(0..0) sleep_time)

Description

Perform one pass through the backend.

Parameter sleep_time

Wait at most sleep_time seconds. The default when unspecified or the integer 0 is no time limit.

Returns

If the backend did call any callbacks or call outs then the time spent in the backend is returned as a float. Otherwise the integer 0 is returned.


Method executing_thread

Thread.Thread executing_thread()
int executing_thread()

Description

Return the thread currently executing in the backend. I.e. the thread that has called `() and haven't exited from that call. Zero is returned if there's no thread in the backend.

If Pike is compiled without thread support then 1 is returned if we're inside the backend, 0 otherwise.


Method add_file

void add_file(Stdio.File|Stdio.FILE f)

Description

Add f to this backend. This simply does f->set_backend(backend) where backend is this object.


Method id

int id()

Description

Return an integer that uniquely identifies this backend. For the default backend that integer is 0.

  CLASS Pike.BacktraceFrame


Method _is_type

int(0..1) _is_type(string t)

Description

This object claims to be an array for backward compatibility.


Method _sprintf

string _sprintf(int c, mapping|void opts)


Method _sizeof

int(3..) _sizeof()


Method `[]

mixed `[](int index, int|void end_or_none)

Description

The BacktraceFrame object can be indexed as an array.


Method `[]=

mixed `[]=(int index, mixed value)

  Module Pike.Security

Description

Pike has an optional internal security system, which can be enabled with the configure-option --with-security.

The security system is based on attaching credential objects (Pike.Security.Creds ) to objects, programs, arrays, mappings or multisets.

A credential object in essence holds three values:

user -- The owner.

allow_bits -- Run-time access permissions.

data_bits -- Data access permissions.


Method call_with_creds

mixed Pike.Security.call_with_creds(Creds creds, mixed func, mixed ... args)

Description

Call with credentials.

Sets the current credentials to creds , and calls func (@args ). If creds is 0 (zero), the credentials from the current object will be used.

Note

The current creds or the current object must have the allow bit BIT_SECURITY set to allow calling with creds other than 0 (zero).


Method get_current_creds

Creds Pike.Security.get_current_creds()

Description

Get the current credentials

Returns the credentials that are currently active. Returns 0 (zero) if no credentials are active.

See also

call_with_creds()


Method get_object_creds

Creds Pike.Security.get_object_creds(object|program|function|array|mapping|multiset o)

Description

Get the credentials from o .

Returns 0 if o does not have any credentials.


Constant BIT_INDEX

constant Pike.Security.BIT_INDEX

Description

Allow indexing.


Constant BIT_SET_INDEX

constant Pike.Security.BIT_SET_INDEX

Description

Allow setting of indices.


Constant BIT_CALL

constant Pike.Security.BIT_CALL

Description

Allow calling of functions.


Constant BIT_SECURITY

constant Pike.Security.BIT_SECURITY

Description

Allow usage of security related functions.


Constant BIT_NOT_SETUID

constant Pike.Security.BIT_NOT_SETUID

Description

Don't change active credentials on function call.


Constant BIT_CONDITIONAL_IO

constant Pike.Security.BIT_CONDITIONAL_IO

Description

Allow conditional useage of I/O. The callbacks valid_open and valid_io will be called in the User object in the current Creds object to determine if the I/O is allowed or not.


Constant BIT_DESTRUCT

constant Pike.Security.BIT_DESTRUCT

Description

Allow use of destruct .

  CLASS Pike.Security.Creds

Description

The credentials object.


Method get_default_creds

Creds get_default_creds()

Description

Get the default credentials.

Returns the default credentials object if it has been set. Returns 0 (zero) if it has not been set.

See also

set_default_creds()


Method set_default_creds

void set_default_creds(Creds creds)

Description

Set the default credentials

Note

The current creds must have the allow bit BIT_SECURITY set.

See also

get_default_creds()


Method create

void Pike.Security.Creds(User user, int allow_bits, int data_bits)

Description

Initialize a new credentials object.

Parameter allow_bits

Any of the flags BIT_SECURITY and BIT_CONDITIONAL_IO or:ed together.

Parameter data_bits

Any of the flags BIT_INDEX , BIT_SET_INDEX , BIT_CALL , BIT_NOT_SETUID and BIT_DESTRUCT or:ed together.

Throws

Throws an exception if the current creds doesn't have the allow bit BIT_SECURITY set.


Method get_user

object get_user()

Description

Get the user part.


Method get_allow_bits

int get_allow_bits()

Description

Get the allow_bit bitmask.


Method get_data_bits

int get_data_bits()

Description

Get the data_bits bitmask.


Method apply

void apply(object|program|function|array|mapping|multiset o)

Description

Set the credentials for o to this credentials object.

Note

To perform this operation the current credentials needs to have the bit BIT_SECURITY set, or have the same user as the old credentials and not change the user by performing the operation.

  CLASS Pike.Security.User

Description

Virtual class for User objects, used in Creds objects.


Method valid_open

int(0..3)|string valid_open(string type, object current, string filename, string flags, int access)

Description

This callback gets called when a new file is to be opened (and the Creds object has BIT_CONDITIONAL_IO set).

Parameter type

The type of file operation requested. Can either be "read" or "write".

Parameter current

The current object, i.e. the Fd object the user is trying to open.

Parameter filename

The file name requested.

Parameter flags

The flag string passed to open, e.g. "cwt".

Parameter access

The access flags requested for the file, e.g. 0666.

Returns

The function can either return a string, which means that the user is allowed to open a file, but the returned file should be opened instead, or it can return an integer. The integers are intepreted as follows.

0

The user was not allowed to open the file. ERRNO will be set to EPERM and an exception is thrown.

1

Do nothing, i.e. valid_open has initilized the current object with an open file. This can (natuarally) only be returned if a current object was given, which is not always the case.

2

The user was allowed to open the file and the open code proceeds.

3

The user was not allowed to open the file and an exception is thrown.



Method valid_io

int(0..3)|array valid_io(string fun, string type, mixed ... args)

Description

This callback gets called when I/O operations not performed on file objects are performed.

  Module Pike.DefaultBackend

Description

This is the Backend object that files and call_outs are handled by by default.

This is also the Backend object that will be used if main() returns -1.

See also

Backend , Stdio.File()->set_nonblocking() , call_out()

  Module Process


Method exec

int Process.exec(string file, string ... foo)


Method search_path

string Process.search_path(string command)


Method sh_quote

string Process.sh_quote(string s)


Method split_quoted_string

array(string) Process.split_quoted_string(string s, int(0..1)|void nt_mode)


Method spawn

Process Process.spawn(string s, object|void stdin, object|void stdout, object|void stderr, function|void cleanup, mixed ... args)


Method popen

string Process.popen(string s)


Method system

int Process.system(string s)

  CLASS Process.create_process

Description

This is the recommended and most portable way to start processes in Pike. The process object is a pike abstraction of the running system process, with methods for various process housekeeping.


Method wait

int wait()

Description

Waits for the process to end.

Returns
0..

The exit code of the process.

-1

The process was killed by a signal.


See also

TraceProcess()->wait()


Method status

int(-1..2) status()

Description

Returns the status of the process:

-1

Unknown

0

Running

1

Stopped

2

Exited


Note

Prior to Pike 7.5 the value 1 was returned for exited processes.


Method last_signal

int(0..) last_signal()

Description

Returns the last signal that was sent to the process.


Method pid

int pid()

Description

Returns the process identifier of the process.


Method set_priority

int set_priority(string priority)

Description

Sets the priority of the process. priority is one of the strings

realtime
highest
higher
high
low
lowest

Constant limit_value

constant limit_value

Description

Each limit_value may be either of:

integer

sets current limit, max is left as it is.

mapping

([ "hard":int, "soft":int ]) Both values are optional, hard <= soft.

array

({ hard, soft }), both can be set to the string "unlimited". A value of -1 means 'keep the old value'.

string

The string "unlimited" sets both the hard and soft limit to unlimited


Method create

void Process.create_process(array(string) command_args, void|mapping modifiers)

Parameter command_args

The command name and its command-line arguments. You do not have to worry about quoting them; pike does this for you.

Parameter modifiers

This optional mapping can can contain zero or more of the following parameters:

"cwd" : string

Execute the command in another directory than the current directory of this process. Please note that if the command is given is a relative path, it will be relative to this directory rather than the current directory of this process.

"chroot" : string

Chroot to this directory before executing the command.

"stdin" : Stdio.File

These parameters allows you to change the standard input, output and error streams of the newly created process. This is particularly useful in combination with Stdio.File.pipe .

"stdout" : Stdio.File
"stderr" : Stdio.File
"env" : mapping(string:string)

This mapping will become the environment variables for the created process. Normally you will want to only add or change variables which can be achived by getting the environment mapping for this process with getenv . See the examples section.

"uid" : int|string

This parameter changes which user the new process will execute as. Note that the current process must be running as UID 0 to use this option. The uid can be given either as an integer as a string containing the login name of that user.

The "gid" and "groups" for the new process will be set to the right values for that user unless overriden by options below.

(See setuid and getpwuid for more info.)

"gid" : int|string

This parameter changes the primary group for the new process. When the new process creates files, they will will be created with this group. The group can either be given as an int or a string containing the name of the group. (See setuid and getgrgid for more info.)

"setsid" : int(0..1)|Stdio.File

Set this to 1 to create a new session group. It is also possible to set it to a File object, in which case a new session group will be created with this file as the controlling terminal.

"setgroups" : array(int|string)

This parameter allows you to the set the list of groups that the new process belongs to. It is recommended that if you use this parameter you supply at least one and no more than 16 groups. (Some system only support up to 8...) The groups can be given as gids or as strings with the group names.

"noinitgroups" : int(0..1)

This parameter overrides a behaviour of the "uid" parameter. If this parameter is used, the gid and groups of the new process will be inherited from the current process rather than changed to the approperiate values for that uid.

"priority" : string

This sets the priority of the new process, see set_priority for more info.

"nice" : int

This sets the nice level of the new process; the lower the number, the higher the priority of the process. Note that only UID 0 may use negative numbers.

"keep_signals" : int(0..1)

This prevents Pike from restoring all signal handlers to their default values for the new process. Useful to ignore certain signals in the new process.

"fds" : array(Stdio.File|int(0..0))

This parameter allows you to map files to filedescriptors 3 and up. The file fds[0] will be remapped to fd 3 in the new process, etc.

"rlimit" : mapping(string:limit_value)

There are two values for each limit, the soft limit and the hard limit. Processes that do not have UID 0 may not raise the hard limit, and the soft limit may never be increased over the hard limit. The indices of the mapping indicate what limit to impose, and the values dictate what the limit should be. (See also System.setrlimit )

"core" : limit_value

maximum core file size in bytes

"cpu" : limit_value

maximum amount of cpu time used by the process in seconds

"data" : limit_value

maximum heap (brk, malloc) size in bytes

"fsize" : limit_value

maximum size of files created by the process in bytes

"map_mem" : limit_value

maximum size of the process's mapped address space (mmap() and heap size) in bytes

"mem" : limit_value

maximum size of the process's total amount of available memory (mmap, heap and stack size) in bytes

"nofile" : limit_value

maximum number of file descriptors the process may create

"stack" : limit_value

maximum stack size in bytes



Example

Process.create_process(({ "/usr/bin/env" }), (["env" : getenv() + (["TERM":"vt100"]) ]));

Example

//! Spawn a new process with the args @[args] and optionally a //! standard input if you provide such a @[Stdio.File] object. //! @returns //! Returns the new process and a pipe from which you can read //! its output. array(Process.Process|Stdio.File) spawn(Stdio.File|void stdin, string ... args) { Stdio.File stdout = Stdio.File(); mapping opts = ([ "stdout" : stdout->pipe() ]); if( stdin ) opts->stdin = stdin; return ({ Process.create_process( args, opts ), stdout }); }

Note

All parameters that accept both string or int input can be noticeably slower using a string instead of an integer; if maximum performance is an issue, please use integers.

The modifiers "fds", "uid", "gid", "nice", "noinitgroups", "setgroups", "keep_signals" and "rlimit" only exist on unix.


Method kill

int kill(int signal)

Note

This function is only available on platforms that support signals.

  CLASS Process.TraceProcess

Description

Class that enables tracing of processes.

The new process will be started in stopped state. Use cont() to let it start executing.

Note

This class currently only exists on systems that implement ptrace().


Inherit create_process

inherit create_process : create_process


Method wait

int wait()

Description

Waits for the process to stop.

Returns
0..

The exit code of the process.

-1

The process was killed by a signal.

-2

The process has stopped.


See also

create_process::wait()


Method cont

void cont(int|void signal)

Description

Allow a traced process to continue.

Parameter signal

Deliver this signal to the process.

Note

This function may only be called for stopped processes.

See also

wait()


Method exit

void exit()

Description

Cause the traced process to exit.

Note

This function may only be called for stopped processes.

See also

cont() , wait()

  CLASS Process.TraceProcess.Registers

Description

Interface to the current register contents of a stopped process.

See also

TraceProcess


Method `[]

int `[](int regno)

Description

Get the contents of register regno .

  CLASS Process.Process

Description

Slightly polished version of create_process .

See also

create_process


Inherit create_process

inherit create_process : create_process


Method create

void Process.Process(string|array(string) args, void|mapping(string:mixed) m)

Parameter args

Either a command line array, as the command_args argument to create_process() , or a string that will be splitted into a command line array by calling split_quoted_string() in an operating system dependant mode.

Parameter m

In addition to the modifiers that create_process accepts, this object also accepts

"read_callback" : function(Process:void)

This callback is called when there is data to be read from the process.

"timeout_callback" : function(Process:void)

This callback is called if the process times out.

"timeout" : int

The time it takes for the process to time out. Default is 15 seconds.


See also

create_process , split_quoted_string

  CLASS Process.Spawn


Method create

void Process.Spawn(string cmd, void|array(string) args, void|mapping(string:string) env, string|void cwd, void|array(Stdio.File|void) ownpipes, void|array(Stdio.File|void) fds_to_close)


Method kill

int kill(int signal)


Method wait

int wait()

  Module Thread


Method all_threads

array(Thread.Thread) Thread.all_threads()

Description

This function returns an array with the thread ids of all threads.

See also

Thread()


Method thread_set_concurrency

void Thread.thread_set_concurrency(int concurrency)

FIXME

Document this function


Method this_thread

Thread.Thread Thread.this_thread()

Description

This function returns the object that identifies this thread.

See also

Thread()


Inherit Thread

inherit Thread : Thread

  CLASS Thread.Thread


Method create

void Thread.Thread(function(mixed ... :void) f, mixed ... args)

Description

This function creates a new thread which will run simultaneously to the rest of the program. The new thread will call the function f with the arguments args . When f returns the thread will cease to exist.

All Pike functions are 'thread safe' meaning that running a function at the same time from different threads will not corrupt any internal data in the Pike process.

Returns

The returned value will be the same as the return value of this_thread() for the new thread.

Note

This function is only available on systems with POSIX or UNIX or WIN32 threads support.

See also

Mutex , Condition , this_thread()


Method backtrace

array(mixed) backtrace()

Description

Returns the current call stack for the thread.

Returns

The result has the same format as for predef::backtrace() .

See also

predef::backtrace()


Method status

int status()


Method _sprintf

string _sprintf(int c)

Description

Returns a string identifying the thread.


Method id_number

int id_number()

Description

Returns an id number identifying the thread.

Note

This function was added in Pike 7.2.204.


Method wait

mixed wait()

Description

Waits for the thread to complete, and then returns the value returned from the thread function.

  CLASS Thread.Mutex

Description

Mutex is a class that implements mutual exclusion locks. Mutex locks are used to prevent multiple threads from simultaneously execute sections of code which access or change shared data. The basic operations for a mutex is locking and unlocking. If a thread attempts to lock an already locked mutex the thread will sleep until the mutex is unlocked.

Note

This class is simulated when Pike is compiled without thread support, so it's always available.

In POSIX threads, mutex locks can only be unlocked by the same thread that locked them. In Pike any thread can unlock a locked mutex.


Method lock

MutexKey lock()
MutexKey lock(int type)

Description

This function attempts to lock the mutex. If the mutex is already locked by a different thread the current thread will sleep until the mutex is unlocked. The value returned is the 'key' to the lock. When the key is destructed or has no more references the mutex will automatically be unlocked.

The type argument specifies what lock() should do if the mutex is already locked by this thread:

0

Throw an error.

1

Sleep until the mutex is unlocked. Useful if some other thread will unlock it.

2

Return zero. This allows recursion within a locked region of code, but in conjunction with other locks it easily leads to unspecified locking order and therefore a risk for deadlocks.


Note

If the mutex is destructed while it's locked or while threads are waiting on it, it will continue to exist internally until the last thread has stopped waiting and the last MutexKey has disappeared, but further calls to the functions in this class will fail as is usual for destructed objects.

Note

Pike 7.4 and earlier destructed any outstanding lock when the mutex was destructed, but threads waiting in lock still got functioning locks as discussed above. This is inconsistent no matter how you look at it, so it was changed in 7.6. The old behavior is retained in compatibility mode for applications that explicitly destruct mutexes to unlock them.

See also

trylock()


Method trylock

MutexKey trylock()
MutexKey trylock(int type)

Description

This function performs the same operation as lock() , but if the mutex is already locked, it will return zero instead of sleeping until it's unlocked.

See also

lock()


Method current_locking_thread

Thread.Thread current_locking_thread()

Description

This mutex method returns the object that identifies the thread that has locked the mutex. 0 is returned if the mutex isn't locked.

See also

Thread()


Method current_locking_key

Thread.MutexKey current_locking_key()

Description

This mutex method returns the key object currently governing the lock on this mutex. 0 is returned if the mutex isn't locked.

See also

Thread()

  CLASS Thread.MutexKey

Description

Objects of this class are returned by Mutex()->lock() and Mutex()->trylock() . They are also passed as arguments to Condition()->wait() .

As long as they are held, the corresponding mutex will be locked.

The corresponding mutex will be unlocked when the object is destructed (eg by not having any references left).

See also

Mutex , Condition

  CLASS Thread.Condition

Description

Implementation of condition variables.

Condition variables are used by threaded programs to wait for events happening in other threads.

Note

Condition variables are only available on systems with thread support. The Condition class is not simulated otherwise, since that can't be done accurately without continuations.

See also

Mutex


Method wait

void wait(Thread.MutexKey mutex_key)

Description

Wait for contition.

This function makes the current thread sleep until the condition variable is signalled. The argument should be a Thread.MutexKey object for a Thread.Mutex . It will be unlocked atomically before waiting for the signal and then relocked atomically when the signal is received.

The thread that sends the signal should have the mutex locked while sending it. Otherwise it's impossible to avoid races where signals are sent while the listener(s) haven't arrived to the wait calls yet.

Note

In Pike 7.2 and earlier it was possible to call wait() without arguments. This possibility was removed in later versions since it unavoidably leads to programs with races and/or deadlocks.

See also

Mutex->lock()


Method signal

void signal()

Description

signal() wakes up one of the threads currently waiting for the condition.

Note

Sometimes more than one thread is woken up.

See also

broadcast()


Method broadcast

void broadcast()

Description

broadcast() wakes up all threads currently waiting for this condition.

See also

signal()

  CLASS Thread.Local

Description

Thread local variable storage.

This class allows you to have variables which are separate for each thread that uses it. It has two methods: get() and set() . A value stored in an instance of Local can only be retrieved by that same thread.

Note

This class is simulated when Pike is compiled without thread support, so it's always available.


Method get

mixed get()

Description

Get the thread local value.

This returns the value prevoiusly stored in the Local object by the set() method by this thread.

See also

set()


Method set

mixed set(mixed value)

Description

Set the thread local value.

This sets the value returned by the get method.

Calling this method does not affect the value returned by get() when it's called by another thread (ie multiple values can be stored at the same time, but only one value per thread).

Returns

This function returns its argument.

Note

Note that the value set can only be retreived by the same thread.

See also

get()

  CLASS Thread.Fifo

Description

Fifo implements a fixed length first-in, first-out queue. A fifo is a queue of values and is often used as a stream of data between two threads.

See also

Queue


Inherit r_cond

inherit Condition : r_cond


Inherit w_cond

inherit Condition : w_cond


Inherit lock

inherit Mutex : lock


Method size

int size()

Description

This function returns the number of elements currently in the fifo.

See also

read() , write()


Method read

mixed read()

Description

This function retrieves a value from the fifo. Values will be returned in the order they were written. If there are no values present in the fifo the current thread will sleep until some other thread writes one.

See also

try_read() , read_array() , write()


Method try_read

mixed try_read()

Description

This function retrieves a value from the fifo if there is any there. Values will be returned in the order they were written. If there are no values present in the fifo then UNDEFINED will be returned.

See also

read()


Method read_array

array read_array()

Description

This function returns all values in the fifo as an array. The values in the array will be in the order they were written. If there are no values present in the fifo the current thread will sleep until some other thread writes one.

See also

read() , try_read_array()


Method try_read_array

array try_read_array()

Description

This function returns all values in the fifo as an array but doesn't wait if there are no values there. The values in the array will be in the order they were written.

See also

read_array()


Method write

int write(mixed value)

Description

Append a value to the end of the fifo. If there is no more room in the fifo the current thread will sleep until space is available. The number of items in the queue after the write is returned.

See also

read()


Method try_write

int try_write(mixed value)

Description

Append a value to the end of the fifo. If there is no more room in the fifo then zero will be returned, otherwise the number of items in the fifo after the write is returned.

See also

read()


Method create

void Thread.Fifo()
void Thread.Fifo(int size)

Description

Create a fifo. If the optional size argument is present it sets how many values can be written to the fifo without blocking. The default size is 128.

  CLASS Thread.Queue

Description

Queue implements a queue, or a pipeline. The main difference between Queue and Fifo is that Queue will never block in write(), only allocate more memory.

See also

Fifo


Inherit r_cond

inherit Condition : r_cond


Inherit lock

inherit Mutex : lock


Method size

int size()

Description

This function returns the number of elements currently in the queue.

See also

read() , write()


Method read

mixed read()

Description

This function retrieves a value from the queue. Values will be returned in the order they were written. If there are no values present in the queue the current thread will sleep until some other thread writes one.

See also

try_read() , write()


Method try_read

mixed try_read()

Description

This function retrieves a value from the queue if there is any there. Values will be returned in the order they were written. If there are no values present in the fifo then UNDEFINED will be returned.

See also

write()


Method read_array

array read_array()

Description

This function returns all values in the queue as an array. The values in the array will be in the order they were written. If there are no values present in the queue the current thread will sleep until some other thread writes one.

See also

read() , try_read_array()


Method try_read_array

array try_read_array()

Description

This function returns all values in the queue as an array but doesn't wait if there are no values there. The values in the array will be in the order they were written.

See also

read_array()


Method write

int write(mixed value)

Description

This function puts a value last in the queue. If the queue is too small to hold the value it will be expanded to make room. The number of items in the queue after the write is returned.

See also

read()

  Module Mapping


Constant delete

constant Mapping.delete

Description

Alias for m_delete()

  CLASS Mapping.Iterator

Description

An object of this class is returned by get_iterator() when called with a mapping.

See also

get_iterator


Inherit predef::Iterator

inherit predef::Iterator : predef::Iterator

  Module Multiset

  CLASS Multiset.Iterator

Description

An object of this class is returned by get_iterator() when called with a multiset.

See also

get_iterator


Inherit predef::Iterator

inherit predef::Iterator : predef::Iterator

  Module Audio

  Module Audio.Format

Description

Audio data format handling

Note

API remains marked "unstable".

  CLASS Audio.Format.MP3

Description

A MP3 file parser with ID3 tag support.


Inherit ANY

inherit .module.ANY : ANY


Method get_frame

mapping|int get_frame()

Description

Gets next frame from file

Frame is represented by the following mapping. It contains from parsed frame headers and frame data itself.

([ "bitrate": int "copyright": int(0..1), "data": frame_data, "emphasis": emphasis, "extension": "channels":0, "id":1, "layer":3, "original": int(0..1), "padding": int(0..1), "private": int(0..1), "sampling": int ])

  CLASS Audio.Format.ANY


Method read_file

this_program read_file(string filename, int|void nocheck)

Description

Reads data from file

See also

read_streamed


Method read_streamed

this_program read_streamed(string filename, int|void nocheck)

Description

Reads data from stream

Ie. for packetized data source the beggining of data is searched.

See also

read_file


Method read_string

this_program read_string(string data, int|void nocheck)

Description

Reads data from string


Method get_frame

string get_frame()

Description

Returns frame for current position and moves cursor forward.

Note

The operation is destructive. Ie. current data cursor is moved over.

See also

get_data , get_sample


Method get_sample

mapping get_sample()

Description

Returns sample for current position and moves cursor forward.

Note

The operation is destructive. Ie. current data cursor is moved over.

See also

get_frame , get_data


Method get_data

string get_data()

Description

Returns data only.

Note

The operation is destructive. Ie. current data cursor is moved over.

See also

get_frame , get_sample


Method check_format

int check_format()

Description

Check if data are correctly formated.


Method get_map

mapping get_map()

  Module Audio.Codec

  CLASS Audio.Codec.decoder

Description

Decoder object.

Note

It needs _Ffmpeg.ffmpeg module for real work.


Method create

void Audio.Codec.decoder(string|void codecname, object|void _codec)

Description

Creates decoder object

Parameter codecnum

Some of supported codec, like _Ffmpeg.CODEC_ID_*

Parameter _codec

The low level object will be used for decoder. By default _Ffmpeg.ffmpeg object will be used.

Note

Until additional library is implemented the second parameter _codec hasn't effect.

See also

_Ffmpeg.ffmpeg , _Ffmpeg.CODEC_ID_MP2


Method from_file

this_program from_file(Audio.Format.ANY file)

Description

Set codec type from file

It uses Audio.Format.ANY 's method get_map() to determine which codec should be used.

Parameter file

The object Audio.Format.ANY .


Method decode

mapping|int decode(int|void partial)

Description

Decodes audio data

Parameter partial

Only one frame will be decoded per call.

Returns

If successfull a mapping with decoded data and byte number of used input data is returned, 0 otherwise.


Method get_status

mapping get_status()

Description

Returns decoder status

  Module Cache

  CLASS Cache.cache

Description

This module serves as a front-end to different kinds of caching systems. It uses two helper objects to actually store data, and to determine expiration policies. Mechanisms to allow for distributed caching systems will be added in time, or at least that is the plan.


Method lookup

mixed lookup(string key)

Description

Looks in the cache for an element with the given key and, if available, returns it. Returns 0 if the element is not available


Method alookup

void alookup(string key, function(string:void) callback, int|float timeout, mixed ... args)

Description

Asynchronously look the cache up. The callback will be given as arguments the key, the value, and then any user-supplied arguments. If the timeout (in seconds) expires before any data could be retrieved, the callback is called anyways, with 0 as value.


Method store

void store(string key, mixed value, void|int max_life, void|float preciousness, void|multiset(string) dependants)

Description

Sets some value in the cache. Notice that the actual set operation might even not happen at all if the set data doesn't make sense. For instance, storing an object or a program in an SQL-based backend will not be done, and no error will be given about the operation not being performed.

Notice that while max_life will most likely be respected (objects will be garbage-collected at pre-determined intervals anyways), the preciousness . is to be seen as advisory only for the garbage collector If some data was stored with the same key, it gets returned. Also notice that max_life is relative and in seconds. dependants are not fully implemented yet. They are implemented after a request by Martin Stjerrholm, and their purpose is to have some weak form of referential integrity. Simply speaking, they are a list of keys which (if present) will be deleted when the stored entry is deleted (either forcibly or not). They must be handled by the storage manager.


Method delete

void delete(string key, void|int(0..1) hard)

Description

Forcibly removes some key. If the 'hard' parameter is supplied and true, deleted objects will also have their lfun::destroy method called upon removal by some backends (i.e. memory)


Method start_cleanup_cycle

void start_cleanup_cycle()


Method async_cleanup_cache

void async_cleanup_cache()


Method threaded_cleanup_cycle

void threaded_cleanup_cycle()


Method create

void Cache.cache(Cache.Storage.Base storage_mgr, Cache.Policy.Base policy_mgr, void|int cleanup_cycle_delay)

Description

Creates a new cache object. Required are a storage manager, and an expiration policy object.

  Module Cache.Policy

  CLASS Cache.Policy.Base

Description

Base class for cache expiration policies.


Method expire

void expire(Cache.Storage.Base storage)

Description

Expire callback.

This function is called to expire parts of storage .

Note

All Storage.Policy classes must MUST implement this method.

  CLASS Cache.Policy.Timed

Description

An access-time-based expiration policy manager.


Inherit Base

inherit Cache.Policy.Base : Base

  Module Cache.Storage

  CLASS Cache.Storage.Base

Description

Base class for cache storage managers.

All Cache.Storage managers must provide these methods.


Method first
Method next

int(0..0)|string first()
int(0..0)|string next()

Description

These two functions are an iterator over the cache. There is an internal cursor, which is reset by each call to first() . Subsequent calls to next() will iterate over all the contents of the cache.

These functions are not meant to be exported to the user, but are solely for the policy managers' benefit.


Method set

void set(string key, mixed value, void|int max_life, void|float preciousness, void|multiset(string) dependants)

Description

Data-object creation is performed here if necessary, or in get() depending on the backend.

This allows the storage managers to have their own data class implementation.


Method get

int(0..0)|Cache.Data get(string key, void|int(0..1) notouch)

Description

Fetch some data from the cache synchronously.

Note

Be careful, as with some storage managers it might block the calling thread for some time.


Method aget

void aget(string key, function(string:void) callback, mixed ... extra_callback_args)

Description

Fetch some data from the cache asynchronously.

callback() will get as first argument key , and as second argument 0 (cache miss) or an Cache.Data object, plus any additional argument that the user may have supplied.


Method delete

mixed delete(string key, void|int(0..1) hard)

Description

Delete the entry specified by key from the cache (if present).

If hard is 1, some backends may force a destruct() on the deleted value.

Dependants (if present) are automatically deleted.

Returns

Returns the deleted entry.

  Module Calendar


Constant nulltimerange

constant Calendar.nulltimerange = TimeRange

Description

This represents the null time range, which, to differ from the zero time range (the zero-length time range), isn't placed in time. This is the result of for instance `& between two strict non-overlapping timeranges - no time at all.

It has a constant, is_nulltimerange, which is non-zero. `! on this timerange is true.

  CLASS Calendar.Calendar

Description

This is the base class of the calendars.


Method now

.TimeRanges.TimeRange now()

Description

Give the zero-length time period of the current time.

  CLASS Calendar.Ruleset

Description

This is the container class for rules.


Method set_timezone

this_program set_timezone(string|.Rule.Timezone t)


Method set_language

this_program set_language(string|.Rule.Language lang)


Method set_abbr2zone

this_program set_abbr2zone(mapping(string:string) abbr2zone)

Description

Sets the guess-mapping for timezones. Default is the mapping:

AbbreviationInterpretationUTC
AMTAmerica/ManausUTC-4
ASTAmerica/CuracaoUTC-4
CDTAmerica/Costa_RicaUTC-5
CSTAmerica/El SalvadorUTC-6
ESTAmerica/PanamaUTC-5
GSTAsia/DubaiUTC+4
ISTAsia/JerusalemUTC+2
WSTAustralia/PerthUTC+8

See also

YMD.parse


Method set_rule

this_program set_rule(.Rule.Language|.Rule.Timezone rule)


Method clone

this_program clone()


Method `==

int(0..1) `==(this_program other)

  CLASS Calendar.TimeRange

Description

This is the base class (usually implemented by e.g. Calendar subclasses like Calendar.Second) for any time measurement and calendrar information. It defines all the things you can do with a time range or any time period.

A TimeRange doubles as both a fixed period in time, and an amount of time. For instance, a week plus a day moves the week-period one day ahead (unaligning it with the week period, and thereby reducing it to just 7 days), no matter when in time the actual day were.


Method add

TimeRange add(int n, void|TimeRange step)

Description

calculates the (promoted) time period n steps away; if no step is given, the step's length is of the same length as the called time period.

It is not recommended to loop by adding the increment time period to a shorter period; this can cause faults, if the shorter time period doesn't exist in the incremented period. (Like week 53, day 31 of a month or the leap day of a year.)

Recommended use are like this:

   // loop over the 5th of the next 10 months
   TimeRange month=Month()+1;
   TimeRange orig_day=month()->day(5);
   for (int i=0; i<10; i++)
   {
      month++;
      TimeRange day=month->place(orig_day);
      ...use day...
   }


Method beginning
Method end

TimeRange beginning()
TimeRange end()

Description

This gives back the zero-sized beginning or end of the called time period.

rule: range(t->beginning(),t->end())==t


Method calendar

Calendar calendar()

Description

Simply gives back the calendar in use, for instance Calendar.ISO or Calendar.Discordian.


Method strictly_preceeds
Method preceeds
Method is_previous_to
Method overlaps
Method contains
Method equals
Method is_next_to
Method succeeds
Method strictly_succeeds

int(0..1) strictly_preceeds(TimeRange what)
int(0..1) preceeds(TimeRange what)
int(0..1) is_previous_to(TimeRange what)
int(0..1) overlaps(TimeRange what)
int(0..1) contains(TimeRange what)
int(0..1) equals(TimeRange what)
int(0..1) is_next_to(TimeRange what)
int(0..1) succeeds(TimeRange what)
int(0..1) strictly_succeeds(TimeRange what)

Description

These methods exists to compare two periods of time on the timeline.

          case            predicates
 
 <-- past       future ->
 
 |----A----|              A strictly preceeds B,
              |----B----| A preceeds B
 
 |----A----|              A strictly preceeds B, A preceeds B,
           |----B----|    A is previous to B, A touches B
 
     |----A----|          A preceeds B,
           |----B----|    A overlaps B, A touches B
 
     |-------A-------|    A preceeds B, A ends with B
           |----B----|    A overlaps B, A contains B, A touches B,
 
     |-------A-------|    A preceeds B,  A succeeds B,
         |---B---|        A overlaps B, A contains B, A touches B
 
        |----A----|       A overlaps B, A touches B, A contains B
        |----B----|       A equals B, A starts with B, A ends with B
 
     |-------A-------|    A succeeds B, A starts with B
     |----B----|          A overlaps B, A contains B, A touches B
 
           |----A----|    A succeeds B,
     |----B----|          A overlaps B, A touches B
 
           |----A----|    A strictly succeeds B, A succeeds B
 |----B----|              A is next to B, A touches B
 
             |----A----|  A strictly succeeds B,
 |----B----|              A succeeds B
 
 

Note

These methods only check the range of the first to the last time in the period; use of combined time periods (SuperTimeRange s) might not give you the result you want.

See also

`&amp;


Method create

void Calendar.TimeRange("unix", int unixtime)
void Calendar.TimeRange("unix", int unixtime, int seconds_len)

Description

Create the timerange from unix time (as given by time(2)), with eventually the size of the time range in the same unit, seconds.


Method create

void Calendar.TimeRange("julian", int|float julian_day)

Description

Create the timerange from a julian day, the standardized method of counting days. If the timerange is more then a day, it will at least enclose the day.


Method create

void Calendar.TimeRange(TimeRange from)

Description

Create the timerange from another timerange.

This is useful when converting objects from one calendar to another. Note that the ruleset will be transferred to the new object, so this method can't be used to convert between timezones or languges - use set_timezone , set_language or set_ruleset to achieve this.

Note

The size of the new object may be inexact; a Month object can't comprehend seconds, for instance.


Method range
Method space
Method distance

TimeRange range(TimeRange other)
TimeRange space(TimeRange other)
TimeRange distance(TimeRange other)

Description

Derives different time periods in between the called timerange and the parameter timerange.

>- the past          the future -<
 |--called--|         |--other--|
 >------------ range -----------<
            >--space--<
 >----- distance -----<
 

See also: add, TimeRanges.range, TimeRanges.space, TimeRanges.distance


Method `/
Method how_many

int `/(TimeRange with)
int how_many(TimeRange with)

Description

This calculates how many instances of the given timerange has passed during the called timerange.

For instance, to figure out your age, create the timerange of your lifespan, and divide with the instance of a Year .


Method set_language
Method language

TimeRange set_language(Rule.Language lang)
TimeRange set_language(string lang)
Language language()

Description

Set or get the current language rule.


Method next
Method prev

TimeRange next()
TimeRange prev()

Description

Next and prev are compatible and convinience functions; a->next() is exactly the same as a+1; a=a->next() is a++.


Method offset_to

int offset_to(TimeRange x)

Description

Calculates offset to x; this compares two timeranges and gives the integer offset between the two starting points.

This is true for suitable a and b: a+a->offset_to(b)==b

By suitable means that a and b are of the same type and size. This is obviously true only if a+n has b as a possible result for any n.


Method place

TimeRange place(TimeRange this)
TimeRange place(TimeRange this, int(0..1) force)

Description

This will place the given timerange in this timerange, for instance, day 37 in the year - Year(1934)->place(Day(1948 d37)) => Day(1934 d37).

Note

The rules how to place things in different timeranges can be somewhat 'dwim'.


Method set_ruleset
Method ruleset

TimeRange set_ruleset(Ruleset r)
TimeRange ruleset(Ruleset r)

Description

Set or get the current ruleset.

Note

this may include timezone shanges, and change the time of day.


Method set_size

TimeRange set_size(TimeRange size)
TimeRange set_size(int n, TimeRange size)

Description

Gives back a new (or the same, if the size matches) timerange with the new size. If n are given, the resulting size will be n amounts of the given size.

Note

A negative size is not permitted; a zero one are.


Method set_timezone
Method timezone

TimeRange set_timezone(Timezone tz)
TimeRange set_timezone(string tz)
TimeZone timezone()

Description

Set or get the current timezone (including dst) rule.

Note

The time-of-day may very well change when you change timezone.

To get the time of day for a specified timezone, select the timezone before getting the time of day:

Year(2003)->...->set_timezone(TimeZone.CET)->...->hour(14)->...


Method `/
Method split

array(TimeRange) `/(int n)
array(TimeRange) split(int n)

Description

This divides the called timerange into n pieces. The returned timerange type is not neccesarily of the same type as the called one.

known bugs: These are currently not defined for supertimeranges .


Method subtract

TimeRange subtract(TimeRange what)

Description

This subtracts a period of time from another;

>- the past          the future -<
|-------called-------|
     |-------other--------|
<---->  <- called->subtract(other)
 
|-------called-------|
     |---third---|
<---->           <---> <- called->subtract(third)


Method `&

TimeRange `&(TimeRange with)

Description

Gives the cut on the called time period with another time period. The result is zero if the two periods doesn't overlap.

>- the past          the future -<
 |-------called-------|
      |-------other--------|
      >----- cut -----<
 


Method `*

TimeRange `*(int n)

Description

This changes the amount of time in the time period. t*17 is the same as doing t->set_size (t,17).


Method `+
Method `-

TimeRange `+(int n)
TimeRange `+(TimeRange offset)
TimeRange `-(int m)
TimeRange `-(TimeRange x)

Description

This calculates the (promoted) time period either n step away or with a given offset. These functions does use add to really do the job:

t+n         t->add(n)             t is a time period
t-n         t->add(-n)            offset is a time period
t+offset    t->add(1,offset)      n is an integer
t-offset    t->add(-1,offset)
n+t         t->add(n)
n-t         illegal
offset+t    offset->add(1,t)      | note this!
offset-t    offset->add(-1,t)     |

Mathematic rules:

x+(t-x) == t    x is an integer or a time period
(x+t)-x == t    t is a time period
(t+x)-x == t
o-(o-t) == t    o is a time period
t++ == t+1
t-- == t-1

Note

a-b does not give the distance between the start of a and b. Use the distance () function to calculate that.

The integer used to `+, `- and add are the number of steps the motion will be. It does never represent any fixed amount of time, like seconds or days.


Method `<
Method `>

int(0..1) `<(TimeRange compared_to)
int(0..1) `>(TimeRange compared_to)

Description

These operators sorts roughty on the periods place in time. The major use might be to get multiset to work, besides sorting events clearly defined in time.


Method `==
Method _equal

int(0..1) `==(TimeRange compared_to)
int(0..1) _equal(TimeRange compared_to)

Description

These two overloads the operator `== and the result of the equal function.

a==b is considered true if the two timeranges are of the same type, have the same rules (language, timezone, etc) and are the same timerange.

equal(a,b) are considered true if a and b are the same timerange, exactly the same as the equals method.

The __hash method is also present, to make timeranges possible to use as keys in mappings.

known bugs: _equal is not currently possible to overload, due to weird bugs, so equal uses `== for now.


Method `^

TimeRange `^(TimeRange with)

Description

Gives the exclusive-or on the called time period and another time period, ie the union without the cut. The result is zero if the two periods were the same.

>- the past          the future -<
 |-------called-------|
      |-------other--------|
 <----|               |---->   - exclusive or
 


Method `|

TimeRange `|(TimeRange with)

Description

Gives the union on the called time period and another time period.

>- the past          the future -<
 |-------called-------|
      |-------other--------|
 <----------union---------->
 

  CLASS Calendar.SuperTimeRange

Description
inherits TimeRange

This class handles the cases where you have a time period with holes. These can be created by the ^ or | operators on time ranges.


Method create

void Calendar.SuperTimeRange(array(TimeRange) parts)

Description

A SuperTimeRange must have at least two parts, two time ranges. Otherwise, it's either not a time period at all or a normal time period.

  Module Calendar.Austrian

Description

Same as the ISO calendar, but with austrian as the default language.

This calendar exist only for backwards compatible purposes.


Inherit ISO

inherit .ISO : ISO

  Module Calendar.Coptic

Description

This is the Coptic Orthodox Church calendar, that starts the 11th or 12th September and has 13 months.

Note

The (default) names of the months are different then other the emacs calendar; I do not know which ones are used - the difference seem to be only the transcription of the phonetic sounds (B <-> P, etc).

I do not know for how long back the calendar is valid, either. My sources claim that the calendar is synchronized with the Gregorian calendar, which is odd.


Inherit Gregorian

inherit .Gregorian : Gregorian

  Module Calendar.Discordian

Description

The Discordian calendar, as described on page 34 in the fourth edition of Principia Discordia.

Chaotic enough, it's quite simpler then the Gregorian calendar; weeks are 5 days, and evens up on a year. Months are 73 days.

The leap day is inserted at the 60th day of the first month (Chaos), giving the first month 74 days. The description of the calendar is a "perpetual date converter from the gregorian to the POEE calendar", so the leap years are the same as the gregorians.

The Principia calls months "seasons", but for simplicity I call them months in this calendar.

If anyone know more about how to treat the leap day - now it is inserted in the month and week where it lands, rather then being separated from month and weeks, I'm interested to know.

- Mirar, Pope of POEE.


Inherit Gregorian

inherit .Gregorian : Gregorian

  Module Calendar.Event

  CLASS Calendar.Event.Event

Description

Event is an abstract class, defining what methods an Event need to have.


Constant is_event

constant is_event

Description

This constant may be used to identify an event object.


Method next
Method previous

.TimeRanges.TimeRange next(void|.TimeRanges.TimeRange from, void|int(0..1) including)
.TimeRanges.TimeRange previous(void|.TimeRanges.TimeRange from, void|int(0..1) including)

Description

This calculates the next or previous occurance of the event, from the given timerange's start, including any event occuring at the start if that flag is set.

It returns zero if there is no next event.

These methods are virtual in the base class.


Method scan

array(.TimeRanges.TimeRange) scan(.TimeRanges.TimeRange in)

Description

This calculates the eventual events that is contained or overlapped by the given timerange. scan uses next , if not overloaded.

Example

Calendar.Event.Easter()->scan(Calendar.Year(2000)) => ({ Day(Sun 23 Apr 2000) })

Note

scan can return an array of overlapping timeranges.

This method must use in->calendar_object->type to create the returned timeranges, and must keep the ruleset.


Method scan_events

mapping(.TimeRanges.TimeRange:Event) scan_events(.TimeRanges.TimeRange in)

Description

Returns a mapping with time ranges mapped to events.


Method `|
Method ``|

SuperEvent `|(Event ... with)
SuperEvent ``|(Event with)

Description

Joins several events into one SuperEvent .


Method describe

string describe()

Description

Returns a description of the event.

  CLASS Calendar.Event.NullEvent

Description

A non-event.


Inherit Event

inherit Event : Event


Constant is_nullevent

constant is_nullevent

Description

This constant may be used to identify a NullEvent.

  CLASS Calendar.Event.Day_Event

Description

Day_Event is an abstract class, extending Event for events that are single days, using julian day numbers for the calculations.


Inherit Event

inherit Event : Event


Constant is_day_event

constant is_day_event

Description

This constant may be used to identify Day_Event objects.


Constant NODAY

constant NODAY

Description

Returned from scan_jd if the even searched for did not exist.


Method scan_jd

int scan_jd(.Calendar realm, int jd, int(-1..-1)|int(1..1) direction)

Description

These methods has to be defined, and is what really does some work. It should return the next or previos julian day (>jd) when the event occurs, or the constant NODAY if it doesn't.

Parameter direction
1

Forward (next),

-1

Backward (previous).



Method next

.TimeRanges.TimeRange next(void|.TimeRanges.TimeRange from, void|int(0..1) including)

Description

Uses the virtual method scan_jd .

See also

Event.next


Method previous

.TimeRanges.TimeRange previous(void|.TimeRanges.TimeRange from, void|int(0..1) including)

Description

Uses the virtual method scan_jd .

See also

Event.previous

  CLASS Calendar.Event.Nameday

Description

This is created by the Namedays classes to represent an event for a name.


Inherit Day_Event

inherit Day_Event : Day_Event


Constant is_nameday

constant is_nameday

Description

This constant may be used to identify Nameday objects.

  CLASS Calendar.Event.Namedays

Description

This contains a ruleset about namedays.


Inherit Event

inherit Event : Event


Constant is_namedays

constant is_namedays

Description

This constant may be used to identify Namedays .


Method names

array(string) names(.TimeRanges.TimeRange t)

Description

Gives back an array of names that occur during the time period, in no particular order.


Method namedays

mapping(.TimeRanges.TimeRange:array(string)) namedays(.TimeRanges.TimeRange t)

Description

Gives back an table of days with names that occur during the time period. Note that days without names will not appear in the returned mapping.

  CLASS Calendar.Event.SuperNamedays

Description

Container for merged Namedays objects.


Inherit Event

inherit Event : Event

  CLASS Calendar.Event.Gregorian_Fixed

Description

A set date of year, counting leap day in February, used for the Gregorian fixed events in the events list.

See also

Julian_Fixed


Inherit Day_Event

inherit Day_Event : Day_Event


Constant is_fixed

constant is_fixed

Description

This constant may be used to identify Gregorian_Fixed objects.


Method create

void Calendar.Event.Gregorian_Fixed(string id, string name, int(1..31) month_day, int(1..12) month, int extra)

  CLASS Calendar.Event.Julian_Fixed

Description

A set date of year, counting leap day in February, used for the Gregorian fixed events in the events list.

See also

Gregorian_Fixed


Inherit Gregorian_Fixed

inherit Gregorian_Fixed : Gregorian_Fixed


Constant is_julian_fixed

constant is_julian_fixed

Description

This constant may be used to identify Julian_Fixed objects.

  CLASS Calendar.Event.Date

Description

This class represents the event of a given gregorian date. For instance, Event.Date(12,10)->next(Day()) finds the next 12 of October.


Inherit Day_Event

inherit Day_Event : Day_Event


Method create

void Calendar.Event.Date(int(1..31) month_day, int(1..12) month)

Description

The event is created by a given month day and a month number (1=January, 12=December).

  CLASS Calendar.Event.Date_Weekday

Description

This class represents the event that a given gregorian date appears a given weekday. For instance, Event.Date_Weekday(12,10,5)->next(Day()) finds the next 12 of October that is a friday.


Inherit Day_Event

inherit Day_Event : Day_Event


Method create

void Calendar.Event.Date_Weekday(int month_day, int month, int weekday)

Description

The event is created by a given month day, a month number (1=January, 12=December), and a weekday number (1=Monday, 7=Sunday).

Note

The week day numbers used are the same as the day of week in the ISO calendar - the Gregorian calendar has 1=Sunday, 7=Saturday.

  CLASS Calendar.Event.Monthday_Weekday

Description

This class represents the event that a given gregorian day of month appears a given weekday. For instance, Event.Monthday_Weekday(13,5)->next(Day()) finds the next friday the 13th.


Inherit Day_Event

inherit Day_Event : Day_Event


Method create

void Calendar.Event.Monthday_Weekday(int month_day, int weekday)

Description

The event is created by a given month day, and a weekday number (1=Monday, 7=Sunday).

Note

The week day numbers used are the same as the day of week in the ISO calendar - the Gregorian calendar has 1=Sunday, 7=Saturday.

  CLASS Calendar.Event.Weekday

Description

This class represents any given weekday. For instance, Event.Weekday(5)->next(Day()) finds the next friday.

These are also available as the pre-defined events Events.monday , Events.tuesday , Events.wednesday , Events.thursday , Events.friday , Events.saturday and Events.sunday .


Inherit Day_Event

inherit Day_Event : Day_Event


Method create

void Calendar.Event.Weekday(int weekday, void|string id)

Description

The event is created by a given weekday number (1=Monday, 7=Sunday).

Note

The week day numbers used are the same as the day of week in the ISO calendar - the Gregorian calendar has 1=Sunday, 7=Saturday.

  CLASS Calendar.Event.Easter

Description

This class represents an easter.


Inherit Day_Event

inherit Day_Event : Day_Event


Method create

void Calendar.Event.Easter(void|int shift)

Description

shift is the year to shift from old to new style easter calculation. Default is 1582.


Method easter_yd

int easter_yd(int y, int yjd, int leap)

Description

Calculates the year day for the easter.

  CLASS Calendar.Event.Easter_Relative

Description

This class represents an easter relative event.


Inherit Easter

inherit Easter : Easter


Method create

void Calendar.Event.Easter_Relative(string id, string name, int offset)

  CLASS Calendar.Event.Orthodox_Easter_Relative

Description

This class represents an orthodox easter relative event.


Inherit Easter_Relative

inherit Easter_Relative : Easter_Relative


Method create

void Calendar.Event.Orthodox_Easter_Relative(string id, string name, int offset)

  CLASS Calendar.Event.Monthday_Weekday_Relative

Description

This class represents a monthday weekday relative event or n:th special weekday event, e.g. "fourth sunday before 24 dec" => md=24,mn=12,wd=7,n=-4


Inherit Gregorian_Fixed

inherit Gregorian_Fixed : Gregorian_Fixed


Method create

void Calendar.Event.Monthday_Weekday_Relative(string id, string name, int(1..31) md, int(1..12) mn, int(1..7) _wd, int _n, void|int(0..1) _inclusive)

  CLASS Calendar.Event.SuperEvent

Description

This class holds any number of events, and adds the functionality of event flags.

Note

Scanning (scan_events,next,etc) will drop flag information. Dig out what you need with holidays et al first.


Inherit Event

inherit Event : Event


Method filter_flag
Method holidays
Method flagdays

SuperEvent filter_flag(string flag)
SuperEvent holidays()
SuperEvent flagdays()

Description

Filter out the events that has a certain flag set. Holidays (flag "h") are the days that are marked red in the calendar (non-working days), Flagdays (flag "f") are the days that the flag should be visible in (only some countries).

  CLASS Calendar.Event.TZShift_Event

Description

Event containing information about when a timezone is changed.


Inherit Event

inherit Event : Event


Method scan_shift

.TimeRanges.TimeRange scan_shift(.Rule.Timezone tz, .TimeRanges.TimeRange from, int direction, int including)


Method scan_history

.TimeRanges.TimeRange scan_history(.Rule.Timezone tz, .TimeRanges.TimeRange from, int direction, int(0..1) including)


Method scan_rule

.TimeRanges.TimeRange scan_rule(.Rule.Timezone tz, .TimeRanges.TimeRange from, int direction, int including)

  Module Calendar.Gregorian

Description

This is the standard conservative christian calendar, used regularly in some countries - USA, for instance - and which derivate - the ISO calendar - is used in most of Europe.


Inherit YMD

inherit .YMD : YMD

  Module Calendar.ISO

Description

This is the standard western calendar, which is a derivate of the Gregorian calendar, but with weeks that starts on Monday instead of Sunday.


Inherit Gregorian

inherit .Gregorian : Gregorian

  Module Calendar.Islamic

Description

This is the islamic calendar. Due to some sources, they decide the first day of the new months on a month-to-month basis (sightings of the new moon), so it's probably not that accurate. If someone can confirm (or deny) accuracy better than that, please contact me so I can change this statement.

It's vaugely based on rules presented in algorithms by Dershowitz, Reingold and Clamen, 'Calendrical Calculations'. It is the same that's used in Emacs calendar mode.

Bugs

I have currently no idea how the arabic countries count the week. Follow the same rules as ISO for now... The time is also suspicious; the day really starts at sunrise (sunset?) and not midnight, the hours of the day is not correct. Also don't know what to call years before 1 - go for "BH"; positive years are "AH", anno Hegirac.


Inherit YMD

inherit .YMD : YMD

  Module Calendar.Julian

Description

This is the Julian calendar, conjured up by the old Romans when their calendar were just too weird. It was used by the christians as so far as the 18th century in some parts of the world. (Especially the protestantic and orthodox parts.)

Note

Don't confuse the julian day with the Julian calendar. The former is just a linear numbering of days, used in the Calendar module as a common unit for absolute time.


Inherit Gregorian

inherit .Gregorian : Gregorian

  Module Calendar.Rule

  CLASS Calendar.Rule.Timezone

Description

Contains a time zone.


Method create

void Calendar.Rule.Timezone(int offset, string name)

Parameter offset

Offset to UTC, not counting DST.

Parameter name

The name of the time zone.


Method tz_ux

array tz_ux(int unixtime)

FIXME

This method takes one integer argument, ignores it and returns an array with the UTC offset and the timezone name.


Method tz_jd

array tz_jd(int julian_day)

FIXME

This method takes one integer argument, ignores it and returns an array with the UTC offset and the timezone name.


Method raw_utc_offset

int raw_utc_offset()

Description

Returns the offset to UTC, not counting DST.

  Module Calendar.Stardate

Description

This implements TNG stardates.


Method now

cTick Calendar.Stardate.now()

Description

Give the zero-length time period of the current time.

  CLASS Calendar.Stardate.cTick


Inherit TimeRange

inherit Calendar.TimeRange : TimeRange


Method create

void Calendar.Stardate.cTick(mixed ... args)
void Calendar.Stardate.cTick(int|float date)
void Calendar.Stardate.cTick()

Description

Apart from the standard creation methods (julian day, etc), you can create a stardate from the stardate number. The length of the period will then be zero.

You can also omit any arguments to create now.

Bugs

Since the precision is limited to the float type of Pike you can get non-precise results:

> Calendar.Second(Calendar.Stardate.Day(Calendar.Year())); Result: Second(Fri 31 Dec 1999 23:59:18 CET - Sun 31 Dec 2000 23:59:18 CET)


Method tic

float tic()

Description

This gives back the start of the stardate period, as a float.


Method tics

float tics()

Description

This gives back the number of stardate tics in the period.


Method number_of_seconds

int number_of_seconds()

Description

This gives back the Gregorian/Earth/ISO number of seconds, for convinience and conversion to other calendars.


Method number_of_days

int number_of_days()

Description

This gives back the Gregorian/Earth/ISO number of days, for convinience and conversion to other calendars.


Method format_long
Method format_short
Method format_vshort

string format_long(void|int precision)
string format_short(void|int precision)
string format_vshort(void|int precision)

Description

Format the stardate tick nicely. Precision is the number of decimals. Defaults to 3.
long"-322537.312"
short"77463.312"(w/o >100000-component)
vshort"7463.312"(w/o >10000-component)

  Module Calendar.Swedish

Description

Same as the ISO calendar, but with Swedish as the default language.

This calendar exist only for backwards compatible purposes.


Inherit ISO

inherit .ISO : ISO

  Module Calendar.TZnames

Description

This module contains listnings of available timezones, in some different ways


Constant zones

constant Calendar.TZnames.zones = mapping(string:array(string))

Description

This constant is a mapping that can be used to loop over to get all the region-based timezones.

It looks like this:

([ "America": ({ "Los_Angeles", "Chicago", [...] }),
   "Europe":  ({ "Stockholm", [...] }),
   [...] }),

Please note that loading all the timezones can take some time, since they are generated and compiled on the fly.


Constant abbr2zones

constant Calendar.TZnames.abbr2zones = mapping(string:array(string))

Description

This mapping is used to look up abbreviation to the possible regional zones.

It looks like this:

([ "CET": ({ "Europe/Stockholm", [...] }),
   "CST": ({ "America/Chicago", "Australia/Adelaide", [...] }),
   [...] }),

Note this: Just because it's noted "CST" doesn't mean it's a unique timezone. There is about 7 *different* timezones that uses "CST" as abbreviation; not at the same time, though, so the DWIM routines checks this before it's satisfied. Same with some other timezones.

For most timezones, there is a number of region timezones that for the given time are equal. This is because region timezones include rules about local summer time shifts and possible historic shifts.

The YMD.parse functions can handle timezone abbreviations by guessing.


Method zonenames

array(string) Calendar.TZnames.zonenames()

Description

This reads the zone.tab file and returns name of all standard timezones, like "Europe/Belgrade".


Method _zone_tab
Method zone_tab

string Calendar.TZnames._zone_tab()
array(array) Calendar.TZnames.zone_tab()

Description

This returns the raw respectively parsed zone tab file from the timezone data files.

The parsed format is an array of zone tab line arrays,

({ string country_code,
   string position,
   string zone_name,
   string comment })

To convert the position to a Geography.Position, simply feed it to the constructor.

  Module Calendar.Time

Description

Base for time of day in calendars, ie calendars with hours, minutes, seconds

This module can't be used by itself, but is inherited by other modules (ISO by YMD , for instance).

  CLASS Calendar.Time.TimeofDay

Description
inherits TimeRange

Virtual class used by e.g. Hour.


Method call_out

void call_out(function fun, mixed ...args)

Description

Creates a call_out to this point in time.


Method create

void Calendar.Time.TimeofDay()
void Calendar.Time.TimeofDay(int unixtime)

Description

In addition to the wide range of construction arguments for a normal TimeRange (see TimeRange.create ), a time of day can also be constructed with unixtime as single argument consisting of the unix time - as returned from time(2) - of the time unit start.

It can also be constructed without argument, which then means "now", as in "this minute".


Method format_iso_ymd
Method format_ymd
Method format_ymd_short
Method format_ymd_xshort
Method format_iso_week
Method format_iso_week_short
Method format_week
Method format_week_short
Method format_month
Method format_month_short
Method format_iso_time
Method format_time
Method format_time_short
Method format_iso_short
Method format_time_xshort
Method format_mtime
Method format_xtime
Method format_tod
Method format_xtod
Method format_mod
Method format_nice
Method format_nicez

string format_iso_ymd()
string format_ymd()
string format_ymd_short()
string format_ymd_xshort()
string format_iso_week()
string format_iso_week_short()
string format_week()
string format_week_short()
string format_month()
string format_month_short()
string format_iso_time()
string format_time()
string format_time_short()
string format_iso_short()
string format_time_xshort()
string format_mtime()
string format_xtime()
string format_tod()
string format_xtod()
string format_mod()
string format_nice()
string format_nicez()

Description

Format the object into nice strings;

iso_ymd        "2000-06-02 (Jun) -W22-5 (Fri)" [2]
ext_ymd        "Friday, 2 June 2000" [2]
ymd            "2000-06-02"
ymd_short      "20000602"
ymd_xshort     "000602" [1]
iso_week       "2000-W22"
iso_week_short "2000W22"
week           "2000-w22" [2]
week_short     "2000w22" [2]
month          "2000-06"
month_short    "200006" [1]
iso_time       "2000-06-02 (Jun) -W22-5 (Fri) 20:53:14 UTC+1" [2]
ext_time       "Friday, 2 June 2000, 20:53:14" [2]
ctime          "Fri Jun  4 20:53:14 2000\n" [2] [3]
http           "Fri, 02 Jun 2000 19:53:14 GMT" [4]
time           "2000-06-02 20:53:14"
time_short     "20000602 20:53:14"
time_xshort    "000602 20:53:14"
iso_short      "20000602T20:53:14"
mtime          "2000-06-02 20:53"
xtime          "2000-06-02 20:53:14.000000"
todz           "20:53:14 CET"
todz_iso       "20:53:14 UTC+1"
tod            "20:53:14"
tod_short      "205314"
xtod           "20:53:14.000000"
mod            "20:53"
nice           "2 Jun 20:53", "2 Jun 2000 20:53:14" [2][5]
nicez          "2 Jun 20:53 CET" [2][5]
smtp           "Fri, 2 Jun 2000 20:53:14 +0100" [6]
commonlog      "02/Jun/2000:20:53:14 +0100" [2]
[1] note conflict (think 1 February 2003)
[2] language dependent
[3] as from the libc function ctime()
[4] as specified by the HTTP standard; this is always in GMT, ie, UTC. The timezone calculations needed will be executed implicitly. It is not language dependent.
[5] adaptive to type and with special cases for yesterday, tomorrow and other years
[6] as seen in Date: headers in mails


Method hour_no
Method minute_no
Method second_no
Method fraction_no

int hour_no()
int minute_no()
int second_no()
float fraction_no()

Description

This gives back the number of the time unit, on this day. Fraction is a float number, 0<=fraction<1. function mapping datetime() This gives back a mapping with the relevant time information (representing the start of the period);

     ([ "year":     int        // year number (2000 AD=2000, 1 BC==0)
        "month":    int(1..)   // month of year
        "day":      int(1..)   // day of month
        "yearday":  int(1..)   // day of year
        "week":     int(1..)   // week of year
        "week_day": int(1..)   // day of week (depending on calendar)
 
        "hour":     int(0..)   // hour of day, including dst
        "minute":   int(0..59) // minute of hour
        "second":   int(0..59) // second of minute
        "fraction": float      // fraction of second
        "timezone": int        // offset to utc, including dst
 
        "unix":     int        // unix time
        "julian":   float      // julian day
     ]);
    


Method hour
Method hours
Method number_of_hours

Hour hour()
Hour hour(int n)
array(Hour) hours()
array(Hour) hours(int first, int last)
int number_of_hours()

Description

hour () gives back the timerange representing the first or nth Hour of the called object. Note that hours normally starts to count at zero, so ->hour(2) gives the third hour within the range.

An Hour is in the Calendar perspective as any other time range not only 60 minutes, but also one of the (normally) 24 hours of the day, precisely.

hours () give back an array of all the hours containing the time periods called. With arguments, it will give back a range of those hours, in the same enumeration as the n to hour ().

number_of_hours () simple counts the number of hours containing the called time period.

Note: The called object doesn't have to *fill* all the hours it will send back, it's enough if it exist in those hours:

    > object h=Calendar.Time.Hour();
    Result: Hour(265567)
    > h->hours();
    Result: ({ /* 1 element */
                Hour(265567)
            })
    > h+=Calendar.Time.Minute();
    Result: Minute(265567:01+60m)
    > h->hours();
    Result: ({ /* 2 elements */
                Hour(265567),
                Hour(265568)
            })
    


Method julian_day

float julian_day()

Description

This calculates the corresponding julian day, from the time range. Note that the calculated day is the beginning of the period, and is a float - julian day standard says .00 is midday, 12:00 pm.

Note

Normal pike (ie, 32 bit) floats (without --with-double-precision) has a limit of about 7 digits, and since we are about julian day 2500000, the precision on time of day is very limited.


Method minute
Method minutes
Method number_of_minutes

Minute minute()
Minute minute(int n)
array(Minute) minutes()
array(Minute) minutes(int first, int last)
int number_of_minutes()

Description

minute () gives back the timerange representing the first or nth Minute of the called object. Note that minutes normally starts to count at zero, so ->minute(2) gives the third minute within the range.

An Minute is in the Calendar perspective as any other time range not only 60 seconds, but also one of the (normally) 60 minutes of the Hour , precisely.

minutes () give back an array of all the minutes containing the time periods called. With arguments, it will give back a range of those minutes, in the same enumeration as the n to minute ().

number_of_minutes () simple counts the number of minutes containing the called time period.


Method move_seconds
Method move_ns

TimeRange move_seconds(int seconds)
TimeRange move_ns(int nanoseconds)

Description

These two methods gives back the time range called moved the specified amount of time, with the length intact.

The motion is relative to the original position in time; 10 seconds ahead of 10:42:32 is 10:42:42, etc.


Method second
Method seconds
Method number_of_seconds

Second second()
Second second(int n)
array(Second) seconds()
array(Second) seconds(int first, int last)
int number_of_seconds()

Description

second () gives back the timerange representing the first or nth Second of the called object. Note that seconds normally starts to count at zero, so ->second(2) gives the third second within the range.

seconds () give back an array of all the seconds containing the time periods called. With arguments, it will give back a range of those seconds, in the same enumeration as the n to second ().

number_of_seconds () simple counts the number of seconds containing the called time period.


Method set_size_seconds
Method set_size_ns

TimeRange set_size_seconds(int seconds)
TimeRange set_size_ns(int nanoseconds)

Description

These two methods allows the time range to be edited by size of specific units.


Method unix_time

int unix_time()

Description

This calculates the corresponding unix time, - as returned from time(2) - from the time range. Note that the calculated unix time is the beginning of the period.

  CLASS Calendar.Time.SuperTimeRange


Method second
Method seconds
Method number_of_seconds
Method minute
Method minutes
Method number_of_minutes
Method hour
Method hours
Method number_of_hours

Second second()
Second second(int n)
array(Second) seconds()
array(Second) seconds(int first, int last)
int number_of_seconds()
Minute minute()
Minute minute(int n)
array(Minute) minutes()
array(Minute) minutes(int first, int last)
int number_of_minutes()
Hour hour()
Hour hour(int n)
array(Hour) hours()
array(Hour) hours(int first, int last)
int number_of_hours()

Description

Similar to TimeofDay , the Time::SuperTimeRange has a number of methods for digging out time parts of the range. Since a SuperTimeRange is a bit more complex - the major reason for its existance it that it contains holes, this calculation is a bit more advanced too.

If a range contains the seconds, say, 1..2 and 4..5, the third second (number 2, since we start from 0) in the range would be number 4, like this:

no   means this second
0    1
1    2
2    4      <- second three is missing,
3    5         as we don't have it in the example range

number_of_seconds () will in this example therefore also report 4, not 5, even if the time from start of the range to the end of the range is 5 seconds.

  CLASS Calendar.Time.Fraction

Description
inherits TimeofDay

A Fraction is a part of a second, and/or a time period with higher resolution then a second.

It contains everything that is possible to do with a Second , and also some methods of grabbing the time period with higher resolution.

Note

Internally, the fraction time period is measured in nanoseconds. A shorter or more precise time period then in nanoseconds is not possible within the current Fraction class.


Method create

void Calendar.Time.Fraction()
void Calendar.Time.Fraction("unix", int|float unixtime)
void Calendar.Time.Fraction("unix", int|float unixtime, int|float len)
void Calendar.Time.Fraction(int y, int m, int d, int h, int m, int s, int ns)

Description

It is possible to create a Fraction in three ways, either "now" with no arguments or from a unix time (as from time(2)), or the convenience way from ymd-hms integers.

If created from unix time, both the start of the period and the size of the period can be given in floats, both representing seconds. Note that the default float precision in pike is rather low (same as 'float' in C, the 32 bit floating point precision, normally about 7 digits), so beware that the resolution might bite you. (Internally in a Fraction, the representation is an integer.)

If created without explicit length, the fraction will always be of zero length.


Method now

TimeofDay now()

Description

Give the zero-length time period of the current time.


Method set_ruleset
Method ruleset

Calendar set_ruleset(Ruleset r)
Ruleset ruleset()

Description

Set or read the ruleset for the calendar. set_ruleset returns a new calendar object, but with the new ruleset.


Method set_timezone
Method timezone

Calendar set_timezone(Timezone tz)
Calendar set_timezone(string|Timezone tz)
TimeZone timezone()

Description

Set or get the current timezone (including dst) rule. set_timezone returns a new calendar object, as the called calendar but with another set of rules.

Example:

> Calendar.now();
Result: Fraction(Fri 2 Jun 2000 18:03:22.010300 CET)
> Calendar.set_timezone(Calendar.Timezone.UTC)->now();
Result: Fraction(Fri 2 Jun 2000 16:03:02.323912 UTC)

  Module Calendar.Timezone

Description

This module contains all the predefined timezones. Index it with whatever timezone you want to use.

Example: Calendar.Calendar my_cal= Calendar.ISO->set_timezone(Calendar.Timezone["Europe/Stockholm"]);

A simpler way of selecting timezones might be to just give the string to set_timezone ; it indexes by itself:

Calendar.Calendar my_cal= Calendar.ISO->set_timezone("Europe/Stockholm");

Note

Do not confuse this module with Ruleset.Timezone , which is the base class of a timezone object.

"CET" and some other standard abbreviations work too, but not all of them (due to more then one country using them).

Do not call set_timezone too often, but remember the result if possible. It might take some time to initialize a timezone object.

There are about 504 timezones with 127 different daylight saving rules. Most of them historic.

The timezone information comes from ftp://elsie.nci.nih.gov/pub/ and are not made up from scratch. Timezone bugs may be reported to the timezone mailing list, tz@elsie.nci.nih.gov, preferable with a cc to mirar+pike@mirar.org. /Mirar

See also

TZnames


Constant locale

constant Calendar.Timezone.locale = Rule.Timezone

Description

This contains the local timezone, found from various parts of the system, if possible.


Constant localtime

constant Calendar.Timezone.localtime = Rule.Timezone

Description

This is a special timezone, that uses localtime () and tzname to find out what current offset and timezone string to use.

locale uses this if there is no other way of finding a better timezone to use.

This timezone is limited by localtime and libc to the range of time_t, which is a MAXINT on most systems - 13 Dec 1901 20:45:52 to 19 Jan 2038 3:14:07, UTC.

  Module Calendar.YMD

Description

base for all Roman-kind of Calendars, ie, one with years, months, weeks and days

  CLASS Calendar.YMD.YMD

Description
inherits TimeRange

Base (virtual) time period of the Roman-kind of calendar.


Method format_iso_ymd
Method format_ymd
Method format_ymd_short
Method format_ymd_xshort
Method format_iso_week
Method format_iso_week_short
Method format_week
Method format_week_short
Method format_month
Method format_month_short
Method format_iso_time
Method format_time
Method format_time_short
Method format_time_xshort
Method format_mtime
Method format_xtime
Method format_tod
Method format_todz
Method format_xtod
Method format_mod

string format_iso_ymd()
string format_ymd()
string format_ymd_short()
string format_ymd_xshort()
string format_iso_week()
string format_iso_week_short()
string format_week()
string format_week_short()
string format_month()
string format_month_short()
string format_iso_time()
string format_time()
string format_time_short()
string format_time_xshort()
string format_mtime()
string format_xtime()
string format_tod()
string format_todz()
string format_xtod()
string format_mod()

Description

Format the object into nice strings;

iso_ymd        "2000-06-02 (Jun) -W22-5 (Fri)" [2]
ext_ymd        "Friday, 2 June 2000" [2]
ymd            "2000-06-02"
ymd_short      "20000602"
ymd_xshort     "000602" [1]
iso_week       "2000-W22"
iso_week_short "2000W22"
week           "2000-w22" [2]
week_short     "2000w22" [2]
month          "2000-06"
month_short    "200006" [1]
iso_time       "2000-06-02 (Jun) -W22-5 (Fri) 00:00:00 UTC+1" [2]
ext_time       "Friday, 2 June 2000, 00:00:00" [2]
ctime          "Fri Jun  2 00:00:00 2000\n" [2] [3]
http           "Fri, 02 Jun 2000 00:00:00 GMT" [4]
time           "2000-06-02 00:00:00"
time_short     "20000602 00:00:00"
time_xshort    "000602 00:00:00"
iso_short      "2000-06-02T00:00:00"
mtime          "2000-06-02 00:00"
xtime          "2000-06-02 00:00:00.000000"
tod            "00:00:00"
tod_short      "000000"
todz           "00:00:00 CET"
todz_iso       "00:00:00 UTC+1"
xtod           "00:00:00.000000"
mod            "00:00"
[1] note conflict (think 1 February 2003)
[2] language dependent
[3] as from the libc function ctime()
[4] as specified by the HTTP standard; not language dependent.


Method fraction_no
Method hour_no
Method julian_day
Method leap_year
Method minute_no
Method month_day
Method month_no
Method second_no
Method utc_offset
Method week_day
Method week_no
Method year_day
Method year_no
Method month_name
Method month_shortname
Method month_day_name
Method week_day_name
Method week_day_shortname
Method week_name
Method year_name
Method tzname
Method tzname_iso

float fraction_no()
int hour_no()
int julian_day()
int leap_year()
int minute_no()
int month_day()
int month_no()
int second_no()
int utc_offset()
int week_day()
int week_no()
int year_day()
int year_no()
string month_name()
string month_shortname()
string month_day_name()
string week_day_name()
string week_day_shortname()
string week_name()
string year_name()
string tzname()
string tzname_iso()

Description

function method int unix_time() Returns the unix time integer corresponding to the start of the time range object. (An unix time integer is UTC.) function method datetime() This gives back a mapping with the relevant time information (representing the start of the period);

     ([ "year":     int        // year number (2000 AD=2000, 1 BC==0)
        "month":    int(1..)   // month of year
        "day":      int(1..)   // day of month
        "yearday":  int(0..)   // day of year
        "week":     int(1..)   // week of year
        "week_day": int(0..)   // day of week
        "timezone": int        // offset to utc, including dst
 
        "unix":     int        // unix time
        "julian":   int        // julian day
     // for compatibility:
        "hour":     0          // hour of day, including dst
        "minute":   0          // minute of hour
        "second":   0          // second of minute
        "fraction": 0.0        // fraction of second
     ]);
    

Note

Day of week is compatible with old versions, ie, 0 is sunday, 6 is saturday, so it shouldn't be used to calculate the day of the week with the given week number. Year day is also backwards compatible, ie, one (1) less then from the year_day() function.


Method second
Method minute
Method seconds
Method number_of_seconds
Method minutes
Method number_of_minutes
Method hour
Method hours
Method number_of_hours

Second second()
Second second(int n)
Minute minute(int hour, int minute, int second)
array(Second) seconds()
array(Second) seconds(int first, int last)
int number_of_seconds()
Minute minute()
Minute minute(int n)
Minute minute(int hour, int minute)
array(Minute) minutes()
array(Minute) minutes(int first, int last)
int number_of_minutes()
Hour hour()
Hour hour(int n)
array(Hour) hours()
array(Hour) hours(int first, int last)
int number_of_hours()

  CLASS Calendar.YMD.Year

Description
inherits TimeRange
inherits YMD

This is the time period of a year.


Method create

void Calendar.YMD.Year("unix", int unix_time)
void Calendar.YMD.Year("julian", int|float julian_day)
void Calendar.YMD.Year(int year)
void Calendar.YMD.Year(string year)

Description

It's possible to create the standard week by using three different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from the year number.


Method month

Month month()
Month month(int n)
Month month(string name)

Description

The Year type overloads the month() method, so it is possible to get a specified month by string:

year->month("April")

The integer and no argument behavior is inherited from YMD ().


Method week

Week week()
Week week(int n)
Week week(string name)

Description

The Year type overloads the week() method, so it is possible to get a specified week by name:

year->week("17") year->week("w17")

The integer and no argument behavior is inherited from YMD ().

This is useful, since the first week of a year not always (about half the years, in the ISO calendar) is numbered '1'.

  CLASS Calendar.YMD.Week

Description

The Calendar week represents a standard time period of a week. In the Gregorian calendar, the standard week starts on a sunday and ends on a saturday; in the ISO calendar, it starts on a monday and ends on a sunday.

The week are might not be aligned to the year, and thus the week may cross year borders and the year of the week might not be the same as the year of all the days in the week. The basic rule is that the week year is the year that has the most days in the week, but since week number only is specified in the ISO calendar - and derivates - the week number of most calendars is the week number of most of the days in the ISO calendar, which modifies this rule for the Gregorian calendar; the week number and year is the same as for the ISO calendar, except for the sundays.

When adding, moving and subtracting months to a week, it falls back to using days.

When adding, moving or subtracting years, if tries to place the moved week in the resulting year.


Method create

void Calendar.YMD.Week("unix", int unix_time)
void Calendar.YMD.Week("julian", int|float julian_day)
void Calendar.YMD.Week(int year, int week)

Description

It's possible to create the standard week by using three different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from year and week number.


Method create

void Calendar.YMD.Week("unix", int unix_time)
void Calendar.YMD.Week("julian", int|float julian_day)
void Calendar.YMD.Week(int year, int month, int day)
void Calendar.YMD.Week(int year, int year_day)
void Calendar.YMD.Week(int julian_day)

Description

It's possible to create the day by using five different methods; either the normal way - from standard unix time or the julian day, and also, for more practical use, from year, month and day, from year and day of year, and from julian day without extra fuzz.


Method day

Day day()
Day day(int n)
Day day(string name)

Description

The Week type overloads the day() method, so it is possible to get a specified weekday by string:

week->day("sunday")

The integer and no argument behavior is inherited from YMD ().

Note

the weekday-from-string routine is language dependent.

  CLASS Calendar.YMD.Hour

Description
inherits Time.Hour
inherits YMD

global convinience functions


Method parse

TimeRange parse(string fmt, string arg)

Description

parse a date, create relevant object fmt is in the format "abc%xdef..." where abc and def is matched, and %x is one of those time units:

%Y absolute year
%y dwim year (70-99 is 1970-1999, 0-69 is 2000-2069)
%M month (number, name or short name) (needs %y)
%W week (needs %y)
%D date (needs %y, %m)
%d short date (20000304, 000304)
%a day (needs %y)
%e weekday (needs %y, %w)
%h hour (needs %d, %D or %W)
%m minute (needs %h)
%s second (needs %m)
%S seconds since the Epoch (only combines with %f)
%f fraction of a second (needs %s or %S)
%t short time (205314, 2053)
%z zone
%p "am" or "pm"
%n empty string (to be put at the end of formats)

Returns

0 if format doesn't match data, or the appropriate time object.

Note

The zone will be a guess if it doesn't state an exact regional timezone (like "Europe/Stockholm") - most zone abbriviations (like "CET") are used by more then one region with it's own daylight saving rules. Also beware that for instance CST can be up to four different zones, central Australia or America being the most common.

    Abbreviation Interpretation
    AMT          America/Manaus       [UTC-4]
    AST          America/Curacao      [UTC-4]
    CDT          America/Costa_Rica   [UTC-6]
    CST          America/El Salvador  [UTC-6]
    EST          America/Panama       [UTC-5]
    GST          Asia/Dubai           [UTC+4]
    IST          Asia/Jerusalem       [UTC+2]
    WST          Australia/Perth      [UTC+8]
    

This mapping is modifiable in the ruleset, see Ruleset.set_abbr2zone . function Day dwim_day(string date) function Day dwim_day(string date,TimeRange context) Tries a number of different formats on the given date (in order):

parse  format                  as in
    "%y-%M-%D (%M) -W%W-%e (%e)"  "2000-03-20 (Mar) -W12-1 (Mon)"
    "%y-%M-%D"                    "2000-03-20", "00-03-20"
    "%M%/%D/%y"                   "3/20/2000"
    "%D%*[ /]%M%*[ /-,]%y"        "20/3/2000" "20 mar 2000" "20/3 -00"
    "%e%*[ ]%D%*[ /]%M%*[ /-,]%y" "Mon 20 Mar 2000" "Mon 20/3 2000"
    "-%y%*[ /]%D%*[ /]%M"         "-00 20/3" "-00 20 mar"
    "-%y%*[ /]%M%*[ /]%D"         "-00 3/20" "-00 march 20"
    "%y%*[ /]%D%*[ /]%M"          "00 20 mar" "2000 20/3"
    "%y%*[ /]%M%*[ /]%D"          "2000 march 20"
    "%D%.%M.%y"                   "20.3.2000"
    "%D%*[ -/]%M"                 "20/3" "20 mar" "20-03"
    "%M%*[ -/]%D"                 "3/20" "march 20"
    "%M-%D-%y"                    "03-20-2000"
    "%D-%M-%y"                    "20-03-2000"
    "%e%*[- /]%D%*[- /]%M"        "mon 20 march"
    "%e%*[- /]%M%*[- /]%D"        "mon/march/20"
    "%e%*[ -/wv]%W%*[ -/]%y"      "mon w12 -00" "1 w12 2000"
    "%e%*[ -/wv]%W"               "mon w12"
    "%d"                          "20000320", "000320"
    "today"                       "today"
    "last %e"                     "last monday"
    "next %e"                     "next monday"
    

Casts exception if it fails to dwim out a day. "dwim" means do-what-i-mean.

function datetime(int|void unix_time) Replacement for localtime; gives back a mapping:

     ([ "year":     int        // year number (2000 AD=2000, 1 BC==0)
        "month":    int(1..)   // month of year
        "day":      int(1..)   // day of month
        "yearday":  int(1..)   // day of year
        "week":     int(1..)   // week of year
        "week_day": int(1..)   // day of week (depending on calendar)
        "unix":     int        // unix time
        "julian":   float      // julian day
        "hour":     int(0..)   // hour of day, including dst
        "minute":   int(0..59) // minute of hour
        "second":   int(0..59) // second of minute
        "fraction": float      // fraction of second
        "timezone": int        // offset to utc, including dst
     ]);
    
This is the same as calling Second ()->datetime ().

function datetime_name(int|void unix_time) function datetime_short_name(int|void unix_time) Compat functions; same as format_iso and format_iso_short .

function string format_iso(void|int unix_time) function string format_iso_short(void|int unix_time) function string format_iso_tod(void|int unix_time) function string format_day_iso(void|int unix_time) function string format_day_iso_short(void|int unix_time) Format the object into nice strings;

    iso    "2000-06-02 (Jun) -W22-5 (Fri) 11:57:18 CEST"
    iso_short   "2000-06-02 11:57:18"
    iso_tod     "11:57:18"
    

  Module Calendar_I

Description

This module exist only for backwards compatibility issues with earlier Pike releases. Use the Calendar module instead.

This code can be used to simulate the old calendar for now (it might be removed in later Pike's):

This module has been totally rewritten in Pike 7.1+. To be forward compatible the lazy way, you can do something like this, though:

#if constant(Calendar.II) #define Calendar Calendar_I #endif ... import Calendar or whatever ...

This module implements calendar calculations, and base classes for time units.

  CLASS Calendar_I._TimeUnit

Description

Base class for units of time.


Method lesser

array(string) lesser()

Description

Gives a list of methods to get lesser (shorter) time units. ie, for a month, this gives back ({"day"}) and the method day(mixed n) gives back that day object. The method days() gives back a list of possible argument values to the method day. Concurrently, Array.map(o->days(),o->day) gives a list of day objects in the object o.

Ie:

	  array(string) lesser()    - gives back a list of possible xxx's.
	  object xxxs()             - gives back a list of possible n's.
	  object xxx(mixed n)       - gives back xxx n
	  object xxx(object(Xxx) o) - gives back the corresponing xxx 
	

The list of n's (as returned from xxxs) are always in order.

There are two n's with special meaning, 0 and -1. 0 always gives the first xxx, equal to my_obj->xxx(my_obj->xxxs()[0]), and -1 gives the last, equal to my_obj->xxx(my_obj->xxxs()[-1]).

To get all xxxs in the object, do something like Array.map(my_obj->xxxs(),my_obj->xxx).

xxx(object) may return zero, if there was no correspondning xxx.


Method greater

array(string) greater()

Description

Gives a list of methods to get greater (longer) time units from this object. For a month, this gives back ({"year"}), thus the method month->year() gives the year object.


Method next
Method prev
Method `+
Method `-

object next()
object prev()
object `+(int n)
object `-(int n)
object `-(object x)

Description

next() and prev() give the logical next and previous object. The `+() operator gives that logical relative object, ie my_day+14 gives 14 days ahead. `-() works the same way, but can also take an object of the same type and give the difference as an integer.

  Module Calendar_I.Gregorian

Description

time units: Year , Month , Week , Day


Method parse

object Calendar_I.Gregorian.parse(string fmt, string arg)

Description

Parse a date, create relevant object fmt is in the format "abc%xdef..." where abc and def is matched, and %x is one of those time units: %Y absolute year %y year (70-99 is 1970-1999, 0-69 is 2000-2069) %M month (number, name or short name) (needs %y) %W week (needs %y) %D date (needs %y, %m) %a day (needs %y) %e weekday (needs %y, %w) %h hour (needs %d, %D or %W) %m minute (needs %h) %s second (needs %s)


Method datetime

mapping(string:int) Calendar_I.Gregorian.datetime(int|void unix_time, int|void skip_extra)

Description

Replacement for localtime.


Method datetime_name

string Calendar_I.Gregorian.datetime_name(int|void unix_time)

Description

Replacement for ctime.


Method datetime_short_name

string Calendar_I.Gregorian.datetime_short_name(int|void unix_time)

Description

Replacement for ctime.

  CLASS Calendar_I.Gregorian.Year

Description

A Calendar_I.time_unit

Lesser units: Month , Week , Day Greater units: none


Inherit _TimeUnit

inherit _TimeUnit : _TimeUnit

  Module Calendar_I.Stardate

Description

time unit: TNGDate

  CLASS Calendar_I.Stardate.TNGDate

Description

Implements ST:TNG stardates. Can be used as create argument to Day.


Inherit _TimeUnit

inherit Calendar_I._TimeUnit : _TimeUnit

  Module Debug


Method pp_memory_usage

string Debug.pp_memory_usage()

Description

Returns a pretty printed version of the output from memory_usage .


Method verify_internals

void Debug.verify_internals()

Description

Perform sanity checks.

This function goes through most of the internal Pike structures and generates a fatal error if one of them is found to be out of order. It is only used for debugging.

Note

This function does a more thorough check if the Pike runtime has been compiled with RTL debug.


Method debug

int Debug.debug(int(0..) level)

Description

Set the run-time debug level.

Returns

The old debug level will be returned.

Note

This function is only available if the Pike runtime has been compiled with RTL debug.


Method optimizer_debug

int Debug.optimizer_debug(int(0..) level)

Description

Set the optimizer debug level.

Returns

The old optimizer debug level will be returned.

Note

This function is only available if the Pike runtime has been compiled with RTL debug.


Method assembler_debug

int Debug.assembler_debug(int(0..) level)

Description

Set the assembler debug level.

Returns

The old assembler debug level will be returned.

Note

This function is only available if the Pike runtime has been compiled with RTL debug.


Method compiler_trace

int Debug.compiler_trace(int(0..) level)

Description

Set the compiler trace level.

Returns

The old compiler trace level will be returned.

Note

This function is only available if the Pike runtime has been compiled with RTL debug.


Method memory_usage

mapping(string:int) Debug.memory_usage()

Description

Check memory usage.

This function is mostly intended for debugging. It delivers a mapping with information about how many arrays/mappings/strings etc. there are currently allocated and how much memory they use.

Note

Exactly what this function returns is version dependant.

See also

_verify_internals()


Method reset_dmalloc

void Debug.reset_dmalloc()

Note

Only available when compiled with dmalloc.


Method dmalloc_set_name

void Debug.dmalloc_set_name(string filename, int linenumber)

Note

Only available when compiled with dmalloc.


Method list_open_fds

void Debug.list_open_fds()

Note

Only available when compiled with dmalloc.


Method locate_references

void Debug.locate_references(string|array|mapping|multiset|function|object|program|type(mixed) o)

Description

This function is mostly intended for debugging. It will search through all data structures in Pike looking for o and print the locations on stderr. o can be anything but int or float.

Note

This function only exists if the Pike runtime has been compiled with RTL debug.


Method describe

mixed Debug.describe(mixed x)

Description

Prints out a description of the thing x to standard error. The description contains various internal info associated with x .

Note

This function only exists if the Pike runtime has been compiled with RTL debug.


Method gc_set_watch

void Debug.gc_set_watch(array|multiset|mapping|object|function|program|string x)

Description

Sets a watch on the given thing, so that the gc will print a message whenever it's encountered. Intended to be used together with breakpoints to debug the garbage collector.

Note

This function only exists if the Pike runtime has been compiled with RTL debug.


Method dump_backlog

void Debug.dump_backlog()

Description

Dumps the 1024 latest executed opcodes, along with the source code lines, to standard error. The backlog is only collected on debug level 1 or higher, set with _debug or with the -d argument on the command line.

Note

This function only exists if the Pike runtime has been compiled with RTL debug.


Method gc_status

mapping(string:int|float) Debug.gc_status()

Description

Get statistics from the garbage collector.

Returns

A mapping with the following content will be returned:

"num_objects" : int

Number of arrays, mappings, multisets, objects and programs.

"num_allocs" : int

Number of memory allocations since the last gc run.

"alloc_threshold" : int

Threshold for "num_allocs" when another automatic gc run is scheduled.

"projected_garbage" : float

Estimation of the current amount of garbage.

"objects_alloced" : int

Decaying average over the number of allocated objects between gc runs.

"objects_freed" : int

Decaying average over the number of freed objects in each gc run.

"last_garbage_ratio" : float

Garbage ratio in the last gc run.

"non_gc_time" : int

Decaying average over the CPU milliseconds spent outside the garbage collector.

"gc_time" : int

Decaying average over the CPU milliseconds spent inside the garbage collector.

"last_garbage_strategy" : string

The garbage accumulation goal that the gc aimed for when setting "alloc_threshold" in the last run. The value is either "garbage_ratio_low" or "garbage_ratio_high", which corresponds to the gc parameters with the same names in Pike.gc_parameters .

"last_gc" : int

Time when the garbage-collector last ran.


See also

gc() , Pike.gc_parameters()


Method describe_program

array(array(int|string)) Debug.describe_program(program p)

Description

Debug function for showing the symbol table of a program.

  CLASS Debug.Subject

Description

This is a probe subject which you can send in somewhere to get probed (not to be confused with a probe object, which does some active probing). All calls to LFUNs will be printed to stderr. It is possible to name the subject by passing a string as the first and only argument when creating the subject object.

Example

> object s = Debug.Subject(); create() > random(s); _random() (1) Result: 0 > abs(s); `<(0) _sprintf(79, ([ "indent":2 ])) (2) Result: Debug.Subject > abs(class { inherit Debug.Subject; int `<(mixed ... args) { return 1; } }()); create() `-() destroy() (3) Result: 0 > pow(s,2); `[]("pow") Attempt to call the NULL-value Unknown program: 0(2)

  CLASS Debug.Tracer

Description

A class that when instatiated will turn on trace, and when it's destroyed will turn it off again.


Method create

void Debug.Tracer(int level)

Description

Sets the level of debug trace to level .

  CLASS Debug.Wrapper

Description

This wrapper can be placed around another object to get printouts about what is happening to it. Only a few LFUNs are currently supported.

Example

> object x=Debug.Wrapper(Crypto.MD5()); Debug.Wrapper is proxying ___Nettle.MD5_State() > x->name(); ___Nettle.MD5_State()->name (1) Result: "md5" > !x; !___Nettle.MD5_State() (2) Result: 0


Method create

void Debug.Wrapper(object x)


Method `!

int(0..1) `!()


Method `[]

mixed `[](mixed x, void|mixed y)


Method `->

mixed `->(mixed x)


Method _indices

array _indices()


Method _values

array _values()


Method _sizeof

int _sizeof()


Method _sprintf

string _sprintf(int c, mapping(string:mixed)|void attrs)

  Module Filesystem


Method parse_mode

int Filesystem.parse_mode(int old, int|string mode)

Description

FIXME: Document this function


Method get_filesystem

program Filesystem.get_filesystem(string what)

Description

FIXME: Document this function


Method `()

function Filesystem.`()(void|string path)

Description

FIXME: Document this function

  CLASS Filesystem.System

Description

Implements an abstraction of the normal filesystem.


Inherit Base

inherit Filesystem.Base : Base


Method create

void Filesystem.System(void|string directory, void|string root, void|int fast, void|Filesystem.Base parent)

Description

Instanciate a new object representing the filesystem.

Parameter directory

The directory (in the real filesystem) that should become the root of the filesystemobject.

Parameter root

Internal

Parameter fast

Internal

Parameter parent

Internal

  CLASS Filesystem.Stat

Description

Describes the stat of a file


Method isfifo
Method ischr
Method isdir
Method isblk
Method isreg
Method islnk
Method issock
Method isdoor

int(0..1) isfifo()
int(0..1) ischr()
int(0..1) isdir()
int(0..1) isblk()
int(0..1) isreg()
int(0..1) islnk()
int(0..1) issock()
int(0..1) isdoor()

Description
fifo

Is the file a FIFO?

chr

Is the file a character device?

dir

Is the file (?) a directory?

blk

Is the file a block device?

reg

Is the file a regular file?

lnk

Is the file a link to some other file or directory?

sock

Is the file a socket?

door

FIXME: Document this function.

Returns

1 if the file is of a specific type 0 if the file is not.

See also

[set_type]


Method set_type

void set_type(string x)

Description

Set a type for the stat-object.

Note

This call doesnot change the filetype in the underlaying filesystem.

Parameter x

Type to set. Type is one of the following:

  • fifo, chr, dir, blk, reg, lnk, sock and door
See also

[isfifo], [ischr], [isdir], [isblk], [isreg], [islnk], [issock], [isdoor]


Method attach_statarray

void attach_statarray(array(int) a)

Description

Fills the stat-object with data from a Stdio.File.stat() call.


Method open

Stdio.File open(string mode)

Description

Open the stated file within the filesystem

Returns

a [Stdio.File] object

See also

[Stdio.File]


Method cd

object cd()

Description

Change to the stated directory.

Returns

the directory if the stated object was a directory, 0 otherwise.


Method nice_date

string nice_date()

Description

Returns the date of the stated object as cleartext.

  CLASS Filesystem.Base

Description

Baseclass that can be extended to create new filesystems. Is used by the Tar and System filesystem classes.


Method cd

Base cd(string|void directory)

Description

Change directory within the filesystem. Returns a new filesystem object with the given directory as cwd.


Method cwd

string cwd()

Description

Returns the current working directory within the filesystem.


Method chroot

Base chroot(void|string directory)

Description

Change the root of the filesystem.


Method stat

Stat stat(string file, int|void lstat)

Description

Return a stat-object for a file or a directory within the filesystem.


Method get_dir

array(string) get_dir(void|string directory, void|string|array glob)

Description

Returns an array of all files and directories within a given directory.

Parameter directory

Directory where the search should be made within the filesystem. CWD is assumed if none (or 0) is given.

Parameter glob

Return only files and dirs matching the glob (if given).

See also

[get_stats]


Method get_stats

array(Stat) get_stats(void|string directory, void|string|array glob)

Description

Returns stat-objects for the files and directories matching the given glob within the given directory.

See also

[get_dir]


Method open

Stdio.File open(string filename, string mode)

Description

Open a file within the filesystem

Returns

A Stdio.File object.


Method apply

int apply()

Description

FIXME: Document this function


Method chmod

void chmod(string filename, int|string mode)

Description

Change mode of a file or directory.


Method chown

void chown(string filename, int|object owner, int|object group)

Description

Change ownership of the file or directory


Method mkdir

int mkdir(string directory, void|int|string mode)

Description

Create a new directory


Method rm

int rm(string filename)

Description

Remove a file from the filesystem.


Method find

array find(void|function(Stat:int) mask, mixed ... extra)

Description

FIXME: Document this function

  CLASS Filesystem.Traversion

Description

Iterator object that traverses a directory tree and returns files as values and paths as indices. Example that uses the iterator to create a really simple sort of make:

Example

object i=Filesystem.Traversion("."); foreach(i; string dir; string file) { if(!has_suffix(file, ".c")) continue; file = dir+file; string ofile = file; ofile[-1]='o'; object s=file_stat(ofile); if(s && i->stat()->mtime<s->mtime) continue; // compile file }


Method progress

float progress(void|float share)

Description

Returns the current progress of the traversion as a value between 0.0 and 1.0. Note that this value isn't based on the number of files, but the directory structure.


Method create

void Filesystem.Traversion(string path, void|int(0..1) symlink)

Parameter path

The root path from which to traverse.

Parameter symlink

Don't traverse symlink directories.


Method stat

Stdio.Stat stat()

Description

Returns the stat for the current index-value-pair.

  Module Filesystem.Tar


Method create

void Filesystem.Tar.(string filename, void|Filesystem.Base parent, void|object file)

Description

Filesystem which can be used to mount a Tar file.

Parameter filename

The tar file to mount.

Parameter parent

The parent filesystem. If non is given, the normal system filesystem is assumed. This allows mounting a TAR-file within a tarfile.

Parameter file

If specified, this should be an open file descriptor. This object could e.g. be a Stdio.File , Gz.File or Bz2.File object.

  Module Geography

  CLASS Geography.Position

Description

This class contains a geographical position, ie a point on the earths surface. The resulting position object implements comparision methods (__hash, `==, `< and `>) so that you can compare and sort positions as well as using them as index in mappings. Comparision is made primary on latidue and secondly on longitude. It does not currently take the ellipsoid into account.

It is possible to cast a position into an array, which will yield ({ float latitude, float longitude }), as well as into a string.


Variable lat

float lat

Description

Latitude (N--S) of the position, in degrees. Positive number is north, negative number is south.


Variable long

float long

Description

Longitude (W--E) of the position, in degrees. Positive number is east, negative number is west.


Variable alt

float alt

Description

Altitud of the position, in meters. Positive numbers is up. Zero is the shell of the current ellipsoid.


Method create

void Geography.Position(float lat, float long, void|float alt)
void Geography.Position(string lat, string long)
void Geography.Position(string both)

Description

Constructor for this class. If fed with strings, it will perform a dwim scan on the strings. If they fails to be understood, there will be an exception.


Method latitude
Method longitude

string latitude(void|int n)
string longitude(void|int n)

Description

Returns the nicely formatted latitude or longitude.

0

"17°42.19'N" / "42°22.2'W"

1

"17.703°N" / "42.37°W"

2

"17°42.18'N" / "42°22.2'W"

3

"17°42'10.4"N" / "42°22'12"W"

-1

"17.703" / "-42.37"



Method standard_grid

string standard_grid()

Description

Returns the standard map grid system for the current position. Can either be "UPS" or "UTM".


Variable polar_radius

float polar_radius

Description

The polar radius is how many meters the earth radius is at the poles (north-south direction).


Variable equatorial_radius

float equatorial_radius

Description

The equatorial radius is how many meters the earth radius is at the equator (east-west direction).


Method flattening

float flattening()

Description

Returns the flattening factor for the selected earth approximation ellipsoid.


Method eccentricity_squared

float eccentricity_squared()

Description

Returns the first eccentricity squared for the selected earth approximation ellipsoid.


Constant ellipsoids

constant ellipsoids

Description

A mapping with reference ellipsoids, which can be fed to the UTM converter. The mapping maps the name of the ellipsoid to an array where the first element is a float describing the equatorial radius and the second element is a float describing the polar radius.


Method set_ellipsoid

int(0..1) set_ellipsoid(string name)
int(0..1) set_ellipsoid(float equatorial_radius, float polar_radius)

Description

Sets the equatorial and polar radius to the provided values. A name can also be provided, in which case the radius will be looked up in the ellipsoid mapping. The function returns 1 upon success, 0 on failure.

"Airy 1830"
"ATS77"
"Australian National"
"Bessel 1841"
"Bessel 1841 Namibia"
"Clarke 1866"
"Clarke 1880"
"Everest"
"Everest 1830"
"Everest 1848"
"Everest 1856"
"Everest 1869"
"Everest Pakistan"
"Fisher 1960"
"Fisher 1968"
"G R S 1967"
"G R S 1975"
"G R S 1980"
"Helmert 1906"
"Hough 1956"
"Indonesian 1974"
"Krassovsky 1940"
"Mercury"
"Modified Airy"
"Modified Fisher 1960"
"New International 1967"
"SGS 85"
"South American 1969"
"Sphere"
"WGS 60"
"WGS 66"
"WGS 72"
"WGS 84"

Note

The longitude and lattitude are not converted to the new ellipsoid.


Method UTM_zone_number

int UTM_zone_number()

Description

Returns the UTM zone number for the current longitude, with correction for the Svalbard deviations.


Method UTM_zone_designator

string UTM_zone_designator()

Description

Returns the UTM letter designator for the current latitude. Returns "Z" if latitude is outside the UTM limits of 84N to 80S.


Method UTM_offset

array(float) UTM_offset()

Description

Returns the offset within the present UTM cell. The result will be returned in an array of floats, containing easting and northing.


Method UTM

string UTM()

Description

Returns the current UTM coordinates position. An example output is "32T 442063.562 5247479.500" where the parts are zone number + zone designator, easting and northing.


Method set_from_UTM

void set_from_UTM(int zone_number, string zone_designator, float UTME, float UTMN)

Description

Sets the longitude and lattitude from the given UTM coordinates.


Method GEOREF

string GEOREF()

Description

Gives the full GEOREF position for the current position, e.g. "LDJA0511".


Method RT38

array(float) RT38()


Method set_from_RT38

void set_from_RT38(int|float|string x_n, int|float|string y_e)

Description

Sets the longitude and lattitude from the given RT38 coordinates.


Method approx_height

float approx_height()

Description

Returns a very crude approximation of where the ground level is at the current position, compared against the ellipsoid shell. WGS-84 is assumed, but the approximation is so bad that it doesn't matter which of the standard ellipsoids is used.


Method ECEF

array(float) ECEF()

Description

Returns the current position as Earth Centered Earth Fixed Cartesian Coordinates.

Returns

({ X, Y, Z })


Method __hash

int __hash()


Method `==

int `==(object pos)


Method `<

int `<(object pos)


Method `>

int `>(object pos)


Method _sprintf

string _sprintf(int|void t)


Method euclidian_distance

float euclidian_distance(this_program p)

Description

Calculate the euclidian distance between two Geography.Position. Result is in meter. This uses the ECEF function.

  CLASS Geography.PositionRT38

Description

Create a Position object from a RT38 coordinate


Inherit Position

inherit .Position : Position

  Module Geography.Countries


Variable countries

array(Country) Geography.Countries.countries

Description

All known countries.


Method from_domain

Country Geography.Countries.from_domain(string domain)

Description

Look up a country from a domain name. Returns zero if the domain doesn't map to a country. Note that there are some valid domains that don't:

INT

International

MIL

US Military

NET

Network

ORG

Non-Profit Organization

ARPA

Old style Arpanet

NATO

Nato field

And that US has five domains, Great Britain and france two: <dl compact> <dt>EDU <dd>US Educational <dt>MIL <dd>US Military <dt>GOV <dd>US Government <dt>UM <dd>US Minor Outlying Islands <dt>US <dd>US <dt>GB <dd>Great Britain (UK) <dt>UK <dd>United Kingdom <dt>FR <dd>France <dt>FX <dd>France, Metropolitan <dt>There's also three domains that for convinience maps to US: <dt>NET <dd>Network <dt>ORG <dd>Organization <dt>COM <dd>Commercial </dl>


Method from_domain

Country Geography.Countries.from_domain(string name)

Description

Look up a country from its name or aka. The search is case-insensitive but regards whitespace and interpunctation.


Method continents

mapping(string:array(Country)) Geography.Countries.continents()

Description

Gives back a mapping from continent name to an array of the countries on that continent.

The continents are:

    	  "Europe"
    	  "Africa"
    	  "Asia"
    	  "North America"
    	  "South America"
    	  "Oceania"
	  "Antarctica"
	

Note

Some countries are considered to be on more than one continent.


Method `[]
Method `->

mixed Geography.Countries.`[](string what)
mixed Geography.Countries.`->(string what)

Description

Convenience functions for getting a country the name-space way; it looks up whatever it is in the name- and domain-space and returns that country if possible:

> Geography.Countries.se; Result: Country(Sweden) > Geography.Countries.djibouti; Result: Country(Djibouti) > Geography.Countries.com; Result: Country(United States) > Geography.Countries.wallis_and_futuna_islands->iso2; Result: "WF"

  CLASS Geography.Countries.Country

Description

Country


Variable iso2

string iso2

Description

ISO 2-character code aka domain name


Variable fips10

string fips10

Description

FIPS 10-character code; "Federal Information Processing Standards 10-3" etc, used by some goverments in the US.


string name
array(string) aka

Description

Country name and as-known-as, if any


Variable former

int former

Description

Flag that is set if this country doesn't exist anymore. (eg USSR.)


Method continent

string continent()

Description

Returns the continent of the country.

Note

Some countries are geographically in more then one continent; any of the continents might be returned then, but probably the continent in which the capital is resident - Europe for Russia, for instance.


Method cast

string cast("string")

Description

It is possible to cast a country to a string, which will be the same as performing country->name;.

  Module Graphics

  Module Graphics.Graph


Inherit polyline

inherit .polyline : polyline


Inherit create_graph

inherit .create_graph : create_graph


Inherit create_bars

inherit .create_bars : create_bars


Inherit create_pie

inherit .create_pie : create_pie


Method check_mapping

mapping(string:mixed) Graphics.Graph.check_mapping(mapping(string:mixed) diagram_data, string type)

Description

This function sets all unset elements in diagram_data to its default value as well as performing some simple sanity checks. This function is called from within pie , bars , sumbars , line , norm and graph .


Method pie

Image.Image Graphics.Graph.pie(mapping(string:mixed) diagram_data)

FIXME

Document this function


Method bars

Image.Image Graphics.Graph.bars(mapping(string:mixed) diagram_data)

FIXME

Document this function


Method sumbars

Image.Image Graphics.Graph.sumbars(mapping(string:mixed) diagram_data)

FIXME

Document this function


Method line

Image.Image Graphics.Graph.line(mapping(string:mixed) diagram_data)

FIXME

Document this function


Method norm

Image.Image Graphics.Graph.norm(mapping(string:mixed) diagram_data)

FIXME

Document this function


Method graph

Image.Image Graphics.Graph.graph(mapping(string:mixed) diagram_data)

FIXME

Document this function

  CLASS Graphics.Graph.create_bars

Description

Graph sub-module for drawing bars.



Inherit "polyline.pike"

inherit "polyline.pike"


Inherit "create_graph.pike"

inherit "create_graph.pike"

  CLASS Graphics.Graph.create_graph

Description

Graph sub-module for drawing graphs.

create_graph draws a graph but there are also some other functions used by create_pie and create_bars .



Inherit "polyline.pike"

inherit "polyline.pike"

  CLASS Graphics.Graph.create_pie

Description

Graph sub-module for drawing pie-charts.


Inherit "polyline.pike"

inherit "polyline.pike"


Inherit "create_graph.pike"

inherit "create_graph.pike"


Inherit "create_bars.pike"

inherit "create_bars.pike"

  CLASS Graphics.Graph.polyline

Description

Graph sub-module providing draw functions.

$Id: polyline.pike,v 1.6 2003/11/22 15:00:54 grubba Exp $

  Module Languages

  Module Languages.PLIS

Description

PLIS, Permuted Lisp. A Lisp language somewhat similar to scheme.


Method init_specials

void Languages.PLIS.init_specials(Environment environment)

Description

Adds the special functions quote, set!, setq, while, define, defmacro, lambda, if, and, or, begin and catch to the environment .


Method init_functions

void Languages.PLIS.init_functions(Environment environment)

Description

Adds the functions +, *, -, =, <, >, concat, read-string, eval, apply, global-environment, var, cdr, null?, setcar!, setcdr!, cons and list to the environment .


Method default_environment

Environment Languages.PLIS.default_environment()

Description

Creates a new environment on which it runs init_functions, init_specials and the following boot code.

(begin (defmacro (cddr x) (list (quote cdr) (list (quote cdr) x))) (defmacro (cadr x) (list (quote car) (list (quote cdr) x))) (defmacro (cdar x) (list (quote cdr) (list (quote car) x))) (defmacro (caar x) (list (quote car) (list (quote car) x)))

(defmacro (when cond . body) (list (quote if) cond (cons (quote begin) body)))

(define (map fun list) (if (null? list) (quote ()) (cons (fun (car list)) (map fun (cdr list)))))

(defmacro (let decl . body) (cons (cons (quote lambda) (cons (map car decl) body)) (map cadr decl))))


Method main

void Languages.PLIS.main()

Description

Instantiates a copy of the default environment and starts an interactive main loop that connects to standard I/O. The main loop is as follows:

(begin (define (loop) (let ((line (read-line \"PLIS: \"))) (if line (let ((res (catch (eval (read-string line) (global-environment))))) (display res) (loop))))) (loop))

  Module Remote

  CLASS Remote.Call


Method `()

mixed `()(mixed ... args)


Method sync

mixed sync(mixed ... args)


Method async

void async(mixed ... args)


Method exists

int exists()


Method is_async

int is_async()


Method set_async

void set_async(int a)


Method create

void Remote.Call(string objectid, string name, object connection, object context, int async)

  CLASS Remote.Connection


Method create

void Remote.Connection(void|int nice, void|int max_call_threads)

Parameter nice

If set, no errors will be thrown.


Method connect

int connect(string host, int port, void|int timeout)

Description

This function is called by clients to connect to a server.


Method start_server

void start_server(object c, object cx)

Description

This function is called by servers when they have got a connection from a client. The first argument is the connection file object, and the second argument is the context to be used.


Method add_close_callback

void add_close_callback(function f, mixed ... args)

Description

Add a function that is called when the connection is closed.


Method remove_close_callback

void remove_close_callback(array f)

Description

Remove a function that is called when the connection is closed.


Method close

void close()

Description

Closes the connection nicely, after waiting in outstanding calls in both directions.


Method call_sync

mixed call_sync(array data)

Description

Make a call and wait for the result


Method call_async

void call_async(array data)

Description

Make a call but don't wait for the result


Method get_named_object

object get_named_object(string name)

Description

Get a named object provided by the server.

  CLASS Remote.Context


Method id_for

string id_for(mixed thing)


Method object_for

object object_for(string id)


Method function_for

object function_for(string id)


Method encode

array encode(mixed val)


Method decode

mixed decode(array a)


Method encode_call

array encode_call(object|string o, string|function f, array args, int type)


Method decode_call

function|object decode_call(array data)


Method decode_existp

int decode_existp(array data)


Method add

void add(object o, string id)


Method describe

string describe(array data)


Method set_server_context

void set_server_context(object ctx, object cn)


Method create

void Remote.Context(string b, object|void cn)

  CLASS Remote.Obj


Method get_function

mixed get_function(string f)


Method `[]

mixed `[](string f)


Method `->

mixed `->(string f)


Method exists

int exists()


Method create

void Remote.Obj(string id, object connection, object context)

  Module Standards

  CLASS Standards.URI

Description

This class implements URI parsing and resolving of relative references to absolute form, as defined in RFC 2396


Variable scheme

string scheme

Description

Scheme component of URI


Variable authority

string authority

Description

Authority component of URI (formerly called net_loc, from RFC 2396 known as authority)


Variable path

string path

Description

Path component of URI. May be empty, but not undefined.


Variable query

string query

Description

Query component of URI. May be 0 if not present.


Variable fragment

string fragment

Description

The fragment part of URI. May be 0 if not present.


string host
string user
string password

Description

Certain classes of URI (e.g. URL) may have these defined


Variable port

int port

Description

If no port number is present in URI, but the scheme used has a default port number, this number is put here.


Variable base_uri

this_program base_uri

Description

The base URI object, if present


Method `==

int `==(mixed something)

Description

Compare this URI to something, in a canonical way.

Parameter something

Compare the URI to this


Method reparse_uri

void reparse_uri()
void reparse_uri(URI base_uri)
void reparse_uri(string base_uri)

Description

Reparse the URI with respect to a new base URI. If no base_uri was supplied, the old base_uri is thrown away. The resolving is performed according to the guidelines outlined by RFC 2396, Uniform Resource Identifiers (URI): Generic Syntax.

Parameter base_uri

Set the new base URI to this.


Method create

void Standards.URI(URI uri)
void Standards.URI(URI uri, URI base_uri)
void Standards.URI(URI uri, string base_uri)
void Standards.URI(string uri)
void Standards.URI(string uri, URI base_uri)
void Standards.URI(string uri, string base_uri)

Parameter base_uri

When supplied, will root the URI a the given location. This is needed to correctly verify relative URIs, but may be left out otherwise. If left out, and uri is a relative URI, an error is thrown.

Parameter uri

When uri is another URI object, the created URI will inherit all properties of the supplied uri except, of course, for its base_uri.


Method `->=
Method `[]=

mixed `->=(string property, mixed value)
mixed `[]=(string property, mixed value)

Description

Assign a new value to a property of URI

Parameter property

When any of the following properties are used, properties that depend on them are recalculated: user, password, host, port, authority, base_uri.

Parameter value

The value to assign to property


Method cast

string|mapping cast(string to)

Description

When cast to string, return the URI (in a canonicalized form). When cast to mapping, return a mapping with scheme, authority, user, password, host, port, path, query, fragment, raw_uri, base_uri as documented above.


Method get_path_query

string get_path_query()

Description

Returns path and query part of the URI if present.

  Module Standards.ASN1

  Module Standards.ASN1.Decode

Description

Decodes a DER object.



Method der_decode

Object Standards.ASN1.Decode.der_decode(ADT.struct data, mapping(int:program) types)

Parameter data

an instance of ADT.struct

Parameter types

a mapping from combined tag numbers to classes from or derived from Standards.ASN1.Types . Combined tag numbers may be generated using Standards.ASN1.Types.make_combined_tag .

Returns

an object from Standards.ASN1.Types or either Standards.ASN1.Decode.primitive or Standards.ASN1.Decode.constructed if the type is unknown. Throws an exception if the data could not be decoded.

FIXME

Handling of implicit and explicit ASN.1 tagging, as well as other context dependence, is next to non_existant.


Method simple_der_decode

Object Standards.ASN1.Decode.simple_der_decode(string data)

Description

decode a DER encoded object using universal data types

Parameter data

a DER encoded object

Returns

an object from Standards.ASN1.Types or either Standards.ASN1.Decode.primitive or Standards.ASN1.Decode.constructed if the type is unknown.

  CLASS Standards.ASN1.Decode.primitive

Description

Primitive unconstructed ASN1 data type.


Inherit Object

inherit Types.Object : Object


Method get_der
Method get_combined_tag

string get_der()
int get_combined_tag()

Description

get raw encoded contents of object


Method get_tag

int get_tag()

Description

get tag


Method get_cls

int get_cls()

Description

get class

  CLASS Standards.ASN1.Decode.constructed

Description

constructed type


Inherit Object

inherit Types.Object : Object


Variable raw

string raw

Description

raw encoded contents


Variable elements

array elements

Description

elements of object


Method get_tag

int get_tag()

Description

get tag


Method get_cls

int get_cls()

Description

get class

  Module Standards.ASN1.Types

Description

Encodes various asn.1 objects according to the Distinguished Encoding Rules (DER)


Method make_combined_tag

int Standards.ASN1.Types.make_combined_tag(int cls, int tag)

Description

Combines tag and class as a single integer, in a somewhat arbitrary way. This works also for tags beyond 31 (although not for tags beyond 2^30.

Parameter cls

ASN1 type class

Parameter tag

ASN1 type tag

Returns

combined tag

See also

Standards.ASN1.Types.extract_tag Standards.ASN1.Types.extract_cls


Method extract_tag

int Standards.ASN1.Types.extract_tag(int i)

Description

extract ASN1 type tag from a combined tag

See also

Standards.ASN1.Types.make_combined_tag


Method extract_cls

int Standards.ASN1.Types.extract_cls(int i)

Description

extract ASN1 type class from a combined tag

See also

Standards.ASN1.Types.make_combined_tag


Method asn1_utf8_valid

int(1..1) Standards.ASN1.Types.asn1_utf8_valid(string s)

Description

Checks if a Pike string can be encoded with UTF8. That is always the case...


Method asn1_printable_valid

int(0..1) Standards.ASN1.Types.asn1_printable_valid(string s)

Description

Checks if a Pike string can be encoded as a PrintableString .


Method asn1_teletex_valid

int(0..1) Standards.ASN1.Types.asn1_teletex_valid(string s)


Method asn1_broken_teletex_valid

int(0..1) Standards.ASN1.Types.asn1_broken_teletex_valid(string s)


Method asn1_IA5_valid

int(0..1) Standards.ASN1.Types.asn1_IA5_valid(string s)


Method asn1_universal_valid

int(0..0) Standards.ASN1.Types.asn1_universal_valid(string s)


Method asn1_bmp_valid

int(0..1) Standards.ASN1.Types.asn1_bmp_valid(string s)

  CLASS Standards.ASN1.Types.Object

Description

Generic, abstract base class for ASN1 data types.


Method get_cls

int get_cls()

Description

Get the class of this object.

Returns

The class of this object.


Method get_tag

int get_tag()

Description

Get the tag for this object.

Returns

The tag for this object.


Method get_combined_tag

int get_combined_tag()

Description

Get the combined tag (tag + class) for this object.

Returns

the combined tag header


Method get_der

string get_der()

Description

Get the DER encoded version of this object.

Returns

DER encoded representation of this object.

  CLASS Standards.ASN1.Types.Compound

Description

Compound object primitive


Inherit Object

inherit Object : Object


Variable elements

array(Object) elements

Description

contents of compound object, elements are from Standards.ASN1.Types

  CLASS Standards.ASN1.Types.String

Description

string object primitive


Inherit Object

inherit Object : Object


Variable value

string value

Description

value of object

  CLASS Standards.ASN1.Types.Boolean

Description

boolean object


Inherit Object

inherit Object : Object


Variable value

int value

Description

value of object

  CLASS Standards.ASN1.Types.Integer

Description

Integer object All integers are represented as bignums, for simplicity


Inherit Object

inherit Object : Object


Variable value

Gmp.mpz value

Description

value of object

  CLASS Standards.ASN1.Types.Enumerated

Description

Enumerated object


Inherit Integer

inherit Integer : Integer

  CLASS Standards.ASN1.Types.BitString

Description

Bit string object


Inherit Object

inherit Object : Object


Variable value

string value

Description

value of object


Method set_from_ascii

this_program set_from_ascii(string s)

Description

Set the bitstring value as a string with "1" and "0".


Method set_length

int set_length(int len)

Description

Sets the length of the bit string to len number of bits.

  CLASS Standards.ASN1.Types.OctetString

Description

Octet string object


Inherit String

inherit String : String

  CLASS Standards.ASN1.Types.Null

Description

Null object


Inherit Object

inherit Object : Object

  CLASS Standards.ASN1.Types.Identifier

Description

Object identifier object


Inherit Object

inherit Object : Object


Variable id

array(int) id

Description

value of object


Method append

this_program append(int ... args)

Description

Returns a new Identifier object with args appended to the ID path.

  CLASS Standards.ASN1.Types.UTF8String

Description

UTF8 string object

Character set: ISO/IEC 10646-1 (compatible with Unicode).

Variable width encoding, see rfc2279.


Inherit String

inherit String : String

  CLASS Standards.ASN1.Types.Sequence

Description

Sequence object


Inherit Compound

inherit Compound : Compound

  CLASS Standards.ASN1.Types.Set

Description

Set object


Inherit Compound

inherit Compound : Compound

  CLASS Standards.ASN1.Types.PrintableString

Description

PrintableString object


Inherit String

inherit String : String

  CLASS Standards.ASN1.Types.TeletexString

Description

TeletexString object

Avoid this one; it seems to be common that this type is used to label strings encoded with the ISO 8859-1 character set (use asn1_broken_teletex_string for that). From http://www.mindspring.com/~asn1/nlsasn.htm:

/.../ Types GeneralString, VideotexString, TeletexString (T61String), and GraphicString exist in earlier versions [pre-1994] of ASN.1. They are considered difficult to use correctly by applications providing national language support. Varying degrees of application support for T61String values seems to be most common in older applications. Correct support is made more difficult, as character values available in type T61String have changed with the addition of new register entries from the 1984 through 1997 versions.

This implementation is based on the description of T.61 and T.51 in "Some functions for representing T.61 characters from the X.500 Directory Service in ISO 8859 terminals (Version 0.2. July 1994.)" by Enrique Silvestre Mora (mora@si.uji.es), Universitat Jaume I, Spain, found in the package ftp://pereiii.uji.es/pub/uji-ftp/unix/ldap/iso-t61.translation.tar.Z

The translation is only complete for 8-bit latin 1 strings. It encodes strictly to T.61, but decodes from the superset T.51.


Inherit String

inherit String : String

  CLASS Standards.ASN1.Types.BrokenTeletexString

Description

(broken) TeletexString object

Encodes and decodes latin1, but labels it TeletexString, as is common in many broken programs (e.g. Netscape 4.0X).


Inherit String

inherit String : String

  CLASS Standards.ASN1.Types.IA5String

Description

IA5 String object

Character set: ASCII. Fixed width encoding with 1 octet per character.


Inherit String

inherit String : String

  CLASS Standards.ASN1.Types.VisibleString


Inherit String

inherit String : String

  CLASS Standards.ASN1.Types.UTC


Inherit String

inherit String : String

  CLASS Standards.ASN1.Types.UniversalString

Description

Universal String object

Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 4 octets per character.

FIXME

The encoding is very likely UCS-4, but that's not yet verified.


Inherit OctetString

inherit OctetString : OctetString

  CLASS Standards.ASN1.Types.BMPString

Description

BMP String object

Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 2 octets per character.

FIXME: The encoding is very likely UCS-2, but that's not yet verified.


Inherit OctetString

inherit OctetString : OctetString

  CLASS Standards.ASN1.Types.MetaExplicit

Description

Meta-instances handle a particular explicit tag and set of types.

FIXME

document me!

  Module Standards.PKCS

  Module Standards.PKCS.CSR

Description

Handling of Certifikate Signing Requests (PKCS-10)



Method build_csr

Sequence Standards.PKCS.CSR.build_csr(Crypto.RSA rsa, object name, mapping(string:array(object)) attributes)

  Module Standards.PKCS.Certificate

Description

Handle PKCS-6 and PKCS-10 certificates and certificate requests.




Method build_distinguished_name

Sequence Standards.PKCS.Certificate.build_distinguished_name(mapping(string:object) ... args)


Method get_certificate_issuer

Sequence Standards.PKCS.Certificate.get_certificate_issuer(string cert)

Description

Return the certificate issuer RDN from a certificate string.

Parameter cert

A string containing an X509 certificate.

Note that the certificate normally must be decoded using MIME.decode_base64 .

Returns

An Standards.ASN1.Sequence object containing the certificate issuer Distinguished Name (DN).


Method get_dn_string

string Standards.PKCS.Certificate.get_dn_string(Sequence dnsequence)

Description

Converts an RDN (relative distinguished name) Seqeunce object to a human readable string in X500 format.

Parameter cert

A string containing an X509 certificate.

Note that the certificate normally must be decoded using MIME.decode_base64 .

Returns

A string containing the certificate issuer Distinguished Name (DN) in human readable X500 format.

Note

We don't currently handle attributes with multiple values, not all attribute types are understood.


Method get_certificate_subject

Sequence Standards.PKCS.Certificate.get_certificate_subject(string cert)

Description

Return the certificate subject RDN from a certificate string.

Parameter cert

A string containing an X509 certificate.

Note that the certificate normally must be decoded using MIME.decode_base64 .

Returns

An Standards.ASN1.Sequence object containing the certificate subject Distinguished Name (DN).

  Module Standards.PKCS.DSA

Description

DSA operations as defined in RFC-2459.



Method algorithm_identifier

Sequence Standards.PKCS.DSA.algorithm_identifier(Crypto.DSA|void dsa)


Method public_key

string Standards.PKCS.DSA.public_key(Crypto.DSA dsa)


Method private_key

string Standards.PKCS.DSA.private_key(Crypto.DSA dsa)


Method parse_private_key

Crypto.DSA Standards.PKCS.DSA.parse_private_key(string key)

  Module Standards.PKCS.Identifiers

Description

Various ASN.1 identifiers used by PKCS.


  Module Standards.PKCS.RSA

Description

RSA operations and types as described in PKCS-1.



Method public_key

string Standards.PKCS.RSA.public_key(Crypto.RSA rsa)

Description

Create a DER-coded RSAPublicKey structure

Parameter rsa

Crypto.RSA object

Returns

ASN1 coded RSAPublicKey structure


Method private_key

string Standards.PKCS.RSA.private_key(Crypto.RSA rsa)

Description

Create a DER-coded RSAPrivateKey structure

Parameter rsa

Crypto.RSA object

Returns

ASN1 coded RSAPrivateKey structure


Method parse_public_key

Crypto.RSA Standards.PKCS.RSA.parse_public_key(string key)

Description

Decode a DER-coded RSAPublicKey structure

Parameter key

RSAPublicKey provided in ASN1 encoded format

Returns

Crypto.RSA object


Method parse_private_key

Crypto.RSA Standards.PKCS.RSA.parse_private_key(string key)

Description

Decode a DER-coded RSAPrivateKey structure

Parameter key

RSAPrivateKey provided in ASN1 encoded format

Returns

Crypto.RSA object

  Module Standards.PKCS.Signature


Method build_digestinfo

string Standards.PKCS.Signature.build_digestinfo(string msg, Crypto.Hash hash)

Description

Construct a PKCS-1 digestinfo

Parameter msg

message to digest

Parameter hash

crypto hash object such as Crypto.SHA or Crypto.MD5

  Module Standards.EXIF

Description

This module implements EXIF (Exchangeable image file format for Digital Still Cameras) 2.2 parsing.


Method get_properties

mapping Standards.EXIF.get_properties(Stdio.File file)

Description

Retrieve the EXIF properties of the given file.

Parameter file

The Stdio.File object containing wanted EXIF properties.

Returns

A mapping with all found EXIF properties.

  Module Standards.ID3

Description

ID3 decoder/encoder. Supports versions 1.0, 1.1, 2.2-2.4. For more info see http://www.id3.org

Note

Note that this implementation is far from complete and that interface changes might be neccessary during the implementation of the full standard.


Method synchsafe_to_int

int Standards.ID3.synchsafe_to_int(array(int) bytes)

Description

Decodes a synchsafe integer, generated according to ID3v2.4.0-structure section 6.2.

See also

int_to_synchsafe


Method int_to_synchsafe

array(int) Standards.ID3.int_to_synchsafe(int in, void|int no_bytes)

Description

Encodes a integer to a synchsafe integer according to ID3v2.4.0-structure section 6.2.

See also

synchsafe_to_int


Method resynchronise

string Standards.ID3.resynchronise(string in)

Description

Reverses the effects of unsyncronisation done according to ID3v2.4.0-structure section 6.1.

See also

unsynchronise


Method unsynchronise

string Standards.ID3.unsynchronise(string in)

Description

Unsynchronises the string according to ID3v2.4.0-structure section 6.1.

See also

resynchronise


Method decode_string

string Standards.ID3.decode_string(string in, int type)

Description

Decodes the string in from the type , according to ID3v2.4.0-structure section 4, into a wide string.

See also

encode_string


Method encode_string

array(string|int) Standards.ID3.encode_string(string in)

Description

Encodes the string in to an int-string pair, where the integer is the encoding mode, according to ID3v2.4.0-structure, and the string is the encoded string. This function tries to minimize the size of the encoded string by selecting the most apropriate encoding method.

See also

decode_string , encode_strings


Method encode_strings

array(string|int) Standards.ID3.encode_strings(array(string) in)

Description

Encodes several strings in the same way as encode_string , but encodes all the strings with the same method, selected as in encode_string . The first element in the resulting array is the selected method, while the following elements are the encoded strings.

See also

decode_string , encode_string

  CLASS Standards.ID3.Buffer

Description

A wrapper around a Stdio.File object that provides a read limit capability.


syntax

Stdio.File buffervoid Standards.ID3.Buffer(Stdio.File buffer)


Method read

string read(int bytes)

Description

Read bytes bytes from the buffer. Throw an exception if bytes is bigger than the number of bytes left in the buffer before reaching the limit set by set_limit .


Method peek

string peek()

Description

Preview the next byte. Technically it is read from the encapsulated buffer and put locally to avoid seeking.


Method set_limit

void set_limit(int bytes)

Description

Set an artificial EOF bytes bytes further into the buffer.


Method bytes_left

int bytes_left()

Description

The number of bytes left before reaching the limit set by set_limit .

  CLASS Standards.ID3.TagHeader

Description

Represents an ID3v2 header.


Method create

void Standards.ID3.TagHeader(void|Buffer buffer)


Method decode

void decode(Buffer buffer)

Description

Decode a tag header from buffer and store its data in this object.


Method encode

string encode()

Description

Encode the data in this tag and return as a string.


Method set_flag_unsynchronisation

int(0..1) set_flag_unsynchronisation(array(Frame) frames)

Description

Should the unsynchronisation flag be set or not?

  CLASS Standards.ID3.ExtendedHeader


Method create

void Standards.ID3.ExtendedHeader(void|Buffer buffer)


Method decode

void decode(Buffer buffer)


Method encode

string encode()

  CLASS Standards.ID3.FrameData

Description

Abstract class for frame data.


Method create

void Standards.ID3.FrameData(void|string data)


Method changed

int(0..1) changed()

Description

Is the content altered?

  CLASS Standards.ID3.Tagv2

Description

ID3 version 2 (2.2, 2.3, 2.4) Tags


Method create

void Standards.ID3.Tagv2(void|Buffer|Stdio.File buffer, void|int(0..1) _best_effort)

  CLASS Standards.ID3.Tagv1

Description

ID3 version 1.0 or 1.1 tag. This is really a clumsy way of reading ID3v1 tags, but it has the same interface as the v2 reader.

  CLASS Standards.ID3.Tag

Description

This is a ID3 tag super object, which encapsulates all versions ID3 tags. This is useful if you are only interested in the metadata of a file, and care not about how it is stored or have no interest in changing the data.

Note

Version 1 tag is searched only if version 2 isn't found.

See also

Tagv2 , Tagv1


Method create

void Standards.ID3.Tag(Stdio.File fd)

Description

The file object fd is searched for version 2 tags, and if not found, version 1 tags.

Throws

If no tag was found in the file an error is thrown.


Method `[]
Method `->

mixed `[](string index)
mixed `->(string index)

Description

The index operators are overloaded to index the encapsulated Tagv1 or Tagv2 object.


Constant version

constant version

Description

The version of the encapsulated tag in the form "%d.%d.%d".


Method _indices

array _indices()

Description

Indices will return the indices of the tag object.


Method _values

array _values()

Description

Values will return the values of the tag object.


Method friendly_values

mapping(string:string) friendly_values()

Description

Returns tag values in a mapping. Only tag values that exists in ID3v1.1 is used. Nonexisting or undefined values will not appear in the mapping.

"artist" : string

Takes its value from TPE1 or TP1 frames.

"album" : string

Takes its value from TALB or TAL frames.

"title" : string

Takes its value from TIT2 or TT2 frames.

"genre" : string

Takes its value from TCON or TCM frames.

"year" : string

Takes its value from TYER or TYE frames.

"track" : string

Takes its value from TRCK or TRK frames. The string may be either in the "%d" form or in the "%d/%d" form.


  Module Standards.IDNA

Description

This module implements various algorithms specified by the Internationalizing Domain Names in Applications (IDNA) memo by the Internet Engineering Task Force (IETF), see ftp://ftp.rfc-editor.org/in-notes/rfc3490.txt.


Variable Punycode

object Standards.IDNA.Punycode

Description

Punycode transcoder, see ftp://ftp.rfc-editor.org/in-notes/rfc3492.txt. Punycode is used by to_ascii as an "ASCII Compatible Encoding" when needed.


Method nameprep

string Standards.IDNA.nameprep(string s, int(0..1)|void allow_unassigned)

Description

Prepare a Unicode string for ACE transcoding. Used by to_ascii . Nameprep is a profile of Stringprep, which is described in RFC 3454.

Parameter s

The string to prep.

Parameter allow_unassigned

Set this flag the the string to transform is a "query string", and not a "stored string". See RFC 3454.


Method to_ascii

string Standards.IDNA.to_ascii(string s, int(0..1)|void allow_unassigned, int(0..1)|void use_std3_ascii_rules)

Description

The to_ascii operation takes a sequence of Unicode code points that make up one label and transforms it into a sequence of code points in the ASCII range (0..7F). If to_ascci succeeds, the original sequence and the resulting sequence are equivalent labels.

Parameter s

The sequence of Unicode code points to transform.

Parameter allow_unassigned

Set this flag if the the string to transform is a "query string", and not a "stored string". See RFC 3454.

Parameter use_std3_ascii_rules

Set this flag to enforce the restrictions on ASCII characters in host names imposed by STD3.


Method to_unicode

string Standards.IDNA.to_unicode(string s)

Description

The to_unicode operation takes a sequence of Unicode code points that make up one label and returns a sequence of Unicode code points. If the input sequence is a label in ACE form, then the result is an equivalent internationalized label that is not in ACE form, otherwise the original sequence is returned unaltered.

Parameter s

The sequence of Unicode code points to transform.


Method zone_to_ascii

string Standards.IDNA.zone_to_ascii(string s, int(0..1)|void allow_unassigned, int(0..1)|void use_std3_ascii_rules)

Description

Takes a sequence of labels separated by '.' and applies to_ascii on each.


Method zone_to_unicode

string Standards.IDNA.zone_to_unicode(string s)

Description

Takes a sequence of labels separated by '.' and applies to_unicode on each.

  Module Standards.ISO639_2


Method get_language

string Standards.ISO639_2.get_language(string code)

Description

Look up the language name given an ISO 639-2 code in lower case. It will first be looked up in the ISO 639-2/T table and then in ISO 639-2/B if the first lookup failed. Returns zero typed zero on failure.


Method get_language_t

string Standards.ISO639_2.get_language_t(string code)

Description

Look up the language name given an ISO 639-2/T code in lower case. Returns zero typed zero on failure.


Method get_language_b

string Standards.ISO639_2.get_language_b(string code)

Description

Look up the language name given an ISO 639-2/B code in lower case. Returns zero typed zero on failure.


Method list_languages

mapping(string:string) Standards.ISO639_2.list_languages()

Description

Return a mapping from ISO 639-2/T + ISO 639-2/B codes to language names.


Method list_languages_t

mapping(string:string) Standards.ISO639_2.list_languages_t()

Description

Return a mapping from ISO 639-2/T codes to language names.


Method list_languages_b

mapping(string:string) Standards.ISO639_2.list_languages_b()

Description

Return a mapping from ISO 639-2/B codes to language names.


Method convert_b_to_t

string Standards.ISO639_2.convert_b_to_t(string code)

Description

Converts an ISO 639-2/B code to an ISO 639-2/T code.


Method convert_t_to_b

string Standards.ISO639_2.convert_t_to_b(string code)

Description

Converts an ISO 639-2/T code to an ISO 639-2/B code.


Method map_639_1

string Standards.ISO639_2.map_639_1(string code)

Description

Look up the ISO 639-2/T code given an ISO 639-1 code in lower case.


Method map_to_639_1

string Standards.ISO639_2.map_to_639_1(string code)

Description

Look up the ISO 639-1 code given an ISO 639-2/T code in lower case.


Method list_639_1

mapping(string:string) Standards.ISO639_2.list_639_1()

Description

Return a mapping from ISO 639-1 code to ISO 639-2/T code.

  Module Tools

  CLASS Tools.PV

Description

Display a image on the screen. Requires GTK.


Inherit Window

inherit GTK.Window : Window


Typedef PVImage

typedef Standards.URI|string|Image.Image|Image.Layer|array(Image.Layer) PVImage

Description

The image types accepted. If the image is a string, it is assumed to be a filename of a image that can be loaded with Image.load. This includes URLs.


Method set_alpha_mode

void set_alpha_mode(AlphaMode m)

Description

Set the alpha combining mode. m is one of Squares , Solid , None and AlphaOnly .


Method set_alpha_colors

void set_alpha_colors(Image.Color.Color c1, Image.Color.Color|void c2)

Description

Set the colors used for the alpha combination. c2 is only used for the Squares alpha mode.

See also

set_alpha_mode()


Method get_as_image

Image.Image get_as_image(PVImage i)

Description

Return the current image as a Image object, with the alpha combining done.


Method set_image

void set_image(PVImage i)

Description

Change the image.


Method scale

void scale(float factor)

Description

Scale the image before display with the specified factor.


Method save

void save(string filename, string|void format)

Description

Write the image to a file. If no format is specified, PNG is used. The alpha combination is done on the image before it's saved.

  ENUM Tools.PV.AlphaMode

Description

The alpha combination modes.

Use set_alpha_mode() to change the mode.


Constant Squares

constant Squares

Description

Checkerboard pattern (default).


Constant Solid

constant Solid

Description

Solid color.


Constant None

constant None

Description

Ignore alpha.


Constant AlphaOnly

constant AlphaOnly

Description

Only show the alpha channel (if any).

  Module Tools.AutoDoc

  Module Tools.AutoDoc.ProcessXML


Inherit Tree

inherit Parser.XML.Tree : Tree


Inherit "module.pmod"

inherit "module.pmod"


Method extractXML

string Tools.AutoDoc.ProcessXML.extractXML(string filename, int|void pikeMode, string|void type, string|void name, array(string)|void parentModules)

Description

This function extracts documentation from a file. The parameters type , name , and parentModules are used only when pikeMode != 0 and no C-style doc comments are present.

Parameter filename

The file to extract from.

Parameter pikeMode

Non-zero if it is a Pike file. If the file contains style doc comments, C-mode is used despite pikeMode != 0.

Parameter type

"class", "module" or "namespace".

Parameter name

The name of the class/module/namespace.

Parameter parentModules

The ancestors of the class/module/namespace.

Example

// To extract doc for Foo.Bar.Ippa: string xml = extractXML("lib/modules/Foo.pmod/Bar.pmod/Ippa.pike", 1, "class", "Ippa", ({ "Foo", "Bar" }));


Method moveImages

string Tools.AutoDoc.ProcessXML.moveImages(string docXMLFile, string imageSourceDir, string imageDestDir, int|void quiet)

Description

Copy all images to canonical files in a flat directory.

Parameter docXMLFile

The contents of the XML file. The XML file is the result of extraction from a single C or Pike file, for example the result of calling extractXML .

Parameter imageSourceDir

The directory that is the base of the relative paths to images. This should be the directory of the source file that was the input to extract the XML file.

Parameter imageDestDir

The directory where the images should be copied.

Parameter quiet

Quiet operation.

Returns

The XML file contents (with decorated <image>-tags)


Method mergeTrees

void Tools.AutoDoc.ProcessXML.mergeTrees(Node dest, Node source)

Description

Puts all children of source into the tree dest , in their right place module-hierarchically. Used to merge the results of extractions of different Pike and C files.

Parameter source
Parameter dest

The nodes source and dest are <class>, <module>, <namespace> or <autodoc> nodes that are identical in the sense that they represent the same module, class or namespace. Typically they both represent <autodoc> nodes.

Note

After calling this method, any <class> or <module> nodes that have been marked with @appears or @belongs, are still in the wrong place in the tree, so handleAppears() (or postProcess() ) must be called on the whole documentation tree to relocate them once the tree has been fully merged.


Method handleAppears

void Tools.AutoDoc.ProcessXML.handleAppears(Node root)

Description

Take care of all the @appears and @belongs directives everywhere, and rearranges the nodes in the tree accordingly

Parameter root

The root (<autodoc>) node of the documentation tree.


Method postProcess

void Tools.AutoDoc.ProcessXML.postProcess(Node root)

Description

Perform the last steps on a completed documentation tree.

Parameter root

Root <autodoc> node of the completed documentation tree.

Calls handleAppears() , cleanUndocumented() and resolveRefs() in turn.

See also

handleAppears() , cleanUndocumented() , resolveRefs()

  Module Tools.Legal

  Module Tools.Legal.License


Method get_text

string Tools.Legal.License.get_text()

Description

Returns all the licenses as a string, suitable for saving as a file.

  Module Tools.Legal.Copyright

Description

Contains functions and information to store and present copyright information about Pike and it's components.


Method add

void Tools.Legal.Copyright.add(string what, array(string) holders)

Description

Adds a copyright message for the copyright holders for the component what .

Throws

An error is thrown if the copyrighted component what is already in the list of copyrights.


Method get_latest_pike

string Tools.Legal.Copyright.get_latest_pike()

Description

Return the latest copyright holder of Pike.


Method get_all

mapping(string:array(string)) Tools.Legal.Copyright.get_all()

Description

Returns a mapping containing all the stored copyrights. The mapping maps component name to an array of copyright holders.


Method get_text

string Tools.Legal.Copyright.get_text()

Description

Returns the copyrights as a string, suitable for saving as a file.

  Module Tools.Shoot



Method _shoot

void Tools.Shoot._shoot(string id)

Description

This function is called in the spawned pike, to perform the test but also to write some important data to stdout. id is the current test.

  CLASS Tools.Shoot.Test


Constant name

constant name

Description

The name of the test.


Method perform

void perform()

Description

perform() is the function called in the tests, when it returns the test is complete.

  CLASS Tools.Shoot.ExecTest

Description

The test call/result class. Instantiated with a test id and the test object itself.


syntax

string id
Test testvoid Tools.Shoot.ExecTest(string id, Test test)


Method run

int(0..1) run(int maximum_seconds, int maximum_runs, void|int silent)

Description

This function runs the actual test, by spawning off a new pike and call it until at least one of these conditions: maximum_seconds has passed, or the number of runs is at least maximum_runs.

  Module Tools.Hilfe


Method format_hr_time

string Tools.Hilfe.format_hr_time(int i)

Description

Helper function that formats a time span in nanoseconds to something more human readable (ns, ms or s).

  CLASS Tools.Hilfe.Command

Description

Abstract class for Hilfe commands.


Method help

string help(string what)

Description

Returns a one line description of the command. This help should be shorter than 54 characters.


Method doc

string doc(string what, string with)

Description

A more elaborate documentation of the command. This should be less than 68 characters per line.


Method exec

void exec(Evaluator e, string line, array(string) words, array(string) tokens)

Description

The actual command callback. Messages to the user should be written out by using the safe_write method in the Evaluator object.

  CLASS Tools.Hilfe.CommandReset

Description

Variable reset command. Put ___Hilfe->commands->reset = Tools.Hilfe.CommandReset(); in your .hilferc to have this command defined when you open Hilfe.


Inherit Command

inherit Command : Command

  CLASS Tools.Hilfe.ParserState

Description

In every Hilfe object (Evaluator ) there is a ParserState object that manages the current state of the parser. Essentially tokens are entered in one end and complete expressions are outputted in the other. The parser object is accessible as ___Hilfe->state from Hilfe expressions.


Method feed

void feed(array(string) tokens)

Description

Feed more tokens into the state.


Method read

array(Expression) read()

Description

Read out completed expressions. Returns an array where every element is an expression represented as an array of tokens.


Method show_error

void show_error(function(string:int) w)

Description

Prints out any error that might have occured while push_string was executed. The error will be printed with the print function w .


Method push_string

array(string) push_string(string line)

Description

Sends the input line to Parser.Pike for tokenization, but keeps a state between each call to handle multiline /**/ comments and multiline #"" strings.


Method datap

int datap()

Description

Returns true if there is any waiting expression that can be fetched with read .


Method finishedp

int(0..1) finishedp()

Description

Are we in the middle of an expression. Used e.g. for changing the Hilfe prompt when entering multiline expressions.


Method flush

void flush()

Description

Clear the current state.


Method status

string status()

Description

Returns the current parser state. Used by "dump state".

  CLASS Tools.Hilfe.HilfeHistory

Description

In every Hilfe object (Evaluator ) there is a HilfeHistory object that manages the result history. That history object is accessible both from __ and ___Hilfe->history in Hilfe expressions.


Inherit History

inherit ADT.History : History

  CLASS Tools.Hilfe.Evaluator

Description

This class implements the actual Hilfe interpreter. It is accessible as ___Hilfe from Hilfe expressions.


Variable commands

mapping(string:Command) commands

Description

This mapping contains the available Hilfe commands, including the built in ones (dump, exit, help, new, quit), so it is possible to replace or remove them. The name of a command should be 10 characters or less.


Variable state

ParserState state

Description

Keeps the state, e.g. multiline input in process etc.


Variable variables

mapping(string:mixed) variables

Description

The locally defined variables (name:value).


Variable types

mapping(string:string) types

Description

The types of the locally defined variables (name:type).


Variable constants

mapping(string:mixed) constants

Description

The locally defined constants (name:value).


Variable functions

mapping(string:function) functions

Description

The locally defined functions (name:value).


Variable programs

mapping(string:program) programs

Description

The locally defined programs (name:value).


Variable imports

array(string) imports

Description

The current imports.


Variable inherits

array(string) inherits

Description

The current inherits.


Variable history

HilfeHistory history

Description

The current result history.


Variable write

array|object|function(string:int(0..)) write

Description

The function to use when writing to the user.


Method add_writer

void add_writer(object|function(string:int(0..)) new)

Description

Adds another output function.


Method remove_writer

void remove_writer(object|function old)

Description

Removes an output function.


Method safe_write

int safe_write(string in, mixed ... args)

Description

An output method that shouldn't crash.


Method add_input_hook

void add_input_hook(function|object new)

Description

Adds a function to the input hook, making all user data be fed into the function.

See also

remove_input_hook


Method remove_input_hook

void remove_input_hook(function|object old)

Description

Removes a function from the input hook.

See also

add_input_hook


Method create

void Tools.Hilfe.Evaluator()


Method print_version

void print_version()

Description

Displays the current version of Hilfe.


Method reset_evaluator

void reset_evaluator()

Description

Clears the current state, history and removes all locally defined variables, constants, functions and programs. Removes all imports and inherits. It does not reset the command mapping nor reevaluate the .hilferc file.


Method add_input_line

void add_input_line(string s)

Description

Input a line of text into Hilfe. It checks if s is ".", in which case it calls state->flush(). Otherwise just calls add_buffer.


Method add_buffer

void add_buffer(string s)

Description

Add buffer tokenizes the input string and determines if the new line is a Hilfe command. If not, it updates the current state with the new tokens and sends any and all complete expressions to evaluation in parse_expression .


Method parse_expression

string parse_expression(Expression expr)

Description

Parses a Pike expression. Returns 0 if everything went well, or a string with an error message otherwise.


Variable last_compiled_expr

string last_compiled_expr

Description

The last created wrapper in which an expression was evaluated.


Variable last_compile_time

int(0..) last_compile_time

Description

The last compile time;


Variable last_eval_time

int(0..) last_eval_time

Description

The last evaluation time;


Variable strict_types

int(0..1) strict_types

Description

Strict types?


Variable warnings

int(0..1) warnings

Description

Show warnings?


Variable trace_level

int trace_level

Description

The current trace level.


Variable assembler_debug_level

int assembler_debug_level

Description

The current assembler debug level. Only available if Pike is compiled with RTL debug.


Variable compiler_trace_level

int compiler_trace_level

Description

The current compiler trace level. Only available if Pike is compiled with RTL debug.


Variable debug_level

int debug_level

Description

The current debug level. Only available if Pike is compiled with RTL debug.


Method std_reswrite

void std_reswrite(function w, string sres, int num, mixed res)

Description

The standard reswrite function.


Variable reswrite

function reswrite

Description

The function used to write results. Gets as arguments in order: The safe_write function (function(string, mixed ...:int), the result as a string (string), the history entry number (int), the result (mixed), the compilation time (int) and the evaulation time (int). If the evaluated expression didn't return anything (e.g. a for loop) then 0 will be given as the result string.


Method hilfe_compile

object hilfe_compile(string f, void|string new_var)

Description

Creates a wrapper and compiles the pike code f in it. If a new variable is compiled to be tested, its name should be given in new_var so that magically defined entities can be undefined and a warning printed.


Method evaluate

void evaluate(string a, int(0..1) show_result)

Description

Compiles the Pike code a and evaluates it by calling ___HilfeWrapper in the generated object. If show_result is set the result will be displayed and the result buffer updated with its value.

  CLASS Tools.Hilfe.StdinHilfe

Description

This is a wrapper containing a user interface to the Hilfe Evaluator so that it can actually be used. This wrapper uses the Stdio.Readline module to interface with the user. All input history is handled by that module, and as a consequence loading and saving .hilfe_history is handled in this class. Also .hilferc is handled by this class.


Inherit Evaluator

inherit Evaluator : Evaluator


Variable readline

Stdio.Readline readline

Description

The readline object,


Method save_history

void save_history()

Description

Saves the user input history, if possible, when called.


Method create

void Tools.Hilfe.StdinHilfe(void|array(string) init)

Description

Any hilfe statements given in the init array will be executed once .hilferc has been executed.

  CLASS Tools.Hilfe.GenericHilfe


Inherit Evaluator

inherit Evaluator : Evaluator


Method create

void Tools.Hilfe.GenericHilfe(Stdio.FILE in, Stdio.File out)

  CLASS Tools.Hilfe.GenericAsyncHilfe


Inherit Evaluator

inherit Evaluator : Evaluator


Method create

void Tools.Hilfe.GenericAsyncHilfe(Stdio.File in, Stdio.File out)

  Module Tools.Install

Description

Common routines which are useful for various install scripts based on Pike.


Method features

array(string) Tools.Install.features()


Method make_absolute_path

string Tools.Install.make_absolute_path(string path, string|void cwd)

  CLASS Tools.Install.ProgressBar

Description

A class keeping some methods and state to conveniently render ASCII progress bars to stdout.


Method set_current

void set_current(int _cur)

Description

Change the amount of progress without updating on stdout.


Method set_name

void set_name(string _name)

Description

Change the name of the progress bar without updating on stdout.


Method set_phase

void set_phase(float _phase_base, float _phase_size)


Method update

int update(int increment)

Description

Write the current look of the progressbar to stdout.

Parameter increment

the number of increments closer to completion since last call

Returns

the length (in characters) of the line with the progressbar


Method create

void Tools.Install.ProgressBar(string name, int cur, int max, float|void phase_base, float|void phase_size)

Parameter name

The name (printed in the first 13 columns of the row)

Parameter cur

How much progress has been made so far

Parameter max

The amount of progress signifying 100% done. Must be greater than zero.

  CLASS Tools.Install.Readline


Inherit Readline

inherit Stdio.Readline : Readline


Method trap_signal

void trap_signal(int n)


Method edit

string edit(mixed ... args)


Method edit_filename

string edit_filename(mixed ... args)


Method edit_directory

string edit_directory(mixed ... args)


Method absolute_path

string absolute_path(string path)


Method set_cwd

void set_cwd(string _cwd)

  Module Tools.PEM

Description

Support for parsing PEM-style messages.

  CLASS Tools.PEM.EncapsulatedMsg


Variable boundary

string boundary

Description

contains the boundary string


Variable body

string body

Description

contains the body of the message


Variable headers

mapping(string:string) headers


Method create

void Tools.PEM.EncapsulatedMsg(string eb, string contents)


Method decoded_body

string decoded_body()

Description

decodes a base 64 encoded message body


Method get_boundary

string get_boundary()


Method canonical_body

string canonical_body()


Method to_string

string to_string()

Description

converts the message body and headers to the standard message format.

  CLASS Tools.PEM.RFC934


Variable initial_text

string initial_text


Variable final_text

string final_text


Variable final_boundary

string final_boundary


Variable encapsulated

array(EncapsulatedMsg) encapsulated


Method create

void Tools.PEM.RFC934(string data)

Description

decodes an RFC 934 encoded message.


Method get_final_boundary

string get_final_boundary()


Method to_string

string to_string()

  CLASS Tools.PEM.Msg

Description

Disassembles PGP and PEM style messages with parts separated by "-----BEGIN FOO-----" and "-----END FOO-----".


Variable initial_text

string initial_text

Description

Contains any text preceeding the PEM message.


Variable final_text

string final_text

Description

Contains any text following the PEM message.


Variable parts

mapping(string:EncapsulatedMsg) parts

Description

The decoded PEM message, as an array of EncapsulatedMsg objects indexed by message name, such as "CERTIFICATE".


Method create

void Tools.PEM.Msg(string s)

Description

Creates a decoded PEM message

Parameter s

a string containing a PEM encoded message to be decoded.

  Module Tools.X509




Constant CERT_TOO_OLD

constant Tools.X509.CERT_TOO_OLD


Constant CERT_TOO_NEW

constant Tools.X509.CERT_TOO_NEW


Constant CERT_INVALID

constant Tools.X509.CERT_INVALID


Constant CERT_CHAIN_BROKEN

constant Tools.X509.CERT_CHAIN_BROKEN


Constant CERT_ROOT_UNTRUSTED

constant Tools.X509.CERT_ROOT_UNTRUSTED


Constant CERT_BAD_SIGNATURE

constant Tools.X509.CERT_BAD_SIGNATURE


Constant CERT_UNAUTHORIZED_CA

constant Tools.X509.CERT_UNAUTHORIZED_CA


Method make_time

UTC Tools.X509.make_time(int t)

Description

Creates a Standards.ASN1.Types.UTC object from the posix time t .


Method parse_time

mapping(string:int) Tools.X509.parse_time(UTC asn1)

Description

Returns a mapping similar to that returned by gmtime

Returns
"year" : int
"mon" : int
"mday" : int
"hour" : int
"min" : int
"sec" : int


Method time_compare

int(-1..1) Tools.X509.time_compare(mapping(string:int) t1, mapping(string:int) t2)

Description

Comparision function between two "date" mappings of the kind that parse_time returns.


Method make_tbs

Sequence Tools.X509.make_tbs(object issuer, object algorithm, object subject, object keyinfo, object serial, int ttl, array extensions)


Method make_selfsigned_dsa_certificate

string Tools.X509.make_selfsigned_dsa_certificate(Crypto.DSA dsa, int ttl, array name, array|void extensions)


Method rsa_sign_digest

string Tools.X509.rsa_sign_digest(Crypto.RSA rsa, object digest_id, string digest)


Method rsa_verify_digest

int(0..1) Tools.X509.rsa_verify_digest(Crypto.RSA rsa, object digest_id, string digest, string s)


Method make_selfsigned_rsa_certificate

string Tools.X509.make_selfsigned_rsa_certificate(Crypto.RSA rsa, int ttl, array name, array|void extensions)


Method make_verifier

Verifier Tools.X509.make_verifier(Object _keyinfo)


Method decode_certificate

TBSCertificate Tools.X509.decode_certificate(string|object cert)


Method verify_certificate

TBSCertificate Tools.X509.verify_certificate(string s, mapping authorities)

Description

Decodes a certificate, checks the signature. Returns the TBSCertificate structure, or 0 if decoding or verification failes.

Authorities is a mapping from (DER-encoded) names to a verifiers.

Note

This function allows self-signed certificates, and it doesn't check that names or extensions make sense.


Method verify_certificate_chain

mapping Tools.X509.verify_certificate_chain(array(string) cert_chain, mapping authorities, int|void require_trust)

Description

Decodes a certificate chain, checks the signatures. Verifies that the chain is unbroken, and that all certificates are in effect (time-wise.)

Returns a mapping with the following contents, depending on the verification of the certificate chain:

"error_code" : int

Error describing type of verification failure, if verification failed. May be one of the following: CERT_TOO_NEW , CERT_TOO_OLD , CERT_ROOT_UNTRUSTED , CERT_BAD_SIGNATURE , CERT_INVALID , CERT_UNAUTHORIZED_CA or CERT_CHAIN_BROKEN

"error_cert" : int

Index number of the certificate that caused the verification failure.

"self_signed" : int(0..1)

Non-zero if the certificate is self-signed.

"verified" : int(0..1)

Non-zero if the certificate is verified.

"authority" : string

Standards.ASN1.Sequence of the authority RDN that verified the chain.

"cn" : string

Standards.ASN1.Sequence of the common name RDN of the leaf certificate.


Parameter cert_chain

An array of certificates, with the relative-root last. Each certificate should be a DER-encoded certificate.

Parameter authorities

A mapping from (DER-encoded) names to verifiers.

Parameter require_trust

Require that the certificate be traced to an authority, even if it is self signed.

See Standards.PKCS.Certificate.get_dn_string for converting the RDN to an X500 style string.

  CLASS Tools.X509.rsa_verifier


Inherit Verifier

inherit Verifier : Verifier


Method init

this_program init(string key)


Method verify

int(0..1) verify(Sequence algorithm, string msg, string signature)

  CLASS Tools.X509.TBSCertificate


Variable der

string der


Variable version

int version


Variable serial

Gmp.mpz serial


Variable algorithm

Sequence algorithm


Variable issuer

Sequence issuer


Variable not_after

mapping not_after


Variable not_before

mapping not_before


Variable subject

Sequence subject


Variable public_key

Verifier public_key


Variable issuer_id

BitString issuer_id

Note

optional


Variable subject_id

BitString subject_id

Note

optional


Variable extensions

object extensions

Note

optional


Method init

this_program init(Object asn1)

  Module Tools.sed

Description

edit commands supported:

 <firstline>,<lastline><edit command>
    ^^ numeral (17) ^^
       or relative (+17, -17)
       or a search regexp (/regexp/)
       or multiple (17/regexp//regexp/+2)
 

CommandAction
DDelete first line in space
GInsert hold space
HAppend current space to hold space
PPrint current data
a<string>Insert
c<string>Change current space
dDelete current space
hCopy current space to hold space
i<string>Print string
lPrint current space
pPrint first line in data
qQuit evaluating
s/regexp/with/xReplace
y/chars/chars/Replace chars

where line is numeral, first 'line'==0


Method `()

string|array Tools.sed.`()(string|array(string) commands, string|array(string) data, void|int suppress)

  Module Web

  CLASS Web.RDF

Description

Represents an RDF domain which can contain any number of complete statements.


Variable rdf_Statement

RDFResource rdf_Statement

Description

Statement resource.


Variable rdf_predicate

RDFResource rdf_predicate

Description

predicate resource.


Variable rdf_subject

RDFResource rdf_subject

Description

subject resource.


Variable rdf_object

RDFResource rdf_object

Description

object resource.


Variable rdf_type

RDFResource rdf_type

Description

type resource.


Variable rdf_Seq

RDFResource rdf_Seq

Description

Seq resource.


Variable rdf_first

RDFResource rdf_first

Description

first resource.


Variable rdf_rest

RDFResource rdf_rest

Description

rest resource.


Variable rdf_nil

RDFResource rdf_nil

Description

nil resource.


Method add_statement

void add_statement(Resource subj, Resource pred, Resource obj)

Description

Adds a statement to the RDF set.

Throws

Throws an exception if any argument isn't a Resouce object.


Method has_statement

int(0..1) has_statement(Resource subj, Resource pred, Resource obj)

Description

Returns 1 if the RDF domain contains the relation {subj, pred, obj}, otherwise 0.


Method remove_statement

int(0..1) remove_statement(Resource subj, Resource pred, Resource obj)

Description

Removes the relation from the RDF set. Returns 1 if the relation did exist in the RDF set.


Method reify_low

Resource reify_low(Resource subj, Resource pred, Resource obj)

Description

Reifies the statement { pred, subj, obj } and returns the resource that denotes the reified statement. There will not be any check to see if the unreified statement is already in the domain, making it possible to define the relation twice. The original statement will not be removed.

Returns

The subject of the reified statement.


Method get_reify

Resource get_reify(Resource subj, Resource pred, Resource obj)

Description

Returns a resource that is the subject of the reified statement {subj, pred, obj}, if such a resource exists in the RDF domain.


Method reify

Resource reify(Resource subj, Resource pred, Resource obj)

Description

Returns the result of get_reify , if any. Otherwise calls reify_low followed by remove_statement of the provided statement {subj, pred, obj}.

Returns

The subject of the reified statement.


Method dereify

int(0..1) dereify(Resource r)

Description

Turns the reified statement r into a normal statement, if possible.

Returns

1 for success, 0 for failure.


Method dereify_all

int(0..) dereify_all()

Description

Dereifies as many statements as possible. Returns the number of dereified statements.


Method get_properties

array(Resource) get_properties()

Description

Returns all properties in the domain, e.g. all resources that has been used as predicates.


Method get_subject_map

mapping(Resource:mapping(Resource:array(Resource))) get_subject_map()

Description

Returns a mapping with all the domains subject resources as indices and a mapping with that subjects predicates and objects as value.


Method get_resource

URIResource get_resource(string uri)

Description

Returns an RDF resource with the given URI as identifier, or zero.


Method make_resource

URIResource make_resource(string uri)

Description

Returns an RDF resource with the given URI as identifier, or if no such resrouce exists, creates it and returns it.


Method find_statements

array(array(Resource)) find_statements(Resource|int(0..0) subj, Resource|int(0..0) pred, Resource|int(0..0) obj)

Description

Returns an array with the statements that matches the given subject subj , predicate pred and object obj . Any and all of the resources may be zero to disregard from matching that part of the statement, i.e. find_statements(0,0,0) returns all statements in the domain.

Returns

An array with arrays of three elements.

Array
Resource 0

The subject of the statement

Resource 1

The predicate of the statement

Resource 2

The object of the statement



Method is_subject

int(0..1) is_subject(Resource r)

Description

Returns 1 if resource r is used as a subject, otherwise 0.


Method is_predicate

int(0..1) is_predicate(Resource r)

Description

Returns 1 if resource r is used as a predicate, otherwise 0.


Method is_object

int(0..1) is_object(Resource r)

Description

Returns 1 if resource r is used as an object, otherwise 0.


Method get_3_tuples

string get_3_tuples()

Description

Returns a 3-tuple serialization of all the statements in the RDF set.


Method get_n_triples

string get_n_triples()

Description

Returns an N-triples serialization of all the statements in the RDF set.


Method parse_n_triples

int parse_n_triples(string in)

Description

Parses an N-triples string and adds the found statements to the RDF set. Returns the number of added relations.

Throws

The parser will throw errors on invalid N-triple input.


Method decode_n_triple_string

string decode_n_triple_string(string in)

Description

Decodes a string that has been encoded for N-triples serialization.

Bugs

Doesn't correctly decode backslashes that has been encoded with with \u- or \U-notation.


Method encode_n_triple_string

string encode_n_triple_string(string in)

Description

Encodes a string for use as tring in N-triples serialization.


Method parse_xml

Web.RDF parse_xml(string|Parser.XML.NSTree.NSNode in, void|string base)

Description

Adds the statements represented by the string or tree in to the RDF domain. If in is a tree the in-node should be the RDF node of the XML serialization. RDF documents take its default namespace from the URI of the document, so if the RDF document relies such ingenious mechanisms, pass the document URI in the base variable.


Method get_xml

string get_xml()

Description

Serialize the RDF domain as an XML string.


Method _sizeof

int _sizeof()

Description

Returns the number of statements in the RDF domain.


Method `|

Web.RDF `|(Web.RDF x)

Description

Modifies the current object to create a union of the current object and the object x .

  CLASS Web.RDF.Resource

Description

Instances of this class represents resources as defined in RDF: All things being described by RDF expressions are called resources. A resource may be an entire Web page; such as the HTML document "http://www.w3.org/Overview.html" for example. A resource may be a part of a Web page; e.g. a specific HTML or XML element within the document source. A resource may also be a whole collection of pages; e.g. an entire Web site. A resource may also be an object that is not directly accessible via the Web; e.g. a printed book. This general resource is anonymous and has no URI or literal id.

Note

Resources instantiated from this class should not be used in other RDF domain objects.

See also

URIResource , LiteralResource


Method get_n_triple_name

string get_n_triple_name()

Description

Returns the nodes' N-triple serialized ID.


Method get_3_tuple_name

string get_3_tuple_name()

Description

Returns the nodes' 3-tuple serialized ID.

  CLASS Web.RDF.LiteralResource

Description

Resource identified by literal.


Inherit Resource

inherit Resource : Resource


Variable datatype

string datatype

Description

Used to contain rdf:datatype value.


Method create

void Web.RDF.LiteralResource(string literal)

Description

The resource will be identified by literal .


Method get_xml

string get_xml()

Description

Returns the literal as an XML string.


Method get_literal

string get_literal()

Description

Returns the literal string.

  CLASS Web.RDF.URIResource

Description

Resource identified by URI.


Inherit Resource

inherit Resource : Resource


Method create

void Web.RDF.URIResource(string uri)

Description

Creates an URI resource with the uri as identifier.

Throws

Throws an error if another resource with the same URI already exists in the RDF domain.


Method get_uri

string get_uri()

Description

Returns the URI the resource references to.


Method get_qname

string get_qname(void|string ns)

Description

Returns the qualifying name, or zero.


Method get_namespace

string get_namespace()

Description

Returns the namespace this resource URI references to.

  CLASS Web.RDF.RDFResource

Description

Resource used for RDF-technical reasons like reification.


Inherit URIResource

inherit URIResource : URIResource


Method create

void Web.RDF.RDFResource(string rdf_id)

Description

The resource will be identified by the identifier rdf_id


Method get_qname

string get_qname(void|string ns)

Description

Returns the qualifying name.

  CLASS Web.OWL

Description

Represents an RDF tuple set from an OWL perspective.


Inherit RDFS

inherit .RDFS : RDFS

  Module Web.Crawler

Description

This module implements a generic web crawler.

Features:

Fully asynchronous operation (Several hundred simultaneous requests)

Supports the /robots.txt exclusion standard

Extensible

URI Queues

Allow/Deny rules

Configurable

Number of concurrent fetchers

Bits per second (bandwidth throttling)

Number of concurrent fetchers per host

Delay between fetches from the same host

Supports HTTP and HTTPS

  CLASS Web.Crawler.Stats

Description

Statistics.


syntax

int window_width
int granularityvoid Web.Crawler.Stats(int window_width, int granularity)


Method bytes_read_callback

void bytes_read_callback(Standards.URI uri, int num_bytes_read)

Description

This callback is called when data has arrived for a presently crawled URI, but no more often than once a second.


Method close_callback

void close_callback(Standards.URI uri)

Description

This callback is called whenever the crawling of a URI is finished or fails.

  CLASS Web.Crawler.Policy

Description

The crawler policy object.


Variable max_concurrent_fetchers

int max_concurrent_fetchers

Description

Maximum number of fetchers. Defaults to 100.


Variable max_bits_per_second_total

int max_bits_per_second_total

Description

Maximum number of bits per second. Defaults to off (0).


Variable max_bits_per_second_per_host

int max_bits_per_second_per_host

Description

Maximum number of bits per second, per host. Defaults to off (0).


Variable bandwidth_throttling_floating_window_width

int bandwidth_throttling_floating_window_width

Description

Bandwidth throttling floating window width. Defaults to 30.


Variable max_concurrent_fetchers_per_host

int max_concurrent_fetchers_per_host

Description

Maximum concurrent fetchers per host. Defaults to 1.


Variable min_delay_per_host

int min_delay_per_host

Description

Minimum delay per host. Defaults to 0.

  CLASS Web.Crawler.Queue

Description

A crawler queue. Does not need to be reentrant safe. The Crawler always runs in just one thread.


Method get

int|Standards.URI get()

Description

Get the next URI to index. Returns -1 if there are no URIs to index at the time of the function call, with respect to bandwidth throttling and other limits. Returns 0 if there are no more URIs to index.


Method put

void put(string|array(string)|Standards.URI|array(Standards.URI) uri)

Description

Put one or several URIs in the queue. Any URIs that were already present in the queue are silently disregarded.

  CLASS Web.Crawler.Rule

Description

Abstract rule class.


Method check

int check(string|Standards.URI uri)

  CLASS Web.Crawler.GlobRule

Description

A rule that uses glob expressions

Parameter pattern

a glob pattern that the rule will match against.

Example

GlobRule("http://pike.ida.liu.se/*.xml");


Inherit Rule

inherit Rule : Rule


syntax

string patternvoid Web.Crawler.GlobRule(string pattern)

  CLASS Web.Crawler.RegexpRule

Description

A rule that uses Regexp expressions


Inherit Rule

inherit Rule : Rule


Method create

void Web.Crawler.RegexpRule(string re)

Parameter re

a string describing the Regexp expression

  CLASS Web.Crawler.RuleSet

Description

A set of rules


Method add_rule

void add_rule(Rule rule)

Description

add a rule to the ruleset


Method remove_rule

void remove_rule(Rule rule)

Description

remove a rule from the ruleset

  CLASS Web.Crawler.MySQLQueue


Inherit Queue

inherit Queue : Queue


Method create

void Web.Crawler.MySQLQueue(Stats _stats, Policy _policy, string _host, string _table, void|RuleSet _allow, void|RuleSet _deny)

  CLASS Web.Crawler.MemoryQueue

Description

Memory queue


Inherit Queue

inherit Queue : Queue


Method create

void Web.Crawler.MemoryQueue(Stats _stats, Policy _policy, RuleSet _allow, RuleSet _deny)


Method get

int|Standards.URI get()

Description

Get the next URI to index. Returns -1 if there are no URIs to index at the time of the function call, with respect to bandwidth throttling, outstanding requests and other limits. Returns 0 if there are no more URIs to index.


Method put

void put(string|array(string)|Standards.URI|array(Standards.URI) uri)

Description

Put one or several URIs in the queue. Any URIs that were already present in the queue are silently disregarded.

  CLASS Web.Crawler.ComplexQueue


Inherit Queue

inherit Queue : Queue


syntax

Stats stats
Policy policyvoid Web.Crawler.ComplexQueue(Stats stats, Policy policy)

  CLASS Web.Crawler.Crawler


Method create

void Web.Crawler.Crawler(Queue _queue, function _page_cb, function _error_cb, function _done_cb, function _prepare_cb, string|array(string)|Standards.URI|array(Standards.URI) start_uri, mixed ... _args)

Parameter _page_cb

function called when a page is retreived. Arguments are: Standards.URI uri, mixed data, mapping headers, mixed ... args. should return an array containing additional links found within data that will be analyzed for insertion into the crawler queue (assuming they are allowed by the allow/deny rulesets.

Parameter _error_cb

function called when an error is received from a server. Arguments are: Standards.URI real_uri, int status_code, mapping headers, mixed ... args. Returns void.

Parameter _done_cb

function called when crawl is complete. Accepts mixed ... args and returns void.

Parameter _prepare_cb

argument called before a uri is retrieved. may be used to alter the request. Argument is Standards.URI uri. Returns array with element 0 of Standards.URI uri, element 1 is a header mapping for the outgoing request.

Parameter start_uri

location to start the crawl from.

Parameter _args

optional arguments sent as the last argument to the callback functions.

  Module Web.RSS

Description

Represents a RSS (RDF Site Summary) file.


Method parse_xml

Index Web.RSS.parse_xml(string|Parser.XML.Tree.Node n, void|string base)

Description

Returns an Index object, populated with the rss information given in the rss file n .

  CLASS Web.RSS.Thing

Description

The base class for the RSS resources.


Method create

void Web.RSS.Thing(string about, mapping attributes)
void Web.RSS.Thing(.RDF.Resource me)

Description

Creates an RSS resource.


Method get_id

.RDF.Resource get_id()

Description

Returns the RDF.Resource that identifies this RSS resource.

  CLASS Web.RSS.Image

Description

Represents an RSS image resource.


Inherit Thing

inherit Thing : Thing


string title
string url
string link

  CLASS Web.RSS.Item

Description

Represents an RSS item resource.


Inherit Thing

inherit Thing : Thing


string title
string link
string description

  CLASS Web.RSS.Textinput

Description

Represents an RSS textinput resource.


Inherit Thing

inherit Thing : Thing


string title
string description
string name
string link

  CLASS Web.RSS.Channel

Description

Represents an RSS channel.


Inherit Thing

inherit Thing : Thing


string title
string link
string description
string|Standards.URI image
string|Standards.URI textinput
array(Item) items


Method add_item

void add_item(Item i)

Description

Adds the Item i to the Channel .


Method remove_item

void remove_item(Item i)

Description

Removes the Item i from the Channel .

  CLASS Web.RSS.Index

Description

Represents the top level of an RSS index.


Variable rdf

.RDF rdf

Description

The underlying RDF representation of the RSS index.


Variable channels

array(Channel) channels

Description

The RSS channels.


Variable images

array(Image) images

Description

The RSS images.


Variable items

array(Item) items

Description

The RSS items.


Variable textinputs

array(Textinput) textinputs

Description

The RSS textinputs.


Method create

void Web.RSS.Index(.RDF|void _rdf)

  Module GLUE

Description

GL Universal Environment



Method get_drivers

array(string) GLUE.get_drivers()

Description

Returns the name of the available drivers.

See also

init


Method add_reinit_callback

void GLUE.add_reinit_callback(function(void:void) f)

Description

Add a callback that will be called every time the resolution is about to change.

See also

remove_reinit_callback


Method remove_reinit_callback

void GLUE.remove_reinit_callback(function(void:void) f)

Description

Removes a reinitialization callback.

See also

add_reinit_callback


Method get_screen_mode

int(0..1) GLUE.get_screen_mode()

Description

Returns 1 if in fullscreen mode, otherwise 0.

See also

toggle_fullscreen


Method toggle_fullscreen

void GLUE.toggle_fullscreen(void|int(0..1) _fullscreen)

Description

Toggles between fullscreen and window mode. If a screen mode is provided, that mode will be assumed.

See also

get_screen_mode


Method get_gl_flags

int GLUE.get_gl_flags()

Description

Returns the GL flags currently used.

See also

set_gl_flags


Method set_gl_flags

void GLUE.set_gl_flags(int _gl_flags)

Description

Sets the GL flags.

See also

get_gl_flags


Method get_depth

int GLUE.get_depth()

Description

Returns the current color depth.

See also

set_depth


Method set_depth

void GLUE.set_depth(int _depth)

Description

Sets the color depth.

See also

get_depth


Method xsize
Method ysize

int GLUE.xsize()
int GLUE.ysize()

Description

Returns the screen width/height.

See also

set_resolution


Method set_resolution

void GLUE.set_resolution(int w, int h)

Description

Sets the resolution to w xh pixels.

See also

xsize , ysize


Method get_aspect

float GLUE.get_aspect()

Description

Returns the screen aspect.

See also

set_aspect


Method set_aspect

void GLUE.set_aspect(float asp)
void GLUE.set_aspect(int w, int h)

Description

Set the aspect of the draw area. Does nothing if the provided aspect is equal to the one currently used.

See also

get_aspect


Method set_screen_rotation

void GLUE.set_screen_rotation(float deg)

Description

Rotates the drawing area deg degrees. Useful e.g. when drawing for tilted monitors.


Method mirror_screen

void GLUE.mirror_screen(string how)

Description

Mirrors the screen in x and/or y axis. Useful e.g. when drawing for backlight projection.

Parameter how

A string that contains the mirror axis, e.g. "x" or "xy".


Method init

void GLUE.init(void|mapping(string:mixed) options)

Description

Initializes GLUE and loads a driver from a list of drivers. If a driver fails to load or initialize, the next driver is tried.

Throws

driver_names not listed in the result from get_drivers will cause an error to be thrown.

Parameter options
"driver_names" : string|array(string)

The name of a driver or a list of drivers to try, in given order. If no driver name is given, the list given by get_drivers is used.

"event_callback" : function(.Events.Event:void)

This callback is called with a Events.Event object whenever an event is trapped by the driver.

"resize_callback" : function(float:void)

This callback is called with the aspect whenever the drawing area is resized, either by an event or explicitly by the program.

"fullscreen" : int(0..1)

Set fullscreen/window mode. 1 is fullscreen, 0 is window. Defaults to fullscreen.

"resolution" : array(int)

Sets the resolution of the drawing area. Defaults to ({ 800, 600 }).

"aspect" : float

Sets the aspect of the drawing area. Defaults to 1.333333 (4:3).

"depth" : int

Sets the color depth of the drawing area. Defaults to 32.

"title" : string

Sets the window title to this string.

"icon_title" : string

Sets the icon title to this string.

"fast_mipmap" : int(0..1)

Use GL_NEAREST_MIMAP_NEAREST instead of GL_LINEAR_MIPMAP_LINEAR, which also is the default.

"rotation" : float

The rotation in z-axis of the drawing field.

"mirror" : string

Mirroring in x and/or y axis.


See also

get_drivers


Method swap_buffers

void GLUE.swap_buffers()

Description

Swap the drawing buffer and the viewing buffer.


Method show_cursor

void GLUE.show_cursor()

Description

Show the mouse cursor.


Method hide_cursor

void GLUE.hide_cursor()

Description

Hide the mouse cursor.


Method allocate_light

int GLUE.allocate_light()

Description

Allocate a hardwareaccelerated lightsource from OpenGL.

Returns

an id which may be added to the GL.GL_LIGHT0 constant.

See also

free_light


Method free_light

void GLUE.free_light(int l)

Description

Call this function to free a lightsource that has been allocated with allocate_light .

Parameter l

Id which has been allocated using allocate_light .

See also

allocate_light


Method pushpop_depth

int(0..) GLUE.pushpop_depth()

Description

Returns the PushPop depth, i.e. the number of pushes awaiting corresponding pops.


Method PushPop

void GLUE.PushPop(function f)

Description

Performs function f between GL.glPushMatrix and GL.glPopMatrix calls.

Example

PushPop() { GL.glTranslate( 0.01, -0.9, 0.0 ); write_text( "Press esc to quit" ); };


Method get_all_lists

array(List) GLUE.get_all_lists()

Description

Returns all defined lists. Only available on Windows.


Method only_dynlists

int(0..1) GLUE.only_dynlists()

Description

Returns 1 if all defined lists are DynList lists.


Method make_texture

BaseTexture GLUE.make_texture(mapping|Image.Image image, string|void name)

Description

Create a texture. Mainly here for symetry with make_rect_texture

See also

Texture , make_rect_texture


Method make_rect_texture

BaseTexture GLUE.make_rect_texture(mapping|Image.Image image, string|void name)

Description

Create a texture with the specified image as contents. Will try to use the TEXTURE_RECTANGLE_NV extension if available, otherwise normal textures will be used (like make_texture ).

See also

make_texture


Method get_all_textures

array(BaseTexture) GLUE.get_all_textures()

Description

Returns a list of all current textures.


Method get_texture_mem_usage

int GLUE.get_texture_mem_usage()

Description

Returns the number of bytes used by the textures.


Method draw_line

void GLUE.draw_line(float x0, float y0, float x1, float y1, Image.Color.Color c, void|float a)
void GLUE.draw_line(float x0, float y0, float z0, float x1, float y1, float z1, Image.Color.Color c, void|float a)


Method draw_obox

void GLUE.draw_obox(float x0, float y0, float x1, float y1, array(Image.Color.Color)|Image.Color.Color c, void|array(float)|float a)

Description

Draw a box outline around the specified coordinates. c is either a single color, in which case it will be used for all corners, or an array of four colors, which will be used for each corner.

a is similar to c , but is the alpha values for each coordinate.


Method draw_box

void GLUE.draw_box(float x0, float y0, float x1, float y1, array(Image.Color.Color)|Image.Color.Color c, void|array(float)|float a)

Description

Draw a box at the specified coordinates. c is either a single color, in which case it will be used for all corners, or an array of four colors, which will be used for each corner.

a is similar to c , but is the alpha values for each coordinate.


Method draw_polygon

void GLUE.draw_polygon(array(float) coords, Image.Color.Color c, float a)


Method debug_stuff

mapping(string:mixed) GLUE.debug_stuff()

Description

Returns some internal states for debug purposes. The actual content may change.

  CLASS GLUE.List

Description

A display list abstraction. Automatically allocates a display list id upon creation and correctly deallocate it upon destruction.

See also

DynList


Method create

void GLUE.List(void|function f)

Description

When creating a new list, the list code can be compiled upon creation by supplying a function f that performs the GL operations.

See also

call

Example

List list = List() { // GL code };


Method destroy

void destroy()

Description

Deletes this list and frees the list id from the id pool.


Method get_id

int get_id()

Description

Returns this lists' id.


Method `>

int(0..1) `>(mixed x)

Description

List objects can be sorted according to list id.

See also

get_id


Method begin

void begin(int(0..1)|void run)

Description

Start defining the list. If run is provided, the list will be executed as it is compiled (GL.GL_COMPILE_AND_EXECUTE ).

See also

end , compile


Method end

void end()

Description

Finish the list definition.

See also

begin , compile


Method compile

void compile(function f)

Description

Compile a list be executing the list code f . Exceptions in f will be thrown after GL.glEndList has been called.

See also

begin


Method call

void call()

Description

Execute the commands in the list.

  CLASS GLUE.DynList

Description

A displaylist that is generated on demand.

Note

On Windows lists needs to be regenerated when the video driver mode is changed. Thus the DynList is to prefer over List , since regeneration is done automatically upon video mode change.


Inherit List

inherit List : List


Method modeswitch

void modeswitch()

Description

Called by videodriver when a video mode change occurs.


Method set_generator

void set_generator(function _generator)

Description

Sets a function which can generate a displaylist. Hint: Use implicit lambda...


Method init

void init()

Description

Generates the displaylist, ie calls the function set in set_generator . Called only when the display list needs to be generated.


Method call

void call()

Description

Call the displaylist, ie draw it.


Method create

void GLUE.DynList(function|void f)

Description

Create a new DynList object and optionally set a function that can generate the displaylist

Parameter f

Function which contains the GL commands that generates the displaylist.

  CLASS GLUE.BaseTexture

Description

The texture base class. Using e.g. Texture might be more convenient.


int t_width
int t_height

Description

Texture dimensions


int i_width
int i_height

Description

Image dimensions


float width_u
float height_u

Description

Utilization in percent.


Variable texture_type

int texture_type

Description

The texture type, e.g. GL.GL_TEXTURE_2D .


Variable debug

string debug

Description

A string to identify the texture.


Method construct

void construct(int width, int height, int _alpha, mapping|void imgs, int(0..1)|void mipmap, int|void _mode, string|void debug_text)

Description

Construct a new texture. Processes _alpha , _mode and debug_text and calls resize .

Parameter _alpha

The alpha mode the texture is operating in.

0

RGB

1

RGBA

2

ALPHA

3

LUM

4

LUM+ALPHA


Parameter _mode

The mode the texture is operating in. Autoselected wrt _alpha if 0.

Parameter debug_text

A string that can be used to identify this texture.


Method create

void GLUE.BaseTexture(mixed ... args)

Description

Calls construct with args .


Method destroy

void destroy()

Description

Properly deallocates the texture.


Method resize

void resize(int width, int height, mapping|void imgs, int(0..1)|void mipmap, int(0..1)|void nocreate)

Description

Resizes/creates a texture to meet the dimensions width and height . If nocreate isn't given, create_texture is called to actually perform the resize/creation.

See also

construct


Method create_texture

void create_texture(mapping|void imgs, int(0..1)|void mipmap, int|void width, int|void height)

Description

Actually creates the texture.

Parameter imgs

If zero, a black texture with the dimensions width * height will be generated. Otherwise imgs should be a mapping as follows.

"image" : Image.Image

The actual image to be used as texture. It will be cropped/padded to meet the dimensions given in width and height .

"alpha" : Image.Image

Optional image to be used as alpha channel, depending on the alpha value given to create /construct .


Parameter mipmap

If 1, the texture will be mipmapped.

Parameter width
Parameter height

The dimensions of the texture. If omitted the dimensions of the images in imgs will be used.

See also

resize


Method make_mipmap

void make_mipmap(mapping imgs, int|void imode, int|void dx, int|void dy)

Description

Renders a mipmap of the image/partial image imgs .

Parameter imgs

Image data mapping to feed GL.glTexImage2D or GL.glTexSubImage2D .

Parameter imode

Internal format to feed GL.glTexImage2D , or UNDEFINED for partial images.

Parameter dx
Parameter dy

Xoffs, yoffs to feed GL.glTexSubImage2D for partial images.

See also

create_texture


Method clear

void clear()

Description

Clears the texture.


Method paste

void paste(Image.Image i, Image.Image a, int x, int y)

Description

Paste the image i with alpha channel a at coordinates x and y in the current texture.


Method _sizeof

int _sizeof()

Description

Returns the size of memory allocated by the texture.


Method get_id

int get_id()

Description

Returns the id of this texture.


Method `>

int(0..1) `>(mixed x)

Description

Textures can be sorted according to texture id.


Method draw

void draw(float x, float y, float z, float w, float h)

Description

Draw the texture at x ,y ,z with dimensions w *h .


Method draw_region

void draw_region(float x, float y, float z, float w, float h, float s0, float q0, float ss, float qs)

Description

Draw texture region s0 ,q0 - ss ,qs at x ,y ,z with dimensions w *h .


Method use

void use()

Description

Use the generated texture (GL.glBindTexture ).


Method coords

void coords(float x, float y)

Description

Sets the texture coordinates to x *width,y *height.


Method set_image_data

void set_image_data(Image.Image|mapping(string:mixed) data, int(0..1)|void no_resize)

Description

Set the contents (and size) of the texture from the supplied data. The data is identical to what would normally be sent as the last argument to glTex[Sub]Image2D() or an Image.Image object.

If no_resize is specified, it is assumed that the data will fit in the texture, otherwise the parts that extend beyond it will be discarded.

Parameter data

Besides being an Image.Image object, data can be either of two types of mappins. First it can be a mapping with Image data.

"rgb" : Image.Image

Texture image data.

"alpha" : Image.Image

Optional alpha channel.

"luminance" : Image.Image

Optional luminance channel.


Second it can be a mapping pointing out a shared memory segment.

"mem" : System.Memory

The shared memory segment.

"mem_w" : int

The width and height of the memory segment.

"mem_h" : int
"mem_format" : int

The format of the memory segment, e.g. GL.GL_RGB .

"mem_type" : int

The low level format of the memory segment, e.g. GL.GL_UNSIGNED_BYTE .


  CLASS GLUE.RectangleTexture

Description

Uses the NVidia RECT texture extension for non-power-of-two textures.


Inherit BaseTexture

inherit BaseTexture : BaseTexture

  CLASS GLUE.BaseDWIM

Description

A mixin class with a dwim create function.


Method create

void GLUE.BaseDWIM(mixed ... args)

Description

This create function has the following heuristic:

If a mapping is encountered, the following information will be attempted to be extracted.

"image" : Image.Image

The texture image.

"xsize" : int

The image dimensions. If not provided, the dimensions of the "image" member will be used.

"ysize" : int
"height" : int
"width" : int
"alpha" : int

The alpha mode.

"mipmap" : int(0..1)

Should the texture be mipmapped or not.

"mode" : int

The texture mode.

"debug" : string

The debug name associated with this texture.


If an object is encountered in the argument list, the first object will be used as texture image and the second as texture alpha.

If a string is encountered in the argument list, it will be used as debug name associated with this texture.

Once all mappings, strings and objects are removed from the argument list, the remaining integers will be interpreted as width, height, alpha, mipmap and mode, unless there is only one argument. In that case it will be interpreted as the alpha mode.

  CLASS GLUE.Texture

Description

Convenience version of the Texture class.


Inherit BaseTexture

inherit BaseTexture : BaseTexture

Description

Texture base


Inherit BaseDWIM

inherit BaseDWIM : BaseDWIM

Description

Convenience methods

  CLASS GLUE.RectangleDWIMTexture

Description

Convenience version of the RectangleTexture class.


Inherit RectangleTexture

inherit RectangleTexture : RectangleTexture

Description

Texture base


Inherit BaseDWIM

inherit BaseDWIM : BaseDWIM

Description

Convenience methods

  CLASS GLUE.Region

Description

A rectangle. Used by the text routines to avoid drawing outside the current region.


syntax

float x
float y
float w
float hvoid GLUE.Region(float x, float y, float w, float h)


Constant is_region

constant is_region

Description

All region objects have this constant.


Method move

void move(float xp, float yp)

Description

Move the region xp units right and yp units down.


Method resize

void resize(float xs, float ys)

Description

Make the region xs units wider and ys units higher.


Method outside

int(0..1) outside(Region R)

Description

Returns 1 if the region R is fully outside this region.


Method inside

int(0..1) inside(Region R)

Description

Returns 1 if the region R is fully inside this region.


Method `&

Region `&(mixed R)

Description

Creates a new region with the intersection of this region and R .

  CLASS GLUE.Font

Description

A font.


Method create

void GLUE.Font(Image.Fonts.Font f, float|void _scale_width, float|void _scale_spacing)


Method get_character

array(int|BaseTexture|Region) get_character(int c)

Description

Returns the advance (in pixels), the texture and the texture coordinates for the specified character, or 0 if it's nonprintable.

Note

If the font->write call fails, the backtrace will be written to stderr.


Method text_extents

array(float) text_extents(string text, float h)

Description

Get the width and height of the area that the string text in size h would cover.


Method write_now

array(float) write_now(string text, float h, void|float|Region roi, string|void align)

Description

Write the text in size [h], possibly restricted by region roi . Return the width and height of the resulting text area. If roi is a float, Region(0.0, 0.0, roi, 10000.0) will be used.


Method write

array(List|float) write(string text, float h, void|float|Region roi, string|void align)

Description

Create a display list that writes text.

Parameter text

The text to write.

Parameter h

The font height

Parameter roi

The region, if supplied, to restrict writing to.

Parameter align

The text justification; "left" (default), "center" or "right".

  CLASS GLUE.Font.Character

Description

A character to draw.


Inherit Region

inherit Region : Region


Variable pos

Region pos

Description

Character position in texture txt .


Variable txt

BaseTexture txt

Description

Texture holding the character.


Variable slice

Region slice

Description

Slice of character to be shown.


Method set_data

void set_data(Region _pos, BaseTexture _txt, void|Region _slice)

Description

Set character to be region _slice of region _pos of texture _txt .


Method draw

void draw()

Description

Draw the character using the texture txt with the texture-coordinates indicated in pos , possible cropped with slice .

  CLASS GLUE.SquareMesh

Description

A mesh of squares.


Method recalculate

void recalculate()

Description

Recalculate the mesh.


Method surface_normal

Math.Matrix surface_normal(int x, int y)

Description

Return the normal for the surface at coordinates x,y. Used internally.


Method set_texture

void set_texture(BaseTexture tex)

Description

Set a texture to be mapped on the mesh.


Method draw

void draw()

Description

Draw the mesh.


Method set_lighting

void set_lighting(int(0..1) do_lighting)

Description

Indicate whether or not lighting is used. If it is, the normals of each vertex will be calculated as well as the coordinates.


Method set_size

void set_size(int x, int y)

Description

Set the size of the mesh


Method create

void GLUE.SquareMesh(function(float:Math.Matrix) calculator)

Description

The calculator will be called for each corner and should return a 1x3 matrix describing the coordinates for the given spot om the surface.

  Module GLUE.Events

Description

GLUE Event abstraction.


Constant _SHFT

constant GLUE.Events._SHFT

Description

Integer constant representing shift.


Constant _CTRL

constant GLUE.Events._CTRL

Description

Integer constant representing control.


Constant _ALT

constant GLUE.Events._ALT

Description

Integer constant representing alternate.


Constant KNOWN_MODIFIERS

constant GLUE.Events.KNOWN_MODIFIERS

Description

Integer constant with the union of all known modifiers, i.e. _SHFT | _CTRL | _ALT.


Method CTRL

Event GLUE.Events.CTRL(int|Event X)
array(Event) GLUE.Events.CTRL(array(int|Event) X)

Description

Adds the _CTRL modifier to an Event , key or array of Events and/or keys.


Method SHFT

Event GLUE.Events.SHFT(int|Event X)
array(Event) GLUE.Events.SHFT(array(int|Event) X)

Description

Adds the _SHFT modifier to an Event , key or array of Events and/or keys.


Method ALT

Event GLUE.Events.ALT(int|Event X)
array(Event) GLUE.Events.ALT(array(int|Event) X)

Description

Adds the _ALT modifier to an Event , key or array of Events and/or keys.


constant GLUE.Events.BACKSPACE
constant GLUE.Events.DELETE
constant GLUE.Events.TAB
constant GLUE.Events.F1
constant GLUE.Events.F2
constant GLUE.Events.F3
constant GLUE.Events.F4
constant GLUE.Events.F5
constant GLUE.Events.F6
constant GLUE.Events.F7
constant GLUE.Events.F8
constant GLUE.Events.F9
constant GLUE.Events.F10
constant GLUE.Events.F11
constant GLUE.Events.F12
constant GLUE.Events.ESCAPE
constant GLUE.Events.UP
constant GLUE.Events.DOWN
constant GLUE.Events.LEFT
constant GLUE.Events.RIGHT
constant GLUE.Events.PGUP
constant GLUE.Events.PGDWN
constant GLUE.Events.ENTER
constant GLUE.Events.SPACE
constant GLUE.Events.HOME
constant GLUE.Events.END
constant GLUE.Events.PAUSE
constant GLUE.Events.INSERT
constant GLUE.Events.SCROLL_LOCK
constant GLUE.Events.SYS_REQ
constant GLUE.Events.PRINT_SCRN
constant GLUE.Events.CAPSLOCK
constant GLUE.Events.MENU
constant GLUE.Events.NUMLOCK
constant GLUE.Events.A
constant GLUE.Events.B
constant GLUE.Events.C
constant GLUE.Events.D
constant GLUE.Events.E
constant GLUE.Events.F
constant GLUE.Events.G
constant GLUE.Events.H
constant GLUE.Events.I
constant GLUE.Events.J
constant GLUE.Events.K
constant GLUE.Events.L
constant GLUE.Events.M
constant GLUE.Events.N
constant GLUE.Events.O
constant GLUE.Events.P
constant GLUE.Events.Q
constant GLUE.Events.R
constant GLUE.Events.S
constant GLUE.Events.T
constant GLUE.Events.U
constant GLUE.Events.V
constant GLUE.Events.W
constant GLUE.Events.X
constant GLUE.Events.Y
constant GLUE.Events.Z

Description

Numeric constant representing a key.


constant GLUE.Events.BUTTON_1
constant GLUE.Events.BUTTON_2
constant GLUE.Events.BUTTON_3
constant GLUE.Events.BUTTON_4
constant GLUE.Events.BUTTON_5

Description

Numeric constant representing a mouse button.


constant GLUE.Events.MOUSE_UP
constant GLUE.Events.MOUSE_DOWN
constant GLUE.Events.MOUSE_LEFT
constant GLUE.Events.MOUSE_RIGHT
constant GLUE.Events.MOUSE_ABS

Description

Numeric constant representing a mouse movement.


constant GLUE.Events.LSHIFT
constant GLUE.Events.RSHIFT
constant GLUE.Events.LCTRL
constant GLUE.Events.RCTRL
constant GLUE.Events.LALT
constant GLUE.Events.RALT

Description

Numeric constant representing a modifier key.


Constant MODIFIERS

constant GLUE.Events.MODIFIERS

Description

Mapping that maps a modifier key to any of the symbolic modifiers _SHFT , _CTRL and _ALT .


Constant EXIT

constant GLUE.Events.EXIT

Description

Numeric constant representing an exit event.


Constant key_names

constant GLUE.Events.key_names

Description

Mapping that maps key identifiers with a printable name, e.g. LSHIFT to "Left shift".


Method is_modifier

int(0..1) GLUE.Events.is_modifier(int k)

Description

Returns 1 if the key code k is a modifier key, e.g. LSHIFT or RSHIFT .

  CLASS GLUE.Events.Event

Description

Contains an event.


Method dup

this_program dup()

Description

Returns a copy of this Event object.


Variable pressure

float pressure

Description

The pressure of the key stroke. A value between 0.0 and 1.0. Unknown values are represented as 0.


Variable press

int(0..1) press

Description

Press event or release event.


Method create

void GLUE.Events.Event(int|void _key, int(0..1)|void _press, string|void _data, int|void _modifiers, float|void pressure)

  Module Colors


Method rgb_to_hsv

array(int(0..255)) Colors.rgb_to_hsv(array(int(0..255)) rgb)
array(int(0..255)) Colors.rgb_to_hsv(int(0..255) r, int(0..255) g, int(0..255) b)

Description

This function returns the HSV value of the color described by the provided RGB value. It is essentially calling Image.Color.rgb(r,g,b)->hsv().

See also

Colors.hsv_to_rgb() Image.Color.Color.hsv()


Method hsv_to_rgb

array(int(0..255)) Colors.hsv_to_rgb(array(int(0..255)) hsv)
array(int(0..255)) Colors.hsv_to_rgb(int(0..255) h, int(0..255) s, int(0..255) v)

Description

This function returns the RGB value of the color described by the provided HSV value. It is essentially calling Image.Color.hsv(h,s,v)->rgb().

See also

Colors.rgb_to_hsv() Image.Color.hsv()


Method rgb_to_cmyk

array(int(0..100)) Colors.rgb_to_cmyk(array(int(0..255)) rgb)
array(int(0..100)) Colors.rgb_to_cmyk(int(0..255) r, int(0..255) g, int(0..255) b)

Description

This function returns the CMYK value of the color described by the provided RGB value. It is essentially calling Image.Color.rgb(r,g,b)->cmyk().

See also

Colors.cmyk_to_rgb() Image.Color.Color.cmyk()


Method cmyk_to_rgb

array(int(0..255)) Colors.cmyk_to_rgb(array(int(0..100)) cmyk)
array(int(0..255)) Colors.cmyk_to_rgb(int(0..100) c, int(0..100) m, int(0..100) y, int(0..100) k)

Description

This function return the RGB value of the color describe by the provided CMYK value. It is essentially calling Image.Color.cmyk(c,m,y,k)->rgb()

See also

Colors.rgb_to_cmyk() Image.Color.cmyk()


Method parse_color

array(int(0..255)) Colors.parse_color(string name, void|array(int) def)

Description

This function returns the RGB values that corresponds to the color that is provided by name to the function. It is essentially calling Image.Color.guess() , but returns the default value (or black if none is provided) if it failes.


Method color_name

string Colors.color_name(array(int(0..255)) rgb)

Description

Tries to find a name to color described by the provided RGB values. Partially an inverse function to Colors.parse_color() , although it can not find all the names that Colors.parse_color() can find RGB values for. Returns the colors rgb hex value prepended with "#" upon failure.

  Module Float


constant Float.DIGITS_10
constant Float.MIN_10_EXP
constant Float.MAX_10_EXP
constant Float.MIN
constant Float.MAX
constant Float.EPSILON

Description

These constants define the limits for floats on the current architecture:

DIGITS_10

The number of decimal digits that can be represented. Any number with this many decimal digits can be stored in a float and converted back to decimal form without change. DIGITS_10 is not less than 6.

MIN_10_EXP
MAX_10_EXP

Limits of the exponent in decimal base. 10 raised to any number within this range can be represented in normalized form. MIN_10_EXP is not greater than -37. MAX_10_EXP is not less than 37.

MIN

The smallest normalized float greater than zero. It's not greater than 1e-37.

MAX

The largest finite float. It's not less than 1e37.

EPSILON

The difference between 1 and the smallest value greater than 1 that can be represented. It's not greater than 1e-5.

Note

The size of the float type can be controlled when Pike is compiled with the configure flags --with-double-precision and --with-long-double-precision. The default is to use the longest available float type that fits inside a pointer.


constant Float.FLOAT_PRECISION
constant Float.DOUBLE_PRECISION
constant Float.LONG_DOUBLE_PRECISION

Description

Tells which C compiler float type that is used for Pike floats. Only one of these constants will exist (with the value 1) at runtime.

FLOAT_PRECISION

The float type of the C compiler is used.

DOUBLE_PRECISION

The double type of the C compiler is used.

LONG_DOUBLE_PRECISION

The long double type of the C compiler is used.

Note

The float type can be controlled when Pike is compiled with the configure flags --with-double-precision and --with-long-double-precision. The default is to use the longest available float type that fits inside a pointer.

  Module Getopt

Description

Getopt is a group of functions which can be used to find command line options.

Command line options come in two flavors: long and short. The short ones consists of a dash followed by a character (-t), the long ones consist of two dashes followed by a string of text (--test). The short options can also be combined, which means that you can write -tda instead of -t -d -a.

Options can also require arguments, in which case they cannot be combined. To write an option with an argument you write -t argument or -targument or --test=argument.


Method find_option

string|int(0..1) Getopt.find_option(array(string) argv, array(string)|string shortform, array(string)|string|void longform, array(string)|string|void envvars, string|int(0..1)|void def, int|void throw_errors)

Description

This is a generic function to parse command line options of the type -f, --foo or --foo=bar.

Parameter argv

The first argument should be the array of strings that was sent as the second argument to your main() function.

Parameter shortform

The second is a string with the short form of your option. The short form must be only one character long. It can also be an array of strings, in which case any of the options in the array will be accepted.

Parameter longform

This is an alternative and maybe more readable way to give the same option. If you give "foo" as longform your program will accept --foo as argument. This argument can also be an array of strings, in which case any of the options in the array will be accepted.

Parameter envvars

This argument specifies an environment variable that can be used to specify the same option, to make it easier to customize program usage. It can also be an array of strings, in which case any of the mentioned variables in the array may be used.

Parameter def

This argument has two functions: It specifies if the option takes an argument or not, and it informs find_option() what to return if the option is not present. If def is given and the option does not have an argument find_option() will fail. def can be specified as UNDEFINED or left out if the option does not take an argument.

Parameter throw_errors

If throw_errors has been specified find_option() will throw errors on failure. If it has been left out, or is 0 (zero), it will instead print an error message on Stdio.stderr and exit the program with result code 1 on failure.

Returns

Returns the value the option has been set to if any.

If the option is present, but has not been set to anything 1 will be returned.

Otherwise if any of the environment variables specified in envvars has been set, that value will be returned.

If all else fails, def will be returned.

Throws

If an option that requires an argument lacks an argument and throw_errors is set an error will be thrown.

Note

find_option() modifies argv . Parsed options will be removed from argv . Elements of argv that have been removed entirely will be replaced with zeroes.

This function reads options even if they are written after the first non-option on the line.

Index 0 (zero) of argv is not scanned for options, since it is reserved for the program name.

Only the first ocurrance of an option will be parsed. To parse multiple ocurrances, call find_option() multiple times.

See also

Getopt.get_args()


Constant HAS_ARG

constant Getopt.HAS_ARG

Description

Used with find_all_options() to indicate that an option requires an argument.

See also

find_all_options()


Constant NO_ARG

constant Getopt.NO_ARG

Description

Used with find_all_options() to indicate that an option does not take an argument.

See also

find_all_options()


Constant MAY_HAVE_ARG

constant Getopt.MAY_HAVE_ARG

Description

Used with find_all_options() to indicate that an option takes an optional argument.

See also

find_all_options()


Method find_all_options

array(array) Getopt.find_all_options(array(string) argv, array(array(array(string)|string|int)) options, void|int(-1..1) posix_me_harder, void|int throw_errors)

Description

This function does the job of several calls to find_option() . The main advantage of this is that it allows it to handle the POSIX_ME_HARDER environment variable better. When the either the argument posix_me_harder or the environment variable POSIX_ME_HARDER is true, no arguments will be parsed after the first non-option on the command line.

Parameter argv

The should be the array of strings that was sent as the second argument to your main() function.

Parameter options

Each element in the array options should be an array on the following form:

Array
string name

Name is a tag used to identify the option in the output.

int type

Type is one of Getopt.HAS_ARG , Getopt.NO_ARG and Getopt.MAY_HAVE_ARG and it affects how the error handling and parsing works. You should use HAS_ARG for options that require a path, a number or similar. NO_ARG should be used for options that do not need an argument, such as --version. MAY_HAVE_ARG should be used for options that may or may not need an argument.

string|array(string) aliases

This is a string or an array of string of options that will be looked for. Short and long options can be mixed, and short options can be combined into one string. Note that you must include the dashes so that find_all_options() can distinguish between long and short options. Example: ({"-tT","--test"}) This would make find_all_options look for -t, -T and --test.

void|string|array(string) env_var

This is a string or an array of strings containing names of environment variables that can be used instead of the command line option.

void|mixed default

This is the default value a MAY_HAVE_ARG option will have in the output if it was set but not assigned any value.


Only the first three elements need to be included.

Parameter posix_me_harder

Don't scan for arguments after the first non-option.

Parameter throw_errors

If throw_errors has been specified find_all_options() will throw errors on failure. If it has been left out, or is 0 (zero), it will instead print an error message on Stdio.stderr and exit the program with result code 1 on failure.

Returns

The good news is that the output from this function is a lot simpler. find_all_options() returns an array where each element is an array on this form:

Array
string name

Option identifier name from the input.

mixed value

Value given. If no value was specified, and no default has been specified, the value will be 1.


Note

find_all_options() modifies argv .

Index 0 (zero) of argv is not scanned for options, since it is reserved for the program name.

See also

Getopt.get_args() , Getopt.find_option()


Method get_args

array(string) Getopt.get_args(array(string) argv, void|int(-1..1) posix_me_harder, void|int throw_errors)

Description

This function returns the remaining command line arguments after you have run find_option() or find_all_options() to find all the options in the argument list. If there are any options left not handled by find_option() or find_all_options() this function will fail.

If throw_errors has been specified get_args() will throw errors on failure. If it has been left out, or is 0 (zero), it will instead print an error message on Stdio.stderr and exit the program with result code 1 on failure.

Returns

On success a new argv array without the parsed options is returned.

See also

Getopt.find_option() , Getopt.find_all_options()

  Module Int


Method parity

int(0..1) Int.parity(int(0..) value)

Description

Returns the parity of the integer value . If the parity is odd 1 is returned. If it is even 0 is returned.


constant Int.NATIVE_MIN
constant Int.NATIVE_MAX

Description

The limits for using the native representation of integers on the current architecture. Any integer that is outside this range uses a more complex and slower representation. Also, some builtin functions that don't expect very large integers might start to complain about invalid argument type when given values outside this range (they typically say something like "Expected integer, got object").

NATIVE_MIN is not greater than -2147483648 (-0x80000000).

NATIVE_MAX is not less than 2147483647 (0x7fffffff).

Note

The size of the native integers can be controlled when Pike is compiled with the configure flags --with-int-int, --with-long-int, and --with-long-long-int. The default is to use the longest available integer type that fits inside a pointer, which typically means that it's 64 bit on "true" 64 bit architectures.

Note

If Pike is compiled with the configure flag --without-bignum (which is discouraged), then all arithmetic operations will instead silently wrap around at these limits.


Method swap_word

int(0..65535) Int.swap_word(int(0..65535) i)

Description

Swaps the upper and lower byte in a word.


Method swap_long

int(0..4294967295) Int.swap_long(int(0..4294967295) i)

Description

Swaps the upper and lower word in a longword, and the upper and lower bytes in the words. Simply put, the bytes are reversed.

  Module Local

Description

Local gives a local module namespace used for locally installed pike modules. Modules are searched for in the directory pike_modules which can be located in the user's home directory or profile directory, or in any of the system directories /opt/share, /usr/local/share, /opt or /usr/local/. The user's home directory is determined by examining the environment variable HOME, and if that fails the environment variable USERPROFILE. If the environment variable PIKE_LOCAL_PATH is set, the paths specified there will be searched first.

See also

Local.add_path() , Local.remove_path()


Method add_path

int(0..1) Local.add_path(string path)

Description

This function prepends path to the Local module searchpath.

Parameter path

The path to the directory to be added.

Returns

Returns 1 on success, otherwise 0.


Method remove_path

void Local.remove_path(string path)

Description

This function removes path from the Local module searchpath. If path is not in the search path, this is a noop.

Parameter path

The path to be removed.

  Namespace 0.6::

Description

Pike 0.6 compatibility.

The symbols in this namespace will appear in programs that use #pike 0.6 or lower.

See also

7.0::


Inherit

inherit 7.0:: :


Method aggregate

array(mixed) aggregate(mixed ... args)

Description

More lax types than in later versions.

  Module Array


Inherit Array

inherit Array : Array


Method map

array Array.map(array x, int|string|function fun, mixed ... args)

Description

Much simplified type compared to later versions of map.