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
|
---|---|---|---|---|---|---|---|---|---|---|---|
43,900 | tonistiigi/styler | lib/public/build/editor.js | function(session) {
this.session = session;
this.doc = session.getDocument();
this.clearSelection();
this.selectionLead = this.doc.createAnchor(0, 0);
this.selectionAnchor = this.doc.createAnchor(0, 0);
var _self = this;
this.selectionLead.on("change", function(e) {
_self._emit("changeCursor");
if (!_self.$isEmpty)
_self._emit("changeSelection");
if (!_self.$preventUpdateDesiredColumnOnChange && e.old.column != e.value.column)
_self.$updateDesiredColumn();
});
this.selectionAnchor.on("change", function() {
if (!_self.$isEmpty)
_self._emit("changeSelection");
});
} | javascript | function(session) {
this.session = session;
this.doc = session.getDocument();
this.clearSelection();
this.selectionLead = this.doc.createAnchor(0, 0);
this.selectionAnchor = this.doc.createAnchor(0, 0);
var _self = this;
this.selectionLead.on("change", function(e) {
_self._emit("changeCursor");
if (!_self.$isEmpty)
_self._emit("changeSelection");
if (!_self.$preventUpdateDesiredColumnOnChange && e.old.column != e.value.column)
_self.$updateDesiredColumn();
});
this.selectionAnchor.on("change", function() {
if (!_self.$isEmpty)
_self._emit("changeSelection");
});
} | [
"function",
"(",
"session",
")",
"{",
"this",
".",
"session",
"=",
"session",
";",
"this",
".",
"doc",
"=",
"session",
".",
"getDocument",
"(",
")",
";",
"this",
".",
"clearSelection",
"(",
")",
";",
"this",
".",
"selectionLead",
"=",
"this",
".",
"doc",
".",
"createAnchor",
"(",
"0",
",",
"0",
")",
";",
"this",
".",
"selectionAnchor",
"=",
"this",
".",
"doc",
".",
"createAnchor",
"(",
"0",
",",
"0",
")",
";",
"var",
"_self",
"=",
"this",
";",
"this",
".",
"selectionLead",
".",
"on",
"(",
"\"change\"",
",",
"function",
"(",
"e",
")",
"{",
"_self",
".",
"_emit",
"(",
"\"changeCursor\"",
")",
";",
"if",
"(",
"!",
"_self",
".",
"$isEmpty",
")",
"_self",
".",
"_emit",
"(",
"\"changeSelection\"",
")",
";",
"if",
"(",
"!",
"_self",
".",
"$preventUpdateDesiredColumnOnChange",
"&&",
"e",
".",
"old",
".",
"column",
"!=",
"e",
".",
"value",
".",
"column",
")",
"_self",
".",
"$updateDesiredColumn",
"(",
")",
";",
"}",
")",
";",
"this",
".",
"selectionAnchor",
".",
"on",
"(",
"\"change\"",
",",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"_self",
".",
"$isEmpty",
")",
"_self",
".",
"_emit",
"(",
"\"changeSelection\"",
")",
";",
"}",
")",
";",
"}"
]
| Keeps cursor position and the text selection of an edit session.
The row/columns used in the selection are in document coordinates
representing ths coordinates as thez appear in the document
before applying soft wrap and folding. | [
"Keeps",
"cursor",
"position",
"and",
"the",
"text",
"selection",
"of",
"an",
"edit",
"session",
"."
]
| f20dd9621f671b77cbb660d35327e007e8a56e2a | https://github.com/tonistiigi/styler/blob/f20dd9621f671b77cbb660d35327e007e8a56e2a/lib/public/build/editor.js#L10737-L10758 |
|
43,901 | tonistiigi/styler | lib/public/build/editor.js | function(data, hashId, key, keyCode, e) {
// If we pressed any command key but no other key, then ignore the input.
// Otherwise "shift-" is added to the buffer, and later on "shift-g"
// which results in "shift-shift-g" which doesn't make sense.
if (hashId != 0 && (key == "" || key == String.fromCharCode(0))) {
return null;
}
// Compute the current value of the keyboard input buffer.
var r = this.$composeBuffer(data, hashId, key, e);
var buffer = r.bufferToUse;
var symbolicName = r.symbolicName;
var keyId = r.keyIdentifier;
r = this.$find(data, buffer, symbolicName, hashId, key, keyId);
if (DEBUG) {
console.log("KeyboardStateMapper#match", buffer, symbolicName, r);
}
return r;
} | javascript | function(data, hashId, key, keyCode, e) {
// If we pressed any command key but no other key, then ignore the input.
// Otherwise "shift-" is added to the buffer, and later on "shift-g"
// which results in "shift-shift-g" which doesn't make sense.
if (hashId != 0 && (key == "" || key == String.fromCharCode(0))) {
return null;
}
// Compute the current value of the keyboard input buffer.
var r = this.$composeBuffer(data, hashId, key, e);
var buffer = r.bufferToUse;
var symbolicName = r.symbolicName;
var keyId = r.keyIdentifier;
r = this.$find(data, buffer, symbolicName, hashId, key, keyId);
if (DEBUG) {
console.log("KeyboardStateMapper#match", buffer, symbolicName, r);
}
return r;
} | [
"function",
"(",
"data",
",",
"hashId",
",",
"key",
",",
"keyCode",
",",
"e",
")",
"{",
"// If we pressed any command key but no other key, then ignore the input.",
"// Otherwise \"shift-\" is added to the buffer, and later on \"shift-g\"",
"// which results in \"shift-shift-g\" which doesn't make sense.",
"if",
"(",
"hashId",
"!=",
"0",
"&&",
"(",
"key",
"==",
"\"\"",
"||",
"key",
"==",
"String",
".",
"fromCharCode",
"(",
"0",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"// Compute the current value of the keyboard input buffer.",
"var",
"r",
"=",
"this",
".",
"$composeBuffer",
"(",
"data",
",",
"hashId",
",",
"key",
",",
"e",
")",
";",
"var",
"buffer",
"=",
"r",
".",
"bufferToUse",
";",
"var",
"symbolicName",
"=",
"r",
".",
"symbolicName",
";",
"var",
"keyId",
"=",
"r",
".",
"keyIdentifier",
";",
"r",
"=",
"this",
".",
"$find",
"(",
"data",
",",
"buffer",
",",
"symbolicName",
",",
"hashId",
",",
"key",
",",
"keyId",
")",
";",
"if",
"(",
"DEBUG",
")",
"{",
"console",
".",
"log",
"(",
"\"KeyboardStateMapper#match\"",
",",
"buffer",
",",
"symbolicName",
",",
"r",
")",
";",
"}",
"return",
"r",
";",
"}"
]
| This function is called by keyBinding. | [
"This",
"function",
"is",
"called",
"by",
"keyBinding",
"."
]
| f20dd9621f671b77cbb660d35327e007e8a56e2a | https://github.com/tonistiigi/styler/blob/f20dd9621f671b77cbb660d35327e007e8a56e2a/lib/public/build/editor.js#L17825-L17845 |
|
43,902 | aholstenson/ecolect-js | src/graph/matching/match-set.js | findInsertLocation | function findInsertLocation(matches, score) {
const idx = binarySearch(matches, 0, matches.length, score);
if(idx < 0) {
// If the score was not found
return - idx - 1;
}
/*
* Something with the same score was found, make sure this item is
* added after all previous items with the same score.
*/
for(let i=idx+1; i<matches.length; i++) {
if(matches[i].score < score) return i;
}
return matches.length;
} | javascript | function findInsertLocation(matches, score) {
const idx = binarySearch(matches, 0, matches.length, score);
if(idx < 0) {
// If the score was not found
return - idx - 1;
}
/*
* Something with the same score was found, make sure this item is
* added after all previous items with the same score.
*/
for(let i=idx+1; i<matches.length; i++) {
if(matches[i].score < score) return i;
}
return matches.length;
} | [
"function",
"findInsertLocation",
"(",
"matches",
",",
"score",
")",
"{",
"const",
"idx",
"=",
"binarySearch",
"(",
"matches",
",",
"0",
",",
"matches",
".",
"length",
",",
"score",
")",
";",
"if",
"(",
"idx",
"<",
"0",
")",
"{",
"// If the score was not found",
"return",
"-",
"idx",
"-",
"1",
";",
"}",
"/*\n\t\t* Something with the same score was found, make sure this item is\n\t\t* added after all previous items with the same score.\n\t\t*/",
"for",
"(",
"let",
"i",
"=",
"idx",
"+",
"1",
";",
"i",
"<",
"matches",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"matches",
"[",
"i",
"]",
".",
"score",
"<",
"score",
")",
"return",
"i",
";",
"}",
"return",
"matches",
".",
"length",
";",
"}"
]
| Find the insert location of an matches with the given score.
@param {number} score | [
"Find",
"the",
"insert",
"location",
"of",
"an",
"matches",
"with",
"the",
"given",
"score",
"."
]
| db7f473a7d38588778b5724daa6ad38ac5ea4ec4 | https://github.com/aholstenson/ecolect-js/blob/db7f473a7d38588778b5724daa6ad38ac5ea4ec4/src/graph/matching/match-set.js#L28-L45 |
43,903 | layerhq/node-layer-webhooks-services | src/listen.js | handleValidation | function handleValidation(req, res, next) {
var payload = JSON.stringify(req.body);
var nodeVersion = Number(process.version.replace(/^v/, '').split(/\./)[0]);
var utf8safe = nodeVersion >= 6 ? payload : unescape(encodeURIComponent(payload));
var hash = crypto.createHmac('sha1', secret).update(utf8safe).digest('hex');
var signature = req.get('layer-webhook-signature');
if (hash === signature) next();
else {
loggerError('Computed HMAC Signature ' + hash + ' did not match signed header ' + signature + '. Returning Error. Config:', JSON.stringify(payload.config || {}));
res.sendStatus(403);
}
} | javascript | function handleValidation(req, res, next) {
var payload = JSON.stringify(req.body);
var nodeVersion = Number(process.version.replace(/^v/, '').split(/\./)[0]);
var utf8safe = nodeVersion >= 6 ? payload : unescape(encodeURIComponent(payload));
var hash = crypto.createHmac('sha1', secret).update(utf8safe).digest('hex');
var signature = req.get('layer-webhook-signature');
if (hash === signature) next();
else {
loggerError('Computed HMAC Signature ' + hash + ' did not match signed header ' + signature + '. Returning Error. Config:', JSON.stringify(payload.config || {}));
res.sendStatus(403);
}
} | [
"function",
"handleValidation",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"var",
"payload",
"=",
"JSON",
".",
"stringify",
"(",
"req",
".",
"body",
")",
";",
"var",
"nodeVersion",
"=",
"Number",
"(",
"process",
".",
"version",
".",
"replace",
"(",
"/",
"^v",
"/",
",",
"''",
")",
".",
"split",
"(",
"/",
"\\.",
"/",
")",
"[",
"0",
"]",
")",
";",
"var",
"utf8safe",
"=",
"nodeVersion",
">=",
"6",
"?",
"payload",
":",
"unescape",
"(",
"encodeURIComponent",
"(",
"payload",
")",
")",
";",
"var",
"hash",
"=",
"crypto",
".",
"createHmac",
"(",
"'sha1'",
",",
"secret",
")",
".",
"update",
"(",
"utf8safe",
")",
".",
"digest",
"(",
"'hex'",
")",
";",
"var",
"signature",
"=",
"req",
".",
"get",
"(",
"'layer-webhook-signature'",
")",
";",
"if",
"(",
"hash",
"===",
"signature",
")",
"next",
"(",
")",
";",
"else",
"{",
"loggerError",
"(",
"'Computed HMAC Signature '",
"+",
"hash",
"+",
"' did not match signed header '",
"+",
"signature",
"+",
"'. Returning Error. Config:'",
",",
"JSON",
".",
"stringify",
"(",
"payload",
".",
"config",
"||",
"{",
"}",
")",
")",
";",
"res",
".",
"sendStatus",
"(",
"403",
")",
";",
"}",
"}"
]
| Validate that the request comes from Layer services by comparing the secret
provided when registering the webhook with the 'layer-webhook-signature' header. | [
"Validate",
"that",
"the",
"request",
"comes",
"from",
"Layer",
"services",
"by",
"comparing",
"the",
"secret",
"provided",
"when",
"registering",
"the",
"webhook",
"with",
"the",
"layer",
"-",
"webhook",
"-",
"signature",
"header",
"."
]
| 7ef63df31fb5b769ebe57b8855806178e1ce8dd8 | https://github.com/layerhq/node-layer-webhooks-services/blob/7ef63df31fb5b769ebe57b8855806178e1ce8dd8/src/listen.js#L120-L133 |
43,904 | cast-org/figuration | js/tab-responsive.js | function(node) {
var $activeTab = $(node);
var data = $($activeTab).data('cfw.tab');
if (data) {
var $activePane = data.$target;
var $paneContainer = $activePane.closest('.tab-content');
$paneContainer.find('[data-cfw="collapse"]').each(function() {
$(this).one('afterHide.cfw.collapse', function(e) {
e.stopPropagation();
e.preventDefault();
})
.CFW_Collapse('hide');
});
var $collapseItem = $activePane.find('[data-cfw="collapse"]');
$collapseItem.one('afterShow.cfw.collapse', function(e) {
e.stopPropagation();
e.preventDefault();
})
.CFW_Collapse('show');
}
} | javascript | function(node) {
var $activeTab = $(node);
var data = $($activeTab).data('cfw.tab');
if (data) {
var $activePane = data.$target;
var $paneContainer = $activePane.closest('.tab-content');
$paneContainer.find('[data-cfw="collapse"]').each(function() {
$(this).one('afterHide.cfw.collapse', function(e) {
e.stopPropagation();
e.preventDefault();
})
.CFW_Collapse('hide');
});
var $collapseItem = $activePane.find('[data-cfw="collapse"]');
$collapseItem.one('afterShow.cfw.collapse', function(e) {
e.stopPropagation();
e.preventDefault();
})
.CFW_Collapse('show');
}
} | [
"function",
"(",
"node",
")",
"{",
"var",
"$activeTab",
"=",
"$",
"(",
"node",
")",
";",
"var",
"data",
"=",
"$",
"(",
"$activeTab",
")",
".",
"data",
"(",
"'cfw.tab'",
")",
";",
"if",
"(",
"data",
")",
"{",
"var",
"$activePane",
"=",
"data",
".",
"$target",
";",
"var",
"$paneContainer",
"=",
"$activePane",
".",
"closest",
"(",
"'.tab-content'",
")",
";",
"$paneContainer",
".",
"find",
"(",
"'[data-cfw=\"collapse\"]'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"$",
"(",
"this",
")",
".",
"one",
"(",
"'afterHide.cfw.collapse'",
",",
"function",
"(",
"e",
")",
"{",
"e",
".",
"stopPropagation",
"(",
")",
";",
"e",
".",
"preventDefault",
"(",
")",
";",
"}",
")",
".",
"CFW_Collapse",
"(",
"'hide'",
")",
";",
"}",
")",
";",
"var",
"$collapseItem",
"=",
"$activePane",
".",
"find",
"(",
"'[data-cfw=\"collapse\"]'",
")",
";",
"$collapseItem",
".",
"one",
"(",
"'afterShow.cfw.collapse'",
",",
"function",
"(",
"e",
")",
"{",
"e",
".",
"stopPropagation",
"(",
")",
";",
"e",
".",
"preventDefault",
"(",
")",
";",
"}",
")",
".",
"CFW_Collapse",
"(",
"'show'",
")",
";",
"}",
"}"
]
| Open the collapse element in the active panel Closes all related collapse items first | [
"Open",
"the",
"collapse",
"element",
"in",
"the",
"active",
"panel",
"Closes",
"all",
"related",
"collapse",
"items",
"first"
]
| c82f491ebccb477f7e1c945bfff61c2340afe1ac | https://github.com/cast-org/figuration/blob/c82f491ebccb477f7e1c945bfff61c2340afe1ac/js/tab-responsive.js#L50-L71 |
|
43,905 | cast-org/figuration | js/tab-responsive.js | function(node) {
var $activeCollapse = $(node);
var $paneParent = $activeCollapse.closest('.tab-pane');
var $paneID = $paneParent.attr('id');
var $paneContainer = $activeCollapse.closest('.tab-content');
$paneContainer.find('[data-cfw="collapse"]').each(function() {
var $this = $(this);
if ($this[0] === $activeCollapse[0]) {
return;
}
$this.CFW_Collapse('hide');
});
var $tabList = this.$element.find('[data-cfw="tab"]');
$tabList.each(function() {
var $this = $(this);
var selector = $this.attr('data-cfw-tab-target');
if (!selector) {
selector = $this.attr('href');
}
selector = selector.replace(/^#/, '');
if (selector == $paneID) {
$this.one('beforeShow.cfw.tab', function(e) {
e.stopPropagation();
})
.CFW_Tab('show');
}
});
} | javascript | function(node) {
var $activeCollapse = $(node);
var $paneParent = $activeCollapse.closest('.tab-pane');
var $paneID = $paneParent.attr('id');
var $paneContainer = $activeCollapse.closest('.tab-content');
$paneContainer.find('[data-cfw="collapse"]').each(function() {
var $this = $(this);
if ($this[0] === $activeCollapse[0]) {
return;
}
$this.CFW_Collapse('hide');
});
var $tabList = this.$element.find('[data-cfw="tab"]');
$tabList.each(function() {
var $this = $(this);
var selector = $this.attr('data-cfw-tab-target');
if (!selector) {
selector = $this.attr('href');
}
selector = selector.replace(/^#/, '');
if (selector == $paneID) {
$this.one('beforeShow.cfw.tab', function(e) {
e.stopPropagation();
})
.CFW_Tab('show');
}
});
} | [
"function",
"(",
"node",
")",
"{",
"var",
"$activeCollapse",
"=",
"$",
"(",
"node",
")",
";",
"var",
"$paneParent",
"=",
"$activeCollapse",
".",
"closest",
"(",
"'.tab-pane'",
")",
";",
"var",
"$paneID",
"=",
"$paneParent",
".",
"attr",
"(",
"'id'",
")",
";",
"var",
"$paneContainer",
"=",
"$activeCollapse",
".",
"closest",
"(",
"'.tab-content'",
")",
";",
"$paneContainer",
".",
"find",
"(",
"'[data-cfw=\"collapse\"]'",
")",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"$this",
"=",
"$",
"(",
"this",
")",
";",
"if",
"(",
"$this",
"[",
"0",
"]",
"===",
"$activeCollapse",
"[",
"0",
"]",
")",
"{",
"return",
";",
"}",
"$this",
".",
"CFW_Collapse",
"(",
"'hide'",
")",
";",
"}",
")",
";",
"var",
"$tabList",
"=",
"this",
".",
"$element",
".",
"find",
"(",
"'[data-cfw=\"tab\"]'",
")",
";",
"$tabList",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"$this",
"=",
"$",
"(",
"this",
")",
";",
"var",
"selector",
"=",
"$this",
".",
"attr",
"(",
"'data-cfw-tab-target'",
")",
";",
"if",
"(",
"!",
"selector",
")",
"{",
"selector",
"=",
"$this",
".",
"attr",
"(",
"'href'",
")",
";",
"}",
"selector",
"=",
"selector",
".",
"replace",
"(",
"/",
"^#",
"/",
",",
"''",
")",
";",
"if",
"(",
"selector",
"==",
"$paneID",
")",
"{",
"$this",
".",
"one",
"(",
"'beforeShow.cfw.tab'",
",",
"function",
"(",
"e",
")",
"{",
"e",
".",
"stopPropagation",
"(",
")",
";",
"}",
")",
".",
"CFW_Tab",
"(",
"'show'",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Set parent panel to active when collapse called Close all other collapse items | [
"Set",
"parent",
"panel",
"to",
"active",
"when",
"collapse",
"called",
"Close",
"all",
"other",
"collapse",
"items"
]
| c82f491ebccb477f7e1c945bfff61c2340afe1ac | https://github.com/cast-org/figuration/blob/c82f491ebccb477f7e1c945bfff61c2340afe1ac/js/tab-responsive.js#L75-L104 |
|
43,906 | NickCis/react-data-ssr | packages/react-data-ssr-server/src/resolveInitialData.js | resolveInitialData | function resolveInitialData(branches, extra) {
const errors = {};
const { promises, keys } = branches.reduce(
({ promises, keys }, b) => {
const getInitialData = (b.route ? b.route.component : b.component || b)
.getInitialData;
if (getInitialData) {
const { promise, key } = getInitialData(b, extra);
promises.push(promise.catch(e => (errors[key] = e)));
keys.push(key);
}
return {
promises,
keys,
};
},
{ promises: [], keys: [] }
);
return Promise.all(promises).then(data => ({
errors,
store: keys.reduce((s, k, i) => {
if (!(k in errors)) s[k] = data[i];
return s;
}, {}),
}));
} | javascript | function resolveInitialData(branches, extra) {
const errors = {};
const { promises, keys } = branches.reduce(
({ promises, keys }, b) => {
const getInitialData = (b.route ? b.route.component : b.component || b)
.getInitialData;
if (getInitialData) {
const { promise, key } = getInitialData(b, extra);
promises.push(promise.catch(e => (errors[key] = e)));
keys.push(key);
}
return {
promises,
keys,
};
},
{ promises: [], keys: [] }
);
return Promise.all(promises).then(data => ({
errors,
store: keys.reduce((s, k, i) => {
if (!(k in errors)) s[k] = data[i];
return s;
}, {}),
}));
} | [
"function",
"resolveInitialData",
"(",
"branches",
",",
"extra",
")",
"{",
"const",
"errors",
"=",
"{",
"}",
";",
"const",
"{",
"promises",
",",
"keys",
"}",
"=",
"branches",
".",
"reduce",
"(",
"(",
"{",
"promises",
",",
"keys",
"}",
",",
"b",
")",
"=>",
"{",
"const",
"getInitialData",
"=",
"(",
"b",
".",
"route",
"?",
"b",
".",
"route",
".",
"component",
":",
"b",
".",
"component",
"||",
"b",
")",
".",
"getInitialData",
";",
"if",
"(",
"getInitialData",
")",
"{",
"const",
"{",
"promise",
",",
"key",
"}",
"=",
"getInitialData",
"(",
"b",
",",
"extra",
")",
";",
"promises",
".",
"push",
"(",
"promise",
".",
"catch",
"(",
"e",
"=>",
"(",
"errors",
"[",
"key",
"]",
"=",
"e",
")",
")",
")",
";",
"keys",
".",
"push",
"(",
"key",
")",
";",
"}",
"return",
"{",
"promises",
",",
"keys",
",",
"}",
";",
"}",
",",
"{",
"promises",
":",
"[",
"]",
",",
"keys",
":",
"[",
"]",
"}",
")",
";",
"return",
"Promise",
".",
"all",
"(",
"promises",
")",
".",
"then",
"(",
"data",
"=>",
"(",
"{",
"errors",
",",
"store",
":",
"keys",
".",
"reduce",
"(",
"(",
"s",
",",
"k",
",",
"i",
")",
"=>",
"{",
"if",
"(",
"!",
"(",
"k",
"in",
"errors",
")",
")",
"s",
"[",
"k",
"]",
"=",
"data",
"[",
"i",
"]",
";",
"return",
"s",
";",
"}",
",",
"{",
"}",
")",
",",
"}",
")",
")",
";",
"}"
]
| Server side initial data resolution for react-data-ssr.
This function support 3 types of branches:
- React Router Config: `{ route: { component: Component, routes: [] }, match: { path: '', url: '', params: {}, isExact: } }`
- Dictionary: `{ component: Component, ... }`
- Component: `Component`
The branches argument can be a mixed list of the branch types. This function searches the Component object following the previous order and calls the `getInitialData` static method.
Then, it waits for the returned promises to be resolved.
@param {Array} branches - A list of branches. (React router config branches, { component: Component, ...}, component list, etc)
@param {Object} extra - Extra data that will be passed to `getInitialData` (see `mapArgsToProps`)
@return {Promise} - Will resolve when all `getInitialData` promises are resolved. It passes: `{ errors: Object, store: Object }`. `errors` is a dictionary that relates the components (by the key), that have a failing promise, with the error. `store` is a dictionary that relates successful components (by the key) with the resolved data. | [
"Server",
"side",
"initial",
"data",
"resolution",
"for",
"react",
"-",
"data",
"-",
"ssr",
"."
]
| 5271a04ed62e53a6a0fef09471f751e778aede10 | https://github.com/NickCis/react-data-ssr/blob/5271a04ed62e53a6a0fef09471f751e778aede10/packages/react-data-ssr-server/src/resolveInitialData.js#L15-L43 |
43,907 | opendxl/opendxl-client-javascript | lib/_cli/cli-update-config.js | cliUpdateConfig | function cliUpdateConfig (configDir, hostname, command) {
cliUtil.fillEmptyServerCredentialsFromPrompt(command,
function (error) {
if (error) {
provisionUtil.invokeCallback(error, command.doneCallback,
command.verbosity)
} else {
updateConfig(configDir,
cliUtil.pullHostInfoFromCommand(hostname, command),
command)
}
}
)
} | javascript | function cliUpdateConfig (configDir, hostname, command) {
cliUtil.fillEmptyServerCredentialsFromPrompt(command,
function (error) {
if (error) {
provisionUtil.invokeCallback(error, command.doneCallback,
command.verbosity)
} else {
updateConfig(configDir,
cliUtil.pullHostInfoFromCommand(hostname, command),
command)
}
}
)
} | [
"function",
"cliUpdateConfig",
"(",
"configDir",
",",
"hostname",
",",
"command",
")",
"{",
"cliUtil",
".",
"fillEmptyServerCredentialsFromPrompt",
"(",
"command",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"provisionUtil",
".",
"invokeCallback",
"(",
"error",
",",
"command",
".",
"doneCallback",
",",
"command",
".",
"verbosity",
")",
"}",
"else",
"{",
"updateConfig",
"(",
"configDir",
",",
"cliUtil",
".",
"pullHostInfoFromCommand",
"(",
"hostname",
",",
"command",
")",
",",
"command",
")",
"}",
"}",
")",
"}"
]
| Action function invoked for the updateconfig subcommand.
@param {String} configDir - Directory in which to store the private key
and CSR file.
@param {String} hostname - Name of the management service host.
@param {Command} command - The Commander command to append options onto. | [
"Action",
"function",
"invoked",
"for",
"the",
"updateconfig",
"subcommand",
"."
]
| eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997 | https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_cli/cli-update-config.js#L19-L32 |
43,908 | silas/swagger-framework | lib/framework/router.js | FrameworkRouter | function FrameworkRouter(framework) {
debug('create framework router');
this.framework = framework;
this.encoder = lodash.clone(http.encoder);
this.decoder = lodash.clone(http.decoder);
} | javascript | function FrameworkRouter(framework) {
debug('create framework router');
this.framework = framework;
this.encoder = lodash.clone(http.encoder);
this.decoder = lodash.clone(http.decoder);
} | [
"function",
"FrameworkRouter",
"(",
"framework",
")",
"{",
"debug",
"(",
"'create framework router'",
")",
";",
"this",
".",
"framework",
"=",
"framework",
";",
"this",
".",
"encoder",
"=",
"lodash",
".",
"clone",
"(",
"http",
".",
"encoder",
")",
";",
"this",
".",
"decoder",
"=",
"lodash",
".",
"clone",
"(",
"http",
".",
"decoder",
")",
";",
"}"
]
| Initialize a new `FrameworkRouter`.
@param {Framework} framework
@api private | [
"Initialize",
"a",
"new",
"FrameworkRouter",
"."
]
| d5b5bcb30feafc5e37b431ec09e494f9b6303950 | https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/framework/router.js#L27-L33 |
43,909 | opendxl/opendxl-client-javascript | lib/_provisioning/provision-util.js | function (message, component, header) {
if (typeof header === 'undefined') {
header = ''
}
if (component) {
if (header) {
header += ' '
}
header += '('
header += component
header += ')'
}
if (header) {
message = header + ': ' + message
}
return message
} | javascript | function (message, component, header) {
if (typeof header === 'undefined') {
header = ''
}
if (component) {
if (header) {
header += ' '
}
header += '('
header += component
header += ')'
}
if (header) {
message = header + ': ' + message
}
return message
} | [
"function",
"(",
"message",
",",
"component",
",",
"header",
")",
"{",
"if",
"(",
"typeof",
"header",
"===",
"'undefined'",
")",
"{",
"header",
"=",
"''",
"}",
"if",
"(",
"component",
")",
"{",
"if",
"(",
"header",
")",
"{",
"header",
"+=",
"' '",
"}",
"header",
"+=",
"'('",
"header",
"+=",
"component",
"header",
"+=",
"')'",
"}",
"if",
"(",
"header",
")",
"{",
"message",
"=",
"header",
"+",
"': '",
"+",
"message",
"}",
"return",
"message",
"}"
]
| Returns a formatted error message string for use in log and exception
messages.
@param {String} message - The base message.
@param {String} [component] - Description of the system component in which
the error occurred.
@param {String} [header] - Prefix to include before the error message.
@returns {String} The formatted error message. | [
"Returns",
"a",
"formatted",
"error",
"message",
"string",
"for",
"use",
"in",
"log",
"and",
"exception",
"messages",
"."
]
| eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997 | https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/provision-util.js#L42-L58 |
|
43,910 | opendxl/opendxl-client-javascript | lib/_provisioning/provision-util.js | function (error, options) {
options = options || {}
var verbosity = options.verbosity || 0
var message = module.exports.getErrorMessage(
typeof error === 'object' ? error.message : error, options.component,
options.header)
if (typeof header === 'undefined') {
message = 'ERROR: ' + message
}
console.error(message)
if ((verbosity > 1) && (typeof error === 'object') && error.stack) {
console.log(error.stack)
}
} | javascript | function (error, options) {
options = options || {}
var verbosity = options.verbosity || 0
var message = module.exports.getErrorMessage(
typeof error === 'object' ? error.message : error, options.component,
options.header)
if (typeof header === 'undefined') {
message = 'ERROR: ' + message
}
console.error(message)
if ((verbosity > 1) && (typeof error === 'object') && error.stack) {
console.log(error.stack)
}
} | [
"function",
"(",
"error",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
"var",
"verbosity",
"=",
"options",
".",
"verbosity",
"||",
"0",
"var",
"message",
"=",
"module",
".",
"exports",
".",
"getErrorMessage",
"(",
"typeof",
"error",
"===",
"'object'",
"?",
"error",
".",
"message",
":",
"error",
",",
"options",
".",
"component",
",",
"options",
".",
"header",
")",
"if",
"(",
"typeof",
"header",
"===",
"'undefined'",
")",
"{",
"message",
"=",
"'ERROR: '",
"+",
"message",
"}",
"console",
".",
"error",
"(",
"message",
")",
"if",
"(",
"(",
"verbosity",
">",
"1",
")",
"&&",
"(",
"typeof",
"error",
"===",
"'object'",
")",
"&&",
"error",
".",
"stack",
")",
"{",
"console",
".",
"log",
"(",
"error",
".",
"stack",
")",
"}",
"}"
]
| Writes an error to the log.
@param {(String|Error)} error - The Error or error message string to log.
@param {Object} [options] - Error message options.
@param {String} [options.component] - Description of the system component
in which the error occurred.
@param {String} [options.header] - Prefix to include before the error
message.
@param {Number} [options.verbosity] - Level of verbosity at which to log
the error message. | [
"Writes",
"an",
"error",
"to",
"the",
"log",
"."
]
| eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997 | https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/provision-util.js#L70-L83 |
|
43,911 | opendxl/opendxl-client-javascript | lib/_provisioning/provision-util.js | function (file, data) {
module.exports.mkdirRecursive(path.dirname(file))
fs.writeFileSync(file, data, {mode: _0644})
} | javascript | function (file, data) {
module.exports.mkdirRecursive(path.dirname(file))
fs.writeFileSync(file, data, {mode: _0644})
} | [
"function",
"(",
"file",
",",
"data",
")",
"{",
"module",
".",
"exports",
".",
"mkdirRecursive",
"(",
"path",
".",
"dirname",
"(",
"file",
")",
")",
"fs",
".",
"writeFileSync",
"(",
"file",
",",
"data",
",",
"{",
"mode",
":",
"_0644",
"}",
")",
"}"
]
| Saves the supplied data into the specified file. This function attempts to
create the directory in which the file would reside if the directory does
not already exist.
@param {String} file - File to create.
@param {String} data - Data to store in the file. | [
"Saves",
"the",
"supplied",
"data",
"into",
"the",
"specified",
"file",
".",
"This",
"function",
"attempts",
"to",
"create",
"the",
"directory",
"in",
"which",
"the",
"file",
"would",
"reside",
"if",
"the",
"directory",
"does",
"not",
"already",
"exist",
"."
]
| eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997 | https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/provision-util.js#L114-L117 |
|
43,912 | opendxl/opendxl-client-javascript | lib/_provisioning/provision-util.js | function (error, callback, verbosity) {
if (callback) {
callback(error)
} else {
module.exports.logError(error, {verbosity: verbosity})
}
} | javascript | function (error, callback, verbosity) {
if (callback) {
callback(error)
} else {
module.exports.logError(error, {verbosity: verbosity})
}
} | [
"function",
"(",
"error",
",",
"callback",
",",
"verbosity",
")",
"{",
"if",
"(",
"callback",
")",
"{",
"callback",
"(",
"error",
")",
"}",
"else",
"{",
"module",
".",
"exports",
".",
"logError",
"(",
"error",
",",
"{",
"verbosity",
":",
"verbosity",
"}",
")",
"}",
"}"
]
| Invokes a callback with the supplied `Error`.
@param {Error} error - The error.
@param {Function} callback - Callback to invoke. If null, the `Error`
is written to a log.
@param {Number} [verbosity] - Level of verbosity at which to log the
error message if the callback is not invoked. | [
"Invokes",
"a",
"callback",
"with",
"the",
"supplied",
"Error",
"."
]
| eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997 | https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_provisioning/provision-util.js#L126-L132 |
|
43,913 | plouc/node-firewall | lib/firewall.js | Firewall | function Firewall(name, path, authenticationHandler, successHandler, failureHandler) {
this.name = name;
this.path = utils.ensureRegexp(path);
this.rules = [];
// configure handlers
this.authenticationHandler = authenticationHandler || function (req, res, next) {
res.status(401);
return res.redirect('/login');
};
this.successHandler = successHandler;
this.failureHandler = failureHandler || function (req, res, next) {
return res.send(403, 'forbidden');
};
this.logger = debug;
this.strategies = {
role: strategy.role
};
} | javascript | function Firewall(name, path, authenticationHandler, successHandler, failureHandler) {
this.name = name;
this.path = utils.ensureRegexp(path);
this.rules = [];
// configure handlers
this.authenticationHandler = authenticationHandler || function (req, res, next) {
res.status(401);
return res.redirect('/login');
};
this.successHandler = successHandler;
this.failureHandler = failureHandler || function (req, res, next) {
return res.send(403, 'forbidden');
};
this.logger = debug;
this.strategies = {
role: strategy.role
};
} | [
"function",
"Firewall",
"(",
"name",
",",
"path",
",",
"authenticationHandler",
",",
"successHandler",
",",
"failureHandler",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"path",
"=",
"utils",
".",
"ensureRegexp",
"(",
"path",
")",
";",
"this",
".",
"rules",
"=",
"[",
"]",
";",
"// configure handlers",
"this",
".",
"authenticationHandler",
"=",
"authenticationHandler",
"||",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"res",
".",
"status",
"(",
"401",
")",
";",
"return",
"res",
".",
"redirect",
"(",
"'/login'",
")",
";",
"}",
";",
"this",
".",
"successHandler",
"=",
"successHandler",
";",
"this",
".",
"failureHandler",
"=",
"failureHandler",
"||",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"return",
"res",
".",
"send",
"(",
"403",
",",
"'forbidden'",
")",
";",
"}",
";",
"this",
".",
"logger",
"=",
"debug",
";",
"this",
".",
"strategies",
"=",
"{",
"role",
":",
"strategy",
".",
"role",
"}",
";",
"}"
]
| The firewall is a simple container for multiple url based authorization rules.
@param {string} name The firewall name
@param {string|RegExp} path The firewall will only apply on request url matching this value
@param {function|null} authenticationHandler Function to call when login is required
@param {function|null} successHandler Function to call when access is granted
@param {function|null} failureHandler Function to call when access is denied
@constructor | [
"The",
"firewall",
"is",
"a",
"simple",
"container",
"for",
"multiple",
"url",
"based",
"authorization",
"rules",
"."
]
| 42520e18acecf1e4c0e0d842da1a517ce37aa8ff | https://github.com/plouc/node-firewall/blob/42520e18acecf1e4c0e0d842da1a517ce37aa8ff/lib/firewall.js#L18-L38 |
43,914 | cocos-creator/fire-fs | index.js | exists | function exists (path, callback) {
Fs.stat(path, function (err) {
callback(checkErr(err));
});
} | javascript | function exists (path, callback) {
Fs.stat(path, function (err) {
callback(checkErr(err));
});
} | [
"function",
"exists",
"(",
"path",
",",
"callback",
")",
"{",
"Fs",
".",
"stat",
"(",
"path",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"checkErr",
"(",
"err",
")",
")",
";",
"}",
")",
";",
"}"
]
| check if a given path exists
@method exists
@param {string} path
@param {function} callback | [
"check",
"if",
"a",
"given",
"path",
"exists"
]
| 12cc33baf42774f2360fafdb56ef7ad13258f234 | https://github.com/cocos-creator/fire-fs/blob/12cc33baf42774f2360fafdb56ef7ad13258f234/index.js#L12-L16 |
43,915 | cocos-creator/fire-fs | index.js | existsSync | function existsSync(path) {
if ( path === null || path === undefined )
return false;
try {
Fs.statSync(path);
return true;
} catch (err) {
return checkErr(err);
}
} | javascript | function existsSync(path) {
if ( path === null || path === undefined )
return false;
try {
Fs.statSync(path);
return true;
} catch (err) {
return checkErr(err);
}
} | [
"function",
"existsSync",
"(",
"path",
")",
"{",
"if",
"(",
"path",
"===",
"null",
"||",
"path",
"===",
"undefined",
")",
"return",
"false",
";",
"try",
"{",
"Fs",
".",
"statSync",
"(",
"path",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"checkErr",
"(",
"err",
")",
";",
"}",
"}"
]
| check if a given path exists, this is the sync version of FireFs.exists
@method existsSync
@param {string} path
@return {boolean} | [
"check",
"if",
"a",
"given",
"path",
"exists",
"this",
"is",
"the",
"sync",
"version",
"of",
"FireFs",
".",
"exists"
]
| 12cc33baf42774f2360fafdb56ef7ad13258f234 | https://github.com/cocos-creator/fire-fs/blob/12cc33baf42774f2360fafdb56ef7ad13258f234/index.js#L26-L36 |
43,916 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | cleanup | function cleanup(err, compacted, activeCtx, options) {
if(err) {
return callback(err);
}
if(options.compactArrays && !options.graph && _isArray(compacted)) {
// simplify to a single item
if(compacted.length === 1) {
compacted = compacted[0];
}
// simplify to an empty object
else if(compacted.length === 0) {
compacted = {};
}
}
// always use array if graph option is on
else if(options.graph && _isObject(compacted)) {
compacted = [compacted];
}
// follow @context key
if(_isObject(ctx) && '@context' in ctx) {
ctx = ctx['@context'];
}
// build output context
ctx = _clone(ctx);
if(!_isArray(ctx)) {
ctx = [ctx];
}
// remove empty contexts
var tmp = ctx;
ctx = [];
for(var i = 0; i < tmp.length; ++i) {
if(!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) {
ctx.push(tmp[i]);
}
}
// remove array if only one context
var hasContext = (ctx.length > 0);
if(ctx.length === 1) {
ctx = ctx[0];
}
// add context and/or @graph
if(_isArray(compacted)) {
// use '@graph' keyword
var kwgraph = _compactIri(activeCtx, '@graph');
var graph = compacted;
compacted = {};
if(hasContext) {
compacted['@context'] = ctx;
}
compacted[kwgraph] = graph;
}
else if(_isObject(compacted) && hasContext) {
// reorder keys so @context is first
var graph = compacted;
compacted = {'@context': ctx};
for(var key in graph) {
compacted[key] = graph[key];
}
}
callback(null, compacted, activeCtx);
} | javascript | function cleanup(err, compacted, activeCtx, options) {
if(err) {
return callback(err);
}
if(options.compactArrays && !options.graph && _isArray(compacted)) {
// simplify to a single item
if(compacted.length === 1) {
compacted = compacted[0];
}
// simplify to an empty object
else if(compacted.length === 0) {
compacted = {};
}
}
// always use array if graph option is on
else if(options.graph && _isObject(compacted)) {
compacted = [compacted];
}
// follow @context key
if(_isObject(ctx) && '@context' in ctx) {
ctx = ctx['@context'];
}
// build output context
ctx = _clone(ctx);
if(!_isArray(ctx)) {
ctx = [ctx];
}
// remove empty contexts
var tmp = ctx;
ctx = [];
for(var i = 0; i < tmp.length; ++i) {
if(!_isObject(tmp[i]) || Object.keys(tmp[i]).length > 0) {
ctx.push(tmp[i]);
}
}
// remove array if only one context
var hasContext = (ctx.length > 0);
if(ctx.length === 1) {
ctx = ctx[0];
}
// add context and/or @graph
if(_isArray(compacted)) {
// use '@graph' keyword
var kwgraph = _compactIri(activeCtx, '@graph');
var graph = compacted;
compacted = {};
if(hasContext) {
compacted['@context'] = ctx;
}
compacted[kwgraph] = graph;
}
else if(_isObject(compacted) && hasContext) {
// reorder keys so @context is first
var graph = compacted;
compacted = {'@context': ctx};
for(var key in graph) {
compacted[key] = graph[key];
}
}
callback(null, compacted, activeCtx);
} | [
"function",
"cleanup",
"(",
"err",
",",
"compacted",
",",
"activeCtx",
",",
"options",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"if",
"(",
"options",
".",
"compactArrays",
"&&",
"!",
"options",
".",
"graph",
"&&",
"_isArray",
"(",
"compacted",
")",
")",
"{",
"// simplify to a single item",
"if",
"(",
"compacted",
".",
"length",
"===",
"1",
")",
"{",
"compacted",
"=",
"compacted",
"[",
"0",
"]",
";",
"}",
"// simplify to an empty object",
"else",
"if",
"(",
"compacted",
".",
"length",
"===",
"0",
")",
"{",
"compacted",
"=",
"{",
"}",
";",
"}",
"}",
"// always use array if graph option is on",
"else",
"if",
"(",
"options",
".",
"graph",
"&&",
"_isObject",
"(",
"compacted",
")",
")",
"{",
"compacted",
"=",
"[",
"compacted",
"]",
";",
"}",
"// follow @context key",
"if",
"(",
"_isObject",
"(",
"ctx",
")",
"&&",
"'@context'",
"in",
"ctx",
")",
"{",
"ctx",
"=",
"ctx",
"[",
"'@context'",
"]",
";",
"}",
"// build output context",
"ctx",
"=",
"_clone",
"(",
"ctx",
")",
";",
"if",
"(",
"!",
"_isArray",
"(",
"ctx",
")",
")",
"{",
"ctx",
"=",
"[",
"ctx",
"]",
";",
"}",
"// remove empty contexts",
"var",
"tmp",
"=",
"ctx",
";",
"ctx",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"tmp",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"!",
"_isObject",
"(",
"tmp",
"[",
"i",
"]",
")",
"||",
"Object",
".",
"keys",
"(",
"tmp",
"[",
"i",
"]",
")",
".",
"length",
">",
"0",
")",
"{",
"ctx",
".",
"push",
"(",
"tmp",
"[",
"i",
"]",
")",
";",
"}",
"}",
"// remove array if only one context",
"var",
"hasContext",
"=",
"(",
"ctx",
".",
"length",
">",
"0",
")",
";",
"if",
"(",
"ctx",
".",
"length",
"===",
"1",
")",
"{",
"ctx",
"=",
"ctx",
"[",
"0",
"]",
";",
"}",
"// add context and/or @graph",
"if",
"(",
"_isArray",
"(",
"compacted",
")",
")",
"{",
"// use '@graph' keyword",
"var",
"kwgraph",
"=",
"_compactIri",
"(",
"activeCtx",
",",
"'@graph'",
")",
";",
"var",
"graph",
"=",
"compacted",
";",
"compacted",
"=",
"{",
"}",
";",
"if",
"(",
"hasContext",
")",
"{",
"compacted",
"[",
"'@context'",
"]",
"=",
"ctx",
";",
"}",
"compacted",
"[",
"kwgraph",
"]",
"=",
"graph",
";",
"}",
"else",
"if",
"(",
"_isObject",
"(",
"compacted",
")",
"&&",
"hasContext",
")",
"{",
"// reorder keys so @context is first",
"var",
"graph",
"=",
"compacted",
";",
"compacted",
"=",
"{",
"'@context'",
":",
"ctx",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"graph",
")",
"{",
"compacted",
"[",
"key",
"]",
"=",
"graph",
"[",
"key",
"]",
";",
"}",
"}",
"callback",
"(",
"null",
",",
"compacted",
",",
"activeCtx",
")",
";",
"}"
]
| performs clean up after compaction | [
"performs",
"clean",
"up",
"after",
"compaction"
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L164-L230 |
43,917 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | createDocumentLoader | function createDocumentLoader(promise) {
return function(url, callback) {
promise(url).then(
// success
function(remoteDocument) {
callback(null, remoteDocument);
},
// failure
callback
);
};
} | javascript | function createDocumentLoader(promise) {
return function(url, callback) {
promise(url).then(
// success
function(remoteDocument) {
callback(null, remoteDocument);
},
// failure
callback
);
};
} | [
"function",
"createDocumentLoader",
"(",
"promise",
")",
"{",
"return",
"function",
"(",
"url",
",",
"callback",
")",
"{",
"promise",
"(",
"url",
")",
".",
"then",
"(",
"// success",
"function",
"(",
"remoteDocument",
")",
"{",
"callback",
"(",
"null",
",",
"remoteDocument",
")",
";",
"}",
",",
"// failure",
"callback",
")",
";",
"}",
";",
"}"
]
| converts a load document promise callback to a node-style callback | [
"converts",
"a",
"load",
"document",
"promise",
"callback",
"to",
"a",
"node",
"-",
"style",
"callback"
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L894-L905 |
43,918 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | function(msg, type, details) {
if(_nodejs) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
}
this.name = type || 'jsonld.Error';
this.message = msg || 'An unspecified JSON-LD error occurred.';
this.details = details || {};
} | javascript | function(msg, type, details) {
if(_nodejs) {
Error.call(this);
Error.captureStackTrace(this, this.constructor);
}
this.name = type || 'jsonld.Error';
this.message = msg || 'An unspecified JSON-LD error occurred.';
this.details = details || {};
} | [
"function",
"(",
"msg",
",",
"type",
",",
"details",
")",
"{",
"if",
"(",
"_nodejs",
")",
"{",
"Error",
".",
"call",
"(",
"this",
")",
";",
"Error",
".",
"captureStackTrace",
"(",
"this",
",",
"this",
".",
"constructor",
")",
";",
"}",
"this",
".",
"name",
"=",
"type",
"||",
"'jsonld.Error'",
";",
"this",
".",
"message",
"=",
"msg",
"||",
"'An unspecified JSON-LD error occurred.'",
";",
"this",
".",
"details",
"=",
"details",
"||",
"{",
"}",
";",
"}"
]
| A JSON-LD Error.
@param msg the error message.
@param type the error type.
@param details the error details. | [
"A",
"JSON",
"-",
"LD",
"Error",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L1737-L1745 |
|
43,919 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | hashBlankNodes | function hashBlankNodes(unnamed) {
var nextUnnamed = [];
var duplicates = {};
var unique = {};
// hash quads for each unnamed bnode
jsonld.setImmediate(function() {hashUnnamed(0);});
function hashUnnamed(i) {
if(i === unnamed.length) {
// done, name blank nodes
return nameBlankNodes(unique, duplicates, nextUnnamed);
}
// hash unnamed bnode
var bnode = unnamed[i];
var hash = _hashQuads(bnode, bnodes, namer);
// store hash as unique or a duplicate
if(hash in duplicates) {
duplicates[hash].push(bnode);
nextUnnamed.push(bnode);
}
else if(hash in unique) {
duplicates[hash] = [unique[hash], bnode];
nextUnnamed.push(unique[hash]);
nextUnnamed.push(bnode);
delete unique[hash];
}
else {
unique[hash] = bnode;
}
// hash next unnamed bnode
jsonld.setImmediate(function() {hashUnnamed(i + 1);});
}
} | javascript | function hashBlankNodes(unnamed) {
var nextUnnamed = [];
var duplicates = {};
var unique = {};
// hash quads for each unnamed bnode
jsonld.setImmediate(function() {hashUnnamed(0);});
function hashUnnamed(i) {
if(i === unnamed.length) {
// done, name blank nodes
return nameBlankNodes(unique, duplicates, nextUnnamed);
}
// hash unnamed bnode
var bnode = unnamed[i];
var hash = _hashQuads(bnode, bnodes, namer);
// store hash as unique or a duplicate
if(hash in duplicates) {
duplicates[hash].push(bnode);
nextUnnamed.push(bnode);
}
else if(hash in unique) {
duplicates[hash] = [unique[hash], bnode];
nextUnnamed.push(unique[hash]);
nextUnnamed.push(bnode);
delete unique[hash];
}
else {
unique[hash] = bnode;
}
// hash next unnamed bnode
jsonld.setImmediate(function() {hashUnnamed(i + 1);});
}
} | [
"function",
"hashBlankNodes",
"(",
"unnamed",
")",
"{",
"var",
"nextUnnamed",
"=",
"[",
"]",
";",
"var",
"duplicates",
"=",
"{",
"}",
";",
"var",
"unique",
"=",
"{",
"}",
";",
"// hash quads for each unnamed bnode",
"jsonld",
".",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"hashUnnamed",
"(",
"0",
")",
";",
"}",
")",
";",
"function",
"hashUnnamed",
"(",
"i",
")",
"{",
"if",
"(",
"i",
"===",
"unnamed",
".",
"length",
")",
"{",
"// done, name blank nodes",
"return",
"nameBlankNodes",
"(",
"unique",
",",
"duplicates",
",",
"nextUnnamed",
")",
";",
"}",
"// hash unnamed bnode",
"var",
"bnode",
"=",
"unnamed",
"[",
"i",
"]",
";",
"var",
"hash",
"=",
"_hashQuads",
"(",
"bnode",
",",
"bnodes",
",",
"namer",
")",
";",
"// store hash as unique or a duplicate",
"if",
"(",
"hash",
"in",
"duplicates",
")",
"{",
"duplicates",
"[",
"hash",
"]",
".",
"push",
"(",
"bnode",
")",
";",
"nextUnnamed",
".",
"push",
"(",
"bnode",
")",
";",
"}",
"else",
"if",
"(",
"hash",
"in",
"unique",
")",
"{",
"duplicates",
"[",
"hash",
"]",
"=",
"[",
"unique",
"[",
"hash",
"]",
",",
"bnode",
"]",
";",
"nextUnnamed",
".",
"push",
"(",
"unique",
"[",
"hash",
"]",
")",
";",
"nextUnnamed",
".",
"push",
"(",
"bnode",
")",
";",
"delete",
"unique",
"[",
"hash",
"]",
";",
"}",
"else",
"{",
"unique",
"[",
"hash",
"]",
"=",
"bnode",
";",
"}",
"// hash next unnamed bnode",
"jsonld",
".",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"hashUnnamed",
"(",
"i",
"+",
"1",
")",
";",
"}",
")",
";",
"}",
"}"
]
| generates unique and duplicate hashes for bnodes | [
"generates",
"unique",
"and",
"duplicate",
"hashes",
"for",
"bnodes"
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L2502-L2537 |
43,920 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | nameBlankNodes | function nameBlankNodes(unique, duplicates, unnamed) {
// name unique bnodes in sorted hash order
var named = false;
var hashes = Object.keys(unique).sort();
for(var i = 0; i < hashes.length; ++i) {
var bnode = unique[hashes[i]];
namer.getName(bnode);
named = true;
}
// continue to hash bnodes if a bnode was assigned a name
if(named) {
hashBlankNodes(unnamed);
}
// name the duplicate hash bnodes
else {
nameDuplicates(duplicates);
}
} | javascript | function nameBlankNodes(unique, duplicates, unnamed) {
// name unique bnodes in sorted hash order
var named = false;
var hashes = Object.keys(unique).sort();
for(var i = 0; i < hashes.length; ++i) {
var bnode = unique[hashes[i]];
namer.getName(bnode);
named = true;
}
// continue to hash bnodes if a bnode was assigned a name
if(named) {
hashBlankNodes(unnamed);
}
// name the duplicate hash bnodes
else {
nameDuplicates(duplicates);
}
} | [
"function",
"nameBlankNodes",
"(",
"unique",
",",
"duplicates",
",",
"unnamed",
")",
"{",
"// name unique bnodes in sorted hash order",
"var",
"named",
"=",
"false",
";",
"var",
"hashes",
"=",
"Object",
".",
"keys",
"(",
"unique",
")",
".",
"sort",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"hashes",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"bnode",
"=",
"unique",
"[",
"hashes",
"[",
"i",
"]",
"]",
";",
"namer",
".",
"getName",
"(",
"bnode",
")",
";",
"named",
"=",
"true",
";",
"}",
"// continue to hash bnodes if a bnode was assigned a name",
"if",
"(",
"named",
")",
"{",
"hashBlankNodes",
"(",
"unnamed",
")",
";",
"}",
"// name the duplicate hash bnodes",
"else",
"{",
"nameDuplicates",
"(",
"duplicates",
")",
";",
"}",
"}"
]
| names unique hash bnodes | [
"names",
"unique",
"hash",
"bnodes"
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L2540-L2558 |
43,921 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | nameDuplicates | function nameDuplicates(duplicates) {
// enumerate duplicate hash groups in sorted order
var hashes = Object.keys(duplicates).sort();
// process each group
processGroup(0);
function processGroup(i) {
if(i === hashes.length) {
// done, create JSON-LD array
return createArray();
}
// name each group member
var group = duplicates[hashes[i]];
var results = [];
nameGroupMember(group, 0);
function nameGroupMember(group, n) {
if(n === group.length) {
// name bnodes in hash order
results.sort(function(a, b) {
a = a.hash;
b = b.hash;
return (a < b) ? -1 : ((a > b) ? 1 : 0);
});
for(var r in results) {
// name all bnodes in path namer in key-entry order
// Note: key-order is preserved in javascript
for(var key in results[r].pathNamer.existing) {
namer.getName(key);
}
}
return processGroup(i + 1);
}
// skip already-named bnodes
var bnode = group[n];
if(namer.isNamed(bnode)) {
return nameGroupMember(group, n + 1);
}
// hash bnode paths
var pathNamer = new UniqueNamer('_:b');
pathNamer.getName(bnode);
_hashPaths(bnode, bnodes, namer, pathNamer,
function(err, result) {
if(err) {
return callback(err);
}
results.push(result);
nameGroupMember(group, n + 1);
});
}
}
} | javascript | function nameDuplicates(duplicates) {
// enumerate duplicate hash groups in sorted order
var hashes = Object.keys(duplicates).sort();
// process each group
processGroup(0);
function processGroup(i) {
if(i === hashes.length) {
// done, create JSON-LD array
return createArray();
}
// name each group member
var group = duplicates[hashes[i]];
var results = [];
nameGroupMember(group, 0);
function nameGroupMember(group, n) {
if(n === group.length) {
// name bnodes in hash order
results.sort(function(a, b) {
a = a.hash;
b = b.hash;
return (a < b) ? -1 : ((a > b) ? 1 : 0);
});
for(var r in results) {
// name all bnodes in path namer in key-entry order
// Note: key-order is preserved in javascript
for(var key in results[r].pathNamer.existing) {
namer.getName(key);
}
}
return processGroup(i + 1);
}
// skip already-named bnodes
var bnode = group[n];
if(namer.isNamed(bnode)) {
return nameGroupMember(group, n + 1);
}
// hash bnode paths
var pathNamer = new UniqueNamer('_:b');
pathNamer.getName(bnode);
_hashPaths(bnode, bnodes, namer, pathNamer,
function(err, result) {
if(err) {
return callback(err);
}
results.push(result);
nameGroupMember(group, n + 1);
});
}
}
} | [
"function",
"nameDuplicates",
"(",
"duplicates",
")",
"{",
"// enumerate duplicate hash groups in sorted order",
"var",
"hashes",
"=",
"Object",
".",
"keys",
"(",
"duplicates",
")",
".",
"sort",
"(",
")",
";",
"// process each group",
"processGroup",
"(",
"0",
")",
";",
"function",
"processGroup",
"(",
"i",
")",
"{",
"if",
"(",
"i",
"===",
"hashes",
".",
"length",
")",
"{",
"// done, create JSON-LD array",
"return",
"createArray",
"(",
")",
";",
"}",
"// name each group member",
"var",
"group",
"=",
"duplicates",
"[",
"hashes",
"[",
"i",
"]",
"]",
";",
"var",
"results",
"=",
"[",
"]",
";",
"nameGroupMember",
"(",
"group",
",",
"0",
")",
";",
"function",
"nameGroupMember",
"(",
"group",
",",
"n",
")",
"{",
"if",
"(",
"n",
"===",
"group",
".",
"length",
")",
"{",
"// name bnodes in hash order",
"results",
".",
"sort",
"(",
"function",
"(",
"a",
",",
"b",
")",
"{",
"a",
"=",
"a",
".",
"hash",
";",
"b",
"=",
"b",
".",
"hash",
";",
"return",
"(",
"a",
"<",
"b",
")",
"?",
"-",
"1",
":",
"(",
"(",
"a",
">",
"b",
")",
"?",
"1",
":",
"0",
")",
";",
"}",
")",
";",
"for",
"(",
"var",
"r",
"in",
"results",
")",
"{",
"// name all bnodes in path namer in key-entry order",
"// Note: key-order is preserved in javascript",
"for",
"(",
"var",
"key",
"in",
"results",
"[",
"r",
"]",
".",
"pathNamer",
".",
"existing",
")",
"{",
"namer",
".",
"getName",
"(",
"key",
")",
";",
"}",
"}",
"return",
"processGroup",
"(",
"i",
"+",
"1",
")",
";",
"}",
"// skip already-named bnodes",
"var",
"bnode",
"=",
"group",
"[",
"n",
"]",
";",
"if",
"(",
"namer",
".",
"isNamed",
"(",
"bnode",
")",
")",
"{",
"return",
"nameGroupMember",
"(",
"group",
",",
"n",
"+",
"1",
")",
";",
"}",
"// hash bnode paths",
"var",
"pathNamer",
"=",
"new",
"UniqueNamer",
"(",
"'_:b'",
")",
";",
"pathNamer",
".",
"getName",
"(",
"bnode",
")",
";",
"_hashPaths",
"(",
"bnode",
",",
"bnodes",
",",
"namer",
",",
"pathNamer",
",",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"callback",
"(",
"err",
")",
";",
"}",
"results",
".",
"push",
"(",
"result",
")",
";",
"nameGroupMember",
"(",
"group",
",",
"n",
"+",
"1",
")",
";",
"}",
")",
";",
"}",
"}",
"}"
]
| names duplicate hash bnodes | [
"names",
"duplicate",
"hash",
"bnodes"
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L2561-L2614 |
43,922 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | createArray | function createArray() {
var normalized = [];
/* Note: At this point all bnodes in the set of RDF quads have been
assigned canonical names, which have been stored in the 'namer' object.
Here each quad is updated by assigning each of its bnodes its new name
via the 'namer' object. */
// update bnode names in each quad and serialize
for(var i = 0; i < quads.length; ++i) {
var quad = quads[i];
var attrs = ['subject', 'object', 'name'];
for(var ai = 0; ai < attrs.length; ++ai) {
var attr = attrs[ai];
if(quad[attr] && quad[attr].type === 'blank node' &&
quad[attr].value.indexOf('_:c14n') !== 0) {
quad[attr].value = namer.getName(quad[attr].value);
}
}
normalized.push(_toNQuad(quad, quad.name ? quad.name.value : null));
}
// sort normalized output
normalized.sort();
// handle output format
if(options.format) {
if(options.format === 'application/nquads') {
return callback(null, normalized.join(''));
}
return callback(new JsonLdError(
'Unknown output format.',
'jsonld.UnknownFormat', {format: options.format}));
}
// output RDF dataset
callback(null, _parseNQuads(normalized.join('')));
} | javascript | function createArray() {
var normalized = [];
/* Note: At this point all bnodes in the set of RDF quads have been
assigned canonical names, which have been stored in the 'namer' object.
Here each quad is updated by assigning each of its bnodes its new name
via the 'namer' object. */
// update bnode names in each quad and serialize
for(var i = 0; i < quads.length; ++i) {
var quad = quads[i];
var attrs = ['subject', 'object', 'name'];
for(var ai = 0; ai < attrs.length; ++ai) {
var attr = attrs[ai];
if(quad[attr] && quad[attr].type === 'blank node' &&
quad[attr].value.indexOf('_:c14n') !== 0) {
quad[attr].value = namer.getName(quad[attr].value);
}
}
normalized.push(_toNQuad(quad, quad.name ? quad.name.value : null));
}
// sort normalized output
normalized.sort();
// handle output format
if(options.format) {
if(options.format === 'application/nquads') {
return callback(null, normalized.join(''));
}
return callback(new JsonLdError(
'Unknown output format.',
'jsonld.UnknownFormat', {format: options.format}));
}
// output RDF dataset
callback(null, _parseNQuads(normalized.join('')));
} | [
"function",
"createArray",
"(",
")",
"{",
"var",
"normalized",
"=",
"[",
"]",
";",
"/* Note: At this point all bnodes in the set of RDF quads have been\n assigned canonical names, which have been stored in the 'namer' object.\n Here each quad is updated by assigning each of its bnodes its new name\n via the 'namer' object. */",
"// update bnode names in each quad and serialize",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"quads",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"quad",
"=",
"quads",
"[",
"i",
"]",
";",
"var",
"attrs",
"=",
"[",
"'subject'",
",",
"'object'",
",",
"'name'",
"]",
";",
"for",
"(",
"var",
"ai",
"=",
"0",
";",
"ai",
"<",
"attrs",
".",
"length",
";",
"++",
"ai",
")",
"{",
"var",
"attr",
"=",
"attrs",
"[",
"ai",
"]",
";",
"if",
"(",
"quad",
"[",
"attr",
"]",
"&&",
"quad",
"[",
"attr",
"]",
".",
"type",
"===",
"'blank node'",
"&&",
"quad",
"[",
"attr",
"]",
".",
"value",
".",
"indexOf",
"(",
"'_:c14n'",
")",
"!==",
"0",
")",
"{",
"quad",
"[",
"attr",
"]",
".",
"value",
"=",
"namer",
".",
"getName",
"(",
"quad",
"[",
"attr",
"]",
".",
"value",
")",
";",
"}",
"}",
"normalized",
".",
"push",
"(",
"_toNQuad",
"(",
"quad",
",",
"quad",
".",
"name",
"?",
"quad",
".",
"name",
".",
"value",
":",
"null",
")",
")",
";",
"}",
"// sort normalized output",
"normalized",
".",
"sort",
"(",
")",
";",
"// handle output format",
"if",
"(",
"options",
".",
"format",
")",
"{",
"if",
"(",
"options",
".",
"format",
"===",
"'application/nquads'",
")",
"{",
"return",
"callback",
"(",
"null",
",",
"normalized",
".",
"join",
"(",
"''",
")",
")",
";",
"}",
"return",
"callback",
"(",
"new",
"JsonLdError",
"(",
"'Unknown output format.'",
",",
"'jsonld.UnknownFormat'",
",",
"{",
"format",
":",
"options",
".",
"format",
"}",
")",
")",
";",
"}",
"// output RDF dataset",
"callback",
"(",
"null",
",",
"_parseNQuads",
"(",
"normalized",
".",
"join",
"(",
"''",
")",
")",
")",
";",
"}"
]
| creates the sorted array of RDF quads | [
"creates",
"the",
"sorted",
"array",
"of",
"RDF",
"quads"
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L2617-L2654 |
43,923 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _expandLanguageMap | function _expandLanguageMap(languageMap) {
var rval = [];
var keys = Object.keys(languageMap).sort();
for(var ki = 0; ki < keys.length; ++ki) {
var key = keys[ki];
var val = languageMap[key];
if(!_isArray(val)) {
val = [val];
}
for(var vi = 0; vi < val.length; ++vi) {
var item = val[vi];
if(!_isString(item)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; language map values must be strings.',
'jsonld.SyntaxError', {languageMap: languageMap});
}
rval.push({
'@value': item,
'@language': key.toLowerCase()
});
}
}
return rval;
} | javascript | function _expandLanguageMap(languageMap) {
var rval = [];
var keys = Object.keys(languageMap).sort();
for(var ki = 0; ki < keys.length; ++ki) {
var key = keys[ki];
var val = languageMap[key];
if(!_isArray(val)) {
val = [val];
}
for(var vi = 0; vi < val.length; ++vi) {
var item = val[vi];
if(!_isString(item)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; language map values must be strings.',
'jsonld.SyntaxError', {languageMap: languageMap});
}
rval.push({
'@value': item,
'@language': key.toLowerCase()
});
}
}
return rval;
} | [
"function",
"_expandLanguageMap",
"(",
"languageMap",
")",
"{",
"var",
"rval",
"=",
"[",
"]",
";",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"languageMap",
")",
".",
"sort",
"(",
")",
";",
"for",
"(",
"var",
"ki",
"=",
"0",
";",
"ki",
"<",
"keys",
".",
"length",
";",
"++",
"ki",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"ki",
"]",
";",
"var",
"val",
"=",
"languageMap",
"[",
"key",
"]",
";",
"if",
"(",
"!",
"_isArray",
"(",
"val",
")",
")",
"{",
"val",
"=",
"[",
"val",
"]",
";",
"}",
"for",
"(",
"var",
"vi",
"=",
"0",
";",
"vi",
"<",
"val",
".",
"length",
";",
"++",
"vi",
")",
"{",
"var",
"item",
"=",
"val",
"[",
"vi",
"]",
";",
"if",
"(",
"!",
"_isString",
"(",
"item",
")",
")",
"{",
"throw",
"new",
"JsonLdError",
"(",
"'Invalid JSON-LD syntax; language map values must be strings.'",
",",
"'jsonld.SyntaxError'",
",",
"{",
"languageMap",
":",
"languageMap",
"}",
")",
";",
"}",
"rval",
".",
"push",
"(",
"{",
"'@value'",
":",
"item",
",",
"'@language'",
":",
"key",
".",
"toLowerCase",
"(",
")",
"}",
")",
";",
"}",
"}",
"return",
"rval",
";",
"}"
]
| Expands a language map.
@param languageMap the language map to expand.
@return the expanded language map. | [
"Expands",
"a",
"language",
"map",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L2983-L3006 |
43,924 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _labelBlankNodes | function _labelBlankNodes(namer, element) {
if(_isArray(element)) {
for(var i = 0; i < element.length; ++i) {
element[i] = _labelBlankNodes(namer, element[i]);
}
}
else if(_isList(element)) {
element['@list'] = _labelBlankNodes(namer, element['@list']);
}
else if(_isObject(element)) {
// rename blank node
if(_isBlankNode(element)) {
element['@id'] = namer.getName(element['@id']);
}
// recursively apply to all keys
var keys = Object.keys(element).sort();
for(var ki = 0; ki < keys.length; ++ki) {
var key = keys[ki];
if(key !== '@id') {
element[key] = _labelBlankNodes(namer, element[key]);
}
}
}
return element;
} | javascript | function _labelBlankNodes(namer, element) {
if(_isArray(element)) {
for(var i = 0; i < element.length; ++i) {
element[i] = _labelBlankNodes(namer, element[i]);
}
}
else if(_isList(element)) {
element['@list'] = _labelBlankNodes(namer, element['@list']);
}
else if(_isObject(element)) {
// rename blank node
if(_isBlankNode(element)) {
element['@id'] = namer.getName(element['@id']);
}
// recursively apply to all keys
var keys = Object.keys(element).sort();
for(var ki = 0; ki < keys.length; ++ki) {
var key = keys[ki];
if(key !== '@id') {
element[key] = _labelBlankNodes(namer, element[key]);
}
}
}
return element;
} | [
"function",
"_labelBlankNodes",
"(",
"namer",
",",
"element",
")",
"{",
"if",
"(",
"_isArray",
"(",
"element",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"element",
".",
"length",
";",
"++",
"i",
")",
"{",
"element",
"[",
"i",
"]",
"=",
"_labelBlankNodes",
"(",
"namer",
",",
"element",
"[",
"i",
"]",
")",
";",
"}",
"}",
"else",
"if",
"(",
"_isList",
"(",
"element",
")",
")",
"{",
"element",
"[",
"'@list'",
"]",
"=",
"_labelBlankNodes",
"(",
"namer",
",",
"element",
"[",
"'@list'",
"]",
")",
";",
"}",
"else",
"if",
"(",
"_isObject",
"(",
"element",
")",
")",
"{",
"// rename blank node",
"if",
"(",
"_isBlankNode",
"(",
"element",
")",
")",
"{",
"element",
"[",
"'@id'",
"]",
"=",
"namer",
".",
"getName",
"(",
"element",
"[",
"'@id'",
"]",
")",
";",
"}",
"// recursively apply to all keys",
"var",
"keys",
"=",
"Object",
".",
"keys",
"(",
"element",
")",
".",
"sort",
"(",
")",
";",
"for",
"(",
"var",
"ki",
"=",
"0",
";",
"ki",
"<",
"keys",
".",
"length",
";",
"++",
"ki",
")",
"{",
"var",
"key",
"=",
"keys",
"[",
"ki",
"]",
";",
"if",
"(",
"key",
"!==",
"'@id'",
")",
"{",
"element",
"[",
"key",
"]",
"=",
"_labelBlankNodes",
"(",
"namer",
",",
"element",
"[",
"key",
"]",
")",
";",
"}",
"}",
"}",
"return",
"element",
";",
"}"
]
| Labels the blank nodes in the given value using the given UniqueNamer.
@param namer the UniqueNamer to use.
@param element the element with blank nodes to rename.
@return the element. | [
"Labels",
"the",
"blank",
"nodes",
"in",
"the",
"given",
"value",
"using",
"the",
"given",
"UniqueNamer",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3016-L3042 |
43,925 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _expandValue | function _expandValue(activeCtx, activeProperty, value) {
// nothing to expand
if(value === null) {
return null;
}
// special-case expand @id and @type (skips '@id' expansion)
var expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true});
if(expandedProperty === '@id') {
return _expandIri(activeCtx, value, {base: true});
}
else if(expandedProperty === '@type') {
return _expandIri(activeCtx, value, {vocab: true, base: true});
}
// get type definition from context
var type = jsonld.getContextValue(activeCtx, activeProperty, '@type');
// do @id expansion (automatic for @graph)
if(type === '@id' || (expandedProperty === '@graph' && _isString(value))) {
return {'@id': _expandIri(activeCtx, value, {base: true})};
}
// do @id expansion w/vocab
if(type === '@vocab') {
return {'@id': _expandIri(activeCtx, value, {vocab: true, base: true})};
}
// do not expand keyword values
if(_isKeyword(expandedProperty)) {
return value;
}
rval = {};
// other type
if(type !== null) {
rval['@type'] = type;
}
// check for language tagging for strings
else if(_isString(value)) {
var language = jsonld.getContextValue(
activeCtx, activeProperty, '@language');
if(language !== null) {
rval['@language'] = language;
}
}
rval['@value'] = value;
return rval;
} | javascript | function _expandValue(activeCtx, activeProperty, value) {
// nothing to expand
if(value === null) {
return null;
}
// special-case expand @id and @type (skips '@id' expansion)
var expandedProperty = _expandIri(activeCtx, activeProperty, {vocab: true});
if(expandedProperty === '@id') {
return _expandIri(activeCtx, value, {base: true});
}
else if(expandedProperty === '@type') {
return _expandIri(activeCtx, value, {vocab: true, base: true});
}
// get type definition from context
var type = jsonld.getContextValue(activeCtx, activeProperty, '@type');
// do @id expansion (automatic for @graph)
if(type === '@id' || (expandedProperty === '@graph' && _isString(value))) {
return {'@id': _expandIri(activeCtx, value, {base: true})};
}
// do @id expansion w/vocab
if(type === '@vocab') {
return {'@id': _expandIri(activeCtx, value, {vocab: true, base: true})};
}
// do not expand keyword values
if(_isKeyword(expandedProperty)) {
return value;
}
rval = {};
// other type
if(type !== null) {
rval['@type'] = type;
}
// check for language tagging for strings
else if(_isString(value)) {
var language = jsonld.getContextValue(
activeCtx, activeProperty, '@language');
if(language !== null) {
rval['@language'] = language;
}
}
rval['@value'] = value;
return rval;
} | [
"function",
"_expandValue",
"(",
"activeCtx",
",",
"activeProperty",
",",
"value",
")",
"{",
"// nothing to expand",
"if",
"(",
"value",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"// special-case expand @id and @type (skips '@id' expansion)",
"var",
"expandedProperty",
"=",
"_expandIri",
"(",
"activeCtx",
",",
"activeProperty",
",",
"{",
"vocab",
":",
"true",
"}",
")",
";",
"if",
"(",
"expandedProperty",
"===",
"'@id'",
")",
"{",
"return",
"_expandIri",
"(",
"activeCtx",
",",
"value",
",",
"{",
"base",
":",
"true",
"}",
")",
";",
"}",
"else",
"if",
"(",
"expandedProperty",
"===",
"'@type'",
")",
"{",
"return",
"_expandIri",
"(",
"activeCtx",
",",
"value",
",",
"{",
"vocab",
":",
"true",
",",
"base",
":",
"true",
"}",
")",
";",
"}",
"// get type definition from context",
"var",
"type",
"=",
"jsonld",
".",
"getContextValue",
"(",
"activeCtx",
",",
"activeProperty",
",",
"'@type'",
")",
";",
"// do @id expansion (automatic for @graph)",
"if",
"(",
"type",
"===",
"'@id'",
"||",
"(",
"expandedProperty",
"===",
"'@graph'",
"&&",
"_isString",
"(",
"value",
")",
")",
")",
"{",
"return",
"{",
"'@id'",
":",
"_expandIri",
"(",
"activeCtx",
",",
"value",
",",
"{",
"base",
":",
"true",
"}",
")",
"}",
";",
"}",
"// do @id expansion w/vocab",
"if",
"(",
"type",
"===",
"'@vocab'",
")",
"{",
"return",
"{",
"'@id'",
":",
"_expandIri",
"(",
"activeCtx",
",",
"value",
",",
"{",
"vocab",
":",
"true",
",",
"base",
":",
"true",
"}",
")",
"}",
";",
"}",
"// do not expand keyword values",
"if",
"(",
"_isKeyword",
"(",
"expandedProperty",
")",
")",
"{",
"return",
"value",
";",
"}",
"rval",
"=",
"{",
"}",
";",
"// other type",
"if",
"(",
"type",
"!==",
"null",
")",
"{",
"rval",
"[",
"'@type'",
"]",
"=",
"type",
";",
"}",
"// check for language tagging for strings",
"else",
"if",
"(",
"_isString",
"(",
"value",
")",
")",
"{",
"var",
"language",
"=",
"jsonld",
".",
"getContextValue",
"(",
"activeCtx",
",",
"activeProperty",
",",
"'@language'",
")",
";",
"if",
"(",
"language",
"!==",
"null",
")",
"{",
"rval",
"[",
"'@language'",
"]",
"=",
"language",
";",
"}",
"}",
"rval",
"[",
"'@value'",
"]",
"=",
"value",
";",
"return",
"rval",
";",
"}"
]
| Expands the given value by using the coercion and keyword rules in the
given context.
@param activeCtx the active context to use.
@param activeProperty the active property the value is associated with.
@param value the value to expand.
@return the expanded value. | [
"Expands",
"the",
"given",
"value",
"by",
"using",
"the",
"coercion",
"and",
"keyword",
"rules",
"in",
"the",
"given",
"context",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3054-L3103 |
43,926 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _graphToRDF | function _graphToRDF(graph, namer) {
var rval = [];
var ids = Object.keys(graph).sort();
for(var i = 0; i < ids.length; ++i) {
var id = ids[i];
var node = graph[id];
var properties = Object.keys(node).sort();
for(var pi = 0; pi < properties.length; ++pi) {
var property = properties[pi];
var items = node[property];
if(property === '@type') {
property = RDF_TYPE;
}
else if(_isKeyword(property)) {
continue;
}
for(var ii = 0; ii < items.length; ++ii) {
var item = items[ii];
// RDF subject
var subject = {};
subject.type = (id.indexOf('_:') === 0) ? 'blank node' : 'IRI';
subject.value = id;
// RDF predicate
var predicate = {};
predicate.type = (property.indexOf('_:') === 0) ? 'blank node' : 'IRI';
predicate.value = property;
// convert @list to triples
if(_isList(item)) {
_listToRDF(item['@list'], namer, subject, predicate, rval);
}
// convert value or node object to triple
else {
var object = _objectToRDF(item);
rval.push({subject: subject, predicate: predicate, object: object});
}
}
}
}
return rval;
} | javascript | function _graphToRDF(graph, namer) {
var rval = [];
var ids = Object.keys(graph).sort();
for(var i = 0; i < ids.length; ++i) {
var id = ids[i];
var node = graph[id];
var properties = Object.keys(node).sort();
for(var pi = 0; pi < properties.length; ++pi) {
var property = properties[pi];
var items = node[property];
if(property === '@type') {
property = RDF_TYPE;
}
else if(_isKeyword(property)) {
continue;
}
for(var ii = 0; ii < items.length; ++ii) {
var item = items[ii];
// RDF subject
var subject = {};
subject.type = (id.indexOf('_:') === 0) ? 'blank node' : 'IRI';
subject.value = id;
// RDF predicate
var predicate = {};
predicate.type = (property.indexOf('_:') === 0) ? 'blank node' : 'IRI';
predicate.value = property;
// convert @list to triples
if(_isList(item)) {
_listToRDF(item['@list'], namer, subject, predicate, rval);
}
// convert value or node object to triple
else {
var object = _objectToRDF(item);
rval.push({subject: subject, predicate: predicate, object: object});
}
}
}
}
return rval;
} | [
"function",
"_graphToRDF",
"(",
"graph",
",",
"namer",
")",
"{",
"var",
"rval",
"=",
"[",
"]",
";",
"var",
"ids",
"=",
"Object",
".",
"keys",
"(",
"graph",
")",
".",
"sort",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ids",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"id",
"=",
"ids",
"[",
"i",
"]",
";",
"var",
"node",
"=",
"graph",
"[",
"id",
"]",
";",
"var",
"properties",
"=",
"Object",
".",
"keys",
"(",
"node",
")",
".",
"sort",
"(",
")",
";",
"for",
"(",
"var",
"pi",
"=",
"0",
";",
"pi",
"<",
"properties",
".",
"length",
";",
"++",
"pi",
")",
"{",
"var",
"property",
"=",
"properties",
"[",
"pi",
"]",
";",
"var",
"items",
"=",
"node",
"[",
"property",
"]",
";",
"if",
"(",
"property",
"===",
"'@type'",
")",
"{",
"property",
"=",
"RDF_TYPE",
";",
"}",
"else",
"if",
"(",
"_isKeyword",
"(",
"property",
")",
")",
"{",
"continue",
";",
"}",
"for",
"(",
"var",
"ii",
"=",
"0",
";",
"ii",
"<",
"items",
".",
"length",
";",
"++",
"ii",
")",
"{",
"var",
"item",
"=",
"items",
"[",
"ii",
"]",
";",
"// RDF subject",
"var",
"subject",
"=",
"{",
"}",
";",
"subject",
".",
"type",
"=",
"(",
"id",
".",
"indexOf",
"(",
"'_:'",
")",
"===",
"0",
")",
"?",
"'blank node'",
":",
"'IRI'",
";",
"subject",
".",
"value",
"=",
"id",
";",
"// RDF predicate",
"var",
"predicate",
"=",
"{",
"}",
";",
"predicate",
".",
"type",
"=",
"(",
"property",
".",
"indexOf",
"(",
"'_:'",
")",
"===",
"0",
")",
"?",
"'blank node'",
":",
"'IRI'",
";",
"predicate",
".",
"value",
"=",
"property",
";",
"// convert @list to triples",
"if",
"(",
"_isList",
"(",
"item",
")",
")",
"{",
"_listToRDF",
"(",
"item",
"[",
"'@list'",
"]",
",",
"namer",
",",
"subject",
",",
"predicate",
",",
"rval",
")",
";",
"}",
"// convert value or node object to triple",
"else",
"{",
"var",
"object",
"=",
"_objectToRDF",
"(",
"item",
")",
";",
"rval",
".",
"push",
"(",
"{",
"subject",
":",
"subject",
",",
"predicate",
":",
"predicate",
",",
"object",
":",
"object",
"}",
")",
";",
"}",
"}",
"}",
"}",
"return",
"rval",
";",
"}"
]
| Creates an array of RDF triples for the given graph.
@param graph the graph to create RDF triples for.
@param namer a UniqueNamer for assigning blank node names.
@return the array of RDF triples for the given graph. | [
"Creates",
"an",
"array",
"of",
"RDF",
"triples",
"for",
"the",
"given",
"graph",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3113-L3158 |
43,927 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _objectToRDF | function _objectToRDF(item) {
var object = {};
// convert value object to RDF
if(_isValue(item)) {
object.type = 'literal';
var value = item['@value'];
var datatype = item['@type'] || null;
// convert to XSD datatypes as appropriate
if(_isBoolean(value)) {
object.value = value.toString();
object.datatype = datatype || XSD_BOOLEAN;
}
else if(_isDouble(value) || datatype === XSD_DOUBLE) {
// canonical double representation
object.value = value.toExponential(15).replace(/(\d)0*e\+?/, '$1E');
object.datatype = datatype || XSD_DOUBLE;
}
else if(_isNumber(value)) {
object.value = value.toFixed(0);
object.datatype = datatype || XSD_INTEGER;
}
else if('@language' in item) {
object.value = value;
object.datatype = datatype || RDF_LANGSTRING;
object.language = item['@language'];
}
else {
object.value = value;
object.datatype = datatype || XSD_STRING;
}
}
// convert string/node object to RDF
else {
var id = _isObject(item) ? item['@id'] : item;
object.type = (id.indexOf('_:') === 0) ? 'blank node' : 'IRI';
object.value = id;
}
return object;
} | javascript | function _objectToRDF(item) {
var object = {};
// convert value object to RDF
if(_isValue(item)) {
object.type = 'literal';
var value = item['@value'];
var datatype = item['@type'] || null;
// convert to XSD datatypes as appropriate
if(_isBoolean(value)) {
object.value = value.toString();
object.datatype = datatype || XSD_BOOLEAN;
}
else if(_isDouble(value) || datatype === XSD_DOUBLE) {
// canonical double representation
object.value = value.toExponential(15).replace(/(\d)0*e\+?/, '$1E');
object.datatype = datatype || XSD_DOUBLE;
}
else if(_isNumber(value)) {
object.value = value.toFixed(0);
object.datatype = datatype || XSD_INTEGER;
}
else if('@language' in item) {
object.value = value;
object.datatype = datatype || RDF_LANGSTRING;
object.language = item['@language'];
}
else {
object.value = value;
object.datatype = datatype || XSD_STRING;
}
}
// convert string/node object to RDF
else {
var id = _isObject(item) ? item['@id'] : item;
object.type = (id.indexOf('_:') === 0) ? 'blank node' : 'IRI';
object.value = id;
}
return object;
} | [
"function",
"_objectToRDF",
"(",
"item",
")",
"{",
"var",
"object",
"=",
"{",
"}",
";",
"// convert value object to RDF",
"if",
"(",
"_isValue",
"(",
"item",
")",
")",
"{",
"object",
".",
"type",
"=",
"'literal'",
";",
"var",
"value",
"=",
"item",
"[",
"'@value'",
"]",
";",
"var",
"datatype",
"=",
"item",
"[",
"'@type'",
"]",
"||",
"null",
";",
"// convert to XSD datatypes as appropriate",
"if",
"(",
"_isBoolean",
"(",
"value",
")",
")",
"{",
"object",
".",
"value",
"=",
"value",
".",
"toString",
"(",
")",
";",
"object",
".",
"datatype",
"=",
"datatype",
"||",
"XSD_BOOLEAN",
";",
"}",
"else",
"if",
"(",
"_isDouble",
"(",
"value",
")",
"||",
"datatype",
"===",
"XSD_DOUBLE",
")",
"{",
"// canonical double representation",
"object",
".",
"value",
"=",
"value",
".",
"toExponential",
"(",
"15",
")",
".",
"replace",
"(",
"/",
"(\\d)0*e\\+?",
"/",
",",
"'$1E'",
")",
";",
"object",
".",
"datatype",
"=",
"datatype",
"||",
"XSD_DOUBLE",
";",
"}",
"else",
"if",
"(",
"_isNumber",
"(",
"value",
")",
")",
"{",
"object",
".",
"value",
"=",
"value",
".",
"toFixed",
"(",
"0",
")",
";",
"object",
".",
"datatype",
"=",
"datatype",
"||",
"XSD_INTEGER",
";",
"}",
"else",
"if",
"(",
"'@language'",
"in",
"item",
")",
"{",
"object",
".",
"value",
"=",
"value",
";",
"object",
".",
"datatype",
"=",
"datatype",
"||",
"RDF_LANGSTRING",
";",
"object",
".",
"language",
"=",
"item",
"[",
"'@language'",
"]",
";",
"}",
"else",
"{",
"object",
".",
"value",
"=",
"value",
";",
"object",
".",
"datatype",
"=",
"datatype",
"||",
"XSD_STRING",
";",
"}",
"}",
"// convert string/node object to RDF",
"else",
"{",
"var",
"id",
"=",
"_isObject",
"(",
"item",
")",
"?",
"item",
"[",
"'@id'",
"]",
":",
"item",
";",
"object",
".",
"type",
"=",
"(",
"id",
".",
"indexOf",
"(",
"'_:'",
")",
"===",
"0",
")",
"?",
"'blank node'",
":",
"'IRI'",
";",
"object",
".",
"value",
"=",
"id",
";",
"}",
"return",
"object",
";",
"}"
]
| Converts a JSON-LD value object to an RDF literal or a JSON-LD string or
node object to an RDF resource.
@param item the JSON-LD value or node object.
@return the RDF literal or RDF resource. | [
"Converts",
"a",
"JSON",
"-",
"LD",
"value",
"object",
"to",
"an",
"RDF",
"literal",
"or",
"a",
"JSON",
"-",
"LD",
"string",
"or",
"node",
"object",
"to",
"an",
"RDF",
"resource",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3200-L3241 |
43,928 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _RDFToObject | function _RDFToObject(o, useNativeTypes) {
// convert IRI/blank node object to JSON-LD
if(o.type === 'IRI' || o.type === 'blank node') {
return {'@id': o.value};
}
// convert literal to JSON-LD
var rval = {'@value': o.value};
// add language
if('language' in o) {
rval['@language'] = o.language;
}
// add datatype
else {
var type = o.datatype;
// use native types for certain xsd types
if(useNativeTypes) {
if(type === XSD_BOOLEAN) {
if(rval['@value'] === 'true') {
rval['@value'] = true;
}
else if(rval['@value'] === 'false') {
rval['@value'] = false;
}
}
else if(_isNumeric(rval['@value'])) {
if(type === XSD_INTEGER) {
var i = parseInt(rval['@value']);
if(i.toFixed(0) === rval['@value']) {
rval['@value'] = i;
}
}
else if(type === XSD_DOUBLE) {
rval['@value'] = parseFloat(rval['@value']);
}
}
// do not add native type
if([XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING]
.indexOf(type) === -1) {
rval['@type'] = type;
}
}
else if(type !== XSD_STRING) {
rval['@type'] = type;
}
}
return rval;
} | javascript | function _RDFToObject(o, useNativeTypes) {
// convert IRI/blank node object to JSON-LD
if(o.type === 'IRI' || o.type === 'blank node') {
return {'@id': o.value};
}
// convert literal to JSON-LD
var rval = {'@value': o.value};
// add language
if('language' in o) {
rval['@language'] = o.language;
}
// add datatype
else {
var type = o.datatype;
// use native types for certain xsd types
if(useNativeTypes) {
if(type === XSD_BOOLEAN) {
if(rval['@value'] === 'true') {
rval['@value'] = true;
}
else if(rval['@value'] === 'false') {
rval['@value'] = false;
}
}
else if(_isNumeric(rval['@value'])) {
if(type === XSD_INTEGER) {
var i = parseInt(rval['@value']);
if(i.toFixed(0) === rval['@value']) {
rval['@value'] = i;
}
}
else if(type === XSD_DOUBLE) {
rval['@value'] = parseFloat(rval['@value']);
}
}
// do not add native type
if([XSD_BOOLEAN, XSD_INTEGER, XSD_DOUBLE, XSD_STRING]
.indexOf(type) === -1) {
rval['@type'] = type;
}
}
else if(type !== XSD_STRING) {
rval['@type'] = type;
}
}
return rval;
} | [
"function",
"_RDFToObject",
"(",
"o",
",",
"useNativeTypes",
")",
"{",
"// convert IRI/blank node object to JSON-LD",
"if",
"(",
"o",
".",
"type",
"===",
"'IRI'",
"||",
"o",
".",
"type",
"===",
"'blank node'",
")",
"{",
"return",
"{",
"'@id'",
":",
"o",
".",
"value",
"}",
";",
"}",
"// convert literal to JSON-LD",
"var",
"rval",
"=",
"{",
"'@value'",
":",
"o",
".",
"value",
"}",
";",
"// add language",
"if",
"(",
"'language'",
"in",
"o",
")",
"{",
"rval",
"[",
"'@language'",
"]",
"=",
"o",
".",
"language",
";",
"}",
"// add datatype",
"else",
"{",
"var",
"type",
"=",
"o",
".",
"datatype",
";",
"// use native types for certain xsd types",
"if",
"(",
"useNativeTypes",
")",
"{",
"if",
"(",
"type",
"===",
"XSD_BOOLEAN",
")",
"{",
"if",
"(",
"rval",
"[",
"'@value'",
"]",
"===",
"'true'",
")",
"{",
"rval",
"[",
"'@value'",
"]",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"rval",
"[",
"'@value'",
"]",
"===",
"'false'",
")",
"{",
"rval",
"[",
"'@value'",
"]",
"=",
"false",
";",
"}",
"}",
"else",
"if",
"(",
"_isNumeric",
"(",
"rval",
"[",
"'@value'",
"]",
")",
")",
"{",
"if",
"(",
"type",
"===",
"XSD_INTEGER",
")",
"{",
"var",
"i",
"=",
"parseInt",
"(",
"rval",
"[",
"'@value'",
"]",
")",
";",
"if",
"(",
"i",
".",
"toFixed",
"(",
"0",
")",
"===",
"rval",
"[",
"'@value'",
"]",
")",
"{",
"rval",
"[",
"'@value'",
"]",
"=",
"i",
";",
"}",
"}",
"else",
"if",
"(",
"type",
"===",
"XSD_DOUBLE",
")",
"{",
"rval",
"[",
"'@value'",
"]",
"=",
"parseFloat",
"(",
"rval",
"[",
"'@value'",
"]",
")",
";",
"}",
"}",
"// do not add native type",
"if",
"(",
"[",
"XSD_BOOLEAN",
",",
"XSD_INTEGER",
",",
"XSD_DOUBLE",
",",
"XSD_STRING",
"]",
".",
"indexOf",
"(",
"type",
")",
"===",
"-",
"1",
")",
"{",
"rval",
"[",
"'@type'",
"]",
"=",
"type",
";",
"}",
"}",
"else",
"if",
"(",
"type",
"!==",
"XSD_STRING",
")",
"{",
"rval",
"[",
"'@type'",
"]",
"=",
"type",
";",
"}",
"}",
"return",
"rval",
";",
"}"
]
| Converts an RDF triple object to a JSON-LD object.
@param o the RDF triple object to convert.
@param useNativeTypes true to output native types, false not to.
@return the JSON-LD object. | [
"Converts",
"an",
"RDF",
"triple",
"object",
"to",
"a",
"JSON",
"-",
"LD",
"object",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3251-L3300 |
43,929 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _compareRDFTriples | function _compareRDFTriples(t1, t2) {
var attrs = ['subject', 'predicate', 'object'];
for(var i = 0; i < attrs.length; ++i) {
var attr = attrs[i];
if(t1[attr].type !== t2[attr].type || t1[attr].value !== t2[attr].value) {
return false;
}
}
if(t1.object.language !== t2.object.language) {
return false;
}
if(t1.object.datatype !== t2.object.datatype) {
return false;
}
return true;
} | javascript | function _compareRDFTriples(t1, t2) {
var attrs = ['subject', 'predicate', 'object'];
for(var i = 0; i < attrs.length; ++i) {
var attr = attrs[i];
if(t1[attr].type !== t2[attr].type || t1[attr].value !== t2[attr].value) {
return false;
}
}
if(t1.object.language !== t2.object.language) {
return false;
}
if(t1.object.datatype !== t2.object.datatype) {
return false;
}
return true;
} | [
"function",
"_compareRDFTriples",
"(",
"t1",
",",
"t2",
")",
"{",
"var",
"attrs",
"=",
"[",
"'subject'",
",",
"'predicate'",
",",
"'object'",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"attrs",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"attr",
"=",
"attrs",
"[",
"i",
"]",
";",
"if",
"(",
"t1",
"[",
"attr",
"]",
".",
"type",
"!==",
"t2",
"[",
"attr",
"]",
".",
"type",
"||",
"t1",
"[",
"attr",
"]",
".",
"value",
"!==",
"t2",
"[",
"attr",
"]",
".",
"value",
")",
"{",
"return",
"false",
";",
"}",
"}",
"if",
"(",
"t1",
".",
"object",
".",
"language",
"!==",
"t2",
".",
"object",
".",
"language",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"t1",
".",
"object",
".",
"datatype",
"!==",
"t2",
".",
"object",
".",
"datatype",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
]
| Compares two RDF triples for equality.
@param t1 the first triple.
@param t2 the second triple.
@return true if the triples are the same, false if not. | [
"Compares",
"two",
"RDF",
"triples",
"for",
"equality",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3310-L3325 |
43,930 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _hashQuads | function _hashQuads(id, bnodes, namer) {
// return cached hash
if('hash' in bnodes[id]) {
return bnodes[id].hash;
}
// serialize all of bnode's quads
var quads = bnodes[id].quads;
var nquads = [];
for(var i = 0; i < quads.length; ++i) {
nquads.push(_toNQuad(
quads[i], quads[i].name ? quads[i].name.value : null, id));
}
// sort serialized quads
nquads.sort();
// return hashed quads
var hash = bnodes[id].hash = sha1.hash(nquads);
return hash;
} | javascript | function _hashQuads(id, bnodes, namer) {
// return cached hash
if('hash' in bnodes[id]) {
return bnodes[id].hash;
}
// serialize all of bnode's quads
var quads = bnodes[id].quads;
var nquads = [];
for(var i = 0; i < quads.length; ++i) {
nquads.push(_toNQuad(
quads[i], quads[i].name ? quads[i].name.value : null, id));
}
// sort serialized quads
nquads.sort();
// return hashed quads
var hash = bnodes[id].hash = sha1.hash(nquads);
return hash;
} | [
"function",
"_hashQuads",
"(",
"id",
",",
"bnodes",
",",
"namer",
")",
"{",
"// return cached hash",
"if",
"(",
"'hash'",
"in",
"bnodes",
"[",
"id",
"]",
")",
"{",
"return",
"bnodes",
"[",
"id",
"]",
".",
"hash",
";",
"}",
"// serialize all of bnode's quads",
"var",
"quads",
"=",
"bnodes",
"[",
"id",
"]",
".",
"quads",
";",
"var",
"nquads",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"quads",
".",
"length",
";",
"++",
"i",
")",
"{",
"nquads",
".",
"push",
"(",
"_toNQuad",
"(",
"quads",
"[",
"i",
"]",
",",
"quads",
"[",
"i",
"]",
".",
"name",
"?",
"quads",
"[",
"i",
"]",
".",
"name",
".",
"value",
":",
"null",
",",
"id",
")",
")",
";",
"}",
"// sort serialized quads",
"nquads",
".",
"sort",
"(",
")",
";",
"// return hashed quads",
"var",
"hash",
"=",
"bnodes",
"[",
"id",
"]",
".",
"hash",
"=",
"sha1",
".",
"hash",
"(",
"nquads",
")",
";",
"return",
"hash",
";",
"}"
]
| Hashes all of the quads about a blank node.
@param id the ID of the bnode to hash quads for.
@param bnodes the mapping of bnodes to quads.
@param namer the canonical bnode namer.
@return the new hash. | [
"Hashes",
"all",
"of",
"the",
"quads",
"about",
"a",
"blank",
"node",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3336-L3354 |
43,931 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | nextPermutation | function nextPermutation(skipped) {
if(!skipped && (chosenPath === null || path < chosenPath)) {
chosenPath = path;
chosenNamer = pathNamerCopy;
}
// do next permutation
if(permutator.hasNext()) {
jsonld.setImmediate(function() {permutate();});
}
else {
// digest chosen path and update namer
md.update(chosenPath);
pathNamer = chosenNamer;
// hash the next group
hashGroup(i + 1);
}
} | javascript | function nextPermutation(skipped) {
if(!skipped && (chosenPath === null || path < chosenPath)) {
chosenPath = path;
chosenNamer = pathNamerCopy;
}
// do next permutation
if(permutator.hasNext()) {
jsonld.setImmediate(function() {permutate();});
}
else {
// digest chosen path and update namer
md.update(chosenPath);
pathNamer = chosenNamer;
// hash the next group
hashGroup(i + 1);
}
} | [
"function",
"nextPermutation",
"(",
"skipped",
")",
"{",
"if",
"(",
"!",
"skipped",
"&&",
"(",
"chosenPath",
"===",
"null",
"||",
"path",
"<",
"chosenPath",
")",
")",
"{",
"chosenPath",
"=",
"path",
";",
"chosenNamer",
"=",
"pathNamerCopy",
";",
"}",
"// do next permutation",
"if",
"(",
"permutator",
".",
"hasNext",
"(",
")",
")",
"{",
"jsonld",
".",
"setImmediate",
"(",
"function",
"(",
")",
"{",
"permutate",
"(",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"// digest chosen path and update namer",
"md",
".",
"update",
"(",
"chosenPath",
")",
";",
"pathNamer",
"=",
"chosenNamer",
";",
"// hash the next group",
"hashGroup",
"(",
"i",
"+",
"1",
")",
";",
"}",
"}"
]
| stores the results of this permutation and runs the next | [
"stores",
"the",
"results",
"of",
"this",
"permutation",
"and",
"runs",
"the",
"next"
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3507-L3525 |
43,932 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _getFrameFlag | function _getFrameFlag(frame, options, name) {
var flag = '@' + name;
return (flag in frame) ? frame[flag][0] : options[name];
} | javascript | function _getFrameFlag(frame, options, name) {
var flag = '@' + name;
return (flag in frame) ? frame[flag][0] : options[name];
} | [
"function",
"_getFrameFlag",
"(",
"frame",
",",
"options",
",",
"name",
")",
"{",
"var",
"flag",
"=",
"'@'",
"+",
"name",
";",
"return",
"(",
"flag",
"in",
"frame",
")",
"?",
"frame",
"[",
"flag",
"]",
"[",
"0",
"]",
":",
"options",
"[",
"name",
"]",
";",
"}"
]
| Gets the frame flag value for the given flag name.
@param frame the frame.
@param options the framing options.
@param name the flag name.
@return the flag value. | [
"Gets",
"the",
"frame",
"flag",
"value",
"for",
"the",
"given",
"flag",
"name",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3896-L3899 |
43,933 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _validateFrame | function _validateFrame(state, frame) {
if(!_isArray(frame) || frame.length !== 1 || !_isObject(frame[0])) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a JSON-LD frame must be a single object.',
'jsonld.SyntaxError', {frame: frame});
}
} | javascript | function _validateFrame(state, frame) {
if(!_isArray(frame) || frame.length !== 1 || !_isObject(frame[0])) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a JSON-LD frame must be a single object.',
'jsonld.SyntaxError', {frame: frame});
}
} | [
"function",
"_validateFrame",
"(",
"state",
",",
"frame",
")",
"{",
"if",
"(",
"!",
"_isArray",
"(",
"frame",
")",
"||",
"frame",
".",
"length",
"!==",
"1",
"||",
"!",
"_isObject",
"(",
"frame",
"[",
"0",
"]",
")",
")",
"{",
"throw",
"new",
"JsonLdError",
"(",
"'Invalid JSON-LD syntax; a JSON-LD frame must be a single object.'",
",",
"'jsonld.SyntaxError'",
",",
"{",
"frame",
":",
"frame",
"}",
")",
";",
"}",
"}"
]
| Validates a JSON-LD frame, throwing an exception if the frame is invalid.
@param state the current frame state.
@param frame the frame to validate. | [
"Validates",
"a",
"JSON",
"-",
"LD",
"frame",
"throwing",
"an",
"exception",
"if",
"the",
"frame",
"is",
"invalid",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3907-L3913 |
43,934 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _filterSubjects | function _filterSubjects(state, subjects, frame) {
// filter subjects in @id order
var rval = {};
for(var i = 0; i < subjects.length; ++i) {
var id = subjects[i];
var subject = state.subjects[id];
if(_filterSubject(subject, frame)) {
rval[id] = subject;
}
}
return rval;
} | javascript | function _filterSubjects(state, subjects, frame) {
// filter subjects in @id order
var rval = {};
for(var i = 0; i < subjects.length; ++i) {
var id = subjects[i];
var subject = state.subjects[id];
if(_filterSubject(subject, frame)) {
rval[id] = subject;
}
}
return rval;
} | [
"function",
"_filterSubjects",
"(",
"state",
",",
"subjects",
",",
"frame",
")",
"{",
"// filter subjects in @id order",
"var",
"rval",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"subjects",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"id",
"=",
"subjects",
"[",
"i",
"]",
";",
"var",
"subject",
"=",
"state",
".",
"subjects",
"[",
"id",
"]",
";",
"if",
"(",
"_filterSubject",
"(",
"subject",
",",
"frame",
")",
")",
"{",
"rval",
"[",
"id",
"]",
"=",
"subject",
";",
"}",
"}",
"return",
"rval",
";",
"}"
]
| Returns a map of all of the subjects that match a parsed frame.
@param state the current framing state.
@param subjects the set of subjects to filter.
@param frame the parsed frame.
@return all of the matched subjects. | [
"Returns",
"a",
"map",
"of",
"all",
"of",
"the",
"subjects",
"that",
"match",
"a",
"parsed",
"frame",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3924-L3935 |
43,935 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _filterSubject | function _filterSubject(subject, frame) {
// check @type (object value means 'any' type, fall through to ducktyping)
if('@type' in frame &&
!(frame['@type'].length === 1 && _isObject(frame['@type'][0]))) {
var types = frame['@type'];
for(var i = 0; i < types.length; ++i) {
// any matching @type is a match
if(jsonld.hasValue(subject, '@type', types[i])) {
return true;
}
}
return false;
}
// check ducktype
for(var key in frame) {
// only not a duck if @id or non-keyword isn't in subject
if((key === '@id' || !_isKeyword(key)) && !(key in subject)) {
return false;
}
}
return true;
} | javascript | function _filterSubject(subject, frame) {
// check @type (object value means 'any' type, fall through to ducktyping)
if('@type' in frame &&
!(frame['@type'].length === 1 && _isObject(frame['@type'][0]))) {
var types = frame['@type'];
for(var i = 0; i < types.length; ++i) {
// any matching @type is a match
if(jsonld.hasValue(subject, '@type', types[i])) {
return true;
}
}
return false;
}
// check ducktype
for(var key in frame) {
// only not a duck if @id or non-keyword isn't in subject
if((key === '@id' || !_isKeyword(key)) && !(key in subject)) {
return false;
}
}
return true;
} | [
"function",
"_filterSubject",
"(",
"subject",
",",
"frame",
")",
"{",
"// check @type (object value means 'any' type, fall through to ducktyping)",
"if",
"(",
"'@type'",
"in",
"frame",
"&&",
"!",
"(",
"frame",
"[",
"'@type'",
"]",
".",
"length",
"===",
"1",
"&&",
"_isObject",
"(",
"frame",
"[",
"'@type'",
"]",
"[",
"0",
"]",
")",
")",
")",
"{",
"var",
"types",
"=",
"frame",
"[",
"'@type'",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"types",
".",
"length",
";",
"++",
"i",
")",
"{",
"// any matching @type is a match",
"if",
"(",
"jsonld",
".",
"hasValue",
"(",
"subject",
",",
"'@type'",
",",
"types",
"[",
"i",
"]",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}",
"// check ducktype",
"for",
"(",
"var",
"key",
"in",
"frame",
")",
"{",
"// only not a duck if @id or non-keyword isn't in subject",
"if",
"(",
"(",
"key",
"===",
"'@id'",
"||",
"!",
"_isKeyword",
"(",
"key",
")",
")",
"&&",
"!",
"(",
"key",
"in",
"subject",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
]
| Returns true if the given subject matches the given frame.
@param subject the subject to check.
@param frame the frame to check.
@return true if the subject matches, false if not. | [
"Returns",
"true",
"if",
"the",
"given",
"subject",
"matches",
"the",
"given",
"frame",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3945-L3967 |
43,936 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _embedValues | function _embedValues(state, subject, property, output) {
// embed subject properties in output
var objects = subject[property];
for(var i = 0; i < objects.length; ++i) {
var o = objects[i];
// recurse into @list
if(_isList(o)) {
var list = {'@list': []};
_addFrameOutput(state, output, property, list);
return _embedValues(state, o, '@list', list['@list']);
}
// handle subject reference
if(_isSubjectReference(o)) {
var id = o['@id'];
// embed full subject if isn't already embedded
if(!(id in state.embeds)) {
// add embed
var embed = {parent: output, property: property};
state.embeds[id] = embed;
// recurse into subject
o = {};
var s = state.subjects[id];
for(var prop in s) {
// copy keywords
if(_isKeyword(prop)) {
o[prop] = _clone(s[prop]);
continue;
}
_embedValues(state, s, prop, o);
}
}
_addFrameOutput(state, output, property, o);
}
// copy non-subject value
else {
_addFrameOutput(state, output, property, _clone(o));
}
}
} | javascript | function _embedValues(state, subject, property, output) {
// embed subject properties in output
var objects = subject[property];
for(var i = 0; i < objects.length; ++i) {
var o = objects[i];
// recurse into @list
if(_isList(o)) {
var list = {'@list': []};
_addFrameOutput(state, output, property, list);
return _embedValues(state, o, '@list', list['@list']);
}
// handle subject reference
if(_isSubjectReference(o)) {
var id = o['@id'];
// embed full subject if isn't already embedded
if(!(id in state.embeds)) {
// add embed
var embed = {parent: output, property: property};
state.embeds[id] = embed;
// recurse into subject
o = {};
var s = state.subjects[id];
for(var prop in s) {
// copy keywords
if(_isKeyword(prop)) {
o[prop] = _clone(s[prop]);
continue;
}
_embedValues(state, s, prop, o);
}
}
_addFrameOutput(state, output, property, o);
}
// copy non-subject value
else {
_addFrameOutput(state, output, property, _clone(o));
}
}
} | [
"function",
"_embedValues",
"(",
"state",
",",
"subject",
",",
"property",
",",
"output",
")",
"{",
"// embed subject properties in output",
"var",
"objects",
"=",
"subject",
"[",
"property",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"objects",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"o",
"=",
"objects",
"[",
"i",
"]",
";",
"// recurse into @list",
"if",
"(",
"_isList",
"(",
"o",
")",
")",
"{",
"var",
"list",
"=",
"{",
"'@list'",
":",
"[",
"]",
"}",
";",
"_addFrameOutput",
"(",
"state",
",",
"output",
",",
"property",
",",
"list",
")",
";",
"return",
"_embedValues",
"(",
"state",
",",
"o",
",",
"'@list'",
",",
"list",
"[",
"'@list'",
"]",
")",
";",
"}",
"// handle subject reference",
"if",
"(",
"_isSubjectReference",
"(",
"o",
")",
")",
"{",
"var",
"id",
"=",
"o",
"[",
"'@id'",
"]",
";",
"// embed full subject if isn't already embedded",
"if",
"(",
"!",
"(",
"id",
"in",
"state",
".",
"embeds",
")",
")",
"{",
"// add embed",
"var",
"embed",
"=",
"{",
"parent",
":",
"output",
",",
"property",
":",
"property",
"}",
";",
"state",
".",
"embeds",
"[",
"id",
"]",
"=",
"embed",
";",
"// recurse into subject",
"o",
"=",
"{",
"}",
";",
"var",
"s",
"=",
"state",
".",
"subjects",
"[",
"id",
"]",
";",
"for",
"(",
"var",
"prop",
"in",
"s",
")",
"{",
"// copy keywords",
"if",
"(",
"_isKeyword",
"(",
"prop",
")",
")",
"{",
"o",
"[",
"prop",
"]",
"=",
"_clone",
"(",
"s",
"[",
"prop",
"]",
")",
";",
"continue",
";",
"}",
"_embedValues",
"(",
"state",
",",
"s",
",",
"prop",
",",
"o",
")",
";",
"}",
"}",
"_addFrameOutput",
"(",
"state",
",",
"output",
",",
"property",
",",
"o",
")",
";",
"}",
"// copy non-subject value",
"else",
"{",
"_addFrameOutput",
"(",
"state",
",",
"output",
",",
"property",
",",
"_clone",
"(",
"o",
")",
")",
";",
"}",
"}",
"}"
]
| Embeds values for the given subject and property into the given output
during the framing algorithm.
@param state the current framing state.
@param subject the subject.
@param property the property.
@param output the output. | [
"Embeds",
"values",
"for",
"the",
"given",
"subject",
"and",
"property",
"into",
"the",
"given",
"output",
"during",
"the",
"framing",
"algorithm",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L3978-L4020 |
43,937 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _removeEmbed | function _removeEmbed(state, id) {
// get existing embed
var embeds = state.embeds;
var embed = embeds[id];
var parent = embed.parent;
var property = embed.property;
// create reference to replace embed
var subject = {'@id': id};
// remove existing embed
if(_isArray(parent)) {
// replace subject with reference
for(var i = 0; i < parent.length; ++i) {
if(jsonld.compareValues(parent[i], subject)) {
parent[i] = subject;
break;
}
}
}
else {
// replace subject with reference
var useArray = _isArray(parent[property]);
jsonld.removeValue(parent, property, subject, {propertyIsArray: useArray});
jsonld.addValue(parent, property, subject, {propertyIsArray: useArray});
}
// recursively remove dependent dangling embeds
var removeDependents = function(id) {
// get embed keys as a separate array to enable deleting keys in map
var ids = Object.keys(embeds);
for(var i = 0; i < ids.length; ++i) {
var next = ids[i];
if(next in embeds && _isObject(embeds[next].parent) &&
embeds[next].parent['@id'] === id) {
delete embeds[next];
removeDependents(next);
}
}
};
removeDependents(id);
} | javascript | function _removeEmbed(state, id) {
// get existing embed
var embeds = state.embeds;
var embed = embeds[id];
var parent = embed.parent;
var property = embed.property;
// create reference to replace embed
var subject = {'@id': id};
// remove existing embed
if(_isArray(parent)) {
// replace subject with reference
for(var i = 0; i < parent.length; ++i) {
if(jsonld.compareValues(parent[i], subject)) {
parent[i] = subject;
break;
}
}
}
else {
// replace subject with reference
var useArray = _isArray(parent[property]);
jsonld.removeValue(parent, property, subject, {propertyIsArray: useArray});
jsonld.addValue(parent, property, subject, {propertyIsArray: useArray});
}
// recursively remove dependent dangling embeds
var removeDependents = function(id) {
// get embed keys as a separate array to enable deleting keys in map
var ids = Object.keys(embeds);
for(var i = 0; i < ids.length; ++i) {
var next = ids[i];
if(next in embeds && _isObject(embeds[next].parent) &&
embeds[next].parent['@id'] === id) {
delete embeds[next];
removeDependents(next);
}
}
};
removeDependents(id);
} | [
"function",
"_removeEmbed",
"(",
"state",
",",
"id",
")",
"{",
"// get existing embed",
"var",
"embeds",
"=",
"state",
".",
"embeds",
";",
"var",
"embed",
"=",
"embeds",
"[",
"id",
"]",
";",
"var",
"parent",
"=",
"embed",
".",
"parent",
";",
"var",
"property",
"=",
"embed",
".",
"property",
";",
"// create reference to replace embed",
"var",
"subject",
"=",
"{",
"'@id'",
":",
"id",
"}",
";",
"// remove existing embed",
"if",
"(",
"_isArray",
"(",
"parent",
")",
")",
"{",
"// replace subject with reference",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"parent",
".",
"length",
";",
"++",
"i",
")",
"{",
"if",
"(",
"jsonld",
".",
"compareValues",
"(",
"parent",
"[",
"i",
"]",
",",
"subject",
")",
")",
"{",
"parent",
"[",
"i",
"]",
"=",
"subject",
";",
"break",
";",
"}",
"}",
"}",
"else",
"{",
"// replace subject with reference",
"var",
"useArray",
"=",
"_isArray",
"(",
"parent",
"[",
"property",
"]",
")",
";",
"jsonld",
".",
"removeValue",
"(",
"parent",
",",
"property",
",",
"subject",
",",
"{",
"propertyIsArray",
":",
"useArray",
"}",
")",
";",
"jsonld",
".",
"addValue",
"(",
"parent",
",",
"property",
",",
"subject",
",",
"{",
"propertyIsArray",
":",
"useArray",
"}",
")",
";",
"}",
"// recursively remove dependent dangling embeds",
"var",
"removeDependents",
"=",
"function",
"(",
"id",
")",
"{",
"// get embed keys as a separate array to enable deleting keys in map",
"var",
"ids",
"=",
"Object",
".",
"keys",
"(",
"embeds",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ids",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"next",
"=",
"ids",
"[",
"i",
"]",
";",
"if",
"(",
"next",
"in",
"embeds",
"&&",
"_isObject",
"(",
"embeds",
"[",
"next",
"]",
".",
"parent",
")",
"&&",
"embeds",
"[",
"next",
"]",
".",
"parent",
"[",
"'@id'",
"]",
"===",
"id",
")",
"{",
"delete",
"embeds",
"[",
"next",
"]",
";",
"removeDependents",
"(",
"next",
")",
";",
"}",
"}",
"}",
";",
"removeDependents",
"(",
"id",
")",
";",
"}"
]
| Removes an existing embed.
@param state the current framing state.
@param id the @id of the embed to remove. | [
"Removes",
"an",
"existing",
"embed",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L4028-L4069 |
43,938 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | function(id) {
// get embed keys as a separate array to enable deleting keys in map
var ids = Object.keys(embeds);
for(var i = 0; i < ids.length; ++i) {
var next = ids[i];
if(next in embeds && _isObject(embeds[next].parent) &&
embeds[next].parent['@id'] === id) {
delete embeds[next];
removeDependents(next);
}
}
} | javascript | function(id) {
// get embed keys as a separate array to enable deleting keys in map
var ids = Object.keys(embeds);
for(var i = 0; i < ids.length; ++i) {
var next = ids[i];
if(next in embeds && _isObject(embeds[next].parent) &&
embeds[next].parent['@id'] === id) {
delete embeds[next];
removeDependents(next);
}
}
} | [
"function",
"(",
"id",
")",
"{",
"// get embed keys as a separate array to enable deleting keys in map",
"var",
"ids",
"=",
"Object",
".",
"keys",
"(",
"embeds",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"ids",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"next",
"=",
"ids",
"[",
"i",
"]",
";",
"if",
"(",
"next",
"in",
"embeds",
"&&",
"_isObject",
"(",
"embeds",
"[",
"next",
"]",
".",
"parent",
")",
"&&",
"embeds",
"[",
"next",
"]",
".",
"parent",
"[",
"'@id'",
"]",
"===",
"id",
")",
"{",
"delete",
"embeds",
"[",
"next",
"]",
";",
"removeDependents",
"(",
"next",
")",
";",
"}",
"}",
"}"
]
| recursively remove dependent dangling embeds | [
"recursively",
"remove",
"dependent",
"dangling",
"embeds"
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L4056-L4067 |
|
43,939 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _addFrameOutput | function _addFrameOutput(state, parent, property, output) {
if(_isObject(parent)) {
jsonld.addValue(parent, property, output, {propertyIsArray: true});
}
else {
parent.push(output);
}
} | javascript | function _addFrameOutput(state, parent, property, output) {
if(_isObject(parent)) {
jsonld.addValue(parent, property, output, {propertyIsArray: true});
}
else {
parent.push(output);
}
} | [
"function",
"_addFrameOutput",
"(",
"state",
",",
"parent",
",",
"property",
",",
"output",
")",
"{",
"if",
"(",
"_isObject",
"(",
"parent",
")",
")",
"{",
"jsonld",
".",
"addValue",
"(",
"parent",
",",
"property",
",",
"output",
",",
"{",
"propertyIsArray",
":",
"true",
"}",
")",
";",
"}",
"else",
"{",
"parent",
".",
"push",
"(",
"output",
")",
";",
"}",
"}"
]
| Adds framing output to the given parent.
@param state the current framing state.
@param parent the parent to add to.
@param property the parent property.
@param output the output to add. | [
"Adds",
"framing",
"output",
"to",
"the",
"given",
"parent",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L4079-L4086 |
43,940 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _selectTerm | function _selectTerm(
activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue) {
if(typeOrLanguageValue === null) {
typeOrLanguageValue = '@null';
}
// preferences for the value of @type or @language
var prefs = [];
// determine prefs for @id based on whether or not value compacts to a term
if((typeOrLanguageValue === '@id' || typeOrLanguageValue === '@reverse') &&
_isSubjectReference(value)) {
// prefer @reverse first
if(typeOrLanguageValue === '@reverse') {
prefs.push('@reverse');
}
// try to compact value to a term
var term = _compactIri(activeCtx, value['@id'], null, {vocab: true});
if(term in activeCtx.mappings &&
activeCtx.mappings[term] &&
activeCtx.mappings[term]['@id'] === value['@id']) {
// prefer @vocab
prefs.push.apply(prefs, ['@vocab', '@id']);
}
else {
// prefer @id
prefs.push.apply(prefs, ['@id', '@vocab']);
}
}
else {
prefs.push(typeOrLanguageValue);
}
prefs.push('@none');
var containerMap = activeCtx.inverse[iri];
for(var ci = 0; ci < containers.length; ++ci) {
// if container not available in the map, continue
var container = containers[ci];
if(!(container in containerMap)) {
continue;
}
var typeOrLanguageValueMap = containerMap[container][typeOrLanguage];
for(var pi = 0; pi < prefs.length; ++pi) {
// if type/language option not available in the map, continue
var pref = prefs[pi];
if(!(pref in typeOrLanguageValueMap)) {
continue;
}
// select term
return typeOrLanguageValueMap[pref];
}
}
return null;
} | javascript | function _selectTerm(
activeCtx, iri, value, containers, typeOrLanguage, typeOrLanguageValue) {
if(typeOrLanguageValue === null) {
typeOrLanguageValue = '@null';
}
// preferences for the value of @type or @language
var prefs = [];
// determine prefs for @id based on whether or not value compacts to a term
if((typeOrLanguageValue === '@id' || typeOrLanguageValue === '@reverse') &&
_isSubjectReference(value)) {
// prefer @reverse first
if(typeOrLanguageValue === '@reverse') {
prefs.push('@reverse');
}
// try to compact value to a term
var term = _compactIri(activeCtx, value['@id'], null, {vocab: true});
if(term in activeCtx.mappings &&
activeCtx.mappings[term] &&
activeCtx.mappings[term]['@id'] === value['@id']) {
// prefer @vocab
prefs.push.apply(prefs, ['@vocab', '@id']);
}
else {
// prefer @id
prefs.push.apply(prefs, ['@id', '@vocab']);
}
}
else {
prefs.push(typeOrLanguageValue);
}
prefs.push('@none');
var containerMap = activeCtx.inverse[iri];
for(var ci = 0; ci < containers.length; ++ci) {
// if container not available in the map, continue
var container = containers[ci];
if(!(container in containerMap)) {
continue;
}
var typeOrLanguageValueMap = containerMap[container][typeOrLanguage];
for(var pi = 0; pi < prefs.length; ++pi) {
// if type/language option not available in the map, continue
var pref = prefs[pi];
if(!(pref in typeOrLanguageValueMap)) {
continue;
}
// select term
return typeOrLanguageValueMap[pref];
}
}
return null;
} | [
"function",
"_selectTerm",
"(",
"activeCtx",
",",
"iri",
",",
"value",
",",
"containers",
",",
"typeOrLanguage",
",",
"typeOrLanguageValue",
")",
"{",
"if",
"(",
"typeOrLanguageValue",
"===",
"null",
")",
"{",
"typeOrLanguageValue",
"=",
"'@null'",
";",
"}",
"// preferences for the value of @type or @language",
"var",
"prefs",
"=",
"[",
"]",
";",
"// determine prefs for @id based on whether or not value compacts to a term",
"if",
"(",
"(",
"typeOrLanguageValue",
"===",
"'@id'",
"||",
"typeOrLanguageValue",
"===",
"'@reverse'",
")",
"&&",
"_isSubjectReference",
"(",
"value",
")",
")",
"{",
"// prefer @reverse first",
"if",
"(",
"typeOrLanguageValue",
"===",
"'@reverse'",
")",
"{",
"prefs",
".",
"push",
"(",
"'@reverse'",
")",
";",
"}",
"// try to compact value to a term",
"var",
"term",
"=",
"_compactIri",
"(",
"activeCtx",
",",
"value",
"[",
"'@id'",
"]",
",",
"null",
",",
"{",
"vocab",
":",
"true",
"}",
")",
";",
"if",
"(",
"term",
"in",
"activeCtx",
".",
"mappings",
"&&",
"activeCtx",
".",
"mappings",
"[",
"term",
"]",
"&&",
"activeCtx",
".",
"mappings",
"[",
"term",
"]",
"[",
"'@id'",
"]",
"===",
"value",
"[",
"'@id'",
"]",
")",
"{",
"// prefer @vocab",
"prefs",
".",
"push",
".",
"apply",
"(",
"prefs",
",",
"[",
"'@vocab'",
",",
"'@id'",
"]",
")",
";",
"}",
"else",
"{",
"// prefer @id",
"prefs",
".",
"push",
".",
"apply",
"(",
"prefs",
",",
"[",
"'@id'",
",",
"'@vocab'",
"]",
")",
";",
"}",
"}",
"else",
"{",
"prefs",
".",
"push",
"(",
"typeOrLanguageValue",
")",
";",
"}",
"prefs",
".",
"push",
"(",
"'@none'",
")",
";",
"var",
"containerMap",
"=",
"activeCtx",
".",
"inverse",
"[",
"iri",
"]",
";",
"for",
"(",
"var",
"ci",
"=",
"0",
";",
"ci",
"<",
"containers",
".",
"length",
";",
"++",
"ci",
")",
"{",
"// if container not available in the map, continue",
"var",
"container",
"=",
"containers",
"[",
"ci",
"]",
";",
"if",
"(",
"!",
"(",
"container",
"in",
"containerMap",
")",
")",
"{",
"continue",
";",
"}",
"var",
"typeOrLanguageValueMap",
"=",
"containerMap",
"[",
"container",
"]",
"[",
"typeOrLanguage",
"]",
";",
"for",
"(",
"var",
"pi",
"=",
"0",
";",
"pi",
"<",
"prefs",
".",
"length",
";",
"++",
"pi",
")",
"{",
"// if type/language option not available in the map, continue",
"var",
"pref",
"=",
"prefs",
"[",
"pi",
"]",
";",
"if",
"(",
"!",
"(",
"pref",
"in",
"typeOrLanguageValueMap",
")",
")",
"{",
"continue",
";",
"}",
"// select term",
"return",
"typeOrLanguageValueMap",
"[",
"pref",
"]",
";",
"}",
"}",
"return",
"null",
";",
"}"
]
| Picks the preferred compaction term from the given inverse context entry.
@param activeCtx the active context.
@param iri the IRI to pick the term for.
@param value the value to pick the term for.
@param containers the preferred containers.
@param typeOrLanguage either '@type' or '@language'.
@param typeOrLanguageValue the preferred value for '@type' or '@language'.
@return the preferred term. | [
"Picks",
"the",
"preferred",
"compaction",
"term",
"from",
"the",
"given",
"inverse",
"context",
"entry",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L4177-L4233 |
43,941 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _expandIri | function _expandIri(activeCtx, value, relativeTo, localCtx, defined) {
// already expanded
if(value === null || _isKeyword(value)) {
return value;
}
// define term dependency if not defined
if(localCtx && value in localCtx && defined[value] !== true) {
_createTermDefinition(activeCtx, localCtx, value, defined);
}
relativeTo = relativeTo || {};
if(relativeTo.vocab) {
var mapping = activeCtx.mappings[value];
// value is explicitly ignored with a null mapping
if(mapping === null) {
return null;
}
if(mapping) {
// value is a term
return mapping['@id'];
}
}
// split value into prefix:suffix
var colon = value.indexOf(':');
if(colon !== -1) {
var prefix = value.substr(0, colon);
var suffix = value.substr(colon + 1);
// do not expand blank nodes (prefix of '_') or already-absolute
// IRIs (suffix of '//')
if(prefix === '_' || suffix.indexOf('//') === 0) {
return value;
}
// prefix dependency not defined, define it
if(localCtx && prefix in localCtx) {
_createTermDefinition(activeCtx, localCtx, prefix, defined);
}
// use mapping if prefix is defined
var mapping = activeCtx.mappings[prefix];
if(mapping) {
return mapping['@id'] + suffix;
}
// already absolute IRI
return value;
}
// prepend vocab
if(relativeTo.vocab && '@vocab' in activeCtx) {
return activeCtx['@vocab'] + value;
}
// prepend base
var rval = value;
if(relativeTo.base) {
rval = _prependBase(activeCtx['@base'], rval);
}
if(localCtx) {
// value must now be an absolute IRI
if(!_isAbsoluteIri(rval)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a @context value does not expand to ' +
'an absolute IRI.',
'jsonld.SyntaxError', {context: localCtx, value: value});
}
}
return rval;
} | javascript | function _expandIri(activeCtx, value, relativeTo, localCtx, defined) {
// already expanded
if(value === null || _isKeyword(value)) {
return value;
}
// define term dependency if not defined
if(localCtx && value in localCtx && defined[value] !== true) {
_createTermDefinition(activeCtx, localCtx, value, defined);
}
relativeTo = relativeTo || {};
if(relativeTo.vocab) {
var mapping = activeCtx.mappings[value];
// value is explicitly ignored with a null mapping
if(mapping === null) {
return null;
}
if(mapping) {
// value is a term
return mapping['@id'];
}
}
// split value into prefix:suffix
var colon = value.indexOf(':');
if(colon !== -1) {
var prefix = value.substr(0, colon);
var suffix = value.substr(colon + 1);
// do not expand blank nodes (prefix of '_') or already-absolute
// IRIs (suffix of '//')
if(prefix === '_' || suffix.indexOf('//') === 0) {
return value;
}
// prefix dependency not defined, define it
if(localCtx && prefix in localCtx) {
_createTermDefinition(activeCtx, localCtx, prefix, defined);
}
// use mapping if prefix is defined
var mapping = activeCtx.mappings[prefix];
if(mapping) {
return mapping['@id'] + suffix;
}
// already absolute IRI
return value;
}
// prepend vocab
if(relativeTo.vocab && '@vocab' in activeCtx) {
return activeCtx['@vocab'] + value;
}
// prepend base
var rval = value;
if(relativeTo.base) {
rval = _prependBase(activeCtx['@base'], rval);
}
if(localCtx) {
// value must now be an absolute IRI
if(!_isAbsoluteIri(rval)) {
throw new JsonLdError(
'Invalid JSON-LD syntax; a @context value does not expand to ' +
'an absolute IRI.',
'jsonld.SyntaxError', {context: localCtx, value: value});
}
}
return rval;
} | [
"function",
"_expandIri",
"(",
"activeCtx",
",",
"value",
",",
"relativeTo",
",",
"localCtx",
",",
"defined",
")",
"{",
"// already expanded",
"if",
"(",
"value",
"===",
"null",
"||",
"_isKeyword",
"(",
"value",
")",
")",
"{",
"return",
"value",
";",
"}",
"// define term dependency if not defined",
"if",
"(",
"localCtx",
"&&",
"value",
"in",
"localCtx",
"&&",
"defined",
"[",
"value",
"]",
"!==",
"true",
")",
"{",
"_createTermDefinition",
"(",
"activeCtx",
",",
"localCtx",
",",
"value",
",",
"defined",
")",
";",
"}",
"relativeTo",
"=",
"relativeTo",
"||",
"{",
"}",
";",
"if",
"(",
"relativeTo",
".",
"vocab",
")",
"{",
"var",
"mapping",
"=",
"activeCtx",
".",
"mappings",
"[",
"value",
"]",
";",
"// value is explicitly ignored with a null mapping",
"if",
"(",
"mapping",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"mapping",
")",
"{",
"// value is a term",
"return",
"mapping",
"[",
"'@id'",
"]",
";",
"}",
"}",
"// split value into prefix:suffix",
"var",
"colon",
"=",
"value",
".",
"indexOf",
"(",
"':'",
")",
";",
"if",
"(",
"colon",
"!==",
"-",
"1",
")",
"{",
"var",
"prefix",
"=",
"value",
".",
"substr",
"(",
"0",
",",
"colon",
")",
";",
"var",
"suffix",
"=",
"value",
".",
"substr",
"(",
"colon",
"+",
"1",
")",
";",
"// do not expand blank nodes (prefix of '_') or already-absolute",
"// IRIs (suffix of '//')",
"if",
"(",
"prefix",
"===",
"'_'",
"||",
"suffix",
".",
"indexOf",
"(",
"'//'",
")",
"===",
"0",
")",
"{",
"return",
"value",
";",
"}",
"// prefix dependency not defined, define it",
"if",
"(",
"localCtx",
"&&",
"prefix",
"in",
"localCtx",
")",
"{",
"_createTermDefinition",
"(",
"activeCtx",
",",
"localCtx",
",",
"prefix",
",",
"defined",
")",
";",
"}",
"// use mapping if prefix is defined",
"var",
"mapping",
"=",
"activeCtx",
".",
"mappings",
"[",
"prefix",
"]",
";",
"if",
"(",
"mapping",
")",
"{",
"return",
"mapping",
"[",
"'@id'",
"]",
"+",
"suffix",
";",
"}",
"// already absolute IRI",
"return",
"value",
";",
"}",
"// prepend vocab",
"if",
"(",
"relativeTo",
".",
"vocab",
"&&",
"'@vocab'",
"in",
"activeCtx",
")",
"{",
"return",
"activeCtx",
"[",
"'@vocab'",
"]",
"+",
"value",
";",
"}",
"// prepend base",
"var",
"rval",
"=",
"value",
";",
"if",
"(",
"relativeTo",
".",
"base",
")",
"{",
"rval",
"=",
"_prependBase",
"(",
"activeCtx",
"[",
"'@base'",
"]",
",",
"rval",
")",
";",
"}",
"if",
"(",
"localCtx",
")",
"{",
"// value must now be an absolute IRI",
"if",
"(",
"!",
"_isAbsoluteIri",
"(",
"rval",
")",
")",
"{",
"throw",
"new",
"JsonLdError",
"(",
"'Invalid JSON-LD syntax; a @context value does not expand to '",
"+",
"'an absolute IRI.'",
",",
"'jsonld.SyntaxError'",
",",
"{",
"context",
":",
"localCtx",
",",
"value",
":",
"value",
"}",
")",
";",
"}",
"}",
"return",
"rval",
";",
"}"
]
| Expands a string to a full IRI. The string may be a term, a prefix, a
relative IRI, or an absolute IRI. The associated absolute IRI will be
returned.
@param activeCtx the current active context.
@param value the string to expand.
@param relativeTo options for how to resolve relative IRIs:
base: true to resolve against the base IRI, false not to.
vocab: true to concatenate after @vocab, false not to.
@param localCtx the local context being processed (only given if called
during context processing).
@param defined a map for tracking cycles in context definitions (only given
if called during context processing).
@return the expanded value. | [
"Expands",
"a",
"string",
"to",
"a",
"full",
"IRI",
".",
"The",
"string",
"may",
"be",
"a",
"term",
"a",
"prefix",
"a",
"relative",
"IRI",
"or",
"an",
"absolute",
"IRI",
".",
"The",
"associated",
"absolute",
"IRI",
"will",
"be",
"returned",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L4729-L4804 |
43,942 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _prependBase | function _prependBase(base, iri) {
// already an absolute IRI
if(iri.indexOf(':') !== -1) {
return iri;
}
// parse base if it is a string
if(_isString(base)) {
base = jsonld.url.parse(base || '');
}
// parse given IRI
var rel = jsonld.url.parse(iri);
// start hierarchical part
var hierPart = (base.protocol || '');
if(rel.authority) {
hierPart += '//' + rel.authority;
}
else if(base.href !== '') {
hierPart += '//' + base.authority;
}
// per RFC3986 normalize
var path;
// IRI represents an absolute path
if(rel.pathname.indexOf('/') === 0) {
path = rel.pathname;
}
else {
path = base.pathname;
// append relative path to the end of the last directory from base
if(rel.pathname !== '') {
path = path.substr(0, path.lastIndexOf('/') + 1);
if(path.length > 0 && path.substr(-1) !== '/') {
path += '/';
}
path += rel.pathname;
}
}
// remove slashes and dots in path
path = _removeDotSegments(path, hierPart !== '');
// add query and hash
if(rel.query) {
path += '?' + rel.query;
}
if(rel.hash) {
path += rel.hash;
}
var rval = hierPart + path;
if(rval === '') {
rval = './';
}
return rval;
} | javascript | function _prependBase(base, iri) {
// already an absolute IRI
if(iri.indexOf(':') !== -1) {
return iri;
}
// parse base if it is a string
if(_isString(base)) {
base = jsonld.url.parse(base || '');
}
// parse given IRI
var rel = jsonld.url.parse(iri);
// start hierarchical part
var hierPart = (base.protocol || '');
if(rel.authority) {
hierPart += '//' + rel.authority;
}
else if(base.href !== '') {
hierPart += '//' + base.authority;
}
// per RFC3986 normalize
var path;
// IRI represents an absolute path
if(rel.pathname.indexOf('/') === 0) {
path = rel.pathname;
}
else {
path = base.pathname;
// append relative path to the end of the last directory from base
if(rel.pathname !== '') {
path = path.substr(0, path.lastIndexOf('/') + 1);
if(path.length > 0 && path.substr(-1) !== '/') {
path += '/';
}
path += rel.pathname;
}
}
// remove slashes and dots in path
path = _removeDotSegments(path, hierPart !== '');
// add query and hash
if(rel.query) {
path += '?' + rel.query;
}
if(rel.hash) {
path += rel.hash;
}
var rval = hierPart + path;
if(rval === '') {
rval = './';
}
return rval;
} | [
"function",
"_prependBase",
"(",
"base",
",",
"iri",
")",
"{",
"// already an absolute IRI",
"if",
"(",
"iri",
".",
"indexOf",
"(",
"':'",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"iri",
";",
"}",
"// parse base if it is a string",
"if",
"(",
"_isString",
"(",
"base",
")",
")",
"{",
"base",
"=",
"jsonld",
".",
"url",
".",
"parse",
"(",
"base",
"||",
"''",
")",
";",
"}",
"// parse given IRI",
"var",
"rel",
"=",
"jsonld",
".",
"url",
".",
"parse",
"(",
"iri",
")",
";",
"// start hierarchical part",
"var",
"hierPart",
"=",
"(",
"base",
".",
"protocol",
"||",
"''",
")",
";",
"if",
"(",
"rel",
".",
"authority",
")",
"{",
"hierPart",
"+=",
"'//'",
"+",
"rel",
".",
"authority",
";",
"}",
"else",
"if",
"(",
"base",
".",
"href",
"!==",
"''",
")",
"{",
"hierPart",
"+=",
"'//'",
"+",
"base",
".",
"authority",
";",
"}",
"// per RFC3986 normalize",
"var",
"path",
";",
"// IRI represents an absolute path",
"if",
"(",
"rel",
".",
"pathname",
".",
"indexOf",
"(",
"'/'",
")",
"===",
"0",
")",
"{",
"path",
"=",
"rel",
".",
"pathname",
";",
"}",
"else",
"{",
"path",
"=",
"base",
".",
"pathname",
";",
"// append relative path to the end of the last directory from base",
"if",
"(",
"rel",
".",
"pathname",
"!==",
"''",
")",
"{",
"path",
"=",
"path",
".",
"substr",
"(",
"0",
",",
"path",
".",
"lastIndexOf",
"(",
"'/'",
")",
"+",
"1",
")",
";",
"if",
"(",
"path",
".",
"length",
">",
"0",
"&&",
"path",
".",
"substr",
"(",
"-",
"1",
")",
"!==",
"'/'",
")",
"{",
"path",
"+=",
"'/'",
";",
"}",
"path",
"+=",
"rel",
".",
"pathname",
";",
"}",
"}",
"// remove slashes and dots in path",
"path",
"=",
"_removeDotSegments",
"(",
"path",
",",
"hierPart",
"!==",
"''",
")",
";",
"// add query and hash",
"if",
"(",
"rel",
".",
"query",
")",
"{",
"path",
"+=",
"'?'",
"+",
"rel",
".",
"query",
";",
"}",
"if",
"(",
"rel",
".",
"hash",
")",
"{",
"path",
"+=",
"rel",
".",
"hash",
";",
"}",
"var",
"rval",
"=",
"hierPart",
"+",
"path",
";",
"if",
"(",
"rval",
"===",
"''",
")",
"{",
"rval",
"=",
"'./'",
";",
"}",
"return",
"rval",
";",
"}"
]
| Prepends a base IRI to the given relative IRI.
@param base the base IRI.
@param iri the relative IRI.
@return the absolute IRI. | [
"Prepends",
"a",
"base",
"IRI",
"to",
"the",
"given",
"relative",
"IRI",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L4814-L4875 |
43,943 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _removeBase | function _removeBase(base, iri) {
if(_isString(base)) {
base = jsonld.url.parse(base || '');
}
// establish base root
var root = '';
if(base.href !== '') {
root += (base.protocol || '') + '//' + base.authority;
}
// support network-path reference with empty base
else if(iri.indexOf('//')) {
root += '//';
}
// IRI not relative to base
if(iri.indexOf(root) !== 0) {
return iri;
}
// remove root from IRI and parse remainder
var rel = jsonld.url.parse(iri.substr(root.length));
// remove path segments that match
var baseSegments = base.normalizedPath.split('/');
var iriSegments = rel.normalizedPath.split('/');
while(baseSegments.length > 0 && iriSegments.length > 0) {
if(baseSegments[0] !== iriSegments[0]) {
break;
}
baseSegments.shift();
iriSegments.shift();
}
// use '../' for each non-matching base segment
var rval = '';
if(baseSegments.length > 0) {
// don't count the last segment if it isn't a path (doesn't end in '/')
// don't count empty first segment, it means base began with '/'
if(base.normalizedPath.substr(-1) !== '/' || baseSegments[0] === '') {
baseSegments.pop();
}
for(var i = 0; i < baseSegments.length; ++i) {
rval += '../';
}
}
// prepend remaining segments
rval += iriSegments.join('/');
// add query and hash
if(rel.query) {
rval += '?' + rel.query;
}
if(rel.hash) {
rval += rel.hash;
}
if(rval === '') {
rval = './';
}
return rval;
} | javascript | function _removeBase(base, iri) {
if(_isString(base)) {
base = jsonld.url.parse(base || '');
}
// establish base root
var root = '';
if(base.href !== '') {
root += (base.protocol || '') + '//' + base.authority;
}
// support network-path reference with empty base
else if(iri.indexOf('//')) {
root += '//';
}
// IRI not relative to base
if(iri.indexOf(root) !== 0) {
return iri;
}
// remove root from IRI and parse remainder
var rel = jsonld.url.parse(iri.substr(root.length));
// remove path segments that match
var baseSegments = base.normalizedPath.split('/');
var iriSegments = rel.normalizedPath.split('/');
while(baseSegments.length > 0 && iriSegments.length > 0) {
if(baseSegments[0] !== iriSegments[0]) {
break;
}
baseSegments.shift();
iriSegments.shift();
}
// use '../' for each non-matching base segment
var rval = '';
if(baseSegments.length > 0) {
// don't count the last segment if it isn't a path (doesn't end in '/')
// don't count empty first segment, it means base began with '/'
if(base.normalizedPath.substr(-1) !== '/' || baseSegments[0] === '') {
baseSegments.pop();
}
for(var i = 0; i < baseSegments.length; ++i) {
rval += '../';
}
}
// prepend remaining segments
rval += iriSegments.join('/');
// add query and hash
if(rel.query) {
rval += '?' + rel.query;
}
if(rel.hash) {
rval += rel.hash;
}
if(rval === '') {
rval = './';
}
return rval;
} | [
"function",
"_removeBase",
"(",
"base",
",",
"iri",
")",
"{",
"if",
"(",
"_isString",
"(",
"base",
")",
")",
"{",
"base",
"=",
"jsonld",
".",
"url",
".",
"parse",
"(",
"base",
"||",
"''",
")",
";",
"}",
"// establish base root",
"var",
"root",
"=",
"''",
";",
"if",
"(",
"base",
".",
"href",
"!==",
"''",
")",
"{",
"root",
"+=",
"(",
"base",
".",
"protocol",
"||",
"''",
")",
"+",
"'//'",
"+",
"base",
".",
"authority",
";",
"}",
"// support network-path reference with empty base",
"else",
"if",
"(",
"iri",
".",
"indexOf",
"(",
"'//'",
")",
")",
"{",
"root",
"+=",
"'//'",
";",
"}",
"// IRI not relative to base",
"if",
"(",
"iri",
".",
"indexOf",
"(",
"root",
")",
"!==",
"0",
")",
"{",
"return",
"iri",
";",
"}",
"// remove root from IRI and parse remainder",
"var",
"rel",
"=",
"jsonld",
".",
"url",
".",
"parse",
"(",
"iri",
".",
"substr",
"(",
"root",
".",
"length",
")",
")",
";",
"// remove path segments that match",
"var",
"baseSegments",
"=",
"base",
".",
"normalizedPath",
".",
"split",
"(",
"'/'",
")",
";",
"var",
"iriSegments",
"=",
"rel",
".",
"normalizedPath",
".",
"split",
"(",
"'/'",
")",
";",
"while",
"(",
"baseSegments",
".",
"length",
">",
"0",
"&&",
"iriSegments",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"baseSegments",
"[",
"0",
"]",
"!==",
"iriSegments",
"[",
"0",
"]",
")",
"{",
"break",
";",
"}",
"baseSegments",
".",
"shift",
"(",
")",
";",
"iriSegments",
".",
"shift",
"(",
")",
";",
"}",
"// use '../' for each non-matching base segment",
"var",
"rval",
"=",
"''",
";",
"if",
"(",
"baseSegments",
".",
"length",
">",
"0",
")",
"{",
"// don't count the last segment if it isn't a path (doesn't end in '/')",
"// don't count empty first segment, it means base began with '/'",
"if",
"(",
"base",
".",
"normalizedPath",
".",
"substr",
"(",
"-",
"1",
")",
"!==",
"'/'",
"||",
"baseSegments",
"[",
"0",
"]",
"===",
"''",
")",
"{",
"baseSegments",
".",
"pop",
"(",
")",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"baseSegments",
".",
"length",
";",
"++",
"i",
")",
"{",
"rval",
"+=",
"'../'",
";",
"}",
"}",
"// prepend remaining segments",
"rval",
"+=",
"iriSegments",
".",
"join",
"(",
"'/'",
")",
";",
"// add query and hash",
"if",
"(",
"rel",
".",
"query",
")",
"{",
"rval",
"+=",
"'?'",
"+",
"rel",
".",
"query",
";",
"}",
"if",
"(",
"rel",
".",
"hash",
")",
"{",
"rval",
"+=",
"rel",
".",
"hash",
";",
"}",
"if",
"(",
"rval",
"===",
"''",
")",
"{",
"rval",
"=",
"'./'",
";",
"}",
"return",
"rval",
";",
"}"
]
| Removes a base IRI from the given absolute IRI.
@param base the base IRI.
@param iri the absolute IRI.
@return the relative IRI if relative to base, otherwise the absolute IRI. | [
"Removes",
"a",
"base",
"IRI",
"from",
"the",
"given",
"absolute",
"IRI",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L4885-L4949 |
43,944 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _createInverseContext | function _createInverseContext() {
var activeCtx = this;
// lazily create inverse
if(activeCtx.inverse) {
return activeCtx.inverse;
}
var inverse = activeCtx.inverse = {};
// handle default language
var defaultLanguage = activeCtx['@language'] || '@none';
// create term selections for each mapping in the context, ordered by
// shortest and then lexicographically least
var mappings = activeCtx.mappings;
var terms = Object.keys(mappings).sort(_compareShortestLeast);
for(var i = 0; i < terms.length; ++i) {
var term = terms[i];
var mapping = mappings[term];
if(mapping === null) {
continue;
}
var container = mapping['@container'] || '@none';
// iterate over every IRI in the mapping
var ids = mapping['@id'];
if(!_isArray(ids)) {
ids = [ids];
}
for(var ii = 0; ii < ids.length; ++ii) {
var iri = ids[ii];
var entry = inverse[iri];
// initialize entry
if(!entry) {
inverse[iri] = entry = {};
}
// add new entry
if(!entry[container]) {
entry[container] = {
'@language': {},
'@type': {}
};
}
entry = entry[container];
// term is preferred for values using @reverse
if(mapping.reverse) {
_addPreferredTerm(mapping, term, entry['@type'], '@reverse');
}
// term is preferred for values using specific type
else if('@type' in mapping) {
_addPreferredTerm(mapping, term, entry['@type'], mapping['@type']);
}
// term is preferred for values using specific language
else if('@language' in mapping) {
var language = mapping['@language'] || '@null';
_addPreferredTerm(mapping, term, entry['@language'], language);
}
// term is preferred for values w/default language or no type and
// no language
else {
// add an entry for the default language
_addPreferredTerm(mapping, term, entry['@language'], defaultLanguage);
// add entries for no type and no language
_addPreferredTerm(mapping, term, entry['@type'], '@none');
_addPreferredTerm(mapping, term, entry['@language'], '@none');
}
}
}
return inverse;
} | javascript | function _createInverseContext() {
var activeCtx = this;
// lazily create inverse
if(activeCtx.inverse) {
return activeCtx.inverse;
}
var inverse = activeCtx.inverse = {};
// handle default language
var defaultLanguage = activeCtx['@language'] || '@none';
// create term selections for each mapping in the context, ordered by
// shortest and then lexicographically least
var mappings = activeCtx.mappings;
var terms = Object.keys(mappings).sort(_compareShortestLeast);
for(var i = 0; i < terms.length; ++i) {
var term = terms[i];
var mapping = mappings[term];
if(mapping === null) {
continue;
}
var container = mapping['@container'] || '@none';
// iterate over every IRI in the mapping
var ids = mapping['@id'];
if(!_isArray(ids)) {
ids = [ids];
}
for(var ii = 0; ii < ids.length; ++ii) {
var iri = ids[ii];
var entry = inverse[iri];
// initialize entry
if(!entry) {
inverse[iri] = entry = {};
}
// add new entry
if(!entry[container]) {
entry[container] = {
'@language': {},
'@type': {}
};
}
entry = entry[container];
// term is preferred for values using @reverse
if(mapping.reverse) {
_addPreferredTerm(mapping, term, entry['@type'], '@reverse');
}
// term is preferred for values using specific type
else if('@type' in mapping) {
_addPreferredTerm(mapping, term, entry['@type'], mapping['@type']);
}
// term is preferred for values using specific language
else if('@language' in mapping) {
var language = mapping['@language'] || '@null';
_addPreferredTerm(mapping, term, entry['@language'], language);
}
// term is preferred for values w/default language or no type and
// no language
else {
// add an entry for the default language
_addPreferredTerm(mapping, term, entry['@language'], defaultLanguage);
// add entries for no type and no language
_addPreferredTerm(mapping, term, entry['@type'], '@none');
_addPreferredTerm(mapping, term, entry['@language'], '@none');
}
}
}
return inverse;
} | [
"function",
"_createInverseContext",
"(",
")",
"{",
"var",
"activeCtx",
"=",
"this",
";",
"// lazily create inverse",
"if",
"(",
"activeCtx",
".",
"inverse",
")",
"{",
"return",
"activeCtx",
".",
"inverse",
";",
"}",
"var",
"inverse",
"=",
"activeCtx",
".",
"inverse",
"=",
"{",
"}",
";",
"// handle default language",
"var",
"defaultLanguage",
"=",
"activeCtx",
"[",
"'@language'",
"]",
"||",
"'@none'",
";",
"// create term selections for each mapping in the context, ordered by",
"// shortest and then lexicographically least",
"var",
"mappings",
"=",
"activeCtx",
".",
"mappings",
";",
"var",
"terms",
"=",
"Object",
".",
"keys",
"(",
"mappings",
")",
".",
"sort",
"(",
"_compareShortestLeast",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"terms",
".",
"length",
";",
"++",
"i",
")",
"{",
"var",
"term",
"=",
"terms",
"[",
"i",
"]",
";",
"var",
"mapping",
"=",
"mappings",
"[",
"term",
"]",
";",
"if",
"(",
"mapping",
"===",
"null",
")",
"{",
"continue",
";",
"}",
"var",
"container",
"=",
"mapping",
"[",
"'@container'",
"]",
"||",
"'@none'",
";",
"// iterate over every IRI in the mapping",
"var",
"ids",
"=",
"mapping",
"[",
"'@id'",
"]",
";",
"if",
"(",
"!",
"_isArray",
"(",
"ids",
")",
")",
"{",
"ids",
"=",
"[",
"ids",
"]",
";",
"}",
"for",
"(",
"var",
"ii",
"=",
"0",
";",
"ii",
"<",
"ids",
".",
"length",
";",
"++",
"ii",
")",
"{",
"var",
"iri",
"=",
"ids",
"[",
"ii",
"]",
";",
"var",
"entry",
"=",
"inverse",
"[",
"iri",
"]",
";",
"// initialize entry",
"if",
"(",
"!",
"entry",
")",
"{",
"inverse",
"[",
"iri",
"]",
"=",
"entry",
"=",
"{",
"}",
";",
"}",
"// add new entry",
"if",
"(",
"!",
"entry",
"[",
"container",
"]",
")",
"{",
"entry",
"[",
"container",
"]",
"=",
"{",
"'@language'",
":",
"{",
"}",
",",
"'@type'",
":",
"{",
"}",
"}",
";",
"}",
"entry",
"=",
"entry",
"[",
"container",
"]",
";",
"// term is preferred for values using @reverse",
"if",
"(",
"mapping",
".",
"reverse",
")",
"{",
"_addPreferredTerm",
"(",
"mapping",
",",
"term",
",",
"entry",
"[",
"'@type'",
"]",
",",
"'@reverse'",
")",
";",
"}",
"// term is preferred for values using specific type",
"else",
"if",
"(",
"'@type'",
"in",
"mapping",
")",
"{",
"_addPreferredTerm",
"(",
"mapping",
",",
"term",
",",
"entry",
"[",
"'@type'",
"]",
",",
"mapping",
"[",
"'@type'",
"]",
")",
";",
"}",
"// term is preferred for values using specific language",
"else",
"if",
"(",
"'@language'",
"in",
"mapping",
")",
"{",
"var",
"language",
"=",
"mapping",
"[",
"'@language'",
"]",
"||",
"'@null'",
";",
"_addPreferredTerm",
"(",
"mapping",
",",
"term",
",",
"entry",
"[",
"'@language'",
"]",
",",
"language",
")",
";",
"}",
"// term is preferred for values w/default language or no type and",
"// no language",
"else",
"{",
"// add an entry for the default language",
"_addPreferredTerm",
"(",
"mapping",
",",
"term",
",",
"entry",
"[",
"'@language'",
"]",
",",
"defaultLanguage",
")",
";",
"// add entries for no type and no language",
"_addPreferredTerm",
"(",
"mapping",
",",
"term",
",",
"entry",
"[",
"'@type'",
"]",
",",
"'@none'",
")",
";",
"_addPreferredTerm",
"(",
"mapping",
",",
"term",
",",
"entry",
"[",
"'@language'",
"]",
",",
"'@none'",
")",
";",
"}",
"}",
"}",
"return",
"inverse",
";",
"}"
]
| Generates an inverse context for use in the compaction algorithm, if
not already generated for the given active context.
@return the inverse context. | [
"Generates",
"an",
"inverse",
"context",
"for",
"use",
"in",
"the",
"compaction",
"algorithm",
"if",
"not",
"already",
"generated",
"for",
"the",
"given",
"active",
"context",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L4975-L5050 |
43,945 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _addPreferredTerm | function _addPreferredTerm(mapping, term, entry, typeOrLanguageValue) {
if(!(typeOrLanguageValue in entry)) {
entry[typeOrLanguageValue] = term;
}
} | javascript | function _addPreferredTerm(mapping, term, entry, typeOrLanguageValue) {
if(!(typeOrLanguageValue in entry)) {
entry[typeOrLanguageValue] = term;
}
} | [
"function",
"_addPreferredTerm",
"(",
"mapping",
",",
"term",
",",
"entry",
",",
"typeOrLanguageValue",
")",
"{",
"if",
"(",
"!",
"(",
"typeOrLanguageValue",
"in",
"entry",
")",
")",
"{",
"entry",
"[",
"typeOrLanguageValue",
"]",
"=",
"term",
";",
"}",
"}"
]
| Adds the term for the given entry if not already added.
@param mapping the term mapping.
@param term the term to add.
@param entry the inverse context typeOrLanguage entry to add to.
@param typeOrLanguageValue the key in the entry to add to. | [
"Adds",
"the",
"term",
"for",
"the",
"given",
"entry",
"if",
"not",
"already",
"added",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L5060-L5064 |
43,946 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _cloneActiveContext | function _cloneActiveContext() {
var child = {};
child['@base'] = this['@base'];
child.mappings = _clone(this.mappings);
child.clone = this.clone;
child.inverse = null;
child.getInverse = this.getInverse;
if('@language' in this) {
child['@language'] = this['@language'];
}
if('@vocab' in this) {
child['@vocab'] = this['@vocab'];
}
return child;
} | javascript | function _cloneActiveContext() {
var child = {};
child['@base'] = this['@base'];
child.mappings = _clone(this.mappings);
child.clone = this.clone;
child.inverse = null;
child.getInverse = this.getInverse;
if('@language' in this) {
child['@language'] = this['@language'];
}
if('@vocab' in this) {
child['@vocab'] = this['@vocab'];
}
return child;
} | [
"function",
"_cloneActiveContext",
"(",
")",
"{",
"var",
"child",
"=",
"{",
"}",
";",
"child",
"[",
"'@base'",
"]",
"=",
"this",
"[",
"'@base'",
"]",
";",
"child",
".",
"mappings",
"=",
"_clone",
"(",
"this",
".",
"mappings",
")",
";",
"child",
".",
"clone",
"=",
"this",
".",
"clone",
";",
"child",
".",
"inverse",
"=",
"null",
";",
"child",
".",
"getInverse",
"=",
"this",
".",
"getInverse",
";",
"if",
"(",
"'@language'",
"in",
"this",
")",
"{",
"child",
"[",
"'@language'",
"]",
"=",
"this",
"[",
"'@language'",
"]",
";",
"}",
"if",
"(",
"'@vocab'",
"in",
"this",
")",
"{",
"child",
"[",
"'@vocab'",
"]",
"=",
"this",
"[",
"'@vocab'",
"]",
";",
"}",
"return",
"child",
";",
"}"
]
| Clones an active context, creating a child active context.
@return a clone (child) of the active context. | [
"Clones",
"an",
"active",
"context",
"creating",
"a",
"child",
"active",
"context",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L5071-L5085 |
43,947 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _isSubject | function _isSubject(v) {
// Note: A value is a subject if all of these hold true:
// 1. It is an Object.
// 2. It is not a @value, @set, or @list.
// 3. It has more than 1 key OR any existing key is not @id.
var rval = false;
if(_isObject(v) &&
!(('@value' in v) || ('@set' in v) || ('@list' in v))) {
var keyCount = Object.keys(v).length;
rval = (keyCount > 1 || !('@id' in v));
}
return rval;
} | javascript | function _isSubject(v) {
// Note: A value is a subject if all of these hold true:
// 1. It is an Object.
// 2. It is not a @value, @set, or @list.
// 3. It has more than 1 key OR any existing key is not @id.
var rval = false;
if(_isObject(v) &&
!(('@value' in v) || ('@set' in v) || ('@list' in v))) {
var keyCount = Object.keys(v).length;
rval = (keyCount > 1 || !('@id' in v));
}
return rval;
} | [
"function",
"_isSubject",
"(",
"v",
")",
"{",
"// Note: A value is a subject if all of these hold true:",
"// 1. It is an Object.",
"// 2. It is not a @value, @set, or @list.",
"// 3. It has more than 1 key OR any existing key is not @id.",
"var",
"rval",
"=",
"false",
";",
"if",
"(",
"_isObject",
"(",
"v",
")",
"&&",
"!",
"(",
"(",
"'@value'",
"in",
"v",
")",
"||",
"(",
"'@set'",
"in",
"v",
")",
"||",
"(",
"'@list'",
"in",
"v",
")",
")",
")",
"{",
"var",
"keyCount",
"=",
"Object",
".",
"keys",
"(",
"v",
")",
".",
"length",
";",
"rval",
"=",
"(",
"keyCount",
">",
"1",
"||",
"!",
"(",
"'@id'",
"in",
"v",
")",
")",
";",
"}",
"return",
"rval",
";",
"}"
]
| Returns true if the given value is a subject with properties.
@param v the value to check.
@return true if the value is a subject with properties, false if not. | [
"Returns",
"true",
"if",
"the",
"given",
"value",
"is",
"a",
"subject",
"with",
"properties",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L5263-L5275 |
43,948 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _isBlankNode | function _isBlankNode(v) {
// Note: A value is a blank node if all of these hold true:
// 1. It is an Object.
// 2. If it has an @id key its value begins with '_:'.
// 3. It has no keys OR is not a @value, @set, or @list.
var rval = false;
if(_isObject(v)) {
if('@id' in v) {
rval = (v['@id'].indexOf('_:') === 0);
}
else {
rval = (Object.keys(v).length === 0 ||
!(('@value' in v) || ('@set' in v) || ('@list' in v)));
}
}
return rval;
} | javascript | function _isBlankNode(v) {
// Note: A value is a blank node if all of these hold true:
// 1. It is an Object.
// 2. If it has an @id key its value begins with '_:'.
// 3. It has no keys OR is not a @value, @set, or @list.
var rval = false;
if(_isObject(v)) {
if('@id' in v) {
rval = (v['@id'].indexOf('_:') === 0);
}
else {
rval = (Object.keys(v).length === 0 ||
!(('@value' in v) || ('@set' in v) || ('@list' in v)));
}
}
return rval;
} | [
"function",
"_isBlankNode",
"(",
"v",
")",
"{",
"// Note: A value is a blank node if all of these hold true:",
"// 1. It is an Object.",
"// 2. If it has an @id key its value begins with '_:'.",
"// 3. It has no keys OR is not a @value, @set, or @list.",
"var",
"rval",
"=",
"false",
";",
"if",
"(",
"_isObject",
"(",
"v",
")",
")",
"{",
"if",
"(",
"'@id'",
"in",
"v",
")",
"{",
"rval",
"=",
"(",
"v",
"[",
"'@id'",
"]",
".",
"indexOf",
"(",
"'_:'",
")",
"===",
"0",
")",
";",
"}",
"else",
"{",
"rval",
"=",
"(",
"Object",
".",
"keys",
"(",
"v",
")",
".",
"length",
"===",
"0",
"||",
"!",
"(",
"(",
"'@value'",
"in",
"v",
")",
"||",
"(",
"'@set'",
"in",
"v",
")",
"||",
"(",
"'@list'",
"in",
"v",
")",
")",
")",
";",
"}",
"}",
"return",
"rval",
";",
"}"
]
| Returns true if the given value is a blank node.
@param v the value to check.
@return true if the value is a blank node, false if not. | [
"Returns",
"true",
"if",
"the",
"given",
"value",
"is",
"a",
"blank",
"node",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L5326-L5342 |
43,949 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _parseNQuads | function _parseNQuads(input) {
// define partial regexes
var iri = '(?:<([^:]+:[^>]*)>)';
var bnode = '(_:(?:[A-Za-z][A-Za-z0-9]*))';
var plain = '"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"';
var datatype = '(?:\\^\\^' + iri + ')';
var language = '(?:@([a-z]+(?:-[a-z0-9]+)*))';
var literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)';
var ws = '[ \\t]+';
var wso = '[ \\t]*';
var eoln = /(?:\r\n)|(?:\n)|(?:\r)/g;
var empty = new RegExp('^' + wso + '$');
// define quad part regexes
var subject = '(?:' + iri + '|' + bnode + ')' + ws;
var property = iri + ws;
var object = '(?:' + iri + '|' + bnode + '|' + literal + ')' + wso;
var graphName = '(?:\\.|(?:(?:' + iri + '|' + bnode + ')' + wso + '\\.))';
// full quad regex
var quad = new RegExp(
'^' + wso + subject + property + object + graphName + wso + '$');
// build RDF dataset
var dataset = {};
// split N-Quad input into lines
var lines = input.split(eoln);
var lineNumber = 0;
for(var li = 0; li < lines.length; ++li) {
var line = lines[li];
lineNumber++;
// skip empty lines
if(empty.test(line)) {
continue;
}
// parse quad
var match = line.match(quad);
if(match === null) {
throw new JsonLdError(
'Error while parsing N-Quads; invalid quad.',
'jsonld.ParseError', {line: lineNumber});
}
// create RDF triple
var triple = {};
// get subject
if(!_isUndefined(match[1])) {
triple.subject = {type: 'IRI', value: match[1]};
}
else {
triple.subject = {type: 'blank node', value: match[2]};
}
// get predicate
triple.predicate = {type: 'IRI', value: match[3]};
// get object
if(!_isUndefined(match[4])) {
triple.object = {type: 'IRI', value: match[4]};
}
else if(!_isUndefined(match[5])) {
triple.object = {type: 'blank node', value: match[5]};
}
else {
triple.object = {type: 'literal'};
if(!_isUndefined(match[7])) {
triple.object.datatype = match[7];
}
else if(!_isUndefined(match[8])) {
triple.object.datatype = RDF_LANGSTRING;
triple.object.language = match[8];
}
else {
triple.object.datatype = XSD_STRING;
}
var unescaped = match[6]
.replace(/\\"/g, '"')
.replace(/\\t/g, '\t')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\\\/g, '\\');
triple.object.value = unescaped;
}
// get graph name ('@default' is used for the default graph)
var name = '@default';
if(!_isUndefined(match[9])) {
name = match[9];
}
else if(!_isUndefined(match[10])) {
name = match[10];
}
// initialize graph in dataset
if(!(name in dataset)) {
dataset[name] = [triple];
}
// add triple if unique to its graph
else {
var unique = true;
var triples = dataset[name];
for(var ti = 0; unique && ti < triples.length; ++ti) {
if(_compareRDFTriples(triples[ti], triple)) {
unique = false;
}
}
if(unique) {
triples.push(triple);
}
}
}
return dataset;
} | javascript | function _parseNQuads(input) {
// define partial regexes
var iri = '(?:<([^:]+:[^>]*)>)';
var bnode = '(_:(?:[A-Za-z][A-Za-z0-9]*))';
var plain = '"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"';
var datatype = '(?:\\^\\^' + iri + ')';
var language = '(?:@([a-z]+(?:-[a-z0-9]+)*))';
var literal = '(?:' + plain + '(?:' + datatype + '|' + language + ')?)';
var ws = '[ \\t]+';
var wso = '[ \\t]*';
var eoln = /(?:\r\n)|(?:\n)|(?:\r)/g;
var empty = new RegExp('^' + wso + '$');
// define quad part regexes
var subject = '(?:' + iri + '|' + bnode + ')' + ws;
var property = iri + ws;
var object = '(?:' + iri + '|' + bnode + '|' + literal + ')' + wso;
var graphName = '(?:\\.|(?:(?:' + iri + '|' + bnode + ')' + wso + '\\.))';
// full quad regex
var quad = new RegExp(
'^' + wso + subject + property + object + graphName + wso + '$');
// build RDF dataset
var dataset = {};
// split N-Quad input into lines
var lines = input.split(eoln);
var lineNumber = 0;
for(var li = 0; li < lines.length; ++li) {
var line = lines[li];
lineNumber++;
// skip empty lines
if(empty.test(line)) {
continue;
}
// parse quad
var match = line.match(quad);
if(match === null) {
throw new JsonLdError(
'Error while parsing N-Quads; invalid quad.',
'jsonld.ParseError', {line: lineNumber});
}
// create RDF triple
var triple = {};
// get subject
if(!_isUndefined(match[1])) {
triple.subject = {type: 'IRI', value: match[1]};
}
else {
triple.subject = {type: 'blank node', value: match[2]};
}
// get predicate
triple.predicate = {type: 'IRI', value: match[3]};
// get object
if(!_isUndefined(match[4])) {
triple.object = {type: 'IRI', value: match[4]};
}
else if(!_isUndefined(match[5])) {
triple.object = {type: 'blank node', value: match[5]};
}
else {
triple.object = {type: 'literal'};
if(!_isUndefined(match[7])) {
triple.object.datatype = match[7];
}
else if(!_isUndefined(match[8])) {
triple.object.datatype = RDF_LANGSTRING;
triple.object.language = match[8];
}
else {
triple.object.datatype = XSD_STRING;
}
var unescaped = match[6]
.replace(/\\"/g, '"')
.replace(/\\t/g, '\t')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\\\/g, '\\');
triple.object.value = unescaped;
}
// get graph name ('@default' is used for the default graph)
var name = '@default';
if(!_isUndefined(match[9])) {
name = match[9];
}
else if(!_isUndefined(match[10])) {
name = match[10];
}
// initialize graph in dataset
if(!(name in dataset)) {
dataset[name] = [triple];
}
// add triple if unique to its graph
else {
var unique = true;
var triples = dataset[name];
for(var ti = 0; unique && ti < triples.length; ++ti) {
if(_compareRDFTriples(triples[ti], triple)) {
unique = false;
}
}
if(unique) {
triples.push(triple);
}
}
}
return dataset;
} | [
"function",
"_parseNQuads",
"(",
"input",
")",
"{",
"// define partial regexes",
"var",
"iri",
"=",
"'(?:<([^:]+:[^>]*)>)'",
";",
"var",
"bnode",
"=",
"'(_:(?:[A-Za-z][A-Za-z0-9]*))'",
";",
"var",
"plain",
"=",
"'\"([^\"\\\\\\\\]*(?:\\\\\\\\.[^\"\\\\\\\\]*)*)\"'",
";",
"var",
"datatype",
"=",
"'(?:\\\\^\\\\^'",
"+",
"iri",
"+",
"')'",
";",
"var",
"language",
"=",
"'(?:@([a-z]+(?:-[a-z0-9]+)*))'",
";",
"var",
"literal",
"=",
"'(?:'",
"+",
"plain",
"+",
"'(?:'",
"+",
"datatype",
"+",
"'|'",
"+",
"language",
"+",
"')?)'",
";",
"var",
"ws",
"=",
"'[ \\\\t]+'",
";",
"var",
"wso",
"=",
"'[ \\\\t]*'",
";",
"var",
"eoln",
"=",
"/",
"(?:\\r\\n)|(?:\\n)|(?:\\r)",
"/",
"g",
";",
"var",
"empty",
"=",
"new",
"RegExp",
"(",
"'^'",
"+",
"wso",
"+",
"'$'",
")",
";",
"// define quad part regexes",
"var",
"subject",
"=",
"'(?:'",
"+",
"iri",
"+",
"'|'",
"+",
"bnode",
"+",
"')'",
"+",
"ws",
";",
"var",
"property",
"=",
"iri",
"+",
"ws",
";",
"var",
"object",
"=",
"'(?:'",
"+",
"iri",
"+",
"'|'",
"+",
"bnode",
"+",
"'|'",
"+",
"literal",
"+",
"')'",
"+",
"wso",
";",
"var",
"graphName",
"=",
"'(?:\\\\.|(?:(?:'",
"+",
"iri",
"+",
"'|'",
"+",
"bnode",
"+",
"')'",
"+",
"wso",
"+",
"'\\\\.))'",
";",
"// full quad regex",
"var",
"quad",
"=",
"new",
"RegExp",
"(",
"'^'",
"+",
"wso",
"+",
"subject",
"+",
"property",
"+",
"object",
"+",
"graphName",
"+",
"wso",
"+",
"'$'",
")",
";",
"// build RDF dataset",
"var",
"dataset",
"=",
"{",
"}",
";",
"// split N-Quad input into lines",
"var",
"lines",
"=",
"input",
".",
"split",
"(",
"eoln",
")",
";",
"var",
"lineNumber",
"=",
"0",
";",
"for",
"(",
"var",
"li",
"=",
"0",
";",
"li",
"<",
"lines",
".",
"length",
";",
"++",
"li",
")",
"{",
"var",
"line",
"=",
"lines",
"[",
"li",
"]",
";",
"lineNumber",
"++",
";",
"// skip empty lines",
"if",
"(",
"empty",
".",
"test",
"(",
"line",
")",
")",
"{",
"continue",
";",
"}",
"// parse quad",
"var",
"match",
"=",
"line",
".",
"match",
"(",
"quad",
")",
";",
"if",
"(",
"match",
"===",
"null",
")",
"{",
"throw",
"new",
"JsonLdError",
"(",
"'Error while parsing N-Quads; invalid quad.'",
",",
"'jsonld.ParseError'",
",",
"{",
"line",
":",
"lineNumber",
"}",
")",
";",
"}",
"// create RDF triple",
"var",
"triple",
"=",
"{",
"}",
";",
"// get subject",
"if",
"(",
"!",
"_isUndefined",
"(",
"match",
"[",
"1",
"]",
")",
")",
"{",
"triple",
".",
"subject",
"=",
"{",
"type",
":",
"'IRI'",
",",
"value",
":",
"match",
"[",
"1",
"]",
"}",
";",
"}",
"else",
"{",
"triple",
".",
"subject",
"=",
"{",
"type",
":",
"'blank node'",
",",
"value",
":",
"match",
"[",
"2",
"]",
"}",
";",
"}",
"// get predicate",
"triple",
".",
"predicate",
"=",
"{",
"type",
":",
"'IRI'",
",",
"value",
":",
"match",
"[",
"3",
"]",
"}",
";",
"// get object",
"if",
"(",
"!",
"_isUndefined",
"(",
"match",
"[",
"4",
"]",
")",
")",
"{",
"triple",
".",
"object",
"=",
"{",
"type",
":",
"'IRI'",
",",
"value",
":",
"match",
"[",
"4",
"]",
"}",
";",
"}",
"else",
"if",
"(",
"!",
"_isUndefined",
"(",
"match",
"[",
"5",
"]",
")",
")",
"{",
"triple",
".",
"object",
"=",
"{",
"type",
":",
"'blank node'",
",",
"value",
":",
"match",
"[",
"5",
"]",
"}",
";",
"}",
"else",
"{",
"triple",
".",
"object",
"=",
"{",
"type",
":",
"'literal'",
"}",
";",
"if",
"(",
"!",
"_isUndefined",
"(",
"match",
"[",
"7",
"]",
")",
")",
"{",
"triple",
".",
"object",
".",
"datatype",
"=",
"match",
"[",
"7",
"]",
";",
"}",
"else",
"if",
"(",
"!",
"_isUndefined",
"(",
"match",
"[",
"8",
"]",
")",
")",
"{",
"triple",
".",
"object",
".",
"datatype",
"=",
"RDF_LANGSTRING",
";",
"triple",
".",
"object",
".",
"language",
"=",
"match",
"[",
"8",
"]",
";",
"}",
"else",
"{",
"triple",
".",
"object",
".",
"datatype",
"=",
"XSD_STRING",
";",
"}",
"var",
"unescaped",
"=",
"match",
"[",
"6",
"]",
".",
"replace",
"(",
"/",
"\\\\\"",
"/",
"g",
",",
"'\"'",
")",
".",
"replace",
"(",
"/",
"\\\\t",
"/",
"g",
",",
"'\\t'",
")",
".",
"replace",
"(",
"/",
"\\\\n",
"/",
"g",
",",
"'\\n'",
")",
".",
"replace",
"(",
"/",
"\\\\r",
"/",
"g",
",",
"'\\r'",
")",
".",
"replace",
"(",
"/",
"\\\\\\\\",
"/",
"g",
",",
"'\\\\'",
")",
";",
"triple",
".",
"object",
".",
"value",
"=",
"unescaped",
";",
"}",
"// get graph name ('@default' is used for the default graph)",
"var",
"name",
"=",
"'@default'",
";",
"if",
"(",
"!",
"_isUndefined",
"(",
"match",
"[",
"9",
"]",
")",
")",
"{",
"name",
"=",
"match",
"[",
"9",
"]",
";",
"}",
"else",
"if",
"(",
"!",
"_isUndefined",
"(",
"match",
"[",
"10",
"]",
")",
")",
"{",
"name",
"=",
"match",
"[",
"10",
"]",
";",
"}",
"// initialize graph in dataset",
"if",
"(",
"!",
"(",
"name",
"in",
"dataset",
")",
")",
"{",
"dataset",
"[",
"name",
"]",
"=",
"[",
"triple",
"]",
";",
"}",
"// add triple if unique to its graph",
"else",
"{",
"var",
"unique",
"=",
"true",
";",
"var",
"triples",
"=",
"dataset",
"[",
"name",
"]",
";",
"for",
"(",
"var",
"ti",
"=",
"0",
";",
"unique",
"&&",
"ti",
"<",
"triples",
".",
"length",
";",
"++",
"ti",
")",
"{",
"if",
"(",
"_compareRDFTriples",
"(",
"triples",
"[",
"ti",
"]",
",",
"triple",
")",
")",
"{",
"unique",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"unique",
")",
"{",
"triples",
".",
"push",
"(",
"triple",
")",
";",
"}",
"}",
"}",
"return",
"dataset",
";",
"}"
]
| Parses RDF in the form of N-Quads.
@param input the N-Quads input to parse.
@return an RDF dataset. | [
"Parses",
"RDF",
"in",
"the",
"form",
"of",
"N",
"-",
"Quads",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L5622-L5739 |
43,950 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _toNQuads | function _toNQuads(dataset) {
var quads = [];
for(var graphName in dataset) {
var triples = dataset[graphName];
for(var ti = 0; ti < triples.length; ++ti) {
var triple = triples[ti];
if(graphName === '@default') {
graphName = null;
}
quads.push(_toNQuad(triple, graphName));
}
}
quads.sort();
return quads.join('');
} | javascript | function _toNQuads(dataset) {
var quads = [];
for(var graphName in dataset) {
var triples = dataset[graphName];
for(var ti = 0; ti < triples.length; ++ti) {
var triple = triples[ti];
if(graphName === '@default') {
graphName = null;
}
quads.push(_toNQuad(triple, graphName));
}
}
quads.sort();
return quads.join('');
} | [
"function",
"_toNQuads",
"(",
"dataset",
")",
"{",
"var",
"quads",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"graphName",
"in",
"dataset",
")",
"{",
"var",
"triples",
"=",
"dataset",
"[",
"graphName",
"]",
";",
"for",
"(",
"var",
"ti",
"=",
"0",
";",
"ti",
"<",
"triples",
".",
"length",
";",
"++",
"ti",
")",
"{",
"var",
"triple",
"=",
"triples",
"[",
"ti",
"]",
";",
"if",
"(",
"graphName",
"===",
"'@default'",
")",
"{",
"graphName",
"=",
"null",
";",
"}",
"quads",
".",
"push",
"(",
"_toNQuad",
"(",
"triple",
",",
"graphName",
")",
")",
";",
"}",
"}",
"quads",
".",
"sort",
"(",
")",
";",
"return",
"quads",
".",
"join",
"(",
"''",
")",
";",
"}"
]
| Converts an RDF dataset to N-Quads.
@param dataset the RDF dataset to convert.
@return the N-Quads string. | [
"Converts",
"an",
"RDF",
"dataset",
"to",
"N",
"-",
"Quads",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L5751-L5765 |
43,951 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _parseRdfaApiData | function _parseRdfaApiData(data) {
var dataset = {};
dataset['@default'] = [];
var subjects = data.getSubjects();
for(var si = 0; si < subjects.length; ++si) {
var subject = subjects[si];
if(subject === null) {
continue;
}
// get all related triples
var triples = data.getSubjectTriples(subject);
if(triples === null) {
continue;
}
var predicates = triples.predicates;
for(var predicate in predicates) {
// iterate over objects
var objects = predicates[predicate].objects;
for(var oi = 0; oi < objects.length; ++oi) {
var object = objects[oi];
// create RDF triple
var triple = {};
// add subject
if(subject.indexOf('_:') === 0) {
triple.subject = {type: 'blank node', value: subject};
}
else {
triple.subject = {type: 'IRI', value: subject};
}
// add predicate
if(predicate.indexOf('_:') === 0) {
triple.predicate = {type: 'blank node', value: predicate};
}
else {
triple.predicate = {type: 'IRI', value: predicate};
}
// serialize XML literal
var value = object.value;
if(object.type === RDF_XML_LITERAL) {
// initialize XMLSerializer
if(!XMLSerializer) {
_defineXMLSerializer();
}
var serializer = new XMLSerializer();
value = '';
for(var x = 0; x < object.value.length; x++) {
if(object.value[x].nodeType === Node.ELEMENT_NODE) {
value += serializer.serializeToString(object.value[x]);
}
else if(object.value[x].nodeType === Node.TEXT_NODE) {
value += object.value[x].nodeValue;
}
}
}
// add object
triple.object = {};
// object is an IRI
if(object.type === RDF_OBJECT) {
if(object.value.indexOf('_:') === 0) {
triple.object.type = 'blank node';
}
else {
triple.object.type = 'IRI';
}
}
// literal
else {
triple.object.type = 'literal';
if(object.type === RDF_PLAIN_LITERAL) {
if(object.language) {
triple.object.datatype = RDF_LANGSTRING;
triple.object.language = object.language;
}
else {
triple.object.datatype = XSD_STRING;
}
}
else {
triple.object.datatype = object.type;
}
}
triple.object.value = value;
// add triple to dataset in default graph
dataset['@default'].push(triple);
}
}
}
return dataset;
} | javascript | function _parseRdfaApiData(data) {
var dataset = {};
dataset['@default'] = [];
var subjects = data.getSubjects();
for(var si = 0; si < subjects.length; ++si) {
var subject = subjects[si];
if(subject === null) {
continue;
}
// get all related triples
var triples = data.getSubjectTriples(subject);
if(triples === null) {
continue;
}
var predicates = triples.predicates;
for(var predicate in predicates) {
// iterate over objects
var objects = predicates[predicate].objects;
for(var oi = 0; oi < objects.length; ++oi) {
var object = objects[oi];
// create RDF triple
var triple = {};
// add subject
if(subject.indexOf('_:') === 0) {
triple.subject = {type: 'blank node', value: subject};
}
else {
triple.subject = {type: 'IRI', value: subject};
}
// add predicate
if(predicate.indexOf('_:') === 0) {
triple.predicate = {type: 'blank node', value: predicate};
}
else {
triple.predicate = {type: 'IRI', value: predicate};
}
// serialize XML literal
var value = object.value;
if(object.type === RDF_XML_LITERAL) {
// initialize XMLSerializer
if(!XMLSerializer) {
_defineXMLSerializer();
}
var serializer = new XMLSerializer();
value = '';
for(var x = 0; x < object.value.length; x++) {
if(object.value[x].nodeType === Node.ELEMENT_NODE) {
value += serializer.serializeToString(object.value[x]);
}
else if(object.value[x].nodeType === Node.TEXT_NODE) {
value += object.value[x].nodeValue;
}
}
}
// add object
triple.object = {};
// object is an IRI
if(object.type === RDF_OBJECT) {
if(object.value.indexOf('_:') === 0) {
triple.object.type = 'blank node';
}
else {
triple.object.type = 'IRI';
}
}
// literal
else {
triple.object.type = 'literal';
if(object.type === RDF_PLAIN_LITERAL) {
if(object.language) {
triple.object.datatype = RDF_LANGSTRING;
triple.object.language = object.language;
}
else {
triple.object.datatype = XSD_STRING;
}
}
else {
triple.object.datatype = object.type;
}
}
triple.object.value = value;
// add triple to dataset in default graph
dataset['@default'].push(triple);
}
}
}
return dataset;
} | [
"function",
"_parseRdfaApiData",
"(",
"data",
")",
"{",
"var",
"dataset",
"=",
"{",
"}",
";",
"dataset",
"[",
"'@default'",
"]",
"=",
"[",
"]",
";",
"var",
"subjects",
"=",
"data",
".",
"getSubjects",
"(",
")",
";",
"for",
"(",
"var",
"si",
"=",
"0",
";",
"si",
"<",
"subjects",
".",
"length",
";",
"++",
"si",
")",
"{",
"var",
"subject",
"=",
"subjects",
"[",
"si",
"]",
";",
"if",
"(",
"subject",
"===",
"null",
")",
"{",
"continue",
";",
"}",
"// get all related triples",
"var",
"triples",
"=",
"data",
".",
"getSubjectTriples",
"(",
"subject",
")",
";",
"if",
"(",
"triples",
"===",
"null",
")",
"{",
"continue",
";",
"}",
"var",
"predicates",
"=",
"triples",
".",
"predicates",
";",
"for",
"(",
"var",
"predicate",
"in",
"predicates",
")",
"{",
"// iterate over objects",
"var",
"objects",
"=",
"predicates",
"[",
"predicate",
"]",
".",
"objects",
";",
"for",
"(",
"var",
"oi",
"=",
"0",
";",
"oi",
"<",
"objects",
".",
"length",
";",
"++",
"oi",
")",
"{",
"var",
"object",
"=",
"objects",
"[",
"oi",
"]",
";",
"// create RDF triple",
"var",
"triple",
"=",
"{",
"}",
";",
"// add subject",
"if",
"(",
"subject",
".",
"indexOf",
"(",
"'_:'",
")",
"===",
"0",
")",
"{",
"triple",
".",
"subject",
"=",
"{",
"type",
":",
"'blank node'",
",",
"value",
":",
"subject",
"}",
";",
"}",
"else",
"{",
"triple",
".",
"subject",
"=",
"{",
"type",
":",
"'IRI'",
",",
"value",
":",
"subject",
"}",
";",
"}",
"// add predicate",
"if",
"(",
"predicate",
".",
"indexOf",
"(",
"'_:'",
")",
"===",
"0",
")",
"{",
"triple",
".",
"predicate",
"=",
"{",
"type",
":",
"'blank node'",
",",
"value",
":",
"predicate",
"}",
";",
"}",
"else",
"{",
"triple",
".",
"predicate",
"=",
"{",
"type",
":",
"'IRI'",
",",
"value",
":",
"predicate",
"}",
";",
"}",
"// serialize XML literal",
"var",
"value",
"=",
"object",
".",
"value",
";",
"if",
"(",
"object",
".",
"type",
"===",
"RDF_XML_LITERAL",
")",
"{",
"// initialize XMLSerializer",
"if",
"(",
"!",
"XMLSerializer",
")",
"{",
"_defineXMLSerializer",
"(",
")",
";",
"}",
"var",
"serializer",
"=",
"new",
"XMLSerializer",
"(",
")",
";",
"value",
"=",
"''",
";",
"for",
"(",
"var",
"x",
"=",
"0",
";",
"x",
"<",
"object",
".",
"value",
".",
"length",
";",
"x",
"++",
")",
"{",
"if",
"(",
"object",
".",
"value",
"[",
"x",
"]",
".",
"nodeType",
"===",
"Node",
".",
"ELEMENT_NODE",
")",
"{",
"value",
"+=",
"serializer",
".",
"serializeToString",
"(",
"object",
".",
"value",
"[",
"x",
"]",
")",
";",
"}",
"else",
"if",
"(",
"object",
".",
"value",
"[",
"x",
"]",
".",
"nodeType",
"===",
"Node",
".",
"TEXT_NODE",
")",
"{",
"value",
"+=",
"object",
".",
"value",
"[",
"x",
"]",
".",
"nodeValue",
";",
"}",
"}",
"}",
"// add object",
"triple",
".",
"object",
"=",
"{",
"}",
";",
"// object is an IRI",
"if",
"(",
"object",
".",
"type",
"===",
"RDF_OBJECT",
")",
"{",
"if",
"(",
"object",
".",
"value",
".",
"indexOf",
"(",
"'_:'",
")",
"===",
"0",
")",
"{",
"triple",
".",
"object",
".",
"type",
"=",
"'blank node'",
";",
"}",
"else",
"{",
"triple",
".",
"object",
".",
"type",
"=",
"'IRI'",
";",
"}",
"}",
"// literal",
"else",
"{",
"triple",
".",
"object",
".",
"type",
"=",
"'literal'",
";",
"if",
"(",
"object",
".",
"type",
"===",
"RDF_PLAIN_LITERAL",
")",
"{",
"if",
"(",
"object",
".",
"language",
")",
"{",
"triple",
".",
"object",
".",
"datatype",
"=",
"RDF_LANGSTRING",
";",
"triple",
".",
"object",
".",
"language",
"=",
"object",
".",
"language",
";",
"}",
"else",
"{",
"triple",
".",
"object",
".",
"datatype",
"=",
"XSD_STRING",
";",
"}",
"}",
"else",
"{",
"triple",
".",
"object",
".",
"datatype",
"=",
"object",
".",
"type",
";",
"}",
"}",
"triple",
".",
"object",
".",
"value",
"=",
"value",
";",
"// add triple to dataset in default graph",
"dataset",
"[",
"'@default'",
"]",
".",
"push",
"(",
"triple",
")",
";",
"}",
"}",
"}",
"return",
"dataset",
";",
"}"
]
| Parses the RDF dataset found via the data object from the RDFa API.
@param data the RDFa API data object.
@return the RDF dataset. | [
"Parses",
"the",
"RDF",
"dataset",
"found",
"via",
"the",
"data",
"object",
"from",
"the",
"RDFa",
"API",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L5871-L5969 |
43,952 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _parseAuthority | function _parseAuthority(parsed) {
// parse authority for unparsed relative network-path reference
if(parsed.href.indexOf(':') === -1 && parsed.href.indexOf('//') === 0 &&
!parsed.host) {
// must parse authority from pathname
parsed.pathname = parsed.pathname.substr(2);
var idx = parsed.pathname.indexOf('/');
if(idx === -1) {
parsed.authority = parsed.pathname;
parsed.pathname = '';
}
else {
parsed.authority = parsed.pathname.substr(0, idx);
parsed.pathname = parsed.pathname.substr(idx);
}
}
else {
// construct authority
parsed.authority = parsed.host || '';
if(parsed.auth) {
parsed.authority = parsed.auth + '@' + parsed.authority;
}
}
} | javascript | function _parseAuthority(parsed) {
// parse authority for unparsed relative network-path reference
if(parsed.href.indexOf(':') === -1 && parsed.href.indexOf('//') === 0 &&
!parsed.host) {
// must parse authority from pathname
parsed.pathname = parsed.pathname.substr(2);
var idx = parsed.pathname.indexOf('/');
if(idx === -1) {
parsed.authority = parsed.pathname;
parsed.pathname = '';
}
else {
parsed.authority = parsed.pathname.substr(0, idx);
parsed.pathname = parsed.pathname.substr(idx);
}
}
else {
// construct authority
parsed.authority = parsed.host || '';
if(parsed.auth) {
parsed.authority = parsed.auth + '@' + parsed.authority;
}
}
} | [
"function",
"_parseAuthority",
"(",
"parsed",
")",
"{",
"// parse authority for unparsed relative network-path reference",
"if",
"(",
"parsed",
".",
"href",
".",
"indexOf",
"(",
"':'",
")",
"===",
"-",
"1",
"&&",
"parsed",
".",
"href",
".",
"indexOf",
"(",
"'//'",
")",
"===",
"0",
"&&",
"!",
"parsed",
".",
"host",
")",
"{",
"// must parse authority from pathname",
"parsed",
".",
"pathname",
"=",
"parsed",
".",
"pathname",
".",
"substr",
"(",
"2",
")",
";",
"var",
"idx",
"=",
"parsed",
".",
"pathname",
".",
"indexOf",
"(",
"'/'",
")",
";",
"if",
"(",
"idx",
"===",
"-",
"1",
")",
"{",
"parsed",
".",
"authority",
"=",
"parsed",
".",
"pathname",
";",
"parsed",
".",
"pathname",
"=",
"''",
";",
"}",
"else",
"{",
"parsed",
".",
"authority",
"=",
"parsed",
".",
"pathname",
".",
"substr",
"(",
"0",
",",
"idx",
")",
";",
"parsed",
".",
"pathname",
"=",
"parsed",
".",
"pathname",
".",
"substr",
"(",
"idx",
")",
";",
"}",
"}",
"else",
"{",
"// construct authority",
"parsed",
".",
"authority",
"=",
"parsed",
".",
"host",
"||",
"''",
";",
"if",
"(",
"parsed",
".",
"auth",
")",
"{",
"parsed",
".",
"authority",
"=",
"parsed",
".",
"auth",
"+",
"'@'",
"+",
"parsed",
".",
"authority",
";",
"}",
"}",
"}"
]
| Parses the authority for the pre-parsed given URL.
@param parsed the pre-parsed URL. | [
"Parses",
"the",
"authority",
"for",
"the",
"pre",
"-",
"parsed",
"given",
"URL",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L6535-L6558 |
43,953 | aaaristo/grunt-html-builder | tasks/jsonld/js/jsonld.js | _removeDotSegments | function _removeDotSegments(path, hasAuthority) {
var rval = '';
if(path.indexOf('/') === 0) {
rval = '/';
}
// RFC 3986 5.2.4 (reworked)
var input = path.split('/');
var output = [];
while(input.length > 0) {
if(input[0] === '.' || (input[0] === '' && input.length > 1)) {
input.shift();
continue;
}
if(input[0] === '..') {
input.shift();
if(hasAuthority ||
(output.length > 0 && output[output.length - 1] !== '..')) {
output.pop();
}
// leading relative URL '..'
else {
output.push('..');
}
continue;
}
output.push(input.shift());
}
return rval + output.join('/');
} | javascript | function _removeDotSegments(path, hasAuthority) {
var rval = '';
if(path.indexOf('/') === 0) {
rval = '/';
}
// RFC 3986 5.2.4 (reworked)
var input = path.split('/');
var output = [];
while(input.length > 0) {
if(input[0] === '.' || (input[0] === '' && input.length > 1)) {
input.shift();
continue;
}
if(input[0] === '..') {
input.shift();
if(hasAuthority ||
(output.length > 0 && output[output.length - 1] !== '..')) {
output.pop();
}
// leading relative URL '..'
else {
output.push('..');
}
continue;
}
output.push(input.shift());
}
return rval + output.join('/');
} | [
"function",
"_removeDotSegments",
"(",
"path",
",",
"hasAuthority",
")",
"{",
"var",
"rval",
"=",
"''",
";",
"if",
"(",
"path",
".",
"indexOf",
"(",
"'/'",
")",
"===",
"0",
")",
"{",
"rval",
"=",
"'/'",
";",
"}",
"// RFC 3986 5.2.4 (reworked)",
"var",
"input",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
";",
"var",
"output",
"=",
"[",
"]",
";",
"while",
"(",
"input",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"input",
"[",
"0",
"]",
"===",
"'.'",
"||",
"(",
"input",
"[",
"0",
"]",
"===",
"''",
"&&",
"input",
".",
"length",
">",
"1",
")",
")",
"{",
"input",
".",
"shift",
"(",
")",
";",
"continue",
";",
"}",
"if",
"(",
"input",
"[",
"0",
"]",
"===",
"'..'",
")",
"{",
"input",
".",
"shift",
"(",
")",
";",
"if",
"(",
"hasAuthority",
"||",
"(",
"output",
".",
"length",
">",
"0",
"&&",
"output",
"[",
"output",
".",
"length",
"-",
"1",
"]",
"!==",
"'..'",
")",
")",
"{",
"output",
".",
"pop",
"(",
")",
";",
"}",
"// leading relative URL '..'",
"else",
"{",
"output",
".",
"push",
"(",
"'..'",
")",
";",
"}",
"continue",
";",
"}",
"output",
".",
"push",
"(",
"input",
".",
"shift",
"(",
")",
")",
";",
"}",
"return",
"rval",
"+",
"output",
".",
"join",
"(",
"'/'",
")",
";",
"}"
]
| Removes dot segments from a URL path.
@param path the path to remove dot segments from.
@param hasAuthority true if the URL has an authority, false if not. | [
"Removes",
"dot",
"segments",
"from",
"a",
"URL",
"path",
"."
]
| 9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1 | https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/jsonld/js/jsonld.js#L6566-L6597 |
43,954 | finnfiddle/react-scroll-area | src/index.js | scrollTo | function scrollTo({ container, element, key, options }) {
// if duration is ero then set it to very small so that we do not divide by zero
if (options.duration <= 0) options.duration = 0.1;
// width or height
const sizeKey = SIZE_KEYS[key];
// destination measurement
let to = Math.min(
element[`offset${key}`] + options[`offset${key}`],
(container[`scroll${sizeKey}`] - container[`offset${sizeKey}`])
);
// if destination is greater than avaialable space then limit to avaialable space
if (to > container[`scroll${sizeKey}`]) to = container[`scroll${sizeKey}`];
// if destination is less than zero then make it zero
if (to < 0) to = 0;
// amount that needs to be scrolled
const difference = to - container[`scroll${key}`];
// amount thats needs to be scrolled every tick
const perTick = difference / options.duration * options.tick;
// if we are already scrolled to that point then exit
if (perTick === 0) return;
// scroll the amount for one tick
const doScroll = () => {
setTimeout(() => {
// scroll container
container[`scroll${key}`] = container[`scroll${key}`] + perTick;
// if we have reached desired position then exit
if (
(container[`scroll${key}`] >= to && perTick > 0) ||
(container[`scroll${key}`] <= to && perTick < 0)
) return;
// else repeat after `TICK` interval
doScroll();
}, options.tick);
};
doScroll();
} | javascript | function scrollTo({ container, element, key, options }) {
// if duration is ero then set it to very small so that we do not divide by zero
if (options.duration <= 0) options.duration = 0.1;
// width or height
const sizeKey = SIZE_KEYS[key];
// destination measurement
let to = Math.min(
element[`offset${key}`] + options[`offset${key}`],
(container[`scroll${sizeKey}`] - container[`offset${sizeKey}`])
);
// if destination is greater than avaialable space then limit to avaialable space
if (to > container[`scroll${sizeKey}`]) to = container[`scroll${sizeKey}`];
// if destination is less than zero then make it zero
if (to < 0) to = 0;
// amount that needs to be scrolled
const difference = to - container[`scroll${key}`];
// amount thats needs to be scrolled every tick
const perTick = difference / options.duration * options.tick;
// if we are already scrolled to that point then exit
if (perTick === 0) return;
// scroll the amount for one tick
const doScroll = () => {
setTimeout(() => {
// scroll container
container[`scroll${key}`] = container[`scroll${key}`] + perTick;
// if we have reached desired position then exit
if (
(container[`scroll${key}`] >= to && perTick > 0) ||
(container[`scroll${key}`] <= to && perTick < 0)
) return;
// else repeat after `TICK` interval
doScroll();
}, options.tick);
};
doScroll();
} | [
"function",
"scrollTo",
"(",
"{",
"container",
",",
"element",
",",
"key",
",",
"options",
"}",
")",
"{",
"// if duration is ero then set it to very small so that we do not divide by zero",
"if",
"(",
"options",
".",
"duration",
"<=",
"0",
")",
"options",
".",
"duration",
"=",
"0.1",
";",
"// width or height",
"const",
"sizeKey",
"=",
"SIZE_KEYS",
"[",
"key",
"]",
";",
"// destination measurement",
"let",
"to",
"=",
"Math",
".",
"min",
"(",
"element",
"[",
"`",
"${",
"key",
"}",
"`",
"]",
"+",
"options",
"[",
"`",
"${",
"key",
"}",
"`",
"]",
",",
"(",
"container",
"[",
"`",
"${",
"sizeKey",
"}",
"`",
"]",
"-",
"container",
"[",
"`",
"${",
"sizeKey",
"}",
"`",
"]",
")",
")",
";",
"// if destination is greater than avaialable space then limit to avaialable space",
"if",
"(",
"to",
">",
"container",
"[",
"`",
"${",
"sizeKey",
"}",
"`",
"]",
")",
"to",
"=",
"container",
"[",
"`",
"${",
"sizeKey",
"}",
"`",
"]",
";",
"// if destination is less than zero then make it zero",
"if",
"(",
"to",
"<",
"0",
")",
"to",
"=",
"0",
";",
"// amount that needs to be scrolled",
"const",
"difference",
"=",
"to",
"-",
"container",
"[",
"`",
"${",
"key",
"}",
"`",
"]",
";",
"// amount thats needs to be scrolled every tick",
"const",
"perTick",
"=",
"difference",
"/",
"options",
".",
"duration",
"*",
"options",
".",
"tick",
";",
"// if we are already scrolled to that point then exit",
"if",
"(",
"perTick",
"===",
"0",
")",
"return",
";",
"// scroll the amount for one tick",
"const",
"doScroll",
"=",
"(",
")",
"=>",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"// scroll container",
"container",
"[",
"`",
"${",
"key",
"}",
"`",
"]",
"=",
"container",
"[",
"`",
"${",
"key",
"}",
"`",
"]",
"+",
"perTick",
";",
"// if we have reached desired position then exit",
"if",
"(",
"(",
"container",
"[",
"`",
"${",
"key",
"}",
"`",
"]",
">=",
"to",
"&&",
"perTick",
">",
"0",
")",
"||",
"(",
"container",
"[",
"`",
"${",
"key",
"}",
"`",
"]",
"<=",
"to",
"&&",
"perTick",
"<",
"0",
")",
")",
"return",
";",
"// else repeat after `TICK` interval",
"doScroll",
"(",
")",
";",
"}",
",",
"options",
".",
"tick",
")",
";",
"}",
";",
"doScroll",
"(",
")",
";",
"}"
]
| function that does the scrolling | [
"function",
"that",
"does",
"the",
"scrolling"
]
| a4622c3c6451ee9d7d9194378f1e357bea605bdf | https://github.com/finnfiddle/react-scroll-area/blob/a4622c3c6451ee9d7d9194378f1e357bea605bdf/src/index.js#L21-L59 |
43,955 | opendxl/opendxl-client-javascript | sample/basic/service-example.js | function (request) {
// Extract information from request. The toString() call converts the
// payload from a binary Buffer into a string, decoded using UTF-8
// character encoding.
console.log('Service received request payload: ' +
request.payload.toString())
// Create the response message
var response = new dxl.Response(request)
// Populate the response payload
response.payload = 'pong'
// Send the response
client.sendResponse(response)
} | javascript | function (request) {
// Extract information from request. The toString() call converts the
// payload from a binary Buffer into a string, decoded using UTF-8
// character encoding.
console.log('Service received request payload: ' +
request.payload.toString())
// Create the response message
var response = new dxl.Response(request)
// Populate the response payload
response.payload = 'pong'
// Send the response
client.sendResponse(response)
} | [
"function",
"(",
"request",
")",
"{",
"// Extract information from request. The toString() call converts the",
"// payload from a binary Buffer into a string, decoded using UTF-8",
"// character encoding.",
"console",
".",
"log",
"(",
"'Service received request payload: '",
"+",
"request",
".",
"payload",
".",
"toString",
"(",
")",
")",
"// Create the response message",
"var",
"response",
"=",
"new",
"dxl",
".",
"Response",
"(",
"request",
")",
"// Populate the response payload",
"response",
".",
"payload",
"=",
"'pong'",
"// Send the response",
"client",
".",
"sendResponse",
"(",
"response",
")",
"}"
]
| Handle the receipt of an incoming service request | [
"Handle",
"the",
"receipt",
"of",
"an",
"incoming",
"service",
"request"
]
| eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997 | https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/sample/basic/service-example.js#L27-L39 |
|
43,956 | opendxl/opendxl-client-javascript | sample/basic/service-example.js | function (error, response) {
// Destroy the client - frees up resources so that the application
// stops running
client.destroy()
// Display the contents of an error, if one occurred
if (error) {
console.log('Request error: ' + error.message)
// The 'code' property, if set, typically has a string
// representation of the error code.
if (error.code) {
console.log('Request error code: ' + error.code)
// If no string representation is available for the error code
// but the error is a DXL 'RequestError', a numeric error
// code should be available in the
// 'dxlErrorResponse.errorCode' property.
} else if (error.dxlErrorResponse) {
console.log('Request error code: ' +
error.dxlErrorResponse.errorCode)
}
// No error occurred, so extract information from the response. The
// toString() call converts the payload from a binary Buffer into a
// string, decoded using UTF-8 character encoding.
} else {
console.log('Client received response payload: ' +
response.payload.toString())
}
} | javascript | function (error, response) {
// Destroy the client - frees up resources so that the application
// stops running
client.destroy()
// Display the contents of an error, if one occurred
if (error) {
console.log('Request error: ' + error.message)
// The 'code' property, if set, typically has a string
// representation of the error code.
if (error.code) {
console.log('Request error code: ' + error.code)
// If no string representation is available for the error code
// but the error is a DXL 'RequestError', a numeric error
// code should be available in the
// 'dxlErrorResponse.errorCode' property.
} else if (error.dxlErrorResponse) {
console.log('Request error code: ' +
error.dxlErrorResponse.errorCode)
}
// No error occurred, so extract information from the response. The
// toString() call converts the payload from a binary Buffer into a
// string, decoded using UTF-8 character encoding.
} else {
console.log('Client received response payload: ' +
response.payload.toString())
}
} | [
"function",
"(",
"error",
",",
"response",
")",
"{",
"// Destroy the client - frees up resources so that the application",
"// stops running",
"client",
".",
"destroy",
"(",
")",
"// Display the contents of an error, if one occurred",
"if",
"(",
"error",
")",
"{",
"console",
".",
"log",
"(",
"'Request error: '",
"+",
"error",
".",
"message",
")",
"// The 'code' property, if set, typically has a string",
"// representation of the error code.",
"if",
"(",
"error",
".",
"code",
")",
"{",
"console",
".",
"log",
"(",
"'Request error code: '",
"+",
"error",
".",
"code",
")",
"// If no string representation is available for the error code",
"// but the error is a DXL 'RequestError', a numeric error",
"// code should be available in the",
"// 'dxlErrorResponse.errorCode' property.",
"}",
"else",
"if",
"(",
"error",
".",
"dxlErrorResponse",
")",
"{",
"console",
".",
"log",
"(",
"'Request error code: '",
"+",
"error",
".",
"dxlErrorResponse",
".",
"errorCode",
")",
"}",
"// No error occurred, so extract information from the response. The",
"// toString() call converts the payload from a binary Buffer into a",
"// string, decoded using UTF-8 character encoding.",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'Client received response payload: '",
"+",
"response",
".",
"payload",
".",
"toString",
"(",
")",
")",
"}",
"}"
]
| Handle the response to the request | [
"Handle",
"the",
"response",
"to",
"the",
"request"
]
| eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997 | https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/sample/basic/service-example.js#L58-L84 |
|
43,957 | ckknight/escort | lib/escort.js | function (prototype, properties) {
var object = Object.create(prototype);
Object.keys(properties).forEach(function (key) {
object[key] = properties[key];
});
return object;
} | javascript | function (prototype, properties) {
var object = Object.create(prototype);
Object.keys(properties).forEach(function (key) {
object[key] = properties[key];
});
return object;
} | [
"function",
"(",
"prototype",
",",
"properties",
")",
"{",
"var",
"object",
"=",
"Object",
".",
"create",
"(",
"prototype",
")",
";",
"Object",
".",
"keys",
"(",
"properties",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"object",
"[",
"key",
"]",
"=",
"properties",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"object",
";",
"}"
]
| a simple wrapper around Object.create to easily make new objects without providing property descriptors.
@param {Object} prototype The prototype to inherit from
@param {Object} properties A map of properties
@api private | [
"a",
"simple",
"wrapper",
"around",
"Object",
".",
"create",
"to",
"easily",
"make",
"new",
"objects",
"without",
"providing",
"property",
"descriptors",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L76-L82 |
|
43,958 | ckknight/escort | lib/escort.js | function (descriptor) {
var result = {};
for (var key in descriptor) {
if (Object.prototype.hasOwnProperty.call(descriptor, key)) {
var keys = key.split(',');
for (var i = 0, len = keys.length; i < len; i += 1) {
var method = keys[i];
if (!ACCEPTABLE_METHOD_SET[method]) {
throw new Error("Unknown descriptor method " + method);
}
if (Object.prototype.hasOwnProperty.call(result, method)) {
throw new Error("Already specified descriptor method " + method);
}
result[method] = descriptor[key];
}
}
}
if (!result.options) {
result.options = createOptionsHandler(result);
}
return freeze(result);
} | javascript | function (descriptor) {
var result = {};
for (var key in descriptor) {
if (Object.prototype.hasOwnProperty.call(descriptor, key)) {
var keys = key.split(',');
for (var i = 0, len = keys.length; i < len; i += 1) {
var method = keys[i];
if (!ACCEPTABLE_METHOD_SET[method]) {
throw new Error("Unknown descriptor method " + method);
}
if (Object.prototype.hasOwnProperty.call(result, method)) {
throw new Error("Already specified descriptor method " + method);
}
result[method] = descriptor[key];
}
}
}
if (!result.options) {
result.options = createOptionsHandler(result);
}
return freeze(result);
} | [
"function",
"(",
"descriptor",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"key",
"in",
"descriptor",
")",
"{",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"descriptor",
",",
"key",
")",
")",
"{",
"var",
"keys",
"=",
"key",
".",
"split",
"(",
"','",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"keys",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"var",
"method",
"=",
"keys",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"ACCEPTABLE_METHOD_SET",
"[",
"method",
"]",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Unknown descriptor method \"",
"+",
"method",
")",
";",
"}",
"if",
"(",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"result",
",",
"method",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Already specified descriptor method \"",
"+",
"method",
")",
";",
"}",
"result",
"[",
"method",
"]",
"=",
"descriptor",
"[",
"key",
"]",
";",
"}",
"}",
"}",
"if",
"(",
"!",
"result",
".",
"options",
")",
"{",
"result",
".",
"options",
"=",
"createOptionsHandler",
"(",
"result",
")",
";",
"}",
"return",
"freeze",
"(",
"result",
")",
";",
"}"
]
| Verify the validity of the provided descriptor and return a sanitized version.
This will add an options handler if none is provided.
@param {Object} descriptor A map of methods to their associated callbacks
@return {Object} A map of methods to their associated callbacks
@api private
@example descriptor = sanitizeDescriptor(descriptor); | [
"Verify",
"the",
"validity",
"of",
"the",
"provided",
"descriptor",
"and",
"return",
"a",
"sanitized",
"version",
".",
"This",
"will",
"add",
"an",
"options",
"handler",
"if",
"none",
"is",
"provided",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L141-L162 |
|
43,959 | ckknight/escort | lib/escort.js | function (route) {
if (route === "/") {
return "root";
}
if (route.indexOf("{") >= 0) {
throw new Error("Unable to guess route name for route " + route);
}
var result = route
.replace(SLASH_PREFIX_REGEX, "")
.replace(GUESS_ROUTE_NAME_UNEXPECTED_CHARACTER_REGEX, "")
.replace(PUNCTUATION_LETTER_REGEX, function (full, character) {
return character.toUpperCase();
});
if (!result) {
throw new Error("Unable to guess route name for route " + route);
}
return result;
} | javascript | function (route) {
if (route === "/") {
return "root";
}
if (route.indexOf("{") >= 0) {
throw new Error("Unable to guess route name for route " + route);
}
var result = route
.replace(SLASH_PREFIX_REGEX, "")
.replace(GUESS_ROUTE_NAME_UNEXPECTED_CHARACTER_REGEX, "")
.replace(PUNCTUATION_LETTER_REGEX, function (full, character) {
return character.toUpperCase();
});
if (!result) {
throw new Error("Unable to guess route name for route " + route);
}
return result;
} | [
"function",
"(",
"route",
")",
"{",
"if",
"(",
"route",
"===",
"\"/\"",
")",
"{",
"return",
"\"root\"",
";",
"}",
"if",
"(",
"route",
".",
"indexOf",
"(",
"\"{\"",
")",
">=",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Unable to guess route name for route \"",
"+",
"route",
")",
";",
"}",
"var",
"result",
"=",
"route",
".",
"replace",
"(",
"SLASH_PREFIX_REGEX",
",",
"\"\"",
")",
".",
"replace",
"(",
"GUESS_ROUTE_NAME_UNEXPECTED_CHARACTER_REGEX",
",",
"\"\"",
")",
".",
"replace",
"(",
"PUNCTUATION_LETTER_REGEX",
",",
"function",
"(",
"full",
",",
"character",
")",
"{",
"return",
"character",
".",
"toUpperCase",
"(",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"result",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Unable to guess route name for route \"",
"+",
"route",
")",
";",
"}",
"return",
"result",
";",
"}"
]
| Guess a route name for the given route. This will strip out any characters and give a best-guess.
@param {String} route The provided route that it uses to determine a good name for it.
@return {String} A name for the route.
@throws {Error} When unable to guess a route name.
@api private
@example guessRouteName("/") === "root"
@example guessRouteName("/pages") === "pages"
@example guessRouteName("/pages/view") === "pagesView"
@example guessRouteName("/pages/{name}") // Error | [
"Guess",
"a",
"route",
"name",
"for",
"the",
"given",
"route",
".",
"This",
"will",
"strip",
"out",
"any",
"characters",
"and",
"give",
"a",
"best",
"-",
"guess",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L213-L231 |
|
43,960 | ckknight/escort | lib/escort.js | function (text, value) {
var valueLength = value.length;
if (text.length < valueLength) {
return false;
}
return text.substring(0, valueLength) === value;
} | javascript | function (text, value) {
var valueLength = value.length;
if (text.length < valueLength) {
return false;
}
return text.substring(0, valueLength) === value;
} | [
"function",
"(",
"text",
",",
"value",
")",
"{",
"var",
"valueLength",
"=",
"value",
".",
"length",
";",
"if",
"(",
"text",
".",
"length",
"<",
"valueLength",
")",
"{",
"return",
"false",
";",
"}",
"return",
"text",
".",
"substring",
"(",
"0",
",",
"valueLength",
")",
"===",
"value",
";",
"}"
]
| Determine whether text starts with value.
@param {String} text the text to check if value is the beginning part of the string.
@param {String} value the potential value of the start of the string.
@return {Boolean}
@api private
@example startsWith("hey there", "hey") === true
@example startsWith("hey there", "hello") === true | [
"Determine",
"whether",
"text",
"starts",
"with",
"value",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L244-L251 |
|
43,961 | ckknight/escort | lib/escort.js | function (array, c, depth) {
var start = array.length - (array.length / Math.pow(2, depth));
for (var i = start, len = array.length; i < len; i += 1) {
array[i] += c;
}
} | javascript | function (array, c, depth) {
var start = array.length - (array.length / Math.pow(2, depth));
for (var i = start, len = array.length; i < len; i += 1) {
array[i] += c;
}
} | [
"function",
"(",
"array",
",",
"c",
",",
"depth",
")",
"{",
"var",
"start",
"=",
"array",
".",
"length",
"-",
"(",
"array",
".",
"length",
"/",
"Math",
".",
"pow",
"(",
"2",
",",
"depth",
")",
")",
";",
"for",
"(",
"var",
"i",
"=",
"start",
",",
"len",
"=",
"array",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"array",
"[",
"i",
"]",
"+=",
"c",
";",
"}",
"}"
]
| Add a char to certain elements of an array.
@param {Array} array An array of strings
@param {String} c A string to add to each string
@param {Number} depth The current binary tree depth to add to.
@api private | [
"Add",
"a",
"char",
"to",
"certain",
"elements",
"of",
"an",
"array",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L261-L266 |
|
43,962 | ckknight/escort | lib/escort.js | function (array) {
var set = {};
var result = [];
for (var i = 0, len = array.length; i < len; i += 1) {
var item = array[i];
if (!Object.prototype.hasOwnProperty.call(set, item)) {
set[item] = true;
result.push(item);
}
}
return result;
} | javascript | function (array) {
var set = {};
var result = [];
for (var i = 0, len = array.length; i < len; i += 1) {
var item = array[i];
if (!Object.prototype.hasOwnProperty.call(set, item)) {
set[item] = true;
result.push(item);
}
}
return result;
} | [
"function",
"(",
"array",
")",
"{",
"var",
"set",
"=",
"{",
"}",
";",
"var",
"result",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"array",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"var",
"item",
"=",
"array",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"Object",
".",
"prototype",
".",
"hasOwnProperty",
".",
"call",
"(",
"set",
",",
"item",
")",
")",
"{",
"set",
"[",
"item",
"]",
"=",
"true",
";",
"result",
".",
"push",
"(",
"item",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
]
| Return an array with only distinct elements.
This assumes that the elements of an array have their uniqueness determined by their String value.
@param {Array} array The array to iterate over.
@return {Array} An array with distinct elements.
@api private
@example distinct(["a", "b", "c", "a", "a", "c"]) => ["a", "b", "c"] | [
"Return",
"an",
"array",
"with",
"only",
"distinct",
"elements",
".",
"This",
"assumes",
"that",
"the",
"elements",
"of",
"an",
"array",
"have",
"their",
"uniqueness",
"determined",
"by",
"their",
"String",
"value",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L278-L291 |
|
43,963 | ckknight/escort | lib/escort.js | function (routes) {
if (!Array.isArray(routes)) {
routes = [routes];
}
var result = [];
routes.forEach(function (route) {
if (route.indexOf('[') === -1) {
result.push(route);
return;
}
var immediateResult = [''];
var depth = 0;
var inLiteral = 0;
for (var i = 0, len = route.length; i < len; i += 1) {
var c = route[i];
if (!inLiteral) {
if (c === '[') {
depth += 1;
for (var j = 0, lenJ = immediateResult.length; j < lenJ; j += 1) {
immediateResult.push(immediateResult[j]);
}
} else if (c === ']') {
depth -= 1;
} else {
if (c === '{') {
inLiteral += 1;
} else if (c === '}') {
throw new Error("Found unexpected } in route: " + route);
}
addCharToArray(immediateResult, c, depth);
}
} else {
if (c === '{') {
inLiteral += 1;
} else if (c === '}') {
inLiteral -= 1;
}
addCharToArray(immediateResult, c, depth);
}
}
for (i = 0, len = immediateResult.length; i < len; i += 1) {
result.push(immediateResult[i]);
}
});
return distinct(result);
} | javascript | function (routes) {
if (!Array.isArray(routes)) {
routes = [routes];
}
var result = [];
routes.forEach(function (route) {
if (route.indexOf('[') === -1) {
result.push(route);
return;
}
var immediateResult = [''];
var depth = 0;
var inLiteral = 0;
for (var i = 0, len = route.length; i < len; i += 1) {
var c = route[i];
if (!inLiteral) {
if (c === '[') {
depth += 1;
for (var j = 0, lenJ = immediateResult.length; j < lenJ; j += 1) {
immediateResult.push(immediateResult[j]);
}
} else if (c === ']') {
depth -= 1;
} else {
if (c === '{') {
inLiteral += 1;
} else if (c === '}') {
throw new Error("Found unexpected } in route: " + route);
}
addCharToArray(immediateResult, c, depth);
}
} else {
if (c === '{') {
inLiteral += 1;
} else if (c === '}') {
inLiteral -= 1;
}
addCharToArray(immediateResult, c, depth);
}
}
for (i = 0, len = immediateResult.length; i < len; i += 1) {
result.push(immediateResult[i]);
}
});
return distinct(result);
} | [
"function",
"(",
"routes",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"routes",
")",
")",
"{",
"routes",
"=",
"[",
"routes",
"]",
";",
"}",
"var",
"result",
"=",
"[",
"]",
";",
"routes",
".",
"forEach",
"(",
"function",
"(",
"route",
")",
"{",
"if",
"(",
"route",
".",
"indexOf",
"(",
"'['",
")",
"===",
"-",
"1",
")",
"{",
"result",
".",
"push",
"(",
"route",
")",
";",
"return",
";",
"}",
"var",
"immediateResult",
"=",
"[",
"''",
"]",
";",
"var",
"depth",
"=",
"0",
";",
"var",
"inLiteral",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"route",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"var",
"c",
"=",
"route",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"inLiteral",
")",
"{",
"if",
"(",
"c",
"===",
"'['",
")",
"{",
"depth",
"+=",
"1",
";",
"for",
"(",
"var",
"j",
"=",
"0",
",",
"lenJ",
"=",
"immediateResult",
".",
"length",
";",
"j",
"<",
"lenJ",
";",
"j",
"+=",
"1",
")",
"{",
"immediateResult",
".",
"push",
"(",
"immediateResult",
"[",
"j",
"]",
")",
";",
"}",
"}",
"else",
"if",
"(",
"c",
"===",
"']'",
")",
"{",
"depth",
"-=",
"1",
";",
"}",
"else",
"{",
"if",
"(",
"c",
"===",
"'{'",
")",
"{",
"inLiteral",
"+=",
"1",
";",
"}",
"else",
"if",
"(",
"c",
"===",
"'}'",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Found unexpected } in route: \"",
"+",
"route",
")",
";",
"}",
"addCharToArray",
"(",
"immediateResult",
",",
"c",
",",
"depth",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"c",
"===",
"'{'",
")",
"{",
"inLiteral",
"+=",
"1",
";",
"}",
"else",
"if",
"(",
"c",
"===",
"'}'",
")",
"{",
"inLiteral",
"-=",
"1",
";",
"}",
"addCharToArray",
"(",
"immediateResult",
",",
"c",
",",
"depth",
")",
";",
"}",
"}",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"immediateResult",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"result",
".",
"push",
"(",
"immediateResult",
"[",
"i",
"]",
")",
";",
"}",
"}",
")",
";",
"return",
"distinct",
"(",
"result",
")",
";",
"}"
]
| Parse all potential optional routes out of the provided String or Array.
@param {Array} routes an array of routes, or a String which is a single route.
@return {Array} the parsed-out array of optional routes.
@api private
@example parseOptionalRoutes("/same") => ["/same"]
@example parseOptionalRoutes("/[optional]") => ["/", "/optional"]
@example parseOptionalRoutes("/data[.{format}]") => ["/data", "/data.{format}"]
@example parseOptionalRoutes("/multiple[/optional][/parameters]") => ["/multiple", "/multiple/optional", "/multiple/parameters", "/multiple/optional/parameters"]
@example parseOptionalRoutes("/deep[/optional[/parameters]]") => ["/deep", "/deep/optional", "/deep/optional/parameters"]
@example parseOptionalRoutes(["/data[.{format}]", "/data/page/{num:int}[.{format}]"]) => ["/data", "/data.{format}", "/data/page/{num:int}", "/data/page/{num:int}.{format}"]
@example parseOptionalRoutes("/{name:custom(['a', 'b', 'c'])}") => ["/{name:custom(['a', 'b', 'c'])}"] | [
"Parse",
"all",
"potential",
"optional",
"routes",
"out",
"of",
"the",
"provided",
"String",
"or",
"Array",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L308-L360 |
|
43,964 | ckknight/escort | lib/escort.js | function (bind, prefix) {
return function (path, callback) {
var prefixedPath = prefix + path;
validatePath(prefixedPath);
var innerMethods = spawn(escort.prototype, {
bind: function (routeName, route, descriptor) {
if (arguments.length === 2) {
descriptor = route;
route = routeName;
if (Array.isArray(route)) {
routeName = guessRouteName(prefixedPath + route[0]);
} else {
routeName = guessRouteName(prefixedPath + route);
}
}
return bind(routeName, route, descriptor, prefixedPath);
},
submount: makeSubmountFunction(bind, prefixedPath)
});
callback.call(innerMethods, innerMethods);
};
} | javascript | function (bind, prefix) {
return function (path, callback) {
var prefixedPath = prefix + path;
validatePath(prefixedPath);
var innerMethods = spawn(escort.prototype, {
bind: function (routeName, route, descriptor) {
if (arguments.length === 2) {
descriptor = route;
route = routeName;
if (Array.isArray(route)) {
routeName = guessRouteName(prefixedPath + route[0]);
} else {
routeName = guessRouteName(prefixedPath + route);
}
}
return bind(routeName, route, descriptor, prefixedPath);
},
submount: makeSubmountFunction(bind, prefixedPath)
});
callback.call(innerMethods, innerMethods);
};
} | [
"function",
"(",
"bind",
",",
"prefix",
")",
"{",
"return",
"function",
"(",
"path",
",",
"callback",
")",
"{",
"var",
"prefixedPath",
"=",
"prefix",
"+",
"path",
";",
"validatePath",
"(",
"prefixedPath",
")",
";",
"var",
"innerMethods",
"=",
"spawn",
"(",
"escort",
".",
"prototype",
",",
"{",
"bind",
":",
"function",
"(",
"routeName",
",",
"route",
",",
"descriptor",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
")",
"{",
"descriptor",
"=",
"route",
";",
"route",
"=",
"routeName",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"route",
")",
")",
"{",
"routeName",
"=",
"guessRouteName",
"(",
"prefixedPath",
"+",
"route",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"routeName",
"=",
"guessRouteName",
"(",
"prefixedPath",
"+",
"route",
")",
";",
"}",
"}",
"return",
"bind",
"(",
"routeName",
",",
"route",
",",
"descriptor",
",",
"prefixedPath",
")",
";",
"}",
",",
"submount",
":",
"makeSubmountFunction",
"(",
"bind",
",",
"prefixedPath",
")",
"}",
")",
";",
"callback",
".",
"call",
"(",
"innerMethods",
",",
"innerMethods",
")",
";",
"}",
";",
"}"
]
| Make the submount function for the escort Object.
@param {Function} bind the bind function for the current escort Object.
@param {String} prefix the route prefix for the submount.
@api private
@example makeSubmountFunction("/forums") | [
"Make",
"the",
"submount",
"function",
"for",
"the",
"escort",
"Object",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L399-L421 |
|
43,965 | ckknight/escort | lib/escort.js | function (req, res) {
return function (err) {
if (err) {
res.writeHead(500);
res.end(err.toString());
} else {
res.writeHead(404);
res.end();
}
};
} | javascript | function (req, res) {
return function (err) {
if (err) {
res.writeHead(500);
res.end(err.toString());
} else {
res.writeHead(404);
res.end();
}
};
} | [
"function",
"(",
"req",
",",
"res",
")",
"{",
"return",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"res",
".",
"writeHead",
"(",
"500",
")",
";",
"res",
".",
"end",
"(",
"err",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"{",
"res",
".",
"writeHead",
"(",
"404",
")",
";",
"res",
".",
"end",
"(",
")",
";",
"}",
"}",
";",
"}"
]
| A handler for calling the next middleware module if for some reason one isn't provided.
@param {Error} err An error, if it occurred.
@api private | [
"A",
"handler",
"for",
"calling",
"the",
"next",
"middleware",
"module",
"if",
"for",
"some",
"reason",
"one",
"isn",
"t",
"provided",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L442-L452 |
|
43,966 | ckknight/escort | lib/escort.js | function (object) {
ACCEPTABLE_METHODS.forEach(function (method) {
/**
* Bind the provided route with a specific method to the callback provided.
* Since you cannot specify a route more than once, it is required to use bind to provide multiple methods.
*
* @param {String} routeName The name of the route. Should be a JavaScript identifier. Optional.
* @param {String} route The URL for the route.
* @param {Function} callback The callback to be called when the route is accessed.
*
* @throws Error the routeName is already specified
* @throws Error the route is already specified
* @throws Error the route does not start with "/"
* @throws Error an unknown route converter was specified
*
* @api public
*
* @example routes.get("/", function(request, response) {
* response.end("GET /");
* });
* @example routes.post("item", "/{name}", function(request, response, params) {
* response.end("GET /" + params.name);
* });
*/
object[method] = function (routeName, route, callback) {
if (arguments.length === 2) {
callback = route;
route = routeName;
routeName = null;
}
var descriptor = {};
descriptor[method] = callback;
if (arguments.length === 2) {
return this.bind(route, descriptor);
} else {
return this.bind(routeName, route, descriptor);
}
};
});
object.del = object.delete;
} | javascript | function (object) {
ACCEPTABLE_METHODS.forEach(function (method) {
/**
* Bind the provided route with a specific method to the callback provided.
* Since you cannot specify a route more than once, it is required to use bind to provide multiple methods.
*
* @param {String} routeName The name of the route. Should be a JavaScript identifier. Optional.
* @param {String} route The URL for the route.
* @param {Function} callback The callback to be called when the route is accessed.
*
* @throws Error the routeName is already specified
* @throws Error the route is already specified
* @throws Error the route does not start with "/"
* @throws Error an unknown route converter was specified
*
* @api public
*
* @example routes.get("/", function(request, response) {
* response.end("GET /");
* });
* @example routes.post("item", "/{name}", function(request, response, params) {
* response.end("GET /" + params.name);
* });
*/
object[method] = function (routeName, route, callback) {
if (arguments.length === 2) {
callback = route;
route = routeName;
routeName = null;
}
var descriptor = {};
descriptor[method] = callback;
if (arguments.length === 2) {
return this.bind(route, descriptor);
} else {
return this.bind(routeName, route, descriptor);
}
};
});
object.del = object.delete;
} | [
"function",
"(",
"object",
")",
"{",
"ACCEPTABLE_METHODS",
".",
"forEach",
"(",
"function",
"(",
"method",
")",
"{",
"/**\n * Bind the provided route with a specific method to the callback provided.\n * Since you cannot specify a route more than once, it is required to use bind to provide multiple methods.\n *\n * @param {String} routeName The name of the route. Should be a JavaScript identifier. Optional.\n * @param {String} route The URL for the route.\n * @param {Function} callback The callback to be called when the route is accessed.\n *\n * @throws Error the routeName is already specified\n * @throws Error the route is already specified\n * @throws Error the route does not start with \"/\"\n * @throws Error an unknown route converter was specified\n *\n * @api public\n * \n * @example routes.get(\"/\", function(request, response) {\n * response.end(\"GET /\");\n * });\n * @example routes.post(\"item\", \"/{name}\", function(request, response, params) {\n * response.end(\"GET /\" + params.name);\n * });\n */",
"object",
"[",
"method",
"]",
"=",
"function",
"(",
"routeName",
",",
"route",
",",
"callback",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
")",
"{",
"callback",
"=",
"route",
";",
"route",
"=",
"routeName",
";",
"routeName",
"=",
"null",
";",
"}",
"var",
"descriptor",
"=",
"{",
"}",
";",
"descriptor",
"[",
"method",
"]",
"=",
"callback",
";",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
")",
"{",
"return",
"this",
".",
"bind",
"(",
"route",
",",
"descriptor",
")",
";",
"}",
"else",
"{",
"return",
"this",
".",
"bind",
"(",
"routeName",
",",
"route",
",",
"descriptor",
")",
";",
"}",
"}",
";",
"}",
")",
";",
"object",
".",
"del",
"=",
"object",
".",
"delete",
";",
"}"
]
| Attach all the helper HTTP and WebDAV methods as helper functions which will
ultimately call bind on the provided object.
@param {Object} object the Object to attach the methods to.
@api private | [
"Attach",
"all",
"the",
"helper",
"HTTP",
"and",
"WebDAV",
"methods",
"as",
"helper",
"functions",
"which",
"will",
"ultimately",
"call",
"bind",
"on",
"the",
"provided",
"object",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L461-L501 |
|
43,967 | ckknight/escort | lib/escort.js | function (value, length) {
value = String(value);
var numMissing = length - value.length;
var prefix = "";
while (numMissing > 0) {
prefix += "0";
numMissing -= 1;
}
return prefix + value;
} | javascript | function (value, length) {
value = String(value);
var numMissing = length - value.length;
var prefix = "";
while (numMissing > 0) {
prefix += "0";
numMissing -= 1;
}
return prefix + value;
} | [
"function",
"(",
"value",
",",
"length",
")",
"{",
"value",
"=",
"String",
"(",
"value",
")",
";",
"var",
"numMissing",
"=",
"length",
"-",
"value",
".",
"length",
";",
"var",
"prefix",
"=",
"\"\"",
";",
"while",
"(",
"numMissing",
">",
"0",
")",
"{",
"prefix",
"+=",
"\"0\"",
";",
"numMissing",
"-=",
"1",
";",
"}",
"return",
"prefix",
"+",
"value",
";",
"}"
]
| Pad a value by prepending zeroes until it reaches a specified length.
@param {String} value the current string or number.
@param {Number} length the size wanted for the value.
@return {String} a string of at least the provided length.
@api private
@example zeroPad(50, 4) == "0050"
@example zeroPad("123", 4) == "0123" | [
"Pad",
"a",
"value",
"by",
"prepending",
"zeroes",
"until",
"it",
"reaches",
"a",
"specified",
"length",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L1216-L1225 |
|
43,968 | ckknight/escort | lib/escort.js | function (args) {
if (!args) {
args = {};
}
var fixedDigits = args.fixedDigits;
var min = args.min;
var max = args.max;
if (min === undefined) {
min = null;
}
if (max === undefined) {
max = null;
}
return spawn(IntegerConverter.prototype, {
_fixedDigits: fixedDigits,
_min: min,
_max: max
});
} | javascript | function (args) {
if (!args) {
args = {};
}
var fixedDigits = args.fixedDigits;
var min = args.min;
var max = args.max;
if (min === undefined) {
min = null;
}
if (max === undefined) {
max = null;
}
return spawn(IntegerConverter.prototype, {
_fixedDigits: fixedDigits,
_min: min,
_max: max
});
} | [
"function",
"(",
"args",
")",
"{",
"if",
"(",
"!",
"args",
")",
"{",
"args",
"=",
"{",
"}",
";",
"}",
"var",
"fixedDigits",
"=",
"args",
".",
"fixedDigits",
";",
"var",
"min",
"=",
"args",
".",
"min",
";",
"var",
"max",
"=",
"args",
".",
"max",
";",
"if",
"(",
"min",
"===",
"undefined",
")",
"{",
"min",
"=",
"null",
";",
"}",
"if",
"(",
"max",
"===",
"undefined",
")",
"{",
"max",
"=",
"null",
";",
"}",
"return",
"spawn",
"(",
"IntegerConverter",
".",
"prototype",
",",
"{",
"_fixedDigits",
":",
"fixedDigits",
",",
"_min",
":",
"min",
",",
"_max",
":",
"max",
"}",
")",
";",
"}"
]
| A converter that accepts a numeric string.
This does not support negative values.
@example routes.get("/users/{id:int}", function(req, res, params) { })
@example routes.get("/archive/{year:int({fixedDigits: 4})}", function(req, res, params) { })
@example routes.get("/users/{id:int({min: 1})}", function(req, res) { })
@param {Object} args An options Object that can contain "min", "max", and "fixedDigits" | [
"A",
"converter",
"that",
"accepts",
"a",
"numeric",
"string",
".",
"This",
"does",
"not",
"support",
"negative",
"values",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L1237-L1257 |
|
43,969 | ckknight/escort | lib/escort.js | function () {
var args = Array.prototype.slice.call(arguments, 0);
if (args.length < 1) {
throw new Error("Must specify at least one argument to AnyConverter");
}
var values = {};
for (var i = 0, len = args.length; i < len; i += 1) {
var arg = args[i];
values[arg.toLowerCase()] = arg;
}
return spawn(AnyConverter.prototype, {
_values: values,
regex: "(?:" + args.map(regexpEscape).join("|") + ")",
weight: 200
});
} | javascript | function () {
var args = Array.prototype.slice.call(arguments, 0);
if (args.length < 1) {
throw new Error("Must specify at least one argument to AnyConverter");
}
var values = {};
for (var i = 0, len = args.length; i < len; i += 1) {
var arg = args[i];
values[arg.toLowerCase()] = arg;
}
return spawn(AnyConverter.prototype, {
_values: values,
regex: "(?:" + args.map(regexpEscape).join("|") + ")",
weight: 200
});
} | [
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
";",
"if",
"(",
"args",
".",
"length",
"<",
"1",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Must specify at least one argument to AnyConverter\"",
")",
";",
"}",
"var",
"values",
"=",
"{",
"}",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"args",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"var",
"arg",
"=",
"args",
"[",
"i",
"]",
";",
"values",
"[",
"arg",
".",
"toLowerCase",
"(",
")",
"]",
"=",
"arg",
";",
"}",
"return",
"spawn",
"(",
"AnyConverter",
".",
"prototype",
",",
"{",
"_values",
":",
"values",
",",
"regex",
":",
"\"(?:\"",
"+",
"args",
".",
"map",
"(",
"regexpEscape",
")",
".",
"join",
"(",
"\"|\"",
")",
"+",
"\")\"",
",",
"weight",
":",
"200",
"}",
")",
";",
"}"
]
| A converter that matches one of the items provided.
@example routes.get("/pages/{pageName:any('about', 'help', 'contact')}", function(req, res, params) { }) | [
"A",
"converter",
"that",
"matches",
"one",
"of",
"the",
"items",
"provided",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort.js#L1308-L1325 |
|
43,970 | engineer-andrew/Angular-Tree-View | src/eaTreeView.factory.js | function(state, datasetId, items, matchFound, nestingLevel, stopExpandingParents) {
// initialize whatever wasn't passed to a default value
datasetId = datasetId || 'default';
items = items || concealed.items[datasetId];
matchFound = matchFound || false;
nestingLevel = nestingLevel || 0;
for (var i = items.length; --i >= 0;) {
if (!!items[i].items && !!items[i].items.length) {
// matchFound here would mean that a match was found in a descendant
matchFound = visible.setActive(state, datasetId, items[i].items, matchFound, nestingLevel + 1, stopExpandingParents);
if (matchFound && !stopExpandingParents) {
items[i].expanded = true;
if (nestingLevel === 0) {
stopExpandingParents = true;
}
}
} else {
if (matchFound) {
// matchFound here would mean either a sibling node or some other node was already matched
// so we want to skip the comparison to save time
items[i].isActive = false;
} else {
if (!!items[i].stateName && items[i].stateName === state) {
// if the item's state is the one being searched for then set the item to active and flip the matched flag
items[i].isActive = true;
matchFound = true;
stopExpandingParents = true;
} else {
items[i].isActive = false;
}
}
}
}
return matchFound;
} | javascript | function(state, datasetId, items, matchFound, nestingLevel, stopExpandingParents) {
// initialize whatever wasn't passed to a default value
datasetId = datasetId || 'default';
items = items || concealed.items[datasetId];
matchFound = matchFound || false;
nestingLevel = nestingLevel || 0;
for (var i = items.length; --i >= 0;) {
if (!!items[i].items && !!items[i].items.length) {
// matchFound here would mean that a match was found in a descendant
matchFound = visible.setActive(state, datasetId, items[i].items, matchFound, nestingLevel + 1, stopExpandingParents);
if (matchFound && !stopExpandingParents) {
items[i].expanded = true;
if (nestingLevel === 0) {
stopExpandingParents = true;
}
}
} else {
if (matchFound) {
// matchFound here would mean either a sibling node or some other node was already matched
// so we want to skip the comparison to save time
items[i].isActive = false;
} else {
if (!!items[i].stateName && items[i].stateName === state) {
// if the item's state is the one being searched for then set the item to active and flip the matched flag
items[i].isActive = true;
matchFound = true;
stopExpandingParents = true;
} else {
items[i].isActive = false;
}
}
}
}
return matchFound;
} | [
"function",
"(",
"state",
",",
"datasetId",
",",
"items",
",",
"matchFound",
",",
"nestingLevel",
",",
"stopExpandingParents",
")",
"{",
"// initialize whatever wasn't passed to a default value",
"datasetId",
"=",
"datasetId",
"||",
"'default'",
";",
"items",
"=",
"items",
"||",
"concealed",
".",
"items",
"[",
"datasetId",
"]",
";",
"matchFound",
"=",
"matchFound",
"||",
"false",
";",
"nestingLevel",
"=",
"nestingLevel",
"||",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"items",
".",
"length",
";",
"--",
"i",
">=",
"0",
";",
")",
"{",
"if",
"(",
"!",
"!",
"items",
"[",
"i",
"]",
".",
"items",
"&&",
"!",
"!",
"items",
"[",
"i",
"]",
".",
"items",
".",
"length",
")",
"{",
"// matchFound here would mean that a match was found in a descendant",
"matchFound",
"=",
"visible",
".",
"setActive",
"(",
"state",
",",
"datasetId",
",",
"items",
"[",
"i",
"]",
".",
"items",
",",
"matchFound",
",",
"nestingLevel",
"+",
"1",
",",
"stopExpandingParents",
")",
";",
"if",
"(",
"matchFound",
"&&",
"!",
"stopExpandingParents",
")",
"{",
"items",
"[",
"i",
"]",
".",
"expanded",
"=",
"true",
";",
"if",
"(",
"nestingLevel",
"===",
"0",
")",
"{",
"stopExpandingParents",
"=",
"true",
";",
"}",
"}",
"}",
"else",
"{",
"if",
"(",
"matchFound",
")",
"{",
"// matchFound here would mean either a sibling node or some other node was already matched",
"// so we want to skip the comparison to save time",
"items",
"[",
"i",
"]",
".",
"isActive",
"=",
"false",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"!",
"items",
"[",
"i",
"]",
".",
"stateName",
"&&",
"items",
"[",
"i",
"]",
".",
"stateName",
"===",
"state",
")",
"{",
"// if the item's state is the one being searched for then set the item to active and flip the matched flag",
"items",
"[",
"i",
"]",
".",
"isActive",
"=",
"true",
";",
"matchFound",
"=",
"true",
";",
"stopExpandingParents",
"=",
"true",
";",
"}",
"else",
"{",
"items",
"[",
"i",
"]",
".",
"isActive",
"=",
"false",
";",
"}",
"}",
"}",
"}",
"return",
"matchFound",
";",
"}"
]
| set the active item and expand all ancestors of the active item | [
"set",
"the",
"active",
"item",
"and",
"expand",
"all",
"ancestors",
"of",
"the",
"active",
"item"
]
| 4a7398057f36290568203c5cb1a3d23f633cc15e | https://github.com/engineer-andrew/Angular-Tree-View/blob/4a7398057f36290568203c5cb1a3d23f633cc15e/src/eaTreeView.factory.js#L30-L66 |
|
43,971 | lucsorel/markdown-image-loader | index.js | requirifyImageReference | function requirifyImageReference(markdownImageReference) {
const [, mdImageStart, mdImagePath, optionalMdTitle, mdImageEnd ] = imagePathRE.exec(markdownImageReference) || []
if (!mdImagePath) {
return JSON.stringify(markdownImageReference)
} else {
const imageRequest = loaderUtils.stringifyRequest(
this,
loaderUtils.urlToRequest(mdImagePath)
)
const mdImageTitleAndEnd = optionalMdTitle ? JSON.stringify(optionalMdTitle + mdImageEnd) : JSON.stringify(mdImageEnd)
return `${JSON.stringify(mdImageStart)} + require(${imageRequest}) + ${mdImageTitleAndEnd}`
}
} | javascript | function requirifyImageReference(markdownImageReference) {
const [, mdImageStart, mdImagePath, optionalMdTitle, mdImageEnd ] = imagePathRE.exec(markdownImageReference) || []
if (!mdImagePath) {
return JSON.stringify(markdownImageReference)
} else {
const imageRequest = loaderUtils.stringifyRequest(
this,
loaderUtils.urlToRequest(mdImagePath)
)
const mdImageTitleAndEnd = optionalMdTitle ? JSON.stringify(optionalMdTitle + mdImageEnd) : JSON.stringify(mdImageEnd)
return `${JSON.stringify(mdImageStart)} + require(${imageRequest}) + ${mdImageTitleAndEnd}`
}
} | [
"function",
"requirifyImageReference",
"(",
"markdownImageReference",
")",
"{",
"const",
"[",
",",
"mdImageStart",
",",
"mdImagePath",
",",
"optionalMdTitle",
",",
"mdImageEnd",
"]",
"=",
"imagePathRE",
".",
"exec",
"(",
"markdownImageReference",
")",
"||",
"[",
"]",
"if",
"(",
"!",
"mdImagePath",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"markdownImageReference",
")",
"}",
"else",
"{",
"const",
"imageRequest",
"=",
"loaderUtils",
".",
"stringifyRequest",
"(",
"this",
",",
"loaderUtils",
".",
"urlToRequest",
"(",
"mdImagePath",
")",
")",
"const",
"mdImageTitleAndEnd",
"=",
"optionalMdTitle",
"?",
"JSON",
".",
"stringify",
"(",
"optionalMdTitle",
"+",
"mdImageEnd",
")",
":",
"JSON",
".",
"stringify",
"(",
"mdImageEnd",
")",
"return",
"`",
"${",
"JSON",
".",
"stringify",
"(",
"mdImageStart",
")",
"}",
"${",
"imageRequest",
"}",
"${",
"mdImageTitleAndEnd",
"}",
"`",
"}",
"}"
]
| converts the image path in the markdowned-image syntax into a require statement, or stringify the given content | [
"converts",
"the",
"image",
"path",
"in",
"the",
"markdowned",
"-",
"image",
"syntax",
"into",
"a",
"require",
"statement",
"or",
"stringify",
"the",
"given",
"content"
]
| e3272fab82a2f3de858425792401c2f2f37ab6b1 | https://github.com/lucsorel/markdown-image-loader/blob/e3272fab82a2f3de858425792401c2f2f37ab6b1/index.js#L7-L20 |
43,972 | m59peacemaker/svelte-modal | build/Modal.js | checkPointerDown | function checkPointerDown(e) {
if (config.clickOutsideDeactivates && !container.contains(e.target)) {
deactivate({ returnFocus: false });
}
} | javascript | function checkPointerDown(e) {
if (config.clickOutsideDeactivates && !container.contains(e.target)) {
deactivate({ returnFocus: false });
}
} | [
"function",
"checkPointerDown",
"(",
"e",
")",
"{",
"if",
"(",
"config",
".",
"clickOutsideDeactivates",
"&&",
"!",
"container",
".",
"contains",
"(",
"e",
".",
"target",
")",
")",
"{",
"deactivate",
"(",
"{",
"returnFocus",
":",
"false",
"}",
")",
";",
"}",
"}"
]
| This needs to be done on mousedown and touchstart instead of click so that it precedes the focus event | [
"This",
"needs",
"to",
"be",
"done",
"on",
"mousedown",
"and",
"touchstart",
"instead",
"of",
"click",
"so",
"that",
"it",
"precedes",
"the",
"focus",
"event"
]
| 7f30bed0fabea376faa3e531dbfdb11b141eb548 | https://github.com/m59peacemaker/svelte-modal/blob/7f30bed0fabea376faa3e531dbfdb11b141eb548/build/Modal.js#L733-L737 |
43,973 | wala/jsdelta | src/transformations.js | applyTransformers | function applyTransformers(options, state, file) {
var transformationSucceededAtLeastOnce = false;
if (options.transformations && state.ext == "js") {
options.transformations.forEach(function (transformation) {
transformationSucceededAtLeastOnce |= transformAndTest(transformation, options, state, file);
});
}
return transformationSucceededAtLeastOnce;
} | javascript | function applyTransformers(options, state, file) {
var transformationSucceededAtLeastOnce = false;
if (options.transformations && state.ext == "js") {
options.transformations.forEach(function (transformation) {
transformationSucceededAtLeastOnce |= transformAndTest(transformation, options, state, file);
});
}
return transformationSucceededAtLeastOnce;
} | [
"function",
"applyTransformers",
"(",
"options",
",",
"state",
",",
"file",
")",
"{",
"var",
"transformationSucceededAtLeastOnce",
"=",
"false",
";",
"if",
"(",
"options",
".",
"transformations",
"&&",
"state",
".",
"ext",
"==",
"\"js\"",
")",
"{",
"options",
".",
"transformations",
".",
"forEach",
"(",
"function",
"(",
"transformation",
")",
"{",
"transformationSucceededAtLeastOnce",
"|=",
"transformAndTest",
"(",
"transformation",
",",
"options",
",",
"state",
",",
"file",
")",
";",
"}",
")",
";",
"}",
"return",
"transformationSucceededAtLeastOnce",
";",
"}"
]
| Applies all the custom transformers.
Returns true iff any of the transformations made the predicate true. | [
"Applies",
"all",
"the",
"custom",
"transformers",
"."
]
| 355febea1ee23e9e909ba2bfa087ffb2499a3295 | https://github.com/wala/jsdelta/blob/355febea1ee23e9e909ba2bfa087ffb2499a3295/src/transformations.js#L61-L69 |
43,974 | asgerf/tscheck | tscore.js | TObject | function TObject(qname, meta) {
this.qname = qname;
this.properties = new Map;
this.modules = new Map;
this.calls = []
this.types = new Map;
this.supers = []
this.typeParameters = []
this.brand = null;
this.meta = {
kind: meta.kind,
origin: meta.origin,
isEnum: false
}
} | javascript | function TObject(qname, meta) {
this.qname = qname;
this.properties = new Map;
this.modules = new Map;
this.calls = []
this.types = new Map;
this.supers = []
this.typeParameters = []
this.brand = null;
this.meta = {
kind: meta.kind,
origin: meta.origin,
isEnum: false
}
} | [
"function",
"TObject",
"(",
"qname",
",",
"meta",
")",
"{",
"this",
".",
"qname",
"=",
"qname",
";",
"this",
".",
"properties",
"=",
"new",
"Map",
";",
"this",
".",
"modules",
"=",
"new",
"Map",
";",
"this",
".",
"calls",
"=",
"[",
"]",
"this",
".",
"types",
"=",
"new",
"Map",
";",
"this",
".",
"supers",
"=",
"[",
"]",
"this",
".",
"typeParameters",
"=",
"[",
"]",
"this",
".",
"brand",
"=",
"null",
";",
"this",
".",
"meta",
"=",
"{",
"kind",
":",
"meta",
".",
"kind",
",",
"origin",
":",
"meta",
".",
"origin",
",",
"isEnum",
":",
"false",
"}",
"}"
]
| Object type. | [
"Object",
"type",
"."
]
| 7bf73cba5d85ec96fda3f4bda20e47b194de6e08 | https://github.com/asgerf/tscheck/blob/7bf73cba5d85ec96fda3f4bda20e47b194de6e08/tscore.js#L130-L144 |
43,975 | asgerf/tscheck | tscore.js | addModuleMember | function addModuleMember(member, moduleObject, qname) {
current_node = member;
var topLevel = qname === '';
if (member instanceof TypeScript.FunctionDeclaration) {
var obj = moduleObject.getMember(member.name.text())
if (obj instanceof TObject) {
obj.calls.push(parseFunctionType(member))
} else {
throw new TypeError(member.name.text() + " is not a function")
}
}
else if (member instanceof TypeScript.VariableStatement) {
member.declaration.declarators.members.forEach(function(decl) {
moduleObject.setMember(decl.id.text(), parseType(decl.typeExpr))
})
}
else if (member instanceof TypeScript.ModuleDeclaration) {
var name = member.name.text()
if (member.isEnum()) { // enums are ModuleDeclarations in the AST, but they are semantically quite different
var enumObj = moduleObject.getModule(name)
enumObj.meta.isEnum = true
var enumResult = parseEnum(member, enumObj, qname)
moduleObject.types.push(name, enumResult.enum)
} else {
if (name[0] === '"' || name[0] === "'") { // external module?
parseExternModule(member)
} else {
var submodule = moduleObject.getModule(name)
parseModule(member, submodule, qualify(qname, name))
}
}
}
else if (member instanceof TypeScript.ClassDeclaration) {
var name = member.name.text()
var clazzObj = moduleObject.getModule(name)
var clazz = parseClass(member, clazzObj, qname)
// moduleObject.setMember(member.name.text(), clazz.constructorType)
moduleObject.types.push(member.name.text(), clazz.instanceType)
}
else if (member instanceof TypeScript.InterfaceDeclaration) {
var name = member.name.text()
var t = parseInterface(member, qname)
moduleObject.types.push(name, t)
}
else if (member instanceof TypeScript.ImportDeclaration) {
var ref = parseType(member.alias)
if (topLevel || TypeScript.hasFlag(member.getVarFlags(), TypeScript.VariableFlags.Exported)) {
moduleObject.types.push(member.id.text(), ref)
} else {
// private alias to (potentially) publicly visible type
current_scope.env.push(member.id.text(), ref)
}
}
else if (member instanceof TypeScript.ExportAssignment) {
// XXX: I think we can actually just ignore these in the tscheck project,
// but for completeness, maybe we should export this information somehow
// For reference, this is what I *think* happens:
// declare module "foo" { export = X }
// This means import("foo") will return the value in global variable X.
// Maybe we need these for modular analysis?
}
else {
throw new TypeError("Unexpected member in module " + qname + ": " + member.constructor.name)
}
} | javascript | function addModuleMember(member, moduleObject, qname) {
current_node = member;
var topLevel = qname === '';
if (member instanceof TypeScript.FunctionDeclaration) {
var obj = moduleObject.getMember(member.name.text())
if (obj instanceof TObject) {
obj.calls.push(parseFunctionType(member))
} else {
throw new TypeError(member.name.text() + " is not a function")
}
}
else if (member instanceof TypeScript.VariableStatement) {
member.declaration.declarators.members.forEach(function(decl) {
moduleObject.setMember(decl.id.text(), parseType(decl.typeExpr))
})
}
else if (member instanceof TypeScript.ModuleDeclaration) {
var name = member.name.text()
if (member.isEnum()) { // enums are ModuleDeclarations in the AST, but they are semantically quite different
var enumObj = moduleObject.getModule(name)
enumObj.meta.isEnum = true
var enumResult = parseEnum(member, enumObj, qname)
moduleObject.types.push(name, enumResult.enum)
} else {
if (name[0] === '"' || name[0] === "'") { // external module?
parseExternModule(member)
} else {
var submodule = moduleObject.getModule(name)
parseModule(member, submodule, qualify(qname, name))
}
}
}
else if (member instanceof TypeScript.ClassDeclaration) {
var name = member.name.text()
var clazzObj = moduleObject.getModule(name)
var clazz = parseClass(member, clazzObj, qname)
// moduleObject.setMember(member.name.text(), clazz.constructorType)
moduleObject.types.push(member.name.text(), clazz.instanceType)
}
else if (member instanceof TypeScript.InterfaceDeclaration) {
var name = member.name.text()
var t = parseInterface(member, qname)
moduleObject.types.push(name, t)
}
else if (member instanceof TypeScript.ImportDeclaration) {
var ref = parseType(member.alias)
if (topLevel || TypeScript.hasFlag(member.getVarFlags(), TypeScript.VariableFlags.Exported)) {
moduleObject.types.push(member.id.text(), ref)
} else {
// private alias to (potentially) publicly visible type
current_scope.env.push(member.id.text(), ref)
}
}
else if (member instanceof TypeScript.ExportAssignment) {
// XXX: I think we can actually just ignore these in the tscheck project,
// but for completeness, maybe we should export this information somehow
// For reference, this is what I *think* happens:
// declare module "foo" { export = X }
// This means import("foo") will return the value in global variable X.
// Maybe we need these for modular analysis?
}
else {
throw new TypeError("Unexpected member in module " + qname + ": " + member.constructor.name)
}
} | [
"function",
"addModuleMember",
"(",
"member",
",",
"moduleObject",
",",
"qname",
")",
"{",
"current_node",
"=",
"member",
";",
"var",
"topLevel",
"=",
"qname",
"===",
"''",
";",
"if",
"(",
"member",
"instanceof",
"TypeScript",
".",
"FunctionDeclaration",
")",
"{",
"var",
"obj",
"=",
"moduleObject",
".",
"getMember",
"(",
"member",
".",
"name",
".",
"text",
"(",
")",
")",
"if",
"(",
"obj",
"instanceof",
"TObject",
")",
"{",
"obj",
".",
"calls",
".",
"push",
"(",
"parseFunctionType",
"(",
"member",
")",
")",
"}",
"else",
"{",
"throw",
"new",
"TypeError",
"(",
"member",
".",
"name",
".",
"text",
"(",
")",
"+",
"\" is not a function\"",
")",
"}",
"}",
"else",
"if",
"(",
"member",
"instanceof",
"TypeScript",
".",
"VariableStatement",
")",
"{",
"member",
".",
"declaration",
".",
"declarators",
".",
"members",
".",
"forEach",
"(",
"function",
"(",
"decl",
")",
"{",
"moduleObject",
".",
"setMember",
"(",
"decl",
".",
"id",
".",
"text",
"(",
")",
",",
"parseType",
"(",
"decl",
".",
"typeExpr",
")",
")",
"}",
")",
"}",
"else",
"if",
"(",
"member",
"instanceof",
"TypeScript",
".",
"ModuleDeclaration",
")",
"{",
"var",
"name",
"=",
"member",
".",
"name",
".",
"text",
"(",
")",
"if",
"(",
"member",
".",
"isEnum",
"(",
")",
")",
"{",
"// enums are ModuleDeclarations in the AST, but they are semantically quite different",
"var",
"enumObj",
"=",
"moduleObject",
".",
"getModule",
"(",
"name",
")",
"enumObj",
".",
"meta",
".",
"isEnum",
"=",
"true",
"var",
"enumResult",
"=",
"parseEnum",
"(",
"member",
",",
"enumObj",
",",
"qname",
")",
"moduleObject",
".",
"types",
".",
"push",
"(",
"name",
",",
"enumResult",
".",
"enum",
")",
"}",
"else",
"{",
"if",
"(",
"name",
"[",
"0",
"]",
"===",
"'\"'",
"||",
"name",
"[",
"0",
"]",
"===",
"\"'\"",
")",
"{",
"// external module?",
"parseExternModule",
"(",
"member",
")",
"}",
"else",
"{",
"var",
"submodule",
"=",
"moduleObject",
".",
"getModule",
"(",
"name",
")",
"parseModule",
"(",
"member",
",",
"submodule",
",",
"qualify",
"(",
"qname",
",",
"name",
")",
")",
"}",
"}",
"}",
"else",
"if",
"(",
"member",
"instanceof",
"TypeScript",
".",
"ClassDeclaration",
")",
"{",
"var",
"name",
"=",
"member",
".",
"name",
".",
"text",
"(",
")",
"var",
"clazzObj",
"=",
"moduleObject",
".",
"getModule",
"(",
"name",
")",
"var",
"clazz",
"=",
"parseClass",
"(",
"member",
",",
"clazzObj",
",",
"qname",
")",
"// moduleObject.setMember(member.name.text(), clazz.constructorType)",
"moduleObject",
".",
"types",
".",
"push",
"(",
"member",
".",
"name",
".",
"text",
"(",
")",
",",
"clazz",
".",
"instanceType",
")",
"}",
"else",
"if",
"(",
"member",
"instanceof",
"TypeScript",
".",
"InterfaceDeclaration",
")",
"{",
"var",
"name",
"=",
"member",
".",
"name",
".",
"text",
"(",
")",
"var",
"t",
"=",
"parseInterface",
"(",
"member",
",",
"qname",
")",
"moduleObject",
".",
"types",
".",
"push",
"(",
"name",
",",
"t",
")",
"}",
"else",
"if",
"(",
"member",
"instanceof",
"TypeScript",
".",
"ImportDeclaration",
")",
"{",
"var",
"ref",
"=",
"parseType",
"(",
"member",
".",
"alias",
")",
"if",
"(",
"topLevel",
"||",
"TypeScript",
".",
"hasFlag",
"(",
"member",
".",
"getVarFlags",
"(",
")",
",",
"TypeScript",
".",
"VariableFlags",
".",
"Exported",
")",
")",
"{",
"moduleObject",
".",
"types",
".",
"push",
"(",
"member",
".",
"id",
".",
"text",
"(",
")",
",",
"ref",
")",
"}",
"else",
"{",
"// private alias to (potentially) publicly visible type",
"current_scope",
".",
"env",
".",
"push",
"(",
"member",
".",
"id",
".",
"text",
"(",
")",
",",
"ref",
")",
"}",
"}",
"else",
"if",
"(",
"member",
"instanceof",
"TypeScript",
".",
"ExportAssignment",
")",
"{",
"// XXX: I think we can actually just ignore these in the tscheck project,",
"// but for completeness, maybe we should export this information somehow",
"// For reference, this is what I *think* happens:",
"// \t\tdeclare module \"foo\" { export = X }",
"// This means import(\"foo\") will return the value in global variable X.",
"// Maybe we need these for modular analysis?",
"}",
"else",
"{",
"throw",
"new",
"TypeError",
"(",
"\"Unexpected member in module \"",
"+",
"qname",
"+",
"\": \"",
"+",
"member",
".",
"constructor",
".",
"name",
")",
"}",
"}"
]
| Some names are resolved before merging, others after. Type parameters must be resolved before merging, because merging generic interfaces requires alpha-renaming of type parameters. Names defined in modules must be resolved after merging, because the whole module type is not available until then. | [
"Some",
"names",
"are",
"resolved",
"before",
"merging",
"others",
"after",
".",
"Type",
"parameters",
"must",
"be",
"resolved",
"before",
"merging",
"because",
"merging",
"generic",
"interfaces",
"requires",
"alpha",
"-",
"renaming",
"of",
"type",
"parameters",
".",
"Names",
"defined",
"in",
"modules",
"must",
"be",
"resolved",
"after",
"merging",
"because",
"the",
"whole",
"module",
"type",
"is",
"not",
"available",
"until",
"then",
"."
]
| 7bf73cba5d85ec96fda3f4bda20e47b194de6e08 | https://github.com/asgerf/tscheck/blob/7bf73cba5d85ec96fda3f4bda20e47b194de6e08/tscore.js#L239-L303 |
43,976 | asgerf/tscheck | tscore.js | resolveReference | function resolveReference(x, isModule) {
if (x instanceof TReference) {
if (isBuiltin(x.name))
return new TBuiltin(x.name)
if (x.resolution)
return x.resolution
if (x.resolving)
throw new TypeError("Cyclic reference involving " + x)
x.resolving = true
var t = lookupInScope(x.scope, x.name, isModule)
if (!t) {
t = new TQualifiedReference(x.name) // XXX: for now assume global reference
// throw new TypeError("Unresolved type: " + x.name)
}
t = resolveReference(t, isModule)
x.resolution = t;
return t;
} else if (x instanceof TMember) {
if (x.resolution)
return x.resolution
if (x.resolving)
throw new TypeError("Cyclic reference involving " + x)
x.resolving = true
var base = resolveReference(x.base, true)
var t = resolveReference(lookupInType(base, x.name, isModule), isModule)
x.resolution = t
return t;
} else if (x instanceof TTypeQuery) {
if (x.resolution)
return x.resolution;
if (x.resolving)
throw new TypeError("Cyclic reference involving " + x)
x.resolving = true
var t = lookupPrtyInScope(x.scope, x.names[0])
if (!t)
throw new TypeError("Name not found: " + x.names[0])
t = resolveReference(t)
for (var i=1; i<x.names.length; i++) {
var prty = t.properties.get(x.names[i])
var module = t.modules.get(x.names[i])
var t = prty ? prty.type : module;
if (!t)
throw new TypeError("Name not found: " + x.names.slice(0,i).join('.'))
t = resolveReference(t)
}
if (t instanceof TObject && !t.qname) {
t = synthesizeName(t) // don't create aliasing
}
x.resolution = t;
return t;
} else {
return x;
}
} | javascript | function resolveReference(x, isModule) {
if (x instanceof TReference) {
if (isBuiltin(x.name))
return new TBuiltin(x.name)
if (x.resolution)
return x.resolution
if (x.resolving)
throw new TypeError("Cyclic reference involving " + x)
x.resolving = true
var t = lookupInScope(x.scope, x.name, isModule)
if (!t) {
t = new TQualifiedReference(x.name) // XXX: for now assume global reference
// throw new TypeError("Unresolved type: " + x.name)
}
t = resolveReference(t, isModule)
x.resolution = t;
return t;
} else if (x instanceof TMember) {
if (x.resolution)
return x.resolution
if (x.resolving)
throw new TypeError("Cyclic reference involving " + x)
x.resolving = true
var base = resolveReference(x.base, true)
var t = resolveReference(lookupInType(base, x.name, isModule), isModule)
x.resolution = t
return t;
} else if (x instanceof TTypeQuery) {
if (x.resolution)
return x.resolution;
if (x.resolving)
throw new TypeError("Cyclic reference involving " + x)
x.resolving = true
var t = lookupPrtyInScope(x.scope, x.names[0])
if (!t)
throw new TypeError("Name not found: " + x.names[0])
t = resolveReference(t)
for (var i=1; i<x.names.length; i++) {
var prty = t.properties.get(x.names[i])
var module = t.modules.get(x.names[i])
var t = prty ? prty.type : module;
if (!t)
throw new TypeError("Name not found: " + x.names.slice(0,i).join('.'))
t = resolveReference(t)
}
if (t instanceof TObject && !t.qname) {
t = synthesizeName(t) // don't create aliasing
}
x.resolution = t;
return t;
} else {
return x;
}
} | [
"function",
"resolveReference",
"(",
"x",
",",
"isModule",
")",
"{",
"if",
"(",
"x",
"instanceof",
"TReference",
")",
"{",
"if",
"(",
"isBuiltin",
"(",
"x",
".",
"name",
")",
")",
"return",
"new",
"TBuiltin",
"(",
"x",
".",
"name",
")",
"if",
"(",
"x",
".",
"resolution",
")",
"return",
"x",
".",
"resolution",
"if",
"(",
"x",
".",
"resolving",
")",
"throw",
"new",
"TypeError",
"(",
"\"Cyclic reference involving \"",
"+",
"x",
")",
"x",
".",
"resolving",
"=",
"true",
"var",
"t",
"=",
"lookupInScope",
"(",
"x",
".",
"scope",
",",
"x",
".",
"name",
",",
"isModule",
")",
"if",
"(",
"!",
"t",
")",
"{",
"t",
"=",
"new",
"TQualifiedReference",
"(",
"x",
".",
"name",
")",
"// XXX: for now assume global reference",
"// throw new TypeError(\"Unresolved type: \" + x.name)",
"}",
"t",
"=",
"resolveReference",
"(",
"t",
",",
"isModule",
")",
"x",
".",
"resolution",
"=",
"t",
";",
"return",
"t",
";",
"}",
"else",
"if",
"(",
"x",
"instanceof",
"TMember",
")",
"{",
"if",
"(",
"x",
".",
"resolution",
")",
"return",
"x",
".",
"resolution",
"if",
"(",
"x",
".",
"resolving",
")",
"throw",
"new",
"TypeError",
"(",
"\"Cyclic reference involving \"",
"+",
"x",
")",
"x",
".",
"resolving",
"=",
"true",
"var",
"base",
"=",
"resolveReference",
"(",
"x",
".",
"base",
",",
"true",
")",
"var",
"t",
"=",
"resolveReference",
"(",
"lookupInType",
"(",
"base",
",",
"x",
".",
"name",
",",
"isModule",
")",
",",
"isModule",
")",
"x",
".",
"resolution",
"=",
"t",
"return",
"t",
";",
"}",
"else",
"if",
"(",
"x",
"instanceof",
"TTypeQuery",
")",
"{",
"if",
"(",
"x",
".",
"resolution",
")",
"return",
"x",
".",
"resolution",
";",
"if",
"(",
"x",
".",
"resolving",
")",
"throw",
"new",
"TypeError",
"(",
"\"Cyclic reference involving \"",
"+",
"x",
")",
"x",
".",
"resolving",
"=",
"true",
"var",
"t",
"=",
"lookupPrtyInScope",
"(",
"x",
".",
"scope",
",",
"x",
".",
"names",
"[",
"0",
"]",
")",
"if",
"(",
"!",
"t",
")",
"throw",
"new",
"TypeError",
"(",
"\"Name not found: \"",
"+",
"x",
".",
"names",
"[",
"0",
"]",
")",
"t",
"=",
"resolveReference",
"(",
"t",
")",
"for",
"(",
"var",
"i",
"=",
"1",
";",
"i",
"<",
"x",
".",
"names",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"prty",
"=",
"t",
".",
"properties",
".",
"get",
"(",
"x",
".",
"names",
"[",
"i",
"]",
")",
"var",
"module",
"=",
"t",
".",
"modules",
".",
"get",
"(",
"x",
".",
"names",
"[",
"i",
"]",
")",
"var",
"t",
"=",
"prty",
"?",
"prty",
".",
"type",
":",
"module",
";",
"if",
"(",
"!",
"t",
")",
"throw",
"new",
"TypeError",
"(",
"\"Name not found: \"",
"+",
"x",
".",
"names",
".",
"slice",
"(",
"0",
",",
"i",
")",
".",
"join",
"(",
"'.'",
")",
")",
"t",
"=",
"resolveReference",
"(",
"t",
")",
"}",
"if",
"(",
"t",
"instanceof",
"TObject",
"&&",
"!",
"t",
".",
"qname",
")",
"{",
"t",
"=",
"synthesizeName",
"(",
"t",
")",
"// don't create aliasing",
"}",
"x",
".",
"resolution",
"=",
"t",
";",
"return",
"t",
";",
"}",
"else",
"{",
"return",
"x",
";",
"}",
"}"
]
| Resolves a TReference or TMember to a TQualifiedReference | [
"Resolves",
"a",
"TReference",
"or",
"TMember",
"to",
"a",
"TQualifiedReference"
]
| 7bf73cba5d85ec96fda3f4bda20e47b194de6e08 | https://github.com/asgerf/tscheck/blob/7bf73cba5d85ec96fda3f4bda20e47b194de6e08/tscore.js#L962-L1015 |
43,977 | asgerf/tscheck | tscore.js | resolveType | function resolveType(x) {
if (x instanceof TReference) {
return resolveReference(x)
} else if (x instanceof TMember) {
return resolveReference(x)
} else if (x instanceof TObject) {
if (x.qname)
return new TQualifiedReference(x.qname) // can happen if a qname was synthesized by resolveReference
return resolveObject(x);
} else if (x instanceof TQualifiedReference) {
return x;
} else if (x instanceof TTypeParam) {
return new TTypeParam(x.name, x.constraint && resolveType(x.constraint))
} else if (x instanceof TGeneric) {
return new TGeneric(resolveType(x.base), x.args.map(resolveType))
} else if (x instanceof TString) {
return x;
} else if (x instanceof TBuiltin) {
return x;
} else if (x instanceof TTypeQuery) {
return resolveReference(x);
} else if (x instanceof TEnum) {
return x;
}
var msg;
if (x.constructor.name === 'Object')
msg = util.inspect(x)
else
msg = '' + x;
throw new TypeError("Cannot canonicalize reference to " + (x && x.constructor.name + ': ' + msg))
} | javascript | function resolveType(x) {
if (x instanceof TReference) {
return resolveReference(x)
} else if (x instanceof TMember) {
return resolveReference(x)
} else if (x instanceof TObject) {
if (x.qname)
return new TQualifiedReference(x.qname) // can happen if a qname was synthesized by resolveReference
return resolveObject(x);
} else if (x instanceof TQualifiedReference) {
return x;
} else if (x instanceof TTypeParam) {
return new TTypeParam(x.name, x.constraint && resolveType(x.constraint))
} else if (x instanceof TGeneric) {
return new TGeneric(resolveType(x.base), x.args.map(resolveType))
} else if (x instanceof TString) {
return x;
} else if (x instanceof TBuiltin) {
return x;
} else if (x instanceof TTypeQuery) {
return resolveReference(x);
} else if (x instanceof TEnum) {
return x;
}
var msg;
if (x.constructor.name === 'Object')
msg = util.inspect(x)
else
msg = '' + x;
throw new TypeError("Cannot canonicalize reference to " + (x && x.constructor.name + ': ' + msg))
} | [
"function",
"resolveType",
"(",
"x",
")",
"{",
"if",
"(",
"x",
"instanceof",
"TReference",
")",
"{",
"return",
"resolveReference",
"(",
"x",
")",
"}",
"else",
"if",
"(",
"x",
"instanceof",
"TMember",
")",
"{",
"return",
"resolveReference",
"(",
"x",
")",
"}",
"else",
"if",
"(",
"x",
"instanceof",
"TObject",
")",
"{",
"if",
"(",
"x",
".",
"qname",
")",
"return",
"new",
"TQualifiedReference",
"(",
"x",
".",
"qname",
")",
"// can happen if a qname was synthesized by resolveReference",
"return",
"resolveObject",
"(",
"x",
")",
";",
"}",
"else",
"if",
"(",
"x",
"instanceof",
"TQualifiedReference",
")",
"{",
"return",
"x",
";",
"}",
"else",
"if",
"(",
"x",
"instanceof",
"TTypeParam",
")",
"{",
"return",
"new",
"TTypeParam",
"(",
"x",
".",
"name",
",",
"x",
".",
"constraint",
"&&",
"resolveType",
"(",
"x",
".",
"constraint",
")",
")",
"}",
"else",
"if",
"(",
"x",
"instanceof",
"TGeneric",
")",
"{",
"return",
"new",
"TGeneric",
"(",
"resolveType",
"(",
"x",
".",
"base",
")",
",",
"x",
".",
"args",
".",
"map",
"(",
"resolveType",
")",
")",
"}",
"else",
"if",
"(",
"x",
"instanceof",
"TString",
")",
"{",
"return",
"x",
";",
"}",
"else",
"if",
"(",
"x",
"instanceof",
"TBuiltin",
")",
"{",
"return",
"x",
";",
"}",
"else",
"if",
"(",
"x",
"instanceof",
"TTypeQuery",
")",
"{",
"return",
"resolveReference",
"(",
"x",
")",
";",
"}",
"else",
"if",
"(",
"x",
"instanceof",
"TEnum",
")",
"{",
"return",
"x",
";",
"}",
"var",
"msg",
";",
"if",
"(",
"x",
".",
"constructor",
".",
"name",
"===",
"'Object'",
")",
"msg",
"=",
"util",
".",
"inspect",
"(",
"x",
")",
"else",
"msg",
"=",
"''",
"+",
"x",
";",
"throw",
"new",
"TypeError",
"(",
"\"Cannot canonicalize reference to \"",
"+",
"(",
"x",
"&&",
"x",
".",
"constructor",
".",
"name",
"+",
"': '",
"+",
"msg",
")",
")",
"}"
]
| Recursively builds a type where all references have been resolved | [
"Recursively",
"builds",
"a",
"type",
"where",
"all",
"references",
"have",
"been",
"resolved"
]
| 7bf73cba5d85ec96fda3f4bda20e47b194de6e08 | https://github.com/asgerf/tscheck/blob/7bf73cba5d85ec96fda3f4bda20e47b194de6e08/tscore.js#L1018-L1048 |
43,978 | asgerf/tscheck | tscheck.js | hasBrand | function hasBrand(value, brand) {
var ctor = lookupPath(brand, function() { return null })
if (!ctor || typeof ctor !== 'object')
return null;
var proto = lookupObject(ctor.key).propertyMap.get('prototype')
if (!proto || !proto.value || typeof proto.value !== 'object')
return null;
while (value && typeof value === 'object') {
if (value.key === proto.value.key)
return true
value = lookupObject(value.key).prototype
}
return false;
} | javascript | function hasBrand(value, brand) {
var ctor = lookupPath(brand, function() { return null })
if (!ctor || typeof ctor !== 'object')
return null;
var proto = lookupObject(ctor.key).propertyMap.get('prototype')
if (!proto || !proto.value || typeof proto.value !== 'object')
return null;
while (value && typeof value === 'object') {
if (value.key === proto.value.key)
return true
value = lookupObject(value.key).prototype
}
return false;
} | [
"function",
"hasBrand",
"(",
"value",
",",
"brand",
")",
"{",
"var",
"ctor",
"=",
"lookupPath",
"(",
"brand",
",",
"function",
"(",
")",
"{",
"return",
"null",
"}",
")",
"if",
"(",
"!",
"ctor",
"||",
"typeof",
"ctor",
"!==",
"'object'",
")",
"return",
"null",
";",
"var",
"proto",
"=",
"lookupObject",
"(",
"ctor",
".",
"key",
")",
".",
"propertyMap",
".",
"get",
"(",
"'prototype'",
")",
"if",
"(",
"!",
"proto",
"||",
"!",
"proto",
".",
"value",
"||",
"typeof",
"proto",
".",
"value",
"!==",
"'object'",
")",
"return",
"null",
";",
"while",
"(",
"value",
"&&",
"typeof",
"value",
"===",
"'object'",
")",
"{",
"if",
"(",
"value",
".",
"key",
"===",
"proto",
".",
"value",
".",
"key",
")",
"return",
"true",
"value",
"=",
"lookupObject",
"(",
"value",
".",
"key",
")",
".",
"prototype",
"}",
"return",
"false",
";",
"}"
]
| Returns true if brand is satisfied, false if brand is not satisfied, or null if brand prototype could not be found. | [
"Returns",
"true",
"if",
"brand",
"is",
"satisfied",
"false",
"if",
"brand",
"is",
"not",
"satisfied",
"or",
"null",
"if",
"brand",
"prototype",
"could",
"not",
"be",
"found",
"."
]
| 7bf73cba5d85ec96fda3f4bda20e47b194de6e08 | https://github.com/asgerf/tscheck/blob/7bf73cba5d85ec96fda3f4bda20e47b194de6e08/tscheck.js#L984-L997 |
43,979 | asgerf/tscheck | tscheck.js | getEnclosingFunction | function getEnclosingFunction(node) {
while (node.type !== 'FunctionDeclaration' &&
node.type !== 'FunctionExpression' &&
node.type !== 'Program') {
node = node.$parent;
}
return node;
} | javascript | function getEnclosingFunction(node) {
while (node.type !== 'FunctionDeclaration' &&
node.type !== 'FunctionExpression' &&
node.type !== 'Program') {
node = node.$parent;
}
return node;
} | [
"function",
"getEnclosingFunction",
"(",
"node",
")",
"{",
"while",
"(",
"node",
".",
"type",
"!==",
"'FunctionDeclaration'",
"&&",
"node",
".",
"type",
"!==",
"'FunctionExpression'",
"&&",
"node",
".",
"type",
"!==",
"'Program'",
")",
"{",
"node",
"=",
"node",
".",
"$parent",
";",
"}",
"return",
"node",
";",
"}"
]
| Returns the function or program immediately enclosing the given node, possibly the node itself. | [
"Returns",
"the",
"function",
"or",
"program",
"immediately",
"enclosing",
"the",
"given",
"node",
"possibly",
"the",
"node",
"itself",
"."
]
| 7bf73cba5d85ec96fda3f4bda20e47b194de6e08 | https://github.com/asgerf/tscheck/blob/7bf73cba5d85ec96fda3f4bda20e47b194de6e08/tscheck.js#L1526-L1533 |
43,980 | asgerf/tscheck | tscheck.js | getEnclosingScope | function getEnclosingScope(node) {
while (node.type !== 'FunctionDeclaration' &&
node.type !== 'FunctionExpression' &&
node.type !== 'CatchClause' &&
node.type !== 'Program') {
node = node.$parent;
}
return node;
} | javascript | function getEnclosingScope(node) {
while (node.type !== 'FunctionDeclaration' &&
node.type !== 'FunctionExpression' &&
node.type !== 'CatchClause' &&
node.type !== 'Program') {
node = node.$parent;
}
return node;
} | [
"function",
"getEnclosingScope",
"(",
"node",
")",
"{",
"while",
"(",
"node",
".",
"type",
"!==",
"'FunctionDeclaration'",
"&&",
"node",
".",
"type",
"!==",
"'FunctionExpression'",
"&&",
"node",
".",
"type",
"!==",
"'CatchClause'",
"&&",
"node",
".",
"type",
"!==",
"'Program'",
")",
"{",
"node",
"=",
"node",
".",
"$parent",
";",
"}",
"return",
"node",
";",
"}"
]
| Returns the function, program or catch clause immediately enclosing the given node, possibly the node itself. | [
"Returns",
"the",
"function",
"program",
"or",
"catch",
"clause",
"immediately",
"enclosing",
"the",
"given",
"node",
"possibly",
"the",
"node",
"itself",
"."
]
| 7bf73cba5d85ec96fda3f4bda20e47b194de6e08 | https://github.com/asgerf/tscheck/blob/7bf73cba5d85ec96fda3f4bda20e47b194de6e08/tscheck.js#L1536-L1544 |
43,981 | fengyuanchen/is-vue-component | dist/is-vue-component.esm.js | isElement | function isElement(value) {
return isNonNullObject(value) && value.nodeType === 1 && toString.call(value).indexOf('Element') > -1;
} | javascript | function isElement(value) {
return isNonNullObject(value) && value.nodeType === 1 && toString.call(value).indexOf('Element') > -1;
} | [
"function",
"isElement",
"(",
"value",
")",
"{",
"return",
"isNonNullObject",
"(",
"value",
")",
"&&",
"value",
".",
"nodeType",
"===",
"1",
"&&",
"toString",
".",
"call",
"(",
"value",
")",
".",
"indexOf",
"(",
"'Element'",
")",
">",
"-",
"1",
";",
"}"
]
| Check if the given value is an element.
@param {*} value - The value to check.
@returns {boolean} Returns `true` if the given value is an element, else `false`. | [
"Check",
"if",
"the",
"given",
"value",
"is",
"an",
"element",
"."
]
| 0bf281b28a87899d104f6d528ccbf6272c43d6b9 | https://github.com/fengyuanchen/is-vue-component/blob/0bf281b28a87899d104f6d528ccbf6272c43d6b9/dist/is-vue-component.esm.js#L70-L72 |
43,982 | fengyuanchen/is-vue-component | dist/is-vue-component.esm.js | isVueComponent | function isVueComponent(value) {
return isPlainObject(value) && (isNonEmptyString(value.template) || isFunction(value.render) || isNonEmptyString(value.el) || isElement(value.el) || isVueComponent(value.extends) || isNonEmptyArray(value.mixins) && value.mixins.some(function (val) {
return isVueComponent(val);
}));
} | javascript | function isVueComponent(value) {
return isPlainObject(value) && (isNonEmptyString(value.template) || isFunction(value.render) || isNonEmptyString(value.el) || isElement(value.el) || isVueComponent(value.extends) || isNonEmptyArray(value.mixins) && value.mixins.some(function (val) {
return isVueComponent(val);
}));
} | [
"function",
"isVueComponent",
"(",
"value",
")",
"{",
"return",
"isPlainObject",
"(",
"value",
")",
"&&",
"(",
"isNonEmptyString",
"(",
"value",
".",
"template",
")",
"||",
"isFunction",
"(",
"value",
".",
"render",
")",
"||",
"isNonEmptyString",
"(",
"value",
".",
"el",
")",
"||",
"isElement",
"(",
"value",
".",
"el",
")",
"||",
"isVueComponent",
"(",
"value",
".",
"extends",
")",
"||",
"isNonEmptyArray",
"(",
"value",
".",
"mixins",
")",
"&&",
"value",
".",
"mixins",
".",
"some",
"(",
"function",
"(",
"val",
")",
"{",
"return",
"isVueComponent",
"(",
"val",
")",
";",
"}",
")",
")",
";",
"}"
]
| Check if the given value is a valid Vue component.
@param {*} value - The value to check.
@returns {boolean} Returns `true` if the given value is a valid Vue component, else `false`. | [
"Check",
"if",
"the",
"given",
"value",
"is",
"a",
"valid",
"Vue",
"component",
"."
]
| 0bf281b28a87899d104f6d528ccbf6272c43d6b9 | https://github.com/fengyuanchen/is-vue-component/blob/0bf281b28a87899d104f6d528ccbf6272c43d6b9/dist/is-vue-component.esm.js#L79-L83 |
43,983 | kevincennis/logbro | lib/logbro.js | initialize | function initialize() {
var flags = [];
Object.keys( levels ).forEach(function( type, level ) {
var method = type.toLowerCase();
exports[ method ] = log.bind( exports, type, level, false );
exports[ method ].json = log.bind( exports, type, level, true );
if ( new RegExp( '\\b' + type + '\\b', 'i' ).test( env ) ) {
flags.push( level );
}
});
loglevel = Math.min.apply( Math, flags );
} | javascript | function initialize() {
var flags = [];
Object.keys( levels ).forEach(function( type, level ) {
var method = type.toLowerCase();
exports[ method ] = log.bind( exports, type, level, false );
exports[ method ].json = log.bind( exports, type, level, true );
if ( new RegExp( '\\b' + type + '\\b', 'i' ).test( env ) ) {
flags.push( level );
}
});
loglevel = Math.min.apply( Math, flags );
} | [
"function",
"initialize",
"(",
")",
"{",
"var",
"flags",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"levels",
")",
".",
"forEach",
"(",
"function",
"(",
"type",
",",
"level",
")",
"{",
"var",
"method",
"=",
"type",
".",
"toLowerCase",
"(",
")",
";",
"exports",
"[",
"method",
"]",
"=",
"log",
".",
"bind",
"(",
"exports",
",",
"type",
",",
"level",
",",
"false",
")",
";",
"exports",
"[",
"method",
"]",
".",
"json",
"=",
"log",
".",
"bind",
"(",
"exports",
",",
"type",
",",
"level",
",",
"true",
")",
";",
"if",
"(",
"new",
"RegExp",
"(",
"'\\\\b'",
"+",
"type",
"+",
"'\\\\b'",
",",
"'i'",
")",
".",
"test",
"(",
"env",
")",
")",
"{",
"flags",
".",
"push",
"(",
"level",
")",
";",
"}",
"}",
")",
";",
"loglevel",
"=",
"Math",
".",
"min",
".",
"apply",
"(",
"Math",
",",
"flags",
")",
";",
"}"
]
| set loglevel based on NODE_DEBUG env variable and create exported methods | [
"set",
"loglevel",
"based",
"on",
"NODE_DEBUG",
"env",
"variable",
"and",
"create",
"exported",
"methods"
]
| f06d5c774de1e2ae94bb67f15457757530f061a1 | https://github.com/kevincennis/logbro/blob/f06d5c774de1e2ae94bb67f15457757530f061a1/lib/logbro.js#L31-L44 |
43,984 | kevincennis/logbro | lib/logbro.js | format | function format( type, args ) {
var now = new Date().toISOString(),
tmpl = '[%s] %s: %s\n',
msg;
msg = args[ 0 ] instanceof Error ? args[ 0 ].stack :
util.format.apply( util, args );
return util.format( tmpl, now, type, msg );
} | javascript | function format( type, args ) {
var now = new Date().toISOString(),
tmpl = '[%s] %s: %s\n',
msg;
msg = args[ 0 ] instanceof Error ? args[ 0 ].stack :
util.format.apply( util, args );
return util.format( tmpl, now, type, msg );
} | [
"function",
"format",
"(",
"type",
",",
"args",
")",
"{",
"var",
"now",
"=",
"new",
"Date",
"(",
")",
".",
"toISOString",
"(",
")",
",",
"tmpl",
"=",
"'[%s] %s: %s\\n'",
",",
"msg",
";",
"msg",
"=",
"args",
"[",
"0",
"]",
"instanceof",
"Error",
"?",
"args",
"[",
"0",
"]",
".",
"stack",
":",
"util",
".",
"format",
".",
"apply",
"(",
"util",
",",
"args",
")",
";",
"return",
"util",
".",
"format",
"(",
"tmpl",
",",
"now",
",",
"type",
",",
"msg",
")",
";",
"}"
]
| format log messages | [
"format",
"log",
"messages"
]
| f06d5c774de1e2ae94bb67f15457757530f061a1 | https://github.com/kevincennis/logbro/blob/f06d5c774de1e2ae94bb67f15457757530f061a1/lib/logbro.js#L47-L56 |
43,985 | xiaoyann/deploy-kit | bin/parse.js | readConfig | function readConfig() {
let options = {}
let cFile = ''
if (program.config) {
cFile = path.resolve(cwd, program.config)
if (fs.existsSync(cFile)) {
Object.assign(config, require(cFile))
} else {
console.warn(`Cannot find configuration file ${program.config}`)
process.exit()
}
} else {
cFile = path.resolve(cwd, 'deploy.js')
}
if (fs.existsSync(cFile)) {
options = require(cFile)
}
;['server', 'ignore'].forEach(function(name) {
if (typeof program[name] !== 'undefined') {
options[name] = program[name]
}
})
if (program.args[0]) {
options.workspace = path.resolve(cwd, program.args[0])
}
if (program.args[1]) {
options.deployTo = program.args[1]
}
return options
} | javascript | function readConfig() {
let options = {}
let cFile = ''
if (program.config) {
cFile = path.resolve(cwd, program.config)
if (fs.existsSync(cFile)) {
Object.assign(config, require(cFile))
} else {
console.warn(`Cannot find configuration file ${program.config}`)
process.exit()
}
} else {
cFile = path.resolve(cwd, 'deploy.js')
}
if (fs.existsSync(cFile)) {
options = require(cFile)
}
;['server', 'ignore'].forEach(function(name) {
if (typeof program[name] !== 'undefined') {
options[name] = program[name]
}
})
if (program.args[0]) {
options.workspace = path.resolve(cwd, program.args[0])
}
if (program.args[1]) {
options.deployTo = program.args[1]
}
return options
} | [
"function",
"readConfig",
"(",
")",
"{",
"let",
"options",
"=",
"{",
"}",
"let",
"cFile",
"=",
"''",
"if",
"(",
"program",
".",
"config",
")",
"{",
"cFile",
"=",
"path",
".",
"resolve",
"(",
"cwd",
",",
"program",
".",
"config",
")",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"cFile",
")",
")",
"{",
"Object",
".",
"assign",
"(",
"config",
",",
"require",
"(",
"cFile",
")",
")",
"}",
"else",
"{",
"console",
".",
"warn",
"(",
"`",
"${",
"program",
".",
"config",
"}",
"`",
")",
"process",
".",
"exit",
"(",
")",
"}",
"}",
"else",
"{",
"cFile",
"=",
"path",
".",
"resolve",
"(",
"cwd",
",",
"'deploy.js'",
")",
"}",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"cFile",
")",
")",
"{",
"options",
"=",
"require",
"(",
"cFile",
")",
"}",
";",
"[",
"'server'",
",",
"'ignore'",
"]",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"if",
"(",
"typeof",
"program",
"[",
"name",
"]",
"!==",
"'undefined'",
")",
"{",
"options",
"[",
"name",
"]",
"=",
"program",
"[",
"name",
"]",
"}",
"}",
")",
"if",
"(",
"program",
".",
"args",
"[",
"0",
"]",
")",
"{",
"options",
".",
"workspace",
"=",
"path",
".",
"resolve",
"(",
"cwd",
",",
"program",
".",
"args",
"[",
"0",
"]",
")",
"}",
"if",
"(",
"program",
".",
"args",
"[",
"1",
"]",
")",
"{",
"options",
".",
"deployTo",
"=",
"program",
".",
"args",
"[",
"1",
"]",
"}",
"return",
"options",
"}"
]
| read configuration from local file | [
"read",
"configuration",
"from",
"local",
"file"
]
| df1fe0ac2dba02d78661ffbbe7c92e4c23aaed03 | https://github.com/xiaoyann/deploy-kit/blob/df1fe0ac2dba02d78661ffbbe7c92e4c23aaed03/bin/parse.js#L57-L92 |
43,986 | vphantom/js-jrpc | jrpc.js | shutdown | function shutdown() {
var instance = this;
instance.active = false;
instance.transmitter = null;
instance.remoteTimeout = 0;
instance.localTimeout = 0;
instance.localComponents = {};
instance.remoteComponents = {};
instance.outbox.requests.length = 0;
instance.outbox.responses.length = 0;
instance.inbox = {};
instance.exposed = {};
Object.keys(instance.localTimers).forEach(function(key) {
clearTimeout(instance.localTimers[key]);
delete instance.localTimers[key];
});
Object.keys(instance.outTimers).forEach(function(key) {
clearTimeout(instance.outTimers[key]);
delete instance.outTimers[key];
});
return instance;
} | javascript | function shutdown() {
var instance = this;
instance.active = false;
instance.transmitter = null;
instance.remoteTimeout = 0;
instance.localTimeout = 0;
instance.localComponents = {};
instance.remoteComponents = {};
instance.outbox.requests.length = 0;
instance.outbox.responses.length = 0;
instance.inbox = {};
instance.exposed = {};
Object.keys(instance.localTimers).forEach(function(key) {
clearTimeout(instance.localTimers[key]);
delete instance.localTimers[key];
});
Object.keys(instance.outTimers).forEach(function(key) {
clearTimeout(instance.outTimers[key]);
delete instance.outTimers[key];
});
return instance;
} | [
"function",
"shutdown",
"(",
")",
"{",
"var",
"instance",
"=",
"this",
";",
"instance",
".",
"active",
"=",
"false",
";",
"instance",
".",
"transmitter",
"=",
"null",
";",
"instance",
".",
"remoteTimeout",
"=",
"0",
";",
"instance",
".",
"localTimeout",
"=",
"0",
";",
"instance",
".",
"localComponents",
"=",
"{",
"}",
";",
"instance",
".",
"remoteComponents",
"=",
"{",
"}",
";",
"instance",
".",
"outbox",
".",
"requests",
".",
"length",
"=",
"0",
";",
"instance",
".",
"outbox",
".",
"responses",
".",
"length",
"=",
"0",
";",
"instance",
".",
"inbox",
"=",
"{",
"}",
";",
"instance",
".",
"exposed",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"instance",
".",
"localTimers",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"clearTimeout",
"(",
"instance",
".",
"localTimers",
"[",
"key",
"]",
")",
";",
"delete",
"instance",
".",
"localTimers",
"[",
"key",
"]",
";",
"}",
")",
";",
"Object",
".",
"keys",
"(",
"instance",
".",
"outTimers",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"clearTimeout",
"(",
"instance",
".",
"outTimers",
"[",
"key",
"]",
")",
";",
"delete",
"instance",
".",
"outTimers",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"instance",
";",
"}"
]
| Semi-destructor for limbo conditions
When we lose connection permanently, we help garbage collection by removing
as many references as we can, including cancelling any outstanding timers.
We may still get some callbacks, but they will immediately return.
@return {undefined} No return value | [
"Semi",
"-",
"destructor",
"for",
"limbo",
"conditions"
]
| d9f4c040418b24b92dafc124613bd699015e620e | https://github.com/vphantom/js-jrpc/blob/d9f4c040418b24b92dafc124613bd699015e620e/jrpc.js#L77-L102 |
43,987 | vphantom/js-jrpc | jrpc.js | confirmTransmit | function confirmTransmit(outpacket, err) {
if (this.active && err) {
// Roll it all back into outbox (which may not be empty anymore)
if (outpacket.responses.length > 0) {
Array.prototype.push.apply(this.outbox.responses, outpacket.responses);
}
if (outpacket.requests.length > 0) {
Array.prototype.push.apply(this.outbox.requests, outpacket.requests);
}
}
} | javascript | function confirmTransmit(outpacket, err) {
if (this.active && err) {
// Roll it all back into outbox (which may not be empty anymore)
if (outpacket.responses.length > 0) {
Array.prototype.push.apply(this.outbox.responses, outpacket.responses);
}
if (outpacket.requests.length > 0) {
Array.prototype.push.apply(this.outbox.requests, outpacket.requests);
}
}
} | [
"function",
"confirmTransmit",
"(",
"outpacket",
",",
"err",
")",
"{",
"if",
"(",
"this",
".",
"active",
"&&",
"err",
")",
"{",
"// Roll it all back into outbox (which may not be empty anymore)",
"if",
"(",
"outpacket",
".",
"responses",
".",
"length",
">",
"0",
")",
"{",
"Array",
".",
"prototype",
".",
"push",
".",
"apply",
"(",
"this",
".",
"outbox",
".",
"responses",
",",
"outpacket",
".",
"responses",
")",
";",
"}",
"if",
"(",
"outpacket",
".",
"requests",
".",
"length",
">",
"0",
")",
"{",
"Array",
".",
"prototype",
".",
"push",
".",
"apply",
"(",
"this",
".",
"outbox",
".",
"requests",
",",
"outpacket",
".",
"requests",
")",
";",
"}",
"}",
"}"
]
| Handle transmission errors
@type {JRPC~transmitConfirmCallback}
@param {Object} outpacket Outbox data of the attempted transmission
@param {boolean} err Anything non-falsey means an error occured
@return {undefined} No return value | [
"Handle",
"transmission",
"errors"
]
| d9f4c040418b24b92dafc124613bd699015e620e | https://github.com/vphantom/js-jrpc/blob/d9f4c040418b24b92dafc124613bd699015e620e/jrpc.js#L207-L217 |
43,988 | vphantom/js-jrpc | jrpc.js | receive | function receive(msg) {
var requests = [];
var responses = [];
if (!this.active) {
return this;
}
// If we got JSON, parse it
if (typeof msg === 'string') {
try {
msg = JSON.parse(msg);
} catch (e) {
// The specification doesn't force us to respond in error, ignoring
return this;
}
}
// If we get a standard single-type batch, dispatch it
if (msg.constructor === Array) {
if (msg.length === 0) {
return this;
}
// Hint of request batch
if (typeof msg[0].method === 'string') {
requests = msg;
} else {
responses = msg;
}
} else if (typeof msg === 'object') {
// Could we be a 'dual-batch' extended message?
if (
typeof msg.requests !== 'undefined'
&& typeof msg.responses !== 'undefined'
) {
requests = msg.requests;
responses = msg.responses;
} else if (typeof msg.method === 'string') {
// We're a single request
requests.push(msg);
} else {
// We must be a single response
responses.push(msg);
}
}
responses.forEach(deliverResponse.bind(this));
requests.forEach(serveRequest.bind(this));
return this;
} | javascript | function receive(msg) {
var requests = [];
var responses = [];
if (!this.active) {
return this;
}
// If we got JSON, parse it
if (typeof msg === 'string') {
try {
msg = JSON.parse(msg);
} catch (e) {
// The specification doesn't force us to respond in error, ignoring
return this;
}
}
// If we get a standard single-type batch, dispatch it
if (msg.constructor === Array) {
if (msg.length === 0) {
return this;
}
// Hint of request batch
if (typeof msg[0].method === 'string') {
requests = msg;
} else {
responses = msg;
}
} else if (typeof msg === 'object') {
// Could we be a 'dual-batch' extended message?
if (
typeof msg.requests !== 'undefined'
&& typeof msg.responses !== 'undefined'
) {
requests = msg.requests;
responses = msg.responses;
} else if (typeof msg.method === 'string') {
// We're a single request
requests.push(msg);
} else {
// We must be a single response
responses.push(msg);
}
}
responses.forEach(deliverResponse.bind(this));
requests.forEach(serveRequest.bind(this));
return this;
} | [
"function",
"receive",
"(",
"msg",
")",
"{",
"var",
"requests",
"=",
"[",
"]",
";",
"var",
"responses",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"this",
".",
"active",
")",
"{",
"return",
"this",
";",
"}",
"// If we got JSON, parse it",
"if",
"(",
"typeof",
"msg",
"===",
"'string'",
")",
"{",
"try",
"{",
"msg",
"=",
"JSON",
".",
"parse",
"(",
"msg",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// The specification doesn't force us to respond in error, ignoring",
"return",
"this",
";",
"}",
"}",
"// If we get a standard single-type batch, dispatch it",
"if",
"(",
"msg",
".",
"constructor",
"===",
"Array",
")",
"{",
"if",
"(",
"msg",
".",
"length",
"===",
"0",
")",
"{",
"return",
"this",
";",
"}",
"// Hint of request batch",
"if",
"(",
"typeof",
"msg",
"[",
"0",
"]",
".",
"method",
"===",
"'string'",
")",
"{",
"requests",
"=",
"msg",
";",
"}",
"else",
"{",
"responses",
"=",
"msg",
";",
"}",
"}",
"else",
"if",
"(",
"typeof",
"msg",
"===",
"'object'",
")",
"{",
"// Could we be a 'dual-batch' extended message?",
"if",
"(",
"typeof",
"msg",
".",
"requests",
"!==",
"'undefined'",
"&&",
"typeof",
"msg",
".",
"responses",
"!==",
"'undefined'",
")",
"{",
"requests",
"=",
"msg",
".",
"requests",
";",
"responses",
"=",
"msg",
".",
"responses",
";",
"}",
"else",
"if",
"(",
"typeof",
"msg",
".",
"method",
"===",
"'string'",
")",
"{",
"// We're a single request",
"requests",
".",
"push",
"(",
"msg",
")",
";",
"}",
"else",
"{",
"// We must be a single response",
"responses",
".",
"push",
"(",
"msg",
")",
";",
"}",
"}",
"responses",
".",
"forEach",
"(",
"deliverResponse",
".",
"bind",
"(",
"this",
")",
")",
";",
"requests",
".",
"forEach",
"(",
"serveRequest",
".",
"bind",
"(",
"this",
")",
")",
";",
"return",
"this",
";",
"}"
]
| Handle incoming message
@param {string} msg JSON message to parse
@return {JRPC} This instance, for chaining | [
"Handle",
"incoming",
"message"
]
| d9f4c040418b24b92dafc124613bd699015e620e | https://github.com/vphantom/js-jrpc/blob/d9f4c040418b24b92dafc124613bd699015e620e/jrpc.js#L226-L275 |
43,989 | vphantom/js-jrpc | jrpc.js | upgrade | function upgrade() {
if (!this.active) {
return this;
}
return this.call(
'system.listComponents',
this.localComponents,
(function(err, result) {
if (!err && typeof result === 'object') {
this.remoteComponents = result;
this.remoteComponents['system._upgraded'] = true;
}
}).bind(this)
);
} | javascript | function upgrade() {
if (!this.active) {
return this;
}
return this.call(
'system.listComponents',
this.localComponents,
(function(err, result) {
if (!err && typeof result === 'object') {
this.remoteComponents = result;
this.remoteComponents['system._upgraded'] = true;
}
}).bind(this)
);
} | [
"function",
"upgrade",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"active",
")",
"{",
"return",
"this",
";",
"}",
"return",
"this",
".",
"call",
"(",
"'system.listComponents'",
",",
"this",
".",
"localComponents",
",",
"(",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"!",
"err",
"&&",
"typeof",
"result",
"===",
"'object'",
")",
"{",
"this",
".",
"remoteComponents",
"=",
"result",
";",
"this",
".",
"remoteComponents",
"[",
"'system._upgraded'",
"]",
"=",
"true",
";",
"}",
"}",
")",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
]
| Handshake to discover remote extended capabilities
@return {JRPC} This instance, for chaining | [
"Handshake",
"to",
"discover",
"remote",
"extended",
"capabilities"
]
| d9f4c040418b24b92dafc124613bd699015e620e | https://github.com/vphantom/js-jrpc/blob/d9f4c040418b24b92dafc124613bd699015e620e/jrpc.js#L282-L296 |
43,990 | vphantom/js-jrpc | jrpc.js | call | function call(methodName, params, next) {
var request = {
jsonrpc: '2.0',
method : methodName
};
if (!this.active) {
return this;
}
if (typeof params === 'function') {
next = params;
params = null;
}
if (
'system._upgraded' in this.remoteComponents
&& !(methodName in this.remoteComponents)
) {
// We're upgraded, yet method name isn't found, immediate error!
if (typeof next === 'function') {
setImmediate(next, {
code : -32601,
message: 'Unknown remote method'
});
}
return this;
}
if (typeof params === 'object') {
request.params = params;
}
this.serial++;
if (typeof next === 'function') {
request.id = this.serial;
this.inbox[this.serial] = next;
}
this.outbox.requests.push(request);
// If we're interactive, send the new request
this.transmit();
if (typeof next !== 'function') {
return this;
}
if (this.remoteTimeout > 0) {
this.outTimers[this.serial] = setTimeout(
deliverResponse.bind(
this,
{
jsonrpc: '2.0',
id : this.serial,
error : {
code : -1000,
message: 'Timed out waiting for response'
}
}
),
this.remoteTimeout
);
} else {
this.outTimers[this.serial] = true; // Placeholder
}
return this;
} | javascript | function call(methodName, params, next) {
var request = {
jsonrpc: '2.0',
method : methodName
};
if (!this.active) {
return this;
}
if (typeof params === 'function') {
next = params;
params = null;
}
if (
'system._upgraded' in this.remoteComponents
&& !(methodName in this.remoteComponents)
) {
// We're upgraded, yet method name isn't found, immediate error!
if (typeof next === 'function') {
setImmediate(next, {
code : -32601,
message: 'Unknown remote method'
});
}
return this;
}
if (typeof params === 'object') {
request.params = params;
}
this.serial++;
if (typeof next === 'function') {
request.id = this.serial;
this.inbox[this.serial] = next;
}
this.outbox.requests.push(request);
// If we're interactive, send the new request
this.transmit();
if (typeof next !== 'function') {
return this;
}
if (this.remoteTimeout > 0) {
this.outTimers[this.serial] = setTimeout(
deliverResponse.bind(
this,
{
jsonrpc: '2.0',
id : this.serial,
error : {
code : -1000,
message: 'Timed out waiting for response'
}
}
),
this.remoteTimeout
);
} else {
this.outTimers[this.serial] = true; // Placeholder
}
return this;
} | [
"function",
"call",
"(",
"methodName",
",",
"params",
",",
"next",
")",
"{",
"var",
"request",
"=",
"{",
"jsonrpc",
":",
"'2.0'",
",",
"method",
":",
"methodName",
"}",
";",
"if",
"(",
"!",
"this",
".",
"active",
")",
"{",
"return",
"this",
";",
"}",
"if",
"(",
"typeof",
"params",
"===",
"'function'",
")",
"{",
"next",
"=",
"params",
";",
"params",
"=",
"null",
";",
"}",
"if",
"(",
"'system._upgraded'",
"in",
"this",
".",
"remoteComponents",
"&&",
"!",
"(",
"methodName",
"in",
"this",
".",
"remoteComponents",
")",
")",
"{",
"// We're upgraded, yet method name isn't found, immediate error!",
"if",
"(",
"typeof",
"next",
"===",
"'function'",
")",
"{",
"setImmediate",
"(",
"next",
",",
"{",
"code",
":",
"-",
"32601",
",",
"message",
":",
"'Unknown remote method'",
"}",
")",
";",
"}",
"return",
"this",
";",
"}",
"if",
"(",
"typeof",
"params",
"===",
"'object'",
")",
"{",
"request",
".",
"params",
"=",
"params",
";",
"}",
"this",
".",
"serial",
"++",
";",
"if",
"(",
"typeof",
"next",
"===",
"'function'",
")",
"{",
"request",
".",
"id",
"=",
"this",
".",
"serial",
";",
"this",
".",
"inbox",
"[",
"this",
".",
"serial",
"]",
"=",
"next",
";",
"}",
"this",
".",
"outbox",
".",
"requests",
".",
"push",
"(",
"request",
")",
";",
"// If we're interactive, send the new request",
"this",
".",
"transmit",
"(",
")",
";",
"if",
"(",
"typeof",
"next",
"!==",
"'function'",
")",
"{",
"return",
"this",
";",
"}",
"if",
"(",
"this",
".",
"remoteTimeout",
">",
"0",
")",
"{",
"this",
".",
"outTimers",
"[",
"this",
".",
"serial",
"]",
"=",
"setTimeout",
"(",
"deliverResponse",
".",
"bind",
"(",
"this",
",",
"{",
"jsonrpc",
":",
"'2.0'",
",",
"id",
":",
"this",
".",
"serial",
",",
"error",
":",
"{",
"code",
":",
"-",
"1000",
",",
"message",
":",
"'Timed out waiting for response'",
"}",
"}",
")",
",",
"this",
".",
"remoteTimeout",
")",
";",
"}",
"else",
"{",
"this",
".",
"outTimers",
"[",
"this",
".",
"serial",
"]",
"=",
"true",
";",
"// Placeholder",
"}",
"return",
"this",
";",
"}"
]
| Client side
Queue up a remote method call
@param {string} methodName Name of method to call
@param {(Object|Array|null)} [params] Parameters
@param {JRPC~receiveCallback} [next] Callback to receive result
@return {JRPC} This instance, for chaining | [
"Client",
"side",
"Queue",
"up",
"a",
"remote",
"method",
"call"
]
| d9f4c040418b24b92dafc124613bd699015e620e | https://github.com/vphantom/js-jrpc/blob/d9f4c040418b24b92dafc124613bd699015e620e/jrpc.js#L310-L376 |
43,991 | vphantom/js-jrpc | jrpc.js | deliverResponse | function deliverResponse(res) {
var err = false;
var result = null;
if (this.active && 'id' in res && res['id'] in this.outTimers) {
clearTimeout(this.outTimers[res['id']]); // Passing true instead of a timeout is safe
delete this.outTimers[res['id']];
} else {
// Silently ignoring second response to same request
return;
}
if (res['id'] in this.inbox) {
if ('error' in res) {
err = res['error'];
} else {
result = res['result'];
}
setImmediate(this.inbox[res['id']], err, result);
delete this.inbox[res['id']];
}
// Silently ignore timeout duplicate and malformed responses
} | javascript | function deliverResponse(res) {
var err = false;
var result = null;
if (this.active && 'id' in res && res['id'] in this.outTimers) {
clearTimeout(this.outTimers[res['id']]); // Passing true instead of a timeout is safe
delete this.outTimers[res['id']];
} else {
// Silently ignoring second response to same request
return;
}
if (res['id'] in this.inbox) {
if ('error' in res) {
err = res['error'];
} else {
result = res['result'];
}
setImmediate(this.inbox[res['id']], err, result);
delete this.inbox[res['id']];
}
// Silently ignore timeout duplicate and malformed responses
} | [
"function",
"deliverResponse",
"(",
"res",
")",
"{",
"var",
"err",
"=",
"false",
";",
"var",
"result",
"=",
"null",
";",
"if",
"(",
"this",
".",
"active",
"&&",
"'id'",
"in",
"res",
"&&",
"res",
"[",
"'id'",
"]",
"in",
"this",
".",
"outTimers",
")",
"{",
"clearTimeout",
"(",
"this",
".",
"outTimers",
"[",
"res",
"[",
"'id'",
"]",
"]",
")",
";",
"// Passing true instead of a timeout is safe",
"delete",
"this",
".",
"outTimers",
"[",
"res",
"[",
"'id'",
"]",
"]",
";",
"}",
"else",
"{",
"// Silently ignoring second response to same request",
"return",
";",
"}",
"if",
"(",
"res",
"[",
"'id'",
"]",
"in",
"this",
".",
"inbox",
")",
"{",
"if",
"(",
"'error'",
"in",
"res",
")",
"{",
"err",
"=",
"res",
"[",
"'error'",
"]",
";",
"}",
"else",
"{",
"result",
"=",
"res",
"[",
"'result'",
"]",
";",
"}",
"setImmediate",
"(",
"this",
".",
"inbox",
"[",
"res",
"[",
"'id'",
"]",
"]",
",",
"err",
",",
"result",
")",
";",
"delete",
"this",
".",
"inbox",
"[",
"res",
"[",
"'id'",
"]",
"]",
";",
"}",
"// Silently ignore timeout duplicate and malformed responses",
"}"
]
| Callback invoked when remote results are ready
@callback JRPC~receiveCallback
@param {boolean} err True if the result is an error or unavailable
@param {Object} result The result from the remote method
@return {undefined} No return value
Deliver a received result
@param {Object} res The single result to parse
@return {undefined} No return value | [
"Callback",
"invoked",
"when",
"remote",
"results",
"are",
"ready"
]
| d9f4c040418b24b92dafc124613bd699015e620e | https://github.com/vphantom/js-jrpc/blob/d9f4c040418b24b92dafc124613bd699015e620e/jrpc.js#L396-L418 |
43,992 | vphantom/js-jrpc | jrpc.js | expose | function expose(subject, callback) {
var name;
if (!this.active) {
return this;
}
if (typeof subject === 'string') {
this.localComponents[subject] = true;
this.exposed[subject] = callback;
} else if (typeof subject === 'object') {
for (name in subject) {
if (subject.hasOwnProperty(name)) {
this.localComponents[name] = true;
this.exposed[name] = subject[name];
}
}
}
return this;
} | javascript | function expose(subject, callback) {
var name;
if (!this.active) {
return this;
}
if (typeof subject === 'string') {
this.localComponents[subject] = true;
this.exposed[subject] = callback;
} else if (typeof subject === 'object') {
for (name in subject) {
if (subject.hasOwnProperty(name)) {
this.localComponents[name] = true;
this.exposed[name] = subject[name];
}
}
}
return this;
} | [
"function",
"expose",
"(",
"subject",
",",
"callback",
")",
"{",
"var",
"name",
";",
"if",
"(",
"!",
"this",
".",
"active",
")",
"{",
"return",
"this",
";",
"}",
"if",
"(",
"typeof",
"subject",
"===",
"'string'",
")",
"{",
"this",
".",
"localComponents",
"[",
"subject",
"]",
"=",
"true",
";",
"this",
".",
"exposed",
"[",
"subject",
"]",
"=",
"callback",
";",
"}",
"else",
"if",
"(",
"typeof",
"subject",
"===",
"'object'",
")",
"{",
"for",
"(",
"name",
"in",
"subject",
")",
"{",
"if",
"(",
"subject",
".",
"hasOwnProperty",
"(",
"name",
")",
")",
"{",
"this",
".",
"localComponents",
"[",
"name",
"]",
"=",
"true",
";",
"this",
".",
"exposed",
"[",
"name",
"]",
"=",
"subject",
"[",
"name",
"]",
";",
"}",
"}",
"}",
"return",
"this",
";",
"}"
]
| Server side
Expose a single or collection of methods to remote end
@param {(Object|String)} subject Name of method or direct object
@param {JRPC~serviceCallback} [callback] Callback to handle requests
@return {JRPC} This instance, for chaining | [
"Server",
"side",
"Expose",
"a",
"single",
"or",
"collection",
"of",
"methods",
"to",
"remote",
"end"
]
| d9f4c040418b24b92dafc124613bd699015e620e | https://github.com/vphantom/js-jrpc/blob/d9f4c040418b24b92dafc124613bd699015e620e/jrpc.js#L431-L451 |
43,993 | vphantom/js-jrpc | jrpc.js | serveRequest | function serveRequest(request) {
var id = null;
var params = null;
if (!this.active || typeof request !== 'object' || request === null) {
return;
}
if (!(typeof request.jsonrpc === 'string' && request.jsonrpc === '2.0')) {
return;
}
id = (typeof request.id !== 'undefined' ? request.id : null);
if (typeof request.method !== 'string') {
if (id !== null) {
this.localTimers[id] = true;
setImmediate(sendResponse.bind(this, id, -32600));
}
return;
}
if (!(request.method in this.exposed)) {
if (id !== null) {
this.localTimers[id] = true;
setImmediate(sendResponse.bind(this, id, -32601));
}
return;
}
if ('params' in request) {
if (typeof request['params'] === 'object') {
params = request['params'];
} else {
if (id !== null) {
this.localTimers[id] = true;
setImmediate(sendResponse.bind(this, id, -32602));
}
return;
}
}
if (id !== null) {
if (this.localTimeout > 0) {
this.localTimers[id] = setTimeout(
sendResponse.bind(
this,
id,
{
code : -1002,
message: 'Method handler timed out'
}
),
this.localTimeout
);
} else {
this.localTimers[id] = true;
}
}
setImmediate(
this.exposed[request.method],
params,
sendResponse.bind(this, id)
);
return;
} | javascript | function serveRequest(request) {
var id = null;
var params = null;
if (!this.active || typeof request !== 'object' || request === null) {
return;
}
if (!(typeof request.jsonrpc === 'string' && request.jsonrpc === '2.0')) {
return;
}
id = (typeof request.id !== 'undefined' ? request.id : null);
if (typeof request.method !== 'string') {
if (id !== null) {
this.localTimers[id] = true;
setImmediate(sendResponse.bind(this, id, -32600));
}
return;
}
if (!(request.method in this.exposed)) {
if (id !== null) {
this.localTimers[id] = true;
setImmediate(sendResponse.bind(this, id, -32601));
}
return;
}
if ('params' in request) {
if (typeof request['params'] === 'object') {
params = request['params'];
} else {
if (id !== null) {
this.localTimers[id] = true;
setImmediate(sendResponse.bind(this, id, -32602));
}
return;
}
}
if (id !== null) {
if (this.localTimeout > 0) {
this.localTimers[id] = setTimeout(
sendResponse.bind(
this,
id,
{
code : -1002,
message: 'Method handler timed out'
}
),
this.localTimeout
);
} else {
this.localTimers[id] = true;
}
}
setImmediate(
this.exposed[request.method],
params,
sendResponse.bind(this, id)
);
return;
} | [
"function",
"serveRequest",
"(",
"request",
")",
"{",
"var",
"id",
"=",
"null",
";",
"var",
"params",
"=",
"null",
";",
"if",
"(",
"!",
"this",
".",
"active",
"||",
"typeof",
"request",
"!==",
"'object'",
"||",
"request",
"===",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"(",
"typeof",
"request",
".",
"jsonrpc",
"===",
"'string'",
"&&",
"request",
".",
"jsonrpc",
"===",
"'2.0'",
")",
")",
"{",
"return",
";",
"}",
"id",
"=",
"(",
"typeof",
"request",
".",
"id",
"!==",
"'undefined'",
"?",
"request",
".",
"id",
":",
"null",
")",
";",
"if",
"(",
"typeof",
"request",
".",
"method",
"!==",
"'string'",
")",
"{",
"if",
"(",
"id",
"!==",
"null",
")",
"{",
"this",
".",
"localTimers",
"[",
"id",
"]",
"=",
"true",
";",
"setImmediate",
"(",
"sendResponse",
".",
"bind",
"(",
"this",
",",
"id",
",",
"-",
"32600",
")",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"!",
"(",
"request",
".",
"method",
"in",
"this",
".",
"exposed",
")",
")",
"{",
"if",
"(",
"id",
"!==",
"null",
")",
"{",
"this",
".",
"localTimers",
"[",
"id",
"]",
"=",
"true",
";",
"setImmediate",
"(",
"sendResponse",
".",
"bind",
"(",
"this",
",",
"id",
",",
"-",
"32601",
")",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"'params'",
"in",
"request",
")",
"{",
"if",
"(",
"typeof",
"request",
"[",
"'params'",
"]",
"===",
"'object'",
")",
"{",
"params",
"=",
"request",
"[",
"'params'",
"]",
";",
"}",
"else",
"{",
"if",
"(",
"id",
"!==",
"null",
")",
"{",
"this",
".",
"localTimers",
"[",
"id",
"]",
"=",
"true",
";",
"setImmediate",
"(",
"sendResponse",
".",
"bind",
"(",
"this",
",",
"id",
",",
"-",
"32602",
")",
")",
";",
"}",
"return",
";",
"}",
"}",
"if",
"(",
"id",
"!==",
"null",
")",
"{",
"if",
"(",
"this",
".",
"localTimeout",
">",
"0",
")",
"{",
"this",
".",
"localTimers",
"[",
"id",
"]",
"=",
"setTimeout",
"(",
"sendResponse",
".",
"bind",
"(",
"this",
",",
"id",
",",
"{",
"code",
":",
"-",
"1002",
",",
"message",
":",
"'Method handler timed out'",
"}",
")",
",",
"this",
".",
"localTimeout",
")",
";",
"}",
"else",
"{",
"this",
".",
"localTimers",
"[",
"id",
"]",
"=",
"true",
";",
"}",
"}",
"setImmediate",
"(",
"this",
".",
"exposed",
"[",
"request",
".",
"method",
"]",
",",
"params",
",",
"sendResponse",
".",
"bind",
"(",
"this",
",",
"id",
")",
")",
";",
"return",
";",
"}"
]
| Callback invoked to handle calls to our side's methods
@callback JRPC~serviceCallback
@param {(Object|Array|null)} params Parameters received
@param {JRPC~serviceResultCallback} next Callback to send your result
@return {undefined} No return value
Serve a request we received
@param {Object} request Request to parse
@return {undefined} No return value | [
"Callback",
"invoked",
"to",
"handle",
"calls",
"to",
"our",
"side",
"s",
"methods"
]
| d9f4c040418b24b92dafc124613bd699015e620e | https://github.com/vphantom/js-jrpc/blob/d9f4c040418b24b92dafc124613bd699015e620e/jrpc.js#L471-L536 |
43,994 | vphantom/js-jrpc | jrpc.js | sendResponse | function sendResponse(id, err, result) {
var response = {
jsonrpc: '2.0',
id : id
};
if (id === null) {
return;
}
if (this.active && id in this.localTimers) {
clearTimeout(this.localTimers[id]); // Passing true instead of a timeout is safe
delete this.localTimers[id];
} else {
// Silently ignoring second response to same request
return;
}
if (typeof err !== 'undefined' && err !== null && err !== false) {
if (typeof err === 'number') {
response.error = {
code : err,
message: 'error'
};
} else if (err === true) {
response.error = {
code : -1,
message: 'error'
};
} else if (typeof err === 'string') {
response.error = {
code : -1,
message: err
};
} else if (
typeof err === 'object'
&& 'code' in err
&& 'message' in err
) {
response.error = err;
} else {
response.error = {
code : -2,
message: 'error',
data : err
};
}
} else {
response.result = result;
}
this.outbox.responses.push(response);
// If we're interactive, send the new response
this.transmit();
} | javascript | function sendResponse(id, err, result) {
var response = {
jsonrpc: '2.0',
id : id
};
if (id === null) {
return;
}
if (this.active && id in this.localTimers) {
clearTimeout(this.localTimers[id]); // Passing true instead of a timeout is safe
delete this.localTimers[id];
} else {
// Silently ignoring second response to same request
return;
}
if (typeof err !== 'undefined' && err !== null && err !== false) {
if (typeof err === 'number') {
response.error = {
code : err,
message: 'error'
};
} else if (err === true) {
response.error = {
code : -1,
message: 'error'
};
} else if (typeof err === 'string') {
response.error = {
code : -1,
message: err
};
} else if (
typeof err === 'object'
&& 'code' in err
&& 'message' in err
) {
response.error = err;
} else {
response.error = {
code : -2,
message: 'error',
data : err
};
}
} else {
response.result = result;
}
this.outbox.responses.push(response);
// If we're interactive, send the new response
this.transmit();
} | [
"function",
"sendResponse",
"(",
"id",
",",
"err",
",",
"result",
")",
"{",
"var",
"response",
"=",
"{",
"jsonrpc",
":",
"'2.0'",
",",
"id",
":",
"id",
"}",
";",
"if",
"(",
"id",
"===",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"this",
".",
"active",
"&&",
"id",
"in",
"this",
".",
"localTimers",
")",
"{",
"clearTimeout",
"(",
"this",
".",
"localTimers",
"[",
"id",
"]",
")",
";",
"// Passing true instead of a timeout is safe",
"delete",
"this",
".",
"localTimers",
"[",
"id",
"]",
";",
"}",
"else",
"{",
"// Silently ignoring second response to same request",
"return",
";",
"}",
"if",
"(",
"typeof",
"err",
"!==",
"'undefined'",
"&&",
"err",
"!==",
"null",
"&&",
"err",
"!==",
"false",
")",
"{",
"if",
"(",
"typeof",
"err",
"===",
"'number'",
")",
"{",
"response",
".",
"error",
"=",
"{",
"code",
":",
"err",
",",
"message",
":",
"'error'",
"}",
";",
"}",
"else",
"if",
"(",
"err",
"===",
"true",
")",
"{",
"response",
".",
"error",
"=",
"{",
"code",
":",
"-",
"1",
",",
"message",
":",
"'error'",
"}",
";",
"}",
"else",
"if",
"(",
"typeof",
"err",
"===",
"'string'",
")",
"{",
"response",
".",
"error",
"=",
"{",
"code",
":",
"-",
"1",
",",
"message",
":",
"err",
"}",
";",
"}",
"else",
"if",
"(",
"typeof",
"err",
"===",
"'object'",
"&&",
"'code'",
"in",
"err",
"&&",
"'message'",
"in",
"err",
")",
"{",
"response",
".",
"error",
"=",
"err",
";",
"}",
"else",
"{",
"response",
".",
"error",
"=",
"{",
"code",
":",
"-",
"2",
",",
"message",
":",
"'error'",
",",
"data",
":",
"err",
"}",
";",
"}",
"}",
"else",
"{",
"response",
".",
"result",
"=",
"result",
";",
"}",
"this",
".",
"outbox",
".",
"responses",
".",
"push",
"(",
"response",
")",
";",
"// If we're interactive, send the new response",
"this",
".",
"transmit",
"(",
")",
";",
"}"
]
| Handle local method results
@type {JRPC~serviceResultCallback}
@param {number} id Serial number, bound, no need to supply
@param {boolean} err Anything non-falsey means error and is sent
@param {Object} result Any result you wish to produce
@return {undefined} No return value | [
"Handle",
"local",
"method",
"results"
]
| d9f4c040418b24b92dafc124613bd699015e620e | https://github.com/vphantom/js-jrpc/blob/d9f4c040418b24b92dafc124613bd699015e620e/jrpc.js#L549-L603 |
43,995 | ckknight/escort | lib/escort-client.js | function (route, converters) {
var literals = route.literals;
var params = route.params;
var conv = [];
var fun = "";
fun += "var generate = function (params) {\n";
fun += " if (arguments.length === 1 && typeof params === 'object' && params.constructor !== String) {\n";
fun += " return ";
fun += JSON.stringify(literals[0]);
for (var i = 0, len = params.length; i < len; i += 1) {
fun += "+converters[";
fun += i;
fun += "](params[";
fun += JSON.stringify(params[i].name);
fun += "])";
if (literals[i + 1]) {
fun += "+";
fun += JSON.stringify(literals[i + 1]);
}
var paramType = params[i].type;
if (!has.call(converters, paramType)) {
throw new Error("Unknown converter: " + paramType);
}
var converter = converters[paramType];
if (!converter) {
throw new Error("Misconfigured converter: " + paramType);
}
conv.push(converter(params[i]));
}
fun += ";\n";
fun += " }\n";
fun += " return generate({";
for (i = 0, len = params.length; i < len; i += 1) {
if (i > 0) {
fun += ", ";
}
fun += JSON.stringify(params[i].name);
fun += ":arguments[";
fun += i;
fun += "]";
}
fun += "});\n";
fun += "};\n";
fun += "return generate;\n";
return new Function("converters", fun)(conv);
} | javascript | function (route, converters) {
var literals = route.literals;
var params = route.params;
var conv = [];
var fun = "";
fun += "var generate = function (params) {\n";
fun += " if (arguments.length === 1 && typeof params === 'object' && params.constructor !== String) {\n";
fun += " return ";
fun += JSON.stringify(literals[0]);
for (var i = 0, len = params.length; i < len; i += 1) {
fun += "+converters[";
fun += i;
fun += "](params[";
fun += JSON.stringify(params[i].name);
fun += "])";
if (literals[i + 1]) {
fun += "+";
fun += JSON.stringify(literals[i + 1]);
}
var paramType = params[i].type;
if (!has.call(converters, paramType)) {
throw new Error("Unknown converter: " + paramType);
}
var converter = converters[paramType];
if (!converter) {
throw new Error("Misconfigured converter: " + paramType);
}
conv.push(converter(params[i]));
}
fun += ";\n";
fun += " }\n";
fun += " return generate({";
for (i = 0, len = params.length; i < len; i += 1) {
if (i > 0) {
fun += ", ";
}
fun += JSON.stringify(params[i].name);
fun += ":arguments[";
fun += i;
fun += "]";
}
fun += "});\n";
fun += "};\n";
fun += "return generate;\n";
return new Function("converters", fun)(conv);
} | [
"function",
"(",
"route",
",",
"converters",
")",
"{",
"var",
"literals",
"=",
"route",
".",
"literals",
";",
"var",
"params",
"=",
"route",
".",
"params",
";",
"var",
"conv",
"=",
"[",
"]",
";",
"var",
"fun",
"=",
"\"\"",
";",
"fun",
"+=",
"\"var generate = function (params) {\\n\"",
";",
"fun",
"+=",
"\" if (arguments.length === 1 && typeof params === 'object' && params.constructor !== String) {\\n\"",
";",
"fun",
"+=",
"\" return \"",
";",
"fun",
"+=",
"JSON",
".",
"stringify",
"(",
"literals",
"[",
"0",
"]",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"len",
"=",
"params",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"fun",
"+=",
"\"+converters[\"",
";",
"fun",
"+=",
"i",
";",
"fun",
"+=",
"\"](params[\"",
";",
"fun",
"+=",
"JSON",
".",
"stringify",
"(",
"params",
"[",
"i",
"]",
".",
"name",
")",
";",
"fun",
"+=",
"\"])\"",
";",
"if",
"(",
"literals",
"[",
"i",
"+",
"1",
"]",
")",
"{",
"fun",
"+=",
"\"+\"",
";",
"fun",
"+=",
"JSON",
".",
"stringify",
"(",
"literals",
"[",
"i",
"+",
"1",
"]",
")",
";",
"}",
"var",
"paramType",
"=",
"params",
"[",
"i",
"]",
".",
"type",
";",
"if",
"(",
"!",
"has",
".",
"call",
"(",
"converters",
",",
"paramType",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Unknown converter: \"",
"+",
"paramType",
")",
";",
"}",
"var",
"converter",
"=",
"converters",
"[",
"paramType",
"]",
";",
"if",
"(",
"!",
"converter",
")",
"{",
"throw",
"new",
"Error",
"(",
"\"Misconfigured converter: \"",
"+",
"paramType",
")",
";",
"}",
"conv",
".",
"push",
"(",
"converter",
"(",
"params",
"[",
"i",
"]",
")",
")",
";",
"}",
"fun",
"+=",
"\";\\n\"",
";",
"fun",
"+=",
"\" }\\n\"",
";",
"fun",
"+=",
"\" return generate({\"",
";",
"for",
"(",
"i",
"=",
"0",
",",
"len",
"=",
"params",
".",
"length",
";",
"i",
"<",
"len",
";",
"i",
"+=",
"1",
")",
"{",
"if",
"(",
"i",
">",
"0",
")",
"{",
"fun",
"+=",
"\", \"",
";",
"}",
"fun",
"+=",
"JSON",
".",
"stringify",
"(",
"params",
"[",
"i",
"]",
".",
"name",
")",
";",
"fun",
"+=",
"\":arguments[\"",
";",
"fun",
"+=",
"i",
";",
"fun",
"+=",
"\"]\"",
";",
"}",
"fun",
"+=",
"\"});\\n\"",
";",
"fun",
"+=",
"\"};\\n\"",
";",
"fun",
"+=",
"\"return generate;\\n\"",
";",
"return",
"new",
"Function",
"(",
"\"converters\"",
",",
"fun",
")",
"(",
"conv",
")",
";",
"}"
]
| Dynamically create a url-generation function.
@param {Object} route A descriptor for the route in question
@param {Object} converters A map of converter name to converter factory.
@return {Function} A function which will generate a URL.
@api private
@example generateUrlFunction({ literals: ["/prefix"], params: [ { name: "name", type: "string" } ] })({name: "hey"}) === "/prefix/hey" | [
"Dynamically",
"create",
"a",
"url",
"-",
"generation",
"function",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort-client.js#L40-L92 |
|
43,996 | ckknight/escort | lib/escort-client.js | function (routes, converters) {
var staticRoute, dynamicRoute;
// we traverse backwards because the beginning ones take precedence and thus can override.
for (var i = routes.length - 1; i >= 0; i -= 1) {
var route = routes[i];
if (route.path) {
staticRoute = route.path;
} else {
dynamicRoute = route;
}
}
if (dynamicRoute) {
dynamicRoute = generateDynamicUrlFunction(dynamicRoute, converters);
}
if (staticRoute) {
staticRoute = generateStaticUrlFunction(staticRoute);
if (dynamicRoute) {
// this can occur if the url is like "/posts" and "/posts/page/{page}"
return function () {
if (arguments.length === 0) {
return staticRoute();
} else {
return dynamicRoute.apply(this, slice.call(arguments, 0));
}
};
} else {
return staticRoute;
}
} else {
if (dynamicRoute) {
return dynamicRoute;
} else {
return null;
}
}
} | javascript | function (routes, converters) {
var staticRoute, dynamicRoute;
// we traverse backwards because the beginning ones take precedence and thus can override.
for (var i = routes.length - 1; i >= 0; i -= 1) {
var route = routes[i];
if (route.path) {
staticRoute = route.path;
} else {
dynamicRoute = route;
}
}
if (dynamicRoute) {
dynamicRoute = generateDynamicUrlFunction(dynamicRoute, converters);
}
if (staticRoute) {
staticRoute = generateStaticUrlFunction(staticRoute);
if (dynamicRoute) {
// this can occur if the url is like "/posts" and "/posts/page/{page}"
return function () {
if (arguments.length === 0) {
return staticRoute();
} else {
return dynamicRoute.apply(this, slice.call(arguments, 0));
}
};
} else {
return staticRoute;
}
} else {
if (dynamicRoute) {
return dynamicRoute;
} else {
return null;
}
}
} | [
"function",
"(",
"routes",
",",
"converters",
")",
"{",
"var",
"staticRoute",
",",
"dynamicRoute",
";",
"// we traverse backwards because the beginning ones take precedence and thus can override.",
"for",
"(",
"var",
"i",
"=",
"routes",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"-=",
"1",
")",
"{",
"var",
"route",
"=",
"routes",
"[",
"i",
"]",
";",
"if",
"(",
"route",
".",
"path",
")",
"{",
"staticRoute",
"=",
"route",
".",
"path",
";",
"}",
"else",
"{",
"dynamicRoute",
"=",
"route",
";",
"}",
"}",
"if",
"(",
"dynamicRoute",
")",
"{",
"dynamicRoute",
"=",
"generateDynamicUrlFunction",
"(",
"dynamicRoute",
",",
"converters",
")",
";",
"}",
"if",
"(",
"staticRoute",
")",
"{",
"staticRoute",
"=",
"generateStaticUrlFunction",
"(",
"staticRoute",
")",
";",
"if",
"(",
"dynamicRoute",
")",
"{",
"// this can occur if the url is like \"/posts\" and \"/posts/page/{page}\"",
"return",
"function",
"(",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"0",
")",
"{",
"return",
"staticRoute",
"(",
")",
";",
"}",
"else",
"{",
"return",
"dynamicRoute",
".",
"apply",
"(",
"this",
",",
"slice",
".",
"call",
"(",
"arguments",
",",
"0",
")",
")",
";",
"}",
"}",
";",
"}",
"else",
"{",
"return",
"staticRoute",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"dynamicRoute",
")",
"{",
"return",
"dynamicRoute",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"}"
]
| Generate a URL function based on the provided routes.
@param {Array} routes An array of route descriptors
@param {Object} converters A map of type to converter factory.
@return {Function} A function that will generate a URL, or null if routes is blank.
@api private | [
"Generate",
"a",
"URL",
"function",
"based",
"on",
"the",
"provided",
"routes",
"."
]
| 6afbe01d48881b7eaf092e7c2307ebd8ee65497e | https://github.com/ckknight/escort/blob/6afbe01d48881b7eaf092e7c2307ebd8ee65497e/lib/escort-client.js#L102-L140 |
|
43,997 | wala/jsdelta | src/file_util.js | getTempFileName | function getTempFileName(state) {
var fn = state.tmp_dir + "/delta_js_" + state.round + "." + state.ext;
state.round++;
return fn;
} | javascript | function getTempFileName(state) {
var fn = state.tmp_dir + "/delta_js_" + state.round + "." + state.ext;
state.round++;
return fn;
} | [
"function",
"getTempFileName",
"(",
"state",
")",
"{",
"var",
"fn",
"=",
"state",
".",
"tmp_dir",
"+",
"\"/delta_js_\"",
"+",
"state",
".",
"round",
"+",
"\".\"",
"+",
"state",
".",
"ext",
";",
"state",
".",
"round",
"++",
";",
"return",
"fn",
";",
"}"
]
| get name of current test case | [
"get",
"name",
"of",
"current",
"test",
"case"
]
| 355febea1ee23e9e909ba2bfa087ffb2499a3295 | https://github.com/wala/jsdelta/blob/355febea1ee23e9e909ba2bfa087ffb2499a3295/src/file_util.js#L8-L12 |
43,998 | wala/jsdelta | src/file_util.js | copyToOut | function copyToOut(src, out, multiFileMode) {
try {
fs.copySync(src, out);
fs.statSync(out)
return out;
} catch (err) {
}
} | javascript | function copyToOut(src, out, multiFileMode) {
try {
fs.copySync(src, out);
fs.statSync(out)
return out;
} catch (err) {
}
} | [
"function",
"copyToOut",
"(",
"src",
",",
"out",
",",
"multiFileMode",
")",
"{",
"try",
"{",
"fs",
".",
"copySync",
"(",
"src",
",",
"out",
")",
";",
"fs",
".",
"statSync",
"(",
"out",
")",
"return",
"out",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"}",
"}"
]
| Return path to file if copy was successful. Return undefined otherwise. | [
"Return",
"path",
"to",
"file",
"if",
"copy",
"was",
"successful",
".",
"Return",
"undefined",
"otherwise",
"."
]
| 355febea1ee23e9e909ba2bfa087ffb2499a3295 | https://github.com/wala/jsdelta/blob/355febea1ee23e9e909ba2bfa087ffb2499a3295/src/file_util.js#L62-L69 |
43,999 | WebReflection/es-class | build/es-class.max.amd.js | function (method) {
var
str = '' + method,
i = str.indexOf(SUPER)
;
return i < 0 ?
false :
isBoundary(str.charCodeAt(i - 1)) &&
isBoundary(str.charCodeAt(i + 5));
} | javascript | function (method) {
var
str = '' + method,
i = str.indexOf(SUPER)
;
return i < 0 ?
false :
isBoundary(str.charCodeAt(i - 1)) &&
isBoundary(str.charCodeAt(i + 5));
} | [
"function",
"(",
"method",
")",
"{",
"var",
"str",
"=",
"''",
"+",
"method",
",",
"i",
"=",
"str",
".",
"indexOf",
"(",
"SUPER",
")",
";",
"return",
"i",
"<",
"0",
"?",
"false",
":",
"isBoundary",
"(",
"str",
".",
"charCodeAt",
"(",
"i",
"-",
"1",
")",
")",
"&&",
"isBoundary",
"(",
"str",
".",
"charCodeAt",
"(",
"i",
"+",
"5",
")",
")",
";",
"}"
]
| all other JS engines should be just fine | [
"all",
"other",
"JS",
"engines",
"should",
"be",
"just",
"fine"
]
| 8e3f3b65a67955d11e15820e8f44e2cdaac4bd50 | https://github.com/WebReflection/es-class/blob/8e3f3b65a67955d11e15820e8f44e2cdaac4bd50/build/es-class.max.amd.js#L159-L168 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.