node
-- evented I/O for V8 JavaScript
An example of a web server written with Node which responds with 'Hello World':
var sys = require('sys'),
http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
sys.puts('Server running at http://<IP_ADDRESS>:8124/');
To run the server, put the code into a file called example.js
and execute
it with the node program
> node example.js
Server running at http://<IP_ADDRESS>:8124/
All of the examples in the documentation can be run similarly.
Node comes with a number of modules that are compiled in to the process,
most of which are documented below. The most common way to use these modules
is with require('name')
and then assigning the return value to a local
variable with the same name as the module.
Example:
var sys = require('sys');
It is possible to extend node with other modules. See 'Modules'
Pure Javascript is Unicode friendly but not nice to binary data. When dealing with TCP streams or the file system, it's necessary to handle octet streams. Node has several strategies for manipulating, creating, and consuming octet streams.
Raw data is stored in instances of the Buffer
class. A Buffer
is similar
to an array of integers but corresponds to a raw memory allocation outside
the V8 heap. A Buffer
cannot be resized.
Access the class with require('buffer').Buffer
.
Converting between Buffers and JavaScript string objects requires an explicit encoding
method. Node supports 3 string encodings: UTF-8 ('utf8'
), ASCII ('ascii'
), and
Binary ('binary'
).
'ascii'
- for 7 bit ASCII data only. This encoding method is very fast, and will
strip the high bit if set.
'binary'
- for 8 bit binary data such as images.
'utf8'
- Unicode characters. Many web pages and other document formats use UTF-8.
Allocates a new buffer of size
octets.
Allocates a new buffer using an array
of octets.
Allocates a new buffer containing the given str
.
Writes string
to the buffer at offset
using the given encoding. Returns
number of octets written. If buffer
did not contain enough space to fit
the entire string it will write a partial amount of the string. In the case
of 'utf8'
encoding, the method will not write partial characters.
Example: write a utf8 string into a buffer, then print it
var sys = require('sys'),
Buffer = require('buffer').Buffer,
buf = new Buffer(256),
len;
len = buf.write('\u00bd + \u00bc = \u00be', 'utf8', 0);
sys.puts(len + " bytes: " + buf.toString('utf8', 0, len));
// 12 bytes: ½ + ¼ = ¾
Decodes and returns a string from buffer data encoded with encoding
beginning at start
and ending at end
.
See buffer.write()
example, above.
Get and set the octet at index
. The values refer to individual bytes,
so the legal range is between 0x00
and 0xFF
hex or 0
and 255
.
Example: copy an ASCII string into a buffer, one byte at a time:
var sys = require('sys'),
Buffer = require('buffer').Buffer,
str = "node.js",
buf = new Buffer(str.length),
i;
for (i = 0; i < str.length ; i += 1) {
buf[i] = str.charCodeAt(i);
}
sys.puts(buf);
// node.js
Gives the actual byte length of a string. This is not the same as
String.prototype.length
since that returns the number of characters in a
string.
Example:
var sys = require('sys'),
Buffer = require('buffer').Buffer,
str = '\u00bd + \u00bc = \u00be';
sys.puts(str + ": " + str.length + " characters, " +
Buffer.byteLength(str, 'utf8') + " bytes");
// ½ + ¼ = ¾: 9 characters, 12 bytes
The size of the buffer in bytes. Note that this is not necessarily the size
of the contents. length
refers to the amount of memory allocated for the
buffer object. It does not change when the contents of the buffer are changed.
var sys = require('sys'),
Buffer = require('buffer').Buffer,
buf = new Buffer(1234);
sys.puts(buf.length);
buf.write("some string", "ascii", 0);
sys.puts(buf.length);
// 1234
// 1234
Does a memcpy() between buffers.
Example: build two Buffers, then copy buf1
from byte 16 through byte 20
into buf2
, starting at the 8th byte in buf2
.
var sys = require('sys'),
Buffer = require('buffer').Buffer,
buf1 = new Buffer(26),
buf2 = new Buffer(26),
i;
for (i = 0 ; i < 26 ; i += 1) {
buf1[i] = i + 97; // 97 is ASCII a
buf2[i] = 33; // ASCII !
}
buf1.copy(buf2, 8, 16, 20);
sys.puts(buf2.toString('ascii', 0, 25));
// !!!!!!!!qrst!!!!!!!!!!!!!
Returns a new buffer which references the
same memory as the old, but offset and cropped by the start
and end
indexes.
Modifying the new buffer slice will modify memory in the original buffer!
Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte from the original Buffer.
var sys = require('sys'),
Buffer = require('buffer').Buffer,
buf1 = new Buffer(26), buf2,
i;
for (i = 0 ; i < 26 ; i += 1) {
buf1[i] = i + 97; // 97 is ASCII a
}
buf2 = buf1.slice(0, 3);
sys.puts(buf2.toString('ascii', 0, buf2.length));
buf1[0] = 33;
sys.puts(buf2.toString('ascii', 0, buf2.length));
// abc
// !bc
Many objects in Node emit events: a TCP server emits an event each time
there is a stream, a child process emits an event when it exits. All
objects which emit events are instances of events.EventEmitter
.
Events are represented by a camel-cased string. Here are some examples:
'stream'
, 'data'
, 'messageBegin'
.
Functions can be then be attached to objects, to be executed when an event is emitted. These functions are called listeners.
require('events').EventEmitter
to access the EventEmitter
class.
All EventEmitters emit the event 'newListener'
when new listeners are
added.
When an EventEmitter experiences an error, the typical action is to emit an
'error'
event. Error events are special--if there is no handler for them
they will print a stack trace and exit the program.
function (event, listener) { }
This event is made any time someone adds a new listener.
function (exception) { }
If an error was encountered, then this event is emitted. This event is special - when there are no listeners to receive the error Node will terminate execution and display the exception's stack trace.
Adds a listener to the end of the listeners array for the specified event.
server.addListener('stream', function (stream) {
sys.puts('someone connected!');
});
Remove a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener.
Removes all listeners from the listener array for the specified event.
Returns an array of listeners for the specified event. This array can be manipulated, e.g. to remove listeners.
Execute each of the listeners in order with the supplied arguments.
A stream is an abstract interface implemented by various objects in Node.
For example a request to an HTTP server is a stream, as is stdout. Streams
are readable, writable, or both. All streams are instances of EventEmitter
.
A readable stream has the following methods, members, and events.
function (data) { }
The 'data'
event emits either a Buffer
(by default) or a string if
setEncoding()
was used.
function () { }
Emitted when the stream has received an EOF (FIN in TCP terminology).
Indicates that no more 'data'
events will happen. If the stream is also
writable, it may be possible to continue writing.
function (exception) { }
Emitted if there was an error receiving data.
function () { }
Emitted when the underlying file descriptor has be closed. Not all streams
will emit this. (For example, an incoming HTTP request will not emit
'close'
.)
Makes the data event emit a string instead of a Buffer
. encoding
can be
'utf8'
, 'ascii'
, or 'binary'
.
Pauses the incoming 'data'
events.
Resumes the incoming 'data'
events after a pause()
.
Closes the underlying file descriptor. Stream will not emit any more events.
A writable stream has the following methods, members, and events.
function () { }
Emitted after a write()
method was called that returned false
to
indicate that it is safe to write again.
function (exception) { }
Emitted on error with the exception exception
.
function () { }
Emitted when the underlying file descriptor has been closed.
Writes string
with the given encoding
to the stream. Returns true
if
the string has been flushed to the kernel buffer. Returns false
to
indicate that the kernel buffer is full, and the data will be sent out in
the future. The 'drain'
event will indicate when the kernel buffer is
empty again. The encoding
defaults to 'utf8'
.
Same as the above except with a raw buffer.
Terminates the stream with EOF or FIN.
Sends string
with the given encoding
and terminates the stream with EOF
or FIN. This is useful to reduce the number of packets sent.
Same as above but with a buffer
.
Closes the underlying file descriptor. Stream will not emit any more events.
These object are available in the global scope and can be accessed from anywhere.
The global namespace object.
The process object. Most stuff lives in here. See the 'process object'
section.
To require modules. See the 'Modules'
section.
An array of search paths for require()
. This array can be modified to add custom paths.
Example: add a new path to the beginning of the search list
var sys = require('sys');
require.paths.unshift('/usr/local/node');
sys.puts(require.paths);
// /usr/local/node,/Users/mjr/.node_libraries
The filename of the script being executed. This is the absolute path, and not necessarily the same filename passed in as a command line argument.
The dirname of the script being executed.
Example: running node example.js
from /Users/mjr
var sys = require('sys');
sys.puts(__filename);
sys.puts(__dirname);
// /Users/mjr/example.js
// /Users/mjr
A reference to the current module (of type process.Module
). In particular
module.exports
is the same as the exports
object. See src/process.js
for more information.
The process
object is a global object and can be accessed from anywhere.
It is an instance of EventEmitter
.
function () {}
Emitted when the process is about to exit. This is a good hook to perform constant time checks of the module's state (like for unit tests). The main event loop will no longer be run after the 'exit' callback finishes, so timers may not be scheduled.
Example of listening for exit
:
var sys = require('sys');
process.addListener('exit', function () {
process.nextTick(function () {
sys.puts('This will not run');
});
sys.puts('About to exit.');
});
function (err) { }
Emitted when an exception bubbles all the way back to the event loop. If a listener is added for this exception, the default action (which is to print a stack trace and exit) will not occur.
Example of listening for uncaughtException
:
var sys = require('sys');
process.addListener('uncaughtException', function (err) {
sys.puts('Caught exception: ' + err);
});
setTimeout(function () {
sys.puts('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
sys.puts('This will not run.');
Note that uncaughtException
is a very crude mechanism for exception
handling. Using try / catch in your program will give you more control over
your program's flow. Especially for server programs that are designed to
stay running forever, uncaughtException
can be a useful safety mechanism.
function () {}
Emitted when the processes receives a signal. See sigaction(2) for a list of standard POSIX signal names such as SIGINT, SIGUSR1, etc.
Example of listening for SIGINT
:
var sys = require('sys'),
stdin = process.openStdin();
process.addListener('SIGINT', function () {
sys.puts('Got SIGINT. Press Control-D to exit.');
});
An easy way to send the SIGINT
signal is with Control-C
in most terminal
programs.
A writable stream to stdout
.
Example: the definition of sys.puts
exports.puts = function (d) {
process.stdout.write(d + '\n');
};
Opens the standard input stream, returns a readable stream.
Example of opening standard input and listening for both events:
var stdin = process.openStdin();
stdin.setEncoding('utf8');
stdin.addListener('data', function (chunk) {
process.stdout.write('data: ' + chunk);
});
stdin.addListener('end', function () {
process.stdout.write('end');
});
An array containing the command line arguments. The first element will be 'node', the second element will be the name of the JavaScript file. The next elements will be any additional command line arguments.
// print process.argv
var sys = require('sys');
process.argv.forEach(function (val, index, array) {
sys.puts(index + ': ' + val);
});
This will generate:
$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four
Changes the current working directory of the process or throws an exception if that fails.
var sys = require('sys');
sys.puts('Starting directory: ' + process.cwd());
try {
process.chdir('/tmp');
sys.puts('New directory: ' + process.cwd());
}
catch (err) {
sys.puts('chdir: ' + err);
}
Similar to eval
except that you can specify a filename
for better
error reporting and the code
cannot see the local scope. The value of filename
will be used as a filename if a stack trace is generated by the compiled code.
Example of using process.compile
and eval
to run the same code:
var sys = require('sys'),
localVar = 123,
compiled, evaled;
compiled = process.compile('localVar = 1;', 'myfile.js');
sys.puts('localVar: ' + localVar + ', compiled: ' + compiled);
evaled = eval('localVar = 1;');
sys.puts('localVar: ' + localVar + ', evaled: ' + evaled);
// localVar: 123, compiled: 1
// localVar: 1, evaled: 1
process.compile
does not have access to the local scope, so localVar
is unchanged.
eval
does have access to the local scope, so localVar
is changed.
In case of syntax error in code
, process.compile
exits node.
See also: Script
Returns the current working directory of the process.
require('sys').puts('Current directory: ' + process.cwd());
An object containing the user environment. See environ(7).
Ends the process with the specified code
. If omitted, exit uses the
'success' code 0
.
To exit with a 'failure' code:
process.exit(1);
The shell that executed node should see the exit code as 1.
Gets/sets the group identity of the process. (See setgid(2).) This is the numerical group id, not the group name.
var sys = require('sys');
sys.puts('Current gid: ' + process.getgid());
try {
process.setgid(501);
sys.puts('New gid: ' + process.getgid());
}
catch (err) {
sys.puts('Failed to set gid: ' + err);
}
Gets/sets the user identity of the process. (See setuid(2).) This is the numerical userid, not the username.
var sys = require('sys');
sys.puts('Current uid: ' + process.getuid());
try {
process.setuid(501);
sys.puts('New uid: ' + process.getuid());
}
catch (err) {
sys.puts('Failed to set uid: ' + err);
}
A compiled-in property that exposes NODE_VERSION
.
require('sys').puts('Version: ' + process.version);
A compiled-in property that exposes NODE_PREFIX
.
require('sys').puts('Prefix: ' + process.installPrefix);
Send a signal to a process. pid
is the process id and signal
is the
string describing the signal to send. Signal names are strings like
'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGINT'.
See kill(2) for more information.
Note that just because the name of this function is process.kill
, it is
really just a signal sender, like the kill
system call. The signal sent
may do something other than kill the target process.
Example of sending a signal to yourself:
var sys = require('sys');
process.addListener('SIGHUP', function () {
sys.puts('Got SIGHUP signal.');
});
setTimeout(function () {
sys.puts('Exiting.');
process.exit(0);
}, 100);
process.kill(process.pid, 'SIGHUP');
The PID of the process.
require('sys').puts('This process is pid ' + process.pid);
What platform you're running on. 'linux2'
, 'darwin'
, etc.
require('sys').puts('This platform is ' + process.platform);
Returns an object describing the memory usage of the Node process.
var sys = require('sys');
sys.puts(sys.inspect(process.memoryUsage()));
This will generate:
{ rss: 4935680
, vsize: 41893888
, heapTotal: 1826816
, heapUsed: 650472
}
heapTotal
and heapUsed
refer to V8's memory usage.
On the next loop around the event loop call this callback.
This is not a simple alias to setTimeout(fn, 0)
, it's much more
efficient.
var sys = require('sys');
process.nextTick(function () {
sys.puts('nextTick callback');
});
Sets or read the process's file mode creation mask. Child processes inherit
the mask from the parent process. Returns the old mask if mask
argument is
given, otherwise returns the current mask.
var sys = require('sys'),
oldmask, newmask = 0644;
oldmask = process.umask(newmask);
sys.puts('Changed umask from: ' + oldmask.toString(8) +
' to ' + newmask.toString(8));
These functions are in the module 'sys'
. Use require('sys')
to access
them.
Outputs string
and a trailing newline to stdout
.
require('sys').puts('String with a newline');
Like puts()
but without the trailing newline.
require('sys').print('String with no newline');
A synchronous output function. Will block the process and
output string
immediately to stderr
.
require('sys').debug('message on stderr');
Output with timestamp on stdout
.
require('sys').log('Timestmaped message.');
Return a string representation of object
, which is useful for debugging.
If showHidden
is true
, then the object's non-enumerable properties will be
shown too.
If depth
is provided, it tells inspect
how many times to recurse while
formatting the object. This is useful for inspecting large complicated objects.
The default is to only recurse twice. To make it recurse indefinitely, pass
in null
for depth
.
Example of inspecting all properties of the sys
object:
var sys = require('sys');
sys.puts(sys.inspect(sys, true, null));
To schedule execution of callback
after delay
milliseconds. Returns a
timeoutId
for possible use with clearTimeout()
.
Prevents a timeout from triggering.
To schedule the repeated execution of callback
every delay
milliseconds.
Returns a intervalId
for possible use with clearInterval()
.
Optionally, you can also pass arguments to the callback.
Stops a interval from triggering.
Node provides a tri-directional popen(3)
facility through the ChildProcess
class.
It is possible to stream data through the child's stdin
, stdout
, and
stderr
in a fully non-blocking way.
To create a child process use require('child_process').spawn()
.
Child processes always have three streams associated with them. child.stdin
,
child.stdout
, and child.stderr
.
ChildProcess
is an EventEmitter.
function (code, signal) {}
This event is emitted after the child process ends. If the process terminated
normally, code
is the final exit code of the process, otherwise null
. If
the process terminated due to receipt of a signal, signal
is the string name
of the signal, otherwise null
.
After this event is emitted, the 'output'
and 'error'
callbacks will no
longer be made.
See waitpid(2)
.
Launches a new process with the given command
, command line arguments, and
environment variables. If omitted, args
defaults to an empty Array, and env
defaults to process.env
.
Example of running ls -lh /usr
, capturing stdout
, stderr
, and the exit code:
var sys = require('sys'),
spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.addListener('data', function (data) {
sys.print('stdout: ' + data);
});
ls.stderr.addListener('data', function (data) {
sys.print('stderr: ' + data);
});
ls.addListener('exit', function (code) {
sys.puts('child process exited with code ' + code);
});
Example of checking for failed exec:
var sys = require('sys'),
spawn = require('child_process').spawn,
child = spawn('bad_command');
child.stderr.addListener('data', function (data) {
if (/^execvp\(\)/.test(data.asciiSlice(0,data.length))) {
sys.puts('Failed to start child process.');
}
});
See also: child_process.exec()
Send a signal to the child process. If no argument is given, the process will
be sent 'SIGTERM'
. See signal(7)
for a list of available signals.
var sys = require('sys'),
spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
grep.addListener('exit', function (code, signal) {
sys.puts('child process terminated due to receipt of signal '+signal);
});
// send SIGHUP to process
grep.kill('SIGHUP');
Note that while the function is called kill
, the signal delivered to the child
process may not actually kill it. kill
really just sends a signal to a process.
See kill(2)
The PID of the child process.
Example:
var sys = require('sys'),
spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
sys.puts('Spawned child pid: ' + grep.pid);
grep.stdin.end();
Write data to the child process's stdin
. The second argument is optional and
specifies the encoding: possible values are 'utf8'
, 'ascii'
, and
'binary'
.
Example: A very elaborate way to run 'ps ax | grep ssh'
var sys = require('sys'),
spawn = require('child_process').spawn,
ps = spawn('ps', ['ax']),
grep = spawn('grep', ['ssh']);
ps.stdout.addListener('data', function (data) {
grep.stdin.write(data);
});
ps.stderr.addListener('data', function (data) {
sys.print('ps stderr: ' + data);
});
ps.addListener('exit', function (code) {
if (code !== 0) {
sys.puts('ps process exited with code ' + code);
}
grep.stdin.end();
});
grep.stdout.addListener('data', function (data) {
sys.print(data);
});
grep.stderr.addListener('data', function (data) {
sys.print('grep stderr: ' + data);
});
grep.addListener('exit', function (code) {
if (code !== 0) {
sys.puts('grep process exited with code ' + code);
}
});
Closes the child process's stdin
stream. This often causes the child process to terminate.
Example:
var sys = require('sys'),
spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
grep.addListener('exit', function (code) {
sys.puts('child process exited with code ' + code);
});
grep.stdin.end();
High-level way to execute a command as a child process, buffer the output, and return it all in a callback.
var sys = require('sys'),
exec = require('child_process').exec,
child;
child = exec('cat *.js bad_file | wc -l',
function (error, stdout, stderr) {
sys.print('stdout: ' + stdout);
sys.print('stderr: ' + stderr);
if (error !== null) {
sys.puts('exec error: ' + error);
}
});
The callback gets the arguments (error, stdout, stderr)
. On success, error
will be null
. On error, error
will be an instance of Error
and err.code
will be the exit code of the child process, and err.signal
will be set to the
signal that terminated the process.
There is a second optional argument to specify several options. The default options are
{ encoding: 'utf8'
, timeout: 0
, maxBuffer: 200*1024
, killSignal: 'SIGKILL'
}
If timeout
is greater than 0, then it will kill the child process
if it runs longer than timeout
milliseconds. The child process is killed with
killSignal
(default: 'SIGKILL'
). maxBuffer
specifies the largest
amount of data allowed on stdout or stderr - if this value is exceeded then
the child process is killed.
Script
class compiles and runs JavaScript code. You can access this class with:
var Script = process.binding('evals').Script;
New JavaScript code can be compiled and run immediately or compiled, saved, and run later.
Similar to process.compile
. Script.runInThisContext
compiles code
as if it were loaded from filename
,
runs it and returns the result. Running code does not have access to local scope. filename
is optional.
Example of using Script.runInThisContext
and eval
to run the same code:
var sys = require('sys'),
localVar = 123,
usingscript, evaled,
Script = process.binding('evals').Script;
usingscript = Script.runInThisContext('localVar = 1;',
'myfile.js');
sys.puts('localVar: ' + localVar + ', usingscript: ' +
usingscript);
evaled = eval('localVar = 1;');
sys.puts('localVar: ' + localVar + ', evaled: ' +
evaled);
// localVar: 123, usingscript: 1
// localVar: 1, evaled: 1
Script.runInThisContext
does not have access to the local scope, so localVar
is unchanged.
eval
does have access to the local scope, so localVar
is changed.
In case of syntax error in code
, Script.runInThisContext
emits the syntax error to stderr
and throws.an exception.
Script.runInNewContext
compiles code
to run in sandbox
as if it were loaded from filename
,
then runs it and returns the result. Running code does not have access to local scope and
the object sandbox
will be used as the global object for code
.
sandbox
and filename
are optional.
Example: compile and execute code that increments a global variable and sets a new one. These globals are contained in the sandbox.
var sys = require('sys'),
Script = process.binding('evals').Script,
sandbox = {
animal: 'cat',
count: 2
};
Script.runInNewContext(
'count += 1; name = "kitty"', sandbox, 'myfile.js');
sys.puts(sys.inspect(sandbox));
// { animal: 'cat', count: 3, name: 'kitty' }
Note that running untrusted code is a tricky business requiring great care. To prevent accidental
global variable leakage, Script.runInNewContext
is quite useful, but safely running untrusted code
requires a separate process.
In case of syntax error in code
, Script.runInThisContext
emits the syntax error to stderr
and throws an exception.
new Script
compiles code
as if it were loaded from filename
,
but does not run it. Instead, it returns a Script
object representing this compiled code.
This script can be run later many times using methods below.
The returned script is not bound to any global object.
It is bound before each run, just for that run. filename
is optional.
In case of syntax error in code
, new Script
emits the syntax error to stderr
and throws an exception.
Similar to Script.runInThisContext
(note capital 'S'), but now being a method of a precompiled Script object.
script.runInThisContext
runs the code of script
and returns the result.
Running code does not have access to local scope, but does have access to the global
object
(v8: in actual context).
Example of using script.runInThisContext
to compile code once and run it multiple times:
var sys = require('sys'),
Script = process.binding('evals').Script,
scriptObj, i;
globalVar = 0;
scriptObj = new Script('globalVar += 1', 'myfile.js');
for (i = 0; i < 1000 ; i += 1) {
scriptObj.runInThisContext();
}
sys.puts(globalVar);
// 1000
Similar to Script.runInNewContext
(note capital 'S'), but now being a method of a precompiled Script object.
script.runInNewContext
runs the code of script
with sandbox
as the global object and returns the result.
Running code does not have access to local scope. sandbox
is optional.
Example: compile code that increments a global variable and sets one, then execute this code multiple times. These globals are contained in the sandbox.
var sys = require('sys'),
Script = process.binding('evals').Script,
scriptObj, i,
sandbox = {
animal: 'cat',
count: 2
};
scriptObj = new Script(
'count += 1; name = "kitty"', 'myfile.js');
for (i = 0; i < 10 ; i += 1) {
scriptObj.runInNewContext(sandbox);
}
sys.puts(sys.inspect(sandbox));
// { animal: 'cat', count: 12, name: 'kitty' }
Note that running untrusted code is a tricky business requiring great care. To prevent accidental
global variable leakage, script.runInNewContext
is quite useful, but safely running untrusted code
requires a separate process.
File I/O is provided by simple wrappers around standard POSIX functions. To
use this module do require('fs')
. All the methods have asynchronous and
synchronous forms.
The asynchronous form always take a completion callback as its last argument.
The arguments passed to the completion callback depend on the method, but the
first argument is always reserved for an exception. If the operation was
completed successfully, then the first argument will be null
or undefined
.
Here is an example of the asynchronous version:
var fs = require('fs'),
sys = require('sys');
fs.unlink('/tmp/hello', function (err) {
if (err) throw err;
sys.puts('successfully deleted /tmp/hello');
});
Here is the synchronous version:
var fs = require('fs'),
sys = require('sys');
fs.unlinkSync('/tmp/hello')
sys.puts('successfully deleted /tmp/hello');
With the asynchronous methods there is no guaranteed ordering. So the following is prone to error:
fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
sys.puts('renamed complete');
});
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
sys.puts('stats: ' + JSON.stringify(stats));
});
It could be that fs.stat
is executed before fs.rename
.
The correct way to do this is to chain the callbacks.
fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
sys.puts('stats: ' + JSON.stringify(stats));
});
});
In busy processes, the programmer is strongly encouraged to use the asynchronous versions of these calls. The synchronous versions will block the entire process until they complete--halting all connections.
Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.
Synchronous rename(2).
Asynchronous ftruncate(2). No arguments other than a possible exception are given to the completion callback.
Synchronous ftruncate(2).
Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback.
Synchronous chmod(2).
Asynchronous stat(2), lstat(2) or fstat(2). The callback gets two arguments (err, stats)
where stats
is a fs.Stats
object. It looks like this:
{ dev: 2049
, ino: 305352
, mode: 16877
, nlink: 12
, uid: 1000
, gid: 1000
, rdev: 0
, size: 4096
, blksize: 4096
, blocks: 8
, atime: '2009-06-29T11:11:55Z'
, mtime: '2009-06-29T11:11:40Z'
, ctime: '2009-06-29T11:11:40Z'
}
See the fs.Stats
section below for more information.
Synchronous stat(2), lstat(2) or fstat(2). Returns an instance of fs.Stats
.
Asynchronous link(2). No arguments other than a possible exception are given to the completion callback.
Synchronous link(2).
Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback.
Synchronous symlink(2).
Asynchronous readlink(2). The callback gets two arguments (err, resolvedPath)
.
Synchronous readlink(2). Returns the resolved path.
Asynchronous realpath(2). The callback gets two arguments (err, resolvedPath)
.
Synchronous realpath(2). Returns the resolved path.
Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback.
Synchronous unlink(2).
Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.
Synchronous rmdir(2).
Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback.
Synchronous mkdir(2).
Asynchronous readdir(3). Reads the contents of a directory.
The callback gets two arguments (err, files)
where files
is an array of
the names of the files in the directory excluding '.'
and '..'
.
Synchronous readdir(3). Returns an array of filenames excluding '.'
and
'..'
.
Asynchronous close(2). No arguments other than a possible exception are given to the completion callback.
Synchronous close(2).
Asynchronous file open. See open(2). Flags can be 'r', 'r+', 'w', 'w+', 'a',
or 'a+'. The callback gets two arguments (err, fd)
.
Synchronous open(2).
Write buffer
to the file specified by fd
.
offset
and length
determine the part of the buffer to be written.
position
refers to the offset from the beginning of the file where this data
should be written. If position
is null
, the data will be written at the
current position.
See pwrite(2).
The callback will be given two arguments (err, written)
where written
specifies how many bytes were written.
Synchronous version of fs.write()
. Returns the number of bytes written.
Read data from the file specified by fd
.
buffer
is the buffer that the data will be written to.
offset
is offset within the buffer where writing will start.
length
is an integer specifying the number of bytes to read.
position
is an integer specifying where to begin reading from in the file.
If position
is null
, data will be read from the current file position.
The callback is given the two arguments, (err, bytesRead)
.
Synchronous version of fs.read
. Returns the number of bytesRead
.
Asynchronously reads the entire contents of a file. Example:
fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
sys.puts(data);
});
The callback is passed two arguments (err, data)
, where data
is the
contents of the file.
If no encoding is specified, then the raw buffer is returned.
Synchronous version of fs.readFile
. Returns the contents of the filename
.
If encoding
is specified then this function returns a string. Otherwise it
returns a buffer.
Asynchronously writes data to a file. Example:
fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
sys.puts('It\'s saved!');
});
The synchronous version of fs.writeFile
.
Watch for changes on filename
. The callback listener
will be called each
time the file changes.
The second argument is optional. The options
if provided should be an object
containing two members a boolean, persistent
, and interval
, a polling
value in milliseconds. The default is {persistent: true, interval: 0}
.
The listener
gets two arguments the current stat object and the previous
stat object:
fs.watchFile(f, function (curr, prev) {
sys.puts('the current mtime is: ' + curr.mtime);
sys.puts('the previous mtime was: ' + prev.mtime);
});
These stat objects are instances of fs.Stat
.
Stop watching for changes on filename
.
Objects returned from fs.stat()
and fs.lstat()
are of this type.
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink()
(only valid with fs.lstat()
)stats.isFIFO()
stats.isSocket()
ReadStream
is a readable stream.
Returns a new ReadStream object.
options
is an object with the following defaults:
{ 'flags': 'r'
, 'encoding': 'binary'
, 'mode': 0666
, 'bufferSize': 4 * 1024
}
A boolean that is true
by default, but turns false
after an 'error'
occured, the stream came to an 'end'
, or destroy()
was called.
Stops the stream from reading further data. No 'data'
event will be fired
until the stream is resumed.
Resumes the stream. Together with pause()
this useful to throttle reading.
Allows to close the stream before the 'end'
is reached. No more events other
than 'close'
will be fired after this method has been called.
WriteStream
is a writable stream.
Returns a new WriteStream object.
options
is an object with the following defaults:
{ 'flags': 'w'
, 'encoding': 'binary'
, 'mode': 0666
}
A boolean that is true
by default, but turns false
after an 'error'
occurred or end()
/ destroy()
was called.
Returns true
if the data was flushed to the kernel, and false
if it was
queued up for being written later. A 'drain'
will fire after all queued data
has been written.
The second optional parameter specifies the encoding of for the string.
Closes the stream right after all queued write()
calls have finished.
Allows to close the stream regardless of its current state.
To use the HTTP server and client one must require('http')
.
The HTTP interfaces in Node are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses--the user is able to stream data.
HTTP message headers are represented by an object like this:
{ 'content-length': '123'
, 'content-type': 'text/plain'
, 'stream': 'keep-alive'
, 'accept': '*/*'
}
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, Node's HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.
HTTPS is supported if OpenSSL is available on the underlying platform.
This is an EventEmitter with the following events:
function (request, response) { }
request
is an instance of http.ServerRequest
and response
is
an instance of http.ServerResponse
function (stream) { }
When a new TCP stream is established. stream
is an object of type
net.Stream
. Usually users will not want to access this event. The
stream
can also be accessed at request.connection
.
function (errno) { }
Emitted when the server closes.
Returns a new web server object.
The options
argument is optional. The
options
argument accepts the same values as the
options argument for net.Server
.
The requestListener
is a function which is automatically
added to the 'request'
event.
function (request, response) {}
Emitted each time there is request. Note that there may be multiple requests per connection (in the case of keep-alive connections).
function (request, socket, head)
Emitted each time a client requests a http upgrade. If this event isn't listened for, then clients requesting an upgrade will have their connections closed.
request
is the arguments for the http request, as it is in the request event.socket
is the network socket between the server and client.head
is an instance of Buffer, the first packet of the upgraded stream, this may be empty.After this event is emitted, the request's socket will not have a data
event listener, meaning you will need to bind to it in order to handle data
sent to the server on that socket.
function (exception) {}
If a client connection emits an 'error' event - it will forwarded here.
Begin accepting connections on the specified port and hostname. If the
hostname is omitted, the server will accept connections directed to any
IPv4 address (INADDR_ANY
).
To listen to a unix socket, supply a filename instead of port and hostname.
This function is asynchronous. The last parameter callback
will be called
when the server has been bound to the port.
Start a UNIX socket server listening for connections on the given path
.
This function is asynchronous. The last parameter callback
will be called
when the server has been bound.
Enables HTTPS support for the server, with the crypto module credentials specifying the private key and certificate of the server, and optionally the CA certificates for use in client authentication.
If the credentials hold one or more CA certificates, then the server will request for the client to submit a client certificate as part of the HTTPS connection handshake. The validity and content of this can be accessed via verifyPeer() and getPeerCertificate() from the server's request.connection.
Stops the server from accepting new connections.
This object is created internally by a HTTP server--not by
the user--and passed as the first argument to a 'request'
listener.
This is an EventEmitter with the following events:
function (chunk) { }
Emitted when a piece of the message body is received.
Example: A chunk of the body is given as the single
argument. The transfer-encoding has been decoded. The
body chunk is a string. The body encoding is set with
request.setBodyEncoding()
.
function () { }
Emitted exactly once for each message. No arguments. After emitted no other events will be emitted on the request.
The request method as a string. Read only. Example:
'GET'
, 'DELETE'
.
Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:
GET /status?name=ryan HTTP/1.1\r\n
Accept: text/plain\r\n
\r\n
Then request.url
will be:
'/status?name=ryan'
If you would like to parse the URL into its parts, you can use
require('url').parse(request.url)
. Example:
node> require('url').parse('/status?name=ryan')
{ href: '/status?name=ryan'
, search: '?name=ryan'
, query: 'name=ryan'
, pathname: '/status'
}
If you would like to extract the params from the query string,
you can use the require('querystring').parse
function, or pass
true
as the second argument to require('url').parse
. Example:
node> require('url').parse('/status?name=ryan', true)
{ href: '/status?name=ryan'
, search: '?name=ryan'
, query: { name: 'ryan' }
, pathname: '/status'
}
Read only.
The HTTP protocol version as a string. Read only. Examples:
'1.1'
, '1.0'
.
Also request.httpVersionMajor
is the first integer and
request.httpVersionMinor
is the second.
Set the encoding for the request body. Either 'utf8'
or 'binary'
. Defaults
to 'binary'
.
Pauses request from emitting events. Useful to throttle back an upload.
Resumes a paused request.
The net.Stream
object assocated with the connection.
With HTTPS support, use request.connection.verifyPeer() and request.connection.getPeerCertificate() to obtain the client's authentication details.
This object is created internally by a HTTP server--not by the user. It is
passed as the second parameter to the 'request'
event. It is a writable stream.
Sends a response header to the request. The status code is a 3-digit HTTP
status code, like 404
. The last argument, headers
, are the response headers.
Optionally one can give a human-readable reasonPhrase
as the second
argument.
Example:
var body = 'hello world';
response.writeHead(200, {
'Content-Length': body.length,
'Content-Type': 'text/plain'
});
This method must only be called once on a message and it must
be called before response.end()
is called.
This method must be called after writeHead
was
called. It sends a chunk of the response body. This method may
be called multiple times to provide successive parts of the body.
If chunk
is a string, the second parameter
specifies how to encode it into a byte stream. By default the
encoding
is 'ascii'
.
Note: This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may be used.
The first time response.write()
is called, it will send the buffered
header information and the first body to the client. The second time
response.write()
is called, Node assumes you're going to be streaming
data, and sends that separately. That is, the response is buffered up to the
first chunk of body.
This method signals to the server that all of the response headers and body
has been sent; that server should consider this message complete.
The method, response.end()
, MUST be called on each
response.
An HTTP client is constructed with a server address as its argument, the returned handle is then used to issue one or more requests. Depending on the server connected to, the client might pipeline the requests or reestablish the stream after each stream. Currently the implementation does not pipeline requests.
Example of connecting to google.com
:
var sys = require('sys'),
http = require('http');
var google = http.createClient(80, 'www.google.com');
var request = google.request('GET', '/',
{'host': 'www.google.com'});
request.end();
request.addListener('response', function (response) {
sys.puts('STATUS: ' + response.statusCode);
sys.puts('HEADERS: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.addListener('data', function (chunk) {
sys.puts('BODY: ' + chunk);
});
});
Constructs a new HTTP client. port
and
host
refer to the server to be connected to. A
stream is not established until a request is issued.
secure
is an optional boolean flag to enable https support and credentials
is an optional credentials object from the crypto module, which may hold the client's private key, certificate, and a list of trusted CA certificates.
If the connection is secure, but no explicit CA certificates are passed in the credentials, then node.js will default to the publicly trusted list of CA certificates, as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt
Issues a request; if necessary establishes stream. Returns a http.ClientRequest
instance.
method
is optional and defaults to 'GET' if omitted.
request_headers
is optional.
Additional request headers might be added internally
by Node. Returns a ClientRequest
object.
Do remember to include the Content-Length
header if you
plan on sending a body. If you plan on streaming the body, perhaps
set Transfer-Encoding: chunked
.
NOTE: the request is not complete. This method only sends the header of
the request. One needs to call request.end()
to finalize the request and
retrieve the response. (This sounds convoluted but it provides a chance for
the user to stream a body to the server with request.write()
.)
Returns true or false depending on the validity of the server's certificate in the context of the defined or default list of trusted CA certificates.
Returns a JSON structure detailing the server's certificate, containing a dictionary with keys for the certificate 'subject', 'issuer', 'valid_from' and 'valid_to'
This object is created internally and returned from the request()
method
of a http.Client
. It represents an in-progress request whose header has
already been sent.
To get the response, add a listener for 'response'
to the request object.
'response'
will be emitted from the request object when the response
headers have been received. The 'response'
event is executed with one
argument which is an instance of http.ClientResponse
.
During the 'response'
event, one can add listeners to the
response object; particularly to listen for the 'data'
event. Note that
the 'response'
event is called before any part of the response body is received,
so there is no need to worry about racing to catch the first part of the
body. As long as a listener for 'data'
is added during the 'response'
event, the entire body will be caught.
// Good
request.addListener('response', function (response) {
response.addListener('data', function (chunk) {
sys.puts('BODY: ' + chunk);
});
});
// Bad - misses all or part of the body
request.addListener('response', function (response) {
setTimeout(function () {
response.addListener('data', function (chunk) {
sys.puts('BODY: ' + chunk);
});
}, 10);
});
This is a writable stream.
This is an EventEmitter
with the following events:
function (response) { }
Emitted when a response is received to this request. This event is emitted only once. The
response
argument will be an instance of http.ClientResponse
.
Sends a chunk of the body. By calling this method
many times, the user can stream a request body to a
server--in that case it is suggested to use the
['Transfer-Encoding', 'chunked']
header line when
creating the request.
The chunk
argument should be an array of integers
or a string.
The encoding
argument is optional and only
applies when chunk
is a string. The encoding
argument should be either 'utf8'
or
'ascii'
. By default the body uses ASCII encoding,
as it is faster.
Finishes sending the request. If any parts of the body are
unsent, it will flush them to the stream. If the request is
chunked, this will send the terminating '0\r\n\r\n'
.
This object is created when making a request with http.Client
. It is
passed to the 'response'
event of the request object.
The response implements the readable stream interface.
function (chunk) {}
Emitted when a piece of the message body is received.
Example: A chunk of the body is given as the single
argument. The transfer-encoding has been decoded. The
body chunk a String. The body encoding is set with
`response.setBodyEncoding()`.
function () {}
Emitted exactly once for each message. No arguments. After emitted no other events will be emitted on the response.
The 3-digit HTTP response status code. E.G. 404
.
The HTTP version of the connected-to server. Probably either
'1.1'
or '1.0'
.
Also response.httpVersionMajor
is the first integer and
response.httpVersionMinor
is the second.
The response headers.
Set the encoding for the response body. Either 'utf8'
or 'binary'
.
Defaults to 'binary'
.
Pauses response from emitting events. Useful to throttle back a download.
Resumes a paused response.
A reference to the http.Client
that this response belongs to.
This class is used to create a TCP or UNIX server.
Here is an example of a echo server which listens for connections on port 8124:
var net = require('net');
var server = net.createServer(function (stream) {
stream.setEncoding('utf8');
stream.addListener('connect', function () {
stream.write('hello\r\n');
});
stream.addListener('data', function (data) {
stream.write(data);
});
stream.addListener('end', function () {
stream.write('goodbye\r\n');
stream.end();
});
});
server.listen(8124, 'localhost');
To listen on the socket '/tmp/echo.sock'
, the last line would just be
changed to
server.listen('/tmp/echo.sock');
This is an EventEmitter with the following events:
function (stream) {}
Emitted when a new connection is made. stream
is an instance of
net.Stream
.
function () {}
Emitted when the server closes.
Creates a new TCP server. The connection_listener
argument is
automatically set as a listener for the 'connection'
event.
Begin accepting connections on the specified port
and host
. If the
host
is omitted, the server will accept connections directed to any
IPv4 address (INADDR_ANY
).
This function is asynchronous. The last parameter callback
will be called
when the server has been bound.
Start a UNIX socket server listening for connections on the given path
.
This function is asynchronous. The last parameter callback
will be called
when the server has been bound.
Stops the server from accepting new connections. This function is
asynchronous, the server is finally closed when the server emits a 'close'
event.
This object is an abstraction of of a TCP or UNIX socket. net.Stream
instance implement a duplex stream interface. They can be created by the
user and used as a client (with connect()
) or they can be created by Node
and passed to the user through the 'connection'
event of a server.
net.Stream
instances are an EventEmitters with the following events:
function () { }
Emitted when a stream connection successfully is established.
See connect()
.
function () { }
Emitted when a stream connection successfully establishes a HTTPS handshake with its peer.
function (data) { }
Emitted when data is received. The argument data
will be a Buffer
or
String
. Encoding of data is set by stream.setEncoding()
.
(See the section on Readable Streams for more infromation.)
function () { }
Emitted when the other end of the stream sends a FIN packet. After this is
emitted the readyState
will be 'writeOnly'
. One should probably just
call stream.end()
when this event is emitted.
function () { }
Emitted if the stream times out from inactivity. This is only to notify that the stream has been idle. The user must manually close the connection.
See also: stream.setTimeout()
function () { }
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
function (exception) { }
Emitted when an error occurs. The 'close'
event will be called directly
following this event.
function () { }
Emitted once the stream is fully closed. The argument had_error
is a boolean which says if
the stream was closed due to a transmission
error.
Construct a new stream object and opens a stream to the specified port
and host
. If the second parameter is omitted, localhost is assumed.
When the stream is established the 'connect'
event will be emitted.
Opens a stream to the specified port
and host
. createConnection()
also opens a stream; normally this method is not needed. Use this only if
a stream is closed and you want to reuse the object to connect to another
server.
This function is asynchronous. When the 'connect'
event is emitted the
stream is established. If there is a problem connecting, the 'connect'
event will not be emitted, the 'error'
event will be emitted with
the exception.
The string representation of the remote IP address. For example,
'<IP_ADDRESS>'
or '2001:4860:a005::68'
.
This member is only present in server-side connections.
Either 'closed'
, 'open'
, 'opening'
, 'readOnly'
, or 'writeOnly'
.
Sets the encoding (either 'ascii'
, 'utf8'
, or 'binary'
) for data that is
received.
Enables HTTPS support for the stream, with the crypto module credentials specifying the private key and certificate of the stream, and optionally the CA certificates for use in peer authentication.
If the credentials hold one ore more CA certificates, then the stream will request for the peer to submit a client certificate as part of the HTTPS connection handshake. The validity and content of this can be accessed via verifyPeer() and getPeerCertificate().
Returns true or false depending on the validity of the peers's certificate in the context of the defined or default list of trusted CA certificates.
Returns a JSON structure detailing the peer's certificate, containing a dictionary with keys for the certificate 'subject', 'issuer', 'valid_from' and 'valid_to'
Sends data on the stream. The second parameter specifies the encoding in the case of a string--it defaults to ASCII because encoding to UTF8 is rather slow.
Returns true
if the entire data was flushed successfully to the kernel
buffer. Returns false
if all or part of the data was queued in user memory.
'drain'
will be emitted when the buffer is again free.
Half-closes the stream. I.E., it sends a FIN packet. It is possible the
server will still send some data. After calling this readyState
will be
'readOnly'
.
Ensures that no more I/O activity happens on this stream. Only necessary in case of errors (parse error or so).
Pauses the reading of data. That is, 'data'
events will not be emitted.
Useful to throttle back an upload.
Resumes reading after a call to pause()
.
Sets the stream to timeout after timeout
milliseconds of inactivity on
the stream. By default net.Stream
do not have a timeout.
When an idle timeout is triggered the stream will receive a 'timeout'
event but the connection will not be severed. The user must manually end()
or destroy()
the stream.
If timeout
is 0, then the existing idle timeout is disabled.
Disables the Nagle algorithm. By default TCP connections use the Nagle
algorithm, they buffer data before sending it off. Setting noDelay
will
immediately fire off data each time stream.write()
is called.
Enable/disable keep-alive functionality, and optionally set the initial
delay before the first keepalive probe is sent on an idle stream.
Set initialDelay
(in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting 0 for
initialDelay will leave the value unchanged from the default
(or previous) setting.
Use require('crypto')
to access this module.
The crypto module requires OpenSSL to be available on the underlying platform. It offers a way of encapsulating secure credentials to be used as part of a secure HTTPS net or http connection.
It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.
Creates a credentials object, with the optional details being a dictionary with keys:
key
: a string holding the PEM encoded private key
cert
: a string holding the PEM encoded certificate
ca
: either a string or list of strings of PEM encoded CA certificates to trust.
If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt
Creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generate hash digests.
algorithm
is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are sha1, md5, sha256, sha512, etc. On recent releases, openssl list-message-digest-algorithms
will display the available digest algorithms.
Updates the hash content with the given data
. This can be called many times with new data as it is streamed.
Calculates the digest of all of the passed data to be hashed. The encoding
can be 'hex', 'binary' or 'base64'.
Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.
algorithm
is dependent on the available algorithms supported by OpenSSL - see createHash above.
key
is the hmac key to be used.
Update the hmac content with the given data
. This can be called many times with new data as it is streamed.
Calculates the digest of all of the passed data to the hmac. The encoding
can be 'hex', 'binary' or 'base64'.
Creates and returns a cipher object, with the given algorithm and key.
algorithm
is dependent on OpenSSL, examples are aes192, etc. On recent releases, openssl list-cipher-algorithms
will display the available cipher algorithms.
Updates the cipher with data
, the encoding of which is given in input_encoding
and can be 'utf8', 'ascii' or 'binary'. The output_encoding
specifies the output format of the enciphered data, and can be 'binary', 'base64' or 'hex'.
Returns the enciphered contents, and can be called many times with new data as it is streamed.
Returns any remaining enciphered contents, with output_encoding
as update above.
Creates and returns a decipher object, with the given algorithm and key. This is the mirror of the cipher object above.
Updates the decipher with data
, which is encoded in 'binary', 'base64' or 'hex'. The output_decoding
specifies in what format to return the deciphered plaintext - either 'binary', 'ascii' or 'utf8'.
Returns any remaining plaintext which is deciphered, with `output_encoding' as update above.
Creates and returns a signing object, with the given algorithm. On recent OpenSSL releases, openssl list-public-key-algorithms
will display the available signing algorithms. Examples are 'RSA-SHA256'.
Updates the signer object with data. This can be called many times with new data as it is streamed.
Calculates the signature on all the updated data passed through the signer. private_key
is a string containing the PEM encoded private key for signing.
Returns the signature in output_format
which can be 'binary', 'hex' or 'base64'
Creates and returns a verification object, with the given algorithm. This is the mirror of the signing object above.
Updates the verifyer object with data. This can be called many times with new data as it is streamed.
Verifies the signed data by using the public_key
which is a string containing the PEM encoded public key, and signature
, which is the previously calculates signature for the data, in the signature_format
which can be 'binary', 'hex' or 'base64'.
Returns true or false depending on the validity of the signature for the data and public key.
Use require('dns')
to access this module.
Here is an example which resolves 'www.google.com'
then reverse
resolves the IP addresses which are returned.
var dns = require('dns'),
sys = require('sys');
dns.resolve4('www.google.com', function (err, addresses) {
if (err) throw err;
sys.puts('addresses: ' + JSON.stringify(addresses));
for (var i = 0; i < addresses.length; i++) {
var a = addresses[i];
dns.reverse(a, function (err, domains) {
if (err) {
sys.puts('reverse for ' + a + ' failed: ' +
err.message);
} else {
sys.puts('reverse for ' + a + ': ' +
JSON.stringify(domains));
}
});
}
});
Resolves a domain (e.g. 'google.com'
) into an array of the record types
specified by rrtype. Valid rrtypes are A
(IPV4 addresses), AAAA
(IPV6
addresses), MX
(mail exchange records), TXT
(text records), SRV
(SRV
records), and PTR
(used for reverse IP lookups).
The callback has arguments (err, addresses)
. The type of each item
in addresses
is determined by the record type, and described in the
documentation for the corresponding lookup methods below.
On error, err
would be an instanceof Error
object, where err.errno
is
one of the error codes listed below and err.message
is a string describing
the error in English.
The same as dns.resolve()
, but only for IPv4 queries (A
records).
addresses
is an array of IPv4 addresses (e.g.
['<IP_ADDRESS>', '<IP_ADDRESS>', '<IP_ADDRESS>']
).
The same as dns.resolve4()
except for IPv6 queries (an AAAA
query).
The same as dns.resolve()
, but only for mail exchange queries (MX
records).
addresses
is an array of MX records, each with a priority and an exchange
attribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]
).
The same as dns.resolve()
, but only for text queries (TXT
records).
addresses
is an array of the text records available for domain
(e.g.,
['v=spf1 ip4:<IP_ADDRESS> ~all']
).
The same as dns.resolve()
, but only for service records (SRV
records).
addresses
is an array of the SRV records available for domain
. Properties
of SRV records are priority, weight, port, and name (e.g.,
[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]
).
Reverse resolves an ip address to an array of domain names.
The callback has arguments (err, domains)
.
If there an an error, err
will be non-null and an instanceof the Error
object.
Each DNS query can return an error code.
dns.TEMPFAIL
: timeout, SERVFAIL or similar.dns.PROTOCOL
: got garbled reply.dns.NXDOMAIN
: domain does not exists.dns.NODATA
: domain exists but no data of reqd type.dns.NOMEM
: out of memory while processing.dns.BADQUERY
: the query is malformed.This module is used for writing unit tests for your applications, you can
access it with require('assert')
.
Tests if actual
is equal to expected
using the operator provided.
Tests if value is a true
value, it is equivalent to assert.equal(true, value, message);
Tests shallow, coercive equality with the equal comparison operator ( ==
).
Tests shallow, coercive non-equality with the not equal comparison operator ( !=
).
Tests for deep equality.
Tests for any deep inequality.
Tests strict equality, as determined by the strict equality operator ( ===
)
Tests strict non-equality, as determined by the strict not equal operator ( !==
)
Expects block
to throw an error.
Expects block
not to throw an error.
Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error
in callbacks.
This module contains utilities for dealing with file paths. Use
require('path')
to use it. It provides the following methods:
Join all arguments together and resolve the resulting path. Example:
node> require('path').join(
... '/foo', 'bar', 'baz/asdf', 'quux', '..')
'/foo/bar/baz/asdf'
Normalize an array of path parts, taking care of '..'
and '.'
parts. Example:
path.normalizeArray(['',
'foo', 'bar', 'baz', 'asdf', 'quux', '..'])
// returns
[ '', 'foo', 'bar', 'baz', 'asdf' ]
Normalize a string path, taking care of '..'
and '.'
parts. Example:
path.normalize('/foo/bar/baz/asdf/quux/..')
// returns
'/foo/bar/baz/asdf'
Return the directory name of a path. Similar to the Unix dirname
command. Example:
path.dirname('/foo/bar/baz/asdf/quux')
// returns
'/foo/bar/baz/asdf'
Return the last portion of a path. Similar to the Unix basename
command. Example:
path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'
path.basename('/foo/bar/baz/asdf/quux.html', '.html')
// returns
'quux'
Return the extension of the path. Everything after the last '.' in the last portion of the path. If there is no '.' in the last portion of the path or the only '.' is the first character, then it returns an empty string. Examples:
path.extname('index.html')
// returns
'.html'
path.extname('index')
// returns
''
Test whether or not the given path exists. Then, call the callback
argument with either true or false. Example:
path.exists('/etc/passwd', function (exists) {
sys.debug(exists ? "it's there" : "no passwd!");
});
This module has utilities for URL resolution and parsing.
Call require('url')
to use it.
Parsed URL objects have some or all of the following fields, depending on whether or not they exist in the URL string. Any parts that are not in the URL string will not be in the parsed object. Examples are shown for the URL
'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
href
The full URL that was originally parsed. Example:
'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
protocol
The request protocol. Example: 'http:'
host
The full host portion of the URL, including port and authentication information. Example:
'user:pass@host.com:8080'
auth
The authentication information portion of a URL. Example: 'user:pass'
hostname
Just the hostname portion of the host. Example: 'host.com'
port
The port number portion of the host. Example: '8080'
pathname
The path section of the URL, that comes after the host and before the query, including the initial slash if present. Example: '/p/a/t/h'
search
The 'query string' portion of the URL, including the leading question mark. Example: '?query=string'
query
Either the 'params' portion of the query string, or a querystring-parsed object. Example:
'query=string'
or {'query':'string'}
hash
The 'fragment' portion of the URL including the pound-sign. Example: '#hash'
The following methods are provided by the URL module:
Take a URL string, and return an object. Pass true
as the second argument to also parse
the query string using the querystring
module.
Take a parsed URL object, and return a formatted URL string.
Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.
This module provides utilities for dealing with query strings. It provides the following methods:
Serialize an object to a query string. Optionally override the default separator and assignment characters. Example:
querystring.stringify({foo: 'bar'})
// returns
'foo=bar'
querystring.stringify({foo: 'bar', baz: 'bob'}, ';', ':')
// returns
'foo:bar;baz:bob'
By default, this function will perform PHP/Rails-style parameter mungeing for arrays and objects used as
values within obj
.
Example:
querystring.stringify({foo: 'bar', foo: 'baz', foo: 'boz'})
// returns
'foo[]=bar&foo[]=baz&foo[]=boz'
querystring.stringify({foo: {bar: 'baz'}})
// returns
'foo[bar]=baz'
If you wish to disable the array mungeing (e.g. when generating parameters for a Java servlet), you
can set the munge
argument to false
.
Example:
querystring.stringify({foo: 'bar', foo: 'baz', foo: 'boz'}, '&', '=', false)
// returns
'foo=bar&foo=baz&foo=boz'
Note that when munge
is false
, parameter names with object values will still be munged.
Deserialize a query string to an object. Optionally override the default separator and assignment characters.
querystring.parse('a=b&b=c')
// returns
{ 'a': 'b'
, 'b': 'c'
}
This function can parse both munged and unmunged query strings (see stringify
for details).
The escape function used by querystring.stringify
, provided so that it could be overridden if necessary.
The unescape function used by querystring.parse
, provided so that it could be overridden if necessary.
A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easily includable in other programs. REPL provides a way to interactively run JavaScript and see the results. It can be used for debugging, testing, or just trying things out.
By executing node
without any arguments from the command-line you will be
dropped into the REPL. It has simplistic emacs line-editting.
mjr:~$ node
Type '.help' for options.
node> a = [ 1, 2, 3];
[ 1, 2, 3 ]
node> a.forEach(function (v) {
... sys.puts(v);
... });
1
2
3
For advanced line-editors, start node with the environmental variable NODE_NO_READLINE=1
.
This will start the REPL in canonical terminal settings which will allow you to use with rlwrap
.
For example, you could add this to your bashrc file:
alias node="env NODE_NO_READLINE=1 rlwrap node"
Starts a REPL with prompt
as the prompt and stream
for all I/O. prompt
is optional and defaults to node>
. stream
is optional and defaults to
process.openStdin()
.
Multiple REPLs may be started against the same running instance of node. Each will share the same global object but will have unique I/O.
Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
var sys = require("sys"),
net = require("net"),
repl = require("repl");
connections = 0;
repl.start("node via stdin> ");
net.createServer(function (socket) {
connections += 1;
repl.start("node via Unix socket> ", socket);
}).listen("/tmp/node-repl-sock");
net.createServer(function (socket) {
connections += 1;
repl.start("node via TCP socket> ", socket);
}).listen(5001);
Running this program from the command line will start a REPL on stdin. Other
REPL clients may connect through the Unix socket or TCP socket. telnet
is useful
for connecting to TCP sockets, and socat
can be used to connect to both Unix and
TCP sockets.
By starting a REPL from a Unix socket-based server instead of stdin, you can connect to a long-running node process without restarting it.
Inside the REPL, Control+D will exit. Multi-line expressions can be input.
The special variable _
(underscore) contains the result of the last expression.
node> [ "a", "b", "c" ]
[ 'a', 'b', 'c' ]
node> _.length
3
node> _ += 1
4
The REPL provides access to any variables in the global scope. You can expose a variable
to the REPL explicitly by assigning it to the scope
object associated with each
REPLServer
. For example:
// repl_test.js
var repl = require("repl"),
msg = "message";
repl.start().scope.m = msg;
Things in the scope
object appear as local within the REPL:
mjr:~$ node repl_test.js
node> m
'message'
There are a few special REPL commands:
.break
- While inputting a multi-line expression, sometimes you get lost or just don't care
about completing it. .break
will start over.
.clear
- Resets the scope
object to an empty object and clears any multi-line expression.
.exit
- Close the I/O stream, which will cause the REPL to exit.
.help
- Show this list of special commands.
Node uses the CommonJS module system.
Node has a simple module loading system. In Node, files and modules are in
one-to-one correspondence. As an example, foo.js
loads the module
circle.js
in the same directory.
The contents of foo.js
:
var circle = require('./circle'),
sys = require('sys');
sys.puts( 'The area of a circle of radius 4 is '
+ circle.area(4));
The contents of circle.js
:
var PI = 3.14;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
The module circle.js
has exported the functions area()
and
circumference()
. To export an object, add to the special exports
object. (Alternatively, one can use this
instead of exports
.) Variables
local to the module will be private. In this example the variable PI
is
private to circle.js
. The function puts()
comes from the module 'sys'
,
which is a built-in module. Modules which are not prefixed by './'
are
built-in module--more about this later.
A module prefixed with './'
is relative to the file calling require()
.
That is, circle.js
must be in the same directory as foo.js
for
require('./circle')
to find it.
Without the leading './'
, like require('assert')
the module is searched
for in the require.paths
array. require.paths
on my system looks like
this:
[ '/home/ryan/.node_libraries' ]
That is, when require('assert')
is called Node looks for:
/home/ryan/.node_libraries/assert.js
/home/ryan/.node_libraries/assert.node
/home/ryan/.node_libraries/assert/index.js
/home/ryan/.node_libraries/assert/index.node
interrupting once a file is found. Files ending in '.node'
are binary Addon
Modules; see 'Addons' below. 'index.js'
allows one to package a module as
a directory.
require.paths
can be modified at runtime by simply unshifting new
paths onto it, or at startup with the NODE_PATH
environmental
variable (which should be a list of paths, colon separated).
Addons are dynamically linked shared objects. They can provide glue to C and C++ libraries. The API (at the moment) is rather complex, involving knowledge of several libraries:
V8 JavaScript, a C++ library. Used for interfacing with JavaScript:
creating objects, calling functions, etc. Documented mostly in the
v8.h
header file (deps/v8/include/v8.h
in the Node source tree).
libev, C event loop library. Anytime one needs to wait for a file
descriptor to become readable, wait for a timer, or wait for a signal to
received one will need to interface with libev. That is, if you perform
any I/O, libev will need to be used. Node uses the EV_DEFAULT
event
loop. Documentation can be found http:/cvs.schmorp.de/libev/ev.html[here].
libeio, C thread pool library. Used to execute blocking POSIX system
calls asynchronously. Mostly wrappers already exist for such calls, in
src/file.cc
so you will probably not need to use it. If you do need it,
look at the header file deps/libeio/eio.h
.
Internal Node libraries. Most importantly is the node::ObjectWrap
class which you will likely want to derive from.
Others. Look in deps/
for what else is available.
Node statically compiles all its dependencies into the executable. When compiling your module, you don't need to worry about linking to any of these libraries.
To get started let's make a small Addon which does the following except in C++:
exports.hello = 'world';
To get started we create a file hello.cc
:
#include <v8.h>
using namespace v8;
extern 'C' void
init (Handle<Object> target)
{
HandleScope scope;
target->Set(String::New("hello"), String::New("World"));
}
This source code needs to be built into hello.node
, the binary Addon. To
do this we create a file called wscript
which is python code and looks
like this:
srcdir = '.'
blddir = 'build'
VERSION = '0.0.1'
def set_options(opt):
opt.tool_options('compiler_cxx')
def configure(conf):
conf.check_tool('compiler_cxx')
conf.check_tool('node_addon')
def build(bld):
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
obj.target = 'hello'
obj.source = 'hello.cc'
Running node-waf configure build
will create a file
build/default/hello.node
which is our Addon.
node-waf
is just http://code.google.com/p/waf/[WAF], the python-based build system. node-waf
is
provided for the ease of users.
All Node addons must export a function called init
with this signature:
extern 'C' void init (Handle<Object> target)
For the moment, that is all the documentation on addons. Please see http://github.com/ry/node_postgres for a real example.


02.15.17
During Ohio University President Roderick McDavis’ tenure, the number of students on the Athens campus has increased by nearly 50 percent.
Between Fall Semester 2005 and Fall Semester 2014, the university’s Athens’ campus enrollment increased by about 9,000 students, according to data provided by OU’s Office of Institutional Research.
During that time, OU saw the second most growth in terms of total number of students on its main campus, with Northeast Ohio Medical University topping the list with about a 94 percent increase in the same time frame.
“It is hard to state the enormity of success that has occurred relative to enrollments under Dr. McDavis’ tenure,” Craig Cornell, senior vice provost for Strategic Enrollment Management, said in an email.
OU’s total enrollment increased by about 33 percent since McDavis became president.
“This unprecedented growth equates to record breaking enrollments year after year for an entire decade,” Cornell said in an email. “These enrollments are also reflected in the fact that we have crossed record after record in any category that we would want to discuss from undergraduate, graduate, Athens, medical, regional and/or online enrollments.”
The regional campuses have seen rises and falls during McDavis’ tenure as president.
When the economy fell in 2008, more students began attending regional campuses, which increased regional enrollment but decreased main campus enrollment.
But when the economy picked back up after the recession, the roles were reversed, and regional campuses saw a drop in the number of students attending the five branch campuses.
Though enrollment on those campuses has plateaued slightly, enrollments are up compared to when McDavis started his presidency.
Online enrollment has also increased in recent years. OU’s online eLearning program started under McDavis’ leadership in 2011.
The most popular online program is the bachelor of science in nursing program.
Landing Page
OU President Roderick McDavis is leaving February 17. The Post looks back at his time as Ohio's president. Click this box to read the rest of the stories from this issue.


BUPA demands more private health insurance subsidies
by Unconventional EconomistWith membership in private health funds in free-fall:
BUPA, Australia’s largest health insurer, has demanded more subsidies from the federal government:
There are 1211 words left in this subscriber-only article.


Introduction
Application programming in DB2 is mostly done by using views, stored procedures and functions. These database objects encapsulate the code, gives better security and faster retrieval of data. Programming using SQL is the most direct method and the effective one as it is usually an extension of SQL. The tutorial uses the health care scenario which is used in the previous tutorials.
Topics presented here are:


Amazon.com, Inc. (/ˈæməzɒn/ or /ˈæməzən/) is an American electronic commerce and cloud computing company with headquarters in Seattle, Washington. It is the largest Internet-based retailer in the United States


With a passion for success, I possess Excellent interpersonal and analytical abilities, I'm a Data scientist, and a AI enthusiast with experience in Data science model building to deployment on cloud as well as Deep Learning model building to deployment on web. I have proven Leadership Skills, meticulous consciousness and can work with minimum supervision And also i'm full stack developer.
Predicting Future with past and present data .
● Model deployment and managing Machine Learning Pipeline
Simply put i write code that makes a website tick
including the Back-end makes the site work
● creating amazing webApps
Applying analytical skills on past data and building Dashboards with tableau to make business Decisions.
● Creating of Dashboards with tableau.
All of us must have craving for at least a few favourite food items, we may also have a few places where we like to get them, a restaurant which serves our favourite food the way we want it to be. But there is one factor that will make us reconsider having our favourite food from our favourite restaurant .
Flight ticket prices can be something hard to guess, today we might see a price, check out the price of the same flight tomorrow, it will be a different story. We might have often heard travellers saying that flight ticket prices are so unpredictable. Huh! Here we take on the challenge! As data scientists, we are gonna prove that given the right data anything can be predicted. Here you will be provided with prices of flight tickets for various airlines between the months of March and June of 2019 and between various cities.
Prediction of Subscription of Newsletter Based on different factors .A leading global leader of e-commerce has over 150 million paid subscription users. One of the many perks of the subscription is the privilege of buying products at lower prices. For an upcoming sale, the organization has decided to promote local artisans and their products, to help them through these tough times. However, slashed prices may impact local artists.
When ever do any business base is customer ,they are always want's to know weather customer satisfy with their services or not ,From here to know customer opinion i had analyse their reviews ,weather they are satisfied with Hotel Services or not.
Analysing Customer behaviour weather customer going to be long term customer or going to left bank using different factors
Forecasting Airlines passengers with FB Prophet
Analysing People's Sentiment before coronavirus and after corona virus
Analying sentiment should we afraid of AI or not using NLP techniques


Scene Recognition
Welcome to scene recognition project!
Select an Image
{% verbatim %}
{% endverbatim %}
Upload:
URL:
Bag Of Words
Bag Of Words with GMM
Convolutional Neural Network
Submit
{% verbatim %}
Results:
{{mCtrl.message}}
{% endverbatim %}


Members Collections
| ReqId |
Client |
Disbursment Date |
Loan Amount |
Expected amount |
Loan Status |
Outstanding |
Payment |
Payment Status |
| 230 |
Jack |
18/082020 |
R1885.65 |
External |
Approved |
555 |
150 |
Paid |
| 230 |
Henry |
17/082020 |
R1200.65 |
Internal |
Approved |
555 |
150 |
Paid |
| 230 |
Jack |
18/082020 |
R1885.65 |
External |
Approved |
555 |
150 |
Paid |
| 230 |
Henry |
17/082020 |
R1200.65 |
Internal |
Approved |
555 |
150 |
Paid |
All Collections
| ReqId |
Member |
Disbursment Date |
Loan Amount |
Expected amount |
Loan Status |
Outstanding |
| 230 |
Jack |
18/082020 |
R1885.65 |
External |
Approved |
566 |
| 230 |
Henry |
17/082020 |
R1200.65 |
Internal |
Approved |
566 |
| 230 |
Jack |
18/082020 |
R1885.65 |
External |
Approved |
566 |
| 230 |
Henry |
17/082020 |
R1200.65 |
Internal |
Approved |
566 |


{% include meta/variables.html %} {% include meta/base.html %} {% include meta/color.html %} {% include meta/facebook_og.html %} {% include meta/twitter_card.html %} {% include meta/link_rel.html %} {% include style/load_first.html %}


Curriculum Vitae
Small project base got from Area301.com most of them consisted of fixing bug
Bilingual B.A economics from york university (Glendon)
Honours B.A in computer science in progress, I'm planning to switch my degree to Bsc
Available upon request


Weather Dashboard
Search
Current City
Date
Humidity:
Wind Speed:
Temperature:
UV Index:
5-Day Forecast:
Day 1
Temp:
Humidity:
Day 2
Temp:
Humidity:
Day 3
Temp:
Humidity:
Day 4
Temp:
Humidity:
Day 5
Temp:
Humidity:


Dawn is filthy rich in 'Money' MV
by germainejDawn has dropped his music video for "Money"!
 "Money" is about not being able to live without something, and it's the former Pentagon member's first release as an artist under P-Nation.
Watch Dawn's "Money" MV above, and let us know what you think in the comments below.


{% if times %}
{% endif %}
{% for time in times %}
{% else %}
{% if time.system == "Milwaukee County Transit System" %}
{% else %}
{% endfor %}
{% endif %}
{% if time.minutes == 0 %}
Stop #{{ time.stop_num }} {{ time.stop_name }}
{{ time.system }}
Now
{% elif time.minutes < 3 %}Arriving
{% else %}{{ time.minutes }} Minutes
{% endif %} {{ time.route }}Stop #{{ time.stop_num }} {{ time.stop_name }}
{{ time.system }}
Welcome!
This page lets you track buses serving the UWM area, giving you the arrival times to and from campus. Useful for when you're in a rush! Select a stop from the menu to see times.


Raster Analytics allows you to perform analysis of large raster datasets across an ArcGIS GeoAnalytics Server. This allows you to analyze more data faster, by harnessing the power of multiple machines. The toolsets and tools currently available through the Portal Web UX are:
These tools calculate some statistics for a raster layer within area boundaries that you define.
Summarize Raster Within |
Calculates some summary statistics for raster cells within defined areas.
Some example applications are:
These tools help you identify, quantify, and visualize spatial patterns in your data.
Calculate Density |
Density analysis takes known quantities of some phenomenon and spreads these quantities across the map. You can use this tool, for example, to show concentrations of lightning strikes or tornadoes, access to health care facilities, and population densities.
Interpolate Points |
This tool allows you to predict values at new locations based on measurements found in a collection of points. The tool takes point data with values at each point and returns areas classified by predicted values. You can use this tool, for example, to predict rainfall levels across a watershed based on measurements taken at individual rain gauges.
The following tool helps you analyze images to determine areas with vegetation.
Monitor Vegetation |
Detects vegetation through many different indices.
These tools help you analyze raster surfaces.
Calculate Slope |
Identifies a surface that shows the slope of the input elevation data. Slope represents the rate of change of elevation for each digital elevation model (DEM) cell.
Derive Aspect |
Identifies the downslope direction of the maximum rate of change in value from each cell to its neighbors. Aspect can be thought of as the slope direction.
Create Viewshed |
Determines the locations on a raster surface that are visible to a set of observers.
These tools are used for both the day-to-day management of geographic data and for combining data prior to analysis.
Extract Raster |
Extract cells from a raster based on value, shape or the extent of a different dataset.
Remap Values |
Change the individual or ranges of cell values to new values.
Convert Feature to Raster |
Create a new raster dataset from an existing feature dataset.
Convert Raster to Feature |
Create a new feature dataset from an existing raster dataset.


% '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Sub ManageMenuBar Response.Write("ADMIN HOME ") Response.Write("Manage Bands ") Response.Write("Manage Venues ") Response.Write("Manage Instructor ") Response.Write("Manage News ") Response.Write("Manage Users ") Response.Write("Manage Events ") Response.Write("Manage Issues ") Response.Write("


Computer Science¶
Open Source Society University¶
Fundamentals¶
- Outline of Computer Science (wiki)
Gives an overview of topics and areas of interest related to the field of computer science; obviously not in-depth content, but it’s still good to have a broad understanding of what computer science actually encompasses as a field
- Introduction to Computer Science and Programming (MIT OCW)
University lectures aren’t always the easiest things to digest, but this is a very solid introduction to many of the fundamental concepts and ideas of computer science
- Basics of Computer Science (interactive slideshow)
This provides a very basic overview of computer architecture, what the system components are, and their function
Discrete Mathematics¶
- Mathematics for Computer Science (MIT OCW)
This seems to be a fairly comprehensive delve into discrete math, although it appears to potentially be missing some topics in boolean logic and combinatorics


--- title: Meeting Minutes layout: default excerpt: Curtin Robotics Club meeting minutes. ---
Our meeting agendas and minutes are hosted on Google Drive. You can view them below.
We are still working on giving access to our minutes.


Welcome to bitboard.
Bitboard is a decentralized anonymous imageboard. It is built on top of
Bitmessage's decentralized mailing lists.
To get started, you must
download
and setup Bitmessage then
enable API access.
Bitmessage must be running in order for Bitboard to work.
If you've set it up correctly, you should see some links below to join new channels, if not,
you'll likely see an unfriendly error message. Lists of popular channels can be found
on the web.


- Fixed bugs
- Added seed to HMRF
- Created functions to read 10X Visium .h5 files
- see createGiottoVisiumObject to create a Giotto object directly
- see get10Xmatrix_h5 to extract the count matrix
This is the first major release of Giotto. If you still want to work with the previous version, then you can find the older releases here.
Here is an overview about what has changed in the meantime:
NEW: Addition of getSpatialDataset to directly download a spatial dataset
(expression matrix, spatial coordinates and metadata). This is now also included in the examples that you can find under the Datasets tab on this website.
-
NEW: We have added tools to install, remove and check a Giotto r-miniconda environment. This miniconda environment is one way to make sure that you can run functions that require Python modules.
-
installGiottoEnvironment: (re-)installs a Giotto miniconda environment
-
removeGiottoEnvironment: removes a Giotto miniconda environment
-
checkGiottoEnvironment: verifies if a Giotto environment can be found
The other alternative is to install them in your own favorite Python environment and provide the path in the createGiottoInstructions command.
-
extension and improvement of spatial gene detection methods:
-
NEW: addition of spark method
- improvements for silhouetteRank:
- faster implementation
- multi parameter version as silhouetteRankTest
- improvements for binSpect:
- faster implementation
- multi parameter version: binSpectSingle or binSpectMulti
-
Spatial cell type enrichment methods have been streamlined and updated
-
runPAGEEnrich to run enrichment using PAGE algorithm and selected marker genes
-
runRankEnrich to run enrichment using a whole expression matrix
-
runHyperGeometricEnrich to run enrichment using the hypergeometric test
-
NEW: Spatial cell type deconvolution has been added:
- use runSpatialDeconv or runDWLSDeconv
NEW: Addition of addCellIntMetadata to add information about interacting cell types, which can subsequently be viewed with the spatPlot commands.
-
NEW: Addition of 3 small vignettes that cover different types of spatial datasets:
-
Cell Proximity Genes has been changed to Interaction Changed Genes
- This better reflects the nature of gene changes due to neighboring cell interactions
- CPG functions are deprecated and will be removed in the future
Several function help pages have been updated with dummy example code
several small and big fixes to the code
- background images See howto’s
- support for sparse matrices
- PCA can be calculated with the packages irlba (default) or factominer (old default)
- complemented PCA with separate functions for a scree plot and jackstraw plot
- addition of readExprMatrix to read an expression matrix
- addition of addGenesPerc to add information about genesets (e.g. mitochondrial genes)
- addition of showGrids and showNetworks to see available spatial grids and networks
- several bug fixes
- added voronoi plots to use in spatial plotting. See howto’s
- generalized visualization parameters between functions
- (optional) automatic installation of python modules through reticulate:
- you can provide your preferred python path
- the giotto environment can be installed automatic
- if you do not provide the python path and do not choose to install the giotto environment, then it will take the default python path
- several bug fixes
- several mini-datasets are now included within Giotto for quick testing:
- field 1 of seqFISH+ (single-cell)
- the visium brain Dentate Gyrus subset (spots)
- subset of starMAP (3D)
example to acces the seqFISH+ mini dataset:
# raw counts
small_seqfish_expr_matrix = read.table(system.file("extdata", "seqfish_field_expr.txt", package = 'Giotto'))
# cell locations
small_seqfish_locations = read.table(system.file("extdata", "seqfish_field_locs.txt", package = 'Giotto'))
- Default spatial network created with createSpatialNetwork is now a Delaunay spatial network.
- The function names for extracting spatial genes have changed:
# binGetSpatialGenes is now:
binSpect(gobject) # binary Spatial extraction
# spatial_genes_python is now:
silhouetteRank(gobject)
- Fixed multiple bugs
- Improved speed by changing code to Rcpp and implementing parallelization options
- updated howto’s tutorials in Start section
- Finished the analysis of 10 different spatial datasets (tutorials are a work-in-progress)
- New examples on mouse kidney and brain using the recently released 10X Visium datasets (NEW)
- Added tools to identify spatial enrichment based on cell-type specific gene signature lists (NEW)
- New example with 3D-like spatial data of the mouse hypothalamic preoptic region using merFISH (NEW)
- New example with 3D spatial data STARmap
- New example with the highly sensitive data from osmFISH
- New example on the Cerebellum with the scalable data from Slideseq
- New example on mouse olfactory bulb using immobilized primers on glass slides from Spatial Transcriptomics
- Updated seqFISH+ cortex example (NEW)
- Updated STARmap cortex example (NEW)
- Implemented SpatialDE and trendsceek
- Updated support for 3D spatial data
- Added support for the use of global instructions and automatically saving your plots (NEW)
- Add wrapper for differential expression with MAST and SCRAN


The median is often a useful number. In many cases it can describe data better than the average, as it is resistant to outliers and contaminated data in general. Take the list: 4, 4, 4, 5, 5, 5, 6, 6, 60. The average is 9 but the median is 5. Depending on usage, 5 might be more informative.
It is trivial to find the median. We can simply sort the list and select the middle index. But sorting the entire array is a waste if we only need to find the median. In this case we can use an algorithm dedicated to finding the n-th largest number - namely Hoare's selection algorithm aka Quickselect. I've implemented a JavaScript version based on the pseudo code on Wikipedia. The inspiration for doing so and an example where the median is used is my implementation of Median Flow tracking. See benchmarking and code below. I have rewritten the code slightly to pack it into a single function.
Implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | function QuickSelect(list, left, right, n) { if (left == right) return list[left]; var tmp; while (true) { pivotIndex = left + ((right - left) >>> 1); // select pivotIndex between left and right var pivotValue = list[pivotIndex]; // Move pivot to end tmp = list[pivotIndex]; list[pivotIndex] = list[right]; list[right] = tmp; pivotIndex = left; for (var i = left; i < right; i++) { if (list[i] <= pivotValue) { //swap tmp = list[pivotIndex]; list[pivotIndex] = list[i]; list[i] = tmp; pivotIndex++; } } // Move pivot to its final place tmp = list[right]; list[right] = list[pivotIndex]; list[pivotIndex] = tmp; if (n == pivotIndex) return list[n]; else if (n < pivotIndex) right = pivotIndex - 1; else left = pivotIndex + 1; } } |
Benchmarking (firefox)


Meghan Markle did take Archie to New York to watch Serena Williams at US Open
Serena Williams said her pal Meghan Markle is the 'strongest person' she knows and is always free for a chat. The tennis star revealed the Duchess took Archie with her to the US Open in September.
by Matthew Dresch, https://www.mirror.co.uk/authors/matthew-dresch/Meghan Markle did take baby Archie to New York to watch Serena Williams compete in the US Open, the tennis star has revealed.
The Duchess of Sussex flew across the Atlantic for the final of the tournament in September, when Archie was four-months-old.
It was widely assumed that Meghan left Archie with Prince Harry when she flew out to the US Open.
Meghan has been close pals with Serena, who described the royal as 'the strongest person I know', since they met at a Super Bowl party in 2010.
Mrs Williams said Meghan flew back to the UK straight after watching her lose to Bianca Andreescu in the final.
She told Access Hollywood: "She flew all the way with a newborn to see me play in New York and flew all the way back that night, and I probably couldn't have done that.
"I think it's really cool to have a group of friends who are doing amazing things and face the same pressures you face with being in the public eye."
Mrs Williams praised Meghan over how she has dealt with the intense scrutiny that comes with being a member of the royal family.
She added: "I'm not sure that many people can relate on that level, I don't think I can. I just think she's the strongest person I know, the nicest, sweetest..."
The tennis star said the Duchess does 'many' things for her - and is always there for a chat if she is feeling low.
Meghan flew to New York on a commercial flight after she and Harry were criticised for their use of private jets, Mail Online reports.


World health organization provides us with the suicide information based on the year,gender, age groups. Suicides are unfotunate and complex incidents that causes pain to hundreds of thousands of people every year around the world. The objective of this project is to help in an open and informed debate about ways to prevent suicide and what can be the target areas and countries. Every suicide is a tragedy. The World Health Organization (WHO) and the Global Burden of Disease study estimate that almost 800,000 people die from suicide every year and thats one person every 40 seconds. With timely, evidence-based interventions and targeted set, suicides can be prevented.
The suicide data over the years for the world is as presented below.
The project also helps us to break the myth that the developed countries are better and wont have have suicides.It further tries to find the target areas in population in the country with respect to world where the suicide are happening at a rapid pace and focus needs to be put.It can also help to find reasons based on further studies as to what causes a spike in suicides in different genders and age groups across the countries. It can also help to analyze what some other countries might be doing better where the suicides are decreasing
The presentation has attempted to draw an analysis over next three scenes.


This is an embedded web view. The contents of the label below will be replaced with the barcode scan results if successful.
The barcode value =


Select the country of your residence or the country that your business is legally established in. We're working hard on expanding our reach, and hope to get more countries supported soon.
If you do not see your country above, all is not lost! We can still manually approve your account.
This information is needed for tax purposes as well as account verification. We use Stripe to store and verify this data. Learn more
Stripe is in the process of verifying your details. This can take anywhere from a few minutes to a few days. We'll contact you when the verification process is complete and if Stripe requires additional supporting documents (such as a photo ID) in order to identify you. Hang tight!
Stripe needs additional identification documents in order to verify your account. Please enter them below.
Please fill in your personal information.
We are required to collection information for a representative of your company.
In Single Euro Payments Area member countries, we are required to collect and verify information about anybody that owns at least 25% of the company, in addition to the representative.
{{ formState.genericError }}
Something went wrong. Please check that you've entered everything correctly. This is usually because of an invalid zip/postal code, or invalid SSN/EIN.