16. The rest |
Module 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 sqrt(float f)
int sqrt(int i)
Returns the square root of f , or in the integer case, the square root truncated to the closest lower integer.
pow() , log() , exp() , floor()
float log(float f)
Return the natural logarithm of f .
for x > 0.exp( log(x) ) == x
pow() , exp()
float exp(float f)
Return the natural exponential of f .
as long as exp(x) doesn't overflow an int.log( exp( x ) ) == x
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)
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)
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.
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(int type, void|mapping flags)
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.3 release 11 running Hilfe v2.0 (Incremental Pike Frontend) > int screen_width=70; Result: 70 > mixed sample; > write(sprintf("fish: %c\n", 65)); fish: A Result: 8 > write(sprintf("Hello green friends\n")); Hello green friends Result: 20 > write(sprintf("num: %d\n", 10)); num: 10 Result: 8 > write(sprintf("num: %+10d\n", 10)); num: +10 Result: 16 > write(sprintf("num: %010d\n", 5*2)); num: 0000000010 Result: 16 > write(sprintf("num: %|10d\n", 20/2)); num: 10 Result: 16 > write(sprintf("%|*s\n",screen_width,"THE NOT END")); THE NOT END Result: 71 > write(sprintf("%|=*s\n",screen_width, "fun with penguins\n")); fun with penguins Result: 71 > write(sprintf("%-=*O\n",screen_width,({ "fish", 9, "gumbies", 2 }))); ({ /* 4 elements */ "fish", 9, "gumbies", 2 }) Result: 426 > write(sprintf("%-=*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. Result: 355 > write(sprintf("%-=*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. Result: 426 > write(sprintf("%-$*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. Result: 312 > write(sprintf("%-#*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. Result: 312 > sample = ([ "align":"left", "valign":"middle" ]); Result: ([ /* 2 elements */ "align":"left", "valign":"middle" ]) > write(sprintf("<td%{ %s='%s'%}>\n", (array)sample)); <td valign='middle' align='left'> Result: 34 > write(sprintf("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 Result: 106 > write(sprintf("%[0]d, %[0]x, %[0]X, %[0]o, %[0]c\n", 75)); 75, 4b, 4B, 113, K Result: 19 > write(sprintf("%|*s\n",screen_width, "THE END")); THE END 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()
int setpwent()
Resets the getpwent function to the first entry in the passwd source using the systemfunction setpwent(3).
Always 0 (zero)
getpwent() endpwent()
int endpwent()
Closes the passwd source opened by getpwent function using the systemfunction endpwent(3).
Always 0 (zero)
getpwent() setpwent()
array(int|string) 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.
getpwnam() getpwent() setpwent() endpwent()
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()
int setgrent()
Rewinds the getgrent pointer to the first entry
getgrent() endgrent()
int endgrent()
Closes the /etc/groups file after using the getgrent function.
getgrent() setgrent()
array(int|string|array(string)) 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
|
getgrnam() getgrgid()
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
.
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.a == b
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
(and it isn't possible either) like
in C, just int a[10]=allocate(10);
will do.array(int) a=allocate(10);
sizeof() , arrayp() , allocate()
int hash_7_0(string s)
int hash_7_0(string s, int max)
This function will return an int derived from the string s . The same string will always hash to the same value. 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.
hash()
int hash(string s)
int hash(string s, int max)
This function will return an int derived from the string s . The same string will always hash to the same value. 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.1. If you want a hash that is compatible with Pike 7.0 and earlier, use hash_7_0() .
hash_7_0()
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)
Convert a string to lower case.
Returns a copy of the string s with all upper case characters converted to lower case.
upper_case()
string upper_case(string s)
Convert a string to upper case.
Returns a copy of the string s with all lower case characters converted to upper case.
lower_case()
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)
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.
When haystack is a string needle must be a string or an int, and the first occurrence of the string or int is returned.
When haystack is an array, needle is compared only to one value at a time in haystack .
When haystack is a mapping, search() tries to find the index connected to the data needle . That is, it tries to lookup the mapping backwards. If needle isn't present in the mapping, zero is returned, and zero_type() will return 1 for this zero.
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)
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() is equvivalent to combine_path_unix() on UNIX-like operating systems, and equvivalent to combine_path_nt() on NT-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 zero)
Allocate an array of size elements and initialize them to zero .
sizeof() , aggregate() , arrayp()
array(int) rusage()
Return resource usage.
Returns an array of ints describing how much resources the interpreter process has used so far. This array will have at least 29 elements, of which those values not available on this system will be zero.
The elements are as follows:
|
The values will not be further explained here; read your system manual for more information.
All values may not be present on all systems.
time()
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)
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.
_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, Jan 1, 1970.
The second syntax does not call the system call time() as often, but is only updated in the backed (when Pike code isn't running).
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()
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(object o)
Mark an object as destructed.
Calls o->destroy(), and then clears all variables in the object.
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 object_program(mixed o)
Return the program from which o was instantiated.
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
can be
used.mkmapping (from , to )
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.
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. It then returns how many arrays/objects/programs/etc. it managed to free by doing this.
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.)
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.
sort() can sort strings, integers and floats in ascending order. Arrays will be sorted first on the first element of each array. Objects will be sorted in ascending order according to `<() , `>() and `==() .
The first argument will be returned.
The sorting algorithm used is not stable, ie elements that are equal may get reordered.
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, Jan 1, 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 .
The field "timezone" may not be available on all platforms.
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 isdst, int 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()
array parse_format(string fmt)
Parses a sprintf/sscanf-style format string
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 _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()
int gethrtime()
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()
array map_array(array arr, function fun, mixed ... args)
array map_array(array(object) arr, string fun, mixed ... args)
array map_array(array(function) arr, int(-1..-1) minus_one, mixed ... args)
This function is similar to map() .
This function has been deprecated in favour of map() .
map()
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
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.cast
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
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
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.cast
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
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()
constant __VERSION__
This define contains the current Pike version as a float. If another Pike version is emulated, this define is updated accordingly.
__REAL_VERSION__
constant __REAL_VERSION__
This define always contains the version of the current Pike, represented as a float.
__VERSION__
constant __MAJOR__
This define contains the major part of the current Pike version, represented as an integer. If another Pike version is emulated, this define is updated accordingly.
__REAL_MAJOR__
constant __REAL_MAJOR__
This define always contains the major part of the version of the current Pike, represented as an integer.
__MAJOR__
constant __MINOR__
This define contains the minor part of the current Pike version, represented as an integer. If another Pike version is emulated, this define is updated accordingly.
__REAL_MINOR__
constant __REAL_MINOR__
This define always contains the minor part of the version of the current Pike, represented as an integer.
__MINOR__
constant __BUILD__
This constant contains the build number of the current Pike version, represented as an integer. If another Pike version is emulated, this constant remains unaltered.
__REAL_MINOR__
constant __REAL_BUILD__
This define always contains the minor part of the version of the current Pike, represented as an integer.
__BUILD__
constant __LINE__
This define contains the current line number, represented as an integer, in the source file.
constant __FILE__
This define contains the file path and name of the source file.
constant __DATE__
This define contains the current date at the time of compilation, e.g. "Jul 28 2001".
constant __TIME__
This define contains the current time at the time of compilation, e.g. "12:20:51".
constant __PIKE__
This define is always true.
constant __AUTO_BIGNUM__
This define is defined when automatic bignum conversion is enabled. When enabled all integers will automatically be converted to bignums when they get bigger than what can be represented by an integer, hampering performance slightly instead of crashing the program.
constant __NT__
This define is defined when the Pike is running on a Microsoft Windows OS, not just Microsoft Windows NT, as the name implies.
constant __amigaos__
This define is defined when the Pike is running on Amiga OS.
string cpp(string data, string|void current_file, int|string|void charset, object|void handler, void|int compat_major, void|int compat_minor)
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 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()
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()
multiset aggregate_multiset(mixed ... elems)
Construct a multiset.
Construct a multiset with the arguments as indices.
This method is most useful when constructing multisets
with map or similar; generally, the multiset literal
syntax is handier: (< elem1, elem2, ... >)
sizeof() , multisetp() , mkmultiset()
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() , `/()
int(0..1) `!=(mixed arg1, mixed arg2, mixed ... extras)
Inequality operator.
Returns 0 (zero) if all the arguments are equal, and 1 otherwise.
This is the inverse of `==() .
`==()
int(0..1) `==(mixed arg1, mixed arg2, mixed ... extras)
Equality operator.
Returns 1 if all the arguments are equal, and 0 (zero) otherwise.
`!=()
int(0..1) `<(mixed arg1, mixed arg2, mixed ... extras)
Less than operator.
Returns 1 if the arguments are strictly increasing, and 0 (zero) otherwise.
`<=() , `>() , `>=()
int(0..1) `<=(mixed arg1, mixed arg2, mixed ... extras)
Less or equal operator.
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 operator.
Returns 1 if the arguments are strictly decreasing, and 0 (zero) otherwise.
`<() , `<=() , `>=()
int(0..1) `>=(mixed arg1, mixed arg2, mixed ... extras)
Greater or equal operator.
Returns 1 if the arguments are not strictly increasing, and 0 (zero) otherwise.
This is the inverse of `<() .
`<=() , `>() , `<()
mixed `+(mixed arg1)
mixed `+(object arg1, mixed ... extras)
string `+(string arg1, string|int|float arg2)
string `+(int|float arg1, string arg2)
int `+(int arg1, int arg2)
float `+(float arg1, int|float arg2)
float `+(int|float arg1, float arg2)
array `+(array arg1, array arg2)
mapping `+(mapping arg1, mapping arg2)
multiset `+(multiset arg1, multiset arg2)
mixed `+(mixed arg1, mixed arg2, mixed ... extras)
Addition operator.
If there's only a single argument, that argument will be returned.
If arg1 is an object and it has an lfun::`+() , that function will be called with the rest of the arguments, and the result returned.
Otherwise if any of the other arguments is an object that has an lfun::``+() the first such function will be called with the arguments leading up to it, and `+() be called recursively with the result and the rest of the arguments.
If there are two arguments the result will be:
arg1 can have any of the following types:
|
Otherwise if there are more than 2 arguments the result will be:
`+(`+(arg1 , arg2 ), @extras )
In Pike 7.0 and earlier the addition order was unspecified.
If arg1 is UNDEFINED it will behave as the empty array/mapping/multiset if needed. This behaviour was new in Pike 7.0.
`-() , lfun::`+() , lfun::``+()
mixed `-(mixed arg1)
mixed `-(object arg1, mixed arg2)
mixed `-(mixed arg1, mixed arg2)
mapping `-(mapping arg1, array arg2)
mapping `-(mapping arg1, multiset arg2)
mapping `-(mapping arg1, mapping arg2)
array `-(array arg1, array arg2)
multiset `-(multiset arg1, multiset arg2)
float `-(float arg1, int|float arg2)
float `-(int arg1, float arg2)
int `-(int arg1, int arg2)
string `-(string arg1, string arg2)
mixed `-(mixed arg1, mixed arg2, mixed ... extras)
Negation/subtraction operator.
If there's only a single argument, that argument will be returned
negated. If arg1 was an object, arg1 ::`-()
will be called
without arguments.
If there are more than two arguments the result will be:
.`-(`-(arg1 , arg2 ), @extras )
If arg1 is an object that overloads `-(), that function will be called with arg2 as the single argument.
If arg2 is an object that overloads ``-(), 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 subtraction order was unspecified.
`+()
mixed `&(mixed arg1)
mixed `&(object arg1, mixed arg2)
mixed `&(mixed arg1, object arg2)
int `&(int arg1, int arg2)
array `&(array arg1, array arg2)
multiset `&(multiset arg1, multiset arg2)
mapping `&(mapping arg1, mapping arg2)
string `&(string arg1, string arg2)
type `&(type|program arg1, type|program arg2)
mapping `&(mapping arg1, array arg2)
mapping `&(array arg1, mapping arg2)
mapping `&(mapping arg1, multiset arg2)
mapping `&(multiset arg1, mapping arg2)
mixed `&(mixed arg1, mixed arg2, mixed ... extras)
Bitwise and/intersection operator.
If there's a single argument, that argument will be returned.
If there are more than two arguments, the result will be:
.`&(`&(arg1 , arg2 ), @extras )
If arg1 is an object that has an lfun::`&() , that function will be called with arg2 as the single argument.
If arg2 is an object that has an 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:
|
`|() , lfun::`&() , lfun::``&()
mixed `|(mixed arg1)
mixed `|(object arg1, mixed arg2)
mixed `|(mixed arg1, object arg2)
int `|(int arg1, int arg2)
mapping `|(mapping arg1, mapping arg2)
multiset `|(multiset arg1, multiset arg2)
array `|(array arg1, array arg2)
string `|(string arg1, atring arg2)
type `|(program|type arg1, program|type arg2)
mixed `|(mixed arg1, mixed arg2, mixed ... extras)
Bitwise or/join operator.
If there's a single argument, that argument will be returned.
If there are more than two arguments, the result will be:
.`|(`|(arg1 , arg2 ), @extras )
If arg1 is an object that has an lfun::`|() , that function will be called with arg2 as the single argument.
If arg2 is an object that has an 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:
|
`&() , lfun::`|() , lfun::``|()
mixed `^(mixed arg1)
mixed `^(object arg1, mixed arg2)
mixed `^(mixed arg1, object arg2)
int `^(int arg1, int arg2)
mapping `^(mapping arg1, mapping arg2)
multiset `^(multiset arg1, multiset arg2)
array `^(array arg1, array arg2)
string `^(string arg1, atring arg2)
type `^(program|type arg1, program|type arg2)
mixed `^(mixed arg1, mixed arg2, mixed ... extras)
Exclusive or operator.
If there's a single argument, that argument will be returned.
If there are more than two arguments, the result will be:
.`^(`^(arg1 , arg2 ), @extras )
If arg1 is an object that has an lfun::`^() , that function will be called with arg2 as the single argument.
If arg2 is an object that has an 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:
|
`&() , `|() , lfun::`^() , lfun::``^()
int `<<(int arg1, int arg2)
mixed `<<(object arg1, int|object arg2)
mixed `<<(int arg1, object arg2)
Left shift operator.
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 operator.
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 operator.
If there's only 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, atring 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 operator.
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:
|
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 operator.
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:
|
int(0..1) `!(object|function arg)
int(1..1) `!(int(0..0) arg)
int(0..0) `!(mixed arg)
Negation operator.
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.
`==() , `!=() , lfun::`!()
mixed `~(object arg)
int `~(int arg)
float `~(float arg)
type `~(type|program arg)
string `~(string arg)
Complement operator.
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 and range operator.
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:
|
`->() , 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 operator.
This function behaves much like `[]() , just that the index is always a string.
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:
|
`[]() , 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 assign operator.
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.
`->=() , 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 assign operator.
This function behaves much like `[]=() , just that the index is always a string.
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.
`[]=() , lfun::`->=()
int sizeof(string arg)
int sizeof(array arg)
int sizeof(mapping arg)
int sizeof(multiset arg)
int sizeof(object arg)
Sizeof operator.
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()
void signal(int sig, function(int: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)
int fork()
Fork the process in two.
Fork splits the process in two, and for the parent it returns the pid of 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()
_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.)
mixed call_function(function fun, mixed ... args)
Call a function.
string version()
Report the version of Pike.
__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 t)
This function changes the debug trace level.
The old level is returned.
Trace level 1 or higher means that calls to Pike functions are printed to stderr, level 2 or higher means calls to builtin functions are printed, 3 means every opcode interpreted is printed, 4 means arguments to these opcodes are printed as well.
See the -t command-line option for more information.
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 the signle argument.
Other wise 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 .
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()
int random(int max)
This function returns a random number in the range 0 - max -1.
random_seed()
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 accomodate 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()
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.
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)
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(mixed trace, void|int linewidth)
Returns a string containing a readable message that describes where the backtrace was made.
The argument trace should normally be the return value from a call to backtrace() , or a caught error.
backtrace() , describe_error() , catch() , throw()
string describe_error(mixed trace)
Returns only the error message from a backtrace.
If there is no error message in the backtrace, a fallback message will be returned.
backtrace() , describe_backtrace()
CLASS Error |
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()
Make a readable error-message.
Uses describe_backtrace() to generate the message.
array backtrace()
Get the backtrace from where the error occurred.
predef::backtrace()
string _sprintf()
void Error(string message)
CLASS string_assignment |
int `[](int i, int j)
String index operator.
int `[]=(int i, int j)
String assign index operator.
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
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:
|
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(mixed)|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)
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 compiling error occurs. Nothing strange about it. Note that previous_object cannot be trusted in ths function, because the compiler calls this function.
void compile_warning(string file, int line, string err)
This function is called whenever a compiling warning occurs. Nothing strange about it. Note that previous_object cannot be trusted in ths function, because the compiler calls this function.
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.CompatResolver |
CompatResolver parent_resolver
If we fail to resolv, try our parent.
Typical configuration:
0.6->7.0->7.2->7.4->master
void master.CompatResolver(mixed version)
The CompatResolver is initialized with a value that can be casted into a "%d.%d" string, e.g. a version object.
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 get_default_module()
mixed resolv_base(string identifier, string|void current_file, object|void current_handler)
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.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.
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 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.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()
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.
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.
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 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(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 intput)
Document this function.
array(string) Unicode.split_words_and_normalize(string input)
Document this function.
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)
Document this function.
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.
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 supported4
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.
ascii 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 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.
Module Gmp |
CLASS Gmp.mpz |
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.
CLASS Gmp.mpf |
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.
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 "___predef::"
int Gz.crc32(string data, void|int start_value)
This function calculates the standard ISO3309 Cyclic Redundancy Check.
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 file, void|string mode)
Filename or filedescriptor of the gzip file to open.
mode for the file. Defaults to "rb".
open Stdio.File
int open(string|int file, void|string mode)
Filename or filedescriptor of the gzip file to open.
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 X)
If given, X 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.
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()
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()
CLASS Gz._file |
Low-level implementation of read/write support for GZip files
int open(string|int file, void|string mode)
Opens a file for I/O.
The filename or an open filedescriptor 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 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.
Not supported on all operating systems.
int tell()
the current position within the file.
Not supported on all operating systems.
int(0..1) eof()
1 if EOF has been reached.
Not supported on all operating systems.
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: Z_DEFAULT_STRATEGY Z_FILTERED Z_HUFFMAN_ONLY
Not supported on all operating systems.
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 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 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. ints).
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 (ints) 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 . 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 |
inherit "___predef::"
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.
CLASS Math.SMatrix |
These classes hold Matrix capabilites, and support a range of matrix operations.
Matrix only handles double precision floating point values FMatrix only handles single precision floating point values LMatrix only handles integers (64 bit) IMatrix only handles integers (32 bit) SMatrix only handles integers (16 bit)
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.
array(array) cast(string to_what)
array(array) cast(string to_what)
This is to be able to get the matrix values. (array) gives back a double array of floats. m->vect() gives back an array of floats.
Matrix convolve(object with)
Convolve called matrix with the argument.
void Math.SMatrix(array(array(int|float)) 2d_matrix)
void Math.SMatrix(array(int|float) 1d_matrix)
void Math.SMatrix(int n, int m)
void Math.SMatrix(int n, int m, string type)
void Math.SMatrix(int n, int m, float|int init)
void Math.SMatrix("identity", int size)
void Math.SMatrix("rotate", int size, float rads, Matrix axis)
void Math.SMatrix("rotate", int size, float rads, float x, float y, float z)
This method initializes the matrix. It is illegal to create and hold an empty matrix.
The normal operation is to create the matrix object with a double array, like Math.Matrix( ({({1,2}),({3,4})}) ).
Another use is to create a special type of matrix, and this is told as third argument.
Currently there are only the "identity" type, which gives a matrix of zeroes except in the diagonal, where the number one (1.0) is. This is the default, too.
The third use is to give all indices in the matrix the same value, for instance zero or 42.
The forth use is some special matrixes. First the square identity matrix again, then the rotation matrix.
Matrix cross(object with)
Matrix `×(object with)
Matrix ``×(object with)
Matrix cross-multiplication.
float dot_product(object with)
float `·(object with)
float ``·(object with)
Matrix dot product.
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.
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 `-()
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 transpose()
Transpose of the matrix as a new object.
array vect()
Return all the elements of the matrix as an array of numbers
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, inte 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 |
This module 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.(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 match or split. Calling create() without an argument can be used to free up a little memory after the regexp has been used.
int Regexp.match(string str)
Returns 1 if str matches the regexp bound to the regexp object. Zero otherwise.
array(string) Regexp.match(array(string) strs)
Returns an array containing strings in strs that match the regexp bound to the regexp object.
The current implementation (Pike 7.3.51) doesn't support searching in strings containing the NUL character or any wide character.
split
array(string) Regexp.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 (Pike 7.3.51) doesn't support searching in strings containing the NUL character or any wide character.
match
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.FrameGreencosntant 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 "___predef::"
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 Crypto |
string Crypto.string_to_hex(string data)
Convert a string of binary data to a hexadecimal string.
hex_to_string()
string Crypto.hex_to_string(string hex)
Convert a string of hexadecimal digits to binary data.
string_to_hex()
string Crypto.des_parity(string raw)
Adjust the parity for a string so that it is acceptable according to DES.
string Crypto.crypt_md5(string password)
string Crypto.crypt_md5(string password, string salt)
This function crypts a password with an algorithm based on MD5 hashing.
If salt is left out, an 8 character long salt (max length) will be randomized.
Verification can be done by supplying the crypted password as salt :
crypt_md5(typed_pw, crypted_pw) == crypted_pw
crypt()
object Crypto.rsaset_public_key(bignum modulo, bignum pub)
Document this function.
CLASS Crypto.arcfour |
Implementation of the arcfour stream-crypto.
string name()
Returns the string "ARCFOUR".
int query_key_length()
Returns the minimum required encryption key length. Currently this is 1.
void set_encrypt_key(string key)
void set_decrypt_key(string key)
Set the encryption/decryption key to key .
string crypt(string data)
Returns the string data encrypted with the current encryption key.
set_encrypt_key()
CLASS Crypto.cast |
Implementation of the CAST block crypto.
string name()
Returns the string "CAST".
int query_block_size()
Return the encryption block size used by CAST.
int query_key_length()
Return the encryption key length used by CAST.
Crypto.cast set_encrypt_key(string key)
Set the encryption key to key , and set the object to encryption mode.
Returns the current object.
Crypto.cast set_decrypt_key(string key)
Set the decryption key to key , and set the object to decryption mode.
Returns the current object.
string crypt_block(string data)
Encrypt/decrypt the string data with the current key.
If data is longer than the block size, additional blocks will be encrypted the same way as the first one (ie ECB-mode).
Will throw errors if
is not a multiple
of the block size.sizeof(data )
set_encrypt_key() , set_decrypt_key()
CLASS Crypto.cbc |
Implementation of the cipher block chaining mode (CBC).
void Crypto.cbc(object cipher)
Initialize a cipher block chaining object with the cipher cipher .
int query_block_size()
Return the block size of the contained object.
int query_key_length()
Return the encryption key length of the contained object.
object set_encrypt_key(string key)
Set the encryption key of the contained object.
object set_decrypt_key(string key)
Set the decryption key of the contained object.
object set_iv(string iv)
Set the initialization vector to iv .
string encrypt_block(string data)
Encrypt the string data according to the cipher block chaining mode.
string decrypt_block(string data)
Decrypt the string data according to the cipher block chaining mode.
string crypt_block(string data)
Encrypt/decrypt the string data according to the cipher block chaining mode.
CLASS Crypto.crypto |
Buffer a block-crypto.
void Crypto.crypto(object cipher)
void Crypto.crypto(program prog, mixed ... args)
Initialize a block-crypto buffer.
int query_block_size()
Get the block size of the contained block-crypto.
int query_key_length()
void set_encrypt_key(string key)
Set the encryption key.
As a side-effect any buffered data will be cleared.
void 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()
CLASS Crypto.rijndael |
Implementation of the Rijndael (aka AES) block-crypto.
Crypto.aes
string name()
Returns the string "RIJNDAEL".
int query_block_size()
Returns the Rijndael block size.
int query_key_length()
Returns the key length used by Rijndael (currently 32).
void set_encrypt_key(string key)
Set the encryption key.
void set_decrypt_key(string key)
Set the decryption key.
string encrypt(string data)
De/encrypt data with Rijndael using the current key.
CLASS Crypto.des |
Implementation of the Data Encryption Standard (DES).
string name()
Return the string "DES".
int query_block_size()
Return the block size used by DES.
int query_key_length()
Return the key length used by DES.
void set_encrypt_key(string key)
Set the encryption key.
void set_decrypt_key(string key)
Set the decryption key.
string crypt_block(string data)
En/decrypt data with DES using the current key.
CLASS Crypto.idea |
Support for the IDEA block crypto.
string name()
Return the string "IDEA".
int query_block_size()
Return the block size for IDEA.
int query_key_length()
Return the key length for IDEA.
void set_encrypt_key(string key)
Set the encryption key to key .
void set_decrypt_key(string key)
Set the decryption key to key .
string crypt_block(string data)
De/encrypt data with IDEA.
CLASS Crypto.invert |
Inversion crypto module.
string name()
Returns the string "INVERT".
int query_block_size()
Returns the block size for the invert crypto (currently 8).
int query_key_length()
Returns the minimum key length for the invert crypto.
Since this crypto doesn't use a key, this will be 0.
void set_key(string key)
Set the encryption key (currently a no op).
string crypt_block(string data)
De/encrypt the string data with the invert crypto (ie invert the string).
CLASS Crypto.md2 |
Implementation of the MD2 message digest algorithm.
string name()
Returns the string "MD2".
void Crypto.md2(Crypto.md2|void init)
Initialize an MD2 digest.
If the argument init is specified, the state from it will be copied.
Crypto.md2 update(string data)
Feed some data to the digest algorithm.
string identifier()
Returns the ASN1 identifier for an MD2 digest.
string digest()
Return the digest.
As a side effect the object will be reinitialized.
CLASS Crypto.md4 |
Implementation of the MD4 message digest algorithm.
string name()
Return the string "MD4".
void Crypto.md4(Crypto.md4|void init)
Initialize an MD4 digest.
If the argument init is specified, the state from it will be copied.
Crypto.md4 update(string data)
Feed some data to the digest algorithm.
string identifier()
Returns the ASN1 identifier for an MD4 digest.
string digest()
Return the digest.
As a side effect the object will be reinitialized.
CLASS Crypto.md5 |
Implementation of the MD5 message digest algorithm.
string name()
Return the string "MD5".
void Crypto.md5(Crypto.md5|void init)
Initialize an MD5 digest.
If the argument init is specified, the state from it will be copied.
Crypto.md5 update(string data)
Feed some data to the digest algorithm.
string identifier()
Returns the ASN1 identifier for an MD5 digest.
string digest()
Return the digest.
As a side effect the object will be reinitialized.
CLASS Crypto.nt |
CryptoContext CryptAcquireContext(string str1, string str2, int typ, int flags)
CLASS Crypto.nt.CryptoContext |
string CryptGenRandom(int size, string|void init)
CLASS Crypto.pipe |
Chains serveral block-cryptos.
This can be used to implement eg DES3.
void Crypto.pipe(program|object|array(program|mixed) ciphers)
Initialize a block-crypto pipe.
string name()
Returns the string "PIPE("
followed by a
comma-separated list of the names of contained ciphers, and
terminated with the string ")"
.
int query_block_size()
Returns the joined block size.
array(int|array) query_key_length()
Returns an array of the contained ciphers key lengths.
void set_encrypt_key(array|string ... keys)
Sets the encryption keys for the contained ciphers.
void set_decrypt_key(array|string ... keys)
Sets the decryption keys for the contained ciphers.
string crypt_block(string data)
De/encrypts the string data with the contained ciphers in sequence.
CLASS Crypto.sha |
string name()
Returns the string "SHA".
void Crypto.sha(Crypto.sha|void init)
Initialize an SHA digest.
If the argument init is specified, the state from it will be copied.
Crypto.sha update(string data)
Feed some data to the digest algorithm.
string identifier()
Returns the ASN1 identifier for an SHA digest.
string digest()
Return the digest.
As a side effect the object will be reinitialized.
CLASS Crypto.des3 |
Triple-DES
pipe , des
inherit Crypto.pipe : pipe
int query_key_size()
Document this function.
int query_block_size()
Document this function.
object set_encrypt_key(string key)
Document this function.
An exception will be raised if key is weak
object set_decrypt_key(string key)
Document this function.
An exception will be raised if key is weak
CLASS Crypto.aes |
Advanced Encryption Standard (AES), previously known as Crypto.rijndael .
inherit Crypto.rijndael : rijndael
string name()
Returns the string "AES".
CLASS Crypto.des3_cbc |
Triple-DES CBC.
cbc , des
inherit Crypto.cbc : cbc
CLASS Crypto.des_cbc |
DES CBC.
cbc , des
inherit Crypto.cbc : cbc
CLASS Crypto.dsa |
The Digital Signature Algorithm (aka DSS, Digital Signature Standard).
object set_public_key(bignum p_, bignum q_, bignum g_, bignum y_)
Document this function.
object set_private_key(bignum secret)
Document this function.
object use_random(function r)
Document this function.
bignum hash2number(string digest)
Document this function.
bignum dsa_hash(string msg)
Document this function.
bignum random_number(bignum n)
Generate a random number k, 0<=k<n
bignum random_exponent()
Document this function.
array(bignum) raw_sign(bignum h)
Document this function.
int raw_verify(bignum h, bignum r, bignum s)
Document this function.
string sign_rsaref(string msg)
Document this function.
int verify_rsaref(string msg, string s)
Document this function.
string sign_ssl(string msg)
Document this function.
int verify_ssl(string msg, string s)
Document this function.
object set_public_test_key()
Document this function.
object set_private_test_key()
Document this function.
string nist_hash(bignum x)
The (slow) NIST method of generating DSA primes. Algorithm 4.56 of Handbook of Applied Cryptography.
array(bignum) nist_primes(int l)
Returns ({ p, q })
Document this function.
bignum find_generator(bignum p, bignum q)
Document this function.
object generate_parameters(int bits)
Document this function.
object generate_key()
Document this function.
int public_key_equal(object dsa)
Document this function.
CLASS Crypto.hmac |
HMAC, defined by RFC-2104
void Crypto.hmac(function h, int|void b)
Document this function.
string raw_hash(string s)
Document this function.
string pkcs_digest(string s)
Document this function.
CLASS Crypto.hmac.`() |
Document this function.
void Crypto.hmac.`()(string passwd)
Document this function.
string `()(string text)
Document this function.
string digest_info(string text)
Document this function.
CLASS Crypto.idea_cbc |
IDEA CBC.
cbc , idea
inherit Crypto.cbc : cbc
CLASS Crypto.rsa |
bignum raw_sign(string digest)
Document this function.
bignum get_n()
Document this function.
bignum get_e()
Document this function.
bignum get_d()
Document this function.
bignum get_p()
Document this function.
bignum get_q()
Document this function.
string cooked_get_p()
Document this function.
string cooked_get_q()
Document this function.
object set_private_key(bignum priv, array(bignum)|void extra)
Document this function.
object sign(string message, program h)
Document this function.
int verify(string msg, program h, object sign)
Document this function.
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.
bignum get_prime(int bits, function r)
Document this function.
object generate_key(int bits, function|void r)
Document this function.
object set_encrypt_key(array(bignum) key)
Document this function.
object set_decrypt_key(array(bignum) key)
Document this function.
string crypt_block(string s)
Document this function.
int query_blocksize()
Document this function.
bignum rsa_pad(string message, int type, mixed|void random)
Document this function.
string rsa_unpad(bignum block, int type)
Document this function.
string cooked_sign(string digest)
Document this function.
int raw_verify(string digest, bignum s)
Document this function.
string encrypt(string s, mixed|void r)
Document this function.
string decrypt(string s)
Document this function.
int rsa_size()
Document this function.
int public_key_equal(object rsa_wrapper)
Document this function.
Module Crypto.randomness |
Assorted stronger or weaker randomnumber generators. These devices try to collect entropy from the environment. They differ in behaviour when they run low on entropy, /dev/random will block if it can't provide enough random bits, while /dev/urandom will degenerate into a reasonably strong pseudo random generator
object Crypto.randomness.reasonably_random()
object Crypto.randomness.really_random(int|void may_block)
CLASS Crypto.randomness.pike_random |
A pseudo random generator based on the ordinary random() function.
string read(int len)
Returns a string of length len with pseudo random values.
CLASS Crypto.randomness.arcfour_random |
A pseudo random generator based on the arcfour crypto.
inherit Crypto.arcfour : arcfour
void Crypto.randomness.arcfour_random(string secret)
Initialize and seed the arcfour random generator.
string read(int len)
Return a string of the next len random characters from the arcfour random generator.
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:
|
Registry key.
Returns an array of value keys stored at the specified location iof any. Throws errors on failure.
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.
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()
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 System.innetgr(string netgroup, string|void machine, string|void user, string|void domain)
Document this function.
void System.setuid(int uid)
Sets the real user ID, effective user ID and saved user ID to uid .
getuid() , setgid() , getgid() , seteuid() , geteuid() , setegid() , getegid()
void System.setgid(int gid)
Sets the real group ID, effective group ID and saved group ID to gid .
getuid() , setuid() , getgid() , seteuid() , geteuid() , setegid() , getegid()
int System.seteuid(int euid)
Set the effective user ID to euid .
int System.setegid(int egid)
Set the effective group ID to egid .
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.
getpid , getpgrp , setsid
int System.setsid()
Set a new process session ID for the current process, and return it.
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)
Document this function.
int System.setresgid(int rgid, int egid, int sgid)
Document this function.
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.
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)
Document this function.
mapping(string:array(int)) System.getrlimits()
Document this function.
int(0..1) System.setrlimit(string resource, int cur, int max)
Document this function.
float System.setitimer(int|float arg)
Document this function.
array(float) System.getitimer()
Document this function.
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.gettimeoday()
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).
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 Pike |
constant Pike.WEAK_INDICES = __builtin.PIKE_WEAK_INDICES
constant Pike.WEAK_VALUES = __builtin.PIKE_WEAK_VALUES
constant Pike.WEAK = WEAK_INDICES|WEAK_VALUES
Flags for use together with set_weak_flag and get_weak_flag . See set_weak_flag for details.
CLASS Pike.Backend |
void `()(float sleep_time)
Perform one pass through the backend.
Wait at most sleep_time seconds.
void add_file(Stdio.File|Stdio.FILE f)
Add f to this 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.
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()
void _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.
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()
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
. If creds is 0 (zero), the
credentials from the current object will be used.func (@args )
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
Document this constant.
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(object user, int allow_bits, int data_bits)
Initialize a new credentials object
The current creds must 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.
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.
The exit code of the process.
int(-1..1) status()
Returns the status of 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 = int|array(int|string)|mapping(string:int|string)|string
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.Process |
inherit __builtin.create_process : create_process
void Process.Process(string|array(string) args, mapping m)
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 result()
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:
|
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.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.
Fifos are only available on systems with threads support.
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 a value to the fifo.
write() , read_array()
array read_array()
This function returns all values currently in the fifo. 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 a value to the fifo.
write() , read()
void 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.
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.
Queues are only available on systems with POSIX or UNIX or WIN32 thread support.
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 a value to the queue.
write()
void write(mixed value)
This function puts a value last in the queue. If the queue is too small to hold the value the queue will be expanded to make room for it.
read()
Module Audio |
Module Audio.Format |
Audio data format handling
API remains marked "unstable".
CLASS Audio.Format.ANY |
object read_file(string filename, int|void nocheck)
Reads data from file
read_streamed
object read_streamed(string filename, int|void nocheck)
Reads data from stream
Ie. for packetized data source the beggining of data is searched.
read_file
object 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()
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 ])
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
object 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 Calendar |
CLASS Calendar.Calendar |
This is the base class of the calendars.
TimeRange now()
Give the zero-length time period of the current time.
CLASS Calendar.Ruleset |
This is the container class for rules.
Ruleset set_abbr2zone(mapping(string:string) abbr2zone)
Sets the guess-mapping for timezones. Default is the mapping
Abbreviation Interpretation
AMT America/Manaus [UTC-4]
AST America/Curacao [UTC-4]
CDT America/Costa_Rica [UTC-5]
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]
YMD.parse
CLASS Calendar.TimeRange |
This is the base class for any time measurement and calendrar information. It defines all the things you can do with a time range, 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(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 wierd 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.
constant 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.
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.
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.
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.
Module Calendar.Event |
CLASS Calendar.Event.Event |
Event is a base class, defining what methods an Event need to have.
TimeRange next(TimeRange from, void|int(0..1) including)
TimeRange previous(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.
This method is virtual in the base class.
array(TimeRange) scan(TimeRange in)
This calculates the eventual events that is contained or overlapped by the given timerange.
Example: Event.christmas_eve->scan(Year(2000)) => ({ Day(Sun 24 Dec 2000) })
scan uses next if not overloaded.
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.
CLASS Calendar.Event.Day_Event |
Day_Event is a base class, extending Event for events that are single days, using julian day numbers for the calculations.
array(TimeRange) scan(TimeRange in)
TimeRange next(TimeRange from)
TimeRange next(TimeRange from, int(0..1) including)
These methods are implemented, using the virtual method scan_jd .
Event
int scan_jd(Calendar realm, int jd, int(-1..-1)|object|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.
direction1 is forward (next), -1 is backward (previous).
CLASS Calendar.Event.Nameday |
This is created by the Namedays classes to represent an event for a name.
CLASS Calendar.Event.Namedays |
This contains a ruleset about namedays.
mapping(TimeRange:array(string)) namedays(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.
array(string) names(TimeRange t)
Gives back an array of names that occur during the time period, in no particular order.
TimeRange previous(TimeRange from, void|int(0..1) including)
TimeRange next(TimeRange from, void|int(0..1) including)
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.
void Calendar.Event.Date(int month_day, int 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.
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.
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 "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" and "sunday".
void Calendar.Event.Weekday(int weekday)
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 - not the Gregorian or Julian calendar that has 1=Sunday, 7=Saturday.
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.
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).
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.
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.
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.
known bugs: I have currently no idea how the arabic countries count the week. Follow the same rules as ISO for now... The time is also suspicious; the *day* really starts at sunrise (sunset?) and not midnight, the hours of the day is not correct. Also don't know what to call years before 1 - go for "BH"; positive years are "AH", anno Hegirac.
Module Calendar.Julian |
This is the Julian calendar, conjured up by the old Romans when their calendar were just too wierd. 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.
Module Calendar.Roman |
base for all Roman-kind of calendars ie, one with years, months, weeks and days
Module Calendar.Stardate |
This implements TNG stardates.
void Calendar.Stardate.(mixed ...)
void Calendar.Stardate.(int|float date)
void Calendar.Stardate.()
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.
known bugs: Since the precision is limited to the float type of pike you can get non-precise results:
> Calendar.Second(Calendar.Stardate.Day(Calendar.Year()));
Result: Second(Fri 31 Dec 1999 23:59:18 CET - Sun 31 Dec 2000 23:59:18 CET)
TimeofDay Calendar.Stardate.now()
Give the zero-length time period of the current time.
int Calendar.Stardate.number_of_seconds()
int Calendar.Stardate.number_of_days()
This gives back the Gregorian/Earth/ISO number of seconds
and 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.
long "-322537.312"
short "77463.312" (w/o >100000-component)
vshort "7463.312" (w/o >10000-component)
float Calendar.Stardate.tics()
This gives back the number of stardate tics in the period.
Module Calendar.Swedish |
Same as the ISO calendar, but with swedish as the default language.
This calendar exist only for backwards compatible purposes.
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 |
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]
[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("unixtime", int|float unixtime)
void Calendar.Time.Fraction("unixtime", int|float unixtime, int|float len)
It is possible to create a Fraction in two ways, either "now" with no arguments or from a unix time (as from time(2)).
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@mirar.org. /Mirar
TZnames , Ruleset.Timezone
constant Calendar.Timezone.locale = Ruleset.Timezone
This contains the local timezone, found from various parts of the system, if possible.
constant Calendar.Timezone.localtime = Ruleset.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 |
class time_unit
array(string) lesser()
Gives a list of methods to get lesser (shorter) time units.
ie, for a month, this gives back
and the method ({"day"})
gives back that
day object. The method day(mixed n)
gives back a
list of possible argument values to the method day.
Concurrently, days()
gives
a list of day objects in the object o.Array.map(o->days(),o->day)
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
, and -1 gives the last,
equal to my_obj->xxx(my_obj->xxxs()[0])
.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
,
thus the method ({"year"})
gives the year object.month->year()
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
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.my_day+14
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 comiled with dmalloc.
mapping(string:int) Debug.locate_references(string|array|mapping|multiset|function|object|program|type 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()
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 .
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
Module Filesystem.Tar |
Filesystem which can be used to mount a Tar file.
void Filesystem.Tar.(string filename, void|Filesystem.Base parent)
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.
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 feeded 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".
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)
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.pike"
inherit "create_graph.pike"
inherit "create_bars.pike"
inherit "create_pie.pike"
inherit "create_graph.pike"
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
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 Standards |
CLASS Standards.RDF |
Represents an RDF domain which can contain any number of complete statements.
void add_statement(Resource subj, Resource pred, Resource obj)
Adds a statement to the RDF set.
Resource get_resource(string uri)
Returns an RDF resource with the given URI as identifier, or zero.
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.
|
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.
CLASS Standards.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.
CLASS Standards.RDF.LiteralResource |
Resource identified by literal.
inherit Resource : Resource
void Standards.RDF.LiteralResource(string literal)
The resource will be identified by literal .
CLASS Standards.RDF.URIResource |
Resource identified by URI.
inherit Resource : Resource
void Standards.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.
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.PKCS |
Module Standards.PKCS.Certificate |
Handle PKCS-6 and PKCS-10 certificates and certificate requests.
Module Standards.PKCS.Signature |
string Standards.PKCS.Signature.build_digestinfo(string msg, object hash)
Construct a PKCS-1 digestinfo
message to digest
crypto hash object such as Crypto.sha or Crypto md5
Module Standards.PKCS.RSA |
RSA operations and types as described in PKCS-1.
string Standards.PKCS.RSA.public_key(object rsa)
Create a DER-coded RSAPublicKey structure
Crypto.rsa object
ASN1 coded RSAPublicKey structure
string Standards.PKCS.RSA.private_key(object rsa)
Create a DER-coded RSAPrivateKey structure
Crypto.rsa object
ASN1 coded RSAPrivateKey structure
string Standards.PKCS.RSA.rsa_public_key(object rsa)
string Standards.PKCS.RSA.rsa_private_key(object rsa)
object Standards.PKCS.RSA.parse_public_key(string key)
Decode a DER-coded RSAPublicKey structure
RSAPublicKey provided in ASN1 encoded format
Crypto.rsa object
object 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.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.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.
int(0..1) Standards.ISO639_2.verify_overlap()
Returns 1 if there is an overlap between ISO 639-2/T and ISO 639-2/B symbols. Only used for debugging when updating the table.
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 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.Tagv2 |
ID3 version 2 (2.2, 2.3, 2.4) Tags
CLASS Standards.ID3.Tagv1 |
ID3 version 1.0 or 1.1 tag
CLASS Standards.ID3.Tag |
ID3 tag object
Tries to find version 2 tags in file and then version 1 tag.
Version 1 tag is searched only if version 2 isn't there.
Tagv2 , Tagv1
mapping friendly_values()
Returns tag values in friendly manner
Only version 1 equivalent of version 2 tags are returned.
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 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.
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" or "module".
The name of the class/module.
The ancestors of the class/module.
// 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)
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.
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.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.
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()
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 |
void set_current(int _cur)
void set_name(string _name)
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)
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.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 |
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.
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.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.GlobRule |
A rule that uses glob expressions
inherit Rule : Rule
void Web.Crawler.GlobRule(string pattern)
A glob pattern that the rule will match against.
GlobRule("http://pike.ida.liu.se/*.xml");
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
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 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)
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 value for black 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 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
constant Getopt.NO_ARG
constant Getopt.MAY_HAVE_ARG
array(array) Getopt.find_all_options(array(string) argv, array(array(array(string)|string)) 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 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.