id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
23,100
jillix/svg.connectable.js
example/js/svg.js
function(s, v) { if (arguments.length == 0) { // get full style return this.node.style.cssText || '' } else if (arguments.length < 2) { // apply every style individually if an object is passed if (typeof s == 'object') { for (v in s) this.style(v, s[v]) } else if (SVG.regex.isCss.test(s)) { // parse css string s = s.split(';') // apply every definition individually for (var i = 0; i < s.length; i++) { v = s[i].split(':') this.style(v[0].replace(/\s+/g, ''), v[1]) } } else { // act as a getter if the first and only argument is not an object return this.node.style[camelCase(s)] } } else { this.node.style[camelCase(s)] = v === null || SVG.regex.isBlank.test(v) ? '' : v } return this }
javascript
function(s, v) { if (arguments.length == 0) { // get full style return this.node.style.cssText || '' } else if (arguments.length < 2) { // apply every style individually if an object is passed if (typeof s == 'object') { for (v in s) this.style(v, s[v]) } else if (SVG.regex.isCss.test(s)) { // parse css string s = s.split(';') // apply every definition individually for (var i = 0; i < s.length; i++) { v = s[i].split(':') this.style(v[0].replace(/\s+/g, ''), v[1]) } } else { // act as a getter if the first and only argument is not an object return this.node.style[camelCase(s)] } } else { this.node.style[camelCase(s)] = v === null || SVG.regex.isBlank.test(v) ? '' : v } return this }
[ "function", "(", "s", ",", "v", ")", "{", "if", "(", "arguments", ".", "length", "==", "0", ")", "{", "// get full style", "return", "this", ".", "node", ".", "style", ".", "cssText", "||", "''", "}", "else", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "// apply every style individually if an object is passed", "if", "(", "typeof", "s", "==", "'object'", ")", "{", "for", "(", "v", "in", "s", ")", "this", ".", "style", "(", "v", ",", "s", "[", "v", "]", ")", "}", "else", "if", "(", "SVG", ".", "regex", ".", "isCss", ".", "test", "(", "s", ")", ")", "{", "// parse css string", "s", "=", "s", ".", "split", "(", "';'", ")", "// apply every definition individually", "for", "(", "var", "i", "=", "0", ";", "i", "<", "s", ".", "length", ";", "i", "++", ")", "{", "v", "=", "s", "[", "i", "]", ".", "split", "(", "':'", ")", "this", ".", "style", "(", "v", "[", "0", "]", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "''", ")", ",", "v", "[", "1", "]", ")", "}", "}", "else", "{", "// act as a getter if the first and only argument is not an object", "return", "this", ".", "node", ".", "style", "[", "camelCase", "(", "s", ")", "]", "}", "}", "else", "{", "this", ".", "node", ".", "style", "[", "camelCase", "(", "s", ")", "]", "=", "v", "===", "null", "||", "SVG", ".", "regex", ".", "isBlank", ".", "test", "(", "v", ")", "?", "''", ":", "v", "}", "return", "this", "}" ]
Dynamic style generator
[ "Dynamic", "style", "generator" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L2888-L2917
23,101
jillix/svg.connectable.js
example/js/svg.js
function() { return SVG.utils.map(SVG.utils.filterSVGElements(this.node.childNodes), function(node) { return SVG.adopt(node) }) }
javascript
function() { return SVG.utils.map(SVG.utils.filterSVGElements(this.node.childNodes), function(node) { return SVG.adopt(node) }) }
[ "function", "(", ")", "{", "return", "SVG", ".", "utils", ".", "map", "(", "SVG", ".", "utils", ".", "filterSVGElements", "(", "this", ".", "node", ".", "childNodes", ")", ",", "function", "(", "node", ")", "{", "return", "SVG", ".", "adopt", "(", "node", ")", "}", ")", "}" ]
Returns all child elements
[ "Returns", "all", "child", "elements" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L2931-L2935
23,102
jillix/svg.connectable.js
example/js/svg.js
function() { // unmask all targets for (var i = this.targets.length - 1; i >= 0; i--) if (this.targets[i]) this.targets[i].unmask() this.targets = [] // remove mask from parent this.parent().removeElement(this) return this }
javascript
function() { // unmask all targets for (var i = this.targets.length - 1; i >= 0; i--) if (this.targets[i]) this.targets[i].unmask() this.targets = [] // remove mask from parent this.parent().removeElement(this) return this }
[ "function", "(", ")", "{", "// unmask all targets", "for", "(", "var", "i", "=", "this", ".", "targets", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "if", "(", "this", ".", "targets", "[", "i", "]", ")", "this", ".", "targets", "[", "i", "]", ".", "unmask", "(", ")", "this", ".", "targets", "=", "[", "]", "// remove mask from parent", "this", ".", "parent", "(", ")", ".", "removeElement", "(", "this", ")", "return", "this", "}" ]
Unmask all masked elements and remove itself
[ "Unmask", "all", "masked", "elements", "and", "remove", "itself" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L3488-L3499
23,103
jillix/svg.connectable.js
example/js/svg.js
function(element) { // use given mask or create a new one this.masker = element instanceof SVG.Mask ? element : this.parent().mask().add(element) // store reverence on self in mask this.masker.targets.push(this) // apply mask return this.attr('mask', 'url("#' + this.masker.attr('id') + '")') }
javascript
function(element) { // use given mask or create a new one this.masker = element instanceof SVG.Mask ? element : this.parent().mask().add(element) // store reverence on self in mask this.masker.targets.push(this) // apply mask return this.attr('mask', 'url("#' + this.masker.attr('id') + '")') }
[ "function", "(", "element", ")", "{", "// use given mask or create a new one", "this", ".", "masker", "=", "element", "instanceof", "SVG", ".", "Mask", "?", "element", ":", "this", ".", "parent", "(", ")", ".", "mask", "(", ")", ".", "add", "(", "element", ")", "// store reverence on self in mask", "this", ".", "masker", ".", "targets", ".", "push", "(", "this", ")", "// apply mask", "return", "this", ".", "attr", "(", "'mask'", ",", "'url(\"#'", "+", "this", ".", "masker", ".", "attr", "(", "'id'", ")", "+", "'\")'", ")", "}" ]
Distribute mask to svg element
[ "Distribute", "mask", "to", "svg", "element" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L3514-L3523
23,104
jillix/svg.connectable.js
example/js/svg.js
function() { // unclip all targets for (var i = this.targets.length - 1; i >= 0; i--) if (this.targets[i]) this.targets[i].unclip() this.targets = [] // remove clipPath from parent this.parent().removeElement(this) return this }
javascript
function() { // unclip all targets for (var i = this.targets.length - 1; i >= 0; i--) if (this.targets[i]) this.targets[i].unclip() this.targets = [] // remove clipPath from parent this.parent().removeElement(this) return this }
[ "function", "(", ")", "{", "// unclip all targets", "for", "(", "var", "i", "=", "this", ".", "targets", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "if", "(", "this", ".", "targets", "[", "i", "]", ")", "this", ".", "targets", "[", "i", "]", ".", "unclip", "(", ")", "this", ".", "targets", "=", "[", "]", "// remove clipPath from parent", "this", ".", "parent", "(", ")", ".", "removeElement", "(", "this", ")", "return", "this", "}" ]
Unclip all clipped elements and remove itself
[ "Unclip", "all", "clipped", "elements", "and", "remove", "itself" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L3547-L3558
23,105
jillix/svg.connectable.js
example/js/svg.js
function(element) { // use given clip or create a new one this.clipper = element instanceof SVG.ClipPath ? element : this.parent().clip().add(element) // store reverence on self in mask this.clipper.targets.push(this) // apply mask return this.attr('clip-path', 'url("#' + this.clipper.attr('id') + '")') }
javascript
function(element) { // use given clip or create a new one this.clipper = element instanceof SVG.ClipPath ? element : this.parent().clip().add(element) // store reverence on self in mask this.clipper.targets.push(this) // apply mask return this.attr('clip-path', 'url("#' + this.clipper.attr('id') + '")') }
[ "function", "(", "element", ")", "{", "// use given clip or create a new one", "this", ".", "clipper", "=", "element", "instanceof", "SVG", ".", "ClipPath", "?", "element", ":", "this", ".", "parent", "(", ")", ".", "clip", "(", ")", ".", "add", "(", "element", ")", "// store reverence on self in mask", "this", ".", "clipper", ".", "targets", ".", "push", "(", "this", ")", "// apply mask", "return", "this", ".", "attr", "(", "'clip-path'", ",", "'url(\"#'", "+", "this", ".", "clipper", ".", "attr", "(", "'id'", ")", "+", "'\")'", ")", "}" ]
Distribute clipPath to svg element
[ "Distribute", "clipPath", "to", "svg", "element" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L3573-L3582
23,106
jillix/svg.connectable.js
example/js/svg.js
function(offset, color, opacity) { return this.put(new SVG.Stop).update(offset, color, opacity) }
javascript
function(offset, color, opacity) { return this.put(new SVG.Stop).update(offset, color, opacity) }
[ "function", "(", "offset", ",", "color", ",", "opacity", ")", "{", "return", "this", ".", "put", "(", "new", "SVG", ".", "Stop", ")", ".", "update", "(", "offset", ",", "color", ",", "opacity", ")", "}" ]
Add a color stop
[ "Add", "a", "color", "stop" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L3605-L3607
23,107
jillix/svg.connectable.js
example/js/svg.js
function(o) { if (typeof o == 'number' || o instanceof SVG.Number) { o = { offset: arguments[0] , color: arguments[1] , opacity: arguments[2] } } // set attributes if (o.opacity != null) this.attr('stop-opacity', o.opacity) if (o.color != null) this.attr('stop-color', o.color) if (o.offset != null) this.attr('offset', new SVG.Number(o.offset)) return this }
javascript
function(o) { if (typeof o == 'number' || o instanceof SVG.Number) { o = { offset: arguments[0] , color: arguments[1] , opacity: arguments[2] } } // set attributes if (o.opacity != null) this.attr('stop-opacity', o.opacity) if (o.color != null) this.attr('stop-color', o.color) if (o.offset != null) this.attr('offset', new SVG.Number(o.offset)) return this }
[ "function", "(", "o", ")", "{", "if", "(", "typeof", "o", "==", "'number'", "||", "o", "instanceof", "SVG", ".", "Number", ")", "{", "o", "=", "{", "offset", ":", "arguments", "[", "0", "]", ",", "color", ":", "arguments", "[", "1", "]", ",", "opacity", ":", "arguments", "[", "2", "]", "}", "}", "// set attributes", "if", "(", "o", ".", "opacity", "!=", "null", ")", "this", ".", "attr", "(", "'stop-opacity'", ",", "o", ".", "opacity", ")", "if", "(", "o", ".", "color", "!=", "null", ")", "this", ".", "attr", "(", "'stop-color'", ",", "o", ".", "color", ")", "if", "(", "o", ".", "offset", "!=", "null", ")", "this", ".", "attr", "(", "'offset'", ",", "new", "SVG", ".", "Number", "(", "o", ".", "offset", ")", ")", "return", "this", "}" ]
add color stops
[ "add", "color", "stops" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L3678-L3693
23,108
jillix/svg.connectable.js
example/js/svg.js
function(text) { // remove contents while (this.node.hasChildNodes()) this.node.removeChild(this.node.lastChild) // create text node this.node.appendChild(document.createTextNode(text)) return this }
javascript
function(text) { // remove contents while (this.node.hasChildNodes()) this.node.removeChild(this.node.lastChild) // create text node this.node.appendChild(document.createTextNode(text)) return this }
[ "function", "(", "text", ")", "{", "// remove contents", "while", "(", "this", ".", "node", ".", "hasChildNodes", "(", ")", ")", "this", ".", "node", ".", "removeChild", "(", "this", ".", "node", ".", "lastChild", ")", "// create text node", "this", ".", "node", ".", "appendChild", "(", "document", ".", "createTextNode", "(", "text", ")", ")", "return", "this", "}" ]
Insert some plain text
[ "Insert", "some", "plain", "text" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L3868-L3877
23,109
jillix/svg.connectable.js
example/js/svg.js
function(size) { return this.put(new SVG.Circle).rx(new SVG.Number(size).divide(2)).move(0, 0) }
javascript
function(size) { return this.put(new SVG.Circle).rx(new SVG.Number(size).divide(2)).move(0, 0) }
[ "function", "(", "size", ")", "{", "return", "this", ".", "put", "(", "new", "SVG", ".", "Circle", ")", ".", "rx", "(", "new", "SVG", ".", "Number", "(", "size", ")", ".", "divide", "(", "2", ")", ")", ".", "move", "(", "0", ",", "0", ")", "}" ]
Create circle element, based on ellipse
[ "Create", "circle", "element", "based", "on", "ellipse" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L3942-L3944
23,110
jillix/svg.connectable.js
example/js/svg.js
function(x1, y1, x2, y2) { return this.put(new SVG.Line).plot(x1, y1, x2, y2) }
javascript
function(x1, y1, x2, y2) { return this.put(new SVG.Line).plot(x1, y1, x2, y2) }
[ "function", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ")", "{", "return", "this", ".", "put", "(", "new", "SVG", ".", "Line", ")", ".", "plot", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ")", "}" ]
Create a line element
[ "Create", "a", "line", "element" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L4061-L4063
23,111
jillix/svg.connectable.js
example/js/svg.js
function(source, width, height) { return this.put(new SVG.Image).load(source).size(width || 0, height || width || 0) }
javascript
function(source, width, height) { return this.put(new SVG.Image).load(source).size(width || 0, height || width || 0) }
[ "function", "(", "source", ",", "width", ",", "height", ")", "{", "return", "this", ".", "put", "(", "new", "SVG", ".", "Image", ")", ".", "load", "(", "source", ")", ".", "size", "(", "width", "||", "0", ",", "height", "||", "width", "||", "0", ")", "}" ]
create image element, load image and set its size
[ "create", "image", "element", "load", "image", "and", "set", "its", "size" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L4254-L4256
23,112
jillix/svg.connectable.js
example/js/svg.js
function(text) { if(text == null) return this.node.textContent + (this.dom.newLined ? '\n' : '') typeof text === 'function' ? text.call(this, this) : this.plain(text) return this }
javascript
function(text) { if(text == null) return this.node.textContent + (this.dom.newLined ? '\n' : '') typeof text === 'function' ? text.call(this, this) : this.plain(text) return this }
[ "function", "(", "text", ")", "{", "if", "(", "text", "==", "null", ")", "return", "this", ".", "node", ".", "textContent", "+", "(", "this", ".", "dom", ".", "newLined", "?", "'\\n'", ":", "''", ")", "typeof", "text", "===", "'function'", "?", "text", ".", "call", "(", "this", ",", "this", ")", ":", "this", ".", "plain", "(", "text", ")", "return", "this", "}" ]
Set text content
[ "Set", "text", "content" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L4452-L4458
23,113
jillix/svg.connectable.js
example/js/svg.js
function(d) { // create textPath element var path = new SVG.TextPath , track = this.doc().defs().path(d) // move lines to textpath while (this.node.hasChildNodes()) path.node.appendChild(this.node.firstChild) // add textPath element as child node this.node.appendChild(path.node) // link textPath to path and add content path.attr('href', '#' + track, SVG.xlink) return this }
javascript
function(d) { // create textPath element var path = new SVG.TextPath , track = this.doc().defs().path(d) // move lines to textpath while (this.node.hasChildNodes()) path.node.appendChild(this.node.firstChild) // add textPath element as child node this.node.appendChild(path.node) // link textPath to path and add content path.attr('href', '#' + track, SVG.xlink) return this }
[ "function", "(", "d", ")", "{", "// create textPath element", "var", "path", "=", "new", "SVG", ".", "TextPath", ",", "track", "=", "this", ".", "doc", "(", ")", ".", "defs", "(", ")", ".", "path", "(", "d", ")", "// move lines to textpath", "while", "(", "this", ".", "node", ".", "hasChildNodes", "(", ")", ")", "path", ".", "node", ".", "appendChild", "(", "this", ".", "node", ".", "firstChild", ")", "// add textPath element as child node", "this", ".", "node", ".", "appendChild", "(", "path", ".", "node", ")", "// link textPath to path and add content", "path", ".", "attr", "(", "'href'", ",", "'#'", "+", "track", ",", "SVG", ".", "xlink", ")", "return", "this", "}" ]
Create path for text to run on
[ "Create", "path", "for", "text", "to", "run", "on" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L4537-L4553
23,114
jillix/svg.connectable.js
example/js/svg.js
function(url) { var link = new SVG.A if (typeof url == 'function') url.call(link, link) else link.to(url) return this.parent().put(link).put(this) }
javascript
function(url) { var link = new SVG.A if (typeof url == 'function') url.call(link, link) else link.to(url) return this.parent().put(link).put(this) }
[ "function", "(", "url", ")", "{", "var", "link", "=", "new", "SVG", ".", "A", "if", "(", "typeof", "url", "==", "'function'", ")", "url", ".", "call", "(", "link", ",", "link", ")", "else", "link", ".", "to", "(", "url", ")", "return", "this", ".", "parent", "(", ")", ".", "put", "(", "link", ")", ".", "put", "(", "this", ")", "}" ]
Create a hyperlink element
[ "Create", "a", "hyperlink", "element" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L4630-L4639
23,115
jillix/svg.connectable.js
example/js/svg.js
function(marker, width, height, block) { var attr = ['marker'] // Build attribute name if (marker != 'all') attr.push(marker) attr = attr.join('-') // Set marker attribute marker = arguments[1] instanceof SVG.Marker ? arguments[1] : this.doc().marker(width, height, block) return this.attr(attr, marker) }
javascript
function(marker, width, height, block) { var attr = ['marker'] // Build attribute name if (marker != 'all') attr.push(marker) attr = attr.join('-') // Set marker attribute marker = arguments[1] instanceof SVG.Marker ? arguments[1] : this.doc().marker(width, height, block) return this.attr(attr, marker) }
[ "function", "(", "marker", ",", "width", ",", "height", ",", "block", ")", "{", "var", "attr", "=", "[", "'marker'", "]", "// Build attribute name", "if", "(", "marker", "!=", "'all'", ")", "attr", ".", "push", "(", "marker", ")", "attr", "=", "attr", ".", "join", "(", "'-'", ")", "// Set marker attribute", "marker", "=", "arguments", "[", "1", "]", "instanceof", "SVG", ".", "Marker", "?", "arguments", "[", "1", "]", ":", "this", ".", "doc", "(", ")", ".", "marker", "(", "width", ",", "height", ",", "block", ")", "return", "this", ".", "attr", "(", "attr", ",", "marker", ")", "}" ]
Create and attach markers
[ "Create", "and", "attach", "markers" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L4706-L4719
23,116
jillix/svg.connectable.js
example/js/svg.js
function(d, cx, cy) { return this.transform({ rotation: d, cx: cx, cy: cy }) }
javascript
function(d, cx, cy) { return this.transform({ rotation: d, cx: cx, cy: cy }) }
[ "function", "(", "d", ",", "cx", ",", "cy", ")", "{", "return", "this", ".", "transform", "(", "{", "rotation", ":", "d", ",", "cx", ":", "cx", ",", "cy", ":", "cy", "}", ")", "}" ]
Map rotation to transform
[ "Map", "rotation", "to", "transform" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L4754-L4756
23,117
jillix/svg.connectable.js
example/js/svg.js
function(x, y) { var type = (this._target || this).type; return type == 'radial' || type == 'circle' ? this.attr('r', new SVG.Number(x)) : this.rx(x).ry(y == null ? x : y) }
javascript
function(x, y) { var type = (this._target || this).type; return type == 'radial' || type == 'circle' ? this.attr('r', new SVG.Number(x)) : this.rx(x).ry(y == null ? x : y) }
[ "function", "(", "x", ",", "y", ")", "{", "var", "type", "=", "(", "this", ".", "_target", "||", "this", ")", ".", "type", ";", "return", "type", "==", "'radial'", "||", "type", "==", "'circle'", "?", "this", ".", "attr", "(", "'r'", ",", "new", "SVG", ".", "Number", "(", "x", ")", ")", ":", "this", ".", "rx", "(", "x", ")", ".", "ry", "(", "y", "==", "null", "?", "x", ":", "y", ")", "}" ]
Add x and y radius
[ "Add", "x", "and", "y", "radius" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L4799-L4804
23,118
jillix/svg.connectable.js
example/js/svg.js
function() { var i, il, elements = [].slice.call(arguments) for (i = 0, il = elements.length; i < il; i++) this.members.push(elements[i]) return this }
javascript
function() { var i, il, elements = [].slice.call(arguments) for (i = 0, il = elements.length; i < il; i++) this.members.push(elements[i]) return this }
[ "function", "(", ")", "{", "var", "i", ",", "il", ",", "elements", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", "for", "(", "i", "=", "0", ",", "il", "=", "elements", ".", "length", ";", "i", "<", "il", ";", "i", "++", ")", "this", ".", "members", ".", "push", "(", "elements", "[", "i", "]", ")", "return", "this", "}" ]
Add element to set
[ "Add", "element", "to", "set" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L4845-L4852
23,119
jillix/svg.connectable.js
example/js/svg.js
function(a, v, r) { if (typeof a == 'object') { for (v in a) this.data(v, a[v]) } else if (arguments.length < 2) { try { return JSON.parse(this.attr('data-' + a)) } catch(e) { return this.attr('data-' + a) } } else { this.attr( 'data-' + a , v === null ? null : r === true || typeof v === 'string' || typeof v === 'number' ? v : JSON.stringify(v) ) } return this }
javascript
function(a, v, r) { if (typeof a == 'object') { for (v in a) this.data(v, a[v]) } else if (arguments.length < 2) { try { return JSON.parse(this.attr('data-' + a)) } catch(e) { return this.attr('data-' + a) } } else { this.attr( 'data-' + a , v === null ? null : r === true || typeof v === 'string' || typeof v === 'number' ? v : JSON.stringify(v) ) } return this }
[ "function", "(", "a", ",", "v", ",", "r", ")", "{", "if", "(", "typeof", "a", "==", "'object'", ")", "{", "for", "(", "v", "in", "a", ")", "this", ".", "data", "(", "v", ",", "a", "[", "v", "]", ")", "}", "else", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "try", "{", "return", "JSON", ".", "parse", "(", "this", ".", "attr", "(", "'data-'", "+", "a", ")", ")", "}", "catch", "(", "e", ")", "{", "return", "this", ".", "attr", "(", "'data-'", "+", "a", ")", "}", "}", "else", "{", "this", ".", "attr", "(", "'data-'", "+", "a", ",", "v", "===", "null", "?", "null", ":", "r", "===", "true", "||", "typeof", "v", "===", "'string'", "||", "typeof", "v", "===", "'number'", "?", "v", ":", "JSON", ".", "stringify", "(", "v", ")", ")", "}", "return", "this", "}" ]
Store data values on svg nodes
[ "Store", "data", "values", "on", "svg", "nodes" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L4992-L5016
23,120
jillix/svg.connectable.js
example/js/svg.js
function(k, v) { // remember every item in an object individually if (typeof arguments[0] == 'object') for (var v in k) this.remember(v, k[v]) // retrieve memory else if (arguments.length == 1) return this.memory()[k] // store memory else this.memory()[k] = v return this }
javascript
function(k, v) { // remember every item in an object individually if (typeof arguments[0] == 'object') for (var v in k) this.remember(v, k[v]) // retrieve memory else if (arguments.length == 1) return this.memory()[k] // store memory else this.memory()[k] = v return this }
[ "function", "(", "k", ",", "v", ")", "{", "// remember every item in an object individually", "if", "(", "typeof", "arguments", "[", "0", "]", "==", "'object'", ")", "for", "(", "var", "v", "in", "k", ")", "this", ".", "remember", "(", "v", ",", "k", "[", "v", "]", ")", "// retrieve memory", "else", "if", "(", "arguments", ".", "length", "==", "1", ")", "return", "this", ".", "memory", "(", ")", "[", "k", "]", "// store memory", "else", "this", ".", "memory", "(", ")", "[", "k", "]", "=", "v", "return", "this", "}" ]
Remember arbitrary data
[ "Remember", "arbitrary", "data" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5020-L5035
23,121
jillix/svg.connectable.js
example/js/svg.js
camelCase
function camelCase(s) { return s.toLowerCase().replace(/-(.)/g, function(m, g) { return g.toUpperCase() }) }
javascript
function camelCase(s) { return s.toLowerCase().replace(/-(.)/g, function(m, g) { return g.toUpperCase() }) }
[ "function", "camelCase", "(", "s", ")", "{", "return", "s", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "-(.)", "/", "g", ",", "function", "(", "m", ",", "g", ")", "{", "return", "g", ".", "toUpperCase", "(", ")", "}", ")", "}" ]
Convert dash-separated-string to camelCase
[ "Convert", "dash", "-", "separated", "-", "string", "to", "camelCase" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5086-L5090
23,122
jillix/svg.connectable.js
example/js/svg.js
fullHex
function fullHex(hex) { return hex.length == 4 ? [ '#', hex.substring(1, 2), hex.substring(1, 2) , hex.substring(2, 3), hex.substring(2, 3) , hex.substring(3, 4), hex.substring(3, 4) ].join('') : hex }
javascript
function fullHex(hex) { return hex.length == 4 ? [ '#', hex.substring(1, 2), hex.substring(1, 2) , hex.substring(2, 3), hex.substring(2, 3) , hex.substring(3, 4), hex.substring(3, 4) ].join('') : hex }
[ "function", "fullHex", "(", "hex", ")", "{", "return", "hex", ".", "length", "==", "4", "?", "[", "'#'", ",", "hex", ".", "substring", "(", "1", ",", "2", ")", ",", "hex", ".", "substring", "(", "1", ",", "2", ")", ",", "hex", ".", "substring", "(", "2", ",", "3", ")", ",", "hex", ".", "substring", "(", "2", ",", "3", ")", ",", "hex", ".", "substring", "(", "3", ",", "4", ")", ",", "hex", ".", "substring", "(", "3", ",", "4", ")", "]", ".", "join", "(", "''", ")", ":", "hex", "}" ]
Ensure to six-based hex
[ "Ensure", "to", "six", "-", "based", "hex" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5098-L5105
23,123
jillix/svg.connectable.js
example/js/svg.js
proportionalSize
function proportionalSize(box, width, height) { if (height == null) height = box.height / box.width * width else if (width == null) width = box.width / box.height * height return { width: width , height: height } }
javascript
function proportionalSize(box, width, height) { if (height == null) height = box.height / box.width * width else if (width == null) width = box.width / box.height * height return { width: width , height: height } }
[ "function", "proportionalSize", "(", "box", ",", "width", ",", "height", ")", "{", "if", "(", "height", "==", "null", ")", "height", "=", "box", ".", "height", "/", "box", ".", "width", "*", "width", "else", "if", "(", "width", "==", "null", ")", "width", "=", "box", ".", "width", "/", "box", ".", "height", "*", "height", "return", "{", "width", ":", "width", ",", "height", ":", "height", "}", "}" ]
Calculate proportional width and height values when necessary
[ "Calculate", "proportional", "width", "and", "height", "values", "when", "necessary" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5114-L5124
23,124
jillix/svg.connectable.js
example/js/svg.js
deltaTransformPoint
function deltaTransformPoint(matrix, x, y) { return { x: x * matrix.a + y * matrix.c + 0 , y: x * matrix.b + y * matrix.d + 0 } }
javascript
function deltaTransformPoint(matrix, x, y) { return { x: x * matrix.a + y * matrix.c + 0 , y: x * matrix.b + y * matrix.d + 0 } }
[ "function", "deltaTransformPoint", "(", "matrix", ",", "x", ",", "y", ")", "{", "return", "{", "x", ":", "x", "*", "matrix", ".", "a", "+", "y", "*", "matrix", ".", "c", "+", "0", ",", "y", ":", "x", "*", "matrix", ".", "b", "+", "y", "*", "matrix", ".", "d", "+", "0", "}", "}" ]
Delta transform point
[ "Delta", "transform", "point" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5127-L5132
23,125
jillix/svg.connectable.js
example/js/svg.js
parseMatrix
function parseMatrix(matrix) { if (!(matrix instanceof SVG.Matrix)) matrix = new SVG.Matrix(matrix) return matrix }
javascript
function parseMatrix(matrix) { if (!(matrix instanceof SVG.Matrix)) matrix = new SVG.Matrix(matrix) return matrix }
[ "function", "parseMatrix", "(", "matrix", ")", "{", "if", "(", "!", "(", "matrix", "instanceof", "SVG", ".", "Matrix", ")", ")", "matrix", "=", "new", "SVG", ".", "Matrix", "(", "matrix", ")", "return", "matrix", "}" ]
Parse matrix if required
[ "Parse", "matrix", "if", "required" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5140-L5145
23,126
jillix/svg.connectable.js
example/js/svg.js
ensureCentre
function ensureCentre(o, target) { o.cx = o.cx == null ? target.bbox().cx : o.cx o.cy = o.cy == null ? target.bbox().cy : o.cy }
javascript
function ensureCentre(o, target) { o.cx = o.cx == null ? target.bbox().cx : o.cx o.cy = o.cy == null ? target.bbox().cy : o.cy }
[ "function", "ensureCentre", "(", "o", ",", "target", ")", "{", "o", ".", "cx", "=", "o", ".", "cx", "==", "null", "?", "target", ".", "bbox", "(", ")", ".", "cx", ":", "o", ".", "cx", "o", ".", "cy", "=", "o", ".", "cy", "==", "null", "?", "target", ".", "bbox", "(", ")", ".", "cy", ":", "o", ".", "cy", "}" ]
Add centre point to transform object
[ "Add", "centre", "point", "to", "transform", "object" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5148-L5151
23,127
jillix/svg.connectable.js
example/js/svg.js
stringToMatrix
function stringToMatrix(source) { // remove matrix wrapper and split to individual numbers source = source .replace(SVG.regex.whitespace, '') .replace(SVG.regex.matrix, '') .split(SVG.regex.matrixElements) // convert string values to floats and convert to a matrix-formatted object return arrayToMatrix( SVG.utils.map(source, function(n) { return parseFloat(n) }) ) }
javascript
function stringToMatrix(source) { // remove matrix wrapper and split to individual numbers source = source .replace(SVG.regex.whitespace, '') .replace(SVG.regex.matrix, '') .split(SVG.regex.matrixElements) // convert string values to floats and convert to a matrix-formatted object return arrayToMatrix( SVG.utils.map(source, function(n) { return parseFloat(n) }) ) }
[ "function", "stringToMatrix", "(", "source", ")", "{", "// remove matrix wrapper and split to individual numbers", "source", "=", "source", ".", "replace", "(", "SVG", ".", "regex", ".", "whitespace", ",", "''", ")", ".", "replace", "(", "SVG", ".", "regex", ".", "matrix", ",", "''", ")", ".", "split", "(", "SVG", ".", "regex", ".", "matrixElements", ")", "// convert string values to floats and convert to a matrix-formatted object", "return", "arrayToMatrix", "(", "SVG", ".", "utils", ".", "map", "(", "source", ",", "function", "(", "n", ")", "{", "return", "parseFloat", "(", "n", ")", "}", ")", ")", "}" ]
Convert string to matrix
[ "Convert", "string", "to", "matrix" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5154-L5167
23,128
jillix/svg.connectable.js
example/js/svg.js
at
function at(o, pos) { // number recalculation (don't bother converting to SVG.Number for performance reasons) return typeof o.from == 'number' ? o.from + (o.to - o.from) * pos : // instance recalculation o instanceof SVG.Color || o instanceof SVG.Number || o instanceof SVG.Matrix ? o.at(pos) : // for all other values wait until pos has reached 1 to return the final value pos < 1 ? o.from : o.to }
javascript
function at(o, pos) { // number recalculation (don't bother converting to SVG.Number for performance reasons) return typeof o.from == 'number' ? o.from + (o.to - o.from) * pos : // instance recalculation o instanceof SVG.Color || o instanceof SVG.Number || o instanceof SVG.Matrix ? o.at(pos) : // for all other values wait until pos has reached 1 to return the final value pos < 1 ? o.from : o.to }
[ "function", "at", "(", "o", ",", "pos", ")", "{", "// number recalculation (don't bother converting to SVG.Number for performance reasons)", "return", "typeof", "o", ".", "from", "==", "'number'", "?", "o", ".", "from", "+", "(", "o", ".", "to", "-", "o", ".", "from", ")", "*", "pos", ":", "// instance recalculation", "o", "instanceof", "SVG", ".", "Color", "||", "o", "instanceof", "SVG", ".", "Number", "||", "o", "instanceof", "SVG", ".", "Matrix", "?", "o", ".", "at", "(", "pos", ")", ":", "// for all other values wait until pos has reached 1 to return the final value", "pos", "<", "1", "?", "o", ".", "from", ":", "o", ".", "to", "}" ]
Calculate position according to from and to
[ "Calculate", "position", "according", "to", "from", "and", "to" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5170-L5180
23,129
jillix/svg.connectable.js
example/js/svg.js
assignNewId
function assignNewId(node) { // do the same for SVG child nodes as well for (var i = node.childNodes.length - 1; i >= 0; i--) if (node.childNodes[i] instanceof SVGElement) assignNewId(node.childNodes[i]) return SVG.adopt(node).id(SVG.eid(node.nodeName)) }
javascript
function assignNewId(node) { // do the same for SVG child nodes as well for (var i = node.childNodes.length - 1; i >= 0; i--) if (node.childNodes[i] instanceof SVGElement) assignNewId(node.childNodes[i]) return SVG.adopt(node).id(SVG.eid(node.nodeName)) }
[ "function", "assignNewId", "(", "node", ")", "{", "// do the same for SVG child nodes as well", "for", "(", "var", "i", "=", "node", ".", "childNodes", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "if", "(", "node", ".", "childNodes", "[", "i", "]", "instanceof", "SVGElement", ")", "assignNewId", "(", "node", ".", "childNodes", "[", "i", "]", ")", "return", "SVG", ".", "adopt", "(", "node", ")", ".", "id", "(", "SVG", ".", "eid", "(", "node", ".", "nodeName", ")", ")", "}" ]
Deep new id assignment
[ "Deep", "new", "id", "assignment" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5220-L5227
23,130
jillix/svg.connectable.js
example/js/svg.js
fullBox
function fullBox(b) { if (b.x == null) { b.x = 0 b.y = 0 b.width = 0 b.height = 0 } b.w = b.width b.h = b.height b.x2 = b.x + b.width b.y2 = b.y + b.height b.cx = b.x + b.width / 2 b.cy = b.y + b.height / 2 return b }
javascript
function fullBox(b) { if (b.x == null) { b.x = 0 b.y = 0 b.width = 0 b.height = 0 } b.w = b.width b.h = b.height b.x2 = b.x + b.width b.y2 = b.y + b.height b.cx = b.x + b.width / 2 b.cy = b.y + b.height / 2 return b }
[ "function", "fullBox", "(", "b", ")", "{", "if", "(", "b", ".", "x", "==", "null", ")", "{", "b", ".", "x", "=", "0", "b", ".", "y", "=", "0", "b", ".", "width", "=", "0", "b", ".", "height", "=", "0", "}", "b", ".", "w", "=", "b", ".", "width", "b", ".", "h", "=", "b", ".", "height", "b", ".", "x2", "=", "b", ".", "x", "+", "b", ".", "width", "b", ".", "y2", "=", "b", ".", "y", "+", "b", ".", "height", "b", ".", "cx", "=", "b", ".", "x", "+", "b", ".", "width", "/", "2", "b", ".", "cy", "=", "b", ".", "y", "+", "b", ".", "height", "/", "2", "return", "b", "}" ]
Add more bounding box properties
[ "Add", "more", "bounding", "box", "properties" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5230-L5246
23,131
jillix/svg.connectable.js
example/js/svg.js
idFromReference
function idFromReference(url) { var m = url.toString().match(SVG.regex.reference) if (m) return m[1] }
javascript
function idFromReference(url) { var m = url.toString().match(SVG.regex.reference) if (m) return m[1] }
[ "function", "idFromReference", "(", "url", ")", "{", "var", "m", "=", "url", ".", "toString", "(", ")", ".", "match", "(", "SVG", ".", "regex", ".", "reference", ")", "if", "(", "m", ")", "return", "m", "[", "1", "]", "}" ]
Get id from reference string
[ "Get", "id", "from", "reference", "string" ]
279b5a44112b99e777462650514ec1332ea5d202
https://github.com/jillix/svg.connectable.js/blob/279b5a44112b99e777462650514ec1332ea5d202/example/js/svg.js#L5249-L5253
23,132
jf3096/json-typescript-mapper
index.js
serializeProperty
function serializeProperty(metadata, prop) { if (!metadata || metadata.excludeToJson === true) { return; } if (metadata.customConverter) { return metadata.customConverter.toJson(prop); } if (!metadata.clazz) { return prop; } if (utils_1.isArrayOrArrayClass(prop)) { return prop.map(function (propItem) { return serialize(propItem); }); } return serialize(prop); }
javascript
function serializeProperty(metadata, prop) { if (!metadata || metadata.excludeToJson === true) { return; } if (metadata.customConverter) { return metadata.customConverter.toJson(prop); } if (!metadata.clazz) { return prop; } if (utils_1.isArrayOrArrayClass(prop)) { return prop.map(function (propItem) { return serialize(propItem); }); } return serialize(prop); }
[ "function", "serializeProperty", "(", "metadata", ",", "prop", ")", "{", "if", "(", "!", "metadata", "||", "metadata", ".", "excludeToJson", "===", "true", ")", "{", "return", ";", "}", "if", "(", "metadata", ".", "customConverter", ")", "{", "return", "metadata", ".", "customConverter", ".", "toJson", "(", "prop", ")", ";", "}", "if", "(", "!", "metadata", ".", "clazz", ")", "{", "return", "prop", ";", "}", "if", "(", "utils_1", ".", "isArrayOrArrayClass", "(", "prop", ")", ")", "{", "return", "prop", ".", "map", "(", "function", "(", "propItem", ")", "{", "return", "serialize", "(", "propItem", ")", ";", "}", ")", ";", "}", "return", "serialize", "(", "prop", ")", ";", "}" ]
Prepare a single property to be serialized to JSON. @param metadata @param prop @returns {any}
[ "Prepare", "a", "single", "property", "to", "be", "serialized", "to", "JSON", "." ]
20c715fa8d58df810fa06dd306ff97442134db51
https://github.com/jf3096/json-typescript-mapper/blob/20c715fa8d58df810fa06dd306ff97442134db51/index.js#L177-L191
23,133
QBisConsult/psql-api
webroot/pages/assets/js/script.js
goTo
function goTo(hash,changehash){ win.unbind('hashchange', hashchange); hash = hash.replace(/!\//,''); win.stop().scrollTo(hash,duration,{ easing:easing, axis:'y' }); if(changehash !== false){ var l = location; location.href = (l.protocol+'//'+l.host+l.pathname+'#!/'+hash.substr(1)); } win.bind('hashchange', hashchange); }
javascript
function goTo(hash,changehash){ win.unbind('hashchange', hashchange); hash = hash.replace(/!\//,''); win.stop().scrollTo(hash,duration,{ easing:easing, axis:'y' }); if(changehash !== false){ var l = location; location.href = (l.protocol+'//'+l.host+l.pathname+'#!/'+hash.substr(1)); } win.bind('hashchange', hashchange); }
[ "function", "goTo", "(", "hash", ",", "changehash", ")", "{", "win", ".", "unbind", "(", "'hashchange'", ",", "hashchange", ")", ";", "hash", "=", "hash", ".", "replace", "(", "/", "!\\/", "/", ",", "''", ")", ";", "win", ".", "stop", "(", ")", ".", "scrollTo", "(", "hash", ",", "duration", ",", "{", "easing", ":", "easing", ",", "axis", ":", "'y'", "}", ")", ";", "if", "(", "changehash", "!==", "false", ")", "{", "var", "l", "=", "location", ";", "location", ".", "href", "=", "(", "l", ".", "protocol", "+", "'//'", "+", "l", ".", "host", "+", "l", ".", "pathname", "+", "'#!/'", "+", "hash", ".", "substr", "(", "1", ")", ")", ";", "}", "win", ".", "bind", "(", "'hashchange'", ",", "hashchange", ")", ";", "}" ]
scroll to a section and set the hash
[ "scroll", "to", "a", "section", "and", "set", "the", "hash" ]
d9a4f32663e9533b13a4e28d2fffa7a3d35e4e12
https://github.com/QBisConsult/psql-api/blob/d9a4f32663e9533b13a4e28d2fffa7a3d35e4e12/webroot/pages/assets/js/script.js#L111-L123
23,134
QBisConsult/psql-api
webroot/pages/assets/js/script.js
activateNav
function activateNav(pos){ var offset = 100, current, next, parent, isSub, hasSub; win.unbind('hashchange', hashchange); for(var i=sectionscount;i>0;i--){ if(sections[i-1].pos <= pos+offset){ navanchors.removeClass('current'); current = navanchors.eq(i-1); current.addClass('current'); parent = current.parent().parent(); next = current.next(); hasSub = next.is('ul'); isSub = !parent.is('#documenter_nav'); nav.find('ol:visible').not(parent).slideUp('fast'); if(isSub){ parent.prev().addClass('current'); parent.stop().slideDown('fast'); }else if(hasSub){ next.stop().slideDown('fast'); } win.bind('hashchange', hashchange); break; }; } }
javascript
function activateNav(pos){ var offset = 100, current, next, parent, isSub, hasSub; win.unbind('hashchange', hashchange); for(var i=sectionscount;i>0;i--){ if(sections[i-1].pos <= pos+offset){ navanchors.removeClass('current'); current = navanchors.eq(i-1); current.addClass('current'); parent = current.parent().parent(); next = current.next(); hasSub = next.is('ul'); isSub = !parent.is('#documenter_nav'); nav.find('ol:visible').not(parent).slideUp('fast'); if(isSub){ parent.prev().addClass('current'); parent.stop().slideDown('fast'); }else if(hasSub){ next.stop().slideDown('fast'); } win.bind('hashchange', hashchange); break; }; } }
[ "function", "activateNav", "(", "pos", ")", "{", "var", "offset", "=", "100", ",", "current", ",", "next", ",", "parent", ",", "isSub", ",", "hasSub", ";", "win", ".", "unbind", "(", "'hashchange'", ",", "hashchange", ")", ";", "for", "(", "var", "i", "=", "sectionscount", ";", "i", ">", "0", ";", "i", "--", ")", "{", "if", "(", "sections", "[", "i", "-", "1", "]", ".", "pos", "<=", "pos", "+", "offset", ")", "{", "navanchors", ".", "removeClass", "(", "'current'", ")", ";", "current", "=", "navanchors", ".", "eq", "(", "i", "-", "1", ")", ";", "current", ".", "addClass", "(", "'current'", ")", ";", "parent", "=", "current", ".", "parent", "(", ")", ".", "parent", "(", ")", ";", "next", "=", "current", ".", "next", "(", ")", ";", "hasSub", "=", "next", ".", "is", "(", "'ul'", ")", ";", "isSub", "=", "!", "parent", ".", "is", "(", "'#documenter_nav'", ")", ";", "nav", ".", "find", "(", "'ol:visible'", ")", ".", "not", "(", "parent", ")", ".", "slideUp", "(", "'fast'", ")", ";", "if", "(", "isSub", ")", "{", "parent", ".", "prev", "(", ")", ".", "addClass", "(", "'current'", ")", ";", "parent", ".", "stop", "(", ")", ".", "slideDown", "(", "'fast'", ")", ";", "}", "else", "if", "(", "hasSub", ")", "{", "next", ".", "stop", "(", ")", ".", "slideDown", "(", "'fast'", ")", ";", "}", "win", ".", "bind", "(", "'hashchange'", ",", "hashchange", ")", ";", "break", ";", "}", ";", "}", "}" ]
activate current nav element
[ "activate", "current", "nav", "element" ]
d9a4f32663e9533b13a4e28d2fffa7a3d35e4e12
https://github.com/QBisConsult/psql-api/blob/d9a4f32663e9533b13a4e28d2fffa7a3d35e4e12/webroot/pages/assets/js/script.js#L127-L154
23,135
EclairJS/eclairjs
server/src/main/resources/eclairjs/ml/param/ParamPair.js
function (param, value) { var jvmObject; if (arguments[0] instanceof org.apache.spark.ml.param.ParamPair) { jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.ml.param.ParamPair(param, value); } this.logger = Logger.getLogger("ParamPair_js"); JavaWrapper.call(this, jvmObject); }
javascript
function (param, value) { var jvmObject; if (arguments[0] instanceof org.apache.spark.ml.param.ParamPair) { jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.ml.param.ParamPair(param, value); } this.logger = Logger.getLogger("ParamPair_js"); JavaWrapper.call(this, jvmObject); }
[ "function", "(", "param", ",", "value", ")", "{", "var", "jvmObject", ";", "if", "(", "arguments", "[", "0", "]", "instanceof", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamPair", ")", "{", "jvmObject", "=", "arguments", "[", "0", "]", ";", "}", "else", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamPair", "(", "param", ",", "value", ")", ";", "}", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"ParamPair_js\"", ")", ";", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
A param and its value. @classdesc @param {module:eclairjs/ml/param.Param} param @param {object} value @class @memberof module:eclairjs/ml/param
[ "A", "param", "and", "its", "value", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/ml/param/ParamPair.js#L31-L41
23,136
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/linalg/distributed/RowMatrix.js
function(rows,nRows,nCols) { this.logger = Logger.getLogger("RowMatrix_js"); var jvmObject; if (arguments[0] instanceof org.apache.spark.mllib.linalg.distributed.RowMatrix) { jvmObject = arguments[0]; } else if (arguments.length === 3) { jvmObject = new org.apache.spark.mllib.linalg.distributed.RowMatrix(Utils.unwrapObject(rows).rdd(),nRows,nCols); } else { jvmObject = new org.apache.spark.mllib.linalg.distributed.RowMatrix(Utils.unwrapObject(rows).rdd()); } DistributedMatrix.call(this, jvmObject); }
javascript
function(rows,nRows,nCols) { this.logger = Logger.getLogger("RowMatrix_js"); var jvmObject; if (arguments[0] instanceof org.apache.spark.mllib.linalg.distributed.RowMatrix) { jvmObject = arguments[0]; } else if (arguments.length === 3) { jvmObject = new org.apache.spark.mllib.linalg.distributed.RowMatrix(Utils.unwrapObject(rows).rdd(),nRows,nCols); } else { jvmObject = new org.apache.spark.mllib.linalg.distributed.RowMatrix(Utils.unwrapObject(rows).rdd()); } DistributedMatrix.call(this, jvmObject); }
[ "function", "(", "rows", ",", "nRows", ",", "nCols", ")", "{", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"RowMatrix_js\"", ")", ";", "var", "jvmObject", ";", "if", "(", "arguments", "[", "0", "]", "instanceof", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "linalg", ".", "distributed", ".", "RowMatrix", ")", "{", "jvmObject", "=", "arguments", "[", "0", "]", ";", "}", "else", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "linalg", ".", "distributed", ".", "RowMatrix", "(", "Utils", ".", "unwrapObject", "(", "rows", ")", ".", "rdd", "(", ")", ",", "nRows", ",", "nCols", ")", ";", "}", "else", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "linalg", ".", "distributed", ".", "RowMatrix", "(", "Utils", ".", "unwrapObject", "(", "rows", ")", ".", "rdd", "(", ")", ")", ";", "}", "DistributedMatrix", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
Represents a row-oriented distributed Matrix with no meaningful row indices. @memberof module:eclairjs/mllib/linalg/distributed @classdesc @param {module:eclairjs.RDD} rows stored as an RDD[Vector] @param {number} [nRows] number of rows. A non-positive value means unknown, and then the number of rows will be determined by the number of records in the RDD `rows`. @param {number} [nCols] number of columns. A non-positive value means unknown, and then the number of columns will be determined by the size of the first row. @class @extends module:eclairjs/mllib/linalg/distributed.DistributedMatrix @example var RowMatrix = require('eclairjs/mllib/linalg/distributed/RowMatrix'); var Vectors = require("'eclairjs/mllib/linalg/Vectors");; var rowsList = [Vectors.dense([1.12, 2.05, 3.12]), Vectors.dense([5.56, 6.28, 8.94]), Vectors.dense([10.2, 8.0, 20.5])]; var rows = sc.parallelize(rowsList); var mat = new RowMatrix(rows);
[ "Represents", "a", "row", "-", "oriented", "distributed", "Matrix", "with", "no", "meaningful", "row", "indices", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/linalg/distributed/RowMatrix.js#L41-L55
23,137
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/optimization/Gradient.js
function () { this.logger = Logger.getLogger("Gradient_js"); var jvmObject; if (arguments[0] instanceof org.apache.spark.mllib.optimization.Gradient) { jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.mllib.optimization.Gradient(); } JavaWrapper.call(this, jvmObject); }
javascript
function () { this.logger = Logger.getLogger("Gradient_js"); var jvmObject; if (arguments[0] instanceof org.apache.spark.mllib.optimization.Gradient) { jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.mllib.optimization.Gradient(); } JavaWrapper.call(this, jvmObject); }
[ "function", "(", ")", "{", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"Gradient_js\"", ")", ";", "var", "jvmObject", ";", "if", "(", "arguments", "[", "0", "]", "instanceof", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "optimization", ".", "Gradient", ")", "{", "jvmObject", "=", "arguments", "[", "0", "]", ";", "}", "else", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "optimization", ".", "Gradient", "(", ")", ";", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
Class used to compute the gradient for a loss function, given a single data point. @class @memberof module:eclairjs/mllib/optimization @constructor
[ "Class", "used", "to", "compute", "the", "gradient", "for", "a", "loss", "function", "given", "a", "single", "data", "point", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/optimization/Gradient.js#L28-L39
23,138
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/clustering/KMeansModel.js
function (clusterCenters) { var jvmObject; if (clusterCenters instanceof org.apache.spark.mllib.clustering.KMeansModel) { jvmObject = clusterCenters; } else { jvmObject = new org.apache.spark.mllib.clustering.KMeansModel(clusterCenters); } this.logger = Logger.getLogger("KMeansModel_js"); JavaWrapper.call(this, jvmObject); }
javascript
function (clusterCenters) { var jvmObject; if (clusterCenters instanceof org.apache.spark.mllib.clustering.KMeansModel) { jvmObject = clusterCenters; } else { jvmObject = new org.apache.spark.mllib.clustering.KMeansModel(clusterCenters); } this.logger = Logger.getLogger("KMeansModel_js"); JavaWrapper.call(this, jvmObject); }
[ "function", "(", "clusterCenters", ")", "{", "var", "jvmObject", ";", "if", "(", "clusterCenters", "instanceof", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "clustering", ".", "KMeansModel", ")", "{", "jvmObject", "=", "clusterCenters", ";", "}", "else", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "clustering", ".", "KMeansModel", "(", "clusterCenters", ")", ";", "}", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"KMeansModel_js\"", ")", ";", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
A clustering model for K-means. Each point belongs to the cluster with the closest center. @classdesc A Java-friendly constructor that takes an Iterable of Vectors. @param {@module:eclairjs/mllib/linalg.Vector[]} clusterCenters @returns {??} @memberof module:eclairjs/mllib/clustering @class
[ "A", "clustering", "model", "for", "K", "-", "means", ".", "Each", "point", "belongs", "to", "the", "cluster", "with", "the", "closest", "center", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/clustering/KMeansModel.js#L35-L46
23,139
EclairJS/eclairjs
server/src/main/resources/eclairjs/Accumulable.js
function () { var jvmObject; if (arguments.length == 1) { jvmObject = arguments[0]; } else { var value = arguments[0]; this._accumulableParam = arguments[1]; if (arguments[1] instanceof FloatAccumulatorParam) { value = parseFloat(value); } else if (arguments[1] instanceof IntAccumulatorParam) { value = new java.lang.Integer(parseInt(value)); // we need to create a Integer or we will get a java.lang.Double } var accumulableParam_uw = Utils.unwrapObject(arguments[1]); jvmObject = new org.apache.spark.Accumulable(value, accumulableParam_uw); } JavaWrapper.call(this, jvmObject); }
javascript
function () { var jvmObject; if (arguments.length == 1) { jvmObject = arguments[0]; } else { var value = arguments[0]; this._accumulableParam = arguments[1]; if (arguments[1] instanceof FloatAccumulatorParam) { value = parseFloat(value); } else if (arguments[1] instanceof IntAccumulatorParam) { value = new java.lang.Integer(parseInt(value)); // we need to create a Integer or we will get a java.lang.Double } var accumulableParam_uw = Utils.unwrapObject(arguments[1]); jvmObject = new org.apache.spark.Accumulable(value, accumulableParam_uw); } JavaWrapper.call(this, jvmObject); }
[ "function", "(", ")", "{", "var", "jvmObject", ";", "if", "(", "arguments", ".", "length", "==", "1", ")", "{", "jvmObject", "=", "arguments", "[", "0", "]", ";", "}", "else", "{", "var", "value", "=", "arguments", "[", "0", "]", ";", "this", ".", "_accumulableParam", "=", "arguments", "[", "1", "]", ";", "if", "(", "arguments", "[", "1", "]", "instanceof", "FloatAccumulatorParam", ")", "{", "value", "=", "parseFloat", "(", "value", ")", ";", "}", "else", "if", "(", "arguments", "[", "1", "]", "instanceof", "IntAccumulatorParam", ")", "{", "value", "=", "new", "java", ".", "lang", ".", "Integer", "(", "parseInt", "(", "value", ")", ")", ";", "// we need to create a Integer or we will get a java.lang.Double", "}", "var", "accumulableParam_uw", "=", "Utils", ".", "unwrapObject", "(", "arguments", "[", "1", "]", ")", ";", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "Accumulable", "(", "value", ",", "accumulableParam_uw", ")", ";", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
A data type that can be accumulated, ie has an commutative and associative "add" operation, but where the result type, `R`, may be different from the element type being added, `T`. You must define how to add data, and how to merge two of these together. For some data types, such as a counter, these might be the same operation. In that case, you can use the simpler {@link Accumulator}. They won't always be the same, though -- e.g., imagine you are accumulating a set. You will add items to the set, and you will union two sets together. @classdesc @constructor @memberof module:eclairjs @param {object} initialValue initial value of accumulator @param {module:eclairjs.AccumulableParam} param helper object defining how to add elements /* NOTE for now EclairJS will only support floats and int types
[ "A", "data", "type", "that", "can", "be", "accumulated", "ie", "has", "an", "commutative", "and", "associative", "add", "operation", "but", "where", "the", "result", "type", "R", "may", "be", "different", "from", "the", "element", "type", "being", "added", "T", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/Accumulable.js#L47-L65
23,140
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/recommendation/ALS.js
function (jvmObject) { this.logger = Logger.getLogger("mllib_recommendation_ALS_js"); if (!jvmObject) { jvmObject = new org.apache.spark.mllib.recommendation.ALS(); } JavaWrapper.call(this, jvmObject); }
javascript
function (jvmObject) { this.logger = Logger.getLogger("mllib_recommendation_ALS_js"); if (!jvmObject) { jvmObject = new org.apache.spark.mllib.recommendation.ALS(); } JavaWrapper.call(this, jvmObject); }
[ "function", "(", "jvmObject", ")", "{", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"mllib_recommendation_ALS_js\"", ")", ";", "if", "(", "!", "jvmObject", ")", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "recommendation", ".", "ALS", "(", ")", ";", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
Alternating Least Squares matrix factorization. ALS attempts to estimate the ratings matrix `R` as the product of two lower-rank matrices, `X` and `Y`, i.e. `X * Yt = R`. Typically these approximations are called 'factor' matrices. The general approach is iterative. During each iteration, one of the factor matrices is held constant, while the other is solved for using least squares. The newly-solved factor matrix is then held constant while solving for the other factor matrix. This is a blocked implementation of the ALS factorization algorithm that groups the two sets of factors (referred to as "users" and "products") into blocks and reduces communication by only sending one copy of each user vector to each product block on each iteration, and only for the product blocks that need that user's feature vector. This is achieved by precomputing some information about the ratings matrix to determine the "out-links" of each user (which blocks of products it will contribute to) and "in-link" information for each product (which of the feature vectors it receives from each user block it will depend on). This allows us to send only an array of feature vectors between each user block and product block, and have the product block find the users' ratings and update the products based on these messages. For implicit preference data, the algorithm used is based on "Collaborative Filtering for Implicit Feedback Datasets", available at [[http://dx.doi.org/10.1109/ICDM.2008.22]], adapted for the blocked approach used here. Essentially instead of finding the low-rank approximations to the rating matrix `R`, this finds the approximations for a preference matrix `P` where the elements of `P` are 1 if r > 0 and 0 if r <= 0. The ratings then act as 'confidence' values related to strength of indicated user preferences rather than explicit ratings given to items. @classdesc Constructs an ALS instance with default parameters: {numBlocks: -1, rank: 10, iterations: 10, lambda: 0.01, implicitPrefs: false, alpha: 1.0}. @returns {??} @class @memberof module:eclairjs/mllib/recommendation
[ "Alternating", "Least", "Squares", "matrix", "factorization", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/recommendation/ALS.js#L61-L69
23,141
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/evaluation/RegressionMetrics.js
function (predictionAndObservations) { this.logger = Logger.getLogger("RegressionMetrics_js"); var jvmObject; if (predictionAndObservations instanceof org.apache.spark.mllib.evaluation.RegressionMetrics) { jvmObject = predictionAndObservations; } else { jvmObject = new org.apache.spark.mllib.evaluation.RegressionMetrics(Utils.unwrapObject(predictionAndObservations).rdd()); } JavaWrapper.call(this, jvmObject); }
javascript
function (predictionAndObservations) { this.logger = Logger.getLogger("RegressionMetrics_js"); var jvmObject; if (predictionAndObservations instanceof org.apache.spark.mllib.evaluation.RegressionMetrics) { jvmObject = predictionAndObservations; } else { jvmObject = new org.apache.spark.mllib.evaluation.RegressionMetrics(Utils.unwrapObject(predictionAndObservations).rdd()); } JavaWrapper.call(this, jvmObject); }
[ "function", "(", "predictionAndObservations", ")", "{", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"RegressionMetrics_js\"", ")", ";", "var", "jvmObject", ";", "if", "(", "predictionAndObservations", "instanceof", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "evaluation", ".", "RegressionMetrics", ")", "{", "jvmObject", "=", "predictionAndObservations", ";", "}", "else", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "evaluation", ".", "RegressionMetrics", "(", "Utils", ".", "unwrapObject", "(", "predictionAndObservations", ")", ".", "rdd", "(", ")", ")", ";", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
Evaluator for regression. @param predictionAndObservations an RDD of (prediction, observation) pairs. @memberof module:eclairjs/mllib/evaluation @classdesc @param {module:eclairjs.RDD} predictionAndObservations @class
[ "Evaluator", "for", "regression", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/evaluation/RegressionMetrics.js#L31-L43
23,142
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/tree/model/DecisionTreeModel.js
function (topNode, algo) { var jvmObject; if (topNode instanceof org.apache.spark.mllib.tree.model.DecisionTreeModel) { jvmObject = topNode; }/* if (topeNode instanceof Node { jvmObject = new org.apache.spark.mllib.tree.model.DecisionTreeModel(topNode,algo); } */ else { throw "DecisionTreeModel invalid constructor parameter" } this.logger = Logger.getLogger("DecisionTreeModel_js"); JavaWrapper.call(this, jvmObject); }
javascript
function (topNode, algo) { var jvmObject; if (topNode instanceof org.apache.spark.mllib.tree.model.DecisionTreeModel) { jvmObject = topNode; }/* if (topeNode instanceof Node { jvmObject = new org.apache.spark.mllib.tree.model.DecisionTreeModel(topNode,algo); } */ else { throw "DecisionTreeModel invalid constructor parameter" } this.logger = Logger.getLogger("DecisionTreeModel_js"); JavaWrapper.call(this, jvmObject); }
[ "function", "(", "topNode", ",", "algo", ")", "{", "var", "jvmObject", ";", "if", "(", "topNode", "instanceof", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "tree", ".", "model", ".", "DecisionTreeModel", ")", "{", "jvmObject", "=", "topNode", ";", "}", "/* if (topeNode instanceof Node {\n jvmObject = new org.apache.spark.mllib.tree.model.DecisionTreeModel(topNode,algo);\n } */", "else", "{", "throw", "\"DecisionTreeModel invalid constructor parameter\"", "}", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"DecisionTreeModel_js\"", ")", ";", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
Decision tree model for classification or regression. This model stores the decision tree structure and parameters. @param topNode root node @param algo algorithm type -- classification or regression @classdesc @param {Node} topNode @param {Algo} algo @class @memberof module:eclairjs/mllib/tree/model
[ "Decision", "tree", "model", "for", "classification", "or", "regression", ".", "This", "model", "stores", "the", "decision", "tree", "structure", "and", "parameters", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/tree/model/DecisionTreeModel.js#L36-L48
23,143
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/feature/Word2Vec.js
function (jvmObject) { this.logger = Logger.getLogger("mllib_feature_Word2Vec_js"); if (!jvmObject) { jvmObject = new org.apache.spark.mllib.feature.Word2Vec(); } JavaWrapper.call(this, jvmObject); }
javascript
function (jvmObject) { this.logger = Logger.getLogger("mllib_feature_Word2Vec_js"); if (!jvmObject) { jvmObject = new org.apache.spark.mllib.feature.Word2Vec(); } JavaWrapper.call(this, jvmObject); }
[ "function", "(", "jvmObject", ")", "{", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"mllib_feature_Word2Vec_js\"", ")", ";", "if", "(", "!", "jvmObject", ")", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "feature", ".", "Word2Vec", "(", ")", ";", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
Word2Vec creates vector representation of words in a text corpus. The algorithm first constructs a vocabulary from the corpus and then learns vector representation of words in the vocabulary. The vector representation can be used as features in natural language processing and machine learning algorithms. We used skip-gram model in our implementation and hierarchical softmax method to train the model. The variable names in the implementation matches the original C implementation. For original C implementation, see https://code.google.com/p/word2vec/ For research papers, see Efficient Estimation of Word Representations in Vector Space and Distributed Representations of Words and Phrases and their Compositionality. @memberof module:eclairjs/mllib/feature @classdesc @class
[ "Word2Vec", "creates", "vector", "representation", "of", "words", "in", "a", "text", "corpus", ".", "The", "algorithm", "first", "constructs", "a", "vocabulary", "from", "the", "corpus", "and", "then", "learns", "vector", "representation", "of", "words", "in", "the", "vocabulary", ".", "The", "vector", "representation", "can", "be", "used", "as", "features", "in", "natural", "language", "processing", "and", "machine", "learning", "algorithms", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/feature/Word2Vec.js#L42-L50
23,144
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/regression/IsotonicRegressionModel.js
function (boundaries, predictions, isotonic) { this.logger = Logger.getLogger("IsotonicRegressionModel_js"); var jvmObject; if (boundaries instanceof org.apache.spark.mllib.regression.IsotonicRegressionModel) { jvmObject = boundaries; } else { jvmObject = new org.apache.spark.mllib.regression.IsotonicRegressionModel(boundaries, predictions, isotonic); } JavaWrapper.call(this, jvmObject); }
javascript
function (boundaries, predictions, isotonic) { this.logger = Logger.getLogger("IsotonicRegressionModel_js"); var jvmObject; if (boundaries instanceof org.apache.spark.mllib.regression.IsotonicRegressionModel) { jvmObject = boundaries; } else { jvmObject = new org.apache.spark.mllib.regression.IsotonicRegressionModel(boundaries, predictions, isotonic); } JavaWrapper.call(this, jvmObject); }
[ "function", "(", "boundaries", ",", "predictions", ",", "isotonic", ")", "{", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"IsotonicRegressionModel_js\"", ")", ";", "var", "jvmObject", ";", "if", "(", "boundaries", "instanceof", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "regression", ".", "IsotonicRegressionModel", ")", "{", "jvmObject", "=", "boundaries", ";", "}", "else", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "regression", ".", "IsotonicRegressionModel", "(", "boundaries", ",", "predictions", ",", "isotonic", ")", ";", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
Regression model for isotonic regression. @param boundaries Array of boundaries for which predictions are known. Boundaries must be sorted in increasing order. @param predictions Array of predictions associated to the boundaries at the same index. Results of isotonic regression and therefore monotone. @param isotonic indicates whether this is isotonic or antitonic. @memberof module:eclairjs/mllib/regression @classdesc @param {float[]} boundaries @param {float[]} predictions @param {boolean} isotonic @class
[ "Regression", "model", "for", "isotonic", "regression", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/regression/IsotonicRegressionModel.js#L41-L52
23,145
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/recommendation/MatrixFactorizationModel.js
function () { this.logger = Logger.getLogger("MatrixFactorizationModel_js"); var jvmObject = arguments[0]; if (arguments.length > 1) { var userFeatures = Utils.unwrapObject(arguments[1]); var productFeatures = Utils.unwrapObject(arguments[2]); jvmObject = new org.apache.spark.mllib.recommendation.MatrixFactorizationModel(arguments[0], userFeatures, productFeatures); } JavaWrapper.call(this, jvmObject); }
javascript
function () { this.logger = Logger.getLogger("MatrixFactorizationModel_js"); var jvmObject = arguments[0]; if (arguments.length > 1) { var userFeatures = Utils.unwrapObject(arguments[1]); var productFeatures = Utils.unwrapObject(arguments[2]); jvmObject = new org.apache.spark.mllib.recommendation.MatrixFactorizationModel(arguments[0], userFeatures, productFeatures); } JavaWrapper.call(this, jvmObject); }
[ "function", "(", ")", "{", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"MatrixFactorizationModel_js\"", ")", ";", "var", "jvmObject", "=", "arguments", "[", "0", "]", ";", "if", "(", "arguments", ".", "length", ">", "1", ")", "{", "var", "userFeatures", "=", "Utils", ".", "unwrapObject", "(", "arguments", "[", "1", "]", ")", ";", "var", "productFeatures", "=", "Utils", ".", "unwrapObject", "(", "arguments", "[", "2", "]", ")", ";", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "recommendation", ".", "MatrixFactorizationModel", "(", "arguments", "[", "0", "]", ",", "userFeatures", ",", "productFeatures", ")", ";", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
Model representing the result of matrix factorization. Note: If you create the model directly using constructor, please be aware that fast prediction requires cached user/product features and their associated partitioners. @param rank Rank for the features in this model. @param userFeatures RDD of tuples where each tuple represents the userId and the features computed for this user. @param productFeatures RDD of tuples where each tuple represents the productId and the features computed for this product. @classdesc @param {number} rank @param {module:eclairjs.RDD} userFeatures @param {module:eclairjs.RDD} productFeatures @class @memberof module:eclairjs/mllib/recommendation
[ "Model", "representing", "the", "result", "of", "matrix", "factorization", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/recommendation/MatrixFactorizationModel.js#L44-L55
23,146
EclairJS/eclairjs
client/lib/utils.js
handleArguments
function handleArguments(args) { return new Promise(function(resolve, reject) { var requires = []; var promises = []; // check for Promises in args if (args && args instanceof Array) { args.some(function (arg, i) { if ((arg.value === null || typeof(arg.value) == 'undefined') && arg.optional) { return true; } if (arg.value && Array.isArray(arg.value) && arg.optional && arg.value.length == 0) { return true; } if (arg.type == 'string') { var s = '"' + arg.value.replace(/"/g, '\\\"') + '"'; promises.push(Promise.resolve(s)); } else if (arg.type == 'lambda') { promises.push(serializeLambda(arg.value)); } else if (arg.type == 'lambdaArgs') { promises.push(new Promise(function(resolve, reject) { handleArrayArgument(arg.value).then(function (result) { resolve(result); }).catch(reject); })); } else if (arg.type == 'map') { promises.push(Promise.resolve(JSON.stringify(arg.value))); } else if (arg.type == 'promise') { promises.push(new Promise(function(resolve, reject) { arg.value.then(function(val) { if (typeof(val) == 'string') { if (isNaN(val)) { // a string var s = '"' + val.replace(/"/g, '\\\"') + '"'; resolve(s); } else { resolve(parseFloat(val)); } } else { resolve(val); } }); })); } else if (arg.value.refIdP) { promises.push(arg.value.refIdP); } else if (arg.type == 'List') { promises.push(Promise.resolve(arg.value.toString())); } else if (arg.type == 'array') { // simple array argument promises.push(handleArrayArgument(arg.value)); } else if (arg.type == '_eclairSerialize') { if (arg.value._eclairSerialize == 'staticProperty') { var val = arg.value.ref.name + '.' + arg.value.value; promises.push(Promise.resolve(val)); requires.push({name: arg.value.ref.name, moduleLocation: arg.value.ref.moduleLocation}); } } else if (Array.isArray(arg.value)) { // TODO: should we try to wrap the array if it isn't? promises.push(new Promise(function (resolve, reject) { handleArguments(arg.value).then(function (result) { if (result.requires.length > 0) { result.requires.forEach(function (r) { requires.push(r) }); } resolve('[' + result.args + ']'); }).catch(reject); })); } else if (arg.type == '_eclairForceFloat') { var val = arg.value.value; if (val.toString().indexOf('.') === -1) { val = val.toFixed(1); } promises.push(Promise.resolve(val)); } else if (arg.type == '_eclairLocal') { promises.push(Promise.resolve(arg.value._generateRemote().refIdP)); } else if (arg.type == 'sparkclassref') { // we have a spark class reference, so return its name promises.push(Promise.resolve(arg.value.name)); // add the class to the requires list requires.push({name: arg.value.name, moduleLocation: arg.value.moduleLocation}); } else { promises.push(Promise.resolve(arg.value)); } return false; }); } Promise.all(promises).then(function(finalArgs) { resolve({args: finalArgs, requires: requires}); //resolve(finalArgs); }).catch(function(e) { console.log(e); reject(e) }); }); }
javascript
function handleArguments(args) { return new Promise(function(resolve, reject) { var requires = []; var promises = []; // check for Promises in args if (args && args instanceof Array) { args.some(function (arg, i) { if ((arg.value === null || typeof(arg.value) == 'undefined') && arg.optional) { return true; } if (arg.value && Array.isArray(arg.value) && arg.optional && arg.value.length == 0) { return true; } if (arg.type == 'string') { var s = '"' + arg.value.replace(/"/g, '\\\"') + '"'; promises.push(Promise.resolve(s)); } else if (arg.type == 'lambda') { promises.push(serializeLambda(arg.value)); } else if (arg.type == 'lambdaArgs') { promises.push(new Promise(function(resolve, reject) { handleArrayArgument(arg.value).then(function (result) { resolve(result); }).catch(reject); })); } else if (arg.type == 'map') { promises.push(Promise.resolve(JSON.stringify(arg.value))); } else if (arg.type == 'promise') { promises.push(new Promise(function(resolve, reject) { arg.value.then(function(val) { if (typeof(val) == 'string') { if (isNaN(val)) { // a string var s = '"' + val.replace(/"/g, '\\\"') + '"'; resolve(s); } else { resolve(parseFloat(val)); } } else { resolve(val); } }); })); } else if (arg.value.refIdP) { promises.push(arg.value.refIdP); } else if (arg.type == 'List') { promises.push(Promise.resolve(arg.value.toString())); } else if (arg.type == 'array') { // simple array argument promises.push(handleArrayArgument(arg.value)); } else if (arg.type == '_eclairSerialize') { if (arg.value._eclairSerialize == 'staticProperty') { var val = arg.value.ref.name + '.' + arg.value.value; promises.push(Promise.resolve(val)); requires.push({name: arg.value.ref.name, moduleLocation: arg.value.ref.moduleLocation}); } } else if (Array.isArray(arg.value)) { // TODO: should we try to wrap the array if it isn't? promises.push(new Promise(function (resolve, reject) { handleArguments(arg.value).then(function (result) { if (result.requires.length > 0) { result.requires.forEach(function (r) { requires.push(r) }); } resolve('[' + result.args + ']'); }).catch(reject); })); } else if (arg.type == '_eclairForceFloat') { var val = arg.value.value; if (val.toString().indexOf('.') === -1) { val = val.toFixed(1); } promises.push(Promise.resolve(val)); } else if (arg.type == '_eclairLocal') { promises.push(Promise.resolve(arg.value._generateRemote().refIdP)); } else if (arg.type == 'sparkclassref') { // we have a spark class reference, so return its name promises.push(Promise.resolve(arg.value.name)); // add the class to the requires list requires.push({name: arg.value.name, moduleLocation: arg.value.moduleLocation}); } else { promises.push(Promise.resolve(arg.value)); } return false; }); } Promise.all(promises).then(function(finalArgs) { resolve({args: finalArgs, requires: requires}); //resolve(finalArgs); }).catch(function(e) { console.log(e); reject(e) }); }); }
[ "function", "handleArguments", "(", "args", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "requires", "=", "[", "]", ";", "var", "promises", "=", "[", "]", ";", "// check for Promises in args", "if", "(", "args", "&&", "args", "instanceof", "Array", ")", "{", "args", ".", "some", "(", "function", "(", "arg", ",", "i", ")", "{", "if", "(", "(", "arg", ".", "value", "===", "null", "||", "typeof", "(", "arg", ".", "value", ")", "==", "'undefined'", ")", "&&", "arg", ".", "optional", ")", "{", "return", "true", ";", "}", "if", "(", "arg", ".", "value", "&&", "Array", ".", "isArray", "(", "arg", ".", "value", ")", "&&", "arg", ".", "optional", "&&", "arg", ".", "value", ".", "length", "==", "0", ")", "{", "return", "true", ";", "}", "if", "(", "arg", ".", "type", "==", "'string'", ")", "{", "var", "s", "=", "'\"'", "+", "arg", ".", "value", ".", "replace", "(", "/", "\"", "/", "g", ",", "'\\\\\\\"'", ")", "+", "'\"'", ";", "promises", ".", "push", "(", "Promise", ".", "resolve", "(", "s", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "type", "==", "'lambda'", ")", "{", "promises", ".", "push", "(", "serializeLambda", "(", "arg", ".", "value", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "type", "==", "'lambdaArgs'", ")", "{", "promises", ".", "push", "(", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "handleArrayArgument", "(", "arg", ".", "value", ")", ".", "then", "(", "function", "(", "result", ")", "{", "resolve", "(", "result", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "type", "==", "'map'", ")", "{", "promises", ".", "push", "(", "Promise", ".", "resolve", "(", "JSON", ".", "stringify", "(", "arg", ".", "value", ")", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "type", "==", "'promise'", ")", "{", "promises", ".", "push", "(", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "arg", ".", "value", ".", "then", "(", "function", "(", "val", ")", "{", "if", "(", "typeof", "(", "val", ")", "==", "'string'", ")", "{", "if", "(", "isNaN", "(", "val", ")", ")", "{", "// a string", "var", "s", "=", "'\"'", "+", "val", ".", "replace", "(", "/", "\"", "/", "g", ",", "'\\\\\\\"'", ")", "+", "'\"'", ";", "resolve", "(", "s", ")", ";", "}", "else", "{", "resolve", "(", "parseFloat", "(", "val", ")", ")", ";", "}", "}", "else", "{", "resolve", "(", "val", ")", ";", "}", "}", ")", ";", "}", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "value", ".", "refIdP", ")", "{", "promises", ".", "push", "(", "arg", ".", "value", ".", "refIdP", ")", ";", "}", "else", "if", "(", "arg", ".", "type", "==", "'List'", ")", "{", "promises", ".", "push", "(", "Promise", ".", "resolve", "(", "arg", ".", "value", ".", "toString", "(", ")", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "type", "==", "'array'", ")", "{", "// simple array argument", "promises", ".", "push", "(", "handleArrayArgument", "(", "arg", ".", "value", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "type", "==", "'_eclairSerialize'", ")", "{", "if", "(", "arg", ".", "value", ".", "_eclairSerialize", "==", "'staticProperty'", ")", "{", "var", "val", "=", "arg", ".", "value", ".", "ref", ".", "name", "+", "'.'", "+", "arg", ".", "value", ".", "value", ";", "promises", ".", "push", "(", "Promise", ".", "resolve", "(", "val", ")", ")", ";", "requires", ".", "push", "(", "{", "name", ":", "arg", ".", "value", ".", "ref", ".", "name", ",", "moduleLocation", ":", "arg", ".", "value", ".", "ref", ".", "moduleLocation", "}", ")", ";", "}", "}", "else", "if", "(", "Array", ".", "isArray", "(", "arg", ".", "value", ")", ")", "{", "// TODO: should we try to wrap the array if it isn't?", "promises", ".", "push", "(", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "handleArguments", "(", "arg", ".", "value", ")", ".", "then", "(", "function", "(", "result", ")", "{", "if", "(", "result", ".", "requires", ".", "length", ">", "0", ")", "{", "result", ".", "requires", ".", "forEach", "(", "function", "(", "r", ")", "{", "requires", ".", "push", "(", "r", ")", "}", ")", ";", "}", "resolve", "(", "'['", "+", "result", ".", "args", "+", "']'", ")", ";", "}", ")", ".", "catch", "(", "reject", ")", ";", "}", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "type", "==", "'_eclairForceFloat'", ")", "{", "var", "val", "=", "arg", ".", "value", ".", "value", ";", "if", "(", "val", ".", "toString", "(", ")", ".", "indexOf", "(", "'.'", ")", "===", "-", "1", ")", "{", "val", "=", "val", ".", "toFixed", "(", "1", ")", ";", "}", "promises", ".", "push", "(", "Promise", ".", "resolve", "(", "val", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "type", "==", "'_eclairLocal'", ")", "{", "promises", ".", "push", "(", "Promise", ".", "resolve", "(", "arg", ".", "value", ".", "_generateRemote", "(", ")", ".", "refIdP", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "type", "==", "'sparkclassref'", ")", "{", "// we have a spark class reference, so return its name", "promises", ".", "push", "(", "Promise", ".", "resolve", "(", "arg", ".", "value", ".", "name", ")", ")", ";", "// add the class to the requires list", "requires", ".", "push", "(", "{", "name", ":", "arg", ".", "value", ".", "name", ",", "moduleLocation", ":", "arg", ".", "value", ".", "moduleLocation", "}", ")", ";", "}", "else", "{", "promises", ".", "push", "(", "Promise", ".", "resolve", "(", "arg", ".", "value", ")", ")", ";", "}", "return", "false", ";", "}", ")", ";", "}", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "function", "(", "finalArgs", ")", "{", "resolve", "(", "{", "args", ":", "finalArgs", ",", "requires", ":", "requires", "}", ")", ";", "//resolve(finalArgs);", "}", ")", ".", "catch", "(", "function", "(", "e", ")", "{", "console", ".", "log", "(", "e", ")", ";", "reject", "(", "e", ")", "}", ")", ";", "}", ")", ";", "}" ]
Returns a promise that resolves once all the arguments have been resolved.
[ "Returns", "a", "promise", "that", "resolves", "once", "all", "the", "arguments", "have", "been", "resolved", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/client/lib/utils.js#L535-L635
23,147
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/clustering/BisectingKMeans.js
function(jvmObject) { this.logger = Logger.getLogger("BisectingKMeans_js"); if (!jvmObject) { jvmObject = new org.apache.spark.mllib.clustering.BisectingKMeans(); } JavaWrapper.call(this, jvmObject); }
javascript
function(jvmObject) { this.logger = Logger.getLogger("BisectingKMeans_js"); if (!jvmObject) { jvmObject = new org.apache.spark.mllib.clustering.BisectingKMeans(); } JavaWrapper.call(this, jvmObject); }
[ "function", "(", "jvmObject", ")", "{", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"BisectingKMeans_js\"", ")", ";", "if", "(", "!", "jvmObject", ")", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "clustering", ".", "BisectingKMeans", "(", ")", ";", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
A bisecting k-means algorithm based on the paper "A comparison of document clustering techniques" by Steinbach, Karypis, and Kumar, with modification to fit Spark. The algorithm starts from a single cluster that contains all points. Iteratively it finds divisible clusters on the bottom level and bisects each of them using k-means, until there are `k` leaf clusters in total or no leaf clusters are divisible. The bisecting steps of clusters on the same level are grouped together to increase parallelism. If bisecting all divisible clusters on the bottom level would result more than `k` leaf clusters, larger clusters get higher priority. @param k the desired number of leaf clusters (default: 4). The actual number could be smaller if there are no divisible leaf clusters. @param maxIterations the max number of k-means iterations to split clusters (default: 20) @param minDivisibleClusterSize the minimum number of points (if >= 1.0) or the minimum proportion of points (if < 1.0) of a divisible cluster (default: 1) @param seed a random seed (default: hash value of the class name) @see [[http://glaros.dtc.umn.edu/gkhome/fetch/papers/docclusterKDDTMW00.pdf Steinbach, Karypis, and Kumar, A comparison of document clustering techniques, KDD Workshop on Text Mining, 2000.]] @classdesc Constructs with the default configuration @class @memberof module:eclairjs/mllib/clustering
[ "A", "bisecting", "k", "-", "means", "algorithm", "based", "on", "the", "paper", "A", "comparison", "of", "document", "clustering", "techniques", "by", "Steinbach", "Karypis", "and", "Kumar", "with", "modification", "to", "fit", "Spark", ".", "The", "algorithm", "starts", "from", "a", "single", "cluster", "that", "contains", "all", "points", ".", "Iteratively", "it", "finds", "divisible", "clusters", "on", "the", "bottom", "level", "and", "bisects", "each", "of", "them", "using", "k", "-", "means", "until", "there", "are", "k", "leaf", "clusters", "in", "total", "or", "no", "leaf", "clusters", "are", "divisible", ".", "The", "bisecting", "steps", "of", "clusters", "on", "the", "same", "level", "are", "grouped", "together", "to", "increase", "parallelism", ".", "If", "bisecting", "all", "divisible", "clusters", "on", "the", "bottom", "level", "would", "result", "more", "than", "k", "leaf", "clusters", "larger", "clusters", "get", "higher", "priority", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/clustering/BisectingKMeans.js#L52-L60
23,148
EclairJS/eclairjs
server/src/main/resources/eclairjs/ml/param/ParamMap.js
function (jvmObject) { this.logger = Logger.getLogger("ml_param_ParamMap_js"); if (!jvmObject) { jvmObject = new org.apache.spark.ml.param.ParamMap(); } JavaWrapper.call(this, jvmObject); }
javascript
function (jvmObject) { this.logger = Logger.getLogger("ml_param_ParamMap_js"); if (!jvmObject) { jvmObject = new org.apache.spark.ml.param.ParamMap(); } JavaWrapper.call(this, jvmObject); }
[ "function", "(", "jvmObject", ")", "{", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"ml_param_ParamMap_js\"", ")", ";", "if", "(", "!", "jvmObject", ")", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "ml", ".", "param", ".", "ParamMap", "(", ")", ";", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
A param to value map. @classdesc Creates an empty param map. @class @memberof module:eclairjs/ml/param
[ "A", "param", "to", "value", "map", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/ml/param/ParamMap.js#L31-L39
23,149
EclairJS/eclairjs
server/examples/mllib/lbfgs_example.js
run
function run(sc) { var LogisticRegressionModel = require('eclairjs/mllib/classification').LogisticRegressionModel; var LabeledPoint = require("eclairjs/mllib/regression/LabeledPoint"); var Vectors = require("eclairjs/mllib/linalg/Vectors"); var BinaryClassificationMetrics = require("eclairjs/mllib/evaluation/BinaryClassificationMetrics"); var LBFGS = require("eclairjs/mllib/optimization/LBFGS"); var LogisticGradient = require("eclairjs/mllib/optimization/LogisticGradient"); var SquaredL2Updater = require("eclairjs/mllib/optimization/SquaredL2Updater"); var Tuple2 = require('eclairjs/Tuple2'); var path = ((typeof args !== "undefined") && (args.length > 1)) ? args[1] : "examples/data/mllib/sample_libsvm_data.txt"; var data = MLUtils.loadLibSVMFile(sc, path); var ret = {}; var numFeatures = data.take(1)[0].getFeatures().size(); // Split initial RDD into two... [60% training data, 40% testing data]. var trainingInit = data.sample(false, 0.6, 11); var test = data.subtract(trainingInit); // Append 1 into the training data as intercept. var training = data.map(function (lp, Tuple2, MLUtils) { /* NOTE: MLUtils must be defined in the Global scope, or in this LAMBDA function. */ return new Tuple2(lp.getLabel(), MLUtils.appendBias(lp.getFeatures())); }, [Tuple2, MLUtils]); training.cache(); // Run training algorithm to build the model. var numCorrections = 10; var convergenceTol = 0.0001; var maxNumIterations = 20; var regParam = 0.1; var w = []; for (var i = 0; i < numFeatures + 1; i++) { w.push(0.0); } var initialWeightsWithIntercept = Vectors.dense(w); var result = LBFGS.runLBFGS( // training.rdd(), training, new LogisticGradient(), new SquaredL2Updater(), numCorrections, convergenceTol, maxNumIterations, regParam, initialWeightsWithIntercept); var weightsWithIntercept = result._1(); ret.loss = result._2(); var arrayWeightsWithIntercept = weightsWithIntercept.toArray(); var copyOfWeightsWithIntercept = []; for (var ii = 0; ii < arrayWeightsWithIntercept.length - 1; ii++) { copyOfWeightsWithIntercept.push(arrayWeightsWithIntercept[ii]); } var model = new LogisticRegressionModel(Vectors.dense(copyOfWeightsWithIntercept), copyOfWeightsWithIntercept.length); // Clear the default threshold. model.clearThreshold(); var scoreAndLabels = test.map(function (lp, model, Tuple2) { return new Tuple2(model.predict(lp.getFeatures()), lp.getLabel()); }, [model, Tuple2]); // Get evaluation metrics. var metrics = new BinaryClassificationMetrics(scoreAndLabels); ret.auROC = metrics.areaUnderROC(); return ret; }
javascript
function run(sc) { var LogisticRegressionModel = require('eclairjs/mllib/classification').LogisticRegressionModel; var LabeledPoint = require("eclairjs/mllib/regression/LabeledPoint"); var Vectors = require("eclairjs/mllib/linalg/Vectors"); var BinaryClassificationMetrics = require("eclairjs/mllib/evaluation/BinaryClassificationMetrics"); var LBFGS = require("eclairjs/mllib/optimization/LBFGS"); var LogisticGradient = require("eclairjs/mllib/optimization/LogisticGradient"); var SquaredL2Updater = require("eclairjs/mllib/optimization/SquaredL2Updater"); var Tuple2 = require('eclairjs/Tuple2'); var path = ((typeof args !== "undefined") && (args.length > 1)) ? args[1] : "examples/data/mllib/sample_libsvm_data.txt"; var data = MLUtils.loadLibSVMFile(sc, path); var ret = {}; var numFeatures = data.take(1)[0].getFeatures().size(); // Split initial RDD into two... [60% training data, 40% testing data]. var trainingInit = data.sample(false, 0.6, 11); var test = data.subtract(trainingInit); // Append 1 into the training data as intercept. var training = data.map(function (lp, Tuple2, MLUtils) { /* NOTE: MLUtils must be defined in the Global scope, or in this LAMBDA function. */ return new Tuple2(lp.getLabel(), MLUtils.appendBias(lp.getFeatures())); }, [Tuple2, MLUtils]); training.cache(); // Run training algorithm to build the model. var numCorrections = 10; var convergenceTol = 0.0001; var maxNumIterations = 20; var regParam = 0.1; var w = []; for (var i = 0; i < numFeatures + 1; i++) { w.push(0.0); } var initialWeightsWithIntercept = Vectors.dense(w); var result = LBFGS.runLBFGS( // training.rdd(), training, new LogisticGradient(), new SquaredL2Updater(), numCorrections, convergenceTol, maxNumIterations, regParam, initialWeightsWithIntercept); var weightsWithIntercept = result._1(); ret.loss = result._2(); var arrayWeightsWithIntercept = weightsWithIntercept.toArray(); var copyOfWeightsWithIntercept = []; for (var ii = 0; ii < arrayWeightsWithIntercept.length - 1; ii++) { copyOfWeightsWithIntercept.push(arrayWeightsWithIntercept[ii]); } var model = new LogisticRegressionModel(Vectors.dense(copyOfWeightsWithIntercept), copyOfWeightsWithIntercept.length); // Clear the default threshold. model.clearThreshold(); var scoreAndLabels = test.map(function (lp, model, Tuple2) { return new Tuple2(model.predict(lp.getFeatures()), lp.getLabel()); }, [model, Tuple2]); // Get evaluation metrics. var metrics = new BinaryClassificationMetrics(scoreAndLabels); ret.auROC = metrics.areaUnderROC(); return ret; }
[ "function", "run", "(", "sc", ")", "{", "var", "LogisticRegressionModel", "=", "require", "(", "'eclairjs/mllib/classification'", ")", ".", "LogisticRegressionModel", ";", "var", "LabeledPoint", "=", "require", "(", "\"eclairjs/mllib/regression/LabeledPoint\"", ")", ";", "var", "Vectors", "=", "require", "(", "\"eclairjs/mllib/linalg/Vectors\"", ")", ";", "var", "BinaryClassificationMetrics", "=", "require", "(", "\"eclairjs/mllib/evaluation/BinaryClassificationMetrics\"", ")", ";", "var", "LBFGS", "=", "require", "(", "\"eclairjs/mllib/optimization/LBFGS\"", ")", ";", "var", "LogisticGradient", "=", "require", "(", "\"eclairjs/mllib/optimization/LogisticGradient\"", ")", ";", "var", "SquaredL2Updater", "=", "require", "(", "\"eclairjs/mllib/optimization/SquaredL2Updater\"", ")", ";", "var", "Tuple2", "=", "require", "(", "'eclairjs/Tuple2'", ")", ";", "var", "path", "=", "(", "(", "typeof", "args", "!==", "\"undefined\"", ")", "&&", "(", "args", ".", "length", ">", "1", ")", ")", "?", "args", "[", "1", "]", ":", "\"examples/data/mllib/sample_libsvm_data.txt\"", ";", "var", "data", "=", "MLUtils", ".", "loadLibSVMFile", "(", "sc", ",", "path", ")", ";", "var", "ret", "=", "{", "}", ";", "var", "numFeatures", "=", "data", ".", "take", "(", "1", ")", "[", "0", "]", ".", "getFeatures", "(", ")", ".", "size", "(", ")", ";", "// Split initial RDD into two... [60% training data, 40% testing data].", "var", "trainingInit", "=", "data", ".", "sample", "(", "false", ",", "0.6", ",", "11", ")", ";", "var", "test", "=", "data", ".", "subtract", "(", "trainingInit", ")", ";", "// Append 1 into the training data as intercept.", "var", "training", "=", "data", ".", "map", "(", "function", "(", "lp", ",", "Tuple2", ",", "MLUtils", ")", "{", "/*\n NOTE: MLUtils must be defined in the Global scope,\n or in this LAMBDA function.\n */", "return", "new", "Tuple2", "(", "lp", ".", "getLabel", "(", ")", ",", "MLUtils", ".", "appendBias", "(", "lp", ".", "getFeatures", "(", ")", ")", ")", ";", "}", ",", "[", "Tuple2", ",", "MLUtils", "]", ")", ";", "training", ".", "cache", "(", ")", ";", "// Run training algorithm to build the model.", "var", "numCorrections", "=", "10", ";", "var", "convergenceTol", "=", "0.0001", ";", "var", "maxNumIterations", "=", "20", ";", "var", "regParam", "=", "0.1", ";", "var", "w", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numFeatures", "+", "1", ";", "i", "++", ")", "{", "w", ".", "push", "(", "0.0", ")", ";", "}", "var", "initialWeightsWithIntercept", "=", "Vectors", ".", "dense", "(", "w", ")", ";", "var", "result", "=", "LBFGS", ".", "runLBFGS", "(", "// training.rdd(),", "training", ",", "new", "LogisticGradient", "(", ")", ",", "new", "SquaredL2Updater", "(", ")", ",", "numCorrections", ",", "convergenceTol", ",", "maxNumIterations", ",", "regParam", ",", "initialWeightsWithIntercept", ")", ";", "var", "weightsWithIntercept", "=", "result", ".", "_1", "(", ")", ";", "ret", ".", "loss", "=", "result", ".", "_2", "(", ")", ";", "var", "arrayWeightsWithIntercept", "=", "weightsWithIntercept", ".", "toArray", "(", ")", ";", "var", "copyOfWeightsWithIntercept", "=", "[", "]", ";", "for", "(", "var", "ii", "=", "0", ";", "ii", "<", "arrayWeightsWithIntercept", ".", "length", "-", "1", ";", "ii", "++", ")", "{", "copyOfWeightsWithIntercept", ".", "push", "(", "arrayWeightsWithIntercept", "[", "ii", "]", ")", ";", "}", "var", "model", "=", "new", "LogisticRegressionModel", "(", "Vectors", ".", "dense", "(", "copyOfWeightsWithIntercept", ")", ",", "copyOfWeightsWithIntercept", ".", "length", ")", ";", "// Clear the default threshold.", "model", ".", "clearThreshold", "(", ")", ";", "var", "scoreAndLabels", "=", "test", ".", "map", "(", "function", "(", "lp", ",", "model", ",", "Tuple2", ")", "{", "return", "new", "Tuple2", "(", "model", ".", "predict", "(", "lp", ".", "getFeatures", "(", ")", ")", ",", "lp", ".", "getLabel", "(", ")", ")", ";", "}", ",", "[", "model", ",", "Tuple2", "]", ")", ";", "// Get evaluation metrics.", "var", "metrics", "=", "new", "BinaryClassificationMetrics", "(", "scoreAndLabels", ")", ";", "ret", ".", "auROC", "=", "metrics", ".", "areaUnderROC", "(", ")", ";", "return", "ret", ";", "}" ]
This needs to be in global scope, as it is used in LAMBDA function
[ "This", "needs", "to", "be", "in", "global", "scope", "as", "it", "is", "used", "in", "LAMBDA", "function" ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/examples/mllib/lbfgs_example.js#L24-L106
23,150
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/evaluation/BinaryClassificationMetrics.js
function(scoreAndLabels,numBins) { var jvmObject; if (scoreAndLabels instanceof org.apache.spark.mllib.evaluation.BinaryClassificationMetrics) { jvmObject = scoreAndLabels; } else { jvmObject = new org.apache.spark.mllib.evaluation.BinaryClassificationMetrics(Utils.unwrapObject(scoreAndLabels).rdd(),numBins); } this.logger = Logger.getLogger("BinaryClassificationMetrics_js"); JavaWrapper.call(this, jvmObject); }
javascript
function(scoreAndLabels,numBins) { var jvmObject; if (scoreAndLabels instanceof org.apache.spark.mllib.evaluation.BinaryClassificationMetrics) { jvmObject = scoreAndLabels; } else { jvmObject = new org.apache.spark.mllib.evaluation.BinaryClassificationMetrics(Utils.unwrapObject(scoreAndLabels).rdd(),numBins); } this.logger = Logger.getLogger("BinaryClassificationMetrics_js"); JavaWrapper.call(this, jvmObject); }
[ "function", "(", "scoreAndLabels", ",", "numBins", ")", "{", "var", "jvmObject", ";", "if", "(", "scoreAndLabels", "instanceof", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "evaluation", ".", "BinaryClassificationMetrics", ")", "{", "jvmObject", "=", "scoreAndLabels", ";", "}", "else", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "evaluation", ".", "BinaryClassificationMetrics", "(", "Utils", ".", "unwrapObject", "(", "scoreAndLabels", ")", ".", "rdd", "(", ")", ",", "numBins", ")", ";", "}", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"BinaryClassificationMetrics_js\"", ")", ";", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
Evaluator for binary classification. @param scoreAndLabels an RDD of (score, label) pairs. @param numBins if greater than 0, then the curves (ROC curve, PR curve) computed internally will be down-sampled to this many "bins". If 0, no down-sampling will occur. This is useful because the curve contains a point for each distinct score in the input, and this could be as large as the input itself -- millions of points or more, when thousands may be entirely sufficient to summarize the curve. After down-sampling, the curves will instead be made of approximately `numBins` points instead. Points are made from bins of equal numbers of consecutive points. The size of each bin is `floor(scoreAndLabels.count() / numBins)`, which means the resulting number of bins may not exactly equal numBins. The last bin in each partition may be smaller as a result, meaning there may be an extra sample at partition boundaries. @classdesc @param {module:eclairjs.RDD} scoreAndLabels @param {number} numBins @class @memberof module:eclairjs/mllib/evaluation
[ "Evaluator", "for", "binary", "classification", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/evaluation/BinaryClassificationMetrics.js#L50-L61
23,151
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/tree/model/GradientBoostedTreesModel.js
function (algo, trees, treeWeights) { this.logger = Logger.getLogger("GradientBoostedTreesModel_js"); var jvmObject; if (arguments[0] instanceof org.apache.spark.mllib.tree.model.GradientBoostedTreesModel) { jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.mllib.tree.model.GradientBoostedTreesModel(Utils.unwrapObject(arguments[0]), Utils.unwrapObject(trees), treeWeights ); } JavaWrapper.call(this, jvmObject); }
javascript
function (algo, trees, treeWeights) { this.logger = Logger.getLogger("GradientBoostedTreesModel_js"); var jvmObject; if (arguments[0] instanceof org.apache.spark.mllib.tree.model.GradientBoostedTreesModel) { jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.mllib.tree.model.GradientBoostedTreesModel(Utils.unwrapObject(arguments[0]), Utils.unwrapObject(trees), treeWeights ); } JavaWrapper.call(this, jvmObject); }
[ "function", "(", "algo", ",", "trees", ",", "treeWeights", ")", "{", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"GradientBoostedTreesModel_js\"", ")", ";", "var", "jvmObject", ";", "if", "(", "arguments", "[", "0", "]", "instanceof", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "tree", ".", "model", ".", "GradientBoostedTreesModel", ")", "{", "jvmObject", "=", "arguments", "[", "0", "]", ";", "}", "else", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "tree", ".", "model", ".", "GradientBoostedTreesModel", "(", "Utils", ".", "unwrapObject", "(", "arguments", "[", "0", "]", ")", ",", "Utils", ".", "unwrapObject", "(", "trees", ")", ",", "treeWeights", ")", ";", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
Represents a gradient boosted trees model. @param algo algorithm for the ensemble model, either Classification or Regression @param trees tree ensembles @param treeWeights tree ensemble weights @classdesc @param {Algo} algo @param {module:eclairjs/mllib/tree/model.DecisionTreeModel[]} trees @param {number[]} treeWeights @returns {??} @class @memberof module:eclairjs/mllib/tree/model
[ "Represents", "a", "gradient", "boosted", "trees", "model", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/tree/model/GradientBoostedTreesModel.js#L40-L53
23,152
EclairJS/eclairjs
server/src/main/resources/eclairjs/sql/execution/QueryExecution.js
function (sqlContext, logical) { var jvmObject; if (arguments[0] instanceof org.apache.spark.sql.execution.QueryExecution) { var jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.sql.execution.QueryExecution(Utils.unwrapObject(sqlContext), Utils.unwrapObject(logical)); } JavaWrapper.call(this, jvmObject); }
javascript
function (sqlContext, logical) { var jvmObject; if (arguments[0] instanceof org.apache.spark.sql.execution.QueryExecution) { var jvmObject = arguments[0]; } else { jvmObject = new org.apache.spark.sql.execution.QueryExecution(Utils.unwrapObject(sqlContext), Utils.unwrapObject(logical)); } JavaWrapper.call(this, jvmObject); }
[ "function", "(", "sqlContext", ",", "logical", ")", "{", "var", "jvmObject", ";", "if", "(", "arguments", "[", "0", "]", "instanceof", "org", ".", "apache", ".", "spark", ".", "sql", ".", "execution", ".", "QueryExecution", ")", "{", "var", "jvmObject", "=", "arguments", "[", "0", "]", ";", "}", "else", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "sql", ".", "execution", ".", "QueryExecution", "(", "Utils", ".", "unwrapObject", "(", "sqlContext", ")", ",", "Utils", ".", "unwrapObject", "(", "logical", ")", ")", ";", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
The primary workflow for executing relational queries using Spark. Designed to allow easy access to the intermediate phases of query execution for developers. While this is not a public class, we should avoid changing the function names for the sake of changing them, because a lot of developers use the feature for debugging. @classdesc @param {module:eclairjs/sql.SQLContext} sqlContext @param {LogicalPlan} logical @class @memberof module:eclairjs/sql/execution
[ "The", "primary", "workflow", "for", "executing", "relational", "queries", "using", "Spark", ".", "Designed", "to", "allow", "easy", "access", "to", "the", "intermediate", "phases", "of", "query", "execution", "for", "developers", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/sql/execution/QueryExecution.js#L40-L50
23,153
EclairJS/eclairjs
server/examples/mllib/lr_example.js
run
function run(sc) { var lines = sc.textFile(directory); var points = lines.map(function (line, LabeledPoint, Vectors) { var parts = line.split(","); var y = parseFloat(parts[0]); var tok = parts[1].split(" "); var x = []; for (var i = 0; i < tok.length; ++i) { x[i] = parseFloat(tok[i]); } return new LabeledPoint(y, Vectors.dense(x)); }, [LabeledPoint, Vectors]).cache(); // Another way to configure LogisticRegression // // LogisticRegressionWithSGD lr = new LogisticRegressionWithSGD(); // lr.optimizer().setNumIterations(iterations) // .setStepSize(stepSize) // .setMiniBatchFraction(1.0); // lr.setIntercept(true); // var model = lr.train(points.rdd()); var model = LogisticRegressionWithSGD.train(points, iterations, stepSize); return model.weights(); }
javascript
function run(sc) { var lines = sc.textFile(directory); var points = lines.map(function (line, LabeledPoint, Vectors) { var parts = line.split(","); var y = parseFloat(parts[0]); var tok = parts[1].split(" "); var x = []; for (var i = 0; i < tok.length; ++i) { x[i] = parseFloat(tok[i]); } return new LabeledPoint(y, Vectors.dense(x)); }, [LabeledPoint, Vectors]).cache(); // Another way to configure LogisticRegression // // LogisticRegressionWithSGD lr = new LogisticRegressionWithSGD(); // lr.optimizer().setNumIterations(iterations) // .setStepSize(stepSize) // .setMiniBatchFraction(1.0); // lr.setIntercept(true); // var model = lr.train(points.rdd()); var model = LogisticRegressionWithSGD.train(points, iterations, stepSize); return model.weights(); }
[ "function", "run", "(", "sc", ")", "{", "var", "lines", "=", "sc", ".", "textFile", "(", "directory", ")", ";", "var", "points", "=", "lines", ".", "map", "(", "function", "(", "line", ",", "LabeledPoint", ",", "Vectors", ")", "{", "var", "parts", "=", "line", ".", "split", "(", "\",\"", ")", ";", "var", "y", "=", "parseFloat", "(", "parts", "[", "0", "]", ")", ";", "var", "tok", "=", "parts", "[", "1", "]", ".", "split", "(", "\" \"", ")", ";", "var", "x", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "tok", ".", "length", ";", "++", "i", ")", "{", "x", "[", "i", "]", "=", "parseFloat", "(", "tok", "[", "i", "]", ")", ";", "}", "return", "new", "LabeledPoint", "(", "y", ",", "Vectors", ".", "dense", "(", "x", ")", ")", ";", "}", ",", "[", "LabeledPoint", ",", "Vectors", "]", ")", ".", "cache", "(", ")", ";", "// Another way to configure LogisticRegression", "//", "// LogisticRegressionWithSGD lr = new LogisticRegressionWithSGD();", "// lr.optimizer().setNumIterations(iterations)", "// .setStepSize(stepSize)", "// .setMiniBatchFraction(1.0);", "// lr.setIntercept(true);", "// var model = lr.train(points.rdd());", "var", "model", "=", "LogisticRegressionWithSGD", ".", "train", "(", "points", ",", "iterations", ",", "stepSize", ")", ";", "return", "model", ".", "weights", "(", ")", ";", "}" ]
Logistic regression based classification using ML Lib.
[ "Logistic", "regression", "based", "classification", "using", "ML", "Lib", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/examples/mllib/lr_example.js#L34-L63
23,154
EclairJS/eclairjs
server/src/main/resources/eclairjs/mllib/tree/DecisionTree.js
function (strategy) { this.logger = Logger.getLogger("DecisionTree_js"); var jvmObject; if (strategy instanceof Strategy) { jvmObject = new org.apache.spark.mllib.tree.DecisionTree(Utils.unwrapObject(strategy)); } else if (strategy instanceof rg.apache.spark.mllib.tree.DecisionTree) { jvmObject = strategy; } else { throw "DecisionTree invalid constructor parameter" } JavaWrapper.call(this, jvmObject); }
javascript
function (strategy) { this.logger = Logger.getLogger("DecisionTree_js"); var jvmObject; if (strategy instanceof Strategy) { jvmObject = new org.apache.spark.mllib.tree.DecisionTree(Utils.unwrapObject(strategy)); } else if (strategy instanceof rg.apache.spark.mllib.tree.DecisionTree) { jvmObject = strategy; } else { throw "DecisionTree invalid constructor parameter" } JavaWrapper.call(this, jvmObject); }
[ "function", "(", "strategy", ")", "{", "this", ".", "logger", "=", "Logger", ".", "getLogger", "(", "\"DecisionTree_js\"", ")", ";", "var", "jvmObject", ";", "if", "(", "strategy", "instanceof", "Strategy", ")", "{", "jvmObject", "=", "new", "org", ".", "apache", ".", "spark", ".", "mllib", ".", "tree", ".", "DecisionTree", "(", "Utils", ".", "unwrapObject", "(", "strategy", ")", ")", ";", "}", "else", "if", "(", "strategy", "instanceof", "rg", ".", "apache", ".", "spark", ".", "mllib", ".", "tree", ".", "DecisionTree", ")", "{", "jvmObject", "=", "strategy", ";", "}", "else", "{", "throw", "\"DecisionTree invalid constructor parameter\"", "}", "JavaWrapper", ".", "call", "(", "this", ",", "jvmObject", ")", ";", "}" ]
A class which implements a decision tree learning algorithm for classification and regression. It supports both continuous and categorical features. @param strategy The configuration parameters for the tree algorithm which specify the type of algorithm (classification, regression, etc.), feature type (continuous, categorical), depth of the tree, quantile calculation strategy, etc. @classdesc @param {module:eclairjs/mllib/tree/configuration.Strategy} strategy @class @memberof module:eclairjs/mllib/tree
[ "A", "class", "which", "implements", "a", "decision", "tree", "learning", "algorithm", "for", "classification", "and", "regression", ".", "It", "supports", "both", "continuous", "and", "categorical", "features", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/server/src/main/resources/eclairjs/mllib/tree/DecisionTree.js#L35-L48
23,155
EclairJS/eclairjs
client/lib/index.js
EclairJS
function EclairJS(sessionName) { if (sessionName && EJSCache[sessionName]) { console.log("got hit") return EJSCache[sessionName].ejs; } else { var server = new Server(); var kernelP = server.getKernelPromise(); var instance = { Accumulable: require('./Accumulable.js')(kernelP), AccumulableParam: require('./AccumulableParam.js')(kernelP), List: require('./List.js')(kernelP), Tuple: require('./Tuple.js')(kernelP), Tuple2: require('./Tuple2.js')(kernelP), Tuple3: require('./Tuple3.js')(kernelP), Tuple4: require('./Tuple4.js')(kernelP), SparkConf: require('./SparkConf.js')(kernelP), SparkContext: require('./SparkContext.js')(kernelP, server), ml: require('./ml/module.js')(kernelP), mllib: require('./mllib/module.js')(kernelP), rdd: require('./rdd/module.js')(kernelP), sql: require('./sql/module.js')(kernelP, server), storage: require('./storage/module.js')(kernelP), streaming: require('./streaming/module.js')(kernelP), forceFloat: Utils.forceFloat, addJar: function (jar) { return Utils.addSparkJar(kernelP, jar); }, getUtils: function () { return Utils; }, executeMethod: function (args) { return Utils.executeMethod(kernelP, args); }, addModule: function (module) { server.addModule(module); } }; if (sessionName) { EJSCache[sessionName] = {ejs: instance, server: server}; } return instance; } }
javascript
function EclairJS(sessionName) { if (sessionName && EJSCache[sessionName]) { console.log("got hit") return EJSCache[sessionName].ejs; } else { var server = new Server(); var kernelP = server.getKernelPromise(); var instance = { Accumulable: require('./Accumulable.js')(kernelP), AccumulableParam: require('./AccumulableParam.js')(kernelP), List: require('./List.js')(kernelP), Tuple: require('./Tuple.js')(kernelP), Tuple2: require('./Tuple2.js')(kernelP), Tuple3: require('./Tuple3.js')(kernelP), Tuple4: require('./Tuple4.js')(kernelP), SparkConf: require('./SparkConf.js')(kernelP), SparkContext: require('./SparkContext.js')(kernelP, server), ml: require('./ml/module.js')(kernelP), mllib: require('./mllib/module.js')(kernelP), rdd: require('./rdd/module.js')(kernelP), sql: require('./sql/module.js')(kernelP, server), storage: require('./storage/module.js')(kernelP), streaming: require('./streaming/module.js')(kernelP), forceFloat: Utils.forceFloat, addJar: function (jar) { return Utils.addSparkJar(kernelP, jar); }, getUtils: function () { return Utils; }, executeMethod: function (args) { return Utils.executeMethod(kernelP, args); }, addModule: function (module) { server.addModule(module); } }; if (sessionName) { EJSCache[sessionName] = {ejs: instance, server: server}; } return instance; } }
[ "function", "EclairJS", "(", "sessionName", ")", "{", "if", "(", "sessionName", "&&", "EJSCache", "[", "sessionName", "]", ")", "{", "console", ".", "log", "(", "\"got hit\"", ")", "return", "EJSCache", "[", "sessionName", "]", ".", "ejs", ";", "}", "else", "{", "var", "server", "=", "new", "Server", "(", ")", ";", "var", "kernelP", "=", "server", ".", "getKernelPromise", "(", ")", ";", "var", "instance", "=", "{", "Accumulable", ":", "require", "(", "'./Accumulable.js'", ")", "(", "kernelP", ")", ",", "AccumulableParam", ":", "require", "(", "'./AccumulableParam.js'", ")", "(", "kernelP", ")", ",", "List", ":", "require", "(", "'./List.js'", ")", "(", "kernelP", ")", ",", "Tuple", ":", "require", "(", "'./Tuple.js'", ")", "(", "kernelP", ")", ",", "Tuple2", ":", "require", "(", "'./Tuple2.js'", ")", "(", "kernelP", ")", ",", "Tuple3", ":", "require", "(", "'./Tuple3.js'", ")", "(", "kernelP", ")", ",", "Tuple4", ":", "require", "(", "'./Tuple4.js'", ")", "(", "kernelP", ")", ",", "SparkConf", ":", "require", "(", "'./SparkConf.js'", ")", "(", "kernelP", ")", ",", "SparkContext", ":", "require", "(", "'./SparkContext.js'", ")", "(", "kernelP", ",", "server", ")", ",", "ml", ":", "require", "(", "'./ml/module.js'", ")", "(", "kernelP", ")", ",", "mllib", ":", "require", "(", "'./mllib/module.js'", ")", "(", "kernelP", ")", ",", "rdd", ":", "require", "(", "'./rdd/module.js'", ")", "(", "kernelP", ")", ",", "sql", ":", "require", "(", "'./sql/module.js'", ")", "(", "kernelP", ",", "server", ")", ",", "storage", ":", "require", "(", "'./storage/module.js'", ")", "(", "kernelP", ")", ",", "streaming", ":", "require", "(", "'./streaming/module.js'", ")", "(", "kernelP", ")", ",", "forceFloat", ":", "Utils", ".", "forceFloat", ",", "addJar", ":", "function", "(", "jar", ")", "{", "return", "Utils", ".", "addSparkJar", "(", "kernelP", ",", "jar", ")", ";", "}", ",", "getUtils", ":", "function", "(", ")", "{", "return", "Utils", ";", "}", ",", "executeMethod", ":", "function", "(", "args", ")", "{", "return", "Utils", ".", "executeMethod", "(", "kernelP", ",", "args", ")", ";", "}", ",", "addModule", ":", "function", "(", "module", ")", "{", "server", ".", "addModule", "(", "module", ")", ";", "}", "}", ";", "if", "(", "sessionName", ")", "{", "EJSCache", "[", "sessionName", "]", "=", "{", "ejs", ":", "instance", ",", "server", ":", "server", "}", ";", "}", "return", "instance", ";", "}", "}" ]
eclairjs module. @example var eclairjs = require('eclairjs'); @module eclairjs
[ "eclairjs", "module", "." ]
336368b99f17674a2f86914abbfa5f3000bd028f
https://github.com/EclairJS/eclairjs/blob/336368b99f17674a2f86914abbfa5f3000bd028f/client/lib/index.js#L31-L82
23,156
mu29/react-radio-buttons
lib/index.js
componentWillReceiveProps
function componentWillReceiveProps(nextProps) { var children = this.props.children; var index = children.findIndex(function (c) { return c.props.value === nextProps.value && !c.props.disabled; }); if (index !== -1 && index !== this.state.checkedIndex) { this.setState({ checkedIndex: index }); } }
javascript
function componentWillReceiveProps(nextProps) { var children = this.props.children; var index = children.findIndex(function (c) { return c.props.value === nextProps.value && !c.props.disabled; }); if (index !== -1 && index !== this.state.checkedIndex) { this.setState({ checkedIndex: index }); } }
[ "function", "componentWillReceiveProps", "(", "nextProps", ")", "{", "var", "children", "=", "this", ".", "props", ".", "children", ";", "var", "index", "=", "children", ".", "findIndex", "(", "function", "(", "c", ")", "{", "return", "c", ".", "props", ".", "value", "===", "nextProps", ".", "value", "&&", "!", "c", ".", "props", ".", "disabled", ";", "}", ")", ";", "if", "(", "index", "!==", "-", "1", "&&", "index", "!==", "this", ".", "state", ".", "checkedIndex", ")", "{", "this", ".", "setState", "(", "{", "checkedIndex", ":", "index", "}", ")", ";", "}", "}" ]
This is the case to handle late arriving props, and set the state according to the value as long as it's not disabled
[ "This", "is", "the", "case", "to", "handle", "late", "arriving", "props", "and", "set", "the", "state", "according", "to", "the", "value", "as", "long", "as", "it", "s", "not", "disabled" ]
6abd72a52d47e091597d687d8366477f25a3909c
https://github.com/mu29/react-radio-buttons/blob/6abd72a52d47e091597d687d8366477f25a3909c/lib/index.js#L76-L84
23,157
andig/fritzapi
index.js
executeCommand
function executeCommand(sid, command, ain, options, path) { path = path || '/webservices/homeautoswitch.lua?0=0'; if (sid) path += '&sid=' + sid; if (command) path += '&switchcmd=' + command; if (ain) path += '&ain=' + ain; return httpRequest(path, {}, options); }
javascript
function executeCommand(sid, command, ain, options, path) { path = path || '/webservices/homeautoswitch.lua?0=0'; if (sid) path += '&sid=' + sid; if (command) path += '&switchcmd=' + command; if (ain) path += '&ain=' + ain; return httpRequest(path, {}, options); }
[ "function", "executeCommand", "(", "sid", ",", "command", ",", "ain", ",", "options", ",", "path", ")", "{", "path", "=", "path", "||", "'/webservices/homeautoswitch.lua?0=0'", ";", "if", "(", "sid", ")", "path", "+=", "'&sid='", "+", "sid", ";", "if", "(", "command", ")", "path", "+=", "'&switchcmd='", "+", "command", ";", "if", "(", "ain", ")", "path", "+=", "'&ain='", "+", "ain", ";", "return", "httpRequest", "(", "path", ",", "{", "}", ",", "options", ")", ";", "}" ]
Execute Fritz API command for device specified by AIN
[ "Execute", "Fritz", "API", "command", "for", "device", "specified", "by", "AIN" ]
33d11eabd51c39bb0c1f409ab640dca93d77d173
https://github.com/andig/fritzapi/blob/33d11eabd51c39bb0c1f409ab640dca93d77d173/index.js#L258-L270
23,158
andig/fritzapi
example.js
sequence
function sequence(promises) { var result = Promise.resolve(); promises.forEach(function(promise,i) { result = result.then(promise); }); return result; }
javascript
function sequence(promises) { var result = Promise.resolve(); promises.forEach(function(promise,i) { result = result.then(promise); }); return result; }
[ "function", "sequence", "(", "promises", ")", "{", "var", "result", "=", "Promise", ".", "resolve", "(", ")", ";", "promises", ".", "forEach", "(", "function", "(", "promise", ",", "i", ")", "{", "result", "=", "result", ".", "then", "(", "promise", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
utility function to sequentialize promises
[ "utility", "function", "to", "sequentialize", "promises" ]
33d11eabd51c39bb0c1f409ab640dca93d77d173
https://github.com/andig/fritzapi/blob/33d11eabd51c39bb0c1f409ab640dca93d77d173/example.js#L16-L22
23,159
andig/fritzapi
example.js
switches
function switches() { return fritz.getSwitchList().then(function(switches) { console.log("Switches: " + switches + "\n"); return sequence(switches.map(function(sw) { return function() { return sequence([ function() { return fritz.getSwitchName(sw).then(function(name) { console.log("[" + sw + "] " + name); }); }, function() { return fritz.getSwitchPresence(sw).then(function(presence) { console.log("[" + sw + "] presence: " + presence); }); }, function() { return fritz.getSwitchState(sw).then(function(state) { console.log("[" + sw + "] state: " + state); }); }, function() { return fritz.getTemperature(sw).then(function(temp) { temp = isNaN(temp) ? '-' : temp + "°C"; console.log("[" + sw + "] temp: " + temp + "\n"); }); } ]); }; })); }); }
javascript
function switches() { return fritz.getSwitchList().then(function(switches) { console.log("Switches: " + switches + "\n"); return sequence(switches.map(function(sw) { return function() { return sequence([ function() { return fritz.getSwitchName(sw).then(function(name) { console.log("[" + sw + "] " + name); }); }, function() { return fritz.getSwitchPresence(sw).then(function(presence) { console.log("[" + sw + "] presence: " + presence); }); }, function() { return fritz.getSwitchState(sw).then(function(state) { console.log("[" + sw + "] state: " + state); }); }, function() { return fritz.getTemperature(sw).then(function(temp) { temp = isNaN(temp) ? '-' : temp + "°C"; console.log("[" + sw + "] temp: " + temp + "\n"); }); } ]); }; })); }); }
[ "function", "switches", "(", ")", "{", "return", "fritz", ".", "getSwitchList", "(", ")", ".", "then", "(", "function", "(", "switches", ")", "{", "console", ".", "log", "(", "\"Switches: \"", "+", "switches", "+", "\"\\n\"", ")", ";", "return", "sequence", "(", "switches", ".", "map", "(", "function", "(", "sw", ")", "{", "return", "function", "(", ")", "{", "return", "sequence", "(", "[", "function", "(", ")", "{", "return", "fritz", ".", "getSwitchName", "(", "sw", ")", ".", "then", "(", "function", "(", "name", ")", "{", "console", ".", "log", "(", "\"[\"", "+", "sw", "+", "\"] \"", "+", "name", ")", ";", "}", ")", ";", "}", ",", "function", "(", ")", "{", "return", "fritz", ".", "getSwitchPresence", "(", "sw", ")", ".", "then", "(", "function", "(", "presence", ")", "{", "console", ".", "log", "(", "\"[\"", "+", "sw", "+", "\"] presence: \"", "+", "presence", ")", ";", "}", ")", ";", "}", ",", "function", "(", ")", "{", "return", "fritz", ".", "getSwitchState", "(", "sw", ")", ".", "then", "(", "function", "(", "state", ")", "{", "console", ".", "log", "(", "\"[\"", "+", "sw", "+", "\"] state: \"", "+", "state", ")", ";", "}", ")", ";", "}", ",", "function", "(", ")", "{", "return", "fritz", ".", "getTemperature", "(", "sw", ")", ".", "then", "(", "function", "(", "temp", ")", "{", "temp", "=", "isNaN", "(", "temp", ")", "?", "'-'", ":", "temp", "+", "\"°C\";", "", "console", ".", "log", "(", "\"[\"", "+", "sw", "+", "\"] temp: \"", "+", "temp", "+", "\"\\n\"", ")", ";", "}", ")", ";", "}", "]", ")", ";", "}", ";", "}", ")", ")", ";", "}", ")", ";", "}" ]
display switch information
[ "display", "switch", "information" ]
33d11eabd51c39bb0c1f409ab640dca93d77d173
https://github.com/andig/fritzapi/blob/33d11eabd51c39bb0c1f409ab640dca93d77d173/example.js#L32-L64
23,160
andig/fritzapi
example.js
function() { return fritz.getDevice(thermostat).then(function(device) { console.log("[" + thermostat + "] " + device.name); }); }
javascript
function() { return fritz.getDevice(thermostat).then(function(device) { console.log("[" + thermostat + "] " + device.name); }); }
[ "function", "(", ")", "{", "return", "fritz", ".", "getDevice", "(", "thermostat", ")", ".", "then", "(", "function", "(", "device", ")", "{", "console", ".", "log", "(", "\"[\"", "+", "thermostat", "+", "\"] \"", "+", "device", ".", "name", ")", ";", "}", ")", ";", "}" ]
there is no native getThermostatName function- use getDevice instead
[ "there", "is", "no", "native", "getThermostatName", "function", "-", "use", "getDevice", "instead" ]
33d11eabd51c39bb0c1f409ab640dca93d77d173
https://github.com/andig/fritzapi/blob/33d11eabd51c39bb0c1f409ab640dca93d77d173/example.js#L75-L79
23,161
andig/fritzapi
example.js
debug
function debug() { return fritz.getDeviceList().then(function(devices) { console.log("Raw devices\n"); console.log(devices); }); }
javascript
function debug() { return fritz.getDeviceList().then(function(devices) { console.log("Raw devices\n"); console.log(devices); }); }
[ "function", "debug", "(", ")", "{", "return", "fritz", ".", "getDeviceList", "(", ")", ".", "then", "(", "function", "(", "devices", ")", "{", "console", ".", "log", "(", "\"Raw devices\\n\"", ")", ";", "console", ".", "log", "(", "devices", ")", ";", "}", ")", ";", "}" ]
display debug information
[ "display", "debug", "information" ]
33d11eabd51c39bb0c1f409ab640dca93d77d173
https://github.com/andig/fritzapi/blob/33d11eabd51c39bb0c1f409ab640dca93d77d173/example.js#L99-L104
23,162
lorenwest/node-monitor
lib/probes/ReplProbe.js
function(params, callback) { var t = this; if (typeof(params) !== 'string' || params.length < 1) { callback("Autocomplete paramter must be a nonzero string"); } // Forward to the completion mechanism if it can be completed if (params.substr(-1).match(/([0-9])|([a-z])|([A-Z])|([_])/)) { t.repl.complete(params, callback); } else { // Return a no-op autocomplete callback(null, [[],'']); } }
javascript
function(params, callback) { var t = this; if (typeof(params) !== 'string' || params.length < 1) { callback("Autocomplete paramter must be a nonzero string"); } // Forward to the completion mechanism if it can be completed if (params.substr(-1).match(/([0-9])|([a-z])|([A-Z])|([_])/)) { t.repl.complete(params, callback); } else { // Return a no-op autocomplete callback(null, [[],'']); } }
[ "function", "(", "params", ",", "callback", ")", "{", "var", "t", "=", "this", ";", "if", "(", "typeof", "(", "params", ")", "!==", "'string'", "||", "params", ".", "length", "<", "1", ")", "{", "callback", "(", "\"Autocomplete paramter must be a nonzero string\"", ")", ";", "}", "// Forward to the completion mechanism if it can be completed", "if", "(", "params", ".", "substr", "(", "-", "1", ")", ".", "match", "(", "/", "([0-9])|([a-z])|([A-Z])|([_])", "/", ")", ")", "{", "t", ".", "repl", ".", "complete", "(", "params", ",", "callback", ")", ";", "}", "else", "{", "// Return a no-op autocomplete", "callback", "(", "null", ",", "[", "[", "]", ",", "''", "]", ")", ";", "}", "}" ]
Process an autocomplete request from the client @method autocomplete @param {Object} params Named parameters @param {Function(error, returnParams)} callback Callback function
[ "Process", "an", "autocomplete", "request", "from", "the", "client" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/probes/ReplProbe.js#L106-L119
23,163
lorenwest/node-monitor
lib/probes/ReplProbe.js
function(params, callback) { var t = this; if (params === '.break' && t.shellCmd) { t.shellCmd.kill(); } if (NEW_REPL) { t.stream.emit('data', params + "\n"); } else { t.stream.emit('data', params); } return callback(null); }
javascript
function(params, callback) { var t = this; if (params === '.break' && t.shellCmd) { t.shellCmd.kill(); } if (NEW_REPL) { t.stream.emit('data', params + "\n"); } else { t.stream.emit('data', params); } return callback(null); }
[ "function", "(", "params", ",", "callback", ")", "{", "var", "t", "=", "this", ";", "if", "(", "params", "===", "'.break'", "&&", "t", ".", "shellCmd", ")", "{", "t", ".", "shellCmd", ".", "kill", "(", ")", ";", "}", "if", "(", "NEW_REPL", ")", "{", "t", ".", "stream", ".", "emit", "(", "'data'", ",", "params", "+", "\"\\n\"", ")", ";", "}", "else", "{", "t", ".", "stream", ".", "emit", "(", "'data'", ",", "params", ")", ";", "}", "return", "callback", "(", "null", ")", ";", "}" ]
Handle user input from the console line @method input @param {Object} params Named parameters @param {Function(error, returnParams)} callback Callback function
[ "Handle", "user", "input", "from", "the", "console", "line" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/probes/ReplProbe.js#L128-L139
23,164
lorenwest/node-monitor
lib/probes/ReplProbe.js
function(command) { var t = this; t.shellCmd = ChildProcess.exec(command, function(err, stdout, stderr) { if (err) { var outstr = 'exit'; if (err.code) { outstr += ' (' + err.code + ')'; } if (err.signal) { outstr += ' ' + err.signal; } t._output(outstr); return null; } if (stdout.length) { t._output(stdout); } if (stderr.length) { t._output(stderr); } t.shellCmd = null; t._output(CONSOLE_PROMPT); }); return null; }
javascript
function(command) { var t = this; t.shellCmd = ChildProcess.exec(command, function(err, stdout, stderr) { if (err) { var outstr = 'exit'; if (err.code) { outstr += ' (' + err.code + ')'; } if (err.signal) { outstr += ' ' + err.signal; } t._output(outstr); return null; } if (stdout.length) { t._output(stdout); } if (stderr.length) { t._output(stderr); } t.shellCmd = null; t._output(CONSOLE_PROMPT); }); return null; }
[ "function", "(", "command", ")", "{", "var", "t", "=", "this", ";", "t", ".", "shellCmd", "=", "ChildProcess", ".", "exec", "(", "command", ",", "function", "(", "err", ",", "stdout", ",", "stderr", ")", "{", "if", "(", "err", ")", "{", "var", "outstr", "=", "'exit'", ";", "if", "(", "err", ".", "code", ")", "{", "outstr", "+=", "' ('", "+", "err", ".", "code", "+", "')'", ";", "}", "if", "(", "err", ".", "signal", ")", "{", "outstr", "+=", "' '", "+", "err", ".", "signal", ";", "}", "t", ".", "_output", "(", "outstr", ")", ";", "return", "null", ";", "}", "if", "(", "stdout", ".", "length", ")", "{", "t", ".", "_output", "(", "stdout", ")", ";", "}", "if", "(", "stderr", ".", "length", ")", "{", "t", ".", "_output", "(", "stderr", ")", ";", "}", "t", ".", "shellCmd", "=", "null", ";", "t", ".", "_output", "(", "CONSOLE_PROMPT", ")", ";", "}", ")", ";", "return", "null", ";", "}" ]
Run a shell command and emit the output to the browser. @private @method _runShellCmd @param {String} command - The shell command to invoke
[ "Run", "a", "shell", "command", "and", "emit", "the", "output", "to", "the", "browser", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/probes/ReplProbe.js#L160-L184
23,165
lorenwest/node-monitor
lib/probes/ReplProbe.js
function(probe){ var t = this; t.probe = probe; events.EventEmitter.call(t); if (t.setEncoding) { t.setEncoding('utf8'); } }
javascript
function(probe){ var t = this; t.probe = probe; events.EventEmitter.call(t); if (t.setEncoding) { t.setEncoding('utf8'); } }
[ "function", "(", "probe", ")", "{", "var", "t", "=", "this", ";", "t", ".", "probe", "=", "probe", ";", "events", ".", "EventEmitter", ".", "call", "(", "t", ")", ";", "if", "(", "t", ".", "setEncoding", ")", "{", "t", ".", "setEncoding", "(", "'utf8'", ")", ";", "}", "}" ]
Define an internal stream class for the probe
[ "Define", "an", "internal", "stream", "class", "for", "the", "probe" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/probes/ReplProbe.js#L189-L196
23,166
lorenwest/node-monitor
lib/probes/InspectProbe.js
function(attrs, callback) { var t = this; // Value is the only thing to set if (typeof attrs.value === 'undefined') { return callback({code:'NO_VALUE'}); } // Set the model elements. These cause change events to fire if (t.isModel) { t.value.set(attrs.value); } else { // Set the variable directly var jsonValue = JSON.stringify(attrs.value); t._evaluate(t.key + ' = ' + jsonValue); t.set('value', attrs.value); } return callback(); }
javascript
function(attrs, callback) { var t = this; // Value is the only thing to set if (typeof attrs.value === 'undefined') { return callback({code:'NO_VALUE'}); } // Set the model elements. These cause change events to fire if (t.isModel) { t.value.set(attrs.value); } else { // Set the variable directly var jsonValue = JSON.stringify(attrs.value); t._evaluate(t.key + ' = ' + jsonValue); t.set('value', attrs.value); } return callback(); }
[ "function", "(", "attrs", ",", "callback", ")", "{", "var", "t", "=", "this", ";", "// Value is the only thing to set", "if", "(", "typeof", "attrs", ".", "value", "===", "'undefined'", ")", "{", "return", "callback", "(", "{", "code", ":", "'NO_VALUE'", "}", ")", ";", "}", "// Set the model elements. These cause change events to fire", "if", "(", "t", ".", "isModel", ")", "{", "t", ".", "value", ".", "set", "(", "attrs", ".", "value", ")", ";", "}", "else", "{", "// Set the variable directly", "var", "jsonValue", "=", "JSON", ".", "stringify", "(", "attrs", ".", "value", ")", ";", "t", ".", "_evaluate", "(", "t", ".", "key", "+", "' = '", "+", "jsonValue", ")", ";", "t", ".", "set", "(", "'value'", ",", "attrs", ".", "value", ")", ";", "}", "return", "callback", "(", ")", ";", "}" ]
Remotely set the inspected variable's value @method set_control @param attrs {Object} Name/Value attributes to set. All must be writable. @param callback {Function(error)} Called when the attributes are set or error
[ "Remotely", "set", "the", "inspected", "variable", "s", "value" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/probes/InspectProbe.js#L101-L120
23,167
lorenwest/node-monitor
lib/probes/InspectProbe.js
function() { var t = this; if (t.isModel) { t.value.off('change', t.poll, t); } else { PollingProbe.prototype.release.apply(t, arguments); } }
javascript
function() { var t = this; if (t.isModel) { t.value.off('change', t.poll, t); } else { PollingProbe.prototype.release.apply(t, arguments); } }
[ "function", "(", ")", "{", "var", "t", "=", "this", ";", "if", "(", "t", ".", "isModel", ")", "{", "t", ".", "value", ".", "off", "(", "'change'", ",", "t", ".", "poll", ",", "t", ")", ";", "}", "else", "{", "PollingProbe", ".", "prototype", ".", "release", ".", "apply", "(", "t", ",", "arguments", ")", ";", "}", "}" ]
Stop watching for change events or polling
[ "Stop", "watching", "for", "change", "events", "or", "polling" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/probes/InspectProbe.js#L123-L130
23,168
lorenwest/node-monitor
lib/probes/InspectProbe.js
function(expression, depth){ var t = this; // Determine a default depth depth = typeof depth === 'undefined' ? DEFAULT_DEPTH : depth; // Get the raw value var value = t._evaluate(expression); // Return the depth limited results return Monitor.deepCopy(value, depth); }
javascript
function(expression, depth){ var t = this; // Determine a default depth depth = typeof depth === 'undefined' ? DEFAULT_DEPTH : depth; // Get the raw value var value = t._evaluate(expression); // Return the depth limited results return Monitor.deepCopy(value, depth); }
[ "function", "(", "expression", ",", "depth", ")", "{", "var", "t", "=", "this", ";", "// Determine a default depth", "depth", "=", "typeof", "depth", "===", "'undefined'", "?", "DEFAULT_DEPTH", ":", "depth", ";", "// Get the raw value", "var", "value", "=", "t", ".", "_evaluate", "(", "expression", ")", ";", "// Return the depth limited results", "return", "Monitor", ".", "deepCopy", "(", "value", ",", "depth", ")", ";", "}" ]
Evaluate an expression, returning the depth-limited results @method eval_control @param expression {String} Expression to evaluate @param [depth=2] {Integer} Depth of the object to return @return value {Mixed} Returns the depth-limited value
[ "Evaluate", "an", "expression", "returning", "the", "depth", "-", "limited", "results" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/probes/InspectProbe.js#L140-L151
23,169
lorenwest/node-monitor
lib/probes/InspectProbe.js
function() { var t = this, newValue = t.eval_control(t.key, t.depth); // Set the new value if it has changed from the current value if (!_.isEqual(newValue, t.get('value'))) { t.set({value: newValue}); } }
javascript
function() { var t = this, newValue = t.eval_control(t.key, t.depth); // Set the new value if it has changed from the current value if (!_.isEqual(newValue, t.get('value'))) { t.set({value: newValue}); } }
[ "function", "(", ")", "{", "var", "t", "=", "this", ",", "newValue", "=", "t", ".", "eval_control", "(", "t", ".", "key", ",", "t", ".", "depth", ")", ";", "// Set the new value if it has changed from the current value", "if", "(", "!", "_", ".", "isEqual", "(", "newValue", ",", "t", ".", "get", "(", "'value'", ")", ")", ")", "{", "t", ".", "set", "(", "{", "value", ":", "newValue", "}", ")", ";", "}", "}" ]
Poll for changes in the evaluation @method poll
[ "Poll", "for", "changes", "in", "the", "evaluation" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/probes/InspectProbe.js#L183-L191
23,170
lorenwest/node-monitor
lib/Connection.js
function() { var t = this, hostName = t.get('hostName'), hostPort = t.get('hostPort'), url = t.get('url'); // Build the URL if not specified if (!url) { url = t.attributes.url = 'http://' + hostName + ':' + hostPort; t.set('url', url); } // Connect with this url var opts = { // 'transports': ['websocket', 'xhr-polling', 'jsonp-polling'], 'force new connection': true, // Don't re-use existing connections 'reconnect': false // Don't let socket.io reconnect. // Reconnects are performed by the Router. }; var socket = SocketIO.connect(url, opts); t.set({socket:socket}).bindConnectionEvents(); }
javascript
function() { var t = this, hostName = t.get('hostName'), hostPort = t.get('hostPort'), url = t.get('url'); // Build the URL if not specified if (!url) { url = t.attributes.url = 'http://' + hostName + ':' + hostPort; t.set('url', url); } // Connect with this url var opts = { // 'transports': ['websocket', 'xhr-polling', 'jsonp-polling'], 'force new connection': true, // Don't re-use existing connections 'reconnect': false // Don't let socket.io reconnect. // Reconnects are performed by the Router. }; var socket = SocketIO.connect(url, opts); t.set({socket:socket}).bindConnectionEvents(); }
[ "function", "(", ")", "{", "var", "t", "=", "this", ",", "hostName", "=", "t", ".", "get", "(", "'hostName'", ")", ",", "hostPort", "=", "t", ".", "get", "(", "'hostPort'", ")", ",", "url", "=", "t", ".", "get", "(", "'url'", ")", ";", "// Build the URL if not specified", "if", "(", "!", "url", ")", "{", "url", "=", "t", ".", "attributes", ".", "url", "=", "'http://'", "+", "hostName", "+", "':'", "+", "hostPort", ";", "t", ".", "set", "(", "'url'", ",", "url", ")", ";", "}", "// Connect with this url", "var", "opts", "=", "{", "// 'transports': ['websocket', 'xhr-polling', 'jsonp-polling'],", "'force new connection'", ":", "true", ",", "// Don't re-use existing connections", "'reconnect'", ":", "false", "// Don't let socket.io reconnect.", "// Reconnects are performed by the Router.", "}", ";", "var", "socket", "=", "SocketIO", ".", "connect", "(", "url", ",", "opts", ")", ";", "t", ".", "set", "(", "{", "socket", ":", "socket", "}", ")", ".", "bindConnectionEvents", "(", ")", ";", "}" ]
Initiate a connection with a remote server
[ "Initiate", "a", "connection", "with", "a", "remote", "server" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L108-L127
23,171
lorenwest/node-monitor
lib/Connection.js
function(callback) { var t = this; callback = callback || function(){}; var onPong = function() { t.off('pong', onPong); callback(); }; t.on('pong', onPong); t.emit('connection:ping'); }
javascript
function(callback) { var t = this; callback = callback || function(){}; var onPong = function() { t.off('pong', onPong); callback(); }; t.on('pong', onPong); t.emit('connection:ping'); }
[ "function", "(", "callback", ")", "{", "var", "t", "=", "this", ";", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "var", "onPong", "=", "function", "(", ")", "{", "t", ".", "off", "(", "'pong'", ",", "onPong", ")", ";", "callback", "(", ")", ";", "}", ";", "t", ".", "on", "(", "'pong'", ",", "onPong", ")", ";", "t", ".", "emit", "(", "'connection:ping'", ")", ";", "}" ]
Ping a remote connection @method ping @param callback {Function(error)} Callback when response is returned
[ "Ping", "a", "remote", "connection" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L135-L144
23,172
lorenwest/node-monitor
lib/Connection.js
function(reason) { var t = this, socket = t.get('socket'); t.connecting = false; t.connected = false; // Only disconnect once. // This method can be called many times during a disconnect (manually, // by socketIO disconnect, and/or by the underlying socket disconnect). if (t.socketEvents) { t.removeAllEvents(); socket.disconnect(); t.trigger('disconnect', reason); log.info(t.logId + 'disconnect', reason); } }
javascript
function(reason) { var t = this, socket = t.get('socket'); t.connecting = false; t.connected = false; // Only disconnect once. // This method can be called many times during a disconnect (manually, // by socketIO disconnect, and/or by the underlying socket disconnect). if (t.socketEvents) { t.removeAllEvents(); socket.disconnect(); t.trigger('disconnect', reason); log.info(t.logId + 'disconnect', reason); } }
[ "function", "(", "reason", ")", "{", "var", "t", "=", "this", ",", "socket", "=", "t", ".", "get", "(", "'socket'", ")", ";", "t", ".", "connecting", "=", "false", ";", "t", ".", "connected", "=", "false", ";", "// Only disconnect once.", "// This method can be called many times during a disconnect (manually,", "// by socketIO disconnect, and/or by the underlying socket disconnect).", "if", "(", "t", ".", "socketEvents", ")", "{", "t", ".", "removeAllEvents", "(", ")", ";", "socket", ".", "disconnect", "(", ")", ";", "t", ".", "trigger", "(", "'disconnect'", ",", "reason", ")", ";", "log", ".", "info", "(", "t", ".", "logId", "+", "'disconnect'", ",", "reason", ")", ";", "}", "}" ]
Disconnect from the remote process This can be called from the underlying transport if it detects a disconnect, or it can be manually called to force a disconnect. @method disconnect @param reason {String} Reason for the disconnect <strong>Disconnected from a remote monitor process</strong> This event is emitted after the remote connection is disconnected and resources released. @event disconnect @param reason {String} Reason for the disconnect
[ "Disconnect", "from", "the", "remote", "process" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L164-L178
23,173
lorenwest/node-monitor
lib/Connection.js
function(hostName) { var t = this, testHost = hostName.toLowerCase(), myHostName = t.get('hostName'), remoteHostName = t.get('remoteHostName'); myHostName = myHostName && myHostName.toLowerCase(); remoteHostName = remoteHostName && remoteHostName.toLowerCase(); return (testHost === myHostName || testHost === remoteHostName); }
javascript
function(hostName) { var t = this, testHost = hostName.toLowerCase(), myHostName = t.get('hostName'), remoteHostName = t.get('remoteHostName'); myHostName = myHostName && myHostName.toLowerCase(); remoteHostName = remoteHostName && remoteHostName.toLowerCase(); return (testHost === myHostName || testHost === remoteHostName); }
[ "function", "(", "hostName", ")", "{", "var", "t", "=", "this", ",", "testHost", "=", "hostName", ".", "toLowerCase", "(", ")", ",", "myHostName", "=", "t", ".", "get", "(", "'hostName'", ")", ",", "remoteHostName", "=", "t", ".", "get", "(", "'remoteHostName'", ")", ";", "myHostName", "=", "myHostName", "&&", "myHostName", ".", "toLowerCase", "(", ")", ";", "remoteHostName", "=", "remoteHostName", "&&", "remoteHostName", ".", "toLowerCase", "(", ")", ";", "return", "(", "testHost", "===", "myHostName", "||", "testHost", "===", "remoteHostName", ")", ";", "}" ]
Is this connection with the specified host? @method isThisHost @protected @param hostName {String} The host name to check @return withHost {Boolean} True if the connection is with this host
[ "Is", "this", "connection", "with", "the", "specified", "host?" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L188-L194
23,174
lorenwest/node-monitor
lib/Connection.js
function() { var t = this, socket = t.get('socket'); log.info(t.logId + 'emit', Monitor.deepCopy(arguments, 5)); socket.emit.apply(socket, arguments); }
javascript
function() { var t = this, socket = t.get('socket'); log.info(t.logId + 'emit', Monitor.deepCopy(arguments, 5)); socket.emit.apply(socket, arguments); }
[ "function", "(", ")", "{", "var", "t", "=", "this", ",", "socket", "=", "t", ".", "get", "(", "'socket'", ")", ";", "log", ".", "info", "(", "t", ".", "logId", "+", "'emit'", ",", "Monitor", ".", "deepCopy", "(", "arguments", ",", "5", ")", ")", ";", "socket", ".", "emit", ".", "apply", "(", "socket", ",", "arguments", ")", ";", "}" ]
Emit the specified message to the socket. The other side of the connection can handle and respond to the message using the 'on' method. @method emit @protected @param name {String} The message name to send @param args... {Mixed} Variable number of arguments to send with the message @param callback {Function} Called when remote sends a reply
[ "Emit", "the", "specified", "message", "to", "the", "socket", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L208-L212
23,175
lorenwest/node-monitor
lib/Connection.js
function(eventName, handler) { var t = this, socket = t.get('socket'); t.socketEvents = t.socketEvents || {}; if (t.socketEvents[eventName]) { throw new Error('Event already connected: ' + eventName); } socket.on(eventName, handler); t.socketEvents[eventName] = handler; return t; }
javascript
function(eventName, handler) { var t = this, socket = t.get('socket'); t.socketEvents = t.socketEvents || {}; if (t.socketEvents[eventName]) { throw new Error('Event already connected: ' + eventName); } socket.on(eventName, handler); t.socketEvents[eventName] = handler; return t; }
[ "function", "(", "eventName", ",", "handler", ")", "{", "var", "t", "=", "this", ",", "socket", "=", "t", ".", "get", "(", "'socket'", ")", ";", "t", ".", "socketEvents", "=", "t", ".", "socketEvents", "||", "{", "}", ";", "if", "(", "t", ".", "socketEvents", "[", "eventName", "]", ")", "{", "throw", "new", "Error", "(", "'Event already connected: '", "+", "eventName", ")", ";", "}", "socket", ".", "on", "(", "eventName", ",", "handler", ")", ";", "t", ".", "socketEvents", "[", "eventName", "]", "=", "handler", ";", "return", "t", ";", "}" ]
Bind the specified handler to the remote socket message. Only a single handler (per message name) can be bound using this method. @method addEvent @protected @param eventName {String} The event name to handle @param handler {Function (args..., callback)} Called when the message is received. <ul> <li>args... {Mixed} Arguments sent in by the remote client</li> <li>callback {Function} Final arg if the client specified a callback</li> </ul>
[ "Bind", "the", "specified", "handler", "to", "the", "remote", "socket", "message", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L228-L237
23,176
lorenwest/node-monitor
lib/Connection.js
function(eventName) { var t = this, socket = t.get('socket'); if (t.socketEvents && t.socketEvents[eventName]) { socket.removeListener(eventName, t.socketEvents[eventName]); delete t.socketEvents[eventName]; } return t; }
javascript
function(eventName) { var t = this, socket = t.get('socket'); if (t.socketEvents && t.socketEvents[eventName]) { socket.removeListener(eventName, t.socketEvents[eventName]); delete t.socketEvents[eventName]; } return t; }
[ "function", "(", "eventName", ")", "{", "var", "t", "=", "this", ",", "socket", "=", "t", ".", "get", "(", "'socket'", ")", ";", "if", "(", "t", ".", "socketEvents", "&&", "t", ".", "socketEvents", "[", "eventName", "]", ")", "{", "socket", ".", "removeListener", "(", "eventName", ",", "t", ".", "socketEvents", "[", "eventName", "]", ")", ";", "delete", "t", ".", "socketEvents", "[", "eventName", "]", ";", "}", "return", "t", ";", "}" ]
Remove the specified event from the socket
[ "Remove", "the", "specified", "event", "from", "the", "socket" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L240-L247
23,177
lorenwest/node-monitor
lib/Connection.js
function() { var t = this, socket = t.get('socket'); for (var event in t.socketEvents) { socket.removeListener(event, t.socketEvents[event]); } t.socketEvents = null; return t; }
javascript
function() { var t = this, socket = t.get('socket'); for (var event in t.socketEvents) { socket.removeListener(event, t.socketEvents[event]); } t.socketEvents = null; return t; }
[ "function", "(", ")", "{", "var", "t", "=", "this", ",", "socket", "=", "t", ".", "get", "(", "'socket'", ")", ";", "for", "(", "var", "event", "in", "t", ".", "socketEvents", ")", "{", "socket", ".", "removeListener", "(", "event", ",", "t", ".", "socketEvents", "[", "event", "]", ")", ";", "}", "t", ".", "socketEvents", "=", "null", ";", "return", "t", ";", "}" ]
Remove all events bound to the socket
[ "Remove", "all", "events", "bound", "to", "the", "socket" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L250-L257
23,178
lorenwest/node-monitor
lib/Connection.js
function() { var t = this, socket = t.get('socket'); if (t.socketEvents) {throw new Error('Already connected');} t.socketEvents = {}; // key = event name, data = handler // Failure events t.addEvent('connect_failed', function(){ t.trigger('error', 'connect failed'); t.disconnect('connect failed'); }); t.addEvent('disconnect', function(){t.disconnect('remote_disconnect');}); t.addEvent('error', function(reason){ t.trigger('error', reason); t.disconnect('connect error'); }); // Inbound probe events t.addEvent('probe:connect', t.probeConnect.bind(t)); t.addEvent('probe:disconnect', t.probeDisconnect.bind(t)); t.addEvent('probe:control', t.probeControl.bind(t)); // Connection events t.addEvent('connection:ping', function(){socket.emit('connection:pong');}); t.addEvent('connection:pong', function(){t.trigger('pong');}); // Connected once remote info is known t.addEvent('connection:info', function (info) { t.set({ remoteHostName: info.hostName, remoteAppName: info.appName, remoteAppInstance: info.appInstance, remotePID: info.pid, remoteProbeClasses: info.probeClasses, remoteGateway: info.gateway, remoteFirewall: info.firewall }); t.connecting = false; t.connected = true; t.trigger('connect'); }); // Determine the process id var pid = typeof process === 'undefined' ? 1 : process.pid; // Determine the app instance var appInstance = '' + (typeof process === 'undefined' ? pid : process.env.NODE_APP_INSTANCE || pid); // Exchange connection information socket.emit('connection:info', { hostName:Monitor.getRouter().getHostName(), appName:Config.Monitor.appName, appInstance: appInstance, pid: pid, probeClasses: _.keys(Probe.classes), gateway:t.get('gateway'), firewall:t.get('firewall') }); }
javascript
function() { var t = this, socket = t.get('socket'); if (t.socketEvents) {throw new Error('Already connected');} t.socketEvents = {}; // key = event name, data = handler // Failure events t.addEvent('connect_failed', function(){ t.trigger('error', 'connect failed'); t.disconnect('connect failed'); }); t.addEvent('disconnect', function(){t.disconnect('remote_disconnect');}); t.addEvent('error', function(reason){ t.trigger('error', reason); t.disconnect('connect error'); }); // Inbound probe events t.addEvent('probe:connect', t.probeConnect.bind(t)); t.addEvent('probe:disconnect', t.probeDisconnect.bind(t)); t.addEvent('probe:control', t.probeControl.bind(t)); // Connection events t.addEvent('connection:ping', function(){socket.emit('connection:pong');}); t.addEvent('connection:pong', function(){t.trigger('pong');}); // Connected once remote info is known t.addEvent('connection:info', function (info) { t.set({ remoteHostName: info.hostName, remoteAppName: info.appName, remoteAppInstance: info.appInstance, remotePID: info.pid, remoteProbeClasses: info.probeClasses, remoteGateway: info.gateway, remoteFirewall: info.firewall }); t.connecting = false; t.connected = true; t.trigger('connect'); }); // Determine the process id var pid = typeof process === 'undefined' ? 1 : process.pid; // Determine the app instance var appInstance = '' + (typeof process === 'undefined' ? pid : process.env.NODE_APP_INSTANCE || pid); // Exchange connection information socket.emit('connection:info', { hostName:Monitor.getRouter().getHostName(), appName:Config.Monitor.appName, appInstance: appInstance, pid: pid, probeClasses: _.keys(Probe.classes), gateway:t.get('gateway'), firewall:t.get('firewall') }); }
[ "function", "(", ")", "{", "var", "t", "=", "this", ",", "socket", "=", "t", ".", "get", "(", "'socket'", ")", ";", "if", "(", "t", ".", "socketEvents", ")", "{", "throw", "new", "Error", "(", "'Already connected'", ")", ";", "}", "t", ".", "socketEvents", "=", "{", "}", ";", "// key = event name, data = handler", "// Failure events", "t", ".", "addEvent", "(", "'connect_failed'", ",", "function", "(", ")", "{", "t", ".", "trigger", "(", "'error'", ",", "'connect failed'", ")", ";", "t", ".", "disconnect", "(", "'connect failed'", ")", ";", "}", ")", ";", "t", ".", "addEvent", "(", "'disconnect'", ",", "function", "(", ")", "{", "t", ".", "disconnect", "(", "'remote_disconnect'", ")", ";", "}", ")", ";", "t", ".", "addEvent", "(", "'error'", ",", "function", "(", "reason", ")", "{", "t", ".", "trigger", "(", "'error'", ",", "reason", ")", ";", "t", ".", "disconnect", "(", "'connect error'", ")", ";", "}", ")", ";", "// Inbound probe events", "t", ".", "addEvent", "(", "'probe:connect'", ",", "t", ".", "probeConnect", ".", "bind", "(", "t", ")", ")", ";", "t", ".", "addEvent", "(", "'probe:disconnect'", ",", "t", ".", "probeDisconnect", ".", "bind", "(", "t", ")", ")", ";", "t", ".", "addEvent", "(", "'probe:control'", ",", "t", ".", "probeControl", ".", "bind", "(", "t", ")", ")", ";", "// Connection events", "t", ".", "addEvent", "(", "'connection:ping'", ",", "function", "(", ")", "{", "socket", ".", "emit", "(", "'connection:pong'", ")", ";", "}", ")", ";", "t", ".", "addEvent", "(", "'connection:pong'", ",", "function", "(", ")", "{", "t", ".", "trigger", "(", "'pong'", ")", ";", "}", ")", ";", "// Connected once remote info is known", "t", ".", "addEvent", "(", "'connection:info'", ",", "function", "(", "info", ")", "{", "t", ".", "set", "(", "{", "remoteHostName", ":", "info", ".", "hostName", ",", "remoteAppName", ":", "info", ".", "appName", ",", "remoteAppInstance", ":", "info", ".", "appInstance", ",", "remotePID", ":", "info", ".", "pid", ",", "remoteProbeClasses", ":", "info", ".", "probeClasses", ",", "remoteGateway", ":", "info", ".", "gateway", ",", "remoteFirewall", ":", "info", ".", "firewall", "}", ")", ";", "t", ".", "connecting", "=", "false", ";", "t", ".", "connected", "=", "true", ";", "t", ".", "trigger", "(", "'connect'", ")", ";", "}", ")", ";", "// Determine the process id", "var", "pid", "=", "typeof", "process", "===", "'undefined'", "?", "1", ":", "process", ".", "pid", ";", "// Determine the app instance", "var", "appInstance", "=", "''", "+", "(", "typeof", "process", "===", "'undefined'", "?", "pid", ":", "process", ".", "env", ".", "NODE_APP_INSTANCE", "||", "pid", ")", ";", "// Exchange connection information", "socket", ".", "emit", "(", "'connection:info'", ",", "{", "hostName", ":", "Monitor", ".", "getRouter", "(", ")", ".", "getHostName", "(", ")", ",", "appName", ":", "Config", ".", "Monitor", ".", "appName", ",", "appInstance", ":", "appInstance", ",", "pid", ":", "pid", ",", "probeClasses", ":", "_", ".", "keys", "(", "Probe", ".", "classes", ")", ",", "gateway", ":", "t", ".", "get", "(", "'gateway'", ")", ",", "firewall", ":", "t", ".", "get", "(", "'firewall'", ")", "}", ")", ";", "}" ]
An error has occurred on the connection This event is triggered when an error occurs on the connection. Errors may occur when network is unstable, and can be an indication of impending disconnection. @event error @param err {Object} Reason for the error (from underlying transport)
[ "An", "error", "has", "occurred", "on", "the", "connection" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L269-L326
23,179
lorenwest/node-monitor
lib/Connection.js
function(monitorJSON, callback) { callback = callback || function(){}; var t = this, errorText = '', router = Monitor.getRouter(), gateway = t.get('gateway'), startTime = Date.now(), firewall = t.get('firewall'), logCtxt = _.extend({}, monitorJSON); // Don't allow inbound requests if this connection is firewalled if (firewall) { errorText = 'firewalled'; log.error('probeConnect', errorText, logCtxt); return callback(errorText); } // Determine the connection to use (or internal) router.determineConnection(monitorJSON, gateway, function(err, connection) { if (err) {return callback(err);} if (connection && !gateway) {return callback('Not a gateway');} // Function to run upon connection (internal or external) var onConnect = function(error, probe) { if (error) { log.error(t.logId + 'probeConnect', error, logCtxt); return callback(error); } // Get probe info var probeId = probe.get('id'); logCtxt.id = probeId; // Check for a duplicate proxy for this probeId. This happens when // two connect requests are made before the first one completes. var monitorProxy = t.incomingMonitorsById[probeId]; if (monitorProxy != null) { probe.refCount--; logCtxt.dupDetected = true; logCtxt.refCount = probe.refCount; log.info(t.logId + 'probeConnected', logCtxt); return callback(null, monitorProxy.probe.toJSON()); } // Connect the montior proxy monitorProxy = new Monitor(monitorJSON); monitorProxy.set('probeId', probeId); t.incomingMonitorsById[probeId] = monitorProxy; monitorProxy.probe = probe; monitorProxy.probeChange = function(){ try { t.emit('probe:change:' + probeId, probe.changedAttributes()); } catch (e) { log.error('probeChange', e, probe, logCtxt); } }; probe.connectTime = Date.now(); var duration = probe.connectTime - startTime; logCtxt.duration = duration; logCtxt.refCount = probe.refCount; log.info(t.logId + 'probeConnected', logCtxt); stat.time(t.logId + 'probeConnected', duration); callback(null, probe.toJSON()); probe.on('change', monitorProxy.probeChange); // Disconnect the probe on connection disconnect t.on('disconnect', function() { t.probeDisconnect({probeId:probeId}); }); }; // Connect internally or externally if (connection) { router.connectExternal(monitorJSON, connection, onConnect); } else { router.connectInternal(monitorJSON, onConnect); } }); }
javascript
function(monitorJSON, callback) { callback = callback || function(){}; var t = this, errorText = '', router = Monitor.getRouter(), gateway = t.get('gateway'), startTime = Date.now(), firewall = t.get('firewall'), logCtxt = _.extend({}, monitorJSON); // Don't allow inbound requests if this connection is firewalled if (firewall) { errorText = 'firewalled'; log.error('probeConnect', errorText, logCtxt); return callback(errorText); } // Determine the connection to use (or internal) router.determineConnection(monitorJSON, gateway, function(err, connection) { if (err) {return callback(err);} if (connection && !gateway) {return callback('Not a gateway');} // Function to run upon connection (internal or external) var onConnect = function(error, probe) { if (error) { log.error(t.logId + 'probeConnect', error, logCtxt); return callback(error); } // Get probe info var probeId = probe.get('id'); logCtxt.id = probeId; // Check for a duplicate proxy for this probeId. This happens when // two connect requests are made before the first one completes. var monitorProxy = t.incomingMonitorsById[probeId]; if (monitorProxy != null) { probe.refCount--; logCtxt.dupDetected = true; logCtxt.refCount = probe.refCount; log.info(t.logId + 'probeConnected', logCtxt); return callback(null, monitorProxy.probe.toJSON()); } // Connect the montior proxy monitorProxy = new Monitor(monitorJSON); monitorProxy.set('probeId', probeId); t.incomingMonitorsById[probeId] = monitorProxy; monitorProxy.probe = probe; monitorProxy.probeChange = function(){ try { t.emit('probe:change:' + probeId, probe.changedAttributes()); } catch (e) { log.error('probeChange', e, probe, logCtxt); } }; probe.connectTime = Date.now(); var duration = probe.connectTime - startTime; logCtxt.duration = duration; logCtxt.refCount = probe.refCount; log.info(t.logId + 'probeConnected', logCtxt); stat.time(t.logId + 'probeConnected', duration); callback(null, probe.toJSON()); probe.on('change', monitorProxy.probeChange); // Disconnect the probe on connection disconnect t.on('disconnect', function() { t.probeDisconnect({probeId:probeId}); }); }; // Connect internally or externally if (connection) { router.connectExternal(monitorJSON, connection, onConnect); } else { router.connectInternal(monitorJSON, onConnect); } }); }
[ "function", "(", "monitorJSON", ",", "callback", ")", "{", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "var", "t", "=", "this", ",", "errorText", "=", "''", ",", "router", "=", "Monitor", ".", "getRouter", "(", ")", ",", "gateway", "=", "t", ".", "get", "(", "'gateway'", ")", ",", "startTime", "=", "Date", ".", "now", "(", ")", ",", "firewall", "=", "t", ".", "get", "(", "'firewall'", ")", ",", "logCtxt", "=", "_", ".", "extend", "(", "{", "}", ",", "monitorJSON", ")", ";", "// Don't allow inbound requests if this connection is firewalled", "if", "(", "firewall", ")", "{", "errorText", "=", "'firewalled'", ";", "log", ".", "error", "(", "'probeConnect'", ",", "errorText", ",", "logCtxt", ")", ";", "return", "callback", "(", "errorText", ")", ";", "}", "// Determine the connection to use (or internal)", "router", ".", "determineConnection", "(", "monitorJSON", ",", "gateway", ",", "function", "(", "err", ",", "connection", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "if", "(", "connection", "&&", "!", "gateway", ")", "{", "return", "callback", "(", "'Not a gateway'", ")", ";", "}", "// Function to run upon connection (internal or external)", "var", "onConnect", "=", "function", "(", "error", ",", "probe", ")", "{", "if", "(", "error", ")", "{", "log", ".", "error", "(", "t", ".", "logId", "+", "'probeConnect'", ",", "error", ",", "logCtxt", ")", ";", "return", "callback", "(", "error", ")", ";", "}", "// Get probe info", "var", "probeId", "=", "probe", ".", "get", "(", "'id'", ")", ";", "logCtxt", ".", "id", "=", "probeId", ";", "// Check for a duplicate proxy for this probeId. This happens when", "// two connect requests are made before the first one completes.", "var", "monitorProxy", "=", "t", ".", "incomingMonitorsById", "[", "probeId", "]", ";", "if", "(", "monitorProxy", "!=", "null", ")", "{", "probe", ".", "refCount", "--", ";", "logCtxt", ".", "dupDetected", "=", "true", ";", "logCtxt", ".", "refCount", "=", "probe", ".", "refCount", ";", "log", ".", "info", "(", "t", ".", "logId", "+", "'probeConnected'", ",", "logCtxt", ")", ";", "return", "callback", "(", "null", ",", "monitorProxy", ".", "probe", ".", "toJSON", "(", ")", ")", ";", "}", "// Connect the montior proxy", "monitorProxy", "=", "new", "Monitor", "(", "monitorJSON", ")", ";", "monitorProxy", ".", "set", "(", "'probeId'", ",", "probeId", ")", ";", "t", ".", "incomingMonitorsById", "[", "probeId", "]", "=", "monitorProxy", ";", "monitorProxy", ".", "probe", "=", "probe", ";", "monitorProxy", ".", "probeChange", "=", "function", "(", ")", "{", "try", "{", "t", ".", "emit", "(", "'probe:change:'", "+", "probeId", ",", "probe", ".", "changedAttributes", "(", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "log", ".", "error", "(", "'probeChange'", ",", "e", ",", "probe", ",", "logCtxt", ")", ";", "}", "}", ";", "probe", ".", "connectTime", "=", "Date", ".", "now", "(", ")", ";", "var", "duration", "=", "probe", ".", "connectTime", "-", "startTime", ";", "logCtxt", ".", "duration", "=", "duration", ";", "logCtxt", ".", "refCount", "=", "probe", ".", "refCount", ";", "log", ".", "info", "(", "t", ".", "logId", "+", "'probeConnected'", ",", "logCtxt", ")", ";", "stat", ".", "time", "(", "t", ".", "logId", "+", "'probeConnected'", ",", "duration", ")", ";", "callback", "(", "null", ",", "probe", ".", "toJSON", "(", ")", ")", ";", "probe", ".", "on", "(", "'change'", ",", "monitorProxy", ".", "probeChange", ")", ";", "// Disconnect the probe on connection disconnect", "t", ".", "on", "(", "'disconnect'", ",", "function", "(", ")", "{", "t", ".", "probeDisconnect", "(", "{", "probeId", ":", "probeId", "}", ")", ";", "}", ")", ";", "}", ";", "// Connect internally or externally", "if", "(", "connection", ")", "{", "router", ".", "connectExternal", "(", "monitorJSON", ",", "connection", ",", "onConnect", ")", ";", "}", "else", "{", "router", ".", "connectInternal", "(", "monitorJSON", ",", "onConnect", ")", ";", "}", "}", ")", ";", "}" ]
Process an inbound request to connect with a probe This will fail if this connection was created as a firewall. @method probeConnect @protected @param monitorJSON {Object} Probe connection parameters, including: @param monitorJSON.probeClass {String} The probe class @param monitorJSON.initParams {Object} Probe initialization parameters @param monitorJSON.hostName {String} Connect with this host (if called as a gateway) @param monitorJSON.appName {String} Connect with this app (if called as a gateway) @param callback {Function(error, probeJSON)} Callback function
[ "Process", "an", "inbound", "request", "to", "connect", "with", "a", "probe" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L342-L422
23,180
lorenwest/node-monitor
lib/Connection.js
function(params, callback) { callback = callback || function(){}; var t = this, errorText = '', router = Monitor.getRouter(), probeId = params.probeId, monitorProxy = t.incomingMonitorsById[probeId], firewall = t.get('firewall'), logCtxt = null, probe = null; // Already disconnected if (!monitorProxy || !monitorProxy.probe) { return callback(null); } // Get a good logging context probe = monitorProxy.probe; logCtxt = { probeClass: monitorProxy.get('probeClass'), initParams: monitorProxy.get('initParams'), probeId: probeId }; // Called upon disconnect (internal or external) var onDisconnect = function(error) { if (error) { log.error(t.logId + 'probeDisconnect', error); return callback(error); } var duration = logCtxt.duration = Date.now() - probe.connectTime; probe.off('change', monitorProxy.probeChange); monitorProxy.probe = monitorProxy.probeChange = null; delete t.incomingMonitorsById[probeId]; log.info(t.logId + 'probeDisconnected', logCtxt); stat.time(t.logId + 'probeDisconnected', duration); return callback(null); }; // Disconnect from an internal or external probe if (probe && probe.connection) { router.disconnectExternal(probe.connection, probeId, onDisconnect); } else { router.disconnectInternal(probeId, onDisconnect); } }
javascript
function(params, callback) { callback = callback || function(){}; var t = this, errorText = '', router = Monitor.getRouter(), probeId = params.probeId, monitorProxy = t.incomingMonitorsById[probeId], firewall = t.get('firewall'), logCtxt = null, probe = null; // Already disconnected if (!monitorProxy || !monitorProxy.probe) { return callback(null); } // Get a good logging context probe = monitorProxy.probe; logCtxt = { probeClass: monitorProxy.get('probeClass'), initParams: monitorProxy.get('initParams'), probeId: probeId }; // Called upon disconnect (internal or external) var onDisconnect = function(error) { if (error) { log.error(t.logId + 'probeDisconnect', error); return callback(error); } var duration = logCtxt.duration = Date.now() - probe.connectTime; probe.off('change', monitorProxy.probeChange); monitorProxy.probe = monitorProxy.probeChange = null; delete t.incomingMonitorsById[probeId]; log.info(t.logId + 'probeDisconnected', logCtxt); stat.time(t.logId + 'probeDisconnected', duration); return callback(null); }; // Disconnect from an internal or external probe if (probe && probe.connection) { router.disconnectExternal(probe.connection, probeId, onDisconnect); } else { router.disconnectInternal(probeId, onDisconnect); } }
[ "function", "(", "params", ",", "callback", ")", "{", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "var", "t", "=", "this", ",", "errorText", "=", "''", ",", "router", "=", "Monitor", ".", "getRouter", "(", ")", ",", "probeId", "=", "params", ".", "probeId", ",", "monitorProxy", "=", "t", ".", "incomingMonitorsById", "[", "probeId", "]", ",", "firewall", "=", "t", ".", "get", "(", "'firewall'", ")", ",", "logCtxt", "=", "null", ",", "probe", "=", "null", ";", "// Already disconnected", "if", "(", "!", "monitorProxy", "||", "!", "monitorProxy", ".", "probe", ")", "{", "return", "callback", "(", "null", ")", ";", "}", "// Get a good logging context", "probe", "=", "monitorProxy", ".", "probe", ";", "logCtxt", "=", "{", "probeClass", ":", "monitorProxy", ".", "get", "(", "'probeClass'", ")", ",", "initParams", ":", "monitorProxy", ".", "get", "(", "'initParams'", ")", ",", "probeId", ":", "probeId", "}", ";", "// Called upon disconnect (internal or external)", "var", "onDisconnect", "=", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "log", ".", "error", "(", "t", ".", "logId", "+", "'probeDisconnect'", ",", "error", ")", ";", "return", "callback", "(", "error", ")", ";", "}", "var", "duration", "=", "logCtxt", ".", "duration", "=", "Date", ".", "now", "(", ")", "-", "probe", ".", "connectTime", ";", "probe", ".", "off", "(", "'change'", ",", "monitorProxy", ".", "probeChange", ")", ";", "monitorProxy", ".", "probe", "=", "monitorProxy", ".", "probeChange", "=", "null", ";", "delete", "t", ".", "incomingMonitorsById", "[", "probeId", "]", ";", "log", ".", "info", "(", "t", ".", "logId", "+", "'probeDisconnected'", ",", "logCtxt", ")", ";", "stat", ".", "time", "(", "t", ".", "logId", "+", "'probeDisconnected'", ",", "duration", ")", ";", "return", "callback", "(", "null", ")", ";", "}", ";", "// Disconnect from an internal or external probe", "if", "(", "probe", "&&", "probe", ".", "connection", ")", "{", "router", ".", "disconnectExternal", "(", "probe", ".", "connection", ",", "probeId", ",", "onDisconnect", ")", ";", "}", "else", "{", "router", ".", "disconnectInternal", "(", "probeId", ",", "onDisconnect", ")", ";", "}", "}" ]
Process an inbound request to disconnect with a probe @method probeDisconnect @protected @param params {Object} Disconnect parameters, including: probeId {String} The unique probe id @param callback {Function(error)} Callback function
[ "Process", "an", "inbound", "request", "to", "disconnect", "with", "a", "probe" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L433-L478
23,181
lorenwest/node-monitor
lib/Connection.js
function(params, callback) { callback = callback || function(){}; var t = this, errorText = '', logId = t.logId + 'probeControl', startTime = Date.now(), router = Monitor.getRouter(), firewall = t.get('firewall'); // Don't allow inbound requests if this connection is firewalled if (firewall) { errorText = 'firewalled'; log.error(logId, errorText); return callback(errorText); } // Called upon return var onReturn = function(error) { if (error) { log.error(logId, error); return callback(error); } else { var duration = Date.now() - startTime; log.info(logId + '.return', {duration:duration, returnArgs: arguments}); stat.time(logId, duration); return callback.apply(null, arguments); } }; // Is this an internal probe? var probe = router.runningProbesById[params.probeId]; if (!probe) { // Is this a remote (proxied) probe? var monitorProxy = t.incomingMonitorsById[params.probeId]; if (!monitorProxy) { errorText = 'Probe id not found: ' + params.probeId; log.error(errorText); return callback(errorText); } // Proxying requires this form vs. callback as last arg. return monitorProxy.control(params.name, params.params, function(err, returnParams) { onReturn(err, returnParams); }); } logId = logId + '.' + probe.probeClass + '.' + params.name; log.info(logId + '.request', {params:params.params, probeId:params.probeId}); return probe.onControl(params.name, params.params, onReturn); }
javascript
function(params, callback) { callback = callback || function(){}; var t = this, errorText = '', logId = t.logId + 'probeControl', startTime = Date.now(), router = Monitor.getRouter(), firewall = t.get('firewall'); // Don't allow inbound requests if this connection is firewalled if (firewall) { errorText = 'firewalled'; log.error(logId, errorText); return callback(errorText); } // Called upon return var onReturn = function(error) { if (error) { log.error(logId, error); return callback(error); } else { var duration = Date.now() - startTime; log.info(logId + '.return', {duration:duration, returnArgs: arguments}); stat.time(logId, duration); return callback.apply(null, arguments); } }; // Is this an internal probe? var probe = router.runningProbesById[params.probeId]; if (!probe) { // Is this a remote (proxied) probe? var monitorProxy = t.incomingMonitorsById[params.probeId]; if (!monitorProxy) { errorText = 'Probe id not found: ' + params.probeId; log.error(errorText); return callback(errorText); } // Proxying requires this form vs. callback as last arg. return monitorProxy.control(params.name, params.params, function(err, returnParams) { onReturn(err, returnParams); }); } logId = logId + '.' + probe.probeClass + '.' + params.name; log.info(logId + '.request', {params:params.params, probeId:params.probeId}); return probe.onControl(params.name, params.params, onReturn); }
[ "function", "(", "params", ",", "callback", ")", "{", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "var", "t", "=", "this", ",", "errorText", "=", "''", ",", "logId", "=", "t", ".", "logId", "+", "'probeControl'", ",", "startTime", "=", "Date", ".", "now", "(", ")", ",", "router", "=", "Monitor", ".", "getRouter", "(", ")", ",", "firewall", "=", "t", ".", "get", "(", "'firewall'", ")", ";", "// Don't allow inbound requests if this connection is firewalled", "if", "(", "firewall", ")", "{", "errorText", "=", "'firewalled'", ";", "log", ".", "error", "(", "logId", ",", "errorText", ")", ";", "return", "callback", "(", "errorText", ")", ";", "}", "// Called upon return", "var", "onReturn", "=", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "log", ".", "error", "(", "logId", ",", "error", ")", ";", "return", "callback", "(", "error", ")", ";", "}", "else", "{", "var", "duration", "=", "Date", ".", "now", "(", ")", "-", "startTime", ";", "log", ".", "info", "(", "logId", "+", "'.return'", ",", "{", "duration", ":", "duration", ",", "returnArgs", ":", "arguments", "}", ")", ";", "stat", ".", "time", "(", "logId", ",", "duration", ")", ";", "return", "callback", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", "}", ";", "// Is this an internal probe?", "var", "probe", "=", "router", ".", "runningProbesById", "[", "params", ".", "probeId", "]", ";", "if", "(", "!", "probe", ")", "{", "// Is this a remote (proxied) probe?", "var", "monitorProxy", "=", "t", ".", "incomingMonitorsById", "[", "params", ".", "probeId", "]", ";", "if", "(", "!", "monitorProxy", ")", "{", "errorText", "=", "'Probe id not found: '", "+", "params", ".", "probeId", ";", "log", ".", "error", "(", "errorText", ")", ";", "return", "callback", "(", "errorText", ")", ";", "}", "// Proxying requires this form vs. callback as last arg.", "return", "monitorProxy", ".", "control", "(", "params", ".", "name", ",", "params", ".", "params", ",", "function", "(", "err", ",", "returnParams", ")", "{", "onReturn", "(", "err", ",", "returnParams", ")", ";", "}", ")", ";", "}", "logId", "=", "logId", "+", "'.'", "+", "probe", ".", "probeClass", "+", "'.'", "+", "params", ".", "name", ";", "log", ".", "info", "(", "logId", "+", "'.request'", ",", "{", "params", ":", "params", ".", "params", ",", "probeId", ":", "params", ".", "probeId", "}", ")", ";", "return", "probe", ".", "onControl", "(", "params", ".", "name", ",", "params", ".", "params", ",", "onReturn", ")", ";", "}" ]
Process an inbound control request to a probe @method probeControl @protected @param params {Object} Control parameters, including: probeId {String} The unique probe id name {String} The control message name params {Object} Any control message parameters @param callback {Function(error, returnParams)} Callback function
[ "Process", "an", "inbound", "control", "request", "to", "a", "probe" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/lib/Connection.js#L491-L541
23,182
lorenwest/node-monitor
dist/monitor-all.js
function(name, callback, context) { if (!(eventsApi(this, 'on', name, [callback, context]) && callback)) return this; this._events || (this._events = {}); var list = this._events[name] || (this._events[name] = []); list.push({callback: callback, context: context, ctx: context || this}); return this; }
javascript
function(name, callback, context) { if (!(eventsApi(this, 'on', name, [callback, context]) && callback)) return this; this._events || (this._events = {}); var list = this._events[name] || (this._events[name] = []); list.push({callback: callback, context: context, ctx: context || this}); return this; }
[ "function", "(", "name", ",", "callback", ",", "context", ")", "{", "if", "(", "!", "(", "eventsApi", "(", "this", ",", "'on'", ",", "name", ",", "[", "callback", ",", "context", "]", ")", "&&", "callback", ")", ")", "return", "this", ";", "this", ".", "_events", "||", "(", "this", ".", "_events", "=", "{", "}", ")", ";", "var", "list", "=", "this", ".", "_events", "[", "name", "]", "||", "(", "this", ".", "_events", "[", "name", "]", "=", "[", "]", ")", ";", "list", ".", "push", "(", "{", "callback", ":", "callback", ",", "context", ":", "context", ",", "ctx", ":", "context", "||", "this", "}", ")", ";", "return", "this", ";", "}" ]
Bind one or more space separated events, or an events map, to a `callback` function. Passing `"all"` will bind the callback to all events fired.
[ "Bind", "one", "or", "more", "space", "separated", "events", "or", "an", "events", "map", "to", "a", "callback", "function", ".", "Passing", "all", "will", "bind", "the", "callback", "to", "all", "events", "fired", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L1350-L1356
23,183
lorenwest/node-monitor
dist/monitor-all.js
function(loud) { this.changed = {}; var already = {}; var triggers = []; var current = this._currentAttributes; var changes = this._changes; // Loop through the current queue of potential model changes. for (var i = changes.length - 2; i >= 0; i -= 2) { var key = changes[i], val = changes[i + 1]; if (already[key]) continue; already[key] = true; // Check if the attribute has been modified since the last change, // and update `this.changed` accordingly. If we're inside of a `change` // call, also add a trigger to the list. if (current[key] !== val) { this.changed[key] = val; if (!loud) continue; triggers.push(key, val); current[key] = val; } } if (loud) this._changes = []; // Signals `this.changed` is current to prevent duplicate calls from `this.hasChanged`. this._hasComputed = true; return triggers; }
javascript
function(loud) { this.changed = {}; var already = {}; var triggers = []; var current = this._currentAttributes; var changes = this._changes; // Loop through the current queue of potential model changes. for (var i = changes.length - 2; i >= 0; i -= 2) { var key = changes[i], val = changes[i + 1]; if (already[key]) continue; already[key] = true; // Check if the attribute has been modified since the last change, // and update `this.changed` accordingly. If we're inside of a `change` // call, also add a trigger to the list. if (current[key] !== val) { this.changed[key] = val; if (!loud) continue; triggers.push(key, val); current[key] = val; } } if (loud) this._changes = []; // Signals `this.changed` is current to prevent duplicate calls from `this.hasChanged`. this._hasComputed = true; return triggers; }
[ "function", "(", "loud", ")", "{", "this", ".", "changed", "=", "{", "}", ";", "var", "already", "=", "{", "}", ";", "var", "triggers", "=", "[", "]", ";", "var", "current", "=", "this", ".", "_currentAttributes", ";", "var", "changes", "=", "this", ".", "_changes", ";", "// Loop through the current queue of potential model changes.", "for", "(", "var", "i", "=", "changes", ".", "length", "-", "2", ";", "i", ">=", "0", ";", "i", "-=", "2", ")", "{", "var", "key", "=", "changes", "[", "i", "]", ",", "val", "=", "changes", "[", "i", "+", "1", "]", ";", "if", "(", "already", "[", "key", "]", ")", "continue", ";", "already", "[", "key", "]", "=", "true", ";", "// Check if the attribute has been modified since the last change,", "// and update `this.changed` accordingly. If we're inside of a `change`", "// call, also add a trigger to the list.", "if", "(", "current", "[", "key", "]", "!==", "val", ")", "{", "this", ".", "changed", "[", "key", "]", "=", "val", ";", "if", "(", "!", "loud", ")", "continue", ";", "triggers", ".", "push", "(", "key", ",", "val", ")", ";", "current", "[", "key", "]", "=", "val", ";", "}", "}", "if", "(", "loud", ")", "this", ".", "_changes", "=", "[", "]", ";", "// Signals `this.changed` is current to prevent duplicate calls from `this.hasChanged`.", "this", ".", "_hasComputed", "=", "true", ";", "return", "triggers", ";", "}" ]
Looking at the built up list of `set` attribute changes, compute how many of the attributes have actually changed. If `loud`, return a boiled-down list of only the real changes.
[ "Looking", "at", "the", "built", "up", "list", "of", "set", "attribute", "changes", "compute", "how", "many", "of", "the", "attributes", "have", "actually", "changed", ".", "If", "loud", "return", "a", "boiled", "-", "down", "list", "of", "only", "the", "real", "changes", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L1755-L1783
23,184
lorenwest/node-monitor
dist/monitor-all.js
function(models, options) { var model, i, l, existing; var add = [], remove = [], modelMap = {}; var idAttr = this.model.prototype.idAttribute; options = _.extend({add: true, merge: true, remove: true}, options); if (options.parse) models = this.parse(models); // Allow a single model (or no argument) to be passed. if (!_.isArray(models)) models = models ? [models] : []; // Proxy to `add` for this case, no need to iterate... if (options.add && !options.remove) return this.add(models, options); // Determine which models to add and merge, and which to remove. for (i = 0, l = models.length; i < l; i++) { model = models[i]; existing = this.get(model.id || model.cid || model[idAttr]); if (options.remove && existing) modelMap[existing.cid] = true; if ((options.add && !existing) || (options.merge && existing)) { add.push(model); } } if (options.remove) { for (i = 0, l = this.models.length; i < l; i++) { model = this.models[i]; if (!modelMap[model.cid]) remove.push(model); } } // Remove models (if applicable) before we add and merge the rest. if (remove.length) this.remove(remove, options); if (add.length) this.add(add, options); return this; }
javascript
function(models, options) { var model, i, l, existing; var add = [], remove = [], modelMap = {}; var idAttr = this.model.prototype.idAttribute; options = _.extend({add: true, merge: true, remove: true}, options); if (options.parse) models = this.parse(models); // Allow a single model (or no argument) to be passed. if (!_.isArray(models)) models = models ? [models] : []; // Proxy to `add` for this case, no need to iterate... if (options.add && !options.remove) return this.add(models, options); // Determine which models to add and merge, and which to remove. for (i = 0, l = models.length; i < l; i++) { model = models[i]; existing = this.get(model.id || model.cid || model[idAttr]); if (options.remove && existing) modelMap[existing.cid] = true; if ((options.add && !existing) || (options.merge && existing)) { add.push(model); } } if (options.remove) { for (i = 0, l = this.models.length; i < l; i++) { model = this.models[i]; if (!modelMap[model.cid]) remove.push(model); } } // Remove models (if applicable) before we add and merge the rest. if (remove.length) this.remove(remove, options); if (add.length) this.add(add, options); return this; }
[ "function", "(", "models", ",", "options", ")", "{", "var", "model", ",", "i", ",", "l", ",", "existing", ";", "var", "add", "=", "[", "]", ",", "remove", "=", "[", "]", ",", "modelMap", "=", "{", "}", ";", "var", "idAttr", "=", "this", ".", "model", ".", "prototype", ".", "idAttribute", ";", "options", "=", "_", ".", "extend", "(", "{", "add", ":", "true", ",", "merge", ":", "true", ",", "remove", ":", "true", "}", ",", "options", ")", ";", "if", "(", "options", ".", "parse", ")", "models", "=", "this", ".", "parse", "(", "models", ")", ";", "// Allow a single model (or no argument) to be passed.", "if", "(", "!", "_", ".", "isArray", "(", "models", ")", ")", "models", "=", "models", "?", "[", "models", "]", ":", "[", "]", ";", "// Proxy to `add` for this case, no need to iterate...", "if", "(", "options", ".", "add", "&&", "!", "options", ".", "remove", ")", "return", "this", ".", "add", "(", "models", ",", "options", ")", ";", "// Determine which models to add and merge, and which to remove.", "for", "(", "i", "=", "0", ",", "l", "=", "models", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "model", "=", "models", "[", "i", "]", ";", "existing", "=", "this", ".", "get", "(", "model", ".", "id", "||", "model", ".", "cid", "||", "model", "[", "idAttr", "]", ")", ";", "if", "(", "options", ".", "remove", "&&", "existing", ")", "modelMap", "[", "existing", ".", "cid", "]", "=", "true", ";", "if", "(", "(", "options", ".", "add", "&&", "!", "existing", ")", "||", "(", "options", ".", "merge", "&&", "existing", ")", ")", "{", "add", ".", "push", "(", "model", ")", ";", "}", "}", "if", "(", "options", ".", "remove", ")", "{", "for", "(", "i", "=", "0", ",", "l", "=", "this", ".", "models", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "model", "=", "this", ".", "models", "[", "i", "]", ";", "if", "(", "!", "modelMap", "[", "model", ".", "cid", "]", ")", "remove", ".", "push", "(", "model", ")", ";", "}", "}", "// Remove models (if applicable) before we add and merge the rest.", "if", "(", "remove", ".", "length", ")", "this", ".", "remove", "(", "remove", ",", "options", ")", ";", "if", "(", "add", ".", "length", ")", "this", ".", "add", "(", "add", ",", "options", ")", ";", "return", "this", ";", "}" ]
Smartly update a collection with a change set of models, adding, removing, and merging as necessary.
[ "Smartly", "update", "a", "collection", "with", "a", "change", "set", "of", "models", "adding", "removing", "and", "merging", "as", "necessary", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L2010-L2043
23,185
lorenwest/node-monitor
dist/monitor-all.js
function(methodName, method) { return function() { // Connect the success/error methods for callback style requests. // These style callbacks don't need the model or options arguments // because they're in the scope of the anonymous callback function. var args = _.toArray(arguments), callback = args[args.length - 1]; if (typeof callback === 'function') { // Remove the last element (the callback) args.splice(-1, 1); // Place options if none were specified. if (args.length === 0) { args.push({}); } // Place attributes if save and only options were specified if (args.length === 1 && methodName === 'save') { args.push({}); } var options = args[args.length - 1]; // Place the success and error methods options.success = function(model, response) { callback(null, response); }; options.error = function(model, response) { // Provide the response as the error. callback(response, null); }; } // Invoke the original method return method.apply(this, args); }; }
javascript
function(methodName, method) { return function() { // Connect the success/error methods for callback style requests. // These style callbacks don't need the model or options arguments // because they're in the scope of the anonymous callback function. var args = _.toArray(arguments), callback = args[args.length - 1]; if (typeof callback === 'function') { // Remove the last element (the callback) args.splice(-1, 1); // Place options if none were specified. if (args.length === 0) { args.push({}); } // Place attributes if save and only options were specified if (args.length === 1 && methodName === 'save') { args.push({}); } var options = args[args.length - 1]; // Place the success and error methods options.success = function(model, response) { callback(null, response); }; options.error = function(model, response) { // Provide the response as the error. callback(response, null); }; } // Invoke the original method return method.apply(this, args); }; }
[ "function", "(", "methodName", ",", "method", ")", "{", "return", "function", "(", ")", "{", "// Connect the success/error methods for callback style requests.", "// These style callbacks don't need the model or options arguments", "// because they're in the scope of the anonymous callback function.", "var", "args", "=", "_", ".", "toArray", "(", "arguments", ")", ",", "callback", "=", "args", "[", "args", ".", "length", "-", "1", "]", ";", "if", "(", "typeof", "callback", "===", "'function'", ")", "{", "// Remove the last element (the callback)", "args", ".", "splice", "(", "-", "1", ",", "1", ")", ";", "// Place options if none were specified.", "if", "(", "args", ".", "length", "===", "0", ")", "{", "args", ".", "push", "(", "{", "}", ")", ";", "}", "// Place attributes if save and only options were specified", "if", "(", "args", ".", "length", "===", "1", "&&", "methodName", "===", "'save'", ")", "{", "args", ".", "push", "(", "{", "}", ")", ";", "}", "var", "options", "=", "args", "[", "args", ".", "length", "-", "1", "]", ";", "// Place the success and error methods", "options", ".", "success", "=", "function", "(", "model", ",", "response", ")", "{", "callback", "(", "null", ",", "response", ")", ";", "}", ";", "options", ".", "error", "=", "function", "(", "model", ",", "response", ")", "{", "// Provide the response as the error.", "callback", "(", "response", ",", "null", ")", ";", "}", ";", "}", "// Invoke the original method", "return", "method", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ";", "}" ]
Anonymous callback style interface for Backbone.js async methods. Load this after Backbone.js to add an anonymous function callback style interface for fetch(), save(), and destroy() in addition to the built-in success/error style interface. This adds a shim to the existing interface, allowing either style to be used. If a callback function is provided as the last argument, it will use that callback style. Otherwise it will use the success/error style. Example: customer.save(attrs, options, function(error, response) { if (error) { return console.log('Error saving customer', error); } console.log('Customer save successful. Response:', response); }); The callback gets two arguments - an error object and response object. One or the other will be set based on an error condition. The motivation for this callback style is to offer Backbone.js clients a common coding style for client-side and server-side applications. @class BackboneCallbacks
[ "Anonymous", "callback", "style", "interface", "for", "Backbone", ".", "js", "async", "methods", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L2802-L2838
23,186
lorenwest/node-monitor
dist/monitor-all.js
function(callback) { var t = this, startTime = Date.now(); Monitor.getRouter().connectMonitor(t, function(error) { // Monitor changes to writable attributes if (!error && t.get('writableAttributes').length > 0) { t.on('change', t.onChange, t); } // Give the caller first crack at knowing we're connected, // followed by anyone registered for the connect event. if (callback) {callback(error);} // Initial data setting into the model was done silently // in order for the connect event to fire before the first // change event. Fire the connect / change in the proper order. if (!error) { // An unfortunate side effect is any change listeners registered during // connect will get triggered with the same values as during connect. // To get around this, add change listeners from connect on nextTick. t.trigger('connect', t); t.trigger('change', t); log.info('connected', {initParams: t.get('initParams'), probeId: t.get('probeId')}); stat.time('connect', Date.now() - startTime); } }); }
javascript
function(callback) { var t = this, startTime = Date.now(); Monitor.getRouter().connectMonitor(t, function(error) { // Monitor changes to writable attributes if (!error && t.get('writableAttributes').length > 0) { t.on('change', t.onChange, t); } // Give the caller first crack at knowing we're connected, // followed by anyone registered for the connect event. if (callback) {callback(error);} // Initial data setting into the model was done silently // in order for the connect event to fire before the first // change event. Fire the connect / change in the proper order. if (!error) { // An unfortunate side effect is any change listeners registered during // connect will get triggered with the same values as during connect. // To get around this, add change listeners from connect on nextTick. t.trigger('connect', t); t.trigger('change', t); log.info('connected', {initParams: t.get('initParams'), probeId: t.get('probeId')}); stat.time('connect', Date.now() - startTime); } }); }
[ "function", "(", "callback", ")", "{", "var", "t", "=", "this", ",", "startTime", "=", "Date", ".", "now", "(", ")", ";", "Monitor", ".", "getRouter", "(", ")", ".", "connectMonitor", "(", "t", ",", "function", "(", "error", ")", "{", "// Monitor changes to writable attributes", "if", "(", "!", "error", "&&", "t", ".", "get", "(", "'writableAttributes'", ")", ".", "length", ">", "0", ")", "{", "t", ".", "on", "(", "'change'", ",", "t", ".", "onChange", ",", "t", ")", ";", "}", "// Give the caller first crack at knowing we're connected,", "// followed by anyone registered for the connect event.", "if", "(", "callback", ")", "{", "callback", "(", "error", ")", ";", "}", "// Initial data setting into the model was done silently", "// in order for the connect event to fire before the first", "// change event. Fire the connect / change in the proper order.", "if", "(", "!", "error", ")", "{", "// An unfortunate side effect is any change listeners registered during", "// connect will get triggered with the same values as during connect.", "// To get around this, add change listeners from connect on nextTick.", "t", ".", "trigger", "(", "'connect'", ",", "t", ")", ";", "t", ".", "trigger", "(", "'change'", ",", "t", ")", ";", "log", ".", "info", "(", "'connected'", ",", "{", "initParams", ":", "t", ".", "get", "(", "'initParams'", ")", ",", "probeId", ":", "t", ".", "get", "(", "'probeId'", ")", "}", ")", ";", "stat", ".", "time", "(", "'connect'", ",", "Date", ".", "now", "(", ")", "-", "startTime", ")", ";", "}", "}", ")", ";", "}" ]
Connect the monitor to the remote probe Upon connection, the monitor data model is a proxy of the current state of the probe. @method connect @param callback {Function(error)} Called when the probe is connected (or error) The monitor has successfully connected with the probe @event connect
[ "Connect", "the", "monitor", "to", "the", "remote", "probe" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L6889-L6917
23,187
lorenwest/node-monitor
dist/monitor-all.js
function() { var t = this; return (t.probe && t.probe.connection ? t.probe.connection : null); }
javascript
function() { var t = this; return (t.probe && t.probe.connection ? t.probe.connection : null); }
[ "function", "(", ")", "{", "var", "t", "=", "this", ";", "return", "(", "t", ".", "probe", "&&", "t", ".", "probe", ".", "connection", "?", "t", ".", "probe", ".", "connection", ":", "null", ")", ";", "}" ]
Get the connection to the remote probe This method returns the Connection object that represents the remote server used for communicating with the connected probe. If the probe is running internally or the monitor isn't currently connected, this will return null. @method getConnection @return connection {Connection} The connection object
[ "Get", "the", "connection", "to", "the", "remote", "probe" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L6931-L6934
23,188
lorenwest/node-monitor
dist/monitor-all.js
function(callback) { var t = this, reason = 'manual_disconnect', startTime = Date.now(), probeId = t.get('probeId'); // Stop forwarding changes to the probe t.off('change', t.onChange, t); // Disconnect from the router Monitor.getRouter().disconnectMonitor(t, reason, function(error, reason) { if (callback) {callback(error);} if (error) { log.error('disconnect', {error: error}); } else { t.trigger('disconnect', reason); log.info('disconnected', {reason: reason, probeId: probeId}); stat.time('disconnect', Date.now() - startTime); } }); }
javascript
function(callback) { var t = this, reason = 'manual_disconnect', startTime = Date.now(), probeId = t.get('probeId'); // Stop forwarding changes to the probe t.off('change', t.onChange, t); // Disconnect from the router Monitor.getRouter().disconnectMonitor(t, reason, function(error, reason) { if (callback) {callback(error);} if (error) { log.error('disconnect', {error: error}); } else { t.trigger('disconnect', reason); log.info('disconnected', {reason: reason, probeId: probeId}); stat.time('disconnect', Date.now() - startTime); } }); }
[ "function", "(", "callback", ")", "{", "var", "t", "=", "this", ",", "reason", "=", "'manual_disconnect'", ",", "startTime", "=", "Date", ".", "now", "(", ")", ",", "probeId", "=", "t", ".", "get", "(", "'probeId'", ")", ";", "// Stop forwarding changes to the probe", "t", ".", "off", "(", "'change'", ",", "t", ".", "onChange", ",", "t", ")", ";", "// Disconnect from the router", "Monitor", ".", "getRouter", "(", ")", ".", "disconnectMonitor", "(", "t", ",", "reason", ",", "function", "(", "error", ",", "reason", ")", "{", "if", "(", "callback", ")", "{", "callback", "(", "error", ")", ";", "}", "if", "(", "error", ")", "{", "log", ".", "error", "(", "'disconnect'", ",", "{", "error", ":", "error", "}", ")", ";", "}", "else", "{", "t", ".", "trigger", "(", "'disconnect'", ",", "reason", ")", ";", "log", ".", "info", "(", "'disconnected'", ",", "{", "reason", ":", "reason", ",", "probeId", ":", "probeId", "}", ")", ";", "stat", ".", "time", "(", "'disconnect'", ",", "Date", ".", "now", "(", ")", "-", "startTime", ")", ";", "}", "}", ")", ";", "}" ]
Disconnect from the remote probe This should be called when the monitor is no longer needed. It releases resources associated with monitoring the probe. If this was the last object monitoring the probe, the probe will be stopped, releasing resources associated with running the probe. @method disconnect @param callback {Function(error)} Called when disconnected (or error) The monitor has disconnected from the probe @event disconnect @param reason {String} Reason specified for the disconnect <ul>Known Reasons: <li>manual_disconnect - A manual call to disconnect() was made.</li> <li>connect_failed - Underlying transport connection problem.</li> <li>remote_disconnect - Underlying transport disconnected.</li> </ul>
[ "Disconnect", "from", "the", "remote", "probe" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L6969-L6990
23,189
lorenwest/node-monitor
dist/monitor-all.js
function() { var t = this, writableAttributes = t.get('writableAttributes'), writableChanges = {}; // Add any writable changes var probeAttrs = t.toProbeJSON(); delete probeAttrs.id; for (var attrName in probeAttrs) { var isWritable = writableAttributes === '*' || writableAttributes.indexOf(attrName) >= 0; if (isWritable && !(_.isEqual(t.attributes[attrName], t._probeValues[attrName]))) { writableChanges[attrName] = t.attributes[attrName]; } } // Pass any writable changes on to control.set() if (Monitor._.size(writableChanges)) { t.control('set', writableChanges, function(error) { if (error) { log.error('probeSet', 'Problem setting writable value', writableChanges, t.toMonitorJSON()); } }); } }
javascript
function() { var t = this, writableAttributes = t.get('writableAttributes'), writableChanges = {}; // Add any writable changes var probeAttrs = t.toProbeJSON(); delete probeAttrs.id; for (var attrName in probeAttrs) { var isWritable = writableAttributes === '*' || writableAttributes.indexOf(attrName) >= 0; if (isWritable && !(_.isEqual(t.attributes[attrName], t._probeValues[attrName]))) { writableChanges[attrName] = t.attributes[attrName]; } } // Pass any writable changes on to control.set() if (Monitor._.size(writableChanges)) { t.control('set', writableChanges, function(error) { if (error) { log.error('probeSet', 'Problem setting writable value', writableChanges, t.toMonitorJSON()); } }); } }
[ "function", "(", ")", "{", "var", "t", "=", "this", ",", "writableAttributes", "=", "t", ".", "get", "(", "'writableAttributes'", ")", ",", "writableChanges", "=", "{", "}", ";", "// Add any writable changes", "var", "probeAttrs", "=", "t", ".", "toProbeJSON", "(", ")", ";", "delete", "probeAttrs", ".", "id", ";", "for", "(", "var", "attrName", "in", "probeAttrs", ")", "{", "var", "isWritable", "=", "writableAttributes", "===", "'*'", "||", "writableAttributes", ".", "indexOf", "(", "attrName", ")", ">=", "0", ";", "if", "(", "isWritable", "&&", "!", "(", "_", ".", "isEqual", "(", "t", ".", "attributes", "[", "attrName", "]", ",", "t", ".", "_probeValues", "[", "attrName", "]", ")", ")", ")", "{", "writableChanges", "[", "attrName", "]", "=", "t", ".", "attributes", "[", "attrName", "]", ";", "}", "}", "// Pass any writable changes on to control.set()", "if", "(", "Monitor", ".", "_", ".", "size", "(", "writableChanges", ")", ")", "{", "t", ".", "control", "(", "'set'", ",", "writableChanges", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "log", ".", "error", "(", "'probeSet'", ",", "'Problem setting writable value'", ",", "writableChanges", ",", "t", ".", "toMonitorJSON", "(", ")", ")", ";", "}", "}", ")", ";", "}", "}" ]
Forward changes on to the probe, when connected. This is called whenever a change trigger is fired. It forwards any changes of writable attributes onto the probe using control('set').
[ "Forward", "changes", "on", "to", "the", "probe", "when", "connected", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L6998-L7021
23,190
lorenwest/node-monitor
dist/monitor-all.js
function(name, params, callback) { var t = this, probe = t.probe, logId = 'control.' + t.get('probeClass') + '.' + name, startTime = Date.now(); // Switch callback if sent in 2nd arg if (typeof params === 'function') { callback = params; params = null; } log.info(logId, params); var whenDone = function(error, args) { if (error) { log.error(logId, error); } else { log.info('return.' + logId, args); stat.time(logId, Date.now() - startTime); } if (callback) { callback.apply(t, arguments); } }; if (!probe) { return whenDone('Probe not connected'); } // Send the message internally or to the probe connection if (probe.connection) { probe.connection.emit('probe:control', {probeId: t.get('probeId'), name: name, params:params}, whenDone); } else { probe.onControl(name, params, whenDone); } }
javascript
function(name, params, callback) { var t = this, probe = t.probe, logId = 'control.' + t.get('probeClass') + '.' + name, startTime = Date.now(); // Switch callback if sent in 2nd arg if (typeof params === 'function') { callback = params; params = null; } log.info(logId, params); var whenDone = function(error, args) { if (error) { log.error(logId, error); } else { log.info('return.' + logId, args); stat.time(logId, Date.now() - startTime); } if (callback) { callback.apply(t, arguments); } }; if (!probe) { return whenDone('Probe not connected'); } // Send the message internally or to the probe connection if (probe.connection) { probe.connection.emit('probe:control', {probeId: t.get('probeId'), name: name, params:params}, whenDone); } else { probe.onControl(name, params, whenDone); } }
[ "function", "(", "name", ",", "params", ",", "callback", ")", "{", "var", "t", "=", "this", ",", "probe", "=", "t", ".", "probe", ",", "logId", "=", "'control.'", "+", "t", ".", "get", "(", "'probeClass'", ")", "+", "'.'", "+", "name", ",", "startTime", "=", "Date", ".", "now", "(", ")", ";", "// Switch callback if sent in 2nd arg", "if", "(", "typeof", "params", "===", "'function'", ")", "{", "callback", "=", "params", ";", "params", "=", "null", ";", "}", "log", ".", "info", "(", "logId", ",", "params", ")", ";", "var", "whenDone", "=", "function", "(", "error", ",", "args", ")", "{", "if", "(", "error", ")", "{", "log", ".", "error", "(", "logId", ",", "error", ")", ";", "}", "else", "{", "log", ".", "info", "(", "'return.'", "+", "logId", ",", "args", ")", ";", "stat", ".", "time", "(", "logId", ",", "Date", ".", "now", "(", ")", "-", "startTime", ")", ";", "}", "if", "(", "callback", ")", "{", "callback", ".", "apply", "(", "t", ",", "arguments", ")", ";", "}", "}", ";", "if", "(", "!", "probe", ")", "{", "return", "whenDone", "(", "'Probe not connected'", ")", ";", "}", "// Send the message internally or to the probe connection", "if", "(", "probe", ".", "connection", ")", "{", "probe", ".", "connection", ".", "emit", "(", "'probe:control'", ",", "{", "probeId", ":", "t", ".", "get", "(", "'probeId'", ")", ",", "name", ":", "name", ",", "params", ":", "params", "}", ",", "whenDone", ")", ";", "}", "else", "{", "probe", ".", "onControl", "(", "name", ",", "params", ",", "whenDone", ")", ";", "}", "}" ]
Send a control message to the probe. Monitors can use this method to send a message and receive a response from a connected probe. The probe must implement the specified control method. All probes are derived from the base <a href="Probe.html">Probe</a> class, which offers a ping control. To send a ping message to a probe and log the results: var myMonitor.control('ping', console.log); @method control @param name {String} Name of the control message. @param [params] {Object} Named input parameters specific to the control message. @param [callback] {Function(error, response)} Function to call upon return. <ul> <li>error (Any) - An object describing an error (null if no errors)</li> <li>response (Any) - Response parameters specific to the control message.</li> </ul>
[ "Send", "a", "control", "message", "to", "the", "probe", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L7046-L7084
23,191
lorenwest/node-monitor
dist/monitor-all.js
function(options) { var t = this, json = {id: t.get('probeId')}; // Transfer all non-monitor attrs _.each(t.toJSON(options), function(value, key) { if (!(key in t.defaults)) { json[key] = value; } }); return json; }
javascript
function(options) { var t = this, json = {id: t.get('probeId')}; // Transfer all non-monitor attrs _.each(t.toJSON(options), function(value, key) { if (!(key in t.defaults)) { json[key] = value; } }); return json; }
[ "function", "(", "options", ")", "{", "var", "t", "=", "this", ",", "json", "=", "{", "id", ":", "t", ".", "get", "(", "'probeId'", ")", "}", ";", "// Transfer all non-monitor attrs", "_", ".", "each", "(", "t", ".", "toJSON", "(", "options", ")", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "!", "(", "key", "in", "t", ".", "defaults", ")", ")", "{", "json", "[", "key", "]", "=", "value", ";", "}", "}", ")", ";", "return", "json", ";", "}" ]
Produce an object without monitor attributes A Monitor object contains a union of the connection attributes required for a Monitor, and the additional attributes defined by the probe it's monitoring. This method produces an object containing only the probe portion of those attributes. The id attribute of the returned JSON is set to the probeId from the monitor. @method toProbeJSON @param [options] {Object} Options to pass onto the model toJSON @return {Object} The probe attributes
[ "Produce", "an", "object", "without", "monitor", "attributes" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L7102-L7113
23,192
lorenwest/node-monitor
dist/monitor-all.js
function(name, params, callback) { var t = this, controlFn = t[name + '_control'], startTime = Date.now(), errMsg, logId = 'onControl.' + t.probeClass + '.' + name; params = params || {}; callback = callback || function(){}; log.info(logId, t.get('id'), params); if (!controlFn) { errMsg = 'No control function: ' + name; log.error(logId, errMsg); return callback({msg: errMsg}); } var whenDone = function(error) { if (error) { log.error(logId + '.whenDone', error); return callback(error); } var duration = Date.now() - startTime; log.info(logId, params); stat.time(t.logId, duration); callback.apply(null, arguments); }; // Run the control on next tick. This provides a consistent callback // chain for local and remote probes. setTimeout(function(){ try { controlFn.call(t, params, whenDone); } catch (e) { errMsg = 'Error calling control: ' + t.probeClass + ':' + name; whenDone({msg:errMsg, err: e.toString()}); } }, 0); }
javascript
function(name, params, callback) { var t = this, controlFn = t[name + '_control'], startTime = Date.now(), errMsg, logId = 'onControl.' + t.probeClass + '.' + name; params = params || {}; callback = callback || function(){}; log.info(logId, t.get('id'), params); if (!controlFn) { errMsg = 'No control function: ' + name; log.error(logId, errMsg); return callback({msg: errMsg}); } var whenDone = function(error) { if (error) { log.error(logId + '.whenDone', error); return callback(error); } var duration = Date.now() - startTime; log.info(logId, params); stat.time(t.logId, duration); callback.apply(null, arguments); }; // Run the control on next tick. This provides a consistent callback // chain for local and remote probes. setTimeout(function(){ try { controlFn.call(t, params, whenDone); } catch (e) { errMsg = 'Error calling control: ' + t.probeClass + ':' + name; whenDone({msg:errMsg, err: e.toString()}); } }, 0); }
[ "function", "(", "name", ",", "params", ",", "callback", ")", "{", "var", "t", "=", "this", ",", "controlFn", "=", "t", "[", "name", "+", "'_control'", "]", ",", "startTime", "=", "Date", ".", "now", "(", ")", ",", "errMsg", ",", "logId", "=", "'onControl.'", "+", "t", ".", "probeClass", "+", "'.'", "+", "name", ";", "params", "=", "params", "||", "{", "}", ";", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "log", ".", "info", "(", "logId", ",", "t", ".", "get", "(", "'id'", ")", ",", "params", ")", ";", "if", "(", "!", "controlFn", ")", "{", "errMsg", "=", "'No control function: '", "+", "name", ";", "log", ".", "error", "(", "logId", ",", "errMsg", ")", ";", "return", "callback", "(", "{", "msg", ":", "errMsg", "}", ")", ";", "}", "var", "whenDone", "=", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "log", ".", "error", "(", "logId", "+", "'.whenDone'", ",", "error", ")", ";", "return", "callback", "(", "error", ")", ";", "}", "var", "duration", "=", "Date", ".", "now", "(", ")", "-", "startTime", ";", "log", ".", "info", "(", "logId", ",", "params", ")", ";", "stat", ".", "time", "(", "t", ".", "logId", ",", "duration", ")", ";", "callback", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", ";", "// Run the control on next tick. This provides a consistent callback", "// chain for local and remote probes.", "setTimeout", "(", "function", "(", ")", "{", "try", "{", "controlFn", ".", "call", "(", "t", ",", "params", ",", "whenDone", ")", ";", "}", "catch", "(", "e", ")", "{", "errMsg", "=", "'Error calling control: '", "+", "t", ".", "probeClass", "+", "':'", "+", "name", ";", "whenDone", "(", "{", "msg", ":", "errMsg", ",", "err", ":", "e", ".", "toString", "(", ")", "}", ")", ";", "}", "}", ",", "0", ")", ";", "}" ]
Dispatch a control message to the appropriate control function. This is called when the <a href="Monitor.html#method_control">```control()```</a> method of a monitor is called. The name determines the method name called on the probe. The probe must implement a method with the name ```{name}_control()```, and that method must accept two parameters - an input params and a callback. The callback must be called, passing an optional error and response object. For example, if the probe supports a control with the name ```go```, then all it needs to do is implement the ```go_control()``` method with the proper signature. See ```ping_control()``` for an example. @method onControl @param name {String} Name of the control message. @param [params] {Any} Input parameters specific to the control message. @param [callback] {Function(error, response)} Called to send the message (or error) response. <ul> <li>error (Any) An object describing an error (null if no errors)</li> <li>response (Any) Response parameters specific to the control message. </ul>
[ "Dispatch", "a", "control", "message", "to", "the", "appropriate", "control", "function", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L8263-L8301
23,193
lorenwest/node-monitor
dist/monitor-all.js
function(attrs, callback) { var t = this, writableAttributes = t.get('writableAttributes') || []; // Validate the attributes are writable if (writableAttributes !== '*') { for (var attrName in attrs) { if (writableAttributes.indexOf(attrName) < 0) { return callback({code:'NOT_WRITABLE', msg: 'Attribute not writable: ' + attrName}); } } } // Set the data var error = null; if (!t.set(attrs)) { error = {code:'VALIDATION_ERROR', msg:'Data set failed validation'}; log.warn('set_control', error); } return callback(error); }
javascript
function(attrs, callback) { var t = this, writableAttributes = t.get('writableAttributes') || []; // Validate the attributes are writable if (writableAttributes !== '*') { for (var attrName in attrs) { if (writableAttributes.indexOf(attrName) < 0) { return callback({code:'NOT_WRITABLE', msg: 'Attribute not writable: ' + attrName}); } } } // Set the data var error = null; if (!t.set(attrs)) { error = {code:'VALIDATION_ERROR', msg:'Data set failed validation'}; log.warn('set_control', error); } return callback(error); }
[ "function", "(", "attrs", ",", "callback", ")", "{", "var", "t", "=", "this", ",", "writableAttributes", "=", "t", ".", "get", "(", "'writableAttributes'", ")", "||", "[", "]", ";", "// Validate the attributes are writable", "if", "(", "writableAttributes", "!==", "'*'", ")", "{", "for", "(", "var", "attrName", "in", "attrs", ")", "{", "if", "(", "writableAttributes", ".", "indexOf", "(", "attrName", ")", "<", "0", ")", "{", "return", "callback", "(", "{", "code", ":", "'NOT_WRITABLE'", ",", "msg", ":", "'Attribute not writable: '", "+", "attrName", "}", ")", ";", "}", "}", "}", "// Set the data", "var", "error", "=", "null", ";", "if", "(", "!", "t", ".", "set", "(", "attrs", ")", ")", "{", "error", "=", "{", "code", ":", "'VALIDATION_ERROR'", ",", "msg", ":", "'Data set failed validation'", "}", ";", "log", ".", "warn", "(", "'set_control'", ",", "error", ")", ";", "}", "return", "callback", "(", "error", ")", ";", "}" ]
Remotely set a probe attribute. This allows setting probe attributes that are listed in writableAttributes. It can be overwritten in derived Probe classes for greater control. @method set_control @param attrs {Object} Name/Value attributes to set. All must be writable. @param callback {Function(error)} Called when the attributes are set or error
[ "Remotely", "set", "a", "probe", "attribute", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L8313-L8333
23,194
lorenwest/node-monitor
dist/monitor-all.js
function(options, callback) { if (typeof options === 'function') { callback = options; options = null; } options = options || {}; callback = callback || function(){}; var t = this, server = t.get('server'), error, startTime = Date.now(), port = options.port || Config.Monitor.serviceBasePort, attempt = options.attempt || 1, allowExternalConnections = Config.Monitor.allowExternalConnections; // Recursion detection. Only scan for so many ports if (attempt > Config.Monitor.portsToScan) { error = {err:'connect:failure', msg: 'no ports available'}; log.error('start', error); return callback(error); } // Bind to an existing server, or create a new server if (server) { t.bindEvents(callback); } else { server = Http.createServer(); // Try next port if a server is listening on this port server.on('error', function(err) { if (err.code === 'EADDRINUSE') { // Error if the requested port is in use if (t.get('port')) { log.error('portInUse',{host:host, port:port}); return callback({err:'portInUse'}); } // Try the next port log.info('portInUse',{host:host, port:port}); return t.start({port:port + 1, attempt:attempt + 1}, callback); } // Unknown error callback(err); }); // Allow connections from INADDR_ANY or LOCALHOST only var host = allowExternalConnections ? '0.0.0.0' : '127.0.0.1'; // Start listening, callback on success server.listen(port, host, function(){ // Set a default NODE_APP_INSTANCE based on the available server port if (!process.env.NODE_APP_INSTANCE) { process.env.NODE_APP_INSTANCE = '' + (port - Config.Monitor.serviceBasePort + 1); } // Record the server & port, and bind incoming events t.set({server: server, port: port}); t.bindEvents(callback); log.info('listening', { appName: Config.Monitor.appName, NODE_APP_INSTANCE: process.env.NODE_APP_INSTANCE, listeningOn: host, port: port }); }); } }
javascript
function(options, callback) { if (typeof options === 'function') { callback = options; options = null; } options = options || {}; callback = callback || function(){}; var t = this, server = t.get('server'), error, startTime = Date.now(), port = options.port || Config.Monitor.serviceBasePort, attempt = options.attempt || 1, allowExternalConnections = Config.Monitor.allowExternalConnections; // Recursion detection. Only scan for so many ports if (attempt > Config.Monitor.portsToScan) { error = {err:'connect:failure', msg: 'no ports available'}; log.error('start', error); return callback(error); } // Bind to an existing server, or create a new server if (server) { t.bindEvents(callback); } else { server = Http.createServer(); // Try next port if a server is listening on this port server.on('error', function(err) { if (err.code === 'EADDRINUSE') { // Error if the requested port is in use if (t.get('port')) { log.error('portInUse',{host:host, port:port}); return callback({err:'portInUse'}); } // Try the next port log.info('portInUse',{host:host, port:port}); return t.start({port:port + 1, attempt:attempt + 1}, callback); } // Unknown error callback(err); }); // Allow connections from INADDR_ANY or LOCALHOST only var host = allowExternalConnections ? '0.0.0.0' : '127.0.0.1'; // Start listening, callback on success server.listen(port, host, function(){ // Set a default NODE_APP_INSTANCE based on the available server port if (!process.env.NODE_APP_INSTANCE) { process.env.NODE_APP_INSTANCE = '' + (port - Config.Monitor.serviceBasePort + 1); } // Record the server & port, and bind incoming events t.set({server: server, port: port}); t.bindEvents(callback); log.info('listening', { appName: Config.Monitor.appName, NODE_APP_INSTANCE: process.env.NODE_APP_INSTANCE, listeningOn: host, port: port }); }); } }
[ "function", "(", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "var", "t", "=", "this", ",", "server", "=", "t", ".", "get", "(", "'server'", ")", ",", "error", ",", "startTime", "=", "Date", ".", "now", "(", ")", ",", "port", "=", "options", ".", "port", "||", "Config", ".", "Monitor", ".", "serviceBasePort", ",", "attempt", "=", "options", ".", "attempt", "||", "1", ",", "allowExternalConnections", "=", "Config", ".", "Monitor", ".", "allowExternalConnections", ";", "// Recursion detection. Only scan for so many ports", "if", "(", "attempt", ">", "Config", ".", "Monitor", ".", "portsToScan", ")", "{", "error", "=", "{", "err", ":", "'connect:failure'", ",", "msg", ":", "'no ports available'", "}", ";", "log", ".", "error", "(", "'start'", ",", "error", ")", ";", "return", "callback", "(", "error", ")", ";", "}", "// Bind to an existing server, or create a new server", "if", "(", "server", ")", "{", "t", ".", "bindEvents", "(", "callback", ")", ";", "}", "else", "{", "server", "=", "Http", ".", "createServer", "(", ")", ";", "// Try next port if a server is listening on this port", "server", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "if", "(", "err", ".", "code", "===", "'EADDRINUSE'", ")", "{", "// Error if the requested port is in use", "if", "(", "t", ".", "get", "(", "'port'", ")", ")", "{", "log", ".", "error", "(", "'portInUse'", ",", "{", "host", ":", "host", ",", "port", ":", "port", "}", ")", ";", "return", "callback", "(", "{", "err", ":", "'portInUse'", "}", ")", ";", "}", "// Try the next port", "log", ".", "info", "(", "'portInUse'", ",", "{", "host", ":", "host", ",", "port", ":", "port", "}", ")", ";", "return", "t", ".", "start", "(", "{", "port", ":", "port", "+", "1", ",", "attempt", ":", "attempt", "+", "1", "}", ",", "callback", ")", ";", "}", "// Unknown error", "callback", "(", "err", ")", ";", "}", ")", ";", "// Allow connections from INADDR_ANY or LOCALHOST only", "var", "host", "=", "allowExternalConnections", "?", "'0.0.0.0'", ":", "'127.0.0.1'", ";", "// Start listening, callback on success", "server", ".", "listen", "(", "port", ",", "host", ",", "function", "(", ")", "{", "// Set a default NODE_APP_INSTANCE based on the available server port", "if", "(", "!", "process", ".", "env", ".", "NODE_APP_INSTANCE", ")", "{", "process", ".", "env", ".", "NODE_APP_INSTANCE", "=", "''", "+", "(", "port", "-", "Config", ".", "Monitor", ".", "serviceBasePort", "+", "1", ")", ";", "}", "// Record the server & port, and bind incoming events", "t", ".", "set", "(", "{", "server", ":", "server", ",", "port", ":", "port", "}", ")", ";", "t", ".", "bindEvents", "(", "callback", ")", ";", "log", ".", "info", "(", "'listening'", ",", "{", "appName", ":", "Config", ".", "Monitor", ".", "appName", ",", "NODE_APP_INSTANCE", ":", "process", ".", "env", ".", "NODE_APP_INSTANCE", ",", "listeningOn", ":", "host", ",", "port", ":", "port", "}", ")", ";", "}", ")", ";", "}", "}" ]
Start accepting monitor connections This method starts listening for incoming monitor connections on the server. If the server was specified during object creation, this binds the socket.io service to the server. If the server was not specified during object creation, this will create a server on the first available monitor port. @method start @param options {Object} - Start options. OPTIONAL @param options.port {Integer} - Port to attempt listening on if server isn't specified. Default: 42000 @param options.attempt {Integer} - Attempt number for internal recursion detection. Default: 1 @param callback {Function(error)} - Called when the server is accepting connections. The server has started This event is fired when the server has determined the port to accept connections on, and has successfully configured the server to start accepting new monitor connections. @event start A client error has been detected This event is fired if an error has been detected in the underlying transport. It may indicate message loss, and may result in a subsequent stop event if the connection cannot be restored. @event error
[ "Start", "accepting", "monitor", "connections" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9019-L9083
23,195
lorenwest/node-monitor
dist/monitor-all.js
function(callback) { var t = this, server = t.get('server'), router = Monitor.getRouter(); callback = callback || function(){}; // Call the callback, but don't stop more than once. if (!t.isListening) { return callback(); } // Release resources t.connections.each(router.removeConnection, router); t.connections.reset(); // Shut down the server t.isListening = false; server.close(); // Send notices t.trigger('stop'); return callback(); }
javascript
function(callback) { var t = this, server = t.get('server'), router = Monitor.getRouter(); callback = callback || function(){}; // Call the callback, but don't stop more than once. if (!t.isListening) { return callback(); } // Release resources t.connections.each(router.removeConnection, router); t.connections.reset(); // Shut down the server t.isListening = false; server.close(); // Send notices t.trigger('stop'); return callback(); }
[ "function", "(", "callback", ")", "{", "var", "t", "=", "this", ",", "server", "=", "t", ".", "get", "(", "'server'", ")", ",", "router", "=", "Monitor", ".", "getRouter", "(", ")", ";", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "// Call the callback, but don't stop more than once.", "if", "(", "!", "t", ".", "isListening", ")", "{", "return", "callback", "(", ")", ";", "}", "// Release resources", "t", ".", "connections", ".", "each", "(", "router", ".", "removeConnection", ",", "router", ")", ";", "t", ".", "connections", ".", "reset", "(", ")", ";", "// Shut down the server", "t", ".", "isListening", "=", "false", ";", "server", ".", "close", "(", ")", ";", "// Send notices", "t", ".", "trigger", "(", "'stop'", ")", ";", "return", "callback", "(", ")", ";", "}" ]
Stop processing inbound monitor traffic This method stops accepting new inbound monitor connections, and closes all existing monitor connections associated with the server. @method stop @param callback {Function(error)} - Called when the server has stopped The server has stopped This event is fired after the server has stopped accepting inbound connections, and has closed all existing connections and released associated resources. @event stop
[ "Stop", "processing", "inbound", "monitor", "traffic" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9153-L9173
23,196
lorenwest/node-monitor
dist/monitor-all.js
function(firewall) { var t = Monitor.getRouter(); // This is a static method t.firewall = firewall; log.info('setFirewall', firewall); }
javascript
function(firewall) { var t = Monitor.getRouter(); // This is a static method t.firewall = firewall; log.info('setFirewall', firewall); }
[ "function", "(", "firewall", ")", "{", "var", "t", "=", "Monitor", ".", "getRouter", "(", ")", ";", "// This is a static method", "t", ".", "firewall", "=", "firewall", ";", "log", ".", "info", "(", "'setFirewall'", ",", "firewall", ")", ";", "}" ]
Firewall new connections from inbound probe requests When two monitor processes connect, they become peers. By default each process can request probe connections with the other. If you want to connect with a remote probe, but don't want those servers to connect with probes in this process, call this method to firewall those inbound probe requests. Setting this will change the firewall value for all *new* connections. Any existing connections will still accept incoming probe requests. @static @method setFirewall @param firewall {Boolean} - Firewall new connections?
[ "Firewall", "new", "connections", "from", "inbound", "probe", "requests" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9272-L9276
23,197
lorenwest/node-monitor
dist/monitor-all.js
function(options) { var t = this; options.gateway = false; // New connection can't be an inbound gateway options.firewall = true; // Gateways are for outbound requests only return t.defaultGateway = t.addConnection(options); }
javascript
function(options) { var t = this; options.gateway = false; // New connection can't be an inbound gateway options.firewall = true; // Gateways are for outbound requests only return t.defaultGateway = t.addConnection(options); }
[ "function", "(", "options", ")", "{", "var", "t", "=", "this", ";", "options", ".", "gateway", "=", "false", ";", "// New connection can't be an inbound gateway", "options", ".", "firewall", "=", "true", ";", "// Gateways are for outbound requests only", "return", "t", ".", "defaultGateway", "=", "t", ".", "addConnection", "(", "options", ")", ";", "}" ]
Set the default gateway server The gateway server is used if a monitor cannot connect directly with the server hosting the probe. When a monitor is requested to connect with a probe on a specific server, a direct connection is attempted. If that direct connection fails, usually due to a firewall or browser restriction, the monitor will attempt the connection to the probe through the gateway server. The server specified in this method must have been started as a gateway like this: // Start a monitor server and act as a gateway var server = new Monitor.Server({gateway:true}); @method setGateway @param options {Object} - Connection parameters @param options.hostName {String} - Name of the gateway host @param options.hostPort {Integer} - Port number to connect with @param options.url {String} - The URL used to connect (created, or used if supplied) @param options.socket {io.socket} - Pre-connected socket.io socket to the gateway server. @return connection {Connection} - The connection with the gateway server
[ "Set", "the", "default", "gateway", "server" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9303-L9308
23,198
lorenwest/node-monitor
dist/monitor-all.js
function() { var localStorage = root.localStorage; if (!hostName) { if (localStorage) {hostName = localStorage.hostName;} hostName = hostName || Monitor.generateUniqueId(); if (localStorage) {localStorage.hostName = hostName;} } return hostName; }
javascript
function() { var localStorage = root.localStorage; if (!hostName) { if (localStorage) {hostName = localStorage.hostName;} hostName = hostName || Monitor.generateUniqueId(); if (localStorage) {localStorage.hostName = hostName;} } return hostName; }
[ "function", "(", ")", "{", "var", "localStorage", "=", "root", ".", "localStorage", ";", "if", "(", "!", "hostName", ")", "{", "if", "(", "localStorage", ")", "{", "hostName", "=", "localStorage", ".", "hostName", ";", "}", "hostName", "=", "hostName", "||", "Monitor", ".", "generateUniqueId", "(", ")", ";", "if", "(", "localStorage", ")", "{", "localStorage", ".", "hostName", "=", "hostName", ";", "}", "}", "return", "hostName", ";", "}" ]
Return a stable host name. @method getHostName @protected @return hostName {String} - The platform's host name, or an otherwise stable ID
[ "Return", "a", "stable", "host", "name", "." ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9317-L9325
23,199
lorenwest/node-monitor
dist/monitor-all.js
function(options) { var t = this, startTime = Date.now(); // Default the firewall value if (_.isUndefined(options.firewall)) { options = _.extend({},options, {firewall: t.firewall}); } // Generate a unique ID for the connection options.id = Monitor.generateUniqueCollectionId(t.connections); var connStr = 'Conn_' + options.id; if (options.hostName) { connStr += ' - ' + options.hostName + ':' + options.hostPort; } log.info('addConnection', connStr); // Instantiate and add the connection for use, once connected var connection = new Connection(options); // Add a connect and disconnect function var onConnect = function(){ t.trigger('connection:add', connection); log.info('connected', connStr, (Date.now() - startTime) + 'ms'); }; var onDisconnect = function(){ t.removeConnection(connection); connection.off('connect', onConnect); connection.off('disconnect', onConnect); log.info('disconnected', connStr, (Date.now() - startTime) + 'ms'); }; connection.on('connect', onConnect); connection.on('disconnect', onDisconnect); // Add to the connections t.connections.add(connection); return connection; }
javascript
function(options) { var t = this, startTime = Date.now(); // Default the firewall value if (_.isUndefined(options.firewall)) { options = _.extend({},options, {firewall: t.firewall}); } // Generate a unique ID for the connection options.id = Monitor.generateUniqueCollectionId(t.connections); var connStr = 'Conn_' + options.id; if (options.hostName) { connStr += ' - ' + options.hostName + ':' + options.hostPort; } log.info('addConnection', connStr); // Instantiate and add the connection for use, once connected var connection = new Connection(options); // Add a connect and disconnect function var onConnect = function(){ t.trigger('connection:add', connection); log.info('connected', connStr, (Date.now() - startTime) + 'ms'); }; var onDisconnect = function(){ t.removeConnection(connection); connection.off('connect', onConnect); connection.off('disconnect', onConnect); log.info('disconnected', connStr, (Date.now() - startTime) + 'ms'); }; connection.on('connect', onConnect); connection.on('disconnect', onDisconnect); // Add to the connections t.connections.add(connection); return connection; }
[ "function", "(", "options", ")", "{", "var", "t", "=", "this", ",", "startTime", "=", "Date", ".", "now", "(", ")", ";", "// Default the firewall value", "if", "(", "_", ".", "isUndefined", "(", "options", ".", "firewall", ")", ")", "{", "options", "=", "_", ".", "extend", "(", "{", "}", ",", "options", ",", "{", "firewall", ":", "t", ".", "firewall", "}", ")", ";", "}", "// Generate a unique ID for the connection", "options", ".", "id", "=", "Monitor", ".", "generateUniqueCollectionId", "(", "t", ".", "connections", ")", ";", "var", "connStr", "=", "'Conn_'", "+", "options", ".", "id", ";", "if", "(", "options", ".", "hostName", ")", "{", "connStr", "+=", "' - '", "+", "options", ".", "hostName", "+", "':'", "+", "options", ".", "hostPort", ";", "}", "log", ".", "info", "(", "'addConnection'", ",", "connStr", ")", ";", "// Instantiate and add the connection for use, once connected", "var", "connection", "=", "new", "Connection", "(", "options", ")", ";", "// Add a connect and disconnect function", "var", "onConnect", "=", "function", "(", ")", "{", "t", ".", "trigger", "(", "'connection:add'", ",", "connection", ")", ";", "log", ".", "info", "(", "'connected'", ",", "connStr", ",", "(", "Date", ".", "now", "(", ")", "-", "startTime", ")", "+", "'ms'", ")", ";", "}", ";", "var", "onDisconnect", "=", "function", "(", ")", "{", "t", ".", "removeConnection", "(", "connection", ")", ";", "connection", ".", "off", "(", "'connect'", ",", "onConnect", ")", ";", "connection", ".", "off", "(", "'disconnect'", ",", "onConnect", ")", ";", "log", ".", "info", "(", "'disconnected'", ",", "connStr", ",", "(", "Date", ".", "now", "(", ")", "-", "startTime", ")", "+", "'ms'", ")", ";", "}", ";", "connection", ".", "on", "(", "'connect'", ",", "onConnect", ")", ";", "connection", ".", "on", "(", "'disconnect'", ",", "onDisconnect", ")", ";", "// Add to the connections", "t", ".", "connections", ".", "add", "(", "connection", ")", ";", "return", "connection", ";", "}" ]
Add a connection to a remote Monitor process @method addConnection @protected @param options {Object} - Connection parameters @param options.hostName {String} - Name of the host to connect with @param options.hostPort {Integer} - Port number to connect with @param options.url {String} - The URL used to connect (created, or used if supplied) @param options.socket {io.socket} - Pre-connected socket.io socket to a Monitor server. @param options.gateway {Boolean} - Allow this connection to use me as a gateway (default false) @param options.firewall {Boolean} Firewall inbound probe requests on this connection? @return connection {Connection} - The added connection
[ "Add", "a", "connection", "to", "a", "remote", "Monitor", "process" ]
7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8
https://github.com/lorenwest/node-monitor/blob/7afd5d22c1d44b93c7cb2250ea9e05ef7b8451f8/dist/monitor-all.js#L9356-L9394