17. The rest |
Namespace predef:: |
float sin(float f)
Returns the sine value for f . f should be specified in radians.
asin() , cos() , tan()
float asin(float f)
Return the arcus sine value for f . The result will be in radians.
sin() , acos()
float cos(float f)
Return the cosine value for f . f should be specified in radians.
acos() , sin() , tan()
float acos(float f)
Return the arcus cosine value for f . The result will be in radians.
cos() , asin()
float tan(float f)
Returns the tangent value for f . f should be specified in radians.
atan() , sin() , cos()
float atan(float f)
Returns the arcus tangent value for f . The result will be in radians.
tan() , asin() , acos() , atan2()
float atan2(float f1, float f2)
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.
tan() , asin() , acos() , atan()
float sinh(float f)
Returns the hyperbolic sine value for f .
asinh() , cosh() , tanh()
float asinh(float f)
Return the hyperbolic arcus sine value for f .
sinh() , acosh()
float cosh(float f)
Return the hyperbolic cosine value for f .
acosh() , sinh() , tanh()
float acosh(float f)
Return the hyperbolic arcus cosine value for f .
cosh() , asinh()
float tanh(float f)
Returns the hyperbolic tangent value for f .
atanh() , sinh() , cosh()
float atanh(float f)
Returns the hyperbolic arcus tangent value for f .
tanh() , asinh() , acosh()
float sqrt(float f)
int sqrt(int i)
mixed sqrt(object o)
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.
pow() , log() , exp() , floor() , lfun::_sqrt
float log(float f)
Return the natural logarithm of f .
exp( log(x) ) == x
for x > 0.
pow() , exp()
float exp(float|int f)
Return the natural exponential of f .
log( exp( x ) ) == x
as long as exp(x) doesn't overflow an int.
pow() , log()
int|float pow(float|int n, float|int x)
mixed pow(object n, float|int|object x)
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.
exp() , log()
float floor(float f)
Return the closest integer value less or equal to f .
floor() does not return an int
, merely an integer value
stored in a float
.
ceil() , round()
float ceil(float f)
Return the closest integer value greater or equal to f .
ceil() does not return an int
, merely an integer value
stored in a float
.
floor() , round()
float round(float f)
Return the closest integer value to f .
round() does not return an int
, merely an integer value
stored in a float
.
floor() , ceil()
int|float|object min(int|float|object ... args)
string min(string ... args)
int(0..0) min()
Returns the smallest value among args . Compared objects must implement the lfun::`< method.
max()
int|float|object max(int|float|object ... args)
string max(string ... args)
int(0..0) max()
Returns the largest value among args . Compared objects must implement the lfun::`< method.
min()
float abs(float f)
int abs(int f)
object abs(object f)
Return the absolute value for f . If f is an object it must implement lfun::`< and unary lfun::`- .
int sgn(mixed value)
int sgn(mixed value, mixed zero)
Check the sign of a value.
Returns -1
if value is less than zero ,
1
if value is greater than zero and 0
(zero) otherwise.
abs()
Stdio.Stat file_stat(string path, void|int(0..1) symlink)
Stat a file.
If the argument symlink is 1
symlinks will not be followed.
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.
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;
}
Stdio.Stat , Stdio.File->stat()
int file_truncate(string file, int length)
Truncates the file file to the length specified in length .
Returns 1 if ok, 0 if failed.
mapping(string:int) filesystem_stat(string path)
Returns a mapping describing the properties of the filesystem containing the path specified by path .
If a filesystem cannot be determined 0
(zero) will be returned.
Otherwise a mapping(string:int) with the following fields will be returned:
|
Please note that not all members are present on all OSs.
file_stat()
void werror(string msg, mixed ... args)
Write to standard error.
int rm(string f)
Remove a file or directory.
Returns 0
(zero) on failure, 1
otherwise.
mkdir() , Stdio.recursive_rm()
int mkdir(string dirname, void|int mode)
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 0
(zero) on failure, 1
otherwise.
rm() , cd() , Stdio.mkdirhier()
array(string) get_dir(string dirname)
Returns an array of all filenames in the directory dirname , or
0
(zero) if the directory does not exist.
mkdir() , cd()
int cd(string s)
Change the current directory for the whole Pike process.
Returns 1
for success, 0
(zero) otherwise.
getcwd()
string getcwd()
Returns the current working directory.
cd()
int exece(string file, array(string) args)
int exece(string file, array(string) args, mapping(string:string) env)
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.
This function only returns if something went wrong during exece(2),
and in that case it returns 0
(zero).
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.
Process.create_process() , fork() , Stdio.File->pipe()
int mv(string from, string to)
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 0
(zero) on failure, 1
otherwise. Call
errno() to get more error info on failure.
rm()
string strerror(int errno)
This function returns a description of an error code. The error code is usually obtained from eg Stdio.File->errno() .
On some platforms the string returned can be somewhat nondescriptive.
int errno()
This function returns the system error from the last file operation.
Note that you should normally use Stdio.File->errno() instead.
Stdio.File->errno() , strerror()
string sprintf(string format, mixed ... args)
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:
|
The following operators are supported:
|
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.
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"
sprintf style formatting is applied by many formatting functions, such write() and werror .
> 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
lfun::_sprintf()
array(int|string|array(string)) getgrgid(int gid)
Get the group entry for the group with the id gid using the systemfunction getgrid(3).
The id of the group
An array with the information about the group
|
getgrent() getgrnam()
array(int|string|array(string)) getgrnam(string str)
Get the group entry for the group with the name str using the systemfunction getgrnam(3).
The name of the group
An array with the information about the group
|
getgrent() getgrgid()
array(int|string) getpwnam(string str)
Get the user entry for login str using the systemfunction getpwnam(3).
The login name of the user whos userrecord is requested.
An array with the information about the user
|
getpwuid() getpwent()
array(int|string) getpwuid(int uid)
Get the user entry for UID uid using the systemfunction getpwuid(3).
The uid of the user whos userrecord is requested.
An array with the information about the user
|
getpwnam() getpwent()
array(array(int|string)) get_all_users()
Returns an array with all users in the system.
An array with arrays of userinfo as in getpwent .
getpwent() getpwnam() getpwuid()
array(array(int|string|array(string))) get_all_groups()
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.
The groups source is system dependant. Refer to your system manuals for information about how to set the source.
|
getgrent()
array(int) get_groups_for_user(int|string user)
Gets all groups which a given user is a member of.
UID or loginname of the user
|
get_all_groups() getgrgid() getgrnam() getpwuid() getpwnam()
int equal(mixed a, mixed b)
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.
copy_value()
array aggregate(mixed ... elements)
Construct an array with the arguments as indices.
This function could be written in Pike as:
array aggregate(mixed ... elems) { return elems; }
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.
sizeof() , arrayp() , allocate()
int hash_7_4(string s)
int hash_7_4(string s, int max)
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.
This function is provided for backward compatibility reasons.
This function is byte-order dependant for wide strings.
hash() , hash_7_0()
int hash_7_0(string s)
int hash_7_0(string s, int max)
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.
This function is provided for backward compatibility reasons.
This function is not NUL-safe, and is byte-order dependant.
hash() , hash_7_4()
int hash(string s)
int hash(string s, int max)
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.
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() .
hash_7_0() , hash_7_4() , hash_value
int hash_value(mixed value)
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.
This is the hashing method used by mappings.
hash
mixed copy_value(mixed value)
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 `==() ).
equal()
string lower_case(string s)
int lower_case(int c)
Convert a string or character to lower case.
Returns a copy of the string s with all upper case characters converted to lower case, or the character c converted to lower case.
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.
Prior to Pike 7.5 this function only accepted strings.
upper_case() , Locale.Charset.decoder
string upper_case(string s)
int upper_case(int c)
Convert a string or character to upper case.
Returns a copy of the string s with all lower case characters converted to upper case, or the character c converted to upper case.
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.
Prior to Pike 7.5 this function only accepted strings.
lower_case() , Locale.Charset.decoder
string random_string(int len)
Returns a string of random characters 0-255 with the length len .
void random_seed(int seed)
This function sets the initial value for the random generator.
random()
int query_num_arg()
Returns the number of arguments given when the previous function was called.
This is useful for functions that take a variable number of arguments.
call_function()
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)
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:
|
If start is supplied to an iterator object without an lfun::_search() , haystack will need to implement Iterator()->set_index() .
indices() , values() , zero_type()
int has_prefix(string s, string prefix)
Returns 1
if the string s starts with prefix ,
returns 0
(zero) otherwise.
int has_suffix(string s, string suffix)
Returns 1
if the string s ends with suffix ,
returns 0
(zero) otherwise.
int has_index(string haystack, int index)
int has_index(array haystack, int index)
int has_index(mapping|multiset|object|program haystack, mixed index)
Search for index in haystack .
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
A negative index in strings and arrays as recognized by the
index operators `[]()
and `[]=()
is not considered
a proper index by has_index()
has_value() , indices() , search() , values() , zero_type()
int has_value(string haystack, string value)
int has_value(string haystack, int value)
int has_value(array|mapping|object|program haystack, mixed value)
Search for value in haystack .
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
has_index() , indices() , search() , values() , zero_type()
void add_constant(string name, mixed value)
void add_constant(string name)
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.
all_constants()
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)
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.
getcwd() , Stdio.append_path()
int zero_type(mixed a)
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() .
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).
find_call_out()
string string_to_unicode(string s)
Converts a string into an UTF16 compliant byte-stream.
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.
Locale.Charset.decoder() , string_to_utf8() , unicode_to_string() , utf8_to_string()
string unicode_to_string(string s)
Converts an UTF16 byte-stream into a string.
This function did not decode surrogates in Pike 7.2 and earlier.
Locale.Charset.decoder() , string_to_unicode() , string_to_utf8() , utf8_to_string()
string string_to_utf8(string s)
string string_to_utf8(string s, int extended)
Converts a string into an UTF8 compliant byte-stream.
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.
Locale.Charset.encoder() , string_to_unicode() , unicode_to_string() , utf8_to_string()
string utf8_to_string(string s)
string utf8_to_string(string s, int extended)
Converts an UTF8 byte-stream into a string.
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
.
Locale.Charset.encoder() , string_to_unicode() , string_to_utf8() , unicode_to_string()
string __parse_pike_type(string t)
mapping(string:mixed) all_constants()
Returns a mapping containing all global constants, indexed on the name of the constant, and with the value of the constant as value.
add_constant()
array allocate(int size)
array allocate(int size, mixed init)
Allocate an array of size elements. If init is specified then each element is initialized by copying that value recursively.
sizeof() , aggregate() , arrayp()
object this_object(void|int level)
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.
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.
void throw(mixed value)
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.
catch
void exit(int returncode, void|string fmt, mixed ... extra)
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.
_exit()
void _exit(int returncode)
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.
exit()
int time()
int time(int(1..1) one)
float time(int(2..) t)
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.
ctime() , localtime() , mktime() , gmtime() , System.gettimeofday , gethrtime
string crypt(string password)
int(0..1) crypt(string typed_password, string crypted_password)
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.
void destruct(void|object o)
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.
array indices(string|array|mapping|multiset|object x)
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.
values()
array values(string|array|mapping|multiset|object x)
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.
indices()
object next_object(object o)
object next_object()
Returns the next object from the list of all objects.
All objects are stored in a linked list.
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.
This function is not recomended to use.
destruct()
program|function object_program(mixed o)
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.
string reverse(string s)
array reverse(array a)
int reverse(int i)
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.
sscanf()
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)
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 that replace() on arrays and mappings is a destructive operation.
program compile(string source, object|void handler, int|void major, int|void minor, program|void target, object|void placeholder)
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 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() .
compile_string() , compile_file() , cpp() , master()
array|mapping|multiset set_weak_flag(array|mapping|multiset m, int state)
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:
|
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 .
m will be returned.
int objectp(mixed arg)
Returns 1
if arg is an object, 0
(zero) otherwise.
mappingp() , programp() , arrayp() , stringp() , functionp() , multisetp() , floatp() , intp()
int functionp(mixed arg)
Returns 1
if arg is a function, 0
(zero) otherwise.
mappingp() , programp() , arrayp() , stringp() , objectp() , multisetp() , floatp() , intp()
int callablep(mixed arg)
Returns 1
if arg is a callable, 0
(zero) otherwise.
mappingp() , programp() , arrayp() , stringp() , objectp() , multisetp() , floatp() , intp()
void sleep(int|float s, void|int abort_on_signal)
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.
signal() , delay()
void delay(int|float s)
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.
signal() , sleep()
int gc()
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.)
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.
Pike.gc_parameters , Debug.gc_status
int programp(mixed arg)
Returns 1
if arg is a program, 0
(zero) otherwise.
mappingp() , intp() , arrayp() , stringp() , objectp() , multisetp() , floatp() , functionp()
int intp(mixed arg)
Returns 1
if arg is an int, 0
(zero) otherwise.
mappingp() , programp() , arrayp() , stringp() , objectp() , multisetp() , floatp() , functionp()
int mappingp(mixed arg)
Returns 1
if arg is a mapping, 0
(zero) otherwise.
intp() , programp() , arrayp() , stringp() , objectp() , multisetp() , floatp() , functionp()
int arrayp(mixed arg)
Returns 1
if arg is an array, 0
(zero) otherwise.
intp() , programp() , mappingp() , stringp() , objectp() , multisetp() , floatp() , functionp()
int multisetp(mixed arg)
Returns 1
if arg is a multiset, 0
(zero) otherwise.
intp() , programp() , arrayp() , stringp() , objectp() , mappingp() , floatp() , functionp()
int stringp(mixed arg)
Returns 1
if arg is a string, 0
(zero) otherwise.
intp() , programp() , arrayp() , multisetp() , objectp() , mappingp() , floatp() , functionp()
int floatp(mixed arg)
Returns 1
if arg is a float, 0
(zero) otherwise.
intp() , programp() , arrayp() , multisetp() , objectp() , mappingp() , stringp() , functionp()
array sort(array(mixed) index, array(mixed) ... data)
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.
The first argument is returned.
The sort is stable, i.e. elements that are compare-wise equal aren't reordered.
Array.sort_array , reverse()
array rows(mixed data, array index)
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.
column()
mapping(string:int) gmtime(int timestamp)
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.
localtime() , time() , ctime() , mktime()
mapping(string:int) localtime(int timestamp)
Convert seconds since 00:00:00 UTC, 1 Jan 1970 into components.
This function returns a mapping with the following components:
|
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 .
Prior to Pike 7.5 the field "timezone"
was sometimes not
present, and was sometimes not adjusted for daylight savings time.
Calendar , gmtime() , time() , ctime() , 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)
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:
|
Or you can just send them all on one line as the second syntax suggests.
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).
time() , ctime() , localtime() , gmtime()
int(0..1) glob(string glob, string str)
array(string) glob(string glob, array(string) arr)
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.
sscanf() , Regexp
mixed _next(mixed x)
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.
next_object() , _prev()
mixed _prev(mixed x)
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.
Unlike _next() this function does not work on strings.
next_object() , _next()
int _refs(string|array|mapping|multiset|function|object|program o)
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 that the number of references will always be at least one since the value is located on the stack when this function is executed.
_next() , _prev()
type(mixed) _typeof(mixed x)
Return the runtime type of x .
typeof()
void replace_master(object o)
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.
master()
object master()
Return the current master object.
replace_master()
int gethrvtime(void|int nsec)
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.
The actual accuracy on many systems is significantly less than milliseconds or nanoseconds.
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.
The special function gauge is implemented with this function.
System.CPU_TIME_IS_THREAD_LOCAL , gauge() , System.getrusage() , gethrtime()
int gethrtime(void|int nsec)
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.
The actual accuracy on many systems is significantly less than milliseconds or nanoseconds.
time() , System.gettimeofday() , gethrvtime()
array(int|mapping(string:array(int))) get_profiling_info(program prog)
Get profiling information.
Returns an array with two elements.
|
This function is only available if the runtime was compiled with the option --with-profiling.
int(0..1) object_variablep(object o, string var)
Find out if an object identifier is a variable.
This function returns 1
if var exists as a non-static variable
in o , and returns 0
(zero) otherwise.
indices() , values()
mixed map(mixed arr, void|mixed fun, mixed ... extra)
Applies fun to the elements in arr and collects the results.
arr is treated as a set of elements, as follows:
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.
fun is applied to the values, and each result is assigned to the same index in a new mapping, which is returned.
The program is treated as a mapping containing the identifiers that are indexable from it and their values.
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:
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.
fun is used as a function like above, i.e. the lfun::`() method in it is called.
fun is indexed with each element. The result of that is collected.
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.
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.
The function is never destructive on arr .
filter() , enumerate() , foreach()
mixed filter(mixed arr, void|mixed fun, mixed ... extra)
Filters the elements in arr through fun .
arr is treated as a set of elements to be filtered, as follows:
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.
The values are filtered with fun , and the index/value pairs it accepts are kept in the returned mapping.
The program is treated as a mapping containing the identifiers that are indexable from it and their values.
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:
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.
The object is used as a function like above, i.e. the lfun::`() method in it is called.
fun is indexed with each element. The element is kept if the result is nonzero, otherwise it's filtered 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.
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.
The function is never destructive on arr .
map() , foreach()
array(int) enumerate(int n)
array enumerate(int n, void|mixed step, void|mixed start, void|function operator)
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 = `+
map() , foreach()
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)
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"
.
compile()
program load_module(string module_name)
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.
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.
string encode_value(mixed value, object|void codec)
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.
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.
decode_value() , sprintf() , encode_value_canonic()
string encode_value_canonic(mixed value, object|void codec)
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 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.
encode_value() , decode_value()
mixed decode_value(string coded_value, void|Codec codec)
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.
encode_value() , encode_value_canonic()
mixed `()(function fun, mixed ... args)
mixed call_function(function fun, mixed ... args)
Call a function.
Calls the function fun with the arguments specified by args .
lfun::`()()
mapping aggregate_mapping(mixed ... elems)
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, ... ])
sizeof() , mappingp() , mkmapping()
int(0..1) `!=(mixed arg1, mixed arg2, mixed ... extras)
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 1
if the test is successful, 0
otherwise.
`==()
int(0..1) `==(mixed arg1, mixed arg2, mixed ... extras)
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:
|
Returns 1
if the test is successful, 0
otherwise.
Floats and integers are not automatically converted to test
against each other, so e.g. 0==0.0
is false.
Programs are not automatically converted to types to be compared type-wise.
`!() , `!=()
int(0..1) `<(mixed arg1, mixed arg2, mixed ... extras)
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 1
if the test is successful, 0
otherwise.
`<=() , `>() , `>=()
int(0..1) `<=(mixed arg1, mixed arg2, mixed ... extras)
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 1
if the arguments are not strictly decreasing, and
0
(zero) otherwise.
This is the inverse of `>() .
`<() , `>() , `>=()
int(0..1) `>(mixed arg1, mixed arg2, mixed ... extras)
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 1
if the arguments are strictly decreasing, and
0
(zero) otherwise.
`<() , `<=() , `>=()
int(0..1) `>=(mixed arg1, mixed arg2, mixed ... extras)
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 1
if the arguments are not strictly increasing, and
0
(zero) otherwise.
This is the inverse of `<() .
`<=() , `>() , `<()
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)
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)
.
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:
|
The function is not destructive on the arguments - the result is always a new instance.
In Pike 7.0 and earlier the addition order was unspecified.
The treatment of UNDEFINED was new in Pike 7.0.
`-() , lfun::`+() , lfun::``+()
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)
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)
.
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:
|
The function is not destructive on the arguments - the result is always a new instance.
In Pike 7.0 and earlier the subtraction order was unspecified.
`+()
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)
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)
.
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:
|
The function is not destructive on the arguments - the result is always a new instance.
`|() , lfun::`&() , lfun::``&()
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)
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)
.
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:
|
The function is not destructive on the arguments - the result is always a new instance.
`&() , lfun::`|() , lfun::``|()
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)
Exclusive or.
Every expression with the ^
operator becomes a call to
this function, i.e. a^b
is the same as
predef::`^(a,b)
.
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:
|
The function is not destructive on the arguments - the result is always a new instance.
`&() , `|() , lfun::`^() , lfun::``^()
int `<<(int arg1, int arg2)
mixed `<<(object arg1, int|object arg2)
mixed `<<(int arg1, object arg2)
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.
`>>()
int `>>(int arg1, int arg2)
mixed `>>(object arg1, int|object arg2)
mixed `>>(int arg1, object arg2)
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.
`<<()
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)
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)
.
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:
|
In Pike 7.0 and earlier the multiplication order was unspecified.
`+() , `-() , `/() , lfun::`*() , lfun::``*()
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)
Division/split.
Every expression with the /
operator becomes a call to
this function, i.e. a/b
is the same as
predef::`/(a,b)
.
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:
|
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.
`%
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)
Modulo.
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::`%() 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:
|
For numbers, this means that
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).
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.
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.
/ and % are compatible, so that a = b*(a/b) + a%b for all a and b.
`/
int(0..1) `!(object|function arg)
int(1..1) `!(int(0..0) arg)
int(0..0) `!(mixed arg)
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.
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.
No float is considered false, not even 0.0
.
`==() , `!=() , lfun::`!()
mixed `~(object arg)
int `~(int arg)
float `~(float arg)
type(mixed) `~(type(mixed)|program arg)
string `~(string arg)
Complement/inversion.
Every expression with the ~
operator becomes a call to
this function, i.e. ~a
is the same as
predef::`~(a)
.
The result will be as follows:
arg can have any of the following types:
|
`!() , lfun::`~()
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)
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.
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:
|
Otherwise if there are 3 arguments the result will be as follows:
arg can have any of the following types:
|
An indexing expression in an lvalue context, i.e. where the index is being assigned a new value, uses `[]= instead of this function.
`->() , lfun::`[]() , `[]=
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)
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.
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:
|
In an expression a->b
, the symbol b
can be any
token that matches the identifier syntax - keywords are
disregarded in that context.
An arrow indexing expression in an lvalue context, i.e. where the index is being assigned a new value, uses `->= instead of this function.
`[]() , lfun::`->() , ::`->() , `->=
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)
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:
|
val will be returned.
An indexing expression in a non-lvalue context, i.e. where the index is being queried instead of assigned, uses `[] instead of this function.
`->=() , lfun::`[]=() , `[]
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)
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:
|
val will be returned.
In an expression a->b=c
, the symbol b
can be any
token that matches the identifier syntax - keywords are
disregarded in that context.
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.
`[]=() , lfun::`->=() , `->
int sizeof(string arg)
int sizeof(array arg)
int sizeof(mapping arg)
int sizeof(multiset arg)
int sizeof(object arg)
Size query.
The result will be as follows:
arg can have any of the following types:
|
lfun::_sizeof()
constant UNDEFINED
The undefined value; ie a zero for which zero_type() returns 1.
constant this
Builtin read only variable that evaluates to the current object.
this_program , this_object()
constant this_program
Builtin constant that evaluates to the current program.
this , this_object()
constant __null_program
Program used internally by the compiler.
__placeholder_object
constant __placeholder_object
Object used internally by the compiler.
__null_program
void signal(int sig, function(int|void:void) callback)
void signal(int sig)
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.
kill() , signame() , signum()
int signum(string sig)
Get a signal number given a descriptive string.
This function is the inverse of signame() .
signame() , kill() , signal()
string signame(int sig)
Returns a string describing the signal sig .
kill() , signum() , signal()
int set_priority(string level, int|void pid)
object fork()
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.
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() .
Process.create_process()
void kill(int pid, int signal)
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:
|
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.
signal() , signum() , signame() , fork()
int getpid()
Returns the process ID of this process.
System.getppid() , System.getpgrp()
int alarm(int seconds)
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 the number of seconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.
This function is only available on platforms that support signals.
ualarm() , signal() , call_out()
int ualarm(int useconds)
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 the number of microseconds remaining until any previously scheduled alarm was due to be delivered, or zero if there was no previously scheduled alarm.
This function is only available on platforms that support signals.
alarm() , signal() , call_out()
void atexit(function callback)
This function puts the callback in a queue of callbacks to call when pike exits.
Please note that atexit callbacks are not called if Pike exits abnormally.
exit() , _exit()
int sscanf(string data, string format, mixed ... lvalues)
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:
|
Similar to sprintf , you may supply modifiers between the % character and the operator, to slightly change its behaviour from the default:
|
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.
// 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);
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).
sprintf , array_sscanf
array array_sscanf(string data, string format)
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.
sscanf() , `/()
_disable_threads _disable_threads()
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.
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.)
string version()
Report the version of Pike. Does the same as
sprintf("Pike v%d.%d release %d", __REAL_VERSION__,
__REAL_MINOR__, __REAL_BUILD__);
__VERSION__ , __MINOR__ , __BUILD__ , __REAL_VERSION__ , __REAL_MINOR__ , __REAL_BUILD__ ,
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()
These are aliases for the corresponding functions in Pike.DefaultBackend .
Pike.Backend()->call_out() , Pike.Backend()->_do_call_outs() , Pike.Backend()->find_call_out() , Pike.Backend()->remove_call_out() , Pike.Backend()->call_out_info()
string basetype(mixed x)
Same as sprintf("%t",x);
sprintf()
array column(array data, mixed index)
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.
rows()
multiset mkmultiset(array a)
This function creates a multiset from an array.
aggregate_multiset()
int trace(int level, void|string facility, void|int all_threads)
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.
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:
|
Valid facilities are:
|
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.
The old trace level in the current thread is returned.
string ctime(int timestamp)
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 .
time() , localtime() , mktime() , gmtime()
mapping mkmapping(array ind, array val)
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() .
indices() , values()
mixed m_delete(object|mapping map, mixed index)
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.
The value that was removed will be returned.
Note that m_delete() changes map destructively.
mappingp()
int get_weak_flag(array|mapping|multiset m)
Returns the weak flag settings for m . It's a combination of Pike.WEAK_INDICES and Pike.WEAK_VALUES .
program __empty_program(int|void line, string|void file)
string function_name(function f)
Return the name of the function f .
If f is a global function defined in the runtime 0
(zero) will be returned.
function_object()
object function_object(function f)
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.
function_name() , function_program()
program function_program(function|program f)
Return the program the function f is in.
If f is a global function defined in the runtime 0
(zero) will be returned.
function_name() , function_object()
mixed random(object o)
If random is called with an object, lfun::random will be called in the object.
lfun::_random
int random(int max)
float random(float max)
This function returns a random number in the range 0 - max -1.
random_seed()
mixed random(array|multiset x)
Returns a random element from x .
array random(mapping m)
Returns a random index-value pair from the mapping.
array(Pike.BacktraceFrame) backtrace()
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:
|
The current call frame will be last in the array.
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).
catch() , throw()
Iterator get_iterator(object|array|mapping|multiset|string data)
Creates and returns a canonical iterator for data .
|
This function is used by foreach to get an iterator for an object.
Iterator , lfun::_get_iterator
void error(string f, mixed ... args)
Throws an error. A more readable version of the code
throw( ({ sprintf(f, @args), backtrace() }) )
.
int is_absolute_path(string p)
Check if a path p is fully qualified (ie not relative).
Returns 1 if the path is absolute, 0 otherwise.
array(string) explode_path(string p)
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() .
string dirname(string x)
Returns all but the last segment of a path. Some example inputs and outputs:
|
basename() , explode_path()
string basename(string x)
Returns the last segment of a path.
dirname() , explode_path()
program compile_string(string source, void|string filename, object|void handler, void|program p, void|object o, void|int _show_if_constant_errors)
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 ))
.
compile() , cpp() , compile_file()
string getenv(string varname)
mapping(string:string) getenv()
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.
program compile_file(string filename, object|void handler, void|program p, void|object o)
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 )
.
compile() , compile_string() , cpp()
void putenv(string varname, string value)
Sets the environment variable varname to value .
On NT the environment variable name is case insensitive.
getenv()
string normalize_path(string path)
Replaces "\" with "/" if runing on MS Windows. It is adviced to use System.normalize_path instead.
int strlen(string|multiset|array|mapping|object thing)
Alias for sizeof .
int write(string fmt, mixed ... args)
Writes a string on stdout. Works just like Stdio.File.write on Stdio.stdout .
string describe_backtrace(array|object trace, void|int linewidth)
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.
backtrace() , describe_error() , catch() , throw()
string describe_error(mixed err)
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.
describe_backtrace() , get_backtrace
array get_backtrace(object|array err)
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.
describe_backtrace() , describe_error()
CLASS MasterObject |
inherit CompilationHandler : CompilationHandler
The master object acts as fallback compilation handler for compile() and cpp() .
CompilationHandler get_compilation_handler(int major, int minor)
Get compilation handler for simulation of Pike vmajor .minor .
This function is called by cpp() when it encounters
#pike
directives.
Major version.
Minor version.
Returns a compilation handler for Pike >= major .minor .
string decode_charset(string raw, string charset)
Convert raw from encoding charset to UNICODE.
This function is called by cpp() when it encounters
#charset
directives.
String to convert.
Name of encoding that raw uses.
raw decoded to UNICODE, or 0
(zero) if the decoding failed.
Locale.Charset
inherit Codec : Codec
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.
string describe_backtrace(mixed exception)
Called by various routines to format a readable description of an exception.
Something that was thrown. Usually an Error.Generic object, or an array with the following content:
|
Returns a string describing the exeception.
Usually added by the initialization code the global name space with add_constant() .
predef::describe_backtrace()
void runtime_warning(string subsystem, string msg, mixed|void data)
Called by the Pike runtime to warn about data inconsistencies.
Runtime subsystem where the warning was generated. Currently the following subsystems may call this function:
|
Warning message. Currently the following messages may be generated:
|
Optional data that further describes the warning specified by msg .
void handle_error(mixed exception)
Called by the Pike runtime if an exception isn't caught.
Value that was throw() 'n.
describe_backtrace()
object cast_to_object(string str, string|void current_file)
Called by the Pike runtime to cast strings to objects.
String to cast to object.
Filename of the file that attempts to perform the cast.
Returns the resulting object.
cast_to_program()
program cast_to_program(string str, string|void current_file)
Called by the Pike runtime to cast strings to programs.
String to cast to object.
Filename of the file that attempts to perform the cast.
Returns the resulting program.
cast_to_object()
void unregister(program p)
Unregister a program that was only partially compiled.
Called by compile() to clean up references to partially compiled programs.
Partially compiled program that should no longer be referenced.
Shouldn't this function be in the compilation handler?
CLASS CompilationHandler |
void compile_error(string filename, int line, string msg)
Called by compile() and cpp() when they encounter errors in the code they compile.
File where the error was detected.
Line where the error was detected.
Description of error.
compile_warning() .
void compile_exception(mixed exception)
Called by compile() and cpp() if they trigger exceptions.
mapping(string:mixed) get_predefines()
Called by cpp() to get the set of global symbols.
Returns a mapping from symbol name to symbol value. Returns zero on failure.
resolv() , get_default_module()
mixed resolv(string symbol, string filename, CompilationHandler handler)
Called by compile() and cpp() to resolv module references.
Returns the resolved value, or UNDEFINED on failure.
get_predefines()
mixed handle_import(string path, string filename, CompilationHandler handler)
Called by compile() and cpp() to handle import directives specifying specific paths.
Returns the resolved value, or UNDEFINED on failure.
string handle_include(string header_file, string current_file, int(0..1) is_local_ref)
Called by cpp() to resolv #include
and #string
directives.
File that was requested for inclusion.
File where the directive was found.
Specifies reference method.
|
Returns the filename to pass to read_include() if found,
and 0
(zero) on failure.
read_include()
string read_include(string filename)
Called by cpp() to read included files.
Filename as returned by handle_include() .
Returns a string with the content of the header file on success,
and 0
(zero) on failure.
handle_include()
mapping(string:mixed)|object get_default_module()
Returns the default module from which global symbols will be fetched.
Returns the default module, or 0
(zero).
If 0
(zero) is returned the compiler use the mapping
returned by all_constants() as fallback.
get_predefines()
void compile_warning(string filename, int line, string msg)
Called by compile() to report warnings.
File which triggered the warning.
Line which triggered the warning.
Warning message.
compile_error()
CLASS Codec |
Codec objects are used by encode_value() and decode_value() to encode and decode objects, functions and programs.
encode_value() and decode_value() will use the current master object as fallback codec object if no codec was specified.
mixed nameof(object|function|program x)
Called by encode_value() to encode objects, functions and programs.
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.
encode_value() has fallbacks for some classes of objects, functions and programs.
objectof() , functionof() , objectof()
object objectof(string data)
Decode object encoded in data .
This function is called by decode_value() when it encounters encoded objects.
Encoding of some object as specified by nameof() .
Minor version.
Returns the decoded object.
functionof() , programof()
function functionof(string data)
Decode function encoded in data .
This function is called by decode_value() when it encounters encoded functions.
Encoding of some function as specified by nameof() .
Minor version.
Returns the decoded function.
objectof() , programof()
program programof(string data)
Decode program encoded in data .
This function is called by decode_value() when it encounters encoded programs.
Encoding of some program as specified by nameof() .
Minor version.
Returns the decoded program.
functionof() , objectof()
object __register_new_program(program p)
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 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 |
int `[](int i, int j)
String index operator.
int `[]=(int i, int j)
String assign index operator.
CLASS Iterator |
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.
predef::get_iterator , lfun::_get_iterator , Array.Iterator , Mapping.Iterator , Multiset.Iterator , String.Iterator , String.SplitIterator .
void Iterator(void|mixed data)
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.
int(0..1) `!()
Returns 0
(zero) when the iterator points to an item,
1
otherwise.
Iterator `+(int steps)
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.
Iterator `+=(int steps)
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
.
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) {
...
}
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.
Iterator `-(int steps)
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.
mixed index()
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
.
mixed value()
Returns the current value, or UNDEFINED if the iterator doesn't point to any item.
int _sizeof()
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.
void _random()
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.
int(0..1) first()
If this function is defined then it resets the iterator to point to the first item.
Returns zero if there are no items at all in the data set, one otherwise.
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.
int next()
If this function is defined it should advance the iterator one
step, just like `+= (1)
would do.
Returns 1 if it succeeded in advancing, and 0 (zero) at end of iterator.
void set_index(zero index)
If this function is defined it should set the iterator at the specified index.
It should be possible to set the index at the end of the iterator.
CLASS master |
inherit CompatResolver : CompatResolver
inherit Codec : Codec
constant bt_max_string_len
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
Should Pike complain about out of date compiled files. 1 means yes and 0 means no. Controlled by the OUT_OF_DATE_WARNING define.
int want_warnings
If not zero compilation warnings will be written out on stderr.
int compat_major
int compat_minor
int show_if_constant_errors
string master_read_file(string file)
mapping(string:array(string)) environment
Mapping containing the environment variables.
The mapping currently has the following structure:
|
This mapping should not be accessed directly; use getenv() and putenv() instead.
This mapping is not compatible with Process.create_process() ; use the mapping returned from calling getenv() without arguments instead.
mapping(string:program|NoValue) programs
Mapping containing the cache of currently compiled files.
This mapping currently has the following structure:
|
The filename path seperator is / on both NT and UNIX.
As a special case the current master program is available
under the name "/master"
.
string programs_reverse_lookup(program prog)
Returns the path for prog in programs , if it got any.
program objects_reverse_lookup(object obj)
Returns the program for obj in objects , if it got any.
string fc_reverse_lookup(object obj)
Returns the path for obj in fc , if it got any.
program cast_to_program(string pname, string current_file, object|void handler)
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.
void handle_error(array|object trace)
This function is called when an error occurs that is not caught with catch().
program handle_inherit(string pname, string current_file, object|void handler)
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.
object cast_to_object(string oname, string current_file, object|void current_handler)
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
These are useful if you want to start other Pike processes with the same options as this one was started with.
int(0..1) asyncp()
Returns 1 if we´re in async-mode, e.g. if the main method has returned a negative number.
object backend_thread()
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.
void _main(array(string) orig_argv, array(string) env)
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.
void compile_error(string file, int line, string err)
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.
void compile_warning(string file, int line, string err)
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.
int compile_exception(array|object trace)
This function is called when an exception is catched during compilation. Its message is also reported to compile_error if this function returns zero.
void runtime_warning(string where, string what, mixed ... args)
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.
string decode_charset(string data, string charset)
This function is called by cpp() when it wants to do character code conversion.
string program_path_to_name(string path, void|string module_prefix, void|string module_suffix, void|string object_suffix)
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"
).
string describe_module(object|program mod, array(object)|void ret_obj)
Describe the path to the module mod .
If mod is a program, attempt to describe the path to a clone of mod .
If an instance of mod is found, it will be returned
by changing element 0
of ret_obj .
The a description of the path.
The returned description will end with a proper indexing method
currently either "."
or "->"
.
string describe_object(object o)
string describe_program(program|function p)
string describe_function(function f)
Version currentversion
Version information about the current Pike version.
CLASS master.dirnode |
Module node representing a single directory.
joinnode
CLASS master.joinnode |
Module node holding possibly multiple directories, and optionally falling back to another level.
dirnode
CLASS master.CompatResolver |
joinnode root_module
Actual resolver
mapping(object:joinnode) handler_root_modules
Lookup from handler module to corresponding root_module.
array(string) system_module_path
The pike system module path, not including any set by the user.
array(string) pike_module_path
The complete module search path
array(string) pike_include_path
The complete include search path
array(string) pike_program_path
The complete program search path
CompatResolver fallback_resolver
If we fail to resolv, try the fallback.
Typical configuration:
0.6->7.0->7.2->7.4->master
void master.CompatResolver(mixed version, CompatResolver|void fallback_resolver)
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.
void add_include_path(string tmp)
Add a directory to search for include files.
This is the same as the command line option -I.
Note that the added directory will only be searched when using < > to quote the included file.
remove_include_path()
void remove_include_path(string tmp)
Remove a directory to search for include files.
This function performs the reverse operation of add_include_path() .
add_include_path()
void add_module_path(string tmp)
Add a directory to search for modules.
This is the same as the command line option -M.
remove_module_path()
void remove_module_path(string tmp)
Remove a directory to search for modules.
This function performs the reverse operation of add_module_path() .
add_module_path()
void add_program_path(string tmp)
Add a directory to search for programs.
This is the same as the command line option -P.
remove_program_path()
void remove_program_path(string tmp)
Remove a directory to search for programs.
This function performs the reverse operation of add_program_path() .
add_program_path()
void add_predefine(string name, string value)
Add a define (without arguments) which will be implicitly defined in cpp calls.
void remove_predefine(string name)
Remove a define from the set that are implicitly defined in cpp calls.
mapping get_predefines()
Returns a mapping with the current predefines.
mapping(string:mixed) instantiate_static_modules(object|mapping static_modules)
Instantiate static modules in the same way that dynamic modules are instantiated.
mapping get_default_module()
mixed resolv_base(string identifier, string|void current_file, object|void current_handler)
mixed resolv_or_error(string identifier, string|void current_file, void|object current_handler)
Same as resolv , but throws an error instead of returning UNDEFINED if the resolv failed.
mixed resolv(string identifier, string|void current_file, object|void current_handler)
string handle_include(string f, string current_file, int local_include)
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
string read_include(string f)
CLASS master.Pike06Resolver |
inherit CompatResolver : CompatResolver
mixed resolv_base(string identifier, string|void current_file, object|void current_handler)
In Pike 0.6 the current directory was implicitly searched.
CLASS master.Encoder |
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.
string|array nameof(mixed what, void|array(object) module_object)
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.
void master.Encoder(void|mixed encoded)
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 |
Codec for use with decode_value . This is the decoder corresponding to Encoder . See that one for more details.
void|string fname
void|int mkobjvoid master.Decoder(void|string fname, void|int mkobj)
CLASS master.Codec |
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 : Encoder
inherit Decoder : Decoder
void master.Codec(void|mixed encoded)
The optional argument is the thing to encode; it's passed on to Encoder .
CLASS master.Version |
Contains version information about a Pike version.
int major
int minor
The major and minor parts of the version.
void master.Version(int major, int minor)
Set the version in the object.
int `<(mixed v)
int `>(mixed v)
int `==(mixed v)
int _hash()
Methods define so that version objects can be compared and ordered.
mixed cast(string type)
The version object can be casted into a string.
Module Bz2 |
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 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 |
Bz2.Deflate is a builtin program written in C. It interfaces the packing routines in the bzlib library.
This program is only available if libz was available and found when Pike was compiled.
Bz2.Inflate()
void Bz2.Deflate(int(1..9)|void block_size)
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.
void feed(string data)
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.
Bz2.Deflate->read() Bz2.Deflate->finish()
string read(string data)
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
Bz2.Deflate->feed() Bz2.Deflate->finish()
string finish(string data)
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.
Bz2.Deflate->feed() Bz2.Deflate->read()
string deflate(string data, int(0..2)|void flush_mode)
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.Inflate->inflate()
CLASS Bz2.Inflate |
Bz2.Inflate is a builtin program written in C. It interfaces the unpacking routines in the libz library.
This program is only available if bzlib was available and found when Pike was compiled.
Deflate
void Bz2.Inflate()
string inflate(string data)
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.
while(..){ foo = compressed_data[i..i+9]; uncompressed_concatenated_data += inflate_object->inflate(foo); i = i+10; }
Bz2.Deflate->deflate()
CLASS Bz2.File |
Low-level implementation of read/write support for Bzip2 files
int(0..1) close()
closes the file
void Bz2.File()
Creates a Bz2.File object
int(0..1) read_open(string file)
Opens a file for reading.
The name of the file to be opened
int(0..1) write_open(string file)
Opens a file for writing.
The name of the file to be opened
int(0..1) open(string file, void|string mode)
Opens a file for I/O.
The name of the file to be opened
Mode for the file operations. Can be either "r" (read) or "w". Read is default.
int write(string data)
Writes the data to the file.
the number of bytes written to the file.
int|string read(int len)
Reads len (uncompressed) bytes from the file. If len is omitted the whole file is read. If read is unsuccessful, 0 is returned.
int(0..1) eof()
1 if EOF has been reached, 0 otherwise
Module Nettle |
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.
string Nettle.crypt_md5(string password, string salt)
Does the crypt_md5 abrakadabra (MD5 + snakeoil). It is assumed that salt does not contain "$".
CLASS Nettle.CipherInfo |
Represents information about a cipher algorithm, such as name, key size, and block size.
string name()
A human readable name for the algorithm.
string key_size()
The recommended key size for the cipher.
string block_size()
The block size of the cipher (1 for stream ciphers).
CLASS Nettle.CipherState |
Base class for hashing contexts.
CipherState set_encrypt_key(string key, void|int force)
Initializes the object for encryption.
set_decrypt_key , crypt
CipherState set_decrypt_key(string key, void|int force)
Initializes the object for decryption.
set_encrypt_key , crypt
string make_key()
Generate a key by calling Crypto.Random.random_string and initialize this object for encryption with that key.
The generated key.
set_encrypt_key
string crypt(string data)
Encrypts or decrypts data, using the current key.
For block ciphers, data must be an integral number of blocks.
The encrypted or decrypted data.
string key_size()
The actual key size for this cipher.
CLASS Nettle.AES_Info |
Internal mixin class, intended to be multiply inherited together with CipherInfo.
CLASS Nettle.AES_State |
State for AES encyption
CLASS Nettle.ARCFOUR_Info |
Internal mixin class, intended to be multiply inherited together with CipherInfo.
CLASS Nettle.ARCFOUR_State |
State for ARCFOUR encyption
CLASS Nettle.BLOWFISH_Info |
Internal mixin class, intended to be multiply inherited together with CipherInfo.
CLASS Nettle.BLOWFISH_State |
State for Blowfish encyption
CLASS Nettle.CAST128_Info |
Internal mixin class, intended to be multiply inherited together with CipherInfo.
CLASS Nettle.CAST128_State |
State for CAST128 encyption
CLASS Nettle.DES_Info |
Internal mixin class, intended to be multiply inherited together with CipherInfo.
string fix_parity(string key)
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 |
State for DES encyption
CLASS Nettle.DES3_Info |
Internal mixin class, intended to be multiply inherited together with CipherInfo.
string fix_parity(string key)
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 |
State for DES3 encyption
CLASS Nettle.Serpent_Info |
Internal mixin class, intended to be multiply inherited together with CipherInfo.
CLASS Nettle.Serpent_State |
State for Serpent encyption
CLASS Nettle.Twofish_Info |
Internal mixin class, intended to be multiply inherited together with CipherInfo.
CLASS Nettle.Twofish_State |
State for Twofish encyption
CLASS Nettle.IDEA_Info |
Internal mixin class, intended to be multiply inherited together with CipherInfo.
CLASS Nettle.IDEA_State |
State for IDEA encyption
CLASS Nettle.HashInfo |
Represents information about a hash algorithm, such as name, digest size, and internal block size.
string name()
Returns a human readable name for the algorithm.
string digest_size()
Returns the size of a hash digests.
string block_size()
Returns the internal block size of the hash algorithm.
CLASS Nettle.HashState |
Base class for hashing contexts.
HashState update(string data)
Hashes more data.
string digest(int|void length)
Generates a digests, and resets the hashing contents.
If the length argument is provided, the digest is truncated to the given length.
The digest.
CLASS Nettle.MD5_Info |
Internal mixin class, intended to be multiply inherited together with HashInfo.
CLASS Nettle.MD5_State |
State for MD5 hashing.
CLASS Nettle.MD4_Info |
Internal mixin class, intended to be multiply inherited together with HashInfo.
CLASS Nettle.MD4_State |
State for MD4 hashing.
CLASS Nettle.MD2_Info |
Internal mixin class, intended to be multiply inherited together with HashInfo.
CLASS Nettle.MD2_State |
State for MD2 hashing.
CLASS Nettle.SHA1_Info |
Internal mixin class, intended to be multiply inherited together with HashInfo.
CLASS Nettle.SHA1_State |
State for SHA1 hashing.
CLASS Nettle.SHA256_Info |
Internal mixin class, intended to be multiply inherited together with HashInfo.
CLASS Nettle.SHA256_State |
State for SHA256 hashing.
CLASS Nettle.Yarrow |
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.
void Nettle.Yarrow(void|int sources)
The number of entropy sources that will feed entropy to the random number generator is given as an argument to Yarrow during instantiation.
update
Yarrow seed(string data)
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 the called object.
min_seed_size , get_seed , is_seeded
int(0..) min_seed_size()
Returns the minimal number of characters that the seed needs to properly seed the random number generator.
seed
string get_seed()
Returns part of the internal state so that it can be saved for later seeding.
seed
int(0..1) is_seeded()
Returns 1 if the random generator is seeded and ready to generator output. 0 otherwise.
seed
void force_reseed()
By calling this function entropy is moved from the slow pool to the fast pool. Read more about Yarrow before using this.
int(0..1) update(string data, int source, int entropy)
Inject additional entropy into the random number generator.
create
int(0..) needed_sources()
The number of sources that must reach the threshold before a slow reseed will happen.
string random_string(int length)
Returns a pseudo-random string of the requested length .
Module Crypto |
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 .
string Crypto.make_crypt_md5(string password, void|string salt)
Hashes a password together with a salt with the crypt_md5 algorithm and returns the result.
verify_crypt_md5
int(0..1) Crypto.verify_crypt_md5(string password, string hash)
Verifies the password against the crypt_md5 hash.
May throw an exception if the hash value is bad.
make_crypt_md5
CLASS Crypto.Pipe |
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 |
Abstract class for hash algorithms. Contains some tools useful for all hashes.
inherit Nettle.HashInfo : HashInfo
HashState `()()
Calling `() will return a Nettle.HashState object.
string hash(string data)
Works as a shortcut for obj->update(data)->digest()
.
HashState()->update() and HashState()->digest() .
CLASS Crypto.Cipher |
Abstract class for crypto algorithms. Contains some tools useful for all ciphers.
inherit Nettle.CipherInfo : CipherInfo
CipherState `()()
Calling `() will return a Nettle.CipherState object.
string encrypt(string key, string data)
Works as a shortcut for obj->set_encrypt_key(key)->crypt(data)
string decrypt(string key, string data)
Works as a shortcut for obj->set_decrypt_key(key)->crypt(data)
CLASS Crypto.DSA |
The Digital Signature Algorithm (aka DSS, Digital Signature Standard).
Gmp.mpz get_p()
Returns the modulo.
Gmp.mpz get_q()
Returns the group order.
Gmp.mpz get_g()
Returns the generator.
Gmp.mpz get_y()
Returns the public key.
Gmp.mpz get_x()
Returns the private key.
this_program set_public_key(Gmp.mpz p_, Gmp.mpz q_, Gmp.mpz g_, Gmp.mpz y_)
Sets the public key in this DSA object.
this_program set_private_key(Gmp.mpz secret)
Sets the private key in this DSA object.
this_program set_random(function(int:string) r)
Sets the random function, used to generate keys and parameters, to the function r . Default is Crypto.Random.random_string .
Gmp.mpz hash(string msg)
Makes a DSA hash of the messge msg .
array(Gmp.mpz) raw_sign(Gmp.mpz h, void|Gmp.mpz k)
Sign the message h . Returns the signature as two Gmp.mpz objects.
int(0..1) raw_verify(Gmp.mpz h, Gmp.mpz r, Gmp.mpz s)
Verify the signature r ,s against the message h .
string sign_rsaref(string msg)
Make a RSA ref signature of message msg .
int(0..1) verify_rsaref(string msg, string s)
Verify a RSA ref signature s of message msg .
string sign_ssl(string msg)
Make an SSL signatrue of message msg .
int(0..1) verify_ssl(string msg, string s)
Verify an SSL signature s of message msg .
array(Gmp.mpz) nist_primes(int l)
The (slow) NIST method of generating a DSA prime pair. Algorithm 4.56 of Handbook of Applied Cryptography.
this_program generate_parameters(int bits)
Generate key parameters using nist_primes .
this_program generate_key()
Generates a public/private key pair. Needs the public parameters p, q and g set, either through set_public_key or generate_parameters .
int(0..1) public_key_equal(.DSA dsa)
Compares the public key in this object with that in the provided DSA object.
string name()
Returns the string "DSA"
.
CLASS Crypto.HMAC |
HMAC, defined by RFC-2104
void Crypto.HMAC(.Hash h, int|void b)
The hash object on which the HMAC object should base its operations. Typical input is Crypto.MD5 .
The block size of one compression block, in octets. Defaults to 64.
string raw_hash(string s)
Calls the hash function given to create and returns the hash value of s .
string pkcs_digest(string s)
Makes a PKCS-1 digestinfo block with the message s .
Standards.PKCS.Signature.build_digestinfo
CLASS Crypto.HMAC.`() |
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")
.
void Crypto.HMAC.`()(string passwd)
The secret password (K).
string `()(string text)
Hashes the text according to the HMAC algorithm and returns the hash value.
string digest_info(string text)
Hashes the text according to the HMAC algorithm and returns the hash value as a PKCS-1 digestinfo block.
CLASS Crypto.RSA |
Gmp.mpz get_n()
Returns the RSA modulo.
Gmp.mpz get_e()
Returns the RSA public exponent.
Gmp.mpz get_d()
Returns the RSA private exponent (if known).
Gmp.mpz get_p()
Returns the first RSA prime (if known).
Gmp.mpz get_q()
Returns the second RSA prime (if known).
string cooked_get_n()
Returns the RSA modulo as a binary string.
string cooked_get_e()
Returns the RSA public exponent as a binary string.
string cooked_get_d()
Returns the RSA private exponent (if known) as a binary string.
string cooked_get_p()
Returns the first RSA prime (if known) as a binary string.
string cooked_get_q()
Returns the second RSA prime (if known) as a binary string.
this_program set_public_key(Gmp.mpz|int modulo, Gmp.mpz|int pub)
Sets the public key.
this_program set_private_key(Gmp.mpz|int priv, array(Gmp.mpz|int)|void extra)
Sets the private key.
|
int query_blocksize()
Returns the crypto block size, or zero if not yet set.
Gmp.mpz rsa_pad(string message, int(1..2) type, function(int:string)|void random)
Pads the message to the current block size with method type and returns the result as an integer.
|
string rsa_unpad(Gmp.mpz block, int type)
Reverse the effect of rsa_pad .
Gmp.mpz raw_sign(string digest)
Pads the digest with rsa_pad type 1 and signs it.
string cooked_sign(string digest)
Signs digest as raw_sign and returns the signature as a byte string.
int(0..1) raw_verify(string digest, Gmp.mpz s)
Verifies the digest against the signature s , assuming pad type 1.
rsa_pad , raw_sign
string encrypt(string s, function(int:string)|void r)
Pads the message s with rsa_pad type 2, signs it and returns the signature as a byte string.
Optional random function to be passed down to rsa_pad .
string decrypt(string s)
Decrypt a message encrypted with encrypt .
int(0..) rsa_size()
Returns the size of the key in terms of number of bits.
int(0..1) public_key_equal(this_program rsa)
Compares the public key of this RSA object with another RSA object.
Gmp.mpz sign(string message, .Hash h)
Signs the message with a PKCS-1 signature using hash algorithm h .
int(0..1) verify(string msg, .Hash h, Gmp.mpz sign)
Verify PKCS-1 signature sign of message msg using hash algorithm h .
string sha_sign(string message, mixed|void r)
Document this function.
int sha_verify(string message, string signature)
Document this function.
string md5_sign(string message, mixed|void r)
Document this function.
int md5_verify(string message, string signature)
Document this function.
Gmp.mpz get_prime(int bits, function(int:string) r)
Generate a prime with bits number of bits using random function r .
this_program generate_key(int(128..) bits, function(int:string)|void r)
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.
this_program set_encrypt_key(array(Gmp.mpz) key)
Sets the public key to key and the mode to encryption.
set_decrypt_key , crypt
this_program set_decrypt_key(array(Gmp.mpz) key)
Sets the public key to key and the mod to decryption.
set_encrypt_key , crypt
string crypt(string s)
Encrypt or decrypt depending on set mode.
set_encrypt_key , set_decrypt_key
string name()
Returns the string "RSA"
.
CLASS Crypto.Substitution |
Implements a simple substitution crypto, ie. one of the first crypto systems ever invented and thus one of the least secure ones available.
this_program set_key(mapping(string:string|array(string)) key)
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.
An error is thrown if the encryption key can not be made reversible.
this_program set_null_chars(int|float p, array(string) chars)
Set null characters (fillers). Characters from chars will be inserted into the output stream with a probability p .
A float between 0.0 and 1.0 or an integer between 0 and 100.
An array of one character strings.
this_program set_rot_key(void|int steps, void|array(string) alphabet)
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.
this_program set_ACA_K1_key(string key, void|int offset, void|array(string) alphabet)
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.
this_program set_ACA_K2_key(string key, void|int offset, void|array(string) alphabet)
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.
this_program set_ACA_K3_key(string key, int offset, void|array(string) alphabet)
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.
this_program set_ACA_K4_key(string key1, string key2, void|int offset, void|array(string) alphabet)
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.
string encrypt(string m)
Encrypts the message m .
string decrypt(string c)
Decrypts the cryptogram c .
string filter(string m, void|multiset(int) save)
Removes characters not in the encryption key or in the save multiset from the message m .
CLASS Crypto.CBC |
Implementation of the cipher block chaining mode (CBC). Works as a wrapper for the cipher algorithm put in create.
void Crypto.CBC(program|object|function cipher, mixed ... args)
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.
string name()
Returns the string "CBC(x)"
where x is the
encapsulated algorithm.
int block_size()
Reurns the block size of the encapsulated cipher.
int key_size()
Returns the key size of the encapsulated cipher.
this_program set_encrypt_key(string key)
Prepare the cipher and the wrapper for encrypting with the given key .
this_program set_decrypt_key(string key)
Prepare the cipher and the wrapper for decrypting with the given key .
this_program set_iv(string iv)
Set the initialization vector to iv .
string crypt(string data)
Encrypt/decrypt data and return the result. data must be an integral number of blocks.
CLASS Crypto.Buffer |
Acts as a buffer so that data can be fed to a cipher in blocks that doesn't correspond to cipher block sizes.
void Crypto.Buffer(program|object|function cipher, mixed ... args)
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.
string name()
Returns the string "CBC(x)"
where x is the
encapsulated algorithm.
int block_size()
Get the block size of the contained block crypto.
int key_size()
Get the key size of the contained block crypto.
this_program set_encrypt_key(string key)
Set the encryption key.
As a side-effect any buffered data will be cleared.
this_program set_decrypt_key(string key)
Set the decryption key.
As a side-effect any buffered data will be cleared.
string crypt(string data)
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.
string pad()
Pad and de/encrypt any data left in the buffer.
unpad()
string unpad(string data)
De/encrypt and unpad a block of data.
This performs the reverse operation of pad() .
pad()
Module Crypto.NT |
CLASS Crypto.NT.CryptContext |
Class representing an HCRYPTPROV handle.
void Crypto.NT.CryptContext(string name, string csp, int type, int flags)
Key container name. When flags is set to CRYPT_VERIFYCONTEXT
the name must be 0
.
The name of the Crypto Service Provider to use. If set to
0
the user default CSP will be used.
string read(int size, string|void init)
Retreive some random data. Calls CryptGenRandom in the NT API.
Module Crypto.AES |
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 Nettle.AES_Info : AES_Info
inherit .Cipher : Cipher
Module Crypto.Arcfour |
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 Nettle.ARCFOUR_Info : ARCFOUR_Info
inherit .Cipher : Cipher
Module Crypto.Blowfish |
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 Nettle.BLOWFISH_Info : BLOWFISH_Info
inherit .Cipher : Cipher
Module Crypto.CAST |
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 Nettle.CAST128_Info : CAST128_Info
inherit .Cipher : Cipher
Module Crypto.DES |
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 Nettle.DES_Info : DES_Info
inherit .Cipher : Cipher
Module Crypto.DES3 |
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 Nettle.DES3_Info : DES3_Info
inherit .Cipher : Cipher
Module Crypto.IDEA |
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 Nettle.IDEA_Info : IDEA_Info
inherit .Cipher : Cipher
Module Crypto.MD2 |
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 Nettle.MD2_Info : MD2_Info
inherit .Hash : Hash
Module Crypto.MD4 |
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 Nettle.MD4_Info : MD4_Info
inherit .Hash : Hash
Module Crypto.MD5 |
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 Nettle.MD5_Info : MD5_Info
inherit .Hash : Hash
Module Crypto.PGP |
PGP stuff. See RFC 2440.
mapping(string:string|mapping) Crypto.PGP.decode(string s)
Decodes PGP data.
int Crypto.PGP.verify_signature(string text, string sig, string pubkey)
Verify text against signature sig with the public key pubkey .
string Crypto.PGP.encode_radix64(string data, string type, void|mapping(string:string) extra)
Encode PGP data with ASCII armour.
mapping(string:mixed) Crypto.PGP.decode_radix64(string data)
Decode ASCII armour.
Module Crypto.Random |
This module contains stuff to that tries to give you the best possible random generation.
string Crypto.Random.random_string(int len)
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.
Gmp.mpz Crypto.Random.random(int top)
Returns a Gmp.mpz object with a random value between 0
and top . Uses random_string .
string Crypto.Random.blocking_random_string(int len)
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.
void Crypto.Random.add_entropy(string data, int entropy)
Inject additional entropy into the random generator.
The random string.
The number of bits in the random string that is truely random.
Module Crypto.SHA256 |
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 Nettle.SHA256_Info : SHA256_Info
inherit .Hash : Hash
Module Crypto.Serpent |
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 Nettle.Serpent_Info : Serpent_Info
inherit .Cipher : Cipher
Module Crypto.Twofish |
Another AES finalist, this one designed by Bruce Schneier and others.
inherit Nettle.Twofish_Info : Twofish_Info
inherit .Cipher : Cipher
Module Crypto.SHA1 |
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 Nettle.SHA1_Info : SHA1_Info
inherit .Hash : Hash
Module Crypto.Koremutake |
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.
string Crypto.Koremutake.encrypt(int m)
Encode an integer as a koremutake string.
int Crypto.Koremutake.decrypt(string c)
Decode a koremutake string into an integer.
Module SDL |
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.
void SDL.init(int flags)
Initializes SDL. This should be called before all other SDL functions.
The flags parameter specifies what part(s) of SDL to initialize. It can be one of many of the following ORed together.
Initializes the timer subsystem.
Initializes the audio subsystem.
Initializes the video subsystem.
Initializes the cdrom subsystem.
Initializes the joystick subsystem.
Initialize all of the above.
Prevents SDL from catching fatal signals.
Run event polling in a separate thread. Not always supported.
SDL.quit() , SDL.init_sub_system() , SDL.quit_sub_system()
void|string SDL.get_error()
Get the last internal SDL error.
The error string, or zero if there was no error.
void SDL.init_sub_system(int flags)
After SDL has been initialized with init() you may initialize uninitialized subsystems with this method.
The same as what is used in SDL.init() .
void SDL.init_sub_system(int flags)
After SDL has been initialized with SDL.init() you may initialize uninitialized subsystems with this method.
a bitwise OR'd combination of the subsystems you wish to check (see SDL.init() for a list of subsystem flags).
SDL.init() , SDL.quit() , SDL.quit_sub_system()
int SDL.was_init(int flags)
This method allows you to see which SDL subsytems have been initialized.
a bitwise OR'd combination of the subsystems you wish to check (see SDL.init() for a list of subsystem flags).
a bitwised OR'd combination of the initialized subsystems
SDL.init() , SDL.init_sub_system()
void SDL.quit()
Shuts down all SDL subsystems and frees the resources allocated to them. This should always be called before you exit.
You can use the atexit() method to ensure that this method is always called when Pike exits normally.
SDL.init() , SDL.init_sub_system() , SDL.quit_sub_system()
int SDL.enable_unicode(int enable)
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.
A value of 1 enables Unicode translation, 0 disables it and -1 leaves it unchanged (useful for querying the current translation mode).
The previous translation mode (1 enabled, 0 disabled). If enable is -1, the return value is the current translation mode.
SDL.Keysym
int SDL.get_mod_state()
Returns the current state of the modifier keys (CTRL, ALT, etc.).
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
SDL.get_key_state()
string SDL.get_key_state()
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.
SDL.pump_events() to update the state array.
int SDL.video_mode_ok(int width, int height, int bpp, int flags)
Document this function
int SDL.flip(SDL.Surface|void screen)
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.
The screen object to flip. If missing, the default screen is used.
This function returns 1 if successful, or 0 if there was an error.
SDL.update_rect()
void SDL.update_rect(int x, int y, int w, int h, SDL.Surface|void screen)
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.
Top left corner of the rectangle to update.
Width and height of the rectangle to update.
The screen object to flip. If missing, the default screen is used.
SDL.flip()
int SDL.set_gamma(float red, float green, float blue)
Document this function
void|object SDL.get_video_surface()
Document this function
void|object SDL.get_video_info()
Document this function
void SDL.gl_set_attribute(int attribute, int value)
Document this function
void SDL.gl_get_attribute(int attribute)
Document this function
int SDL.show_cursor(int show)
Document this function
void SDL.warp_mouse(int xpos, int ypos)
Document this function
void SDL.gl_swap_buffers()
Document this function
object SDL.set_video_mode(int width, int height, int bpp, int flags)
Document this function
int SDL.blit_surface(SDL.Surface src, SDL.Surface dst, SDL.Rect srcrect, SDL.Rect dstrect)
Document this function
void|string SDL.video_driver_name()
Document this function
void SDL.set_caption(string title, string icon)
Document this function
array(string) SDL.get_caption()
Document this function
int SDL.iconify_window()
Document this function
int SDL.toggle_fullscreen(void|SDL.Surface screen)
Document this function
int SDL.grab_input(int mode)
Document this function
int SDL.num_joysticks()
Document this function
string SDL.joystick_name(int device_index)
Document this function
int SDL.joystick_opened(int device_index)
Document this function
void SDL.joystick_update()
Document this function
int SDL.joystick_event_state(int state)
Document this function
int SDL.cd_num_drivers()
Document this function
string|void SDL.cd_name(int drive)
Document this function
void SDL.open_audio(int frequency, int format, int channels, int bufsize)
Document this function
CLASS SDL.Rect |
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
Position of the upper-left corner of the rectangle.
int w
int h
The width and height of the rectangle.
mixed cast(string type)
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 |
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.
UNICODE translation does have a slight overhead so don't enable it unless its needed.
int scancode
Hardware specific scancode
int sym
SDL virtual keysym
int mod
Current key modifiers
int unicode
Translated character
CLASS SDL.PixelFormat |
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.
int bits_per_pixel
The number of bits used to represent each pixel in a surface. Usually 8, 16, 24 or 32.
int bytes_per_pixel
The number of bytes used to represent each pixel in a surface. Usually one to four.
int rmask
int gmask
int bmask
int amask
Binary mask used to retrieve individual color values.
int rloss
int gloss
int bloss
int aloss
Precision loss of each color component.
int rshift
int gshift
int bshift
int ashift
Binary left shift of each color component in the pixel value.
int colorkey
Pixel value of transparent pixels.
int alpha
Overall surface alpha value.
array(int) losses()
Convenience method returning the RGBA precision loss as an array.
array(int) masks()
Convenience method returning the RGBA masks as an array.
array(int) shifts()
Convenience method returning the RGBA shifts as an array.
int map_rgb(int r, int g, int b)
int map_rgb(Image.Color.Color color)
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).
The red, green and blue components specified as an integer between 0 and 255.
The color as represented by an Image.Color.Color object.
A pixel value best approximating the given RGB color value for a given pixel format.
map_rgba() , get_rgb() , get_rgba()
int map_rgba(int r, int g, int b, int a)
int map_rgba(Image.Color.Color color, int a)
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).
The red, green and blue components specified as an integer between 0 and 255.
The color as represented by an Image.Color.Color object.
A pixel value best approximating the given RGB color value for a given pixel format.
map_rgb() , get_rgb() , get_rgba()
Image.Color.Color get_rgb(int pixel)
Get RGB component values from a pixel stored in this pixel format.
A pixel retrieved from a surface with this pixel format or a color previously mapped with map_rgb() or map_rgba() .
A Image.Color.Color object with the RGB components of the pixel.
map_rgb() , map_rgba() , get_rgba()
mapping(string:Image.Color.Color|int) get_rgba(int pixel)
Get RGB component values from a pixel stored in this pixel format.
A pixel retrieved from a surface with this pixel format or a color previously mapped with map_rgb() or map_rgba() .
A mapping containing with the RGBA components of the pixel as described below.
|
map_rgb() , map_rgba() , get_rgb()
CLASS SDL.VideoInfo |
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.
int blit_hw_cc
Are hardware to hardware colorkey blits accelerated?
int blit_hw_a
Are hardware to hardware alpha blits accelerated?
int blit_sw
Are software to hardware blits accelerated?
int blit_sw_cc
Are software to hardware colorkey blits accelerated?
int blit_sw_a
Are software to hardware alpha blits accelerated?
int blit_fill
Are color fills accelerated?
int video_mem
Total amount of video memory in KB.
SDL.PixelFormat format
Pixel format of the video device.
CLASS SDL.Surface |
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
The width and height of the surface in pixels.
SDL.Rect clip_rect
This is the clipping rectangle as set by set_clip_rect() .
int flags
The following are supported in the flags field.
Surface is stored in system memory
Surface is stored in video memory
Surface uses asynchronous blits if possible.
Allows any pixel-format (Display surface).
Surface has exclusive palette.
Surface is double buffered (Display surface).
Surface is full screen (Display Sur face).
Surface has an OpenGL context (Display Surface).
Surface supports OpenGL blitting (Display Surface).
Surface is resizable (Display Surface).
Surface blit uses hardware acceleration.
Surface use colorkey blitting.
Colorkey blitting is accelerated with RLE.
Surface blit uses alpha blending.
Surface uses preallocated memory.
SDL.PixelFormat format
The pixel format of this surface.
int get_pixel(int x, int y)
Get the value of the specified pixel. The surface needs to be locked before this method can be used.
Pixel coordinate to get.
The value of the specified pixel.
set_pixel() , unlock() , lock()
int set_pixel(int x, int y, int pixel)
Set the value of the specified pixel. The surface needs to be locked before this method can be used.
Pixel coordinate to modify.
Pixel value to set to the specified pixel.
A reference to the surface itself.
get_pixel() , unlock() , lock()
int lock()
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.
Calling this method multiple times means that you need to call unlock an equal number of times for the surface to become unlocked.
1 for success or 0 if the surface couldn't be locked.
unlock() , set_pixel() , get_pixel()
void unlock()
Surfaces that were previously locked using lock() must be unlocked with unlock() . Surfaces should be unlocked as soon as possible.
lock()
SDL.Surface init(int flags, int width, int height, int depth, int Rmask, int Gmask, int Bmask, int Amask)
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 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 will attempt to create the surface in video memory. This will allow SDL to take advantage of Video->Video blits (which are often accelerated).
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.
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.
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.
A reference to itself.
If this method fails, the surface will become uninitialized.
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)
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() .
The source image.
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.
When present this specifies the type of surface that should be created. It is an OR'd combination of the following possible values:
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 will attempt to create the surface in video memory. This will allow SDL to take advantage of Video->Video blits (which are often accelerated).
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.
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.
If this method fails, the surface will become uninitialized.
A reference to itself.
init()
SDL.Surface display_format()
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() .
The new surface. An error is thrown if the conversion fails.
SDL.Surface display_format_alpha()
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.
The new surface. An error is thrown if the conversion fails.
object blit(SDL.Surface dst, SDL.Rect|void srcrect, SDL.Rect|void dstrect)
Document this function
object fill_rect(int color, SDL.Rect dstrect)
Document this function
object fill(int color)
Document this function
object set_color_key(int flag, int key)
Document this function
object set_alpha(int flag, int alpha)
Document this function
object set_clip_rect(SDL.Rect rect)
Document this function
object convert_surface(SDL.PixelFormat fmt, int flags)
Document this function
CLASS SDL.Joystick |
void SDL.Joystick(int device_index)
Document this function
int index()
Document this function
int num_axes()
Document this function
int num_balls()
Document this function
int num_hats()
Document this function
int num_buttons()
Document this function
float get_axis(int axis)
Document this function
int get_hat(int hat)
Document this function
array(int) get_ball(int ball)
Document this function
int get_button(int button)
Document this function
string name()
Document this function
CLASS SDL.CDTrack |
int id
int length
int offset
int type
Document this variable
CLASS SDL.CD |
void SDL.CD(int drive)
Document this function
int current_frame
int current_track
int id
int numtracks
Document this variable
CDTrack track(int track)
Document this function
int status()
Document this function
int play(int start, int length)
Document this function
int play_tracks(int start_track, int start_frame, int ntracks, int nframes)
Document this function
int pause()
Document this function
int resume()
Document this function
int stop()
Document this function
int eject()
Document this function
CLASS SDL.Music |
void SDL.Music(string fname)
Document this function
object pause()
Document this function
object halt()
Document this function
object resume()
Document this function
object rewind()
Document this function
int paused()
Document this function
int playing()
Document this function
int fading()
Document this function
object play(int|void loops)
Document this function
object fade_in(int ms, int|void loops)
Document this function
object fade_out(int ms)
Document this function
float set_volume(float vol)
Document this function
float volume()
Document this function
CLASS SDL.Event |
int get()
Document this function
int wait()
Document this function
int poll()
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 |
This is an interface that all Throttler s must implement. It's not an actual class in this module.
void request(Shuffle shuffle, int amount, function(int:void) callback)
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.
void give_back(Shuffle shuffle, int amount)
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 |
This class contains the state for one ongoing data shuffling operation. To create a Shuffle instance, use the Shuffler()->shuffle method.
Shuffler shuffler
The Shuffler that owns this Shuffle object
Throttler throttler
The Throttler that is associated with this Shuffle object, if any.
void set_throttler(Throttler t)
Calling this function overrides the Shuffler global throttler.
int sent_data()
Returns the amount of data that has been sent so far.
int state()
Returns the current state of the shuffler. This is one of the following: INITIAL , RUNNING , PAUSED , DONE , WRITE_ERROR , READ_ERROR and USER_ABORT
void set_done_callback(function(Shuffle:void) cb)
Sets the done callback. This function will be called when all sources have been processed, or if an error occurs.
void set_request_arg(mixed arg)
Sets the extra argument sent to Throttler()->request() and Throttler()->give_back .
void send_more_callback(int amount)
void write_callback(mixed|void x)
void Shuffler.Shuffle(object fd, object shuffler, mixed throttler, mixed backend)
void start()
Start sending data from the sources.
void pause()
Temporarily pause all data transmission
void stop()
Stop all data transmission, and then call the done callback
void add_source(mixed source, int|void start, int|void length)
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
An ordinary 8-bit wide pike string.
An initialized instance of the System.Memory class.
Stdio.File instance pointing to a normal file.
Stdio.File instance pointing to a stream of some kind (network socket, named pipe, stdin etc).
Stdio.File lookalike with read callback support (set_read_callback and set_close_callback).
CLASS Shuffler.Shuffler |
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.
void set_backend(Pike.Backend b)
Set the backend that will be used by all Shuffle objects created from this shuffler.
void set_throttler(Throttler t)
Set the throttler that will be used in all Shuffle objects created from this shuffler, unless overridden in the Shuffle objects.
void pause()
Pause all Shuffle objects associated with this Shuffler
void start()
Unpause all Shuffle objects associated with this Shuffler
Shuffle shuffle(Stdio.File destination)
Create a new Shuffle object.
Module Unicode |
array(string) Unicode.split_words(string input)
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.
array(string) Unicode.split_words_and_normalize(string input)
A less wasteful equivalent of split_words (normalize (input )).
string Unicode.normalize(string data, string method)
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')
int Unicode.is_wordchar(int c)
Returns whether a unicode character c is a word, part of a word or not.
|
Module CommonLog |
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.
int CommonLog.read(function(array(int|string):void) callback, Stdio.File|string logfile, void|int offset)
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.
The callbacks first argument is an array with the different parts of the log entry.
|
The second callback argument is the current offset to the end of the current line.
The position in the file where the parser should begin.
Module DVB |
Implements Digital Video Broadcasting interface
Only Linux version is supported.
CLASS DVB.dvb |
Main class.
void DVB.dvb(int card_number)
Create a DVB object.
The number of card equipment.
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+
mapping|int fe_status()
Return status of a DVB object's frondend device.
The resulting mapping contains the following fields:
|
mapping fe_info()
Return info of a frondend device.
The information heavily depends on driver. Many fields contain dumb values.
int tune(int(0..3) lnb, int freq, int(0..1)|string pol, int sr)
Tunes to apropriate transponder's parameters.
DiSeQc number of LNB.
Frequency divided by 1000.
Polarization. 0
or "v"
for vertical type,
1
or "h"
for horizontal one.
The service rate parameter.
mapping|int get_pids()
Returns mapping with info of currently tuned program's pids.
tune()
mapping analyze_pat()
Return mapping of all PMT.
sid:prognum
array(mapping)|int analyze_pmt(int sid, int prognum)
Parse PMT table.
analyze_pat()
DVB.Stream stream(int pid, int|function rcb, int ptype)
DVB.Stream stream(int pid, int|function rcb)
DVB.Stream stream(int pid)
Create a new stream reader object for PID.
PID of stream.
Callback function called whenever there is the data to read from stream. Only for nonblocking mode.
Type of payload data to read. By default, audio data is fetched.
Setting async callback doesn't set the object to nonblocking state.
DVB.Stream()->read()
CLASS DVB.Stream |
Represents an elementary data stream (PES).
int destroy()
Purge a stream reader.
DVB.dvb()->stream() , read()
string|int read()
Read data from a stream. It reads up to read buffer size data.
Read buffer size is 4096 by default.
DVB.dvb()->stream() , close()
void close()
Closes an open stream.
read()
CLASS DVB.Audio |
Object for controlling an audio subsystem on full featured cards.
void DVB.Audio(int card_number)
void DVB.Audio()
Create a Audio object.
The number of card equipment.
int mute(int mute)
int mute()
Mute or unmute audio device.
mapping status()
Returns mapping of current audio device status.
int mixer(int left, int right)
int mixer(int both)
Sets output level on DVB audio device.
Module Locale |
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.
// 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; }
void Locale.register_project(string name, string path, void|string path_base)
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.
void Locale.set_default_project_path(string path)
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.
array(string) Locale.list_languages(string project)
Returns a list of all registered languages for a specific project.
mapping(string:object) Locale.get_objects(string lang)
Reads in and returns a mapping with all the registred projects' LocaleObjects in the language 'lang'
string Locale.translate(string project, string lang, string|int id, string fallback)
Returns a translation for the given id, or the fallback string
function Locale.call(string project, string lang, string name, void|function|string fb)
Returns a localized function If function not found, tries fallback function fb, or fallback language fb instead
CLASS Locale.DeferredLocale |
This class simulates a multi-language "string". The actual language to use is determined as late as possible.
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)
array get_identifier()
Return the data nessesary to recreate this "string".
Module Locale.Gettext |
This module enables access to localization functions from within Pike.
string Locale.Gettext.gettext(string msg)
string Locale.Gettext.gettext(string msg, string domain)
string Locale.Gettext.gettext(string msg, string domain, int category)
Message to be translated.
Domain from within the message should be translated. Defaults to the current domain.
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.
Prior to Pike 7.3 this function only accepted one argument, and the other functionality was provided by dgettext() and dcgettext() .
bindtextdomain , textdomain , setlocale , localeconv
string Locale.Gettext.dgettext(string domain, string msg)
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.
Obsoleted by gettext() in Pike 7.3.
bindtextdomain , textdomain , gettext , setlocale , localeconv
string Locale.Gettext.dcgettext(string domain, string msg, int category)
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.
Obsoleted by gettext() in Pike 7.3.
bindtextdomain , textdomain , gettext , setlocale , localeconv
string Locale.Gettext.textdomain(void|string domain)
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() .
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.
bindtextdomain , gettext , setlocale , localeconv
string Locale.Gettext.bindtextdomain(string|void domainname, string|void dirname)
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.
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.
textdomain , gettext , setlocale , localeconv
int Locale.Gettext.setlocale(int category, string locale)
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 1 if the locale setting successed, 0 for failure
bindtextdomain , textdomain , gettext , dgettext , dcgettext , localeconv
mapping Locale.Gettext.localeconv()
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 .
|
bindtextdomain , textdomain , gettext , dgettext , dcgettext , setlocale
constant Locale.Gettext.LC_ALL
Locale category for all of the locale.
constant Locale.Gettext.LC_COLLATE
Locale category for the functions strcoll() and strxfrm() (used by pike, but not directly accessible).
constant Locale.Gettext.LC_CTYPE
Locale category for the character classification and conversion routines.
constant Locale.Gettext.LC_MESSAGES
Document this constant.
This category isn't available on all platforms.
constant Locale.Gettext.LC_MONETARY
Locale category for localeconv().
constant Locale.Gettext.LC_NUMERIC
Locale category for the decimal character.
constant Locale.Gettext.LC_TIME
Locale category for strftime() (currently not accessible from Pike).
Module Locale.Language |
CLASS Locale.Language.abstract |
Abstract language locale class, inherited by all the language locale classes.
constant months
Array(string) with the months of the year, beginning with January.
constant days
Array(string) with the days of the week, beginning with Sunday.
constant iso_639_1
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
String with the language code in ISO-639-2/T (three character code).
constant iso_639_2B
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
The name of the language in english.
constant name
The name of the langauge. E.g. "svenska" for Swedish.
constant languages
Mapping(string:string) that maps an ISO-639-2/T id code to the name of that language.
string month(int(1..12) num)
Returns the name of month number num .
string day(int(1..7) num)
Returns the name of weekday number num .
string number(int i)
Returns the number i as a string.
string ordered(int i)
Returns the ordered number i as a string.
string date(int timestamp, string|void mode)
Returns the date for posix time timestamp as a textual string.
Determines what kind of textual string should be produced.
|
> Locale.Language.eng()->date(time()); Result: "today, 06:36"
Module Locale.Language.cat |
Catalan language locale.
inherit "abstract"
Module Locale.Language.ces |
Czech language locale by Jan Petrous 16.10.1997, based on Slovenian language module by Iztok Umek.
inherit "abstract"
Module Locale.Language.deu |
German language locale by Tvns Böker.
inherit "abstract"
Module Locale.Language.eng |
English language locale.
inherit "abstract"
Module Locale.Language.fin |
Finnish language locale created by Janne Edelman, Turku Unix Users Group ry, Turku, Finland
inherit "abstract"
Module Locale.Language.fra |
French language locale by Patrick Kremer.
inherit "abstract"
Module Locale.Language.hrv |
Croatian language locale by Klara Makovac 1997/07/02
inherit "abstract"
Module Locale.Language.hun |
Hungarian language locale by Zsolt Varga.
inherit "abstract"
Module Locale.Language.ita |
Italian language locale by Francesco Chemolli
inherit "abstract"
Module Locale.Language.jpn |
Japanese language locale.
inherit "abstract"
Module Locale.Language.mri |
Maaori (New Zealand) language locale by Jason Rumney
inherit "abstract"
Module Locale.Language.nld |
Dutch language locale by Stephen R. van den Berg
inherit "abstract"
Module Locale.Language.nor |
Norwegian language locale
inherit "abstract"
Module Locale.Language.pol |
Polish language locale by Piotr Klaban.
inherit "abstract"
Module Locale.Language.por |
Portuguese language locale
inherit "abstract"
Module Locale.Language.rus |
Russian language locale
inherit "abstract"
Module Locale.Language.slv |
Slovenian language locale by Iztok Umek 7. 8. 1997
inherit "abstract"
Module Locale.Language.spa |
Spanish language locale
inherit "abstract"
Module Locale.Language.srp |
Serbian language locale by Goran Opacic 1996/12/11
inherit "abstract"
Module Locale.Language.swe |
Swedish language locale
inherit "abstract"
Module Locale.Charset |
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:
UTF encodings
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:
These may be prefixed with "cp"
or "ibm"
.
These may be prefixed with "cp"
, "ibm"
or
"windows"
.
+359 more.
Decoder Locale.Charset.decoder(string name)
Returns a charset decoder object.
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.
If the asked-for name was not supported, an error is thrown.
Encoder Locale.Charset.encoder(string name, string|void replacement, function(string:string)|void repcb)
Returns a charset encoder object.
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.
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.
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.
If the asked-for name was not supported, an error is thrown.
Decoder Locale.Charset.decoder_from_mib(int mib)
Returns a decoder for the encoding schema denoted by MIB mib .
Encoder Locale.Charset.encoder_from_mib(int mib, string|void replacement, function(string:string)|void repcb)
Returns an encoder for the encoding schema denoted by MIB mib .
CLASS Locale.Charset.Decoder |
Virtual base class for charset decoders.
string win1252_to_string( string data ) { return Locale.Charset.decoder("windows-1252")->feed( data )->drain(); }
this_program feed(string s)
Feeds a string to the decoder.
String to be decoded.
Returns the current object, to allow for chaining of calls.
string drain()
Get the decoded data, and reset buffers.
Returns the decoded string.
this_program clear()
Clear buffers, and reset all state.
Returns the current object to allow for chaining of calls.
CLASS Locale.Charset.Encoder |
Virtual base class for charset encoders.
inherit Decoder : Decoder
An encoder only differs from a decoder in that it has an extra function.
void set_replacement_callback(function(string:string) rc)
Change the replacement callback function.
Function that is called to encode characters outside the current character encoding.
Module Gmp |
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/
Gmp.mpz Gmp.fac(int x)
Returns the factorial of x (x !).
CLASS Gmp.bignum |
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 |
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.
void Gmp.mpz()
void Gmp.mpz(string|int|float|object value)
void Gmp.mpz(string value, int(2..36)|int(256..256) base)
Create and initialize a Gmp.mpz object.
Initial value. If no value is specified, the object will be initialized to zero.
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.
Leading zeroes in value are not significant. In particular leading NUL characters are not preserved in base 256 mode.
int cast_to_int()
int __hash()
float cast_to_float()
string cast_to_string()
string digits(void|int(2..36)|int(256..256) base)
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.
cast_to_string
string _sprintf(int ind, mapping opt)
int(0..1) _is_type(string type)
int size(void|int base)
This function returns how long the mpz would be represented in the specified base . The default base is 2.
mixed cast(string type)
It is possible to cast an mpz to a string, int or float.
cast_to_int , cast_to_float , cast_to_string
Gmp.mpz `+(int|float|Gmp.mpz ... x)
Gmp.mpz ``+(int|float|Gmp.mpz ... x)
Gmp.mpz `+=(int|float|Gmp.mpz ... x)
Gmp.mpz `*(int|float|Gmp.mpz ... x)
Gmp.mpz ``*(int|float|Gmp.mpz ... x)
Gmp.mpz `*=(int|float|Gmp.mpz ... x)
Gmp.mpz gcd(object|int|float|string arg)
This function returns the greatest common divisor for arg and mpz.
Gmp.mpz `-(int|float|Gmp.mpz ... x)
Gmp.mpz ``-(int|float|Gmp.mpz ... x)
Gmp.mpz `/(int|float|Gmp.mpz ... x)
Gmp.mpz ``/(int|float|Gmp.mpz ... x)
Gmp.mpz `%(int|float|Gmp.mpz ... x)
Gmp.mpz ``%(int|float|Gmp.mpz ... x)
array(Gmp.mpz) gcdext(int|float|Gmp.mpz x)
array(Gmp.mpz) gcdext2(int|float|Gmp.mpz x)
Gmp.mpz invert(int|float|Gmp.mpz x)
Gmp.mpz `&(int|float|Gmp.mpz ... x)
Gmp.mpz `|(int|float|Gmp.mpz ... x)
Gmp.mpz `^(int|float|Gmp.mpz ... x)
Gmp.mpz `~()
int(0..1) `>(mixed with)
int(0..1) `<(mixed with)
int(0..1) `>=(mixed with)
int(0..1) `<=(mixed with)
int(0..1) `==(mixed with)
int(0..1) `!=(mixed with)
int(0..1) probably_prime_p()
This function returns 1 if mpz is a prime, and 0 most of the time if it is not.
int small_factor(void|int(1..) limit)
Gmp.mpz next_prime(void|int count, void|int limit)
int sgn()
Gmp.mpz sqrt()
This function return the the truncated integer part of the square root of the value of mpz.
array(Gmp.mpz) sqrtrem()
Gmp.mpz `<<(int|float|Gmp.mpz x)
Gmp.mpz `>>(int|float|Gmp.mpz x)
Gmp.mpz ``<<(int|float|Gmp.mpz x)
Gmp.mpz ``>>(int|float|Gmp.mpz x)
Gmp.mpz powm(int|string|float|Gmp.mpz a, int|string|float|Gmp.mpz b)
This function returns ( mpz ** a ) % b.
Gmp.mpz pow(int|float|Gmp.mpz x)
int(0..1) `!()
int popcount()
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.
Gmp.mpz _random()
CLASS Gmp.mpf |
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.
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)
int __hash()
int|object get_int()
float get_float()
Returns the value of the object as a float.
string get_string()
string _sprintf(int c, mapping flags)
int(0..1) _is_type(string arg)
The Gmp.mpf object will claim to be a "float"
.
Perhaps it should also return true for "object"
?
mixed cast(string to)
Gmp.mpf `+(int|float|object ... a)
Gmp.mpf `+=(int|float|object ... a)
Gmp.mpf set_precision(int(0..) prec)
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.
int(0..) get_precision()
Returns the current precision, in bits.
Gmp.mpf `*(int|float|object ... a)
Gmp.mpf ``*(int|float|object ... a)
Gmp.mpf `*=(int|float|object ... a)
Gmp.mpf `-(int|float|object ... a)
Gmp.mpf ``-(int|float|object sv)
Gmp.mpf `/(int|float|object ... a)
Gmp.mpf ``/(int|float|object sv)
Gmp.mpf `~()
int(0..1) `>(mixed q)
int(0..1) `<(mixed q)
int(0..1) `>=(mixed q)
int(0..1) `<=(mixed q)
int(0..1) `==(mixed q)
int(0..1) `!=(mixed q)
int sgn()
int(0..1) `!()
CLASS Gmp.mpq |
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.
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)
int get_int()
int __hash()
float get_float()
string get_string()
string _sprintf(int c, mapping flags)
int(0..1) _is_type(string arg)
int|string|float|object cast(string s)
Gmp.mpq `+(int|float|object ... a)
Gmp.mpq ``+(int|float|object ... a)
Gmp.mpq `+=(int|float|object ... a)
Gmp.mpq `*(int|float|object ... a)
Gmp.mpq ``*(int|float|object ... a)
Gmp.mpq `*=(int|float|object ... a)
Gmp.mpq `-(int|float|object ... a)
Gmp.mpq ``-(int|float|object sv)
Gmp.mpq `/(int|float|object ... a)
Gmp.mpq ``/(int|float|object sv)
Gmp.mpq `%(int|float|object ... a)
a%b = a - floor(a/b)*b
Gmp.mpq ``%(int|float|object a)
Gmp.mpq invert()
Gmp.mpq `~()
Defined as -1-x
.
int(0..1) `>(mixed q)
int(0..1) `<(mixed q)
int(0..1) `>=(mixed q)
int(0..1) `<=(mixed q)
int(0..1) `==(mixed q)
int(0..1) `!=(mixed q)
int(-1..1) sgn()
int(0..1) `!(mixed q)
Module Gz |
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 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 "___"
int Gz.crc32(string data, void|int start_value)
This function calculates the standard ISO3309 Cyclic Redundancy Check.
CLASS Gz._file |
Low-level implementation of read/write support for GZip files
int open(string|int|Stdio.Stream file, void|string mode)
Opens a file for I/O.
The filename or an open filedescriptor or Stream for the GZip file to use.
Mode for the fileoperations. Defaults to read only.
If the object already has been opened, it will first be closed.
void Gz._file(void|string|Stdio.Stream gzFile, void|string mode)
Opens a gzip file for reading.
int close()
closes the file
1 if successful
int|string read(int len)
Reads len (uncompressed) bytes from the file. If read is unsuccessful, 0 is returned.
int write(string data)
Writes the data to the file.
the number of bytes written to the file.
int seek(int pos, void|int type)
Seeks within the file.
Position relative to the searchtype.
SEEK_SET = set current position in file to pos SEEK_CUR = new position is current+pos SEEK_END is not supported.
New position or negative number if seek failed.
int tell()
the current position within the file.
int(0..1) eof()
1 if EOF has been reached.
int setparams(int level, int strategy)
Sets the encoding level and strategy
Level of the compression. 0 is the least compression, 9 is max. 8 is default.
Set strategy for encoding to one of the following: DEFAULT_STRATEGY FILTERED HUFFMAN_ONLY
CLASS Gz.File |
Allows the user to open a Gzip archive and read and write it's contents in an uncompressed form, emulating the Stdio.File interface.
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 : _file
void Gz.File(void|string|int|Stdio.Stream file, void|string mode)
Filename or filedescriptor of the gzip file to open, or an already open Stream.
mode for the file. Defaults to "rb".
open Stdio.File
int open(string|int|Stdio.Stream file, void|string mode)
Filename or filedescriptor of the gzip file to open, or an already open Stream.
mode for the file. Defaults to "rb". May be one of the following:
read mode
write mode
append mode
For the wb and ab mode, additional parameters may be specified. Please se zlib manual for more info.
non-zero if successful.
int|string read(void|int length)
Reads data from the file. If no argument is given, the whole file is read.
CLASS Gz.deflate |
Gz_deflate is a builtin program written in C. It interfaces the packing routines in the libz library.
This program is only available if libz was available and found when Pike was compiled.
Gz.inflate()
void Gz.deflate(int(0..9)|void level, int|void strategy)
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.
string deflate(string data, int|void flush)
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.inflate->inflate()
CLASS Gz.inflate |
Gz_deflate is a builtin program written in C. It interfaces the unpacking routines in the libz library.
This program is only available if libz was available and found when Pike was compiled.
deflate
void Gz.inflate(int|void window_size)
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.
string inflate(string data)
This function performs gzip style decompression. It can inflate a whole file at once or in blocks.
// 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));
Gz.deflate->deflate()
string end_of_stream()
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 |
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:
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.
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.
string MIME.decode_base64(string encoded_data)
This function decodes data encoded using the base64 transfer encoding.
MIME.encode_base64() , MIME.decode()
string MIME.encode_base64(string data, void|int no_linebreaks)
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.
MIME.decode_base64() , MIME.encode()
string MIME.decode_qp(string encoded_data)
This function decodes data encoded using the quoted-printable (a.k.a. quoted-unreadable) transfer encoding.
MIME.encode_qp() , MIME.decode()
string MIME.encode_qp(string data, void|int no_linebreaks)
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.
Please do not use this function. QP is evil, and there's no excuse for using it.
MIME.decode_qp() , MIME.encode()
string MIME.decode_uue(string encoded_data)
This function decodes data encoded using the x-uue transfer encoding. It can also be used to decode generic UUEncoded files.
MIME.encode_uue() , MIME.decode()
string MIME.encode_uue(string encoded_data, void|string filename)
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.
MIME.decode_uue() , MIME.encode()
array(string|int) MIME.tokenize(string header)
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.
int
s).
Quoted-strings, domain-literals and atoms will be decoded and returned as strings.
Comments are not returned in the array at all.
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.
MIME.quote() , tokenize_labled() , decode_words_tokenized_remapped() .
array(array(string|int)) MIME.tokenize_labled(string header)
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:
|
MIME.quote() , tokenize() , decode_words_tokenized_labled_remapped()
string MIME.quote(array(string|int) lexical_elements)
This function is the inverse of the MIME.tokenize function.
A header field value is constructed from a sequence of lexical elements.
Characters (int
s) are taken to be special-characters, whereas
strings are encoded as atoms or quoted-strings, depending on whether
they contain any special characters.
There is no way to construct a domain-literal using this function. Neither can it be used to produce comments.
MIME.tokenize()
string MIME.quote_labled(array(array(string|int)) tokens)
This function performs the reverse operation of tokenize_labled() .
MIME.quote() , MIME.tokenize_labled()
inherit ___MIME : ___MIME
string MIME.generate_boundary()
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.
string MIME.decode(string data, string encoding)
Extract raw data from an encoded string suitable for transport between systems.
The encoding can be any of
|
The encoding string is not case sensitive.
MIME.encode()
string MIME.encode(string data, string encoding, void|string filename, void|int no_linebreaks)
Encode raw data into something suitable for transport to other systems.
The encoding can be any of
|
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).
MIME.decode()
array(string) MIME.decode_word(string word)
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 that this function can only be applied to individual encoded words.
MIME.encode_word()
string MIME.encode_word(string|array(string) word, string encoding)
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.
MIME.decode_word()
array(array(string)) MIME.decode_words_text(string txt)
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() .
MIME.decode_words_tokenized MIME.decode_words_text_remapped
string MIME.decode_words_text_remapped(string txt)
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.
MIME.decode_words_tokenized_remapped
array(array(string)|int) MIME.decode_words_tokenized(string phrase)
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.
MIME.decode_words_tokenized_labled MIME.decode_words_tokenized_remapped MIME.decode_words_text
array(string|int) MIME.decode_words_tokenized_remapped(string phrase)
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.
MIME.decode_words_tokenized_labled_remapped MIME.decode_words_text_remapped
array(array(string|int|array(array(string)))) MIME.decode_words_tokenized_labled(string phrase)
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:
|
MIME.decode_words_tokenized_labled_remapped
array(array(string|int)) MIME.decode_words_tokenized_labled_remapped(string phrase)
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.
string MIME.encode_words_text(array(string|array(string)) phrase, string encoding)
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.
Either "base64"
or "quoted-printable"
(or either "b"
or "q"
for short).
string MIME.encode_words_quoted(array(array(string)|int) phrase, string encoding)
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() .
Either "base64"
or "quoted-printable"
(or either "b"
or "q"
for short).
MIME.encode_words_quoted_labled()
string MIME.encode_words_quoted_labled(array(array(string|int|array(string|array(string)))) phrase, string encoding)
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.
Either "base64"
or "quoted-printable"
(or either "b"
or "q"
for short).
MIME.encode_words_quoted()
string MIME.guess_subtype(string type)
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:
|
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)
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.
int|object MIME.reconstruct_partial(array(object) collection)
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:
|
Note that the returned message may in turn be a part of another, larger, fragmented message.
MIME.Message->is_partial()
string MIME.ext_to_media_type(string extension)
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 |
This class is used to hold a decoded MIME message.
mapping(string:string) headers
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:
|
The contents of these fields can be accessed and/or modified through a set of variables and methods available for this purpose.
type , subtype , charset , boundary , transfer_encoding , params , disposition , disp_params , setencoding() , setparam() , setdisp_param() , setcharset() , setboundary()
array(object) body_parts
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).
type , boundary
string boundary
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.
setboundary()
string charset
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"
.
type
string type
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"
.
subtype , params
string subtype
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"
.
type , params
string transfer_encoding
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.
setencoding()
mapping(string:string) params
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.
charset , boundary , setparam()
string disposition
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
.
mapping(string:string) disp_params
A mapping containing all the additional parameters to the Content-Disposition header.
setdisp_param() , get_filename()
string get_filename()
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.
An interactive application should always query the user for the actual filename to use. This method may provide a reasonable default though.
array(string|int) is_partial()
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.
MIME.reconstruct_partial()
void setdata(string data)
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.
Do not use this method unless you know what you are doing.
getdata()
string getdata()
This method returns the raw data of the message body entity.
The type and subtype attributes indicate how this data should be interpreted.
getencoded()
string getencoded()
This method returns the data of the message body entity, encoded using the current transfer encoding.
You should never have to call this function.
getdata()
void setencoding(string encoding)
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.
getencoded() , MIME.encode()
void setparam(string param, string value)
Set or modify the named parameter of the Content-Type header.
Common parameters include charset for text messages, and boundary for multipart messages.
It is not allowed to modify the Content-Type header directly, please use this function instead.
setcharset() , setboundary() , setdisp_param()
void setdisp_param(string param, string value)
Set or modify the named parameter of the Content-Disposition header.
A common parameters is e.g. filename.
It is not allowed to modify the Content-Disposition header directly, please use this function instead.
setparam() , get_filename()
void setcharset(string charset)
Sets the charset parameter of the Content-Type header.
This is equivalent of calling setparam("charset", charset )
.
setparam()
void setboundary(string boundary)
Sets the boundary parameter of the Content-Type header.
This is equivalent of calling setparam("boundary", boundary )
.
setparam()
string cast(string dest_type)
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() .
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)
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.
cast()
Module Math |
constant Math.pi
The constant pi (3.14159265358979323846).
constant Math.e
The constant e (2.7182818284590452354).
constant Math.inf
Floating point infinity.
constant Math.nan
Floating point not-a-number (e.g. inf/inf).
inherit "___"
int|float Math.convert_angle(int|float angle, string from, string to)
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.
int Math.choose(int n, int k)
Calculate binomial koefficient n choose k .
This is equvivalent to n !/(k !*(n -k )!).
float Math.log10(float x)
The 10-logarithm of x .
array(int) Math.factor(int x)
Factorize the integer x . The returned list of factors will be sorted biggest to smallest factor.
This function is only available when Pike has been compiled with bignums.
CLASS Math.Matrix |
Matrix representation with double precision floating point values.
void Math.Matrix(array(array(int|float)) matrix_2d)
void Math.Matrix(array(int|float) matrix_1d)
Initializes the matrix as a 1D or 2D matrix, e.g.
Math.Matrix( ({({1,2}),({3,4})}) )
.
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)
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
.
void Math.Matrix(string type, int size)
When type is "identity"
the matrix is initializes as a
square identity matrix.
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)
When type is "rotate"
the matrix is initialized as a
rotation matrix.
array(array) cast(string to_what)
array(array) cast(string to_what)
It is possible to cast the matrix to an array and get back a double array of floats with the matrix values.
vect
array vect()
Return all the elements of the matrix as an array of numbers
Matrix transpose()
Returns the transpose of the matrix as a new object.
float norm()
float norm2()
Matrix normv()
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).
Matrix `+(object with)
Matrix ``+(object with)
Matrix add(object with)
Add this matrix to another matrix. A new matrix is returned. The matrices must have the same size.
Matrix `-()
Matrix `-(object with)
Matrix ``-(object with)
Matrix sub(object with)
Subtracts this matrix from another. A new matrix is returned.
-m
is equal to -1*m
.
Matrix sum()
Produces the sum of all the elements in the matrix.
Matrix max()
Matrix min()
Produces the maximum or minimum value of all the elements in the matrix.
Matrix `*(object with)
Matrix ``*(object with)
Matrix mult(object with)
Matrix multiplication.
Matrix cross(object with)
Matrix cross-multiplication.
float dot_product(object with)
Matrix dot product.
Matrix convolve(object with)
Convolve called matrix with the argument.
CLASS Math.FMatrix |
Matrix representation with single precision floating point values.
inherit Matrix : Matrix
CLASS Math.LMatrix |
Matrix representation with 64 bit integer values.
inherit Matrix : Matrix
CLASS Math.IMatrix |
Matrix representation with 32 bit integer values.
inherit Matrix : Matrix
CLASS Math.SMatrix |
Matrix representation with 16 bit integer values.
inherit Matrix : Matrix
CLASS Math.Angle |
Represents an angle.
int|float angle
The actual keeper of the angle value.
string type
The type of the angle value. Is either "deg", "rad", "gon" or "str".
void Math.Angle()
void Math.Angle(int|float radians)
void Math.Angle(int|float angle, string type)
If an angle object is created without arguments it will have the value 0 radians.
Angle clone_me()
Returns a copy of the object.
int|float get(string type)
Gets the value in the provided type.
Angle set(string type, int|float _angle)
Sets the angle value and type to the given value and type.
void normalize()
Normalizes the angle to be within one turn.
int|float degree()
Returns the number of degrees, including minutes and seconds as decimals.
int minute()
Returns the number of minute.
float second()
Returns the number of seconds.
Angle set_dms(int degrees)
Angle set_dms(int degrees, int minutes)
Angle set_dms(int degrees, int minutes, float seconds)
Set degrees, minues and seconds. Returns the current angle object.
string format_dms()
Returns degrees, minutes and seconds as a string, e.g. 47°6'36.00".
Angle set_degree(int|float degree)
Sets the angle to the provided degree. Alters the type to degrees. Returns the current object.
int|float gon()
Returns the number of gons.
Angle set_gon(int|float gon)
Set the angle to the provided gons. Alters the type to gons. Returns the current angle object.
float rad()
Returns the number of radians.
Angle set_rad(int|float rad)
Set the angle to the provided radians. Alters the type to radians. Returns the current angle object.
float|int streck()
Returns the number of strecks.
Angle set_streck(int|float str)
Set the angle to the provided strecks. Alters the type to streck. Returns the current angle object.
void about_face()
Turns the direction of the angle half a turn. Equal to
add(180,"deg")
.
void right_face()
Turns the direction of the angle a quarter of a turn to the right.
Equal to subtract(90,"deg")
.
void left_face()
Turns the direction of the angle a quarter of a turn to the left.
Equal to add(90,"deg")
.
float sin()
Returns the sinus for the angle.
float cos()
Returns the cosinus for the angle.
float tan()
Returns the tangen for the angle.
float|int|string cast(string to)
An angle can be casted to float, int and string.
float|int|Angle `+(float|int|Angle _angle)
Returns the sum of this angle and what it is added with. If added with an angle, a new angle object is returnes.
Angle add(float|int angle)
Angle add(float|int angle, string type)
Angle add(Angle angle)
Adds the provided angle to the current angle. The result is normalized within 360 degrees.
float|int|Angle `-(float|int|Angle _angle)
Returns the difference between this angle and the provided value. If differenced with an angle, a new angle object is returned.
Angle subtract(float|int angle)
Angle subtract(float|int angle, string type)
Angle subtract(Angle angle)
Subtracts the provided angle from the current angle. The result is normalized within 360 degrees.
float|int|Angle `*(float|int|Angle _angle)
Returns the product between this angle and the provided value. If differenced with an angle, a new angle object is returned.
float|int|Angle `/(float|int|Angle _angle)
Returns the fraction between this angle and the provided value. If differenced with an angle, a new angle object is returned.
float|int|Angle `%(float|int|Angle _angle)
Returns this result of this angle modulo the provided value. If differenced with an angle, a new angle object is returned.
int __hash()
int `==(Angle _angle)
Compares the unnormalized angle of two Angle objects.
int `<(Angle _angle)
Compares the unnormalized angle of two Angle objects.
int `>(Angle _angle)
Compares the unnormalized angle of two Angle objects.
Module Math.Transforms |
CLASS Math.Transforms.FFT |
array(array(float)) rFFT(array(int|float) real_input)
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.
The array of floats and/or ints to transform.
rIFFT(rFFT()) returns the input array scaled by n=sizeof(input array). This is due to the nature of the DFT algorithm.
rIFFT()
array(float) rIFFT(array(array(float)) input)
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.
The array of floats and/or ints to transform.
rIFFT(rFFT()) returns the input array scaled by n=sizeof(input array). This is due to the nature of the DFT algorithm.
rFFT()
void Math.Transforms.FFT(void|int n, void|int(0..1) exact)
Creates a new transform object. If n is specified, a plan is created for transformations of n-size arrays.
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.
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 |
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.*
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.
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.
Sql.Sql
constant Msql.version
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 |
void shutdown()
This function shuts a SQL-server down.
void reload_acl()
This function forces a server to reload its ACLs.
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.
create
void Msql.msql(void|string dbserver, void|string dbname, void|string username, void|string passwd)
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.
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.
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.
select_db
array list_dbs(void|string wild)
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.
array list_tables(void|string wild)
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.
void select_db(string dbname)
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.
This function CAN raise exceptions in case something goes wrong (for example: unexistant database, insufficient permissions, whatever).
create , error
array(mapping(string:mixed)) query(string sqlquery)
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"]).
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 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.
error
string server_info()
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.
string host_info()
This function returns a string describing what host are we talking to, and how (TCP/IP or UNIX sockets).
string error()
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).
query
void create_db(string dbname)
This function creates a new database with the given name (assuming we have enough permissions to do this).
drop_db
void drop_db(string dbname)
This function destroys a database and all the data it contains (assuming we have enough permissions to do so). USE WITH CAUTION!
create_db
mapping(string:mapping(string:mixed)) list_fields(string table, void|string glob)
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:
|
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.
query
int affected_rows()
This function returns how many rows in the database were affected by our last SQL query.
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
array list_index(string tablename, string indexname)
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).
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 |
int open_file(string filename)
PDF close()
PDF begin_page()
PDF begin_page(float width, float height)
note: Defaults to a4, portrait
PDF end_page()
float get_value(string key)
float get_value(string key, float modifier)
float set_value(string key, float value)
string get_parameter(string key)
string get_parameter(string key, float modifier)
float set_parameter(string key, string parameter)
float set_info(string key, string info)
int findfont(string fontname)
int findfont(string fontname, void|string encoding, void|int embed)
PDF setfont(int n, float size)
PDF show(string s)
PDF showxy(string s, float x, float y)
PDF continue_text(string s)
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)
float stringwidth(string text, int font, float size)
object set_text_pos(float x, float y)
object setdash(float b, float w)
object setflat(float flatness)
object setlinejoin(int linejoin)
object setlinecap(int linecap)
object setmiterlimit(float miter)
object setlinewidth(float width)
object translate(float tx, float ty)
object scale(float sx, float sy)
object rotate(float phi)
object skew(float alpha, float beta)
object concat(float a, float b, float c, float d, float e, float f)
object moveto(float x, float y)
object lineto(float x, float y)
object curveto(float x1, float y1, float x2, float y2, float x3, float y3)
object circle(float x, float y, float r)
object arc(float x, float y, float r, float start, float end)
object rect(float x, float y, float width, float height)
object setgray_fill(float gray)
object setgray_stroke(float gray)
object setgray(float gray)
object setrgbcolor_fill(float red, float green, float blue)
object setrgbcolor_stroke(float red, float green, float blue)
object setrgbcolor(float red, float green, float blue)
int open_image_file(string type, string filename)
int open_image_file(string type, string filename, void|string stringparam, void|int intparam)
int open_CCITT(string filename, int width, int height, int BitReverse, int K, int BlackIs1)
int open_image(string type, string source, string data, int width, int height, int components, int bpc, string params)
object close_image(int image)
object place_image(int image, float x, float y, float scale)
int add_bookmark(string text, int parent, int open)
object attach_file(float llx, float lly, float urx, float ury, string filename, string description, string author, string mimetype, string icon)
object add_pdflink(float llx, float lly, float urx, float ury, string filename, int page, string dest)
object add_locallink(float llx, float lly, float urx, float ury, int page, string dest)
object add_launchlink(float llx, float lly, float urx, float ury, string filename)
object add_weblink(float llx, float lly, float urx, float ury, string url)
object set_border_style(string style, float width)
object set_border_color(float red, float green, float blue)
object set_border_dash(float b, float w)
Module Perl |
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 |
An object of this class is a Perl interpreter.
void Perl.Perl()
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.
int parse(array(string) args)
int parse(array(string) args, mapping(string:string) env)
Parse a Perl script file and set up argument and environment for it. Returns zero on success, and non-zero if the parsing failed.
Arguments in the style of argv, i.e. with the name of the script first.
Environment mapping, mapping environment variable names to to their values.
int run()
Run a previously parsed Perl script file. Returns a status code.
mixed eval(string expression)
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.
mixed eval_list(string expression)
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.
mixed call(string name, mixed ... arguments)
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.
The name of the subroutine to call, as an 8-bit string.
Zero or more arguments to the function. Only simple value types are supported. Unsupported value types will cause an error to be thrown.
mixed call_list(string name, mixed ... arguments)
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.
The name of the subroutine to call, as an 8-bit string.
Zero or more arguments to the function. Only simple value types are supported. Unsupported value types will cause an error to be thrown.
mixed get_scalar(string name)
Get the value of a Perl scalar variable. Returns the value, or a plain 0 if the value type was not supported.
Name of the scalar variable, as an 8-bit string.
void set_scalar(string name, mixed value)
Set the value of a Perl scalar variable.
Name of the scalar variable, as an 8-bit string.
The new value. Only simple value types are supported. Throws an error for unsupported value types.
mixed get_array_item(string name, int index)
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.
Name of the array variable, as an 8-bit string.
Array index. An error is thrown if the index is negative, non-integer or a bignum.
void set_array_item(string name, int index, mixed value)
Set the value of an entry in a Perl array variable. Only simple value types are supported. Throws an error for unsupported value types.
Name of the array variable, as an 8-bit string.
Array index. An error is thrown if the index is negative, non-integer or a bignum.
New value. Only simple value types are supported. An error is thrown for unsupported value types.
mixed get_hash_item(string name, mixed key)
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.
Name of the array variable, as an 8-bit string.
Hash key. Only simple value types are supported. An error is thrown for unsupported value types.
void set_hash_item(string name, mixed key, mixed value)
Set the value of an entry in a Perl hash variable.
Name of the hash variable, as an 8-bit string.
Hash key. Only simple value types are supported. An error is thrown for unsupported value types.
New value. Only simple value types are supported. An error is thrown for unsupported value types.
int array_size(string name)
Get the size of the Perl array variable with the given name.
Name of the array variable, as an 8-bit string.
array get_array(string name)
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.
Name of the array variable, as an 8-bit string.
array_size_limit()
array get_hash_keys(string name)
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.
Name of the hash variable, as an 8-bit string.
array_size_limit()
int array_size_limit()
int array_size_limit(int limit)
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.
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).
The new array size limit.
Module Regexp |
inherit "___"
SimpleRegexp Regexp.`()(void|string regexp)
Convenience/compatibility method to get a SimpleRegexp object.
int(0..1) Regexp.match(string regexp, string data)
Calls Regexp.PCRE.Plain.match in a temporary regexp object. Faster to type but slower to run...
array Regexp.split(string regexp, string data)
Calls Regexp.PCRE.Plain.split in a temporary regexp object. Faster to type but slower to run...
array Regexp.split2(string regexp, string data)
Calls Regexp.PCRE.Plain.split2 in a temporary regexp object. Faster to type but slower to run...
string Regexp.replace(string regexp, string data, string|function(string:string) transform)
Calls Regexp.PCRE.Plain.replace in a temporary regexp object. Faster to type but slower to run...
CLASS Regexp.SimpleRegexp |
This class implements the interface to a simple regexp engine with the following capabilities:
|
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.
void Regexp.SimpleRegexp(string re)
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.
int match(string str)
Returns 1 if str matches the regexp bound to the regexp object. Zero otherwise.
array(string) match(array(string) strs)
Returns an array containing strings in strs that match the regexp bound to the regexp object.
The current implementation doesn't support searching in strings containing the NUL character or any wide character.
split
array(string) split(string s)
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.
You can currently only have 39 subregexps.
The current implementation doesn't support searching in strings containing the NUL character or any wide character.
match
inherit _SimpleRegexp : _SimpleRegexp
string replace(string in, string|function(string:string) transform)
mixed _encode()
mixed _decode(string s)
Regexp objects can be encoded and decoded.
encode_value , decode_value
Module Regexp.PCRE |
array(string) Regexp.PCRE.split_subject(string subject, array(int) previous_result)
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 Regexp.PCRE.buildconfig_UTF8
(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 Regexp.PCRE.buildconfig_NEWLINE
(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 Regexp.PCRE.buildconfig_LINK_SIZE
(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 Regexp.PCRE.buildconfig_POSIX_MALLOC_THRESHOLD
(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 Regexp.PCRE.buildconfig_MATCH_LIMIT
(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 |
void Regexp.PCRE._pcre(string pattern, void|int options, void|object table)
The option bits are:
|
object study()
(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."
string _sprintf(int c, mapping flags)
mapping info()
Returns additional information about a compiled pattern. Only available if PCRE was compiled with Fullinfo.
|
int|array exec(string subject, void|int startoffset)
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:
|
int get_stringnumber(string stringname)
returns the number of a named subpattern
Module Regexp.PCRE.OPTION |
contains all option constants
constant Regexp.PCRE.OPTION.ANCHORED
(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 Regexp.PCRE.OPTION.CASELESS
(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 Regexp.PCRE.OPTION.DOLLAR_ENDONLY
(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 Regexp.PCRE.OPTION.DOTALL
(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 Regexp.PCRE.OPTION.EXTENDED
(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 Regexp.PCRE.OPTION.EXTRA
(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 Regexp.PCRE.OPTION.MULTILINE
(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 Regexp.PCRE.OPTION.NO_AUTO_CAPTURE
(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 Regexp.PCRE.OPTION.UNGREEDY
(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 Regexp.PCRE.OPTION.UTF8
(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
Documented in exec .
Module Regexp.PCRE._Regexp_PCRE |
inherit "___"
GOOD Regexp.PCRE._Regexp_PCRE.`()(string pattern, void|int options, void|object table)
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 |
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 : _pcre
array(string)|int(0..0) split2(string subject, void|int startoffset)
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" })
array(string)|int(0..0) split(string subject, void|int startoffset)
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 })
int(0..1) match(string subject, void|int startoffset)
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
string replace(string subject, string|function(string:string) with)
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"
string replace1(string subject, string|function(string:string) with)
replace one (first) occurance of a pattern in a subject
example: > Regexp.PCRE("b[^-]*m")->replace1("abam-boom-fooabadoom","gurka"); Result: "agurka-boom-fooabadoom"
this_program matchall(string subject, function(array(string)|void:mixed|void) callback)
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 |
Same as Plain, but will be studied to match faster; useful if you're doing many matches on the same pattern
inherit Plain : Plain
CLASS Regexp.PCRE._Regexp_PCRE.Widestring |
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 : Plain
array(int)|int exec(string subject, void|int startoffset)
The exec function is wrapped to give the correct indexes for the widestring.
CLASS Regexp.PCRE._Regexp_PCRE.StudiedWidestring |
Same as Widestring, but will be studied to match faster; useful if you're doing many matches on the same pattern
inherit Widestring : Widestring
Module SANE |
This module enables access to the SANE (Scanner Access Now Easy) library from pike
array(mapping) SANE.list_scanners()
Returns an array with all available scanners.
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 |
void SANE.Scanner(string name)
array(mapping) list_options()
This method returns an array where every element is a mapping, layed out as follows.
|
void set_option(string name, mixed new_value)
void set_option(string name)
If no value is specified, the option is set to it's default value
mixed get_option(string name)
mapping(string:int) get_parameters()
|
Image.Image simple_scan()
void row_scan(function(Image.Image:void) callback)
void nonblocking_row_scan(function(Image.Image:void) callback)
void cancel_scan()
Module Yp |
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 "___"
string Yp.default_domain()
Returns the default yp-domain.
CLASS Yp.Map |
Network Information Service aka YP map.
void Yp.Map(string map, string|void domain)
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.
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.
string match(string key)
string `[](string key)
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.
key must match exactly, no pattern matching of any kind is done.
mapping(string:string) all()
mapping(string:string) cast_to_mapping()
Returns the whole map as a mapping.
void map(function(string:void) fun)
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)
.
string server()
Return the server that provides this map.
int order()
Return the order number for this map.
int _sizeof()
Return the number of entries in this map.
array(string) _indices()
Return the keys of the map.
array(string) _values()
Return the values of the map.
CLASS Yp.Domain |
string server(string map)
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.
void Yp.Domain(string|void domain)
void bind(string domain)
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.
Yp.default_domain()
mapping(string:string) all(string map)
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.
void map(string map, function(string:void) fun)
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.
int order(string map)
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.
string match(string map, string key)
Search for the key key in the Yp-map map .
If there is no key in the map, 0 (zero) will be returned, otherwise the string matching the key will be returned.
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
Various audio and video codecs.
The list of supported codecs depends on Ffmpeg library.
constant _Ffmpeg.CODEC_TYPE_AUDIO
constant _Ffmpeg.CODEC_TYPE_VIDEO
Type of codec.
CLASS _Ffmpeg.ffmpeg |
Implements support of all codecs from a nice project Ffmpeg. You can find more info about it at http://ffmpeg.sf.net/.
void _Ffmpeg.ffmpeg(int codec_name, int encoder)
Create decoder or encoder object.
Internal number of codec, eg. CODEC_ID_MP2 .
If true, encoder object will be created, decoder object otherwise.
mapping|int get_codec_info()
Returns mapping with info of used codec.
list_codecs()
int set_codec_param(string name, mixed value)
Sets one codec parameter
The name of parameter. One of "sample_rate"
,
"bit_rate"
, "channels"
.
Returns 1 on success, 0 otherwise (parameter not known).
get_codec_params()
mapping|int get_codec_status()
Returns a mapping with the actual codec parameters.
set_codec_param()
mapping|int decode(string data)
Returns a mapping with the new decoded frame and lenght of data which was used for decoding.
int decode(string data, function shuffler)
Decode all data buffer and pass result to shuffler .
Returns 1
on success, 0
otherwise.
Shuffler variant isn't implemented, yet.
Usable only in decoder.
create()
array(mapping) list_codecs()
Gets all supported codecs.
Array of mapping with codec features.
Module spider |
string spider.discdate(int time)
array(mapping(string:int)|int) spider.parse_accessed_database(string database)
string spider.parse_html(string html, mapping(string:function(string:string|array)) tag_callbacks, mapping(string:function(string:string|array)) container_callbacks, mixed ... extras)
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)
void spider.set_end_quote(int quote)
void spider.set_start_quote(int quote)
array(int) spider.get_all_active_fds()
string spider.fd_info(int fd)
string spider._low_program_name(program prog)
array(array(string|int)) spider._dump_obj_table()
string spider.stardate(int time, int precision)
array spider.parse_xml(string xml, function cb)
Module System |
This module embodies common operating system calls, making them available to the Pike programmer.
string|int|array(string) System.RegGetValue(int hkey, string key, string index)
Get a single value from the register.
One of the following:
|
Registry key.
Value name.
Returns the value stored at the specified location in the register if any. Throws errors on failure.
This function is only available on Win32 systems.
RegGetValues() , RegGetKeyNames()
array(string) System.RegGetKeyNames(int hkey, string key)
Get a list of value key names from the register.
One of the following:
|
A registry key.
Returns an array of value keys stored at the specified location if any. Throws errors on failure.
> RegGetKeyNames(HKEY_CURRENT_USER, "Keyboard Layout"); (1) Result: ({ "IMEtoggle", "Preload", "Substitutes", "Toggle" })
This function is only available on Win32 systems.
RegGetValue() , RegGetValues()
mapping(string:string|int|array(string)) System.RegGetValues(int hkey, string key)
Get multiple values from the register.
One of the following:
|
Registry key.
Returns a mapping with all the values stored at the specified location in the register if any. Throws errors on failure.
> RegGetValues(HKEY_CURRENT_USER, "Keyboard Layout\\Preload"); (5) Result: ([ "1":"0000041d" ])
This function is only available on Win32 systems.
RegGetValue() , RegGetKeyNames()
object System.LogonUser(string username, string|int(0..0) domain, string password, int|void logon_type, int|void logon_provider)
Logon a user.
User name of the user to login.
Domain to login on, or zero if local logon.
Password to login with.
One of the following values:
|
One of the following values:
|
Returns a login token object on success, and zero on failure.
This function is only available on some Win32 systems.
string|array(string|int) System.NetUserGetInfo(string username, string|int(0..0) server, int|void level)
Get information about a network user.
User name of the user to get information about.
Server the user exists on.
Information level. One of:
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserEnum() , NetGroupEnum() NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()
array(string|array(string|int)) System.NetUserEnum(string|int(0..0)|void server, int|void level, int|void filter)
Get information about network users.
Server the users exist on.
Information level. One of:
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo() , NetGroupEnum() NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()
array(string|array(string|int)) System.NetGroupEnum(string|int(0..0)|void server, int|void level)
Get information about network groups.
Server the groups exist on.
Information level. One of:
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo() , NetUserEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()
array(array(string|int)) System.NetLocalGroupEnum(string|int(0..0)|void server, int|void level)
Get information about local network groups.
Server the groups exist on.
Information level. One of:
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()
array(array(string|int)) System.NetUserGetGroups(string|int(0..0) server, string user, int|void level)
Get information about group membership for a network user.
Server the groups exist on.
User to retrieve groups for.
Information level. One of:
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()
array(string) System.NetUserGetLocalGroups(string|int(0..0) server, string user, int|void level, int|void flags)
Get information about group membership for a local network user.
Server the groups exist on.
User to retrieve groups for.
Information level. One of:
|
Zero, of one of the following:
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()
array(string|array(int|string)) System.NetGroupGetUsers(string|int(0..0) server, string group, int|void level)
Get information about group membership for a network group.
Server the groups exist on.
Group to retrieve members for.
Information level. One of:
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetLocalGroupGetMembers() , NetGetDCName() , NetGetAnyDCName()
array(string|array(int|string)) System.NetLocalGroupGetMembers(string|int(0..0) server, string group, int|void level)
Get information about group membership for a network group.
Server the groups exist on.
Group to retrieve members for.
Information level. One of:
|
Returns an array on success. Throws errors on failure.
Document the return value.
This function is only available on some Win32 systems.
NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetGetDCName() , NetGetAnyDCName()
string System.NetGetDCName(string|int(0..0) server, string domain)
Get name of the domain controller from a server.
Server the domain exists on.
Domain to get the domain controller for.
Returns the name of the domain controller on success. Throws errors on failure.
This function is only available on some Win32 systems.
NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetAnyDCName()
string System.NetGetAnyDCName(string|int(0..0) server, string domain)
Get name of a domain controller from a server.
Server the domain exists on.
Domain to get a domain controller for.
Returns the name of a domain controller on success. Throws errors on failure.
This function is only available on some Win32 systems.
NetUserGetInfo() , NetUserEnum() , NetGroupEnum() , NetLocalGroupEnum() , NetUserGetGroups() , NetUserGetLocalGroups() , NetGroupGetUsers() , NetLocalGroupGetMembers() , NetGetDCName()
array(int|string) System.NetSessionEnum(string|int(0..0) server, string|int(0..0) client, string|int(0..0) user, int level)
Get session information.
One of
|
This function is only available on some Win32 systems.
array(mixed) System.NetWkstaUserEnum(string|int(0..0) server, int level)
One of
|
This function is only available on some Win32 systems.
string System.normalize_path(string path)
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.
A normalized absolute path without trailing slashes.
Throws errors on failure, e.g. if the file or directory doesn't exist.
File fork information is currently not supported (invalid data).
combine_path() , combine_path_nt()
int System.GetFileAttributes(string filename)
Get the file attributes for the specified file.
This function is only available on Win32 systems.
SetFileAttributes()
int System.SetFileAttributes(string filename)
Set the file attributes for the specified file.
This function is only available on Win32 systems.
GetFileAttributes()
array(mixed) System.LookupAccountName(string|int(0..0) sys, string account)
This function is only available on some Win32 systems.
array(mixed) System.SetNamedSecurityInfo(string name, mapping(string:mixed) options)
This function is only available on some Win32 systems.
GetNamedSecurityInfo()
mapping(mixed:mixed) System.GetNamedSecurityInfo(string name, int|void type, int|void flags)
This function is only available on some Win32 systems.
SetNamedSecurityInfo()
int System.setpwent()
Resets the getpwent function to the first entry in the passwd source using the systemfunction setpwent(3).
Always 0
(zero)
get_all_users() getpwent() endpwent()
int System.endpwent()
Closes the passwd source opened by getpwent function using the systemfunction endpwent(3).
Always 0
(zero)
get_all_users() getpwent() setpwent()
array(int|string) System.getpwent()
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 .
An array with the information about the user
|
0 if EOF.
get_all_users() getpwnam() getpwent() setpwent() endpwent()
int System.setgrent()
Rewinds the getgrent pointer to the first entry
get_all_groups() getgrent() endgrent()
int System.endgrent()
Closes the /etc/groups file after using the getgrent function.
get_all_groups() getgrent() setgrent()
array(int|string|array(string)) System.getgrent()
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 !
An array with the information about the group
|
get_all_groups() getgrnam() getgrgid()
void System.openlog(string ident, int options, facility)
Initializes the connection to syslogd.
The ident argument specifies an identifier to tag all logentries with.
A bitfield specifying the behaviour of the message logging. Valid options are:
|
Specifies what subsystem you want to log as. Valid facilities are:
|
Only available on systems with syslog(3).
LOG_NOWAIT should probably always be specified.
syslog , closelog
void System.syslog(int a, string b)
Document this function.
void System.closelog()
Document this function.
void System.hardlink(string from, string to)
Create a hardlink named to from the file from .
This function is not available on all platforms.
symlink() , mv() , rm()
void System.symlink(string from, string to)
Create a symbolic link named to that points to from .
This function is not available on all platforms.
hardlink() , readlink() , mv() , rm()
string System.readlink(string path)
Returns what the symbolic link path points to.
This function is not available on all platforms.
symlink()
string System.resolvepath(string path)
Resolve all symbolic links of a pathname.
This function is not available on all platforms.
readlink() , symlink()
int System.umask(void|int mask)
Set the current umask to mask .
If mask is not specified the current umask will not be changed.
Returns the old umask setting.
void System.chmod(string path, int mode)
Sets the protection mode of the specified path.
Throws errors on failure.
Stdio.File->open() , errno()
void System.chown(string path, int uid, int gid)
Sets the owner and group of the specified path.
Throws errors on failure.
This function is not available on all platforms.
void System.utime(string path, int atime, int mtime)
Set the last access time and last modification time for the path path to atime and mtime repectively.
Throws errors on failure.
This function is not available on all platforms.
void System.initgroups(string name, int base_gid)
Initializes the supplemental group access list according to the system group database. base_gid is also added to the group access list.
Throws errors on failure.
This function is not available on all platforms.
setuid() , getuid() , setgid() , getgid() , seteuid() , geteuid() , setegid() , getegid() , getgroups() , setgroups()
void System.cleargroups()
Clear the supplemental group access list.
Throws errors on failure.
This function is not available on all platforms.
setgroups() , initgroups() , getgroups()
void System.setgroups(array(int) gids)
Set the supplemental group access list for this process.
Throws errors on failure.
This function is not available on all platforms.
initgroups() , cleargroups() , getgroups() , getgid() , getgid() , getegid() , setegid()
array(int) System.getgroups()
Get the current supplemental group access list for this process.
Throws errors on failure.
This function is not available on all platforms.
setgroups() , cleargroups() , initgroups() , getgid() , getgid() , getegid() , setegid()
int(0..1) System.innetgr(string netgroup, string|void machine, string|void user, string|void domain)
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 .
This function isn't available on all platforms.
int System.setuid(int uid)
Sets the real user ID, effective user ID and saved user ID to uid .
Returns the current errno.
This function isn't available on all platforms.
getuid() , setgid() , getgid() , seteuid() , geteuid() , setegid() , getegid()
int System.setgid(int gid)
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 an error if no "nobody" user when gid is -1
.
Returns the current errno.
This function is not available on all platforms.
getuid() , setuid() , getgid() , seteuid() , geteuid() , setegid() , getegid()
int System.seteuid(int euid)
Set the effective user ID to euid . If euid is
-1
the uid for "nobody" will be used.
Returns the current errno.
Throws an error if there is no
"nobody" user when euid is -1
.
This function isn't available on all platforms.
int System.setegid(int egid)
Set the effective group ID to egid . If egid is
-1
the uid for "nobody" will be used.
Returns the current errno.
Throws an error if there is no "nobody" user when
egid is -1
.
This function isn't available on all platforms.
int System.getpgrp(int|void pid)
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.
Not all platforms support getting the process group for other processes.
Not supported on all platforms.
getpid , getppid
int System.setpgrp()
Make this process a process group leader.
Not supported on all platforms.
int System.getsid(int|void pid)
Get the process session ID for the given process. If pid is not specified, the session ID for the current process will be returned.
This function is not available on all platforms.
Throws an error if the system call fails.
getpid , getpgrp , setsid
int System.setsid()
Set a new process session ID for the current process, and return it.
This function isn't available on all platforms.
Throws an error if the system call fails.
getpid , setpgrp , getsid
int(0..1) System.dumpable(int(0..1)|void val)
Get and/or set whether this process should be able to dump core.
Optional argument to set the core dumping state.
|
Returns 1
if this process currently is capable of dumping core,
and 0
(zero) if not.
This function is currently only available on some versions of Linux.
int System.setresuid(int ruid, int euid, int suid)
Sets the real, effective and saved set-user-ID to ruid , euid and suid respectively.
Returns zero on success and errno on failure.
int System.setresgid(int rgid, int egid, int sgid)
Sets the real, effective and saved group ID to rgid , egid and sgid respectively.
Returns zero on success and errno on failure.
int System.getuid()
Get the real user ID.
setuid , setgid , getgid , seteuid , geteuid , setegid , getegid
int System.getgid()
Get the real group ID.
setuid , getuid , setgid , seteuid , geteuid , getegid , setegid
int System.geteuid()
Get the effective user ID.
setuid , getuid , setgid , getgid , seteuid , getegid , setegid
int System.getegid()
Get the effective group ID.
setuid , getuid , setgid , getgid , seteuid , geteuid , setegid
int System.getpid()
Returns the process ID of this process.
getppid , getpgrp
int System.getppid()
Returns the process ID of the parent process.
getpid , getpgrp
int System.chroot(string newroot)
int System.chroot(Stdio.File newroot)
Changes the root directory for this process to the indicated directory.
A nonzero value is returned if the call is successful. If there's an error then zero is returned and errno is set appropriately.
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.
mapping(string:string) System.uname()
Get operating system information.
The resulting mapping contains the following fields:
|
This function only exists on systems that have the uname(2) or sysinfo(2) system calls.
Only the first five elements are always available.
string System.gethostname()
Returns a string with the name of the host.
This function only exists on systems that have the gethostname(2) or uname(2) system calls.
array(string|array(string)) System.gethostbyaddr(string addr)
Returns an array with information about the specified IP address.
The returned array contains the same information as that returned by gethostbyname() .
This function only exists on systems that have the gethostbyaddr(2) or similar system call.
gethostbyname()
array(string|array(string)) System.gethostbyname(string hostname)
Returns an array with information about the specified host.
The returned array contains the following:
|
This function only exists on systems that have the gethostbyname(2) or similar system call.
gethostbyaddr()
int System.sleep(int seconds)
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).
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.
predef::sleep() usleep() nanosleep()
void System.usleep(int usec)
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).
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.
predef::sleep() sleep() nanosleep()
float System.nanosleep(int|float seconds)
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).
predef::sleep() sleep() usleep()
May not be present; only exists if the function exists in the current system.
array(int) System.getrlimit(string resource)
Returns the current process limitation for the selected resource .
|
|
This function nor all the resources are available on all systems.
getrlimits , setrlimit
mapping(string:array(int)) System.getrlimits()
Returns all process limits in a mapping.
getrlimit , setrlimit
int(0..1) System.setrlimit(string resource, int soft, int hard)
Sets the soft and the hard process limit on a resource .
getrlimit , getrlimits
constant System.ITIMER_REAL
Identifier for a timer that decrements in real time.
setitimer , getitimer
constant System.ITIMER_VIRTUAL
Identifier for a timer that decrements only when the process is executing.
setitimer , getitimer
constant System.ITIMER_PROF
Identifier for a timer that decrements both when the process is executing and when the system is executing on behalf of the process.
setitimer , getitimer
float System.setitimer(int timer, int|float value)
Sets the timer to the supplied value . Returns the current timer interval.
One of ITIMER_REAL , ITIMER_VIRTUAL and ITIMER_PROF .
array(float) System.getitimer(int timer)
Shows the state of the selected timer .
|
One of ITIMER_REAL , ITIMER_VIRTUAL and ITIMER_PROF .
array(string) System.get_netinfo_property(string domain, string path, string property)
Queries a NetInfo server for property values at the given path.
NetInfo domain. Use "." for the local domain.
NetInfo path for the property.
Name of the property to return.
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.
system.get_netinfo_property(".", "/locations/resolver", "domain"); ({ "idonex.se" })
Only available on operating systems which have NetInfo libraries installed.
int System.rdtsc()
Executes the rdtsc (clock pulse counter) instruction and returns the result.
array(int) System.gettimeofday()
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).
time() , gethrtime()
string System.CPU_TIME_IS_THREAD_LOCAL
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.
mapping(string:int) System.getrusage()
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 a mapping describing the current resource usage:
|
[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.
gethrvtime()
CLASS System.Memory |
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.
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)
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.
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)
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.
void allocate(int bytes)
void allocate(int bytes, int(0..255) fill)
void free()
Free the allocated or <tt>mmap</tt>ed memory.
int _sizeof()
returns the size of the memory (bytes). note: throws if not allocated
int(0..1) valid()
returns 1 if the memory is valid, 0 if not allocated
int(0..1) writeable()
returns 1 if the memory is writeable, 0 if not
string|array cast(string to)
Cast to string or array.
Throws if not allocated.
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)
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 (!).
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)
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
int `[](int pos)
string `[](int pos1, int pos2)
int `[]=(int pos, int char)
string `[]=(int pos1, int pos2, string str)
CLASS System.Time |
The current time as a structure containing a sec and a usec member.
int sec
int usec
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.
int usec_full
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.
void System.Time(int fast)
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 |
float peek()
Return the time in seconds since the last time get was called.
float get()
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.
void System.Timer(int|void fast)
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 |
Class for exception objects for errors of unspecified type.
array cast(string type)
Cast operator.
The only supported type to cast to is "array"
, which
generates and old-style error.
array|string `[](int(0..1) index)
Index operator.
Simulates an array
|
The error message is always terminated with a newline.
backtrace()
string describe()
Return a readable error report that includes the backtrace.
string message()
Return a readable message describing the error.
array backtrace()
Return the backtrace where the error occurred.
predef::backtrace()
string _sprintf()
void Error.Generic(string message)
Module Pike |
constant Pike.WEAK_INDICES
constant Pike.WEAK_VALUES
constant Pike.WEAK
Flags for use together with set_weak_flag and get_weak_flag . See set_weak_flag for details.
mapping(string:float) Pike.gc_parameters(void|mapping(string:mixed) params)
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:
|
gc , Debug.gc_status
CLASS Pike.Backend |
mixed call_out(function f, float|int delay, mixed ... args)
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 a call_out identifier that identifies this call_out. This value can be sent to eg find_call_out() or remove_call_out() .
remove_call_out() , find_call_out() , call_out_info()
int _do_call_outs()
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.
Zero if no call outs were called, nonzero otherwise.
call_out() , find_call_out() , remove_call_out()
int find_call_out(function f)
int find_call_out(mixed id)
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).
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.
call_out() , remove_call_out() , call_out_info()
int remove_call_out(function f)
int remove_call_out(function id)
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).
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.
call_out_info() , call_out() , find_call_out()
array(array) call_out_info()
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:
|
call_out() , find_call_out() , remove_call_out()
float|int(0..0) `()(void|float|int(0..0) sleep_time)
Perform one pass through the backend.
Wait at most sleep_time seconds. The default when
unspecified or the integer 0
is no time limit.
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.
Thread.Thread executing_thread()
int executing_thread()
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.
void add_file(Stdio.File|Stdio.FILE f)
Add f to this backend. This simply does
f->set_backend(backend)
where backend
is this
object.
int id()
Return an integer that uniquely identifies this backend. For
the default backend that integer is 0
.
CLASS Pike.BacktraceFrame |
int(0..1) _is_type(string t)
This object claims to be an array for backward compatibility.
string _sprintf(int c, mapping|void opts)
int(3..) _sizeof()
mixed `[](int index, int|void end_or_none)
The BacktraceFrame object can be indexed as an array.
mixed `[]=(int index, mixed value)
Module Pike.Security |
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.
mixed Pike.Security.call_with_creds(Creds creds, mixed func, mixed ... args)
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.
The current creds or the current object must have the allow bit
BIT_SECURITY set to allow calling with creds other than
0
(zero).
Creds Pike.Security.get_current_creds()
Get the current credentials
Returns the credentials that are currently active.
Returns 0
(zero) if no credentials are active.
call_with_creds()
Creds Pike.Security.get_object_creds(object|program|function|array|mapping|multiset o)
Get the credentials from o .
Returns 0
if o does not have any credentials.
constant Pike.Security.BIT_INDEX
Allow indexing.
constant Pike.Security.BIT_SET_INDEX
Allow setting of indices.
constant Pike.Security.BIT_CALL
Allow calling of functions.
constant Pike.Security.BIT_SECURITY
Allow usage of security related functions.
constant Pike.Security.BIT_NOT_SETUID
Don't change active credentials on function call.
constant Pike.Security.BIT_CONDITIONAL_IO
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 Pike.Security.BIT_DESTRUCT
Allow use of destruct .
CLASS Pike.Security.Creds |
The credentials object.
Creds get_default_creds()
Get the default credentials.
Returns the default credentials object if it has been set.
Returns 0
(zero) if it has not been set.
set_default_creds()
void set_default_creds(Creds creds)
Set the default credentials
The current creds must have the allow bit BIT_SECURITY set.
get_default_creds()
void Pike.Security.Creds(User user, int allow_bits, int data_bits)
Initialize a new credentials object.
Any of the flags BIT_SECURITY and BIT_CONDITIONAL_IO or:ed together.
Any of the flags BIT_INDEX , BIT_SET_INDEX , BIT_CALL , BIT_NOT_SETUID and BIT_DESTRUCT or:ed together.
Throws an exception if the current creds doesn't have the allow bit BIT_SECURITY set.
object get_user()
Get the user part.
int get_allow_bits()
Get the allow_bit bitmask.
int get_data_bits()
Get the data_bits bitmask.
void apply(object|program|function|array|mapping|multiset o)
Set the credentials for o to this credentials object.
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 |
Virtual class for User objects, used in Creds objects.
int(0..3)|string valid_open(string type, object current, string filename, string flags, int access)
This callback gets called when a new file is to be opened (and the Creds object has BIT_CONDITIONAL_IO set).
The type of file operation requested. Can either be "read"
or "write"
.
The current object, i.e. the Fd object the user is trying to open.
The file name requested.
The flag string passed to open, e.g. "cwt"
.
The access flags requested for the file, e.g. 0666
.
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.
|
int(0..3)|array valid_io(string fun, string type, mixed ... args)
This callback gets called when I/O operations not performed on file objects are performed.
Module Pike.DefaultBackend |
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
.
Backend , Stdio.File()->set_nonblocking() , call_out()
Module Process |
int Process.exec(string file, string ... foo)
string Process.search_path(string command)
string Process.sh_quote(string s)
array(string) Process.split_quoted_string(string s, int(0..1)|void nt_mode)
Process Process.spawn(string s, object|void stdin, object|void stdout, object|void stderr, function|void cleanup, mixed ... args)
string Process.popen(string s)
int Process.system(string s)
CLASS Process.create_process |
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.
int wait()
Waits for the process to end.
|
TraceProcess()->wait()
int(-1..2) status()
Returns the status of the process:
|
Prior to Pike 7.5 the value 1 was returned for exited processes.
int(0..) last_signal()
Returns the last signal that was sent to the process.
int pid()
Returns the process identifier of the process.
int set_priority(string priority)
Sets the priority of the process. priority is one of the strings
constant limit_value
Each limit_value may be either of:
sets current limit, max is left as it is.
([ "hard":int, "soft":int ]) Both values are optional, hard <= soft.
({ hard, soft }), both can be set to the string "unlimited". A value of -1 means 'keep the old value'.
The string "unlimited" sets both the hard and soft limit to unlimited
void Process.create_process(array(string) command_args, void|mapping modifiers)
The command name and its command-line arguments. You do not have to worry about quoting them; pike does this for you.
This optional mapping can can contain zero or more of the following parameters:
|
Process.create_process(({ "/usr/bin/env" }), (["env" : getenv() + (["TERM":"vt100"]) ]));
//! 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 }); }
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.
int kill(int signal)
This function is only available on platforms that support signals.
CLASS Process.TraceProcess |
Class that enables tracing of processes.
The new process will be started in stopped state. Use cont() to let it start executing.
This class currently only exists on systems that implement ptrace().
inherit create_process : create_process
int wait()
Waits for the process to stop.
|
create_process::wait()
void cont(int|void signal)
Allow a traced process to continue.
Deliver this signal to the process.
This function may only be called for stopped processes.
wait()
void exit()
Cause the traced process to exit.
This function may only be called for stopped processes.
cont() , wait()
CLASS Process.TraceProcess.Registers |
Interface to the current register contents of a stopped process.
TraceProcess
int `[](int regno)
Get the contents of register regno .
CLASS Process.Process |
Slightly polished version of create_process .
create_process
inherit create_process : create_process
void Process.Process(string|array(string) args, void|mapping(string:mixed) m)
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.
In addition to the modifiers that create_process accepts, this object also accepts
|
create_process , split_quoted_string
CLASS Process.Spawn |
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)
int kill(int signal)
int wait()
Module Thread |
array(Thread.Thread) Thread.all_threads()
This function returns an array with the thread ids of all threads.
Thread()
void Thread.thread_set_concurrency(int concurrency)
Document this function
Thread.Thread Thread.this_thread()
This function returns the object that identifies this thread.
Thread()
inherit Thread : Thread
CLASS Thread.Thread |
void Thread.Thread(function(mixed ... :void) f, mixed ... args)
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.
The returned value will be the same as the return value of this_thread() for the new thread.
This function is only available on systems with POSIX or UNIX or WIN32 threads support.
Mutex , Condition , this_thread()
array(mixed) backtrace()
Returns the current call stack for the thread.
The result has the same format as for predef::backtrace() .
predef::backtrace()
int status()
string _sprintf(int c)
Returns a string identifying the thread.
int id_number()
Returns an id number identifying the thread.
This function was added in Pike 7.2.204.
mixed wait()
Waits for the thread to complete, and then returns the value returned from the thread function.
CLASS Thread.Mutex |
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.
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.
MutexKey lock()
MutexKey lock(int type)
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:
|
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.
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.
trylock()
MutexKey trylock()
MutexKey trylock(int type)
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.
lock()
Thread.Thread current_locking_thread()
This mutex method returns the object that identifies the thread that has locked the mutex. 0 is returned if the mutex isn't locked.
Thread()
Thread.MutexKey current_locking_key()
This mutex method returns the key object currently governing the lock on this mutex. 0 is returned if the mutex isn't locked.
Thread()
CLASS Thread.MutexKey |
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).
Mutex , Condition
CLASS Thread.Condition |
Implementation of condition variables.
Condition variables are used by threaded programs to wait for events happening in other threads.
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.
Mutex
void wait(Thread.MutexKey mutex_key)
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.
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.
Mutex->lock()
void signal()
signal() wakes up one of the threads currently waiting for the condition.
Sometimes more than one thread is woken up.
broadcast()
void broadcast()
broadcast() wakes up all threads currently waiting for this condition.
signal()
CLASS Thread.Local |
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.
This class is simulated when Pike is compiled without thread support, so it's always available.
mixed get()
Get the thread local value.
This returns the value prevoiusly stored in the Local object by the set() method by this thread.
set()
mixed set(mixed value)
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).
This function returns its argument.
Note that the value set can only be retreived by the same thread.
get()
CLASS Thread.Fifo |
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.
Queue
inherit Condition : r_cond
inherit Condition : w_cond
inherit Mutex : lock
int size()
This function returns the number of elements currently in the fifo.
read() , write()
mixed read()
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.
try_read() , read_array() , write()
mixed try_read()
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.
read()
array read_array()
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.
read() , try_read_array()
array try_read_array()
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.
read_array()
int write(mixed value)
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.
read()
int try_write(mixed value)
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.
read()
void Thread.Fifo()
void Thread.Fifo(int size)
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 |
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.
Fifo
inherit Condition : r_cond
inherit Mutex : lock
int size()
This function returns the number of elements currently in the queue.
read() , write()
mixed read()
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.
try_read() , write()
mixed try_read()
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.
write()
array read_array()
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.
read() , try_read_array()
array try_read_array()
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.
read_array()
int write(mixed value)
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.
read()
Module Mapping |
constant Mapping.delete
Alias for m_delete()
CLASS Mapping.Iterator |
An object of this class is returned by get_iterator() when called with a mapping.
get_iterator
inherit predef::Iterator : predef::Iterator
Module Multiset |
CLASS Multiset.Iterator |
An object of this class is returned by get_iterator() when called with a multiset.
get_iterator
inherit predef::Iterator : predef::Iterator
Module Audio |
Module Audio.Format |
Audio data format handling
API remains marked "unstable".
CLASS Audio.Format.MP3 |
A MP3 file parser with ID3 tag support.
inherit .module.ANY : ANY
mapping|int get_frame()
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 |
this_program read_file(string filename, int|void nocheck)
Reads data from file
read_streamed
this_program read_streamed(string filename, int|void nocheck)
Reads data from stream
Ie. for packetized data source the beggining of data is searched.
read_file
this_program read_string(string data, int|void nocheck)
Reads data from string
string get_frame()
Returns frame for current position and moves cursor forward.
The operation is destructive. Ie. current data cursor is moved over.
get_data , get_sample
mapping get_sample()
Returns sample for current position and moves cursor forward.
The operation is destructive. Ie. current data cursor is moved over.
get_frame , get_data
string get_data()
Returns data only.
The operation is destructive. Ie. current data cursor is moved over.
get_frame , get_sample
int check_format()
Check if data are correctly formated.
mapping get_map()
Module Audio.Codec |
CLASS Audio.Codec.decoder |
Decoder object.
It needs _Ffmpeg.ffmpeg module for real work.
void Audio.Codec.decoder(string|void codecname, object|void _codec)
Creates decoder object
Some of supported codec, like _Ffmpeg.CODEC_ID_*
The low level object will be used for decoder. By default _Ffmpeg.ffmpeg object will be used.
Until additional library is implemented the second parameter _codec hasn't effect.
_Ffmpeg.ffmpeg , _Ffmpeg.CODEC_ID_MP2
this_program from_file(Audio.Format.ANY file)
Set codec type from file
It uses Audio.Format.ANY 's method get_map() to determine which codec should be used.
The object Audio.Format.ANY .
mapping|int decode(int|void partial)
Decodes audio data
Only one frame will be decoded per call.
If successfull a mapping with decoded data and byte number of used input data is returned, 0 otherwise.
mapping get_status()
Returns decoder status
Module Cache |
CLASS Cache.cache |
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.
mixed lookup(string key)
Looks in the cache for an element with the given key and, if available, returns it. Returns 0 if the element is not available
void alookup(string key, function(string:void) callback, int|float timeout, mixed ... args)
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.
void store(string key, mixed value, void|int max_life, void|float preciousness, void|multiset(string) dependants)
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.
void delete(string key, void|int(0..1) hard)
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)
void start_cleanup_cycle()
void async_cleanup_cache()
void threaded_cleanup_cycle()
void Cache.cache(Cache.Storage.Base storage_mgr, Cache.Policy.Base policy_mgr, void|int cleanup_cycle_delay)
Creates a new cache object. Required are a storage manager, and an expiration policy object.
Module Cache.Policy |
CLASS Cache.Policy.Base |
Base class for cache expiration policies.
void expire(Cache.Storage.Base storage)
Expire callback.
This function is called to expire parts of storage .
All Storage.Policy classes must MUST implement this method.
CLASS Cache.Policy.Timed |
An access-time-based expiration policy manager.
inherit Cache.Policy.Base : Base
Module Cache.Storage |
CLASS Cache.Storage.Base |
Base class for cache storage managers.
All Cache.Storage managers must provide these methods.
int(0..0)|string first()
int(0..0)|string next()
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.
void set(string key, mixed value, void|int max_life, void|float preciousness, void|multiset(string) dependants)
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.
int(0..0)|Cache.Data get(string key, void|int(0..1) notouch)
Fetch some data from the cache synchronously.
Be careful, as with some storage managers it might block the calling thread for some time.
void aget(string key, function(string:void) callback, mixed ... extra_callback_args)
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.
mixed delete(string key, void|int(0..1) hard)
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 the deleted entry.
Module Calendar |
constant Calendar.nulltimerange = TimeRange
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 |
This is the base class of the calendars.
.TimeRanges.TimeRange now()
Give the zero-length time period of the current time.
CLASS Calendar.Ruleset |
This is the container class for rules.
this_program set_timezone(string|.Rule.Timezone t)
this_program set_language(string|.Rule.Language lang)
this_program set_abbr2zone(mapping(string:string) abbr2zone)
Sets the guess-mapping for timezones. Default is the mapping:
|
YMD.parse
this_program set_rule(.Rule.Language|.Rule.Timezone rule)
this_program clone()
int(0..1) `==(this_program other)
CLASS Calendar.TimeRange |
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.
TimeRange add(int n, void|TimeRange step)
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...
}
TimeRange beginning()
TimeRange end()
This gives back the zero-sized beginning or end of the called time period.
rule: range(t->beginning(),t->end())==t
Calendar calendar()
Simply gives back the calendar in use, for instance Calendar.ISO or Calendar.Discordian.
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)
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
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.
`&
void Calendar.TimeRange("unix", int unixtime)
void Calendar.TimeRange("unix", int unixtime, int seconds_len)
Create the timerange from unix time (as given by time(2)), with eventually the size of the time range in the same unit, seconds.
void Calendar.TimeRange("julian", int|float julian_day)
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.
void Calendar.TimeRange(TimeRange from)
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.
The size of the new object may be inexact; a Month object can't comprehend seconds, for instance.
TimeRange range(TimeRange other)
TimeRange space(TimeRange other)
TimeRange distance(TimeRange other)
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
int `/(TimeRange with)
int how_many(TimeRange with)
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 .
TimeRange set_language(Rule.Language lang)
TimeRange set_language(string lang)
Language language()
Set or get the current language rule.
TimeRange next()
TimeRange prev()
Next and prev are compatible and convinience functions; a->next() is exactly the same as a+1; a=a->next() is a++.
int offset_to(TimeRange x)
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.
TimeRange place(TimeRange this)
TimeRange place(TimeRange this, int(0..1) force)
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).
The rules how to place things in different timeranges can be somewhat 'dwim'.
TimeRange set_ruleset(Ruleset r)
TimeRange ruleset(Ruleset r)
Set or get the current ruleset.
this may include timezone shanges, and change the time of day.
TimeRange set_size(TimeRange size)
TimeRange set_size(int n, TimeRange size)
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.
A negative size is not permitted; a zero one are.
TimeRange set_timezone(Timezone tz)
TimeRange set_timezone(string tz)
TimeZone timezone()
Set or get the current timezone (including dst) rule.
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)->...
array(TimeRange) `/(int n)
array(TimeRange) split(int n)
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 .
TimeRange subtract(TimeRange what)
This subtracts a period of time from another;
>- the past the future -<
|-------called-------|
|-------other--------|
<----> <- called->subtract(other)
|-------called-------|
|---third---|
<----> <---> <- called->subtract(third)
TimeRange `&(TimeRange with)
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 -----<
TimeRange `*(int n)
This changes the amount of time in the time period. t*17 is the same as doing t->set_size (t,17).
TimeRange `+(int n)
TimeRange `+(TimeRange offset)
TimeRange `-(int m)
TimeRange `-(TimeRange x)
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
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.
int(0..1) `<(TimeRange compared_to)
int(0..1) `>(TimeRange compared_to)
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.
int(0..1) `==(TimeRange compared_to)
int(0..1) _equal(TimeRange compared_to)
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.
TimeRange `^(TimeRange with)
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
TimeRange `|(TimeRange with)
Gives the union on the called time period
and another time period.
>- the past the future -<
|-------called-------|
|-------other--------|
<----------union---------->
CLASS Calendar.SuperTimeRange |
This class handles the cases where you have a time period with holes. These can be created by the ^ or | operators on time ranges.
void Calendar.SuperTimeRange(array(TimeRange) parts)
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 |
Same as the ISO calendar, but with austrian as the default language.
This calendar exist only for backwards compatible purposes.
inherit .ISO : ISO
Module Calendar.Coptic |
This is the Coptic Orthodox Church calendar, that starts the 11th or 12th September and has 13 months.
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 : Gregorian
Module Calendar.Discordian |
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 : Gregorian
Module Calendar.Event |
CLASS Calendar.Event.Event |
Event is an abstract class, defining what methods an Event need to have.
constant is_event
This constant may be used to identify an event object.
.TimeRanges.TimeRange next(void|.TimeRanges.TimeRange from, void|int(0..1) including)
.TimeRanges.TimeRange previous(void|.TimeRanges.TimeRange from, void|int(0..1) including)
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.
array(.TimeRanges.TimeRange) scan(.TimeRanges.TimeRange in)
This calculates the eventual events that is contained or overlapped by the given timerange. scan uses next , if not overloaded.
Calendar.Event.Easter()->scan(Calendar.Year(2000)) => ({ Day(Sun 23 Apr 2000) })
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.
mapping(.TimeRanges.TimeRange:Event) scan_events(.TimeRanges.TimeRange in)
Returns a mapping with time ranges mapped to events.
SuperEvent `|(Event ... with)
SuperEvent ``|(Event with)
Joins several events into one SuperEvent .
string describe()
Returns a description of the event.
CLASS Calendar.Event.NullEvent |
A non-event.
inherit Event : Event
constant is_nullevent
This constant may be used to identify a NullEvent.
CLASS Calendar.Event.Day_Event |
Day_Event is an abstract class, extending Event for events that are single days, using julian day numbers for the calculations.
inherit Event : Event
constant is_day_event
This constant may be used to identify Day_Event objects.
constant NODAY
Returned from scan_jd if the even searched for did not exist.
int scan_jd(.Calendar realm, int jd, int(-1..-1)|int(1..1) direction)
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.
|
.TimeRanges.TimeRange next(void|.TimeRanges.TimeRange from, void|int(0..1) including)
Uses the virtual method scan_jd .
Event.next
.TimeRanges.TimeRange previous(void|.TimeRanges.TimeRange from, void|int(0..1) including)
Uses the virtual method scan_jd .
Event.previous
CLASS Calendar.Event.Nameday |
This is created by the Namedays classes to represent an event for a name.
inherit Day_Event : Day_Event
constant is_nameday
This constant may be used to identify Nameday objects.
CLASS Calendar.Event.Namedays |
This contains a ruleset about namedays.
inherit Event : Event
constant is_namedays
This constant may be used to identify Namedays .
array(string) names(.TimeRanges.TimeRange t)
Gives back an array of names that occur during the time period, in no particular order.
mapping(.TimeRanges.TimeRange:array(string)) namedays(.TimeRanges.TimeRange t)
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 |
Container for merged Namedays objects.
inherit Event : Event
CLASS Calendar.Event.Gregorian_Fixed |
A set date of year, counting leap day in February, used for the Gregorian fixed events in the events list.
Julian_Fixed
inherit Day_Event : Day_Event
constant is_fixed
This constant may be used to identify Gregorian_Fixed objects.
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 |
A set date of year, counting leap day in February, used for the Gregorian fixed events in the events list.
Gregorian_Fixed
inherit Gregorian_Fixed : Gregorian_Fixed
constant is_julian_fixed
This constant may be used to identify Julian_Fixed objects.
CLASS Calendar.Event.Date |
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 : Day_Event
void Calendar.Event.Date(int(1..31) month_day, int(1..12) month)
The event is created by a given month day and a month number (1=January, 12=December).
CLASS Calendar.Event.Date_Weekday |
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 : Day_Event
void Calendar.Event.Date_Weekday(int month_day, int month, int weekday)
The event is created by a given month day, a month number (1=January, 12=December), and a weekday number (1=Monday, 7=Sunday).
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 |
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 : Day_Event
void Calendar.Event.Monthday_Weekday(int month_day, int weekday)
The event is created by a given month day, and a weekday number (1=Monday, 7=Sunday).
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 |
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 : Day_Event
void Calendar.Event.Weekday(int weekday, void|string id)
The event is created by a given weekday number (1=Monday, 7=Sunday).
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 |
This class represents an easter.
inherit Day_Event : Day_Event
void Calendar.Event.Easter(void|int shift)
shift is the year to shift from old to new style easter calculation. Default is 1582.
int easter_yd(int y, int yjd, int leap)
Calculates the year day for the easter.
CLASS Calendar.Event.Easter_Relative |
This class represents an easter relative event.
inherit Easter : Easter
void Calendar.Event.Easter_Relative(string id, string name, int offset)
CLASS Calendar.Event.Orthodox_Easter_Relative |
This class represents an orthodox easter relative event.
inherit Easter_Relative : Easter_Relative
void Calendar.Event.Orthodox_Easter_Relative(string id, string name, int offset)
CLASS Calendar.Event.Monthday_Weekday_Relative |
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 : Gregorian_Fixed
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 |
This class holds any number of events, and adds the functionality of event flags.
Scanning (scan_events,next,etc) will drop flag information. Dig out what you need with holidays et al first.
inherit Event : Event
SuperEvent filter_flag(string flag)
SuperEvent holidays()
SuperEvent flagdays()
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 |
Event containing information about when a timezone is changed.
inherit Event : Event
.TimeRanges.TimeRange scan_shift(.Rule.Timezone tz, .TimeRanges.TimeRange from, int direction, int including)
.TimeRanges.TimeRange scan_history(.Rule.Timezone tz, .TimeRanges.TimeRange from, int direction, int(0..1) including)
.TimeRanges.TimeRange scan_rule(.Rule.Timezone tz, .TimeRanges.TimeRange from, int direction, int including)
Module Calendar.Gregorian |
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 : YMD
Module Calendar.ISO |
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 : Gregorian
Module Calendar.Islamic |
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.
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 : YMD
Module Calendar.Julian |
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.)
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 : Gregorian
Module Calendar.Rule |
CLASS Calendar.Rule.Timezone |
Contains a time zone.
void Calendar.Rule.Timezone(int offset, string name)
Offset to UTC, not counting DST.
The name of the time zone.
array tz_ux(int unixtime)
This method takes one integer argument, ignores it and returns an array with the UTC offset and the timezone name.
array tz_jd(int julian_day)
This method takes one integer argument, ignores it and returns an array with the UTC offset and the timezone name.
int raw_utc_offset()
Returns the offset to UTC, not counting DST.
Module Calendar.Stardate |
This implements TNG stardates.
cTick Calendar.Stardate.now()
Give the zero-length time period of the current time.
CLASS Calendar.Stardate.cTick |
inherit Calendar.TimeRange : TimeRange
void Calendar.Stardate.cTick(mixed ... args)
void Calendar.Stardate.cTick(int|float date)
void Calendar.Stardate.cTick()
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.
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)
float tic()
This gives back the start of the stardate period, as a float.
float tics()
This gives back the number of stardate tics in the period.
int number_of_seconds()
This gives back the Gregorian/Earth/ISO number of seconds, for convinience and conversion to other calendars.
int number_of_days()
This gives back the Gregorian/Earth/ISO number of days, for convinience and conversion to other calendars.
string format_long(void|int precision)
string format_short(void|int precision)
string format_vshort(void|int precision)
Format the stardate tick nicely. Precision is the number of decimals. Defaults to 3.
|
Module Calendar.Swedish |
Same as the ISO calendar, but with Swedish as the default language.
This calendar exist only for backwards compatible purposes.
inherit .ISO : ISO
Module Calendar.TZnames |
This module contains listnings of available timezones, in some different ways
constant Calendar.TZnames.zones = mapping(string:array(string))
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 Calendar.TZnames.abbr2zones = mapping(string:array(string))
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.
array(string) Calendar.TZnames.zonenames()
This reads the zone.tab file and returns name of all standard timezones, like "Europe/Belgrade".
string Calendar.TZnames._zone_tab()
array(array) Calendar.TZnames.zone_tab()
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 |
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 |
Virtual class used by e.g. Hour.
void call_out(function fun, mixed ...args)
Creates a call_out to this point in time.
void Calendar.Time.TimeofDay()
void Calendar.Time.TimeofDay(int unixtime)
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".
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()
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
int hour_no()
int minute_no()
int second_no()
float fraction_no()
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
]);
Hour hour()
Hour hour(int n)
array(Hour) hours()
array(Hour) hours(int first, int last)
int number_of_hours()
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)
})
float julian_day()
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.
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.
Minute minute()
Minute minute(int n)
array(Minute) minutes()
array(Minute) minutes(int first, int last)
int number_of_minutes()
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.
TimeRange move_seconds(int seconds)
TimeRange move_ns(int nanoseconds)
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.
Second second()
Second second(int n)
array(Second) seconds()
array(Second) seconds(int first, int last)
int number_of_seconds()
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.
TimeRange set_size_seconds(int seconds)
TimeRange set_size_ns(int nanoseconds)
These two methods allows the time range to be edited by size of specific units.
int unix_time()
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 |
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()
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 |
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.
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.
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)
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.
TimeofDay now()
Give the zero-length time period of the current time.
Calendar set_ruleset(Ruleset r)
Ruleset ruleset()
Set or read the ruleset for the calendar. set_ruleset returns a new calendar object, but with the new ruleset.
Calendar set_timezone(Timezone tz)
Calendar set_timezone(string|Timezone tz)
TimeZone timezone()
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 |
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");
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
TZnames
constant Calendar.Timezone.locale = Rule.Timezone
This contains the local timezone, found from various parts of the system, if possible.
constant Calendar.Timezone.localtime = Rule.Timezone
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 |
base for all Roman-kind of Calendars, ie, one with years, months, weeks and days
CLASS Calendar.YMD.YMD |
Base (virtual) time period of the Roman-kind of calendar.
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()
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.
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()
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
]);
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.
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 |
This is the time period of a year.
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)
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.
Month month()
Month month(int n)
Month month(string name)
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 ().
Week week()
Week week(int n)
Week week(string name)
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 |
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.
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)
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.
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)
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.
Day day()
Day day(int n)
Day day(string name)
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 ().
the weekday-from-string routine is language dependent.
CLASS Calendar.YMD.Hour |
global convinience functions
TimeRange parse(string fmt, string arg)
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)
0 if format doesn't match data, or the appropriate time object.
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 |
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 |
Base class for units of time.
array(string) lesser()
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.
array(string) greater()
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.
object next()
object prev()
object `+(int n)
object `-(int n)
object `-(object x)
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 |
time units: Year , Month , Week , Day
object Calendar_I.Gregorian.parse(string fmt, string arg)
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)
mapping(string:int) Calendar_I.Gregorian.datetime(int|void unix_time, int|void skip_extra)
Replacement for localtime.
string Calendar_I.Gregorian.datetime_name(int|void unix_time)
Replacement for ctime.
string Calendar_I.Gregorian.datetime_short_name(int|void unix_time)
Replacement for ctime.
CLASS Calendar_I.Gregorian.Year |
A Calendar_I.time_unit
Lesser units: Month , Week , Day Greater units: none
inherit _TimeUnit : _TimeUnit
Module Calendar_I.Stardate |
time unit: TNGDate
CLASS Calendar_I.Stardate.TNGDate |
Implements ST:TNG stardates. Can be used as create argument to Day.
inherit Calendar_I._TimeUnit : _TimeUnit
Module Debug |
string Debug.pp_memory_usage()
Returns a pretty printed version of the output from memory_usage .
void Debug.verify_internals()
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.
This function does a more thorough check if the Pike runtime has been compiled with RTL debug.
int Debug.debug(int(0..) level)
Set the run-time debug level.
The old debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
int Debug.optimizer_debug(int(0..) level)
Set the optimizer debug level.
The old optimizer debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
int Debug.assembler_debug(int(0..) level)
Set the assembler debug level.
The old assembler debug level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
int Debug.compiler_trace(int(0..) level)
Set the compiler trace level.
The old compiler trace level will be returned.
This function is only available if the Pike runtime has been compiled with RTL debug.
mapping(string:int) Debug.memory_usage()
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.
Exactly what this function returns is version dependant.
_verify_internals()
void Debug.reset_dmalloc()
Only available when compiled with dmalloc.
void Debug.dmalloc_set_name(string filename, int linenumber)
Only available when compiled with dmalloc.
void Debug.list_open_fds()
Only available when compiled with dmalloc.
void Debug.locate_references(string|array|mapping|multiset|function|object|program|type(mixed) o)
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
.
This function only exists if the Pike runtime has been compiled with RTL debug.
mixed Debug.describe(mixed x)
Prints out a description of the thing x to standard error. The description contains various internal info associated with x .
This function only exists if the Pike runtime has been compiled with RTL debug.
void Debug.gc_set_watch(array|multiset|mapping|object|function|program|string x)
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.
This function only exists if the Pike runtime has been compiled with RTL debug.
void Debug.dump_backlog()
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.
This function only exists if the Pike runtime has been compiled with RTL debug.
mapping(string:int|float) Debug.gc_status()
Get statistics from the garbage collector.
A mapping with the following content will be returned:
|
gc() , Pike.gc_parameters()
array(array(int|string)) Debug.describe_program(program p)
Debug function for showing the symbol table of a program.
CLASS Debug.Subject |
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.
> 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 |
A class that when instatiated will turn on trace, and when it's destroyed will turn it off again.
void Debug.Tracer(int level)
Sets the level of debug trace to level .
CLASS Debug.Wrapper |
This wrapper can be placed around another object to get printouts about what is happening to it. Only a few LFUNs are currently supported.
> 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
void Debug.Wrapper(object x)
int(0..1) `!()
mixed `[](mixed x, void|mixed y)
mixed `->(mixed x)
array _indices()
array _values()
int _sizeof()
string _sprintf(int c, mapping(string:mixed)|void attrs)
Module Filesystem |
int Filesystem.parse_mode(int old, int|string mode)
FIXME: Document this function
program Filesystem.get_filesystem(string what)
FIXME: Document this function
function Filesystem.`()(void|string path)
FIXME: Document this function
CLASS Filesystem.System |
Implements an abstraction of the normal filesystem.
inherit Filesystem.Base : Base
void Filesystem.System(void|string directory, void|string root, void|int fast, void|Filesystem.Base parent)
Instanciate a new object representing the filesystem.
The directory (in the real filesystem) that should become the root of the filesystemobject.
Internal
Internal
Internal
CLASS Filesystem.Stat |
Describes the stat of a file
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()
Is the file a FIFO?
Is the file a character device?
Is the file (?) a directory?
Is the file a block device?
Is the file a regular file?
Is the file a link to some other file or directory?
Is the file a socket?
FIXME: Document this function.
1 if the file is of a specific type 0 if the file is not.
[set_type]
void set_type(string x)
Set a type for the stat-object.
This call doesnot change the filetype in the underlaying filesystem.
Type to set. Type is one of the following:
[isfifo], [ischr], [isdir], [isblk], [isreg], [islnk], [issock], [isdoor]
void attach_statarray(array(int) a)
Fills the stat-object with data from a Stdio.File.stat() call.
Stdio.File open(string mode)
Open the stated file within the filesystem
a [Stdio.File] object
[Stdio.File]
object cd()
Change to the stated directory.
the directory if the stated object was a directory, 0 otherwise.
string nice_date()
Returns the date of the stated object as cleartext.
CLASS Filesystem.Base |
Baseclass that can be extended to create new filesystems. Is used by the Tar and System filesystem classes.
Base cd(string|void directory)
Change directory within the filesystem. Returns a new filesystem object with the given directory as cwd.
string cwd()
Returns the current working directory within the filesystem.
Base chroot(void|string directory)
Change the root of the filesystem.
Stat stat(string file, int|void lstat)
Return a stat-object for a file or a directory within the filesystem.
array(string) get_dir(void|string directory, void|string|array glob)
Returns an array of all files and directories within a given directory.
Directory where the search should be made within the filesystem. CWD is assumed if none (or 0) is given.
Return only files and dirs matching the glob (if given).
[get_stats]
array(Stat) get_stats(void|string directory, void|string|array glob)
Returns stat-objects for the files and directories matching the given glob within the given directory.
[get_dir]
Stdio.File open(string filename, string mode)
Open a file within the filesystem
A Stdio.File object.
int apply()
FIXME: Document this function
void chmod(string filename, int|string mode)
Change mode of a file or directory.
void chown(string filename, int|object owner, int|object group)
Change ownership of the file or directory
int mkdir(string directory, void|int|string mode)
Create a new directory
int rm(string filename)
Remove a file from the filesystem.
array find(void|function(Stat:int) mask, mixed ... extra)
FIXME: Document this function
CLASS Filesystem.Traversion |
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:
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 }
float progress(void|float share)
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.
void Filesystem.Traversion(string path, void|int(0..1) symlink)
The root path from which to traverse.
Don't traverse symlink directories.
Stdio.Stat stat()
Returns the stat for the current index-value-pair.
Module Filesystem.Tar |
void Filesystem.Tar.(string filename, void|Filesystem.Base parent, void|object file)
Filesystem which can be used to mount a Tar file.
The tar file to mount.
The parent filesystem. If non is given, the normal system filesystem is assumed. This allows mounting a TAR-file within a tarfile.
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 |
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.
float lat
Latitude (N--S) of the position, in degrees. Positive number is north, negative number is south.
float long
Longitude (W--E) of the position, in degrees. Positive number is east, negative number is west.
float alt
Altitud of the position, in meters. Positive numbers is up. Zero is the shell of the current ellipsoid.
void Geography.Position(float lat, float long, void|float alt)
void Geography.Position(string lat, string long)
void Geography.Position(string both)
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.
string latitude(void|int n)
string longitude(void|int n)
Returns the nicely formatted latitude or longitude.
|
string standard_grid()
Returns the standard map grid system for the current position. Can either be "UPS" or "UTM".
float polar_radius
The polar radius is how many meters the earth radius is at the poles (north-south direction).
float equatorial_radius
The equatorial radius is how many meters the earth radius is at the equator (east-west direction).
float flattening()
Returns the flattening factor for the selected earth approximation ellipsoid.
float eccentricity_squared()
Returns the first eccentricity squared for the selected earth approximation ellipsoid.
constant ellipsoids
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.
int(0..1) set_ellipsoid(string name)
int(0..1) set_ellipsoid(float equatorial_radius, float polar_radius)
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.
|
The longitude and lattitude are not converted to the new ellipsoid.
int UTM_zone_number()
Returns the UTM zone number for the current longitude, with correction for the Svalbard deviations.
string UTM_zone_designator()
Returns the UTM letter designator for the current latitude. Returns "Z" if latitude is outside the UTM limits of 84N to 80S.
array(float) UTM_offset()
Returns the offset within the present UTM cell. The result will be returned in an array of floats, containing easting and northing.
string UTM()
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.
void set_from_UTM(int zone_number, string zone_designator, float UTME, float UTMN)
Sets the longitude and lattitude from the given UTM coordinates.
string GEOREF()
Gives the full GEOREF position for the current position, e.g. "LDJA0511".
array(float) RT38()
void set_from_RT38(int|float|string x_n, int|float|string y_e)
Sets the longitude and lattitude from the given RT38 coordinates.
float approx_height()
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.
array(float) ECEF()
Returns the current position as Earth Centered Earth Fixed Cartesian Coordinates.
({ X, Y, Z })
int __hash()
int `==(object pos)
int `<(object pos)
int `>(object pos)
string _sprintf(int|void t)
float euclidian_distance(this_program p)
Calculate the euclidian distance between two Geography.Position. Result is in meter. This uses the ECEF function.
CLASS Geography.PositionRT38 |
Create a Position object from a RT38 coordinate
inherit .Position : Position
Module Geography.Countries |
array(Country) Geography.Countries.countries
All known countries.
Country Geography.Countries.from_domain(string domain)
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:
International
US Military
Network
Non-Profit Organization
Old style Arpanet
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>
Country Geography.Countries.from_domain(string name)
Look up a country from its name or aka. The search is case-insensitive but regards whitespace and interpunctation.
mapping(string:array(Country)) Geography.Countries.continents()
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"
Some countries are considered to be on more than one continent.
mixed Geography.Countries.`[](string what)
mixed Geography.Countries.`->(string what)
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 |
Country
string iso2
ISO 2-character code aka domain name
string fips10
FIPS 10-character code; "Federal Information Processing Standards 10-3" etc, used by some goverments in the US.
string name
array(string) aka
Country name and as-known-as, if any
int former
Flag that is set if this country doesn't exist anymore. (eg USSR.)
string continent()
Returns the continent of the country.
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.
string cast("string")
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 : polyline
inherit .create_graph : create_graph
inherit .create_bars : create_bars
inherit .create_pie : create_pie
mapping(string:mixed) Graphics.Graph.check_mapping(mapping(string:mixed) diagram_data, string type)
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 .
Image.Image Graphics.Graph.pie(mapping(string:mixed) diagram_data)
Document this function
Image.Image Graphics.Graph.bars(mapping(string:mixed) diagram_data)
Document this function
Image.Image Graphics.Graph.sumbars(mapping(string:mixed) diagram_data)
Document this function
Image.Image Graphics.Graph.line(mapping(string:mixed) diagram_data)
Document this function
Image.Image Graphics.Graph.norm(mapping(string:mixed) diagram_data)
Document this function
Image.Image Graphics.Graph.graph(mapping(string:mixed) diagram_data)
Document this function
CLASS Graphics.Graph.create_bars |
Graph sub-module for drawing bars.
inherit "polyline.pike"
inherit "create_graph.pike"
CLASS Graphics.Graph.create_graph |
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"
CLASS Graphics.Graph.create_pie |
Graph sub-module for drawing pie-charts.
inherit "polyline.pike"
inherit "create_graph.pike"
inherit "create_bars.pike"
CLASS Graphics.Graph.polyline |
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 |
PLIS, Permuted Lisp. A Lisp language somewhat similar to scheme.
void Languages.PLIS.init_specials(Environment environment)
Adds the special functions quote, set!, setq, while, define, defmacro, lambda, if, and, or, begin and catch to the environment .
void Languages.PLIS.init_functions(Environment environment)
Adds the functions +, *, -, =, <, >, concat, read-string, eval, apply, global-environment, var, cdr, null?, setcar!, setcdr!, cons and list to the environment .
Environment Languages.PLIS.default_environment()
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))))
void Languages.PLIS.main()
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 |
mixed `()(mixed ... args)
mixed sync(mixed ... args)
void async(mixed ... args)
int exists()
int is_async()
void set_async(int a)
void Remote.Call(string objectid, string name, object connection, object context, int async)
CLASS Remote.Connection |
void Remote.Connection(void|int nice, void|int max_call_threads)
If set, no errors will be thrown.
int connect(string host, int port, void|int timeout)
This function is called by clients to connect to a server.
void start_server(object c, object cx)
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.
void add_close_callback(function f, mixed ... args)
Add a function that is called when the connection is closed.
void remove_close_callback(array f)
Remove a function that is called when the connection is closed.
void close()
Closes the connection nicely, after waiting in outstanding calls in both directions.
mixed call_sync(array data)
Make a call and wait for the result
void call_async(array data)
Make a call but don't wait for the result
object get_named_object(string name)
Get a named object provided by the server.
CLASS Remote.Context |
string id_for(mixed thing)
object object_for(string id)
object function_for(string id)
array encode(mixed val)
mixed decode(array a)
array encode_call(object|string o, string|function f, array args, int type)
function|object decode_call(array data)
int decode_existp(array data)
void add(object o, string id)
string describe(array data)
void set_server_context(object ctx, object cn)
void Remote.Context(string b, object|void cn)
CLASS Remote.Obj |
mixed get_function(string f)
mixed `[](string f)
mixed `->(string f)
int exists()
void Remote.Obj(string id, object connection, object context)
Module Standards |
CLASS Standards.URI |
This class implements URI parsing and resolving of relative references to absolute form, as defined in RFC 2396
string scheme
Scheme component of URI
string authority
Authority component of URI (formerly called net_loc, from RFC 2396 known as authority)
string path
Path component of URI. May be empty, but not undefined.
string query
Query component of URI. May be 0 if not present.
string fragment
The fragment part of URI. May be 0 if not present.
string host
string user
string password
Certain classes of URI (e.g. URL) may have these defined
int port
If no port number is present in URI, but the scheme used has a default port number, this number is put here.
this_program base_uri
The base URI object, if present
int `==(mixed something)
Compare this URI to something, in a canonical way.
Compare the URI to this
void reparse_uri()
void reparse_uri(URI base_uri)
void reparse_uri(string base_uri)
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.
Set the new base URI to this.
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)
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.
When uri is another URI object, the created URI will inherit all properties of the supplied uri except, of course, for its base_uri.
mixed `->=(string property, mixed value)
mixed `[]=(string property, mixed value)
Assign a new value to a property of URI
When any of the following properties are used, properties that depend on them are recalculated: user, password, host, port, authority, base_uri.
The value to assign to property
string|mapping cast(string to)
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.
string get_path_query()
Returns path and query part of the URI if present.
Module Standards.ASN1 |
Module Standards.ASN1.Decode |
Decodes a DER object.
Object Standards.ASN1.Decode.der_decode(ADT.struct data, mapping(int:program) types)
an instance of ADT.struct
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 .
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.
Handling of implicit and explicit ASN.1 tagging, as well as other context dependence, is next to non_existant.
Object Standards.ASN1.Decode.simple_der_decode(string data)
decode a DER encoded object using universal data types
a DER encoded object
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 |
Primitive unconstructed ASN1 data type.
inherit Types.Object : Object
string get_der()
int get_combined_tag()
get raw encoded contents of object
int get_tag()
get tag
int get_cls()
get class
CLASS Standards.ASN1.Decode.constructed |
constructed type
inherit Types.Object : Object
string raw
raw encoded contents
array elements
elements of object
int get_tag()
get tag
int get_cls()
get class
Module Standards.ASN1.Types |
Encodes various asn.1 objects according to the Distinguished Encoding Rules (DER)
int Standards.ASN1.Types.make_combined_tag(int cls, int tag)
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.
ASN1 type class
ASN1 type tag
combined tag
Standards.ASN1.Types.extract_tag Standards.ASN1.Types.extract_cls
int Standards.ASN1.Types.extract_tag(int i)
extract ASN1 type tag from a combined tag
Standards.ASN1.Types.make_combined_tag
int Standards.ASN1.Types.extract_cls(int i)
extract ASN1 type class from a combined tag
Standards.ASN1.Types.make_combined_tag
int(1..1) Standards.ASN1.Types.asn1_utf8_valid(string s)
Checks if a Pike string can be encoded with UTF8. That is always the case...
int(0..1) Standards.ASN1.Types.asn1_printable_valid(string s)
Checks if a Pike string can be encoded as a PrintableString .
int(0..1) Standards.ASN1.Types.asn1_teletex_valid(string s)
int(0..1) Standards.ASN1.Types.asn1_broken_teletex_valid(string s)
int(0..1) Standards.ASN1.Types.asn1_IA5_valid(string s)
int(0..0) Standards.ASN1.Types.asn1_universal_valid(string s)
int(0..1) Standards.ASN1.Types.asn1_bmp_valid(string s)
CLASS Standards.ASN1.Types.Object |
Generic, abstract base class for ASN1 data types.
int get_cls()
Get the class of this object.
The class of this object.
int get_tag()
Get the tag for this object.
The tag for this object.
int get_combined_tag()
Get the combined tag (tag + class) for this object.
the combined tag header
string get_der()
Get the DER encoded version of this object.
DER encoded representation of this object.
CLASS Standards.ASN1.Types.Compound |
Compound object primitive
inherit Object : Object
array(Object) elements
contents of compound object, elements are from Standards.ASN1.Types
CLASS Standards.ASN1.Types.String |
string object primitive
inherit Object : Object
string value
value of object
CLASS Standards.ASN1.Types.Boolean |
boolean object
inherit Object : Object
int value
value of object
CLASS Standards.ASN1.Types.Integer |
Integer object All integers are represented as bignums, for simplicity
inherit Object : Object
Gmp.mpz value
value of object
CLASS Standards.ASN1.Types.Enumerated |
Enumerated object
inherit Integer : Integer
CLASS Standards.ASN1.Types.BitString |
Bit string object
inherit Object : Object
string value
value of object
this_program set_from_ascii(string s)
Set the bitstring value as a string with "1"
and
"0"
.
int set_length(int len)
Sets the length of the bit string to len number of bits.
CLASS Standards.ASN1.Types.OctetString |
Octet string object
inherit String : String
CLASS Standards.ASN1.Types.Null |
Null object
inherit Object : Object
CLASS Standards.ASN1.Types.Identifier |
Object identifier object
inherit Object : Object
array(int) id
value of object
this_program append(int ... args)
Returns a new Identifier object with args appended to the ID path.
CLASS Standards.ASN1.Types.UTF8String |
UTF8 string object
Character set: ISO/IEC 10646-1 (compatible with Unicode).
Variable width encoding, see rfc2279.
inherit String : String
CLASS Standards.ASN1.Types.Sequence |
Sequence object
inherit Compound : Compound
CLASS Standards.ASN1.Types.Set |
Set object
inherit Compound : Compound
CLASS Standards.ASN1.Types.PrintableString |
PrintableString object
inherit String : String
CLASS Standards.ASN1.Types.TeletexString |
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 : String
CLASS Standards.ASN1.Types.BrokenTeletexString |
(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 : String
CLASS Standards.ASN1.Types.IA5String |
IA5 String object
Character set: ASCII. Fixed width encoding with 1 octet per character.
inherit String : String
CLASS Standards.ASN1.Types.VisibleString |
inherit String : String
CLASS Standards.ASN1.Types.UTC |
inherit String : String
CLASS Standards.ASN1.Types.UniversalString |
Universal String object
Character set: ISO/IEC 10646-1 (compatible with Unicode). Fixed width encoding with 4 octets per character.
The encoding is very likely UCS-4, but that's not yet verified.
inherit OctetString : OctetString
CLASS Standards.ASN1.Types.BMPString |
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 : OctetString
CLASS Standards.ASN1.Types.MetaExplicit |
Meta-instances handle a particular explicit tag and set of types.
document me!
Module Standards.PKCS |
Module Standards.PKCS.CSR |
Handling of Certifikate Signing Requests (PKCS-10)
Sequence Standards.PKCS.CSR.build_csr(Crypto.RSA rsa, object name, mapping(string:array(object)) attributes)
Module Standards.PKCS.Certificate |
Handle PKCS-6 and PKCS-10 certificates and certificate requests.
Sequence Standards.PKCS.Certificate.build_distinguished_name(mapping(string:object) ... args)
Sequence Standards.PKCS.Certificate.get_certificate_issuer(string cert)
Return the certificate issuer RDN from a certificate string.
A string containing an X509 certificate.
Note that the certificate normally must be decoded using MIME.decode_base64 .
An Standards.ASN1.Sequence object containing the certificate issuer Distinguished Name (DN).
string Standards.PKCS.Certificate.get_dn_string(Sequence dnsequence)
Converts an RDN (relative distinguished name) Seqeunce object to a human readable string in X500 format.
A string containing an X509 certificate.
Note that the certificate normally must be decoded using MIME.decode_base64 .
A string containing the certificate issuer Distinguished Name (DN) in human readable X500 format.
We don't currently handle attributes with multiple values, not all attribute types are understood.
Sequence Standards.PKCS.Certificate.get_certificate_subject(string cert)
Return the certificate subject RDN from a certificate string.
A string containing an X509 certificate.
Note that the certificate normally must be decoded using MIME.decode_base64 .
An Standards.ASN1.Sequence object containing the certificate subject Distinguished Name (DN).
Module Standards.PKCS.DSA |
DSA operations as defined in RFC-2459.
Sequence Standards.PKCS.DSA.algorithm_identifier(Crypto.DSA|void dsa)
string Standards.PKCS.DSA.public_key(Crypto.DSA dsa)
string Standards.PKCS.DSA.private_key(Crypto.DSA dsa)
Crypto.DSA Standards.PKCS.DSA.parse_private_key(string key)
Module Standards.PKCS.Identifiers |
Various ASN.1 identifiers used by PKCS.
Module Standards.PKCS.RSA |
RSA operations and types as described in PKCS-1.
string Standards.PKCS.RSA.public_key(Crypto.RSA rsa)
Create a DER-coded RSAPublicKey structure
Crypto.RSA object
ASN1 coded RSAPublicKey structure
string Standards.PKCS.RSA.private_key(Crypto.RSA rsa)
Create a DER-coded RSAPrivateKey structure
Crypto.RSA object
ASN1 coded RSAPrivateKey structure
Crypto.RSA Standards.PKCS.RSA.parse_public_key(string key)
Decode a DER-coded RSAPublicKey structure
RSAPublicKey provided in ASN1 encoded format
Crypto.RSA object
Crypto.RSA Standards.PKCS.RSA.parse_private_key(string key)
Decode a DER-coded RSAPrivateKey structure
RSAPrivateKey provided in ASN1 encoded format
Crypto.RSA object
Module Standards.PKCS.Signature |
string Standards.PKCS.Signature.build_digestinfo(string msg, Crypto.Hash hash)
Construct a PKCS-1 digestinfo
message to digest
crypto hash object such as Crypto.SHA or Crypto.MD5
Module Standards.EXIF |
This module implements EXIF (Exchangeable image file format for Digital Still Cameras) 2.2 parsing.
mapping Standards.EXIF.get_properties(Stdio.File file)
Retrieve the EXIF properties of the given file.
The Stdio.File object containing wanted EXIF properties.
A mapping with all found EXIF properties.
Module Standards.ID3 |
ID3 decoder/encoder. Supports versions 1.0, 1.1, 2.2-2.4. For more info see http://www.id3.org
Note that this implementation is far from complete and that interface changes might be neccessary during the implementation of the full standard.
int Standards.ID3.synchsafe_to_int(array(int) bytes)
Decodes a synchsafe integer, generated according to ID3v2.4.0-structure section 6.2.
int_to_synchsafe
array(int) Standards.ID3.int_to_synchsafe(int in, void|int no_bytes)
Encodes a integer to a synchsafe integer according to ID3v2.4.0-structure section 6.2.
synchsafe_to_int
string Standards.ID3.resynchronise(string in)
Reverses the effects of unsyncronisation done according to ID3v2.4.0-structure section 6.1.
unsynchronise
string Standards.ID3.unsynchronise(string in)
Unsynchronises the string according to ID3v2.4.0-structure section 6.1.
resynchronise
string Standards.ID3.decode_string(string in, int type)
Decodes the string in from the type , according to ID3v2.4.0-structure section 4, into a wide string.
encode_string
array(string|int) Standards.ID3.encode_string(string in)
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.
decode_string , encode_strings
array(string|int) Standards.ID3.encode_strings(array(string) in)
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.
decode_string , encode_string
CLASS Standards.ID3.Buffer |
A wrapper around a Stdio.File object that provides a read limit capability.
Stdio.File buffervoid Standards.ID3.Buffer(Stdio.File buffer)
string read(int bytes)
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 .
string peek()
Preview the next byte. Technically it is read from the encapsulated buffer and put locally to avoid seeking.
void set_limit(int bytes)
Set an artificial EOF bytes bytes further into the buffer.
int bytes_left()
The number of bytes left before reaching the limit set by set_limit .
CLASS Standards.ID3.TagHeader |
Represents an ID3v2 header.
void Standards.ID3.TagHeader(void|Buffer buffer)
void decode(Buffer buffer)
Decode a tag header from buffer and store its data in this object.
string encode()
Encode the data in this tag and return as a string.
int(0..1) set_flag_unsynchronisation(array(Frame) frames)
Should the unsynchronisation flag be set or not?
CLASS Standards.ID3.ExtendedHeader |
void Standards.ID3.ExtendedHeader(void|Buffer buffer)
void decode(Buffer buffer)
string encode()
CLASS Standards.ID3.FrameData |
Abstract class for frame data.
void Standards.ID3.FrameData(void|string data)
int(0..1) changed()
Is the content altered?
CLASS Standards.ID3.Tagv2 |
ID3 version 2 (2.2, 2.3, 2.4) Tags
void Standards.ID3.Tagv2(void|Buffer|Stdio.File buffer, void|int(0..1) _best_effort)
CLASS Standards.ID3.Tagv1 |
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 |
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.
Version 1 tag is searched only if version 2 isn't found.
Tagv2 , Tagv1
void Standards.ID3.Tag(Stdio.File fd)
The file object fd is searched for version 2 tags, and if not found, version 1 tags.
If no tag was found in the file an error is thrown.
mixed `[](string index)
mixed `->(string index)
The index operators are overloaded to index the encapsulated Tagv1 or Tagv2 object.
constant version
The version of the encapsulated tag in the form "%d.%d.%d"
.
array _indices()
Indices will return the indices of the tag object.
array _values()
Values will return the values of the tag object.
mapping(string:string) friendly_values()
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.
|
Module Standards.IDNA |
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.
object Standards.IDNA.Punycode
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.
string Standards.IDNA.nameprep(string s, int(0..1)|void allow_unassigned)
Prepare a Unicode string for ACE transcoding. Used by to_ascii . Nameprep is a profile of Stringprep, which is described in RFC 3454.
The string to prep.
Set this flag the the string to transform is a "query string", and not a "stored string". See RFC 3454.
string Standards.IDNA.to_ascii(string s, int(0..1)|void allow_unassigned, int(0..1)|void use_std3_ascii_rules)
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.
The sequence of Unicode code points to transform.
Set this flag if the the string to transform is a "query string", and not a "stored string". See RFC 3454.
Set this flag to enforce the restrictions on ASCII characters in host names imposed by STD3.
string Standards.IDNA.to_unicode(string s)
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.
The sequence of Unicode code points to transform.
string Standards.IDNA.zone_to_ascii(string s, int(0..1)|void allow_unassigned, int(0..1)|void use_std3_ascii_rules)
Takes a sequence of labels separated by '.' and applies to_ascii on each.
string Standards.IDNA.zone_to_unicode(string s)
Takes a sequence of labels separated by '.' and applies to_unicode on each.
Module Standards.ISO639_2 |
string Standards.ISO639_2.get_language(string code)
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.
string Standards.ISO639_2.get_language_t(string code)
Look up the language name given an ISO 639-2/T code in lower case. Returns zero typed zero on failure.
string Standards.ISO639_2.get_language_b(string code)
Look up the language name given an ISO 639-2/B code in lower case. Returns zero typed zero on failure.
mapping(string:string) Standards.ISO639_2.list_languages()
Return a mapping from ISO 639-2/T + ISO 639-2/B codes to language names.
mapping(string:string) Standards.ISO639_2.list_languages_t()
Return a mapping from ISO 639-2/T codes to language names.
mapping(string:string) Standards.ISO639_2.list_languages_b()
Return a mapping from ISO 639-2/B codes to language names.
string Standards.ISO639_2.convert_b_to_t(string code)
Converts an ISO 639-2/B code to an ISO 639-2/T code.
string Standards.ISO639_2.convert_t_to_b(string code)
Converts an ISO 639-2/T code to an ISO 639-2/B code.
string Standards.ISO639_2.map_639_1(string code)
Look up the ISO 639-2/T code given an ISO 639-1 code in lower case.
string Standards.ISO639_2.map_to_639_1(string code)
Look up the ISO 639-1 code given an ISO 639-2/T code in lower case.
mapping(string:string) Standards.ISO639_2.list_639_1()
Return a mapping from ISO 639-1 code to ISO 639-2/T code.
Module Tools |
CLASS Tools.PV |
Display a image on the screen. Requires GTK.
inherit GTK.Window : Window
typedef Standards.URI|string|Image.Image|Image.Layer|array(Image.Layer) PVImage
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.
void set_alpha_mode(AlphaMode m)
Set the alpha combining mode. m is one of Squares , Solid , None and AlphaOnly .
void set_alpha_colors(Image.Color.Color c1, Image.Color.Color|void c2)
Set the colors used for the alpha combination. c2 is only used for the Squares alpha mode.
set_alpha_mode()
Image.Image get_as_image(PVImage i)
Return the current image as a Image object, with the alpha combining done.
void set_image(PVImage i)
Change the image.
void scale(float factor)
Scale the image before display with the specified factor.
void save(string filename, string|void format)
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 |
The alpha combination modes.
Use set_alpha_mode() to change the mode.
constant Squares
Checkerboard pattern (default).
constant Solid
Solid color.
constant None
Ignore alpha.
constant AlphaOnly
Only show the alpha channel (if any).
Module Tools.AutoDoc |
Module Tools.AutoDoc.ProcessXML |
inherit Parser.XML.Tree : Tree
inherit "module.pmod"
string Tools.AutoDoc.ProcessXML.extractXML(string filename, int|void pikeMode, string|void type, string|void name, array(string)|void parentModules)
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.
The file to extract from.
Non-zero if it is a Pike file. If the file contains style doc comments, C-mode is used despite pikeMode != 0.
"class"
, "module"
or "namespace"
.
The name of the class/module/namespace.
The ancestors of the class/module/namespace.
// To extract doc for Foo.Bar.Ippa: string xml = extractXML("lib/modules/Foo.pmod/Bar.pmod/Ippa.pike", 1, "class", "Ippa", ({ "Foo", "Bar" }));
string Tools.AutoDoc.ProcessXML.moveImages(string docXMLFile, string imageSourceDir, string imageDestDir, int|void quiet)
Copy all images to canonical files in a flat directory.
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 .
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.
The directory where the images should be copied.
Quiet operation.
The XML file contents (with decorated <image>-tags)
void Tools.AutoDoc.ProcessXML.mergeTrees(Node dest, Node source)
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.
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.
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.
void Tools.AutoDoc.ProcessXML.handleAppears(Node root)
Take care of all the @appears and @belongs directives everywhere, and rearranges the nodes in the tree accordingly
The root (<autodoc>) node of the documentation tree.
void Tools.AutoDoc.ProcessXML.postProcess(Node root)
Perform the last steps on a completed documentation tree.
Root <autodoc> node of the completed documentation tree.
Calls handleAppears() , cleanUndocumented() and resolveRefs() in turn.
handleAppears() , cleanUndocumented() , resolveRefs()
Module Tools.Legal |
Module Tools.Legal.License |
string Tools.Legal.License.get_text()
Returns all the licenses as a string, suitable for saving as a file.
Module Tools.Legal.Copyright |
Contains functions and information to store and present copyright information about Pike and it's components.
void Tools.Legal.Copyright.add(string what, array(string) holders)
Adds a copyright message for the copyright holders for the component what .
An error is thrown if the copyrighted component what is already in the list of copyrights.
string Tools.Legal.Copyright.get_latest_pike()
Return the latest copyright holder of Pike.
mapping(string:array(string)) Tools.Legal.Copyright.get_all()
Returns a mapping containing all the stored copyrights. The mapping maps component name to an array of copyright holders.
string Tools.Legal.Copyright.get_text()
Returns the copyrights as a string, suitable for saving as a file.
Module Tools.Shoot |
void Tools.Shoot._shoot(string id)
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
The name of the test.
void perform()
perform() is the function called in the tests, when it returns the test is complete.
CLASS Tools.Shoot.ExecTest |
The test call/result class. Instantiated with a test id and the test object itself.
string id
Test testvoid Tools.Shoot.ExecTest(string id, Test test)
int(0..1) run(int maximum_seconds, int maximum_runs, void|int silent)
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 |
string Tools.Hilfe.format_hr_time(int i)
Helper function that formats a time span in nanoseconds to something more human readable (ns, ms or s).
CLASS Tools.Hilfe.Command |
Abstract class for Hilfe commands.
string help(string what)
Returns a one line description of the command. This help should be shorter than 54 characters.
string doc(string what, string with)
A more elaborate documentation of the command. This should be less than 68 characters per line.
void exec(Evaluator e, string line, array(string) words, array(string) tokens)
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 |
Variable reset command. Put ___Hilfe->commands->reset = Tools.Hilfe.CommandReset(); in your .hilferc to have this command defined when you open Hilfe.
inherit Command : Command
CLASS Tools.Hilfe.ParserState |
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.
void feed(array(string) tokens)
Feed more tokens into the state.
array(Expression) read()
Read out completed expressions. Returns an array where every element is an expression represented as an array of tokens.
void show_error(function(string:int) w)
Prints out any error that might have occured while push_string was executed. The error will be printed with the print function w .
array(string) push_string(string line)
Sends the input line to Parser.Pike for tokenization, but keeps a state between each call to handle multiline /**/ comments and multiline #"" strings.
int datap()
Returns true if there is any waiting expression that can be fetched with read .
int(0..1) finishedp()
Are we in the middle of an expression. Used e.g. for changing the Hilfe prompt when entering multiline expressions.
void flush()
Clear the current state.
string status()
Returns the current parser state. Used by "dump state".
CLASS Tools.Hilfe.HilfeHistory |
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 ADT.History : History
CLASS Tools.Hilfe.Evaluator |
This class implements the actual Hilfe interpreter. It is accessible as ___Hilfe from Hilfe expressions.
mapping(string:Command) commands
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.
ParserState state
Keeps the state, e.g. multiline input in process etc.
mapping(string:mixed) variables
The locally defined variables (name:value).
mapping(string:string) types
The types of the locally defined variables (name:type).
mapping(string:mixed) constants
The locally defined constants (name:value).
mapping(string:function) functions
The locally defined functions (name:value).
mapping(string:program) programs
The locally defined programs (name:value).
array(string) imports
The current imports.
array(string) inherits
The current inherits.
HilfeHistory history
The current result history.
array|object|function(string:int(0..)) write
The function to use when writing to the user.
void add_writer(object|function(string:int(0..)) new)
Adds another output function.
void remove_writer(object|function old)
Removes an output function.
int safe_write(string in, mixed ... args)
An output method that shouldn't crash.
void add_input_hook(function|object new)
Adds a function to the input hook, making all user data be fed into the function.
remove_input_hook
void remove_input_hook(function|object old)
Removes a function from the input hook.
add_input_hook
void Tools.Hilfe.Evaluator()
void print_version()
Displays the current version of Hilfe.
void reset_evaluator()
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.
void add_input_line(string s)
Input a line of text into Hilfe. It checks if s is ".", in which case it calls state->flush(). Otherwise just calls add_buffer.
void add_buffer(string s)
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 .
string parse_expression(Expression expr)
Parses a Pike expression. Returns 0 if everything went well, or a string with an error message otherwise.
string last_compiled_expr
The last created wrapper in which an expression was evaluated.
int(0..) last_compile_time
The last compile time;
int(0..) last_eval_time
The last evaluation time;
int(0..1) strict_types
Strict types?
int(0..1) warnings
Show warnings?
int trace_level
The current trace level.
int assembler_debug_level
The current assembler debug level. Only available if Pike is compiled with RTL debug.
int compiler_trace_level
The current compiler trace level. Only available if Pike is compiled with RTL debug.
int debug_level
The current debug level. Only available if Pike is compiled with RTL debug.
void std_reswrite(function w, string sres, int num, mixed res)
The standard reswrite function.
function reswrite
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.
object hilfe_compile(string f, void|string new_var)
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.
void evaluate(string a, int(0..1) show_result)
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 |
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 : Evaluator
Stdio.Readline readline
The readline object,
void save_history()
Saves the user input history, if possible, when called.
void Tools.Hilfe.StdinHilfe(void|array(string) init)
Any hilfe statements given in the init array will be executed once .hilferc has been executed.
CLASS Tools.Hilfe.GenericHilfe |
inherit Evaluator : Evaluator
void Tools.Hilfe.GenericHilfe(Stdio.FILE in, Stdio.File out)
CLASS Tools.Hilfe.GenericAsyncHilfe |
inherit Evaluator : Evaluator
void Tools.Hilfe.GenericAsyncHilfe(Stdio.File in, Stdio.File out)
Module Tools.Install |
Common routines which are useful for various install scripts based on Pike.
array(string) Tools.Install.features()
string Tools.Install.make_absolute_path(string path, string|void cwd)
CLASS Tools.Install.ProgressBar |
A class keeping some methods and state to conveniently render ASCII progress bars to stdout.
void set_current(int _cur)
Change the amount of progress without updating on stdout.
void set_name(string _name)
Change the name of the progress bar without updating on stdout.
void set_phase(float _phase_base, float _phase_size)
int update(int increment)
Write the current look of the progressbar to stdout.
the number of increments closer to completion since last call
the length (in characters) of the line with the progressbar
void Tools.Install.ProgressBar(string name, int cur, int max, float|void phase_base, float|void phase_size)
The name (printed in the first 13 columns of the row)
How much progress has been made so far
The amount of progress signifying 100% done. Must be greater than zero.
CLASS Tools.Install.Readline |
inherit Stdio.Readline : Readline
void trap_signal(int n)
string edit(mixed ... args)
string edit_filename(mixed ... args)
string edit_directory(mixed ... args)
string absolute_path(string path)
void set_cwd(string _cwd)
Module Tools.PEM |
Support for parsing PEM-style messages.
CLASS Tools.PEM.EncapsulatedMsg |
string boundary
contains the boundary string
string body
contains the body of the message
mapping(string:string) headers
void Tools.PEM.EncapsulatedMsg(string eb, string contents)
string decoded_body()
decodes a base 64 encoded message body
string get_boundary()
string canonical_body()
string to_string()
converts the message body and headers to the standard message format.
CLASS Tools.PEM.RFC934 |
string initial_text
string final_text
string final_boundary
array(EncapsulatedMsg) encapsulated
void Tools.PEM.RFC934(string data)
decodes an RFC 934 encoded message.
string get_final_boundary()
string to_string()
CLASS Tools.PEM.Msg |
Disassembles PGP and PEM style messages with parts separated by "-----BEGIN FOO-----" and "-----END FOO-----".
string initial_text
Contains any text preceeding the PEM message.
string final_text
Contains any text following the PEM message.
mapping(string:EncapsulatedMsg) parts
The decoded PEM message, as an array of EncapsulatedMsg objects indexed by message name, such as "CERTIFICATE".
void Tools.PEM.Msg(string s)
Creates a decoded PEM message
a string containing a PEM encoded message to be decoded.
Module Tools.X509 |
constant Tools.X509.CERT_TOO_OLD
constant Tools.X509.CERT_TOO_NEW
constant Tools.X509.CERT_INVALID
constant Tools.X509.CERT_CHAIN_BROKEN
constant Tools.X509.CERT_ROOT_UNTRUSTED
constant Tools.X509.CERT_BAD_SIGNATURE
constant Tools.X509.CERT_UNAUTHORIZED_CA
UTC Tools.X509.make_time(int t)
Creates a Standards.ASN1.Types.UTC object from the posix time t .
mapping(string:int) Tools.X509.parse_time(UTC asn1)
Returns a mapping similar to that returned by gmtime
|
int(-1..1) Tools.X509.time_compare(mapping(string:int) t1, mapping(string:int) t2)
Comparision function between two "date" mappings of the kind that parse_time returns.
Sequence Tools.X509.make_tbs(object issuer, object algorithm, object subject, object keyinfo, object serial, int ttl, array extensions)
string Tools.X509.make_selfsigned_dsa_certificate(Crypto.DSA dsa, int ttl, array name, array|void extensions)
string Tools.X509.rsa_sign_digest(Crypto.RSA rsa, object digest_id, string digest)
int(0..1) Tools.X509.rsa_verify_digest(Crypto.RSA rsa, object digest_id, string digest, string s)
string Tools.X509.make_selfsigned_rsa_certificate(Crypto.RSA rsa, int ttl, array name, array|void extensions)
Verifier Tools.X509.make_verifier(Object _keyinfo)
TBSCertificate Tools.X509.decode_certificate(string|object cert)
TBSCertificate Tools.X509.verify_certificate(string s, mapping authorities)
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.
This function allows self-signed certificates, and it doesn't check that names or extensions make sense.
mapping Tools.X509.verify_certificate_chain(array(string) cert_chain, mapping authorities, int|void require_trust)
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:
|
An array of certificates, with the relative-root last. Each certificate should be a DER-encoded certificate.
A mapping from (DER-encoded) names to verifiers.
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 : Verifier
this_program init(string key)
int(0..1) verify(Sequence algorithm, string msg, string signature)
CLASS Tools.X509.TBSCertificate |
string der
int version
Gmp.mpz serial
Sequence algorithm
Sequence issuer
mapping not_after
mapping not_before
Sequence subject
Verifier public_key
BitString issuer_id
optional
BitString subject_id
optional
object extensions
optional
this_program init(Object asn1)
Module Tools.sed |
edit commands supported:
<firstline>,<lastline><edit command>
^^ numeral (17) ^^
or relative (+17, -17)
or a search regexp (/regexp/)
or multiple (17/regexp//regexp/+2)
|
where line is numeral, first 'line'==0
string|array Tools.sed.`()(string|array(string) commands, string|array(string) data, void|int suppress)
Module Web |
CLASS Web.RDF |
Represents an RDF domain which can contain any number of complete statements.
RDFResource rdf_Statement
Statement resource.
RDFResource rdf_predicate
predicate resource.
RDFResource rdf_subject
subject resource.
RDFResource rdf_object
object resource.
RDFResource rdf_type
type resource.
RDFResource rdf_Seq
Seq resource.
RDFResource rdf_first
first resource.
RDFResource rdf_rest
rest resource.
RDFResource rdf_nil
nil resource.
void add_statement(Resource subj, Resource pred, Resource obj)
Adds a statement to the RDF set.
Throws an exception if any argument isn't a Resouce object.
int(0..1) has_statement(Resource subj, Resource pred, Resource obj)
Returns 1 if the RDF domain contains the relation {subj, pred, obj}, otherwise 0.
int(0..1) remove_statement(Resource subj, Resource pred, Resource obj)
Removes the relation from the RDF set. Returns 1 if the relation did exist in the RDF set.
Resource reify_low(Resource subj, Resource pred, Resource obj)
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.
The subject of the reified statement.
Resource get_reify(Resource subj, Resource pred, Resource obj)
Returns a resource that is the subject of the reified statement {subj, pred, obj}, if such a resource exists in the RDF domain.
Resource reify(Resource subj, Resource pred, Resource obj)
Returns the result of get_reify , if any. Otherwise calls reify_low followed by remove_statement of the provided statement {subj, pred, obj}.
The subject of the reified statement.
int(0..1) dereify(Resource r)
Turns the reified statement r into a normal statement, if possible.
1 for success, 0 for failure.
int(0..) dereify_all()
Dereifies as many statements as possible. Returns the number of dereified statements.
array(Resource) get_properties()
Returns all properties in the domain, e.g. all resources that has been used as predicates.
mapping(Resource:mapping(Resource:array(Resource))) get_subject_map()
Returns a mapping with all the domains subject resources as indices and a mapping with that subjects predicates and objects as value.
URIResource get_resource(string uri)
Returns an RDF resource with the given URI as identifier, or zero.
URIResource make_resource(string uri)
Returns an RDF resource with the given URI as identifier, or if no such resrouce exists, creates it and returns it.
array(array(Resource)) find_statements(Resource|int(0..0) subj, Resource|int(0..0) pred, Resource|int(0..0) obj)
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.
An array with arrays of three elements.
|
int(0..1) is_subject(Resource r)
Returns 1
if resource r is used as a subject, otherwise
0
.
int(0..1) is_predicate(Resource r)
Returns 1
if resource r is used as a predicate,
otherwise 0
.
int(0..1) is_object(Resource r)
Returns 1
if resource r is used as an object, otherwise
0
.
string get_3_tuples()
Returns a 3-tuple serialization of all the statements in the RDF set.
string get_n_triples()
Returns an N-triples serialization of all the statements in the RDF set.
int parse_n_triples(string in)
Parses an N-triples string and adds the found statements to the RDF set. Returns the number of added relations.
The parser will throw errors on invalid N-triple input.
string decode_n_triple_string(string in)
Decodes a string that has been encoded for N-triples serialization.
Doesn't correctly decode backslashes that has been encoded with with \u- or \U-notation.
string encode_n_triple_string(string in)
Encodes a string for use as tring in N-triples serialization.
Web.RDF parse_xml(string|Parser.XML.NSTree.NSNode in, void|string base)
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.
string get_xml()
Serialize the RDF domain as an XML string.
int _sizeof()
Returns the number of statements in the RDF domain.
Web.RDF `|(Web.RDF x)
Modifies the current object to create a union of the current object and the object x .
CLASS Web.RDF.Resource |
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.
Resources instantiated from this class should not be used in other RDF domain objects.
URIResource , LiteralResource
string get_n_triple_name()
Returns the nodes' N-triple serialized ID.
string get_3_tuple_name()
Returns the nodes' 3-tuple serialized ID.
CLASS Web.RDF.LiteralResource |
Resource identified by literal.
inherit Resource : Resource
string datatype
Used to contain rdf:datatype value.
void Web.RDF.LiteralResource(string literal)
The resource will be identified by literal .
string get_xml()
Returns the literal as an XML string.
string get_literal()
Returns the literal string.
CLASS Web.RDF.URIResource |
Resource identified by URI.
inherit Resource : Resource
void Web.RDF.URIResource(string uri)
Creates an URI resource with the uri as identifier.
Throws an error if another resource with the same URI already exists in the RDF domain.
string get_uri()
Returns the URI the resource references to.
string get_qname(void|string ns)
Returns the qualifying name, or zero.
string get_namespace()
Returns the namespace this resource URI references to.
CLASS Web.RDF.RDFResource |
Resource used for RDF-technical reasons like reification.
inherit URIResource : URIResource
void Web.RDF.RDFResource(string rdf_id)
The resource will be identified by the identifier rdf_id
string get_qname(void|string ns)
Returns the qualifying name.
CLASS Web.OWL |
Represents an RDF tuple set from an OWL perspective.
inherit .RDFS : RDFS
Module Web.Crawler |
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 |
Statistics.
int window_width
int granularityvoid Web.Crawler.Stats(int window_width, int granularity)
void bytes_read_callback(Standards.URI uri, int num_bytes_read)
This callback is called when data has arrived for a presently crawled URI, but no more often than once a second.
void close_callback(Standards.URI uri)
This callback is called whenever the crawling of a URI is finished or fails.
CLASS Web.Crawler.Policy |
The crawler policy object.
int max_concurrent_fetchers
Maximum number of fetchers. Defaults to 100.
int max_bits_per_second_total
Maximum number of bits per second. Defaults to off (0).
int max_bits_per_second_per_host
Maximum number of bits per second, per host. Defaults to off (0).
int bandwidth_throttling_floating_window_width
Bandwidth throttling floating window width. Defaults to 30.
int max_concurrent_fetchers_per_host
Maximum concurrent fetchers per host. Defaults to 1.
int min_delay_per_host
Minimum delay per host. Defaults to 0.
CLASS Web.Crawler.Queue |
A crawler queue. Does not need to be reentrant safe. The Crawler always runs in just one thread.
int|Standards.URI get()
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.
void put(string|array(string)|Standards.URI|array(Standards.URI) uri)
Put one or several URIs in the queue. Any URIs that were already present in the queue are silently disregarded.
CLASS Web.Crawler.Rule |
Abstract rule class.
int check(string|Standards.URI uri)
CLASS Web.Crawler.GlobRule |
A rule that uses glob expressions
a glob pattern that the rule will match against.
GlobRule("http://pike.ida.liu.se/*.xml");
inherit Rule : Rule
string patternvoid Web.Crawler.GlobRule(string pattern)
CLASS Web.Crawler.RegexpRule |
A rule that uses Regexp expressions
inherit Rule : Rule
void Web.Crawler.RegexpRule(string re)
a string describing the Regexp expression
CLASS Web.Crawler.RuleSet |
A set of rules
void add_rule(Rule rule)
add a rule to the ruleset
void remove_rule(Rule rule)
remove a rule from the ruleset
CLASS Web.Crawler.MySQLQueue |
inherit Queue : Queue
void Web.Crawler.MySQLQueue(Stats _stats, Policy _policy, string _host, string _table, void|RuleSet _allow, void|RuleSet _deny)
CLASS Web.Crawler.MemoryQueue |
Memory queue
inherit Queue : Queue
void Web.Crawler.MemoryQueue(Stats _stats, Policy _policy, RuleSet _allow, RuleSet _deny)
int|Standards.URI get()
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.
void put(string|array(string)|Standards.URI|array(Standards.URI) uri)
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 : Queue
Stats stats
Policy policyvoid Web.Crawler.ComplexQueue(Stats stats, Policy policy)
CLASS Web.Crawler.Crawler |
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)
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.
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.
function called when crawl is complete. Accepts mixed ... args and returns void.
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.
location to start the crawl from.
optional arguments sent as the last argument to the callback functions.
Module Web.RSS |
Represents a RSS (RDF Site Summary) file.
Index Web.RSS.parse_xml(string|Parser.XML.Tree.Node n, void|string base)
Returns an Index object, populated with the rss information given in the rss file n .
CLASS Web.RSS.Thing |
The base class for the RSS resources.
void Web.RSS.Thing(string about, mapping attributes)
void Web.RSS.Thing(.RDF.Resource me)
Creates an RSS resource.
.RDF.Resource get_id()
Returns the RDF.Resource that identifies this RSS resource.
CLASS Web.RSS.Image |
Represents an RSS image resource.
inherit Thing : Thing
string title
string url
string link
CLASS Web.RSS.Item |
Represents an RSS item resource.
inherit Thing : Thing
string title
string link
string description
CLASS Web.RSS.Textinput |
Represents an RSS textinput resource.
inherit Thing : Thing
string title
string description
string name
string link
CLASS Web.RSS.Channel |
Represents an RSS channel.
inherit Thing : Thing
string title
string link
string description
string|Standards.URI image
string|Standards.URI textinput
array(Item) items
void add_item(Item i)
Adds the Item i to the Channel .
void remove_item(Item i)
Removes the Item i from the Channel .
CLASS Web.RSS.Index |
Represents the top level of an RSS index.
.RDF rdf
The underlying RDF representation of the RSS index.
array(Channel) channels
The RSS channels.
array(Image) images
The RSS images.
array(Item) items
The RSS items.
array(Textinput) textinputs
The RSS textinputs.
void Web.RSS.Index(.RDF|void _rdf)
Module GLUE |
GL Universal Environment
array(string) GLUE.get_drivers()
Returns the name of the available drivers.
init
void GLUE.add_reinit_callback(function(void:void) f)
Add a callback that will be called every time the resolution is about to change.
remove_reinit_callback
void GLUE.remove_reinit_callback(function(void:void) f)
Removes a reinitialization callback.
add_reinit_callback
int(0..1) GLUE.get_screen_mode()
Returns 1 if in fullscreen mode, otherwise 0.
toggle_fullscreen
void GLUE.toggle_fullscreen(void|int(0..1) _fullscreen)
Toggles between fullscreen and window mode. If a screen mode is provided, that mode will be assumed.
get_screen_mode
int GLUE.get_gl_flags()
Returns the GL flags currently used.
set_gl_flags
void GLUE.set_gl_flags(int _gl_flags)
Sets the GL flags.
get_gl_flags
int GLUE.get_depth()
Returns the current color depth.
set_depth
void GLUE.set_depth(int _depth)
Sets the color depth.
get_depth
int GLUE.xsize()
int GLUE.ysize()
Returns the screen width/height.
set_resolution
void GLUE.set_resolution(int w, int h)
Sets the resolution to w xh pixels.
xsize , ysize
float GLUE.get_aspect()
Returns the screen aspect.
set_aspect
void GLUE.set_aspect(float asp)
void GLUE.set_aspect(int w, int h)
Set the aspect of the draw area. Does nothing if the provided aspect is equal to the one currently used.
get_aspect
void GLUE.set_screen_rotation(float deg)
Rotates the drawing area deg degrees. Useful e.g. when drawing for tilted monitors.
void GLUE.mirror_screen(string how)
Mirrors the screen in x and/or y axis. Useful e.g. when drawing for backlight projection.
A string that contains the mirror axis, e.g. "x"
or
"xy"
.
void GLUE.init(void|mapping(string:mixed) options)
Initializes GLUE and loads a driver from a list of drivers. If a driver fails to load or initialize, the next driver is tried.
driver_names not listed in the result from get_drivers will cause an error to be thrown.
|
get_drivers
void GLUE.swap_buffers()
Swap the drawing buffer and the viewing buffer.
void GLUE.show_cursor()
Show the mouse cursor.
void GLUE.hide_cursor()
Hide the mouse cursor.
int GLUE.allocate_light()
Allocate a hardwareaccelerated lightsource from OpenGL.
an id which may be added to the GL.GL_LIGHT0 constant.
free_light
void GLUE.free_light(int l)
Call this function to free a lightsource that has been allocated with allocate_light .
Id which has been allocated using allocate_light .
allocate_light
int(0..) GLUE.pushpop_depth()
Returns the PushPop depth, i.e. the number of pushes awaiting corresponding pops.
void GLUE.PushPop(function f)
Performs function f between GL.glPushMatrix and GL.glPopMatrix calls.
PushPop() { GL.glTranslate( 0.01, -0.9, 0.0 ); write_text( "Press esc to quit" ); };
array(List) GLUE.get_all_lists()
Returns all defined lists. Only available on Windows.
int(0..1) GLUE.only_dynlists()
Returns 1
if all defined lists are DynList lists.
BaseTexture GLUE.make_texture(mapping|Image.Image image, string|void name)
Create a texture. Mainly here for symetry with make_rect_texture
Texture , make_rect_texture
BaseTexture GLUE.make_rect_texture(mapping|Image.Image image, string|void name)
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 ).
make_texture
array(BaseTexture) GLUE.get_all_textures()
Returns a list of all current textures.
int GLUE.get_texture_mem_usage()
Returns the number of bytes used by the textures.
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)
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)
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.
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)
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.
void GLUE.draw_polygon(array(float) coords, Image.Color.Color c, float a)
mapping(string:mixed) GLUE.debug_stuff()
Returns some internal states for debug purposes. The actual content may change.
CLASS GLUE.List |
A display list abstraction. Automatically allocates a display list id upon creation and correctly deallocate it upon destruction.
DynList
void GLUE.List(void|function f)
When creating a new list, the list code can be compiled upon creation by supplying a function f that performs the GL operations.
call
List list = List() { // GL code };
void destroy()
Deletes this list and frees the list id from the id pool.
int get_id()
Returns this lists' id.
int(0..1) `>(mixed x)
List objects can be sorted according to list id.
get_id
void begin(int(0..1)|void run)
Start defining the list. If run is provided, the list will be executed as it is compiled (GL.GL_COMPILE_AND_EXECUTE ).
end , compile
void end()
Finish the list definition.
begin , compile
void compile(function f)
Compile a list be executing the list code f . Exceptions in f will be thrown after GL.glEndList has been called.
begin
void call()
Execute the commands in the list.
CLASS GLUE.DynList |
A displaylist that is generated on demand.
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 : List
void modeswitch()
Called by videodriver when a video mode change occurs.
void set_generator(function _generator)
Sets a function which can generate a displaylist. Hint: Use implicit lambda...
void init()
Generates the displaylist, ie calls the function set in set_generator . Called only when the display list needs to be generated.
void call()
Call the displaylist, ie draw it.
void GLUE.DynList(function|void f)
Create a new DynList object and optionally set a function that can generate the displaylist
Function which contains the GL commands that generates the displaylist.
CLASS GLUE.BaseTexture |
The texture base class. Using e.g. Texture might be more convenient.
int t_width
int t_height
Texture dimensions
int i_width
int i_height
Image dimensions
float width_u
float height_u
Utilization in percent.
int texture_type
The texture type, e.g. GL.GL_TEXTURE_2D .
string debug
A string to identify the texture.
void construct(int width, int height, int _alpha, mapping|void imgs, int(0..1)|void mipmap, int|void _mode, string|void debug_text)
Construct a new texture. Processes _alpha , _mode and debug_text and calls resize .
The alpha mode the texture is operating in.
|
The mode the texture is operating in. Autoselected wrt _alpha
if 0
.
A string that can be used to identify this texture.
void GLUE.BaseTexture(mixed ... args)
Calls construct with args .
void destroy()
Properly deallocates the texture.
void resize(int width, int height, mapping|void imgs, int(0..1)|void mipmap, int(0..1)|void nocreate)
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.
construct
void create_texture(mapping|void imgs, int(0..1)|void mipmap, int|void width, int|void height)
Actually creates the texture.
If zero, a black texture with the dimensions width * height will be generated. Otherwise imgs should be a mapping as follows.
|
If 1
, the texture will be mipmapped.
The dimensions of the texture. If omitted the dimensions of the images in imgs will be used.
resize
void make_mipmap(mapping imgs, int|void imode, int|void dx, int|void dy)
Renders a mipmap of the image/partial image imgs .
Image data mapping to feed GL.glTexImage2D or GL.glTexSubImage2D .
Internal format to feed GL.glTexImage2D , or UNDEFINED for partial images.
Xoffs, yoffs to feed GL.glTexSubImage2D for partial images.
create_texture
void clear()
Clears the texture.
void paste(Image.Image i, Image.Image a, int x, int y)
Paste the image i with alpha channel a at coordinates x and y in the current texture.
int _sizeof()
Returns the size of memory allocated by the texture.
int get_id()
Returns the id of this texture.
int(0..1) `>(mixed x)
Textures can be sorted according to texture id.
void draw(float x, float y, float z, float w, float h)
Draw the texture at x ,y ,z with dimensions w *h .
void draw_region(float x, float y, float z, float w, float h, float s0, float q0, float ss, float qs)
Draw texture region s0 ,q0 - ss ,qs at x ,y ,z with dimensions w *h .
void use()
Use the generated texture (GL.glBindTexture ).
void coords(float x, float y)
Sets the texture coordinates to x *width,y *height.
void set_image_data(Image.Image|mapping(string:mixed) data, int(0..1)|void no_resize)
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.
Besides being an Image.Image object, data can be either of two types of mappins. First it can be a mapping with Image data.
|
Second it can be a mapping pointing out a shared memory segment.
|
CLASS GLUE.RectangleTexture |
Uses the NVidia RECT texture extension for non-power-of-two textures.
inherit BaseTexture : BaseTexture
CLASS GLUE.BaseDWIM |
A mixin class with a dwim create function.
void GLUE.BaseDWIM(mixed ... args)
This create function has the following heuristic:
If a mapping is encountered, the following information will be attempted to be extracted.
|
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 |
Convenience version of the Texture class.
inherit BaseTexture : BaseTexture
Texture base
inherit BaseDWIM : BaseDWIM
Convenience methods
CLASS GLUE.RectangleDWIMTexture |
Convenience version of the RectangleTexture class.
inherit RectangleTexture : RectangleTexture
Texture base
inherit BaseDWIM : BaseDWIM
Convenience methods
CLASS GLUE.Region |
A rectangle. Used by the text routines to avoid drawing outside the current region.
float x
float y
float w
float hvoid GLUE.Region(float x, float y, float w, float h)
constant is_region
All region objects have this constant.
void move(float xp, float yp)
Move the region xp units right and yp units down.
void resize(float xs, float ys)
Make the region xs units wider and ys units higher.
int(0..1) outside(Region R)
Returns 1 if the region R is fully outside this region.
int(0..1) inside(Region R)
Returns 1 if the region R is fully inside this region.
Region `&(mixed R)
Creates a new region with the intersection of this region and R .
CLASS GLUE.Font |
A font.
void GLUE.Font(Image.Fonts.Font f, float|void _scale_width, float|void _scale_spacing)
array(int|BaseTexture|Region) get_character(int c)
Returns the advance (in pixels), the texture and the texture coordinates for the specified character, or 0 if it's nonprintable.
If the font->write call fails, the backtrace will be written to stderr.
array(float) text_extents(string text, float h)
Get the width and height of the area that the string text in size h would cover.
array(float) write_now(string text, float h, void|float|Region roi, string|void align)
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.
array(List|float) write(string text, float h, void|float|Region roi, string|void align)
Create a display list that writes text.
The text to write.
The font height
The region, if supplied, to restrict writing to.
The text justification; "left" (default), "center" or "right".
CLASS GLUE.Font.Character |
A character to draw.
inherit Region : Region
Region pos
Character position in texture txt .
BaseTexture txt
Texture holding the character.
Region slice
Slice of character to be shown.
void set_data(Region _pos, BaseTexture _txt, void|Region _slice)
Set character to be region _slice of region _pos of texture _txt .
void draw()
Draw the character using the texture txt with the texture-coordinates indicated in pos , possible cropped with slice .
CLASS GLUE.SquareMesh |
A mesh of squares.
void recalculate()
Recalculate the mesh.
Math.Matrix surface_normal(int x, int y)
Return the normal for the surface at coordinates x,y. Used internally.
void set_texture(BaseTexture tex)
Set a texture to be mapped on the mesh.
void draw()
Draw the mesh.
void set_lighting(int(0..1) do_lighting)
Indicate whether or not lighting is used. If it is, the normals of each vertex will be calculated as well as the coordinates.
void set_size(int x, int y)
Set the size of the mesh
void GLUE.SquareMesh(function(float:Math.Matrix) calculator)
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 |
GLUE Event abstraction.
constant GLUE.Events._SHFT
Integer constant representing shift.
constant GLUE.Events._CTRL
Integer constant representing control.
constant GLUE.Events._ALT
Integer constant representing alternate.
constant GLUE.Events.KNOWN_MODIFIERS
Integer constant with the union of all known modifiers, i.e.
_SHFT | _CTRL | _ALT
.
Event GLUE.Events.CTRL(int|Event X)
array(Event) GLUE.Events.CTRL(array(int|Event) X)
Adds the _CTRL modifier to an Event , key or array of Events and/or keys.
Event GLUE.Events.SHFT(int|Event X)
array(Event) GLUE.Events.SHFT(array(int|Event) X)
Adds the _SHFT modifier to an Event , key or array of Events and/or keys.
Event GLUE.Events.ALT(int|Event X)
array(Event) GLUE.Events.ALT(array(int|Event) X)
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
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
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
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
Numeric constant representing a modifier key.
constant GLUE.Events.MODIFIERS
Mapping that maps a modifier key to any of the symbolic modifiers _SHFT , _CTRL and _ALT .
constant GLUE.Events.EXIT
Numeric constant representing an exit event.
constant GLUE.Events.key_names
Mapping that maps key identifiers with a printable name, e.g.
LSHIFT to "Left shift"
.
int(0..1) GLUE.Events.is_modifier(int k)
Returns 1
if the key code k is a modifier key, e.g.
LSHIFT or RSHIFT .
CLASS GLUE.Events.Event |
Contains an event.
this_program dup()
Returns a copy of this Event object.
float pressure
The pressure of the key stroke. A value between 0.0 and 1.0. Unknown values are represented as 0.
int(0..1) press
Press event or release event.
void GLUE.Events.Event(int|void _key, int(0..1)|void _press, string|void _data, int|void _modifiers, float|void pressure)
Module Colors |
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)
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().
Colors.hsv_to_rgb() Image.Color.Color.hsv()
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)
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().
Colors.rgb_to_hsv() Image.Color.hsv()
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)
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().
Colors.cmyk_to_rgb() Image.Color.Color.cmyk()
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)
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()
Colors.rgb_to_cmyk() Image.Color.cmyk()
array(int(0..255)) Colors.parse_color(string name, void|array(int) def)
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.
string Colors.color_name(array(int(0..255)) rgb)
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
These constants define the limits for floats on the current architecture:
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
.
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
.
The smallest normalized float greater than zero. It's not
greater than 1e-37
.
The largest finite float. It's not less than 1e37
.
The difference between 1 and the smallest value greater than 1
that can be represented. It's not greater than 1e-5
.
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
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.
The float
type of the C compiler is used.
The double
type of the C compiler is used.
The long double
type of the C compiler is used.
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 |
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.
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)
This is a generic function to parse command line options of the type -f, --foo or --foo=bar.
The first argument should be the array of strings that was sent as
the second argument to your main()
function.
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.
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.
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.
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.
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 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.
If an option that requires an argument lacks an argument and throw_errors is set an error will be thrown.
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.
Getopt.get_args()
constant Getopt.HAS_ARG
Used with find_all_options() to indicate that an option requires an argument.
find_all_options()
constant Getopt.NO_ARG
Used with find_all_options() to indicate that an option does not take an argument.
find_all_options()
constant Getopt.MAY_HAVE_ARG
Used with find_all_options() to indicate that an option takes an optional argument.
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)
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.
The should be the array of strings that was sent as the second
argument to your main()
function.
Each element in the array options should be an array on the following form:
|
Only the first three elements need to be included.
Don't scan for arguments after the first non-option.
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.
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:
|
find_all_options() modifies argv .
Index 0
(zero) of argv is not scanned for options,
since it is reserved for the program name.
Getopt.get_args() , Getopt.find_option()
array(string) Getopt.get_args(array(string) argv, void|int(-1..1) posix_me_harder, void|int throw_errors)
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.
On success a new argv array without the parsed options is returned.
Getopt.find_option() , Getopt.find_all_options()
Module Int |
int(0..1) Int.parity(int(0..) value)
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
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
).
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.
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.
int(0..65535) Int.swap_word(int(0..65535) i)
Swaps the upper and lower byte in a word.
int(0..4294967295) Int.swap_long(int(0..4294967295) i)
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 |
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.
Local.add_path() , Local.remove_path()
int(0..1) Local.add_path(string path)
This function prepends path to the Local module searchpath.
The path to the directory to be added.
Returns 1 on success, otherwise 0.
void Local.remove_path(string path)
This function removes path from the Local module searchpath. If path is not in the search path, this is a noop.
The path to be removed.
Namespace 0.6:: |
Pike 0.6 compatibility.
The symbols in this namespace will appear in programs that use #pike 0.6 or lower.
7.0::
inherit 7.0:: :
array(mixed) aggregate(mixed ... args)
More lax types than in later versions.
Module Array |
inherit Array : Array
array Array.map(array x, int|string|function fun, mixed ... args)
Much simplified type compared to later versions of map.