code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
exports.setOptimizationLevel = (level) => {
engine.setOptimizationLevel(level);
} | Set the Rhino optimization level for the current thread and context.
The optimization level is an integer between -1 (interpreter mode)
and 9 (compiled mode, all optimizations enabled). The default level
is 0.
@param {Number} level an integer between -1 and 9 | exports.setOptimizationLevel | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.getRhinoContext = () => Context.getCurrentContext(); | Get the org.mozilla.javascript.Context associated with the current thread. | exports.getRhinoContext | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.getRhinoEngine = () => engine; | Get the org.ringojs.engine.RhinoEngine associated with this application.
@returns {org.ringojs.engine.RhinoEngine} the current RhinoEngine instance | exports.getRhinoEngine | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.getWorker = () => engine.getWorker(); | Get a new worker instance.
@return {org.ringojs.engine.RingoWorker} a new RingoWorker instance | exports.getWorker | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.getCurrentWorker = (obj) => engine.getCurrentWorker(obj || null); | Get the worker instance associated with the current thread or the given scope or function object.
@param {Object} obj optional scope or function to get the worker from.
@return {org.ringojs.engine.RingoWorker} the current worker | exports.getCurrentWorker | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.getErrors = () => new ScriptableList(engine.getCurrentWorker(null).getErrors()); | Get a list containing the syntax errors encountered in the current worker.
@returns {ScriptableList} a list containing the errors encountered in the
current worker | exports.getErrors | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.getRepositories = () => new ScriptableList(engine.getRepositories()); | Get the app's module search path as list of repositories.
@returns {ScriptableList} a list containing the module search path repositories | exports.getRepositories | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.addRepository = (repo) => {
if (typeof repo == "string") {
repo = new org.ringojs.repository.FileRepository(repo);
}
const path = getRepositories();
if (repo.exists() && !path.contains(repo)) {
path.add(Math.max(0, path.length) - 1, repo);
}
}; | Add a repository to the module search path
@param {Repository} repo a repository | exports.addRepository | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
exports.loadJars = (location, recursive) => {
if (typeof location !== "string" && !(location instanceof org.ringojs.repository.Repository)) {
throw new TypeError("location must be of type string or a repository");
}
if (recursive !== undefined && typeof recursive !== "boolean") {
throw new TypeError("recursive must be a boolean");
}
recursive = recursive === undefined || recursive === true;
const repo = typeof location === "string" ? getRepository(location) : location;
const jars = repo.getResources(recursive).filter(r => /.+\.jar$/i.test(r.name));
jars.forEach(function(file) {
addToClasspath(file);
});
}; | Loads the given location and adds all resources with a `*.jar` suffix to the class path.
If location is a string, it will be treated as repository path like `getRepository(location)`.
Otherwise, location must be a valid Ringo repository.
By default, JAR resources inside the repository will be looked up recursively and subjacent JARs will be loaded.
@param {Repository|string} location a path or repository to lookup JAR resources.
@param {boolean} recursive load JARs recursively, defaults to true | exports.loadJars | javascript | ringo/ringojs | modules/ringo/engine.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/engine.js | Apache-2.0 |
const prepareOptions = (options) => {
const defaultValues = {
"data": {},
"headers": {},
"method": "GET",
"username": undefined,
"password": undefined,
"followRedirects": true,
"readTimeout": 30000,
"connectTimeout": 60000,
"binary": false,
"beforeSend": null
};
const opts = options ? objects.merge(options, defaultValues) : defaultValues;
const headers = Headers(opts.headers);
opts.contentType = opts.contentType
|| headers.get("Content-Type")
|| "application/x-www-form-urlencoded;charset=utf-8";
return opts;
}; | Defaults for options passable to to request() | prepareOptions | javascript | ringo/ringojs | modules/ringo/httpclient.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpclient.js | Apache-2.0 |
const generateBoundary = () => {
// taken from apache httpclient
const buffer = new Buffer();
const random = new Random();
const count = random.nextInt(11) + 30; // a random size from 30 to 40
for (let i=0; i<count; i++) {
buffer.write(BOUNDARY_CHARS[random.nextInt(BOUNDARY_CHARS.length)]);
}
return buffer.toString();
}; | Generates a multipart boundary.
@returns {String} A multipart boundary | generateBoundary | javascript | ringo/ringojs | modules/ringo/httpclient.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpclient.js | Apache-2.0 |
const request = exports.request = (options) => {
if (options.complete != null || options.success != null || options.error != null) {
log.warn("ringo/httpclient does not support callbacks anymore!");
}
const opts = prepareOptions(options);
return new Exchange(opts.url, {
"method": opts.method,
"data": opts.data,
"headers": opts.headers,
"username": opts.username,
"password": opts.password,
"contentType": opts.contentType,
"followRedirects": opts.followRedirects,
"connectTimeout": opts.connectTimeout,
"readTimeout": opts.readTimeout,
"binary": opts.binary,
"proxy": opts.proxy,
"beforeSend": opts.beforeSend
});
}; | Make a generic request.
#### Generic request options
The `options` object may contain the following properties:
- `url`: the request URL
- `method`: request method such as GET or POST
- `data`: request parameters as string or object for GET, DELETE, and similar methods. For POST or PUT requests,
the body must be string, object, <code>Stream</code>, or <code>Binary</code>. For a multipart form POST requests,
all parameter values must be instances of <a href="#TextPart"><code>TextPart</code></a> or
<a href="#BinaryPart"><code>BinaryPart</code></a>.
- `headers`: request headers
- `username`: username for HTTP authentication
- `password`: password for HTTP authentication
- `proxy`: proxy-settings as string (<code>http://proxy-hostname:port</code>)
or object <code>{host: "proxy-hostname", port: 3128}</code>
- `contentType`: the contentType. If set to <code>multipart/form-data</code>, PUT and POST request's <code>data</code>
will be treated as multipart form uploads.
- `binary`: if true if content should be delivered as binary,
else it will be decoded to string
- `followRedirects`: whether HTTP redirects (response code 3xx) should be
automatically followed; default: true
- `readTimeout`: setting for read timeout in millis. 0 return implies that the option
is disabled (i.e., timeout of infinity); default: 30000 ms (or until impl decides its time)
- `connectTimeout`: Sets a specified timeout value, in milliseconds, to be used
when opening a communications link to the resource referenced by this
URLConnection. A timeout of zero is interpreted as an infinite timeout.;
default: 60000 ms (or until impl decides its time)
@param {Object} options
@returns {Exchange} exchange object
@see #get
@see #post
@see #put
@see #del | exports.request | javascript | ringo/ringojs | modules/ringo/httpclient.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpclient.js | Apache-2.0 |
const createOptions = (method, url, data) => {
return {
"method": method,
"url": url,
"data": data
};
}; | Creates an options object based on the arguments passed.
@param {String} method The request method
@param {String} url The URL
@param {String|Object|Stream|Binary} data Optional data to send to the server
@returns An options object
@type Object<method, url, data> | createOptions | javascript | ringo/ringojs | modules/ringo/httpclient.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpclient.js | Apache-2.0 |
exports.get = (url, data) => {
return request(createOptions("GET", url, data));
}; | Executes a GET request.
@param {String} url The URL
@param {Object|String} data The data to append as GET parameters to the URL
@returns {Exchange} The Exchange instance representing the request and response | exports.get | javascript | ringo/ringojs | modules/ringo/httpclient.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpclient.js | Apache-2.0 |
exports.post = (url, data) => {
return request(createOptions("POST", url, data));
}; | Executes a POST request.
@param {String} url The URL
@param {Object|String|Stream|Binary} data The data to send to the server
@returns {Exchange} The Exchange instance representing the request and response | exports.post | javascript | ringo/ringojs | modules/ringo/httpclient.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpclient.js | Apache-2.0 |
exports.del = (url, data) => {
return request(createOptions("DELETE", url, data));
}; | Executes a DELETE request.
@param {String} url The URL
@param {Object|String} data The data to append as GET parameters to the URL
@returns {Exchange} The Exchange instance representing the request and response | exports.del | javascript | ringo/ringojs | modules/ringo/httpclient.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpclient.js | Apache-2.0 |
exports.put = (url, data) => {
return request(createOptions("PUT", url, data));
}; | Executes a PUT request.
@param {String} url The URL
@param {Object|String|Stream|Binary} data The data send to the server
@returns {Exchange} The Exchange instance representing the request and response | exports.put | javascript | ringo/ringojs | modules/ringo/httpclient.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpclient.js | Apache-2.0 |
this.write = function(name, writer, outStream) {
writer.append("Content-Disposition: form-data; name=\"")
.append(name).append("\"");
if (fileName != null) {
writer.append("; filename=\"").append(fileName).append("\"");
}
writer.append(CRLF);
writer.append("Content-Type: text/plain; charset=")
.append(charset || "utf-8").append(CRLF);
writer.append(CRLF).flush();
if (data instanceof io.TextStream) {
data.copy(new io.TextStream(outStream, {
"charset": charset || "utf-8"
})).close();
outStream.flush();
} else {
writer.append(data);
}
writer.append(CRLF).flush();
}; | Writes this TextPart's data.
@param {String} name The name of the text part
@param {java.io.PrintWriter} writer The writer
@param {java.io.OutputStream} outStream The output stream
@ignore | this.write ( name , writer , outStream ) | javascript | ringo/ringojs | modules/ringo/httpclient.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpclient.js | Apache-2.0 |
const TextPart = exports.TextPart = function(data, charset, fileName) {
/**
* Writes this TextPart's data.
* @param {String} name The name of the text part
* @param {java.io.PrintWriter} writer The writer
* @param {java.io.OutputStream} outStream The output stream
* @ignore
*/
this.write = function(name, writer, outStream) {
writer.append("Content-Disposition: form-data; name=\"")
.append(name).append("\"");
if (fileName != null) {
writer.append("; filename=\"").append(fileName).append("\"");
}
writer.append(CRLF);
writer.append("Content-Type: text/plain; charset=")
.append(charset || "utf-8").append(CRLF);
writer.append(CRLF).flush();
if (data instanceof io.TextStream) {
data.copy(new io.TextStream(outStream, {
"charset": charset || "utf-8"
})).close();
outStream.flush();
} else {
writer.append(data);
}
writer.append(CRLF).flush();
};
return this;
}; | @name TextPart
@param {String|TextStream} data text data to write
@param {String} charset the charset
@param {String} fileName (optional) file name
@returns {TextPart} A newly constructed TextPart instance
@constructor
@example request({
url: "http://example.org/post-multipart",
method: "POST",
contentType: "multipart/form-data",
data: {
"simple": new TextPart("my string", "utf-8"),
"text": new TextPart(textStream, "utf-8"),
"txtFile": new TextPart(txtStream, "utf-8", "test.txt")
}
}); | exports.TextPart ( data , charset , fileName ) | javascript | ringo/ringojs | modules/ringo/httpclient.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpclient.js | Apache-2.0 |
this.write = function(name, writer, outStream) {
writer.append("Content-Disposition: form-data; name=\"")
.append(name).append("\"");
if (fileName != null) {
writer.append("; filename=\"").append(fileName).append("\"");
}
writer.append(CRLF);
writer.append("Content-Type: ")
.append(contentType || (fileName != null ? mimeType(fileName) : "application/octet-stream"))
.append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
if (data instanceof InputStream) {
(new io.Stream(data)).copy(outStream).close();
} else if (data instanceof binary.Binary) {
(new io.MemoryStream(data)).copy(outStream).close();
} else if (data instanceof io.Stream) {
data.copy(outStream).close();
}
writer.append(CRLF).flush();
};
return this;
}; | Writes this BinaryPart's data
@param {String} name form parameter name of the text part
@param {java.io.PrintWriter} writer print writer
@param {java.io.OutputStream} outStream binary output stream
@ignore | this.write ( name , writer , outStream ) | javascript | ringo/ringojs | modules/ringo/httpclient.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpclient.js | Apache-2.0 |
this.onEnter = function(cx, activation, thisObj, args) {
if (currentTimer) {
timerStack.push(currentTimer);
}
const now = nanoTime();
currentTimer = {
name: name,
start: now,
subTimers: []
// invoker: stack.length ? stack[stack.length - 1].name : null
};
stack.push(this);
}; | @param {Object} cx
@param {Object} activation
@param {Object} thisObj
@param {*...} args... | this.onEnter ( cx , activation , thisObj , args ) | javascript | ringo/ringojs | modules/ringo/profiler.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/profiler.js | Apache-2.0 |
this.onExceptionThrown = function(cx, ex) {}; | @param {Object} cx
@param {Object} ex | this.onExceptionThrown ( cx , ex ) | javascript | ringo/ringojs | modules/ringo/profiler.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/profiler.js | Apache-2.0 |
const Frame = function(name, stack) {
// The timer for the current invocation of this frame.
// This is an object containing start and end timestamp properties and
// a subTimers array property containing timers for functions directly
// invoked from this frame.
let currentTimer;
const timerStack = []; // Timer stack for other currently active invocations of this frame
const finishedTimers = []; // Timer list of finished invocations of this frame
Object.defineProperty(this, "name", {
"value": name,
"enumerable": true
});
/**
* @param {Object} cx
* @param {Object} activation
* @param {Object} thisObj
* @param {*...} args...
*/
this.onEnter = function(cx, activation, thisObj, args) {
if (currentTimer) {
timerStack.push(currentTimer);
}
const now = nanoTime();
currentTimer = {
name: name,
start: now,
subTimers: []
// invoker: stack.length ? stack[stack.length - 1].name : null
};
stack.push(this);
};
/**
* @param {Object} cx
* @param {Object} ex
*/
this.onExceptionThrown = function(cx, ex) {};
this.onExit = function(cx, byThrow, resultOrException) {
currentTimer.end = nanoTime();
stack.pop();
if (stack.length > 0) {
stack[stack.length - 1].addSubTimer(currentTimer);
}
finishedTimers.push(currentTimer);
currentTimer = timerStack.pop();
};
this.addSubTimer = function(subTimer) {
currentTimer.subTimers.push(subTimer);
};
this.getSelftime = function() {
return finishedTimers.reduce((prev, e) => {
// add this timer's runtime minus the accumulated sub-timers
return (prev + e.end - e.start) - e.subTimers.reduce((prev, e) => {
return prev + e.end - e.start;
}, 0);
}, 0);
};
this.getRuntime = function() {
return finishedTimers.reduce((prev, e) => {
return prev + (e.end - e.start);
}, 0);
};
this.countInvocations = function() {
return finishedTimers.length;
};
this.renderLine = function(prefixLength) {
const runtime = this.getSelftime() / 1000000;
const count = this.countInvocations();
const formatter = new java.util.Formatter();
formatter.format("%1$7.0f ms %2$5.0f ms %3$6.0f %4$s",
runtime, Math.round(runtime / count), count, name.slice(prefixLength));
return formatter.toString();
};
return new org.mozilla.javascript.debug.DebugFrame(this);
}; | @param {String} name
@param {Array} stack | Frame ( name , stack ) | javascript | ringo/ringojs | modules/ringo/profiler.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/profiler.js | Apache-2.0 |
this.getScriptFrame = function(cx, script) {
if (!script.isFunction()) {
return null;
}
const name = getScriptName(script);
let frame = frames[name];
if (!frame) {
frame = new Frame(name, stack);
frames[name] = frame;
}
return frame;
}; | @param {Object} cx
@param {Function} script | this.getScriptFrame ( cx , script ) | javascript | ringo/ringojs | modules/ringo/profiler.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/profiler.js | Apache-2.0 |
this.formatResult = function(maxFrames) {
const list = this.getFrames();
// cut list to maxFrames elements
if (typeof maxFrames == "number") {
list.length = maxFrames;
}
// find common prefix in path names
const commonPrefix = list.reduce((previous, current) => {
return strings.getCommonPrefix(previous, current.name);
}, "");
const lines = [];
let maxLength = 0;
list.forEach(item => {
const str = item.renderLine(commonPrefix.length);
maxLength = Math.max(maxLength, str.length);
lines.push(str);
})
const buffer = new Buffer();
buffer.writeln(" total average calls path");
for (let i = 1; i < maxLength; i++) {
buffer.write("-");
}
buffer.writeln();
buffer.write(lines.join("\n"));
return buffer.toString();
}; | @param {Number} maxFrames optional maximal number of frames to include | this.formatResult ( maxFrames ) | javascript | ringo/ringojs | modules/ringo/profiler.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/profiler.js | Apache-2.0 |
const Profiler = exports.Profiler = function() {
const stack = [];
const frames = {};
/**
* @param {Object} cx
* @param {Function} script
*/
this.getScriptFrame = function(cx, script) {
if (!script.isFunction()) {
return null;
}
const name = getScriptName(script);
let frame = frames[name];
if (!frame) {
frame = new Frame(name, stack);
frames[name] = frame;
}
return frame;
};
this.getFrames = function() {
// sort list according to total runtime
return Object.keys(frames)
.map(key => frames[key])
.sort((a, b) => b.getSelftime() - a.getSelftime());
};
/**
* @param {Number} maxFrames optional maximal number of frames to include
*/
this.formatResult = function(maxFrames) {
const list = this.getFrames();
// cut list to maxFrames elements
if (typeof maxFrames == "number") {
list.length = maxFrames;
}
// find common prefix in path names
const commonPrefix = list.reduce((previous, current) => {
return strings.getCommonPrefix(previous, current.name);
}, "");
const lines = [];
let maxLength = 0;
list.forEach(item => {
const str = item.renderLine(commonPrefix.length);
maxLength = Math.max(maxLength, str.length);
lines.push(str);
})
const buffer = new Buffer();
buffer.writeln(" total average calls path");
for (let i = 1; i < maxLength; i++) {
buffer.write("-");
}
buffer.writeln();
buffer.write(lines.join("\n"));
return buffer.toString();
};
this.toString = function() {
return this.formatResult(null);
};
const profiler = new org.ringojs.util.DebuggerBase(this);
profiler.debuggerScript = module.id + ".js";
return profiler;
} | A class for measuring the frequency and runtime of function invocations. | exports.Profiler ( ) | javascript | ringo/ringojs | modules/ringo/profiler.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/profiler.js | Apache-2.0 |
exports.encode = function(str, encoding) {
const input = str instanceof binary.Binary ? str : binary.toByteString(str, encoding || 'utf8');
const length = input.length;
const output = new binary.ByteArray(4 * (length + (3 - length % 3) % 3) / 3);
let i = 0;
let j = 0;
let c1, c2, c3;
while(i < length) {
c1 = input[i++];
if (i === length) {
output[j++] = encodeChars[c1 >> 2];
output[j++] = encodeChars[(c1 & 0x3) << 4];
output[j++] = padding;
output[j++] = padding;
break;
}
c2 = input[i++];
if (i === length) {
output[j++] = encodeChars[c1 >> 2];
output[j++] = encodeChars[((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4)];
output[j++] = encodeChars[(c2 & 0xF) << 2];
output[j++] = padding;
break;
}
c3 = input[i++];
output[j++] = encodeChars[c1 >> 2];
output[j++] = encodeChars[((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4)];
output[j++] = encodeChars[((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6)];
output[j++] = encodeChars[c3 & 0x3F];
}
// length should be correct already, but just to be sure
output.length = j;
return output.decodeToString('ascii');
}; | Encode a string or binary to a Base64 encoded string
@param {String|Binary} str a string or binary
@param {String} encoding optional encoding to use if
first argument is a string. Defaults to 'utf8'.
@returns {String} the Base64 encoded string | exports.encode ( str , encoding ) | javascript | ringo/ringojs | modules/ringo/base64.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/base64.js | Apache-2.0 |
this.decode = function(bytes, start, end) {
start = start || 0;
end = end || bytes.length;
while (end > start) {
let count = Math.min(end - start, input.capacity() - input.position());
input.put(bytes, start, count);
decodeInput(end - start);
start += count;
}
decoded = null;
return this;
}; | Decode bytes from the given buffer.
@param {binary.Binary} bytes a ByteString or ByteArray
@param {Number} start The start index, or 0 if undefined
@param {Number} end the end index, or bytes.length if undefined | this.decode ( bytes , start , end ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.close = function() {
input.flip();
const result = decoder.decode(input, output, true);
if (result.isError()) {
decoder.reset();
input.clear();
throw new Error(result);
}
return this;
}; | Closes the decoder for further input. A closed decoder throws a `java.nio.BufferOverflowException`
if `decode()` is called again.
@returns {Decoder} the decoder | this.close ( ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.read = function() {
let eof = false;
while (stream && !eof) {
if (mark > 0) {
output.limit(output.position());
output.position(mark);
output.compact();
mark = 0;
}
let position = input.position();
let read = stream.readInto(ByteArray.wrap(input.array()), position, input.capacity());
if (read < 0) {
// end of stream has been reached
eof = true;
} else {
input.position(position + read);
decodeInput(0);
}
}
output.flip();
decoded = null; // invalidate
return (mark === output.limit()) ?
null : String(output.subSequence(mark, output.limit()));
}; | Reads the whole stream and returns it as a string.
This method is only useful if the decoder has a connected stream.
@returns {String} the decoded string
@see <a href="#readFrom">readFrom</a> | this.read ( ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.readLine = function(includeNewline) {
let eof = false;
let newline = StringUtils.searchNewline(output, mark);
while (stream && !eof && newline < 0) {
if (mark > 0) {
output.limit(output.position());
output.position(mark);
output.compact();
mark = 0;
}
let position = input.position();
let read = stream.readInto(ByteArray.wrap(input.array()), position, input.capacity());
if (read < 0) {
// end of stream has been reached
eof = true;
} else {
let from = output.position();
input.position(position + read);
decodeInput(0);
newline = StringUtils.searchNewline(output, from);
}
}
output.flip();
// get the raw underlying char[] output buffer
const array = output.array();
let result;
if (newline > -1) {
const isCrlf = array[newline] === 13 && array[newline + 1] === 10;
if (isCrlf && includeNewline) {
// We want to add a single newline to the return value. To save us
// from allocating a new buffer we temporarily mod the existing one.
array[newline] = 10;
result = JavaString.valueOf(array, mark, newline + 1 - mark);
array[newline] = 13;
mark = newline + 2;
} else {
let count = includeNewline ? newline + 1 - mark : newline - mark;
result = JavaString.valueOf(array, mark, count);
mark = isCrlf ? newline + 2 : newline + 1;
}
output.position(output.limit());
output.limit(output.capacity());
} else if (eof) {
result = (mark === output.limit()) ?
null : JavaString.valueOf(array, mark, output.limit() - mark);
this.clear();
}
decoded = null; // invalidate cached decoded representation
return result;
}; | Reads a stream line by line and returns it as a string.
This method is only useful if the decoder has a connected stream.
@param {Boolean} includeNewline if true, the newline character is included in the result, otherwise not
@returns {String} the decoded string or null if stream is empty
@see <a href="#readFrom">readFrom</a> | this.readLine ( includeNewline ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.toString = function() {
if (decoded == null) {
decoded = JavaString.valueOf(output.array(), mark, output.position() - mark);
}
return decoded;
}; | Returns the decoded string.
@returns {String} the decoded string | this.toString ( ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.hasPendingInput = function() {
return input.position() > 0;
}; | Checks if all bytes are already decoded or if there is pending input.
@returns {Boolean} true if there not all bytes are decoded, false otherwise | this.hasPendingInput ( ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.readFrom = function(source) {
stream = source;
return this;
}; | Sets the source stream to read from. Using io streams is an alternative
to reading from plain binary ByteArray or ByteString objects.
@param {io.Stream} source the source stream
@see <a href="../../io/">io streams</a>
@example const stream = new MemoryStream();
stream.write(...); // write some bytes into the stream
stream.position = 0; // reset the pointer
const dec = new Decoder('ASCII');
dec.readFrom(stream); // connect the stream with the decoder
dec.read(); // returns the stream's content as string | this.readFrom ( source ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.clear = function() {
decoded = null;
output.clear();
mark = 0;
return this;
}; | Clears the character buffer.
@example dec.decode(someByteArray);
dec.toString(); // returns the decoded string
dec.clear();
dec.toString(); // returns '' | this.clear ( ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.encode = function(string, start, end) {
start = start || 0;
end = end || string.length;
const input = CharBuffer.wrap(string, start, end);
let result = encoder.encode(input, output, false);
while (result.isOverflow()) {
// grow output buffer
capacity += Math.max(capacity, Math.round(1.2 * (end - start) * encoder.averageBytesPerChar()));
encoded.length = capacity;
let position = output.position();
output = ByteBuffer.wrap(encoded);
output.position(position);
result = encoder.encode(input, output, false);
}
if (result.isError()) {
encoder.reset();
throw new Error(result);
}
if (stream) {
stream.write(encoded, 0, output.position());
// stream.flush();
this.clear();
}
return this;
}; | Encodes the given string into the encoder's binary buffer.
@param {String} string the string to encode
@param {Number} start optional index of the first character to encode
@param {Number} end optional index of the character after the last character to encode
@example // this will only encode 'e' and 'f'
enc.encode("abcdef", 4, 6); | this.encode ( string , start , end ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.close = function() {
const input = CharBuffer.wrap("");
const result = encoder.encode(input, output, true);
if (result.isError()) {
encoder.reset();
throw new Error(result);
}
if (stream) {
stream.write(encoded, 0, output.position());
// stream.flush();
this.clear();
}
return this;
}; | Closes the encoder.
@returns {Encoder} the now closed encoder | this.close ( ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.toByteString = function() {
return binary.ByteString.wrap(encoded.slice(0, output.position()));
}; | Converts the encoded bytes into a ByteString.
@returns {ByteString} the resulting ByteString | this.toByteString ( ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.toByteArray = function() {
return encoded.slice(0, output.position());
}; | Converts the encoded bytes into a ByteArray.
@returns {ByteArray} the resulting ByteArray | this.toByteArray ( ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.writeTo = function(sink) {
stream = sink;
return this;
}; | Sets the output stream to write into. Using io streams as destination is an alternative to writing
into plain binary ByteArray or ByteString objects.
@param {Stream} sink the destination stream
@see <a href="../../io/">io streams</a> | this.writeTo ( sink ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.clear = function() {
output.clear();
return this;
}; | Clears the byte buffer.
@returns {Encoder} the cleared encoder | this.clear ( ) | javascript | ringo/ringojs | modules/ringo/encoding.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/encoding.js | Apache-2.0 |
this.reset = function() {
content.length = 0;
length = 0;
return this;
}; | Reset the buffer discarding all its content.
@returns {Buffer} this buffer object | this.reset ( ) | javascript | ringo/ringojs | modules/ringo/buffer.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/buffer.js | Apache-2.0 |
this.write = function() {
for (let i = 0; i < arguments.length; i++) {
let str = String(arguments[i]);
content.push(str);
length += str.length;
}
return this;
}; | Append all arguments to this buffer.
@param {*...} args... variable arguments to append to the buffer
@returns {Buffer} this buffer object | this.write ( ) | javascript | ringo/ringojs | modules/ringo/buffer.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/buffer.js | Apache-2.0 |
this.writeln = function() {
this.write.apply(this, arguments);
content.push("\r\n");
length += 2;
return this;
}; | Append all arguments to this buffer terminated by a carriage return/newline sequence.
@param {*...} args... variable arguments to append to the buffer
@returns {Buffer} this buffer object | this.writeln ( ) | javascript | ringo/ringojs | modules/ringo/buffer.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/buffer.js | Apache-2.0 |
this.toString = function() {
return content.join('');
}; | Return the content of this buffer as string.
@returns {String} the buffer as string | this.toString ( ) | javascript | ringo/ringojs | modules/ringo/buffer.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/buffer.js | Apache-2.0 |
this.forEach = function(fn) {
content.forEach(fn);
}; | Call function <code>fn</code> with each content part in this buffer.
@param {Function} fn a function to apply to each buffer part | this.forEach ( fn ) | javascript | ringo/ringojs | modules/ringo/buffer.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/buffer.js | Apache-2.0 |
this.digest = function(algorithm) {
const md = java.security.MessageDigest.getInstance(algorithm || "MD5");
content.forEach(part => {
md.update(binary.toByteString(part));
});
const b = binary.ByteString.wrap(md.digest());
return strings.b16encode(b);
}; | Get a message digest on the content of this buffer.
@param {String} algorithm the algorithm to use, defaults to MD5
@returns {String} a Base16 encoded digest | this.digest ( algorithm ) | javascript | ringo/ringojs | modules/ringo/buffer.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/buffer.js | Apache-2.0 |
this.setEnabled = function(flag) {
_enabled = flag === true;
}; | Enable or disable ANSI terminal colors for this writer.
@param {Boolean} flag true to enable ANSI colors. | this.setEnabled ( flag ) | javascript | ringo/ringojs | modules/ringo/term.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/term.js | Apache-2.0 |
this.isEnabled = function() {
return _enabled;
}; | Returns true if ANSI terminal colors are enabled.
@returns {Boolean} true if ANSI is enabled. | this.isEnabled ( ) | javascript | ringo/ringojs | modules/ringo/term.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/term.js | Apache-2.0 |
this.write = function() {
for (let i = 0; i < arguments.length; i++) {
let arg = String(arguments[i]);
if (!_enabled) {
arg = arg.replace(cleaner, '');
}
javaConsole.printf("%s", arg);
if (arg && !matcher.test(arg) && i < arguments.length - 1) {
javaConsole.printf(" ");
}
}
}; | Write the arguments to the stream, applying ANSI terminal colors if
enabled is true.
@param {*...} args... variable number of arguments to write | this.write ( ) | javascript | ringo/ringojs | modules/ringo/term.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/term.js | Apache-2.0 |
exports.write = function() {
tw.write.apply(tw, arguments);
}; | Write the arguments to `system.stdout`, applying ANSI terminal colors if
support has been detected.
@param {*...} args... variable number of arguments to write | exports.write ( ) | javascript | ringo/ringojs | modules/ringo/term.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/term.js | Apache-2.0 |
exports.writeln = function() {
tw.writeln.apply(tw, arguments);
}; | Write the arguments to `system.stdout` followed by a newline character,
applying ANSI terminal colors if support has been detected.
@param {*...} args... variable number of arguments to write | exports.writeln ( ) | javascript | ringo/ringojs | modules/ringo/term.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/term.js | Apache-2.0 |
this.writeln = function() {
this.write.apply(this, arguments);
javaConsole.printf((_enabled ? exports.RESET : "") + "\n");
};
};
const tw = new TermWriter();
/**
* Write the arguments to `system.stdout`, applying ANSI terminal colors if
* support has been detected.
* @param {*...} args... variable number of arguments to write
*/
exports.write = function() {
tw.write.apply(tw, arguments);
};
/**
* Write the arguments to `system.stdout` followed by a newline character,
* applying ANSI terminal colors if support has been detected.
* @param {*...} args... variable number of arguments to write
*/
exports.writeln = function() {
tw.writeln.apply(tw, arguments);
}; | Write the arguments to the stream followed by a newline character,
applying ANSI terminal colors if enabled is true.
@param {*...} args... variable number of arguments to write | this.writeln ( ) | javascript | ringo/ringojs | modules/ringo/term.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/term.js | Apache-2.0 |
const EventEmitter = exports.EventEmitter = function() {
// if called on an object other than EventEmitter define properties
if (!(this instanceof EventEmitter)) {
Object.defineProperties(this, emitterImpl);
}
}; | This class provides methods to emit events and add or remove event listeners.
The `EventEmitter` function can be used as constructor or as mix-in. Use the
`new` keyword to construct a new EventEmitter:
const emitter = new EventEmitter();
To add event handling methods to an existing object, call or apply the
`EventEmitter` function with the object as `this`:
EventEmitter.call(object); | exports.EventEmitter ( ) | javascript | ringo/ringojs | modules/ringo/events.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/events.js | Apache-2.0 |
exports.mimeType = (fileName, fallback) => {
const ext = fileName.slice(fileName.lastIndexOf('.')).toLowerCase();
return exports.MIME_TYPES[ext] || fallback || 'application/octet-stream';
}; | Determines the MIME type for the given file extension. If the file extension
is unknown, the fallback argument is returned. If that is undefined, the
function returns "application/octet-stream".
@param {String} fileName a file name
@param {String} fallback MIME type to return if file extension is unknown
@returns {String} the MIME type for the file name | exports.mimeType | javascript | ringo/ringojs | modules/ringo/mime.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/mime.js | Apache-2.0 |
const write = exports.write = function() {
const length = arguments.length;
const out = system.stdout;
for (let i = 0; i < length; i++) {
out.write(String(arguments[i]));
if (i < length - 1) {
out.write(' ');
}
}
}; | Write 0..n arguments to standard output.
@param {*...} args... | exports.write ( ) | javascript | ringo/ringojs | modules/ringo/shell.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/shell.js | Apache-2.0 |
exports.writeln = function() {
write.apply(this, arguments);
system.stdout.writeLine('');
}; | Write 0..n arguments to standard output, followed by a newline.
@param {*...} args... | exports.writeln ( ) | javascript | ringo/ringojs | modules/ringo/shell.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/shell.js | Apache-2.0 |
exports.read = () => {
if (!input) {
throw new Error('jline not installed');
}
return String.fromCharCode(input.readVirtualKey());
}; | Read a single character from the standard input. | exports.read | javascript | ringo/ringojs | modules/ringo/shell.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/shell.js | Apache-2.0 |
exports.readln = (prompt, echoChar) => {
prompt || (prompt = '');
if (input) {
if (typeof echoChar === 'string') {
const echo = new Character((echoChar === '') ? 0 : echoChar.charCodeAt(0));
return input.readLine(prompt, echo);
}
return input.readLine(prompt);
} else {
system.stdout.write(prompt);
return system.stdin.readLine().trim();
}
}; | Read a single line from the standard input.
@param {String} prompt optional prompt to display
@param {String} echoChar character to use as echo,
e.g. '*' for passwords or '' for no echo. | exports.readln | javascript | ringo/ringojs | modules/ringo/shell.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/shell.js | Apache-2.0 |
exports.start = (engine) => {
engine = engine || require('ringo/engine').getRhinoEngine();
(new org.ringojs.tools.RingoShell(engine)).run();
}; | Start the shell programmatically. This uses the current thread and thus will not
return. You should therefore call this function as the last statement in your script.
Terminating the shell will exit the program.
@since 0.5
@param {RhinoEngine} engine | exports.start | javascript | ringo/ringojs | modules/ringo/shell.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/shell.js | Apache-2.0 |
exports.quit = (status) => {
java.lang.System.exit(status || 0);
}; | Quit the shell and exit the JVM.
@param {Number} status optional integer exit status code (default is 0) | exports.quit | javascript | ringo/ringojs | modules/ringo/shell.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/shell.js | Apache-2.0 |
this.signal = function(permits) {
semaphore.release(permits === undefined ? 1 : permits);
};
} | Add one or more permits to the semaphore.
@param {Number} permits the number of permits to give, defaults to 1 | this.signal ( permits ) | javascript | ringo/ringojs | modules/ringo/concurrent.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/concurrent.js | Apache-2.0 |
this.tryWait = function(timeout, permits) {
return semaphore.tryAcquire(permits === undefined ? 1 : permits,
timeout, TimeUnit.MILLISECONDS);
};
/**
* Add one or more permits to the semaphore.
* @param {Number} permits the number of permits to give, defaults to 1
*/
this.signal = function(permits) { | Wait for one or more permits for the given span of time. Returns true
if the requested permits could be acquired before the timeout elapsed.
@param {Number} timeout The span of time to wait, in milliseconds
@param {Number} permits the number of permits to wait for, defaults to 1
@return true if the requested permits could be acquired, false if the
timeout elapsed | this.tryWait ( timeout , permits ) | javascript | ringo/ringojs | modules/ringo/concurrent.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/concurrent.js | Apache-2.0 |
const jsDump = exports.jsDump = (value, lvl) => {
if (!lvl) {
lvl = 0;
}
let buf;
switch (getType(value)) {
case "string":
return quote(value);
case "boolean":
case "number":
case "nan":
case "date":
case "regexp":
return value.toString();
case "undefined":
case "null":
return String(value);
case "function":
if (getType(value.name) === "string" && value.name.length > 0) {
return value.name;
}
return value.toSource();
case "array":
buf = value.map(val => indent(lvl + 1) + jsDump(val, lvl + 1));
return ["[", buf.join(",\n"), indent(lvl) + "]"].join("\n");
case "object":
buf = Object.keys(value).map(key => {
return indent(lvl + 1) + '"' +
key + '": ' +
jsDump(value[key], lvl + 1);
});
return ["{", buf.join(",\n"), indent(lvl) + "}"].join("\n");
case "java":
return '<java:' + value.class.name + '>';
}
}; | Converts the value passed as argument into a nicely formatted and
indented string
@param {Object} value The value to convert into a string
@param {Number} lvl Optional indentation level (defaults to zero)
@returns {String} The string representation of the object passed as argument | exports.jsDump | javascript | ringo/ringojs | modules/ringo/utils/test.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/test.js | Apache-2.0 |
const getType = exports.getType = (obj) => {
if (typeof(obj) === "string") {
return "string";
} else if (typeof(obj) === "boolean") {
return "boolean";
} else if (typeof (obj) === "number") {
return (isNaN(obj) === true) ? "nan" : "number";
} else if (typeof(obj) === "undefined") {
return "undefined";
} else if (obj === null) {
return "null";
} else if (obj instanceof Array) {
return "array";
} else if (obj instanceof Date) {
return "date";
} else if (obj instanceof RegExp) {
return "regexp";
} else if (obj instanceof Function) {
return "function";
} else if (obj instanceof java.lang.Object) {
return "java";
}
return "object";
}; | Returns the type of the object passed as argument.
@param {Object} obj
@returns {String} The type of the object passed as argument | exports.getType | javascript | ringo/ringojs | modules/ringo/utils/test.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/test.js | Apache-2.0 |
exports.getStackTrace = (trace) => {
// create exception and fill in stack trace
if (!trace) {
const ex = new org.mozilla.javascript.EvaluatorException("");
ex.fillInStackTrace();
trace = ex.getScriptStack();
}
return trace.reduce((stack, el) => {
if (el.fileName != null && el.lineNumber > -1) {
// exclude all lines containing the unittest module itself
if (!el.fileName.startsWith(module.id) &&
!el.fileName.startsWith("assert.js") &&
el.fileName !== "test.js") {
stack.push("at " + el.fileName + ":" + el.lineNumber);
}
}
return stack;
}, []);
}; | Creates a stack trace and parses it for display.
@param {java.lang.StackTraceElement} trace Optional stacktrace to parse.
If undefined a stacktrace will be generated
@returns {String} The parsed stack trace | exports.getStackTrace | javascript | ringo/ringojs | modules/ringo/utils/test.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/test.js | Apache-2.0 |
exports.format = (number, fmt, locale) => {
const symbols = (locale != null) ?
new java.text.DecimalFormatSymbols(locale) :
new java.text.DecimalFormatSymbols();
const df = new java.text.DecimalFormat(fmt || "###,##0.##", symbols);
return df.format(+number);
}; | Format `number` using java.text.DecimalFormat.
@param {Number} number the number
@param {String} fmt the format to apply
@param {java.util.Locale} locale optional locale
@returns {String} the number formatted as string
@see <a href="http://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html">java.text.DecimalFormat</a>
@example >> const numbers = require('ringo/utils/numbers');
>> numbers.format(123, "#,###,##0.00"); // uses the default locale
'123.00'
>> numbers.format(123, "#,###,##0.00", java.util.Locale.GERMAN);
'123,00'
>> numbers.format(123, "#,###,##0.00", java.util.Locale.ENGLISH);
'123.00' | exports.format | javascript | ringo/ringojs | modules/ringo/utils/numbers.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/numbers.js | Apache-2.0 |
exports.times = (num, fun) => {
for (let i = 0; i < num; i++) {
fun(i);
}
}; | Invoke a function `num` times, passing 0 .. (this - 1) as argument.
@param {Number} num the number
@param {Function} fun the function to call
@example const numbers = require('ringo/utils/numbers');
numbers.times(5, function(i) {
console.log("#" + i);
}); | exports.times | javascript | ringo/ringojs | modules/ringo/utils/numbers.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/numbers.js | Apache-2.0 |
exports.supportsFileAttributeView = (attribute) => {
return FS.supportedFileAttributeViews().contains(attribute) === true;
}; | Checks if the default `FileSystem` supports the given file attribute view.
@param attribute the attribute to check
@return {boolean} true if the attribute is supported; false otherwise
@see <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/file/FileSystem.html#supportedFileAttributeViews--">Java File Attribute View</a> | exports.supportsFileAttributeView | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
const resolveUri = exports.resolveUri = function() {
let root = '';
let elements = [];
let leaf = '';
let path;
const SEPARATOR = '/';
const SEPARATOR_RE = /\//;
for (let i = 0; i < arguments.length; i++) {
path = String(arguments[i]);
if (path.trim() === '') {
continue;
}
let parts = path.split(SEPARATOR_RE);
if (path[0] === '/') {
// path is absolute, throw away everyting we have so far
root = parts.shift() + SEPARATOR;
elements = [];
}
leaf = parts.pop();
if (leaf === '.' || leaf === '..') {
parts.push(leaf);
leaf = '';
}
for (let j = 0; j < parts.length; j++) {
let part = parts[j];
if (part === '..') {
if (elements.length > 0 && arrays.peek(elements) !== '..') {
elements.pop();
} else if (!root) {
elements.push(part);
}
} else if (part !== '' && part !== '.') {
elements.push(part);
}
}
}
path = elements.join(SEPARATOR);
if (path.length > 0) {
leaf = SEPARATOR + leaf;
}
return root + path + leaf;
}; | Resolve an arbitrary number of path elements relative to each other.
This is an adapted version of the file module's resolve function that always
and strictly uses forward slashes as file separators. This makes it
usable for resolving URI paths as well as module ids and resource paths.
Originally adapted for helma/file from narwhal's file module.
@param {...} arbitrary number of path elements | exports.resolveUri ( ) | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
exports.resolveId = (parent, child) => {
// only paths starting with "." or ".." are relative according to module spec
const path = child.split("/");
if (path[0] === "." || path[0] === "..") {
// we support absolute paths for module ids. Since absolute
// paths are platform dependent, use the file module's version
// of resolve() for these instead of resolveUri().
return fs.isAbsolute(parent) ?
fs.resolve(parent, child) : resolveUri(parent, child);
}
// child is not relative according to module spec, return it as-is
return child;
}; | Resolve path fragment child relative to parent but only
if child is a a relative path according to the CommonJS Modules
spec, i.e. starts with "." or "..". Otherwise, the child path
is returned unchanged.
@param {String} parent the parent path
@param {String} child the child path | exports.resolveId | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
exports.isHidden = (file) => {
return Files.isHidden(getPath(file));
}; | Tests whether the file represented by this File object is a hidden file.
What constitutes a hidden file may depend on the platform we are running on.
@param {String} file
@returns {Boolean} true if this File object is hidden | exports.isHidden | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
exports.roots = (rootsIterator => {
const rootDirs = [];
while(rootsIterator.hasNext()) {
rootDirs.push(rootsIterator.next().toString());
}
return rootDirs;
})(FS.getRootDirectories().iterator()); | An Array containing the system's file system roots. On UNIX platforms
this contains a single "/" directory, while on Windows platforms this
contains an element for each mounted drive.
@type Array | (anonymous) | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
const octalDigitToSymbolic = function(octalPart) {
switch (octalPart) {
case 0: return "---";
case 1: return "--x";
case 2: return "-w-";
case 3: return "-wx";
case 4: return "r--";
case 5: return "r-x";
case 6: return "rw-";
case 7: return "rwx";
}
throw "Invalid permission number!";
}; | Internal use only!
Converts a octal digit into a string in symbolic notation.
@ignore | octalDigitToSymbolic ( octalPart ) | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
const symbolicToOctalDigit = function(stringPart) {
switch (stringPart) {
case "---": return 0;
case "--x": return 1;
case "-w-": return 2;
case "-wx": return 3;
case "r--": return 4;
case "r-x": return 5;
case "rw-": return 6;
case "rwx": return 7;
}
throw "Invalid POSIX string!";
}; | Internal use only!
Converts a symbolic notation string into an octal digit.
@ignore | symbolicToOctalDigit ( stringPart ) | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
const octalToSymbolicNotation = function(octal) {
return [
octalDigitToSymbolic(octal >> 6),
octalDigitToSymbolic((octal >> 3) & 0o0007),
octalDigitToSymbolic(octal & 0o0007)
].join("");
}; | Internal use only!
Converts octal number permissions into the symbolic representation.
@ignore | octalToSymbolicNotation ( octal ) | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
const symbolicToOctalNotation = function(symbolic) {
if (symbolic.length !== 9) {
throw "Invalid POSIX permission string: " + symbolic;
}
return (symbolicToOctalDigit(symbolic.substring(0,3)) << 6) +
(symbolicToOctalDigit(symbolic.substring(3,6)) << 3) +
symbolicToOctalDigit(symbolic.substring(6,9));
}; | Internal use only!
Converts symbolic represented permissions into the octal notation.
@ignore | symbolicToOctalNotation ( symbolic ) | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
const PosixPermissions = exports.PosixPermissions = function(permissions) {
if (!(this instanceof PosixPermissions)) {
return new PosixPermissions(permissions);
}
// internal holder of the value
let _octalValue;
Object.defineProperty(this, "value", {
configurable: false,
enumerable: true,
get: function() { return _octalValue; },
set: function(newValue) {
if (typeof newValue === "number") {
if (newValue < 0 || newValue > 0o0777) {
throw "Invalid numeric octal permission: " + newValue.toString(8);
}
_octalValue = newValue;
} else if (typeof newValue === "string") {
_octalValue = symbolicToOctalNotation(newValue);
} else if (newValue instanceof java.util.Set) {
_octalValue = enumToOctalNotation(newValue);
} else {
throw "Permissions need to be of type number or string!";
}
}
});
this.value = permissions;
this.toString = function() {
return "[PosixPermissions " + octalToSymbolicNotation(this.value) + "]";
};
return this;
} | This class holds POSIX file permissions and can be used to manipulate permissions on
POSIX-compatible systems with the Java NIO.2 API.
@param {Number|String|java.util.Set<PosixFilePermission>} permissions the POSIX permissions
@returns {PosixPermissions}
@constructor | exports.PosixPermissions ( permissions ) | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
PosixPermissions.prototype.toJavaFileAttribute = function() {
return PosixFilePermissions.asFileAttribute(
PosixFilePermissions.fromString(octalToSymbolicNotation(this.value))
);
}; | Returns a Java file attribute representing the POSIX permissions suitable for NIO.2 methods.
@returns {java.nio.file.attribute.FileAttribute} an object that encapsulates PosixFilePermissions | PosixPermissions.prototype.toJavaFileAttribute ( ) | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
PosixPermissions.prototype.toJavaPosixFilePermissionSet = function() {
return PosixFilePermissions.fromString(octalToSymbolicNotation(this.value));
}; | Returns a set of Java POSIX permissions suitable for NIO.2 methods.
@returns {java.util.Set<PosixFilePermission>} a set of permissions | PosixPermissions.prototype.toJavaPosixFilePermissionSet ( ) | javascript | ringo/ringojs | modules/ringo/utils/files.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/files.js | Apache-2.0 |
exports.format = (date, format, locale, timezone) => {
if (!format) {
return date.toString();
}
if (typeof locale == "string") {
locale = new java.util.Locale(locale);
}
if (typeof timezone == "string") {
timezone = java.util.TimeZone.getTimeZone(timezone);
}
const sdf = locale ? new java.text.SimpleDateFormat(format, locale) : new java.text.SimpleDateFormat(format);
if (timezone && timezone != sdf.getTimeZone()) {
sdf.setTimeZone(timezone);
}
return sdf.format(date);
}; | Format a Date to a string in a locale-sensitive manner.
For details on the format pattern, see
<a href="http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html">
java.text.SimpleDateFormat
</a>.
@param {Date} date the Date to format
@param {String} format the format pattern
@param {String|java.util.Locale} locale (optional) the locale as java Locale object or
lowercase two-letter ISO-639 code (e.g. "en")
@param {String|java.util.TimeZone} timezone (optional) the timezone as java TimeZone
object or an abbreviation such as "PST", a full name such as "America/Los_Angeles",
or a custom ID such as "GMT-8:00". If the id is not provided, the default timezone
is used. If the timezone id is provided but cannot be understood, the "GMT" timezone
is used.
@returns {String} the formatted Date
@see <a href="http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html">java.text.SimpleDateFormat</a>
@example const y2k = new Date(Date.UTC(2000, 0, 1));
// "year 2000"
dates.format(y2k, "'year' yyyy");
// "Samstag, Januar 1, '00"
dates.format(y2k, "EEEE, MMMM d, ''yy", "de");
// "1999-12-31"
dates.format(y2k, "yyyy-MM-dd", "de", "GMT-1");
// "2000-01-01 00:00:00 GMT-00:00"
dates.format(y2k, "yyyy-MM-dd HH:mm:ss z", "de", "GMT-0");
// "1999-12-31 14:00:00 GMT-10:00"
dates.format(y2k, "yyyy-MM-dd HH:mm:ss z", "de", "GMT-10"); | exports.format | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.checkDate = (fullYear, month, day) => {
if (fullYear == null || month == null || day == null) {
return false;
}
const d = new Date(fullYear, month, day);
return d.getFullYear() === fullYear && d.getMonth() === month && d.getDate() === day;
}; | Checks if the date is a valid date.
@example // 2007 is no leap year, so no 29th February
dates.checkDate(2007, 1, 29); // --> false
@param {Number} fullYear
@param {Number} month between 0 and 11
@param {Number} day between 1 and 31
@returns {Boolean} true, if the date is valid, false if not. | exports.checkDate | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.add = (date, delta, unit) => {
unit = (typeof unit === 'undefined') ? "day" : unit;
delta || (delta = 0);
const cal = createGregorianCalender(date);
switch (unit) {
case "year":
case "years":
cal.add(Calendar.YEAR, delta);
break;
case "quarter":
case "quarters":
cal.add(Calendar.MONTH, delta * 3);
break;
case "month":
case "months":
cal.add(Calendar.MONTH, delta);
break;
case "week":
case "weeks":
cal.add(Calendar.WEEK_OF_YEAR, delta);
break;
case "day":
case "days":
cal.add(Calendar.DATE, delta);
break;
case "hour":
case "hours":
cal.add(Calendar.HOUR_OF_DAY, delta);
break;
case "minute":
case "minutes":
cal.add(Calendar.MINUTE, delta);
break;
case "second":
case "seconds":
cal.add(Calendar.SECOND, delta);
break;
case "millisecond":
case "milliseconds":
return new Date(date.getTime() + delta);
default:
throw new Error("Invalid unit: " + unit);
}
return new Date(cal.getTimeInMillis());
}; | Adds delta to the given field or reduces it, if delta is negative. If larger fields are effected,
they will be changed accordingly.
@param {Date} date base date to add or remove time from.
@param {Number} delta amount of time to add (positive delta) or remove (negative delta).
@param {String} unit (optional) field to change. Possible values: <code>year</code>, <code>quarter</code>, <code>month</code>,
<code>week</code>, <code>day</code> (default), <code>hour</code> (24-hour clock), <code>minute</code>, <code>second</code>,
<code>millisecond</code>, and their respective plural form.
@returns {Date} date with the calculated date and time
@see <a href="http://docs.oracle.com/javase/8/docs/api/java/util/GregorianCalendar.html#add-int-int-">java.util.GregorianCalendar add()</a>
@example const d1 = new Date(Date.UTC(2016, 0, 1, 0, 0));
const d2 = dates.add(d1, 1, "hour");
dates.diff(d1, d2, "hours"); // --> 1 | exports.add | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
const isLeapYear = exports.isLeapYear = (date) => {
const year = date.getFullYear();
return year % 4 === 0 && (year % 100 !== 0 || (year % 400 === 0));
}; | Checks if the date's year is a leap year.
@param {Date} date to check year
@returns {Boolean} true if the year is a leap year, false if not. | exports.isLeapYear | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.before = (a, b) => {
return a.getTime() < b.getTime();
}; | Checks if date <code>a</code> is before date <code>b</code>. This is equals to <code>compareTo(a, b) < 0</code>
@param {Date} a first date
@param {Date} b second date
@returns {Boolean} true if <code>a</code> is before <code>b</code>, false if not. | exports.before | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.after = (a, b) => {
return a.getTime() > b.getTime();
}; | Checks if date <code>a</code> is after date <code>b</code>. This is equals to <code>compare(a, b) > 0</code>
@param {Date} a first date
@param {Date} b second date
@returns {Boolean} true if <code>a</code> is after <code>b</code>, false if not. | exports.after | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.compare = (a, b) => {
if (a.getTime() === b.getTime()) {
return 0;
} else if (a.getTime() < b.getTime()) {
return -1;
}
return 1;
}; | Compares the time values of <code>a</code> and <code>b</code>.
@param {Date} a first date
@param {Date} b second date
@returns {Number} -1 if <code>a</code> is before <code>b</code>, 0 if equals and 1 if <code>a</code> is after <code>b</code>.
@see <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#compareTo-java.util.Calendar-">java.util.Calendar compareTo()</a> | exports.compare | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.firstDayOfWeek = (locale) => {
const calendar = locale ? Calendar.getInstance(locale) : Calendar.getInstance();
return calendar.getFirstDayOfWeek();
}; | Gets the first day of the week.
@param {java.util.Locale} locale (optional) the locale as java Locale
@returns {Number} the first day of the week; 1 = Sunday, 2 = Monday.
@see <a href="http://docs.oracle.com/javase/8/docs/api/constant-values.html#java.util">java.util.Calendar constant field values</a> | exports.firstDayOfWeek | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.secondOfDay = (date) => {
return (date.getHours() * 3600) + (date.getMinutes() * 60) + date.getSeconds();
}; | Gets the second of the day for the given date.
@param {Date} date calculate the second of the day.
@returns {Number} second of the day | exports.secondOfDay | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.dayOfYear = (date) => {
return createGregorianCalender(date).get(Calendar.DAY_OF_YEAR);
}; | Gets the day of the year for the given date.
@param {Date} date calculate the day of the year.
@returns {Number} day of the year | exports.dayOfYear | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.weekOfMonth = (date, locale) => {
return createGregorianCalender(date, locale).get(Calendar.WEEK_OF_MONTH);
}; | Gets the week of the month for the given date.
@param {Date} date calculate the week of the month.
@param {java.util.Locale} locale (optional) the locale as java Locale
@returns {Number} week of the month | exports.weekOfMonth | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.weekOfYear = (date, locale) => {
return createGregorianCalender(date, locale).get(Calendar.WEEK_OF_YEAR);
}; | Gets the week of the year for the given date.
@param {Date} date calculate the week of the year.
@param {java.util.Locale} locale (optional) the locale as java Locale
@returns {Number} week of the year | exports.weekOfYear | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.yearInCentury = (date) => {
const year = date.getFullYear();
return year - (Math.floor(year / 100) * 100);
}; | Gets the year of the century for the given date.
@param {Date} date calculate the year of the century.
@returns {Number} second of the day
@example dates.yearInCentury(new Date(1900, 0, 1)); // --> 0
dates.yearInCentury(new Date(2016, 0, 1)); // --> 16 | exports.yearInCentury | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.daysInMonth = (date) => {
return createGregorianCalender(date).getActualMaximum(Calendar.DAY_OF_MONTH);
}; | Gets the number of the days in the month.
@param {Date} date to find the maximum number of days.
@returns {Number} days in the month, between 28 and 31. | exports.daysInMonth | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.daysInYear = (date) => {
return isLeapYear(date) ? 366 : 365;
}; | Gets the number of the days in the year.
@param {Date} date to find the maximum number of days.
@returns {Number} days in the year, 365 or 366, if it's a leap year. | exports.daysInYear | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.daysInFebruary = (date) => {
return isLeapYear(date) ? 29 : 28;
}; | Gets the number of the days in february.
@param {Date} date of year to find the number of days in february.
@returns {Number} days in the february, 28 or 29, if it's a leap year. | exports.daysInFebruary | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
const quarterInYear = exports.quarterInYear = (date) => {
switch (createGregorianCalender(date).get(Calendar.MONTH)) {
case Calendar.JANUARY:
case Calendar.FEBRUARY:
case Calendar.MARCH:
return 1;
case Calendar.APRIL :
case Calendar.MAY :
case Calendar.JUNE :
return 2;
case Calendar.JULY :
case Calendar.AUGUST :
case Calendar.SEPTEMBER :
return 3;
case Calendar.OCTOBER :
case Calendar.NOVEMBER :
case Calendar.DECEMBER :
return 4;
}
throw "Invalid date provided";
}; | Gets the quarter in the year.
@param {Date} date to calculate the quarter for.
@returns {Number} quarter of the year, between 1 and 4. | exports.quarterInYear | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.quarterInFiscalYear = (date, fiscalYearStart) => {
const firstDay = fiscalYearStart.getDate();
const firstMonth = fiscalYearStart.getMonth();
if (firstDay === 29 && firstMonth === 1) {
throw "Fiscal year cannot start on 29th february.";
}
let year = date.getFullYear();
// fiscal year starts in the year before the date
if (date.getMonth() < firstMonth ||
(date.getMonth() === firstMonth && date.getDate() < firstDay)) {
year --;
}
const currentFiscalYear = [
new Date(year, firstMonth, firstDay),
new Date(year, firstMonth + 3, firstDay),
new Date(year, firstMonth + 6, firstDay),
new Date(year, firstMonth + 9, firstDay),
new Date(year, firstMonth + 12, firstDay)
];
for (let i = 1; i <= 4; i++) {
if (inPeriod(date, currentFiscalYear[i-1], currentFiscalYear[i], false, true)) {
return i;
}
}
throw "Kudos! You found a bug, if you see this message. Report it!";
}; | Gets the quarter in the fiscal year.
@param {Date} date to calculate the quarter for.
@param {Date} fiscalYearStart first day in the fiscal year, default is the start of the current year
@returns {Number} quarter of the year, between 1 and 4.
@example // Farmers (grassland calendar starts with 1st May)
// returns 4th quarter
dates.quarterInFiscalYear(new Date(2016, 3, 30), new Date(0, 4, 1)); | exports.quarterInFiscalYear | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.overlapping = (aStart, aEnd, bStart, bEnd) => {
aStart = aStart.getTime();
aEnd = aEnd.getTime();
bStart = bStart.getTime();
bEnd = bEnd.getTime();
// A |----|
// B |----|
if (aStart >= bStart && aStart <= bEnd && aEnd >= bStart && aEnd >= bEnd) {
return true;
}
// A |----|
// B |----|
if (aStart <= bStart && aStart <= bEnd && aEnd >= bStart && aEnd <= bEnd) {
return true;
}
// A |-------|
// B |--|
if (aStart <= bStart && aStart <= bEnd && aEnd >= bStart && aEnd >= bEnd) {
return true;
}
// A |--|
// B |-------|
return aStart >= bStart && aStart <= bEnd && aEnd >= bStart && aEnd <= bEnd;
}; | Look if two periods are overlapping each other.
@param {Date} aStart first period's start
@param {Date} aEnd first period's end
@param {Date} bStart second period's start
@param {Date} bEnd second period's end
@returns {Boolean} true if the periods are overlapping at some point, false if not. | exports.overlapping | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
const inPeriod = exports.inPeriod = (date, periodStart, periodEnd, periodStartOpen, periodEndOpen) => {
const pStart = periodStart.getTime();
const pEnd = periodEnd.getTime();
const pStartOpen = periodStartOpen || false;
const pEndOpen = periodEndOpen || false;
const dateMillis = date.getTime();
if (!pStartOpen && !pEndOpen && pStart <= dateMillis && dateMillis <= pEnd) {
// period |-------|
// date ^
return true;
} else if (!pStartOpen && pEndOpen && pStart <= dateMillis && dateMillis < pEnd) {
// period |-------)
// date ^
return true;
} else if (pStartOpen && !pEndOpen && pStart < dateMillis && dateMillis <= pEnd) {
// period (-------|
// date ^
return true;
} else if (pStartOpen && pEndOpen && pStart < dateMillis && dateMillis < pEnd) {
// period (-------)
// date ^
return true;
}
return false;
} | Look if the date is in the period, using <em>periodStart <= date <= periodEnd</em>.
@param {Date} date to check, if it's in the period
@param {Date} periodStart the period's start
@param {Date} periodEnd the period's end
@param {Boolean} periodStartOpen start point is open - default false.
@param {Boolean} periodEndOpen end point is open - default false.
@returns {Boolean} true if the date is in the period, false if not. | exports.inPeriod | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.