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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
11,100
|
fperucic/treant-js
|
Treant.js
|
function() {
if ( $ ) {
Array.prototype.unshift.apply( arguments, [true, {}] );
return $.extend.apply( $, arguments );
}
else {
return UTIL.createMerge.apply( this, arguments );
}
}
|
javascript
|
function() {
if ( $ ) {
Array.prototype.unshift.apply( arguments, [true, {}] );
return $.extend.apply( $, arguments );
}
else {
return UTIL.createMerge.apply( this, arguments );
}
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"$",
")",
"{",
"Array",
".",
"prototype",
".",
"unshift",
".",
"apply",
"(",
"arguments",
",",
"[",
"true",
",",
"{",
"}",
"]",
")",
";",
"return",
"$",
".",
"extend",
".",
"apply",
"(",
"$",
",",
"arguments",
")",
";",
"}",
"else",
"{",
"return",
"UTIL",
".",
"createMerge",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"}"
] |
Takes any number of arguments
@returns {*}
|
[
"Takes",
"any",
"number",
"of",
"arguments"
] |
a5f95627baa265a891858678de47dff180848613
|
https://github.com/fperucic/treant-js/blob/a5f95627baa265a891858678de47dff180848613/Treant.js#L73-L81
|
|
11,101
|
fperucic/treant-js
|
Treant.js
|
function (jsonConfig, treeId ) {
/**
* @param {object} jsonConfig
* @param {number} treeId
* @returns {Tree}
*/
this.reset = function( jsonConfig, treeId ) {
this.initJsonConfig = jsonConfig;
this.initTreeId = treeId;
this.id = treeId;
this.CONFIG = UTIL.extend( Tree.CONFIG, jsonConfig.chart );
this.drawArea = UTIL.findEl( this.CONFIG.container, true );
if ( !this.drawArea ) {
throw new Error( 'Failed to find element by selector "'+this.CONFIG.container+'"' );
}
UTIL.addClass( this.drawArea, 'Treant' );
// kill of any child elements that may be there
this.drawArea.innerHTML = '';
this.imageLoader = new ImageLoader();
this.nodeDB = new NodeDB( jsonConfig.nodeStructure, this );
// key store for storing reference to node connectors,
// key = nodeId where the connector ends
this.connectionStore = {};
this.loaded = false;
this._R = new Raphael( this.drawArea, 100, 100 );
return this;
};
/**
* @returns {Tree}
*/
this.reload = function() {
this.reset( this.initJsonConfig, this.initTreeId ).redraw();
return this;
};
this.reset( jsonConfig, treeId );
}
|
javascript
|
function (jsonConfig, treeId ) {
/**
* @param {object} jsonConfig
* @param {number} treeId
* @returns {Tree}
*/
this.reset = function( jsonConfig, treeId ) {
this.initJsonConfig = jsonConfig;
this.initTreeId = treeId;
this.id = treeId;
this.CONFIG = UTIL.extend( Tree.CONFIG, jsonConfig.chart );
this.drawArea = UTIL.findEl( this.CONFIG.container, true );
if ( !this.drawArea ) {
throw new Error( 'Failed to find element by selector "'+this.CONFIG.container+'"' );
}
UTIL.addClass( this.drawArea, 'Treant' );
// kill of any child elements that may be there
this.drawArea.innerHTML = '';
this.imageLoader = new ImageLoader();
this.nodeDB = new NodeDB( jsonConfig.nodeStructure, this );
// key store for storing reference to node connectors,
// key = nodeId where the connector ends
this.connectionStore = {};
this.loaded = false;
this._R = new Raphael( this.drawArea, 100, 100 );
return this;
};
/**
* @returns {Tree}
*/
this.reload = function() {
this.reset( this.initJsonConfig, this.initTreeId ).redraw();
return this;
};
this.reset( jsonConfig, treeId );
}
|
[
"function",
"(",
"jsonConfig",
",",
"treeId",
")",
"{",
"/**\r\n * @param {object} jsonConfig\r\n * @param {number} treeId\r\n * @returns {Tree}\r\n */",
"this",
".",
"reset",
"=",
"function",
"(",
"jsonConfig",
",",
"treeId",
")",
"{",
"this",
".",
"initJsonConfig",
"=",
"jsonConfig",
";",
"this",
".",
"initTreeId",
"=",
"treeId",
";",
"this",
".",
"id",
"=",
"treeId",
";",
"this",
".",
"CONFIG",
"=",
"UTIL",
".",
"extend",
"(",
"Tree",
".",
"CONFIG",
",",
"jsonConfig",
".",
"chart",
")",
";",
"this",
".",
"drawArea",
"=",
"UTIL",
".",
"findEl",
"(",
"this",
".",
"CONFIG",
".",
"container",
",",
"true",
")",
";",
"if",
"(",
"!",
"this",
".",
"drawArea",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Failed to find element by selector \"'",
"+",
"this",
".",
"CONFIG",
".",
"container",
"+",
"'\"'",
")",
";",
"}",
"UTIL",
".",
"addClass",
"(",
"this",
".",
"drawArea",
",",
"'Treant'",
")",
";",
"// kill of any child elements that may be there\r",
"this",
".",
"drawArea",
".",
"innerHTML",
"=",
"''",
";",
"this",
".",
"imageLoader",
"=",
"new",
"ImageLoader",
"(",
")",
";",
"this",
".",
"nodeDB",
"=",
"new",
"NodeDB",
"(",
"jsonConfig",
".",
"nodeStructure",
",",
"this",
")",
";",
"// key store for storing reference to node connectors,\r",
"// key = nodeId where the connector ends\r",
"this",
".",
"connectionStore",
"=",
"{",
"}",
";",
"this",
".",
"loaded",
"=",
"false",
";",
"this",
".",
"_R",
"=",
"new",
"Raphael",
"(",
"this",
".",
"drawArea",
",",
"100",
",",
"100",
")",
";",
"return",
"this",
";",
"}",
";",
"/**\r\n * @returns {Tree}\r\n */",
"this",
".",
"reload",
"=",
"function",
"(",
")",
"{",
"this",
".",
"reset",
"(",
"this",
".",
"initJsonConfig",
",",
"this",
".",
"initTreeId",
")",
".",
"redraw",
"(",
")",
";",
"return",
"this",
";",
"}",
";",
"this",
".",
"reset",
"(",
"jsonConfig",
",",
"treeId",
")",
";",
"}"
] |
Tree constructor.
@param {object} jsonConfig
@param {number} treeId
@constructor
|
[
"Tree",
"constructor",
"."
] |
a5f95627baa265a891858678de47dff180848613
|
https://github.com/fperucic/treant-js/blob/a5f95627baa265a891858678de47dff180848613/Treant.js#L404-L452
|
|
11,102
|
fperucic/treant-js
|
Treant.js
|
function( node, level ) {
node.leftNeighborId = this.lastNodeOnLevel[level];
if ( node.leftNeighborId ) {
node.leftNeighbor().rightNeighborId = node.id;
}
this.lastNodeOnLevel[level] = node.id;
return this;
}
|
javascript
|
function( node, level ) {
node.leftNeighborId = this.lastNodeOnLevel[level];
if ( node.leftNeighborId ) {
node.leftNeighbor().rightNeighborId = node.id;
}
this.lastNodeOnLevel[level] = node.id;
return this;
}
|
[
"function",
"(",
"node",
",",
"level",
")",
"{",
"node",
".",
"leftNeighborId",
"=",
"this",
".",
"lastNodeOnLevel",
"[",
"level",
"]",
";",
"if",
"(",
"node",
".",
"leftNeighborId",
")",
"{",
"node",
".",
"leftNeighbor",
"(",
")",
".",
"rightNeighborId",
"=",
"node",
".",
"id",
";",
"}",
"this",
".",
"lastNodeOnLevel",
"[",
"level",
"]",
"=",
"node",
".",
"id",
";",
"return",
"this",
";",
"}"
] |
Algorithm works from left to right, so previous processed node will be left neighbour of the next node
@param {TreeNode} node
@param {number} level
@returns {Tree}
|
[
"Algorithm",
"works",
"from",
"left",
"to",
"right",
"so",
"previous",
"processed",
"node",
"will",
"be",
"left",
"neighbour",
"of",
"the",
"next",
"node"
] |
a5f95627baa265a891858678de47dff180848613
|
https://github.com/fperucic/treant-js/blob/a5f95627baa265a891858678de47dff180848613/Treant.js#L1049-L1056
|
|
11,103
|
fperucic/treant-js
|
Treant.js
|
function( nodeStructure, id, parentId, tree, stackParentId ) {
this.reset( nodeStructure, id, parentId, tree, stackParentId );
}
|
javascript
|
function( nodeStructure, id, parentId, tree, stackParentId ) {
this.reset( nodeStructure, id, parentId, tree, stackParentId );
}
|
[
"function",
"(",
"nodeStructure",
",",
"id",
",",
"parentId",
",",
"tree",
",",
"stackParentId",
")",
"{",
"this",
".",
"reset",
"(",
"nodeStructure",
",",
"id",
",",
"parentId",
",",
"tree",
",",
"stackParentId",
")",
";",
"}"
] |
TreeNode constructor.
@param {object} nodeStructure
@param {number} id
@param {number} parentId
@param {Tree} tree
@param {number} stackParentId
@constructor
|
[
"TreeNode",
"constructor",
"."
] |
a5f95627baa265a891858678de47dff180848613
|
https://github.com/fperucic/treant-js/blob/a5f95627baa265a891858678de47dff180848613/Treant.js#L1305-L1307
|
|
11,104
|
fperucic/treant-js
|
Treant.js
|
function() {
var orientation = this.getTreeConfig().rootOrientation;
if ( this.pseudo ) {
// prevents separating the subtrees
return ( -this.getTreeConfig().subTeeSeparation );
}
if ( orientation === 'NORTH' || orientation === 'SOUTH' ) {
return this.width;
}
else if ( orientation === 'WEST' || orientation === 'EAST' ) {
return this.height;
}
}
|
javascript
|
function() {
var orientation = this.getTreeConfig().rootOrientation;
if ( this.pseudo ) {
// prevents separating the subtrees
return ( -this.getTreeConfig().subTeeSeparation );
}
if ( orientation === 'NORTH' || orientation === 'SOUTH' ) {
return this.width;
}
else if ( orientation === 'WEST' || orientation === 'EAST' ) {
return this.height;
}
}
|
[
"function",
"(",
")",
"{",
"var",
"orientation",
"=",
"this",
".",
"getTreeConfig",
"(",
")",
".",
"rootOrientation",
";",
"if",
"(",
"this",
".",
"pseudo",
")",
"{",
"// prevents separating the subtrees\r",
"return",
"(",
"-",
"this",
".",
"getTreeConfig",
"(",
")",
".",
"subTeeSeparation",
")",
";",
"}",
"if",
"(",
"orientation",
"===",
"'NORTH'",
"||",
"orientation",
"===",
"'SOUTH'",
")",
"{",
"return",
"this",
".",
"width",
";",
"}",
"else",
"if",
"(",
"orientation",
"===",
"'WEST'",
"||",
"orientation",
"===",
"'EAST'",
")",
"{",
"return",
"this",
".",
"height",
";",
"}",
"}"
] |
Returns the width of the node
@returns {float}
|
[
"Returns",
"the",
"width",
"of",
"the",
"node"
] |
a5f95627baa265a891858678de47dff180848613
|
https://github.com/fperucic/treant-js/blob/a5f95627baa265a891858678de47dff180848613/Treant.js#L1408-L1422
|
|
11,105
|
fperucic/treant-js
|
Treant.js
|
function(startPoint) {
var orient = this.Tree().CONFIG.rootOrientation, point = {};
if ( this.stackParentId ) { // return different end point if node is a stacked child
if ( orient === 'NORTH' || orient === 'SOUTH' ) {
orient = 'WEST';
}
else if ( orient === 'EAST' || orient === 'WEST' ) {
orient = 'NORTH';
}
}
// if pseudo, a virtual center is used
if ( orient === 'NORTH' ) {
point.x = (this.pseudo) ? this.X - this.Tree().CONFIG.subTeeSeparation/2 : this.X + this.width/2;
point.y = (startPoint) ? this.Y + this.height : this.Y;
}
else if (orient === 'SOUTH') {
point.x = (this.pseudo) ? this.X - this.Tree().CONFIG.subTeeSeparation/2 : this.X + this.width/2;
point.y = (startPoint) ? this.Y : this.Y + this.height;
}
else if (orient === 'EAST') {
point.x = (startPoint) ? this.X : this.X + this.width;
point.y = (this.pseudo) ? this.Y - this.Tree().CONFIG.subTeeSeparation/2 : this.Y + this.height/2;
}
else if (orient === 'WEST') {
point.x = (startPoint) ? this.X + this.width : this.X;
point.y = (this.pseudo) ? this.Y - this.Tree().CONFIG.subTeeSeparation/2 : this.Y + this.height/2;
}
return point;
}
|
javascript
|
function(startPoint) {
var orient = this.Tree().CONFIG.rootOrientation, point = {};
if ( this.stackParentId ) { // return different end point if node is a stacked child
if ( orient === 'NORTH' || orient === 'SOUTH' ) {
orient = 'WEST';
}
else if ( orient === 'EAST' || orient === 'WEST' ) {
orient = 'NORTH';
}
}
// if pseudo, a virtual center is used
if ( orient === 'NORTH' ) {
point.x = (this.pseudo) ? this.X - this.Tree().CONFIG.subTeeSeparation/2 : this.X + this.width/2;
point.y = (startPoint) ? this.Y + this.height : this.Y;
}
else if (orient === 'SOUTH') {
point.x = (this.pseudo) ? this.X - this.Tree().CONFIG.subTeeSeparation/2 : this.X + this.width/2;
point.y = (startPoint) ? this.Y : this.Y + this.height;
}
else if (orient === 'EAST') {
point.x = (startPoint) ? this.X : this.X + this.width;
point.y = (this.pseudo) ? this.Y - this.Tree().CONFIG.subTeeSeparation/2 : this.Y + this.height/2;
}
else if (orient === 'WEST') {
point.x = (startPoint) ? this.X + this.width : this.X;
point.y = (this.pseudo) ? this.Y - this.Tree().CONFIG.subTeeSeparation/2 : this.Y + this.height/2;
}
return point;
}
|
[
"function",
"(",
"startPoint",
")",
"{",
"var",
"orient",
"=",
"this",
".",
"Tree",
"(",
")",
".",
"CONFIG",
".",
"rootOrientation",
",",
"point",
"=",
"{",
"}",
";",
"if",
"(",
"this",
".",
"stackParentId",
")",
"{",
"// return different end point if node is a stacked child\r",
"if",
"(",
"orient",
"===",
"'NORTH'",
"||",
"orient",
"===",
"'SOUTH'",
")",
"{",
"orient",
"=",
"'WEST'",
";",
"}",
"else",
"if",
"(",
"orient",
"===",
"'EAST'",
"||",
"orient",
"===",
"'WEST'",
")",
"{",
"orient",
"=",
"'NORTH'",
";",
"}",
"}",
"// if pseudo, a virtual center is used\r",
"if",
"(",
"orient",
"===",
"'NORTH'",
")",
"{",
"point",
".",
"x",
"=",
"(",
"this",
".",
"pseudo",
")",
"?",
"this",
".",
"X",
"-",
"this",
".",
"Tree",
"(",
")",
".",
"CONFIG",
".",
"subTeeSeparation",
"/",
"2",
":",
"this",
".",
"X",
"+",
"this",
".",
"width",
"/",
"2",
";",
"point",
".",
"y",
"=",
"(",
"startPoint",
")",
"?",
"this",
".",
"Y",
"+",
"this",
".",
"height",
":",
"this",
".",
"Y",
";",
"}",
"else",
"if",
"(",
"orient",
"===",
"'SOUTH'",
")",
"{",
"point",
".",
"x",
"=",
"(",
"this",
".",
"pseudo",
")",
"?",
"this",
".",
"X",
"-",
"this",
".",
"Tree",
"(",
")",
".",
"CONFIG",
".",
"subTeeSeparation",
"/",
"2",
":",
"this",
".",
"X",
"+",
"this",
".",
"width",
"/",
"2",
";",
"point",
".",
"y",
"=",
"(",
"startPoint",
")",
"?",
"this",
".",
"Y",
":",
"this",
".",
"Y",
"+",
"this",
".",
"height",
";",
"}",
"else",
"if",
"(",
"orient",
"===",
"'EAST'",
")",
"{",
"point",
".",
"x",
"=",
"(",
"startPoint",
")",
"?",
"this",
".",
"X",
":",
"this",
".",
"X",
"+",
"this",
".",
"width",
";",
"point",
".",
"y",
"=",
"(",
"this",
".",
"pseudo",
")",
"?",
"this",
".",
"Y",
"-",
"this",
".",
"Tree",
"(",
")",
".",
"CONFIG",
".",
"subTeeSeparation",
"/",
"2",
":",
"this",
".",
"Y",
"+",
"this",
".",
"height",
"/",
"2",
";",
"}",
"else",
"if",
"(",
"orient",
"===",
"'WEST'",
")",
"{",
"point",
".",
"x",
"=",
"(",
"startPoint",
")",
"?",
"this",
".",
"X",
"+",
"this",
".",
"width",
":",
"this",
".",
"X",
";",
"point",
".",
"y",
"=",
"(",
"this",
".",
"pseudo",
")",
"?",
"this",
".",
"Y",
"-",
"this",
".",
"Tree",
"(",
")",
".",
"CONFIG",
".",
"subTeeSeparation",
"/",
"2",
":",
"this",
".",
"Y",
"+",
"this",
".",
"height",
"/",
"2",
";",
"}",
"return",
"point",
";",
"}"
] |
returns start or the end point of the connector line, origin is upper-left
|
[
"returns",
"start",
"or",
"the",
"end",
"point",
"of",
"the",
"connector",
"line",
"origin",
"is",
"upper",
"-",
"left"
] |
a5f95627baa265a891858678de47dff180848613
|
https://github.com/fperucic/treant-js/blob/a5f95627baa265a891858678de47dff180848613/Treant.js#L1548-L1578
|
|
11,106
|
fperucic/treant-js
|
Treant.js
|
function( jsonConfig, callback, jQuery ) {
if ( jsonConfig instanceof Array ) {
jsonConfig = JSONconfig.make( jsonConfig );
}
// optional
if ( jQuery ) {
$ = jQuery;
}
this.tree = TreeStore.createTree( jsonConfig );
this.tree.positionTree( callback );
}
|
javascript
|
function( jsonConfig, callback, jQuery ) {
if ( jsonConfig instanceof Array ) {
jsonConfig = JSONconfig.make( jsonConfig );
}
// optional
if ( jQuery ) {
$ = jQuery;
}
this.tree = TreeStore.createTree( jsonConfig );
this.tree.positionTree( callback );
}
|
[
"function",
"(",
"jsonConfig",
",",
"callback",
",",
"jQuery",
")",
"{",
"if",
"(",
"jsonConfig",
"instanceof",
"Array",
")",
"{",
"jsonConfig",
"=",
"JSONconfig",
".",
"make",
"(",
"jsonConfig",
")",
";",
"}",
"// optional\r",
"if",
"(",
"jQuery",
")",
"{",
"$",
"=",
"jQuery",
";",
"}",
"this",
".",
"tree",
"=",
"TreeStore",
".",
"createTree",
"(",
"jsonConfig",
")",
";",
"this",
".",
"tree",
".",
"positionTree",
"(",
"callback",
")",
";",
"}"
] |
Chart constructor.
|
[
"Chart",
"constructor",
"."
] |
a5f95627baa265a891858678de47dff180848613
|
https://github.com/fperucic/treant-js/blob/a5f95627baa265a891858678de47dff180848613/Treant.js#L2150-L2162
|
|
11,107
|
auth0/lock
|
support/playground/assets/remember.js
|
uniq
|
function uniq(el, arr){
arr = arr && arr.join ? arr : [];
if (!el) return arr.join(' > ');
if (9 == el.nodeType) return arr.join(' > ');
if (1 != el.nodeType) return arr.join(' > ');
arr.unshift(selector(el));
if (el.id) return arr.join(' > ');
return uniq(el.parentNode, arr);
}
|
javascript
|
function uniq(el, arr){
arr = arr && arr.join ? arr : [];
if (!el) return arr.join(' > ');
if (9 == el.nodeType) return arr.join(' > ');
if (1 != el.nodeType) return arr.join(' > ');
arr.unshift(selector(el));
if (el.id) return arr.join(' > ');
return uniq(el.parentNode, arr);
}
|
[
"function",
"uniq",
"(",
"el",
",",
"arr",
")",
"{",
"arr",
"=",
"arr",
"&&",
"arr",
".",
"join",
"?",
"arr",
":",
"[",
"]",
";",
"if",
"(",
"!",
"el",
")",
"return",
"arr",
".",
"join",
"(",
"' > '",
")",
";",
"if",
"(",
"9",
"==",
"el",
".",
"nodeType",
")",
"return",
"arr",
".",
"join",
"(",
"' > '",
")",
";",
"if",
"(",
"1",
"!=",
"el",
".",
"nodeType",
")",
"return",
"arr",
".",
"join",
"(",
"' > '",
")",
";",
"arr",
".",
"unshift",
"(",
"selector",
"(",
"el",
")",
")",
";",
"if",
"(",
"el",
".",
"id",
")",
"return",
"arr",
".",
"join",
"(",
"' > '",
")",
";",
"return",
"uniq",
"(",
"el",
".",
"parentNode",
",",
"arr",
")",
";",
"}"
] |
Generate unique selector of `el`.
@param {Element} el
@return {String}
@api public
|
[
"Generate",
"unique",
"selector",
"of",
"el",
"."
] |
5fac76442f7257cd86cc1c973a773a1c5527f59c
|
https://github.com/auth0/lock/blob/5fac76442f7257cd86cc1c973a773a1c5527f59c/support/playground/assets/remember.js#L643-L651
|
11,108
|
auth0/lock
|
support/playground/assets/remember.js
|
selector
|
function selector(el){
var classname = trim(el.className.baseVal ? el.className.baseVal : el.className);
var i = el.parentNode && 9 == el.parentNode.nodeType ? -1 : index(el);
return el.tagName.toLowerCase()
+ (el.id ? '#' + el.id : '')
+ (classname ? classname.replace(/^| +/g, '.') : '')
+ (~i ? ':nth-child(' + (i + 1) + ')' : '');
}
|
javascript
|
function selector(el){
var classname = trim(el.className.baseVal ? el.className.baseVal : el.className);
var i = el.parentNode && 9 == el.parentNode.nodeType ? -1 : index(el);
return el.tagName.toLowerCase()
+ (el.id ? '#' + el.id : '')
+ (classname ? classname.replace(/^| +/g, '.') : '')
+ (~i ? ':nth-child(' + (i + 1) + ')' : '');
}
|
[
"function",
"selector",
"(",
"el",
")",
"{",
"var",
"classname",
"=",
"trim",
"(",
"el",
".",
"className",
".",
"baseVal",
"?",
"el",
".",
"className",
".",
"baseVal",
":",
"el",
".",
"className",
")",
";",
"var",
"i",
"=",
"el",
".",
"parentNode",
"&&",
"9",
"==",
"el",
".",
"parentNode",
".",
"nodeType",
"?",
"-",
"1",
":",
"index",
"(",
"el",
")",
";",
"return",
"el",
".",
"tagName",
".",
"toLowerCase",
"(",
")",
"+",
"(",
"el",
".",
"id",
"?",
"'#'",
"+",
"el",
".",
"id",
":",
"''",
")",
"+",
"(",
"classname",
"?",
"classname",
".",
"replace",
"(",
"/",
"^| +",
"/",
"g",
",",
"'.'",
")",
":",
"''",
")",
"+",
"(",
"~",
"i",
"?",
"':nth-child('",
"+",
"(",
"i",
"+",
"1",
")",
"+",
"')'",
":",
"''",
")",
";",
"}"
] |
Generate a selector of the given `el`.
@param {Element} el
@return {String}
@api private
|
[
"Generate",
"a",
"selector",
"of",
"the",
"given",
"el",
"."
] |
5fac76442f7257cd86cc1c973a773a1c5527f59c
|
https://github.com/auth0/lock/blob/5fac76442f7257cd86cc1c973a773a1c5527f59c/support/playground/assets/remember.js#L661-L669
|
11,109
|
yeoman/yo
|
lib/routes/clear-config.js
|
_clearGeneratorConfig
|
function _clearGeneratorConfig(app, generator) {
if (generator === '*') {
globalConfig.removeAll();
} else {
globalConfig.remove(generator);
}
console.log('Global config has been successfully cleared');
app.navigate('home');
}
|
javascript
|
function _clearGeneratorConfig(app, generator) {
if (generator === '*') {
globalConfig.removeAll();
} else {
globalConfig.remove(generator);
}
console.log('Global config has been successfully cleared');
app.navigate('home');
}
|
[
"function",
"_clearGeneratorConfig",
"(",
"app",
",",
"generator",
")",
"{",
"if",
"(",
"generator",
"===",
"'*'",
")",
"{",
"globalConfig",
".",
"removeAll",
"(",
")",
";",
"}",
"else",
"{",
"globalConfig",
".",
"remove",
"(",
"generator",
")",
";",
"}",
"console",
".",
"log",
"(",
"'Global config has been successfully cleared'",
")",
";",
"app",
".",
"navigate",
"(",
"'home'",
")",
";",
"}"
] |
Clear the given generator from the global config file
@param {Object} app
@param {String} generator Name of the generator to be clear. Use '*' to clear all generators.
|
[
"Clear",
"the",
"given",
"generator",
"from",
"the",
"global",
"config",
"file"
] |
932ef07104b81de32fa3f0f6c9c2df61f4f0d9e6
|
https://github.com/yeoman/yo/blob/932ef07104b81de32fa3f0f6c9c2df61f4f0d9e6/lib/routes/clear-config.js#L74-L83
|
11,110
|
probablyup/markdown-to-jsx
|
index.js
|
parserFor
|
function parserFor(rules) {
// Sorts rules in order of increasing order, then
// ascending rule name in case of ties.
let ruleList = Object.keys(rules);
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'production') {
ruleList.forEach(function(type) {
let order = rules[type].order;
if (
process.env.NODE_ENV !== 'production' &&
(typeof order !== 'number' || !isFinite(order))
) {
console.warn(
'markdown-to-jsx: Invalid order for rule `' + type + '`: ' + order
);
}
});
}
ruleList.sort(function(typeA, typeB) {
let orderA = rules[typeA].order;
let orderB = rules[typeB].order;
// First sort based on increasing order
if (orderA !== orderB) {
return orderA - orderB;
// Then based on increasing unicode lexicographic ordering
} else if (typeA < typeB) {
return -1;
}
return 1;
});
function nestedParse(source, state) {
let result = [];
// We store the previous capture so that match functions can
// use some limited amount of lookbehind. Lists use this to
// ensure they don't match arbitrary '- ' or '* ' in inline
// text (see the list rule for more information).
let prevCapture = '';
while (source) {
let i = 0;
while (i < ruleList.length) {
const ruleType = ruleList[i];
const rule = rules[ruleType];
const capture = rule.match(source, state, prevCapture);
if (capture) {
const currCaptureString = capture[0];
source = source.substring(currCaptureString.length);
const parsed = rule.parse(capture, nestedParse, state);
// We also let rules override the default type of
// their parsed node if they would like to, so that
// there can be a single output function for all links,
// even if there are several rules to parse them.
if (parsed.type == null) {
parsed.type = ruleType;
}
result.push(parsed);
prevCapture = currCaptureString;
break;
}
i++;
}
}
return result;
}
return function outerParse(source, state) {
return nestedParse(normalizeWhitespace(source), state);
};
}
|
javascript
|
function parserFor(rules) {
// Sorts rules in order of increasing order, then
// ascending rule name in case of ties.
let ruleList = Object.keys(rules);
/* istanbul ignore next */
if (process.env.NODE_ENV !== 'production') {
ruleList.forEach(function(type) {
let order = rules[type].order;
if (
process.env.NODE_ENV !== 'production' &&
(typeof order !== 'number' || !isFinite(order))
) {
console.warn(
'markdown-to-jsx: Invalid order for rule `' + type + '`: ' + order
);
}
});
}
ruleList.sort(function(typeA, typeB) {
let orderA = rules[typeA].order;
let orderB = rules[typeB].order;
// First sort based on increasing order
if (orderA !== orderB) {
return orderA - orderB;
// Then based on increasing unicode lexicographic ordering
} else if (typeA < typeB) {
return -1;
}
return 1;
});
function nestedParse(source, state) {
let result = [];
// We store the previous capture so that match functions can
// use some limited amount of lookbehind. Lists use this to
// ensure they don't match arbitrary '- ' or '* ' in inline
// text (see the list rule for more information).
let prevCapture = '';
while (source) {
let i = 0;
while (i < ruleList.length) {
const ruleType = ruleList[i];
const rule = rules[ruleType];
const capture = rule.match(source, state, prevCapture);
if (capture) {
const currCaptureString = capture[0];
source = source.substring(currCaptureString.length);
const parsed = rule.parse(capture, nestedParse, state);
// We also let rules override the default type of
// their parsed node if they would like to, so that
// there can be a single output function for all links,
// even if there are several rules to parse them.
if (parsed.type == null) {
parsed.type = ruleType;
}
result.push(parsed);
prevCapture = currCaptureString;
break;
}
i++;
}
}
return result;
}
return function outerParse(source, state) {
return nestedParse(normalizeWhitespace(source), state);
};
}
|
[
"function",
"parserFor",
"(",
"rules",
")",
"{",
"// Sorts rules in order of increasing order, then",
"// ascending rule name in case of ties.",
"let",
"ruleList",
"=",
"Object",
".",
"keys",
"(",
"rules",
")",
";",
"/* istanbul ignore next */",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
")",
"{",
"ruleList",
".",
"forEach",
"(",
"function",
"(",
"type",
")",
"{",
"let",
"order",
"=",
"rules",
"[",
"type",
"]",
".",
"order",
";",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
"&&",
"(",
"typeof",
"order",
"!==",
"'number'",
"||",
"!",
"isFinite",
"(",
"order",
")",
")",
")",
"{",
"console",
".",
"warn",
"(",
"'markdown-to-jsx: Invalid order for rule `'",
"+",
"type",
"+",
"'`: '",
"+",
"order",
")",
";",
"}",
"}",
")",
";",
"}",
"ruleList",
".",
"sort",
"(",
"function",
"(",
"typeA",
",",
"typeB",
")",
"{",
"let",
"orderA",
"=",
"rules",
"[",
"typeA",
"]",
".",
"order",
";",
"let",
"orderB",
"=",
"rules",
"[",
"typeB",
"]",
".",
"order",
";",
"// First sort based on increasing order",
"if",
"(",
"orderA",
"!==",
"orderB",
")",
"{",
"return",
"orderA",
"-",
"orderB",
";",
"// Then based on increasing unicode lexicographic ordering",
"}",
"else",
"if",
"(",
"typeA",
"<",
"typeB",
")",
"{",
"return",
"-",
"1",
";",
"}",
"return",
"1",
";",
"}",
")",
";",
"function",
"nestedParse",
"(",
"source",
",",
"state",
")",
"{",
"let",
"result",
"=",
"[",
"]",
";",
"// We store the previous capture so that match functions can",
"// use some limited amount of lookbehind. Lists use this to",
"// ensure they don't match arbitrary '- ' or '* ' in inline",
"// text (see the list rule for more information).",
"let",
"prevCapture",
"=",
"''",
";",
"while",
"(",
"source",
")",
"{",
"let",
"i",
"=",
"0",
";",
"while",
"(",
"i",
"<",
"ruleList",
".",
"length",
")",
"{",
"const",
"ruleType",
"=",
"ruleList",
"[",
"i",
"]",
";",
"const",
"rule",
"=",
"rules",
"[",
"ruleType",
"]",
";",
"const",
"capture",
"=",
"rule",
".",
"match",
"(",
"source",
",",
"state",
",",
"prevCapture",
")",
";",
"if",
"(",
"capture",
")",
"{",
"const",
"currCaptureString",
"=",
"capture",
"[",
"0",
"]",
";",
"source",
"=",
"source",
".",
"substring",
"(",
"currCaptureString",
".",
"length",
")",
";",
"const",
"parsed",
"=",
"rule",
".",
"parse",
"(",
"capture",
",",
"nestedParse",
",",
"state",
")",
";",
"// We also let rules override the default type of",
"// their parsed node if they would like to, so that",
"// there can be a single output function for all links,",
"// even if there are several rules to parse them.",
"if",
"(",
"parsed",
".",
"type",
"==",
"null",
")",
"{",
"parsed",
".",
"type",
"=",
"ruleType",
";",
"}",
"result",
".",
"push",
"(",
"parsed",
")",
";",
"prevCapture",
"=",
"currCaptureString",
";",
"break",
";",
"}",
"i",
"++",
";",
"}",
"}",
"return",
"result",
";",
"}",
"return",
"function",
"outerParse",
"(",
"source",
",",
"state",
")",
"{",
"return",
"nestedParse",
"(",
"normalizeWhitespace",
"(",
"source",
")",
",",
"state",
")",
";",
"}",
";",
"}"
] |
Creates a parser for a given set of rules, with the precedence
specified as a list of rules.
@rules: an object containing
rule type -> {match, order, parse} objects
(lower order is higher precedence)
(Note: `order` is added to defaultRules after creation so that
the `order` of defaultRules in the source matches the `order`
of defaultRules in terms of `order` fields.)
@returns The resulting parse function, with the following parameters:
@source: the input source string to be parsed
@state: an optional object to be threaded through parse
calls. Allows clients to add stateful operations to
parsing, such as keeping track of how many levels deep
some nesting is. For an example use-case, see passage-ref
parsing in src/widgets/passage/passage-markdown.jsx
|
[
"Creates",
"a",
"parser",
"for",
"a",
"given",
"set",
"of",
"rules",
"with",
"the",
"precedence",
"specified",
"as",
"a",
"list",
"of",
"rules",
"."
] |
9570018bac22c759899be839089cc33d3d739af0
|
https://github.com/probablyup/markdown-to-jsx/blob/9570018bac22c759899be839089cc33d3d739af0/index.js#L417-L497
|
11,111
|
probablyup/markdown-to-jsx
|
index.js
|
inlineRegex
|
function inlineRegex(regex) {
return function match(source, state) {
if (state.inline) {
return regex.exec(source);
} else {
return null;
}
};
}
|
javascript
|
function inlineRegex(regex) {
return function match(source, state) {
if (state.inline) {
return regex.exec(source);
} else {
return null;
}
};
}
|
[
"function",
"inlineRegex",
"(",
"regex",
")",
"{",
"return",
"function",
"match",
"(",
"source",
",",
"state",
")",
"{",
"if",
"(",
"state",
".",
"inline",
")",
"{",
"return",
"regex",
".",
"exec",
"(",
"source",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
";",
"}"
] |
Creates a match function for an inline scoped or simple element from a regex
|
[
"Creates",
"a",
"match",
"function",
"for",
"an",
"inline",
"scoped",
"or",
"simple",
"element",
"from",
"a",
"regex"
] |
9570018bac22c759899be839089cc33d3d739af0
|
https://github.com/probablyup/markdown-to-jsx/blob/9570018bac22c759899be839089cc33d3d739af0/index.js#L500-L508
|
11,112
|
probablyup/markdown-to-jsx
|
index.js
|
parseSimpleInline
|
function parseSimpleInline(parse, content, state) {
const isCurrentlyInline = state.inline || false;
const isCurrentlySimple = state.simple || false;
state.inline = false;
state.simple = true;
const result = parse(content, state);
state.inline = isCurrentlyInline;
state.simple = isCurrentlySimple;
return result;
}
|
javascript
|
function parseSimpleInline(parse, content, state) {
const isCurrentlyInline = state.inline || false;
const isCurrentlySimple = state.simple || false;
state.inline = false;
state.simple = true;
const result = parse(content, state);
state.inline = isCurrentlyInline;
state.simple = isCurrentlySimple;
return result;
}
|
[
"function",
"parseSimpleInline",
"(",
"parse",
",",
"content",
",",
"state",
")",
"{",
"const",
"isCurrentlyInline",
"=",
"state",
".",
"inline",
"||",
"false",
";",
"const",
"isCurrentlySimple",
"=",
"state",
".",
"simple",
"||",
"false",
";",
"state",
".",
"inline",
"=",
"false",
";",
"state",
".",
"simple",
"=",
"true",
";",
"const",
"result",
"=",
"parse",
"(",
"content",
",",
"state",
")",
";",
"state",
".",
"inline",
"=",
"isCurrentlyInline",
";",
"state",
".",
"simple",
"=",
"isCurrentlySimple",
";",
"return",
"result",
";",
"}"
] |
Anything inline that isn't a link.
|
[
"Anything",
"inline",
"that",
"isn",
"t",
"a",
"link",
"."
] |
9570018bac22c759899be839089cc33d3d739af0
|
https://github.com/probablyup/markdown-to-jsx/blob/9570018bac22c759899be839089cc33d3d739af0/index.js#L626-L635
|
11,113
|
HttpErrorPages/HttpErrorPages
|
lib/express.js
|
function(){
res.type('.html');
res.send(_render(tpl, css, {
code: httpStatusCode,
title: pageData.title,
message: pageData.message,
footer: opt.footer
}))
}
|
javascript
|
function(){
res.type('.html');
res.send(_render(tpl, css, {
code: httpStatusCode,
title: pageData.title,
message: pageData.message,
footer: opt.footer
}))
}
|
[
"function",
"(",
")",
"{",
"res",
".",
"type",
"(",
"'.html'",
")",
";",
"res",
".",
"send",
"(",
"_render",
"(",
"tpl",
",",
"css",
",",
"{",
"code",
":",
"httpStatusCode",
",",
"title",
":",
"pageData",
".",
"title",
",",
"message",
":",
"pageData",
".",
"message",
",",
"footer",
":",
"opt",
".",
"footer",
"}",
")",
")",
"}"
] |
standard http-error-pages
|
[
"standard",
"http",
"-",
"error",
"-",
"pages"
] |
055edf7671174432c039b74faaf2e6d3b660d1b1
|
https://github.com/HttpErrorPages/HttpErrorPages/blob/055edf7671174432c039b74faaf2e6d3b660d1b1/lib/express.js#L45-L53
|
|
11,114
|
HttpErrorPages/HttpErrorPages
|
lib/page-renderer.js
|
renderTemplate
|
function renderTemplate(template, css, data={}){
// assign css
data.inlinecss = css;
// render template - use custom escape function to handle linebreaks!
return _ejs.render(template, data, {
escape: function(text){
if (!text){
return '';
}
// apply generic escape function
text = _ejs.escapeXML(text);
// linebreaks
text = text.replace(/\n/g, '<br />');
return text;
}
});
}
|
javascript
|
function renderTemplate(template, css, data={}){
// assign css
data.inlinecss = css;
// render template - use custom escape function to handle linebreaks!
return _ejs.render(template, data, {
escape: function(text){
if (!text){
return '';
}
// apply generic escape function
text = _ejs.escapeXML(text);
// linebreaks
text = text.replace(/\n/g, '<br />');
return text;
}
});
}
|
[
"function",
"renderTemplate",
"(",
"template",
",",
"css",
",",
"data",
"=",
"{",
"}",
")",
"{",
"// assign css",
"data",
".",
"inlinecss",
"=",
"css",
";",
"// render template - use custom escape function to handle linebreaks!",
"return",
"_ejs",
".",
"render",
"(",
"template",
",",
"data",
",",
"{",
"escape",
":",
"function",
"(",
"text",
")",
"{",
"if",
"(",
"!",
"text",
")",
"{",
"return",
"''",
";",
"}",
"// apply generic escape function",
"text",
"=",
"_ejs",
".",
"escapeXML",
"(",
"text",
")",
";",
"// linebreaks",
"text",
"=",
"text",
".",
"replace",
"(",
"/",
"\\n",
"/",
"g",
",",
"'<br />'",
")",
";",
"return",
"text",
";",
"}",
"}",
")",
";",
"}"
] |
render template using given data
|
[
"render",
"template",
"using",
"given",
"data"
] |
055edf7671174432c039b74faaf2e6d3b660d1b1
|
https://github.com/HttpErrorPages/HttpErrorPages/blob/055edf7671174432c039b74faaf2e6d3b660d1b1/lib/page-renderer.js#L4-L25
|
11,115
|
HttpErrorPages/HttpErrorPages
|
lib/json-reader.js
|
readJSONFile
|
async function readJSONFile(filename){
// load file
let raw = await _fs.readFile(filename, 'utf8');
// strip single line js comments
raw = raw.replace(/^\s*\/\/.*$/gm, '');
// parse text
return JSON.parse(raw);
}
|
javascript
|
async function readJSONFile(filename){
// load file
let raw = await _fs.readFile(filename, 'utf8');
// strip single line js comments
raw = raw.replace(/^\s*\/\/.*$/gm, '');
// parse text
return JSON.parse(raw);
}
|
[
"async",
"function",
"readJSONFile",
"(",
"filename",
")",
"{",
"// load file",
"let",
"raw",
"=",
"await",
"_fs",
".",
"readFile",
"(",
"filename",
",",
"'utf8'",
")",
";",
"// strip single line js comments",
"raw",
"=",
"raw",
".",
"replace",
"(",
"/",
"^\\s*\\/\\/.*$",
"/",
"gm",
",",
"''",
")",
";",
"// parse text",
"return",
"JSON",
".",
"parse",
"(",
"raw",
")",
";",
"}"
] |
parse json file and allow single line comments
|
[
"parse",
"json",
"file",
"and",
"allow",
"single",
"line",
"comments"
] |
055edf7671174432c039b74faaf2e6d3b660d1b1
|
https://github.com/HttpErrorPages/HttpErrorPages/blob/055edf7671174432c039b74faaf2e6d3b660d1b1/lib/json-reader.js#L4-L13
|
11,116
|
meodai/color-names
|
scripts/build.js
|
log
|
function log(key, value, message, errorLevel = 1) {
const error = {};
// looks for the original item that caused the error
error.entries = colorsSrc.entires.filter((entry) => {
return entry[key] === value;
});
error.message = message;
error.errorLevel = errorLevel;
errors.push(error);
}
|
javascript
|
function log(key, value, message, errorLevel = 1) {
const error = {};
// looks for the original item that caused the error
error.entries = colorsSrc.entires.filter((entry) => {
return entry[key] === value;
});
error.message = message;
error.errorLevel = errorLevel;
errors.push(error);
}
|
[
"function",
"log",
"(",
"key",
",",
"value",
",",
"message",
",",
"errorLevel",
"=",
"1",
")",
"{",
"const",
"error",
"=",
"{",
"}",
";",
"// looks for the original item that caused the error",
"error",
".",
"entries",
"=",
"colorsSrc",
".",
"entires",
".",
"filter",
"(",
"(",
"entry",
")",
"=>",
"{",
"return",
"entry",
"[",
"key",
"]",
"===",
"value",
";",
"}",
")",
";",
"error",
".",
"message",
"=",
"message",
";",
"error",
".",
"errorLevel",
"=",
"errorLevel",
";",
"errors",
".",
"push",
"(",
"error",
")",
";",
"}"
] |
logs errors and warning
@param {string} key key to look for in input
@param {string} value value to look for
@param {string} message error message
@param {Number} errorLevel if any error is set to 1, the program will exit
|
[
"logs",
"errors",
"and",
"warning"
] |
03c708fd8cea7189bf9c41d51d701c0571bcec7f
|
https://github.com/meodai/color-names/blob/03c708fd8cea7189bf9c41d51d701c0571bcec7f/scripts/build.js#L213-L224
|
11,117
|
kentcdodds/cross-env
|
src/command.js
|
commandConvert
|
function commandConvert(command, env, normalize = false) {
if (!isWindows()) {
return command
}
const envUnixRegex = /\$(\w+)|\${(\w+)}/g // $my_var or ${my_var}
const convertedCmd = command.replace(envUnixRegex, (match, $1, $2) => {
const varName = $1 || $2
// In Windows, non-existent variables are not replaced by the shell,
// so for example "echo %FOO%" will literally print the string "%FOO%", as
// opposed to printing an empty string in UNIX. See kentcdodds/cross-env#145
// If the env variable isn't defined at runtime, just strip it from the command entirely
return env[varName] ? `%${varName}%` : ''
})
// Normalization is required for commands with relative paths
// For example, `./cmd.bat`. See kentcdodds/cross-env#127
// However, it should not be done for command arguments.
// See https://github.com/kentcdodds/cross-env/pull/130#issuecomment-319887970
return normalize === true ? path.normalize(convertedCmd) : convertedCmd
}
|
javascript
|
function commandConvert(command, env, normalize = false) {
if (!isWindows()) {
return command
}
const envUnixRegex = /\$(\w+)|\${(\w+)}/g // $my_var or ${my_var}
const convertedCmd = command.replace(envUnixRegex, (match, $1, $2) => {
const varName = $1 || $2
// In Windows, non-existent variables are not replaced by the shell,
// so for example "echo %FOO%" will literally print the string "%FOO%", as
// opposed to printing an empty string in UNIX. See kentcdodds/cross-env#145
// If the env variable isn't defined at runtime, just strip it from the command entirely
return env[varName] ? `%${varName}%` : ''
})
// Normalization is required for commands with relative paths
// For example, `./cmd.bat`. See kentcdodds/cross-env#127
// However, it should not be done for command arguments.
// See https://github.com/kentcdodds/cross-env/pull/130#issuecomment-319887970
return normalize === true ? path.normalize(convertedCmd) : convertedCmd
}
|
[
"function",
"commandConvert",
"(",
"command",
",",
"env",
",",
"normalize",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"isWindows",
"(",
")",
")",
"{",
"return",
"command",
"}",
"const",
"envUnixRegex",
"=",
"/",
"\\$(\\w+)|\\${(\\w+)}",
"/",
"g",
"// $my_var or ${my_var}",
"const",
"convertedCmd",
"=",
"command",
".",
"replace",
"(",
"envUnixRegex",
",",
"(",
"match",
",",
"$1",
",",
"$2",
")",
"=>",
"{",
"const",
"varName",
"=",
"$1",
"||",
"$2",
"// In Windows, non-existent variables are not replaced by the shell,",
"// so for example \"echo %FOO%\" will literally print the string \"%FOO%\", as",
"// opposed to printing an empty string in UNIX. See kentcdodds/cross-env#145",
"// If the env variable isn't defined at runtime, just strip it from the command entirely",
"return",
"env",
"[",
"varName",
"]",
"?",
"`",
"${",
"varName",
"}",
"`",
":",
"''",
"}",
")",
"// Normalization is required for commands with relative paths",
"// For example, `./cmd.bat`. See kentcdodds/cross-env#127",
"// However, it should not be done for command arguments.",
"// See https://github.com/kentcdodds/cross-env/pull/130#issuecomment-319887970",
"return",
"normalize",
"===",
"true",
"?",
"path",
".",
"normalize",
"(",
"convertedCmd",
")",
":",
"convertedCmd",
"}"
] |
Converts an environment variable usage to be appropriate for the current OS
@param {String} command Command to convert
@param {Object} env Map of the current environment variable names and their values
@param {boolean} normalize If the command should be normalized using `path`
after converting
@returns {String} Converted command
|
[
"Converts",
"an",
"environment",
"variable",
"usage",
"to",
"be",
"appropriate",
"for",
"the",
"current",
"OS"
] |
2b36bb3c303e00d37371f93e08990bf9612ca492
|
https://github.com/kentcdodds/cross-env/blob/2b36bb3c303e00d37371f93e08990bf9612ca492/src/command.js#L14-L32
|
11,118
|
tus/tus-js-client
|
bin/phantom-jasmine.js
|
checkJasmineStatus
|
function checkJasmineStatus() {
// Only inject the source once.
if (jasmineFound) {
return;
}
var found = page.evaluate(function () {
return "jasmine" in window && jasmine.getEnv;
});
if (!found) {
return;
}
jasmineFound = true;
injectReporter();
}
|
javascript
|
function checkJasmineStatus() {
// Only inject the source once.
if (jasmineFound) {
return;
}
var found = page.evaluate(function () {
return "jasmine" in window && jasmine.getEnv;
});
if (!found) {
return;
}
jasmineFound = true;
injectReporter();
}
|
[
"function",
"checkJasmineStatus",
"(",
")",
"{",
"// Only inject the source once.",
"if",
"(",
"jasmineFound",
")",
"{",
"return",
";",
"}",
"var",
"found",
"=",
"page",
".",
"evaluate",
"(",
"function",
"(",
")",
"{",
"return",
"\"jasmine\"",
"in",
"window",
"&&",
"jasmine",
".",
"getEnv",
";",
"}",
")",
";",
"if",
"(",
"!",
"found",
")",
"{",
"return",
";",
"}",
"jasmineFound",
"=",
"true",
";",
"injectReporter",
"(",
")",
";",
"}"
] |
Tests whether the global jasmine object is available yet and if so, inject the source for the ConsoleReporter.
|
[
"Tests",
"whether",
"the",
"global",
"jasmine",
"object",
"is",
"available",
"yet",
"and",
"if",
"so",
"inject",
"the",
"source",
"for",
"the",
"ConsoleReporter",
"."
] |
13cdc861391a343f303c15e9eb0d24f6df87978f
|
https://github.com/tus/tus-js-client/blob/13cdc861391a343f303c15e9eb0d24f6df87978f/bin/phantom-jasmine.js#L40-L57
|
11,119
|
tus/tus-js-client
|
bin/phantom-jasmine.js
|
injectReporter
|
function injectReporter() {
page.evaluate(function (script) {
function print(msg) {
console.log(msg);
}
function onComplete(passed) {
window.callPhantom(passed);
}
eval(script);
var reporter = new ConsoleReporter();
reporter.setOptions({
print: print,
printDeprecation: print,
showColors: true,
onComplete: onComplete
});
jasmine.getEnv().addReporter(reporter);
}, reporterScript);
}
|
javascript
|
function injectReporter() {
page.evaluate(function (script) {
function print(msg) {
console.log(msg);
}
function onComplete(passed) {
window.callPhantom(passed);
}
eval(script);
var reporter = new ConsoleReporter();
reporter.setOptions({
print: print,
printDeprecation: print,
showColors: true,
onComplete: onComplete
});
jasmine.getEnv().addReporter(reporter);
}, reporterScript);
}
|
[
"function",
"injectReporter",
"(",
")",
"{",
"page",
".",
"evaluate",
"(",
"function",
"(",
"script",
")",
"{",
"function",
"print",
"(",
"msg",
")",
"{",
"console",
".",
"log",
"(",
"msg",
")",
";",
"}",
"function",
"onComplete",
"(",
"passed",
")",
"{",
"window",
".",
"callPhantom",
"(",
"passed",
")",
";",
"}",
"eval",
"(",
"script",
")",
";",
"var",
"reporter",
"=",
"new",
"ConsoleReporter",
"(",
")",
";",
"reporter",
".",
"setOptions",
"(",
"{",
"print",
":",
"print",
",",
"printDeprecation",
":",
"print",
",",
"showColors",
":",
"true",
",",
"onComplete",
":",
"onComplete",
"}",
")",
";",
"jasmine",
".",
"getEnv",
"(",
")",
".",
"addReporter",
"(",
"reporter",
")",
";",
"}",
",",
"reporterScript",
")",
";",
"}"
] |
Inject the ConsoleReporter's source into the browser context and register an instance as a reporter.
|
[
"Inject",
"the",
"ConsoleReporter",
"s",
"source",
"into",
"the",
"browser",
"context",
"and",
"register",
"an",
"instance",
"as",
"a",
"reporter",
"."
] |
13cdc861391a343f303c15e9eb0d24f6df87978f
|
https://github.com/tus/tus-js-client/blob/13cdc861391a343f303c15e9eb0d24f6df87978f/bin/phantom-jasmine.js#L61-L83
|
11,120
|
fians/Waves
|
dist/waves.js
|
removeRipple
|
function removeRipple(e, el, ripple) {
// Check if the ripple still exist
if (!ripple) {
return;
}
ripple.classList.remove('waves-rippling');
var relativeX = ripple.getAttribute('data-x');
var relativeY = ripple.getAttribute('data-y');
var scale = ripple.getAttribute('data-scale');
var translate = ripple.getAttribute('data-translate');
// Get delay beetween mousedown and mouse leave
var diff = Date.now() - Number(ripple.getAttribute('data-hold'));
var delay = 350 - diff;
if (delay < 0) {
delay = 0;
}
if (e.type === 'mousemove') {
delay = 150;
}
// Fade out ripple after delay
var duration = e.type === 'mousemove' ? 2500 : Effect.duration;
setTimeout(function() {
var style = {
top: relativeY + 'px',
left: relativeX + 'px',
opacity: '0',
// Duration
'-webkit-transition-duration': duration + 'ms',
'-moz-transition-duration': duration + 'ms',
'-o-transition-duration': duration + 'ms',
'transition-duration': duration + 'ms',
'-webkit-transform': scale + ' ' + translate,
'-moz-transform': scale + ' ' + translate,
'-ms-transform': scale + ' ' + translate,
'-o-transform': scale + ' ' + translate,
'transform': scale + ' ' + translate
};
ripple.setAttribute('style', convertStyle(style));
setTimeout(function() {
try {
el.removeChild(ripple);
} catch (e) {
return false;
}
}, duration);
}, delay);
}
|
javascript
|
function removeRipple(e, el, ripple) {
// Check if the ripple still exist
if (!ripple) {
return;
}
ripple.classList.remove('waves-rippling');
var relativeX = ripple.getAttribute('data-x');
var relativeY = ripple.getAttribute('data-y');
var scale = ripple.getAttribute('data-scale');
var translate = ripple.getAttribute('data-translate');
// Get delay beetween mousedown and mouse leave
var diff = Date.now() - Number(ripple.getAttribute('data-hold'));
var delay = 350 - diff;
if (delay < 0) {
delay = 0;
}
if (e.type === 'mousemove') {
delay = 150;
}
// Fade out ripple after delay
var duration = e.type === 'mousemove' ? 2500 : Effect.duration;
setTimeout(function() {
var style = {
top: relativeY + 'px',
left: relativeX + 'px',
opacity: '0',
// Duration
'-webkit-transition-duration': duration + 'ms',
'-moz-transition-duration': duration + 'ms',
'-o-transition-duration': duration + 'ms',
'transition-duration': duration + 'ms',
'-webkit-transform': scale + ' ' + translate,
'-moz-transform': scale + ' ' + translate,
'-ms-transform': scale + ' ' + translate,
'-o-transform': scale + ' ' + translate,
'transform': scale + ' ' + translate
};
ripple.setAttribute('style', convertStyle(style));
setTimeout(function() {
try {
el.removeChild(ripple);
} catch (e) {
return false;
}
}, duration);
}, delay);
}
|
[
"function",
"removeRipple",
"(",
"e",
",",
"el",
",",
"ripple",
")",
"{",
"// Check if the ripple still exist",
"if",
"(",
"!",
"ripple",
")",
"{",
"return",
";",
"}",
"ripple",
".",
"classList",
".",
"remove",
"(",
"'waves-rippling'",
")",
";",
"var",
"relativeX",
"=",
"ripple",
".",
"getAttribute",
"(",
"'data-x'",
")",
";",
"var",
"relativeY",
"=",
"ripple",
".",
"getAttribute",
"(",
"'data-y'",
")",
";",
"var",
"scale",
"=",
"ripple",
".",
"getAttribute",
"(",
"'data-scale'",
")",
";",
"var",
"translate",
"=",
"ripple",
".",
"getAttribute",
"(",
"'data-translate'",
")",
";",
"// Get delay beetween mousedown and mouse leave",
"var",
"diff",
"=",
"Date",
".",
"now",
"(",
")",
"-",
"Number",
"(",
"ripple",
".",
"getAttribute",
"(",
"'data-hold'",
")",
")",
";",
"var",
"delay",
"=",
"350",
"-",
"diff",
";",
"if",
"(",
"delay",
"<",
"0",
")",
"{",
"delay",
"=",
"0",
";",
"}",
"if",
"(",
"e",
".",
"type",
"===",
"'mousemove'",
")",
"{",
"delay",
"=",
"150",
";",
"}",
"// Fade out ripple after delay",
"var",
"duration",
"=",
"e",
".",
"type",
"===",
"'mousemove'",
"?",
"2500",
":",
"Effect",
".",
"duration",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"var",
"style",
"=",
"{",
"top",
":",
"relativeY",
"+",
"'px'",
",",
"left",
":",
"relativeX",
"+",
"'px'",
",",
"opacity",
":",
"'0'",
",",
"// Duration",
"'-webkit-transition-duration'",
":",
"duration",
"+",
"'ms'",
",",
"'-moz-transition-duration'",
":",
"duration",
"+",
"'ms'",
",",
"'-o-transition-duration'",
":",
"duration",
"+",
"'ms'",
",",
"'transition-duration'",
":",
"duration",
"+",
"'ms'",
",",
"'-webkit-transform'",
":",
"scale",
"+",
"' '",
"+",
"translate",
",",
"'-moz-transform'",
":",
"scale",
"+",
"' '",
"+",
"translate",
",",
"'-ms-transform'",
":",
"scale",
"+",
"' '",
"+",
"translate",
",",
"'-o-transform'",
":",
"scale",
"+",
"' '",
"+",
"translate",
",",
"'transform'",
":",
"scale",
"+",
"' '",
"+",
"translate",
"}",
";",
"ripple",
".",
"setAttribute",
"(",
"'style'",
",",
"convertStyle",
"(",
"style",
")",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"try",
"{",
"el",
".",
"removeChild",
"(",
"ripple",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}",
",",
"duration",
")",
";",
"}",
",",
"delay",
")",
";",
"}"
] |
Hide the effect and remove the ripple. Must be
a separate function to pass the JSLint...
|
[
"Hide",
"the",
"effect",
"and",
"remove",
"the",
"ripple",
".",
"Must",
"be",
"a",
"separate",
"function",
"to",
"pass",
"the",
"JSLint",
"..."
] |
1985b7e18327f86f1bb640efe3a2ab4b4fea4078
|
https://github.com/fians/Waves/blob/1985b7e18327f86f1bb640efe3a2ab4b4fea4078/dist/waves.js#L259-L318
|
11,121
|
zarocknz/javascript-winwheel
|
Winwheel.js
|
winwheelStopAnimation
|
function winwheelStopAnimation(canCallback)
{
// When the animation is stopped if canCallback is not false then try to call the callback.
// false can be passed in to stop the after happening if the animation has been stopped before it ended normally.
if (canCallback != false) {
let callback = winwheelToDrawDuringAnimation.animation.callbackFinished;
if (callback != null) {
// If the callback is a function then call it, otherwise evaluate the property as javascript code.
if (typeof callback === 'function') {
// Pass back the indicated segment as 99% of the time you will want to know this to inform the user of their prize.
callback(winwheelToDrawDuringAnimation.getIndicatedSegment());
} else {
eval(callback);
}
}
}
}
|
javascript
|
function winwheelStopAnimation(canCallback)
{
// When the animation is stopped if canCallback is not false then try to call the callback.
// false can be passed in to stop the after happening if the animation has been stopped before it ended normally.
if (canCallback != false) {
let callback = winwheelToDrawDuringAnimation.animation.callbackFinished;
if (callback != null) {
// If the callback is a function then call it, otherwise evaluate the property as javascript code.
if (typeof callback === 'function') {
// Pass back the indicated segment as 99% of the time you will want to know this to inform the user of their prize.
callback(winwheelToDrawDuringAnimation.getIndicatedSegment());
} else {
eval(callback);
}
}
}
}
|
[
"function",
"winwheelStopAnimation",
"(",
"canCallback",
")",
"{",
"// When the animation is stopped if canCallback is not false then try to call the callback.",
"// false can be passed in to stop the after happening if the animation has been stopped before it ended normally.",
"if",
"(",
"canCallback",
"!=",
"false",
")",
"{",
"let",
"callback",
"=",
"winwheelToDrawDuringAnimation",
".",
"animation",
".",
"callbackFinished",
";",
"if",
"(",
"callback",
"!=",
"null",
")",
"{",
"// If the callback is a function then call it, otherwise evaluate the property as javascript code.",
"if",
"(",
"typeof",
"callback",
"===",
"'function'",
")",
"{",
"// Pass back the indicated segment as 99% of the time you will want to know this to inform the user of their prize.",
"callback",
"(",
"winwheelToDrawDuringAnimation",
".",
"getIndicatedSegment",
"(",
")",
")",
";",
"}",
"else",
"{",
"eval",
"(",
"callback",
")",
";",
"}",
"}",
"}",
"}"
] |
This global is set by the winwheel class to the wheel object to be re-drawn.
|
[
"This",
"global",
"is",
"set",
"by",
"the",
"winwheel",
"class",
"to",
"the",
"wheel",
"object",
"to",
"be",
"re",
"-",
"drawn",
"."
] |
229a47acc3d7fd941d72a3ba9e1649751fd10ed5
|
https://github.com/zarocknz/javascript-winwheel/blob/229a47acc3d7fd941d72a3ba9e1649751fd10ed5/Winwheel.js#L2237-L2254
|
11,122
|
inikulin/parse5
|
packages/parse5/lib/parser/index.js
|
aaObtainFurthestBlock
|
function aaObtainFurthestBlock(p, formattingElementEntry) {
let furthestBlock = null;
for (let i = p.openElements.stackTop; i >= 0; i--) {
const element = p.openElements.items[i];
if (element === formattingElementEntry.element) {
break;
}
if (p._isSpecialElement(element)) {
furthestBlock = element;
}
}
if (!furthestBlock) {
p.openElements.popUntilElementPopped(formattingElementEntry.element);
p.activeFormattingElements.removeEntry(formattingElementEntry);
}
return furthestBlock;
}
|
javascript
|
function aaObtainFurthestBlock(p, formattingElementEntry) {
let furthestBlock = null;
for (let i = p.openElements.stackTop; i >= 0; i--) {
const element = p.openElements.items[i];
if (element === formattingElementEntry.element) {
break;
}
if (p._isSpecialElement(element)) {
furthestBlock = element;
}
}
if (!furthestBlock) {
p.openElements.popUntilElementPopped(formattingElementEntry.element);
p.activeFormattingElements.removeEntry(formattingElementEntry);
}
return furthestBlock;
}
|
[
"function",
"aaObtainFurthestBlock",
"(",
"p",
",",
"formattingElementEntry",
")",
"{",
"let",
"furthestBlock",
"=",
"null",
";",
"for",
"(",
"let",
"i",
"=",
"p",
".",
"openElements",
".",
"stackTop",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"const",
"element",
"=",
"p",
".",
"openElements",
".",
"items",
"[",
"i",
"]",
";",
"if",
"(",
"element",
"===",
"formattingElementEntry",
".",
"element",
")",
"{",
"break",
";",
"}",
"if",
"(",
"p",
".",
"_isSpecialElement",
"(",
"element",
")",
")",
"{",
"furthestBlock",
"=",
"element",
";",
"}",
"}",
"if",
"(",
"!",
"furthestBlock",
")",
"{",
"p",
".",
"openElements",
".",
"popUntilElementPopped",
"(",
"formattingElementEntry",
".",
"element",
")",
";",
"p",
".",
"activeFormattingElements",
".",
"removeEntry",
"(",
"formattingElementEntry",
")",
";",
"}",
"return",
"furthestBlock",
";",
"}"
] |
Steps 9 and 10 of the algorithm
|
[
"Steps",
"9",
"and",
"10",
"of",
"the",
"algorithm"
] |
fff571f3277eadff45c3d60a4c2953ad4dbb16af
|
https://github.com/inikulin/parse5/blob/fff571f3277eadff45c3d60a4c2953ad4dbb16af/packages/parse5/lib/parser/index.js#L910-L931
|
11,123
|
inikulin/parse5
|
packages/parse5/lib/parser/index.js
|
aaInnerLoop
|
function aaInnerLoop(p, furthestBlock, formattingElement) {
let lastElement = furthestBlock;
let nextElement = p.openElements.getCommonAncestor(furthestBlock);
for (let i = 0, element = nextElement; element !== formattingElement; i++, element = nextElement) {
//NOTE: store next element for the next loop iteration (it may be deleted from the stack by step 9.5)
nextElement = p.openElements.getCommonAncestor(element);
const elementEntry = p.activeFormattingElements.getElementEntry(element);
const counterOverflow = elementEntry && i >= AA_INNER_LOOP_ITER;
const shouldRemoveFromOpenElements = !elementEntry || counterOverflow;
if (shouldRemoveFromOpenElements) {
if (counterOverflow) {
p.activeFormattingElements.removeEntry(elementEntry);
}
p.openElements.remove(element);
} else {
element = aaRecreateElementFromEntry(p, elementEntry);
if (lastElement === furthestBlock) {
p.activeFormattingElements.bookmark = elementEntry;
}
p.treeAdapter.detachNode(lastElement);
p.treeAdapter.appendChild(element, lastElement);
lastElement = element;
}
}
return lastElement;
}
|
javascript
|
function aaInnerLoop(p, furthestBlock, formattingElement) {
let lastElement = furthestBlock;
let nextElement = p.openElements.getCommonAncestor(furthestBlock);
for (let i = 0, element = nextElement; element !== formattingElement; i++, element = nextElement) {
//NOTE: store next element for the next loop iteration (it may be deleted from the stack by step 9.5)
nextElement = p.openElements.getCommonAncestor(element);
const elementEntry = p.activeFormattingElements.getElementEntry(element);
const counterOverflow = elementEntry && i >= AA_INNER_LOOP_ITER;
const shouldRemoveFromOpenElements = !elementEntry || counterOverflow;
if (shouldRemoveFromOpenElements) {
if (counterOverflow) {
p.activeFormattingElements.removeEntry(elementEntry);
}
p.openElements.remove(element);
} else {
element = aaRecreateElementFromEntry(p, elementEntry);
if (lastElement === furthestBlock) {
p.activeFormattingElements.bookmark = elementEntry;
}
p.treeAdapter.detachNode(lastElement);
p.treeAdapter.appendChild(element, lastElement);
lastElement = element;
}
}
return lastElement;
}
|
[
"function",
"aaInnerLoop",
"(",
"p",
",",
"furthestBlock",
",",
"formattingElement",
")",
"{",
"let",
"lastElement",
"=",
"furthestBlock",
";",
"let",
"nextElement",
"=",
"p",
".",
"openElements",
".",
"getCommonAncestor",
"(",
"furthestBlock",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"element",
"=",
"nextElement",
";",
"element",
"!==",
"formattingElement",
";",
"i",
"++",
",",
"element",
"=",
"nextElement",
")",
"{",
"//NOTE: store next element for the next loop iteration (it may be deleted from the stack by step 9.5)",
"nextElement",
"=",
"p",
".",
"openElements",
".",
"getCommonAncestor",
"(",
"element",
")",
";",
"const",
"elementEntry",
"=",
"p",
".",
"activeFormattingElements",
".",
"getElementEntry",
"(",
"element",
")",
";",
"const",
"counterOverflow",
"=",
"elementEntry",
"&&",
"i",
">=",
"AA_INNER_LOOP_ITER",
";",
"const",
"shouldRemoveFromOpenElements",
"=",
"!",
"elementEntry",
"||",
"counterOverflow",
";",
"if",
"(",
"shouldRemoveFromOpenElements",
")",
"{",
"if",
"(",
"counterOverflow",
")",
"{",
"p",
".",
"activeFormattingElements",
".",
"removeEntry",
"(",
"elementEntry",
")",
";",
"}",
"p",
".",
"openElements",
".",
"remove",
"(",
"element",
")",
";",
"}",
"else",
"{",
"element",
"=",
"aaRecreateElementFromEntry",
"(",
"p",
",",
"elementEntry",
")",
";",
"if",
"(",
"lastElement",
"===",
"furthestBlock",
")",
"{",
"p",
".",
"activeFormattingElements",
".",
"bookmark",
"=",
"elementEntry",
";",
"}",
"p",
".",
"treeAdapter",
".",
"detachNode",
"(",
"lastElement",
")",
";",
"p",
".",
"treeAdapter",
".",
"appendChild",
"(",
"element",
",",
"lastElement",
")",
";",
"lastElement",
"=",
"element",
";",
"}",
"}",
"return",
"lastElement",
";",
"}"
] |
Step 13 of the algorithm
|
[
"Step",
"13",
"of",
"the",
"algorithm"
] |
fff571f3277eadff45c3d60a4c2953ad4dbb16af
|
https://github.com/inikulin/parse5/blob/fff571f3277eadff45c3d60a4c2953ad4dbb16af/packages/parse5/lib/parser/index.js#L934-L966
|
11,124
|
inikulin/parse5
|
packages/parse5/lib/parser/index.js
|
aaRecreateElementFromEntry
|
function aaRecreateElementFromEntry(p, elementEntry) {
const ns = p.treeAdapter.getNamespaceURI(elementEntry.element);
const newElement = p.treeAdapter.createElement(elementEntry.token.tagName, ns, elementEntry.token.attrs);
p.openElements.replace(elementEntry.element, newElement);
elementEntry.element = newElement;
return newElement;
}
|
javascript
|
function aaRecreateElementFromEntry(p, elementEntry) {
const ns = p.treeAdapter.getNamespaceURI(elementEntry.element);
const newElement = p.treeAdapter.createElement(elementEntry.token.tagName, ns, elementEntry.token.attrs);
p.openElements.replace(elementEntry.element, newElement);
elementEntry.element = newElement;
return newElement;
}
|
[
"function",
"aaRecreateElementFromEntry",
"(",
"p",
",",
"elementEntry",
")",
"{",
"const",
"ns",
"=",
"p",
".",
"treeAdapter",
".",
"getNamespaceURI",
"(",
"elementEntry",
".",
"element",
")",
";",
"const",
"newElement",
"=",
"p",
".",
"treeAdapter",
".",
"createElement",
"(",
"elementEntry",
".",
"token",
".",
"tagName",
",",
"ns",
",",
"elementEntry",
".",
"token",
".",
"attrs",
")",
";",
"p",
".",
"openElements",
".",
"replace",
"(",
"elementEntry",
".",
"element",
",",
"newElement",
")",
";",
"elementEntry",
".",
"element",
"=",
"newElement",
";",
"return",
"newElement",
";",
"}"
] |
Step 13.7 of the algorithm
|
[
"Step",
"13",
".",
"7",
"of",
"the",
"algorithm"
] |
fff571f3277eadff45c3d60a4c2953ad4dbb16af
|
https://github.com/inikulin/parse5/blob/fff571f3277eadff45c3d60a4c2953ad4dbb16af/packages/parse5/lib/parser/index.js#L969-L977
|
11,125
|
inikulin/parse5
|
packages/parse5/lib/parser/index.js
|
aaInsertLastNodeInCommonAncestor
|
function aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement) {
if (p._isElementCausesFosterParenting(commonAncestor)) {
p._fosterParentElement(lastElement);
} else {
const tn = p.treeAdapter.getTagName(commonAncestor);
const ns = p.treeAdapter.getNamespaceURI(commonAncestor);
if (tn === $.TEMPLATE && ns === NS.HTML) {
commonAncestor = p.treeAdapter.getTemplateContent(commonAncestor);
}
p.treeAdapter.appendChild(commonAncestor, lastElement);
}
}
|
javascript
|
function aaInsertLastNodeInCommonAncestor(p, commonAncestor, lastElement) {
if (p._isElementCausesFosterParenting(commonAncestor)) {
p._fosterParentElement(lastElement);
} else {
const tn = p.treeAdapter.getTagName(commonAncestor);
const ns = p.treeAdapter.getNamespaceURI(commonAncestor);
if (tn === $.TEMPLATE && ns === NS.HTML) {
commonAncestor = p.treeAdapter.getTemplateContent(commonAncestor);
}
p.treeAdapter.appendChild(commonAncestor, lastElement);
}
}
|
[
"function",
"aaInsertLastNodeInCommonAncestor",
"(",
"p",
",",
"commonAncestor",
",",
"lastElement",
")",
"{",
"if",
"(",
"p",
".",
"_isElementCausesFosterParenting",
"(",
"commonAncestor",
")",
")",
"{",
"p",
".",
"_fosterParentElement",
"(",
"lastElement",
")",
";",
"}",
"else",
"{",
"const",
"tn",
"=",
"p",
".",
"treeAdapter",
".",
"getTagName",
"(",
"commonAncestor",
")",
";",
"const",
"ns",
"=",
"p",
".",
"treeAdapter",
".",
"getNamespaceURI",
"(",
"commonAncestor",
")",
";",
"if",
"(",
"tn",
"===",
"$",
".",
"TEMPLATE",
"&&",
"ns",
"===",
"NS",
".",
"HTML",
")",
"{",
"commonAncestor",
"=",
"p",
".",
"treeAdapter",
".",
"getTemplateContent",
"(",
"commonAncestor",
")",
";",
"}",
"p",
".",
"treeAdapter",
".",
"appendChild",
"(",
"commonAncestor",
",",
"lastElement",
")",
";",
"}",
"}"
] |
Step 14 of the algorithm
|
[
"Step",
"14",
"of",
"the",
"algorithm"
] |
fff571f3277eadff45c3d60a4c2953ad4dbb16af
|
https://github.com/inikulin/parse5/blob/fff571f3277eadff45c3d60a4c2953ad4dbb16af/packages/parse5/lib/parser/index.js#L980-L993
|
11,126
|
inikulin/parse5
|
packages/parse5/lib/parser/index.js
|
aaReplaceFormattingElement
|
function aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry) {
const ns = p.treeAdapter.getNamespaceURI(formattingElementEntry.element);
const token = formattingElementEntry.token;
const newElement = p.treeAdapter.createElement(token.tagName, ns, token.attrs);
p._adoptNodes(furthestBlock, newElement);
p.treeAdapter.appendChild(furthestBlock, newElement);
p.activeFormattingElements.insertElementAfterBookmark(newElement, formattingElementEntry.token);
p.activeFormattingElements.removeEntry(formattingElementEntry);
p.openElements.remove(formattingElementEntry.element);
p.openElements.insertAfter(furthestBlock, newElement);
}
|
javascript
|
function aaReplaceFormattingElement(p, furthestBlock, formattingElementEntry) {
const ns = p.treeAdapter.getNamespaceURI(formattingElementEntry.element);
const token = formattingElementEntry.token;
const newElement = p.treeAdapter.createElement(token.tagName, ns, token.attrs);
p._adoptNodes(furthestBlock, newElement);
p.treeAdapter.appendChild(furthestBlock, newElement);
p.activeFormattingElements.insertElementAfterBookmark(newElement, formattingElementEntry.token);
p.activeFormattingElements.removeEntry(formattingElementEntry);
p.openElements.remove(formattingElementEntry.element);
p.openElements.insertAfter(furthestBlock, newElement);
}
|
[
"function",
"aaReplaceFormattingElement",
"(",
"p",
",",
"furthestBlock",
",",
"formattingElementEntry",
")",
"{",
"const",
"ns",
"=",
"p",
".",
"treeAdapter",
".",
"getNamespaceURI",
"(",
"formattingElementEntry",
".",
"element",
")",
";",
"const",
"token",
"=",
"formattingElementEntry",
".",
"token",
";",
"const",
"newElement",
"=",
"p",
".",
"treeAdapter",
".",
"createElement",
"(",
"token",
".",
"tagName",
",",
"ns",
",",
"token",
".",
"attrs",
")",
";",
"p",
".",
"_adoptNodes",
"(",
"furthestBlock",
",",
"newElement",
")",
";",
"p",
".",
"treeAdapter",
".",
"appendChild",
"(",
"furthestBlock",
",",
"newElement",
")",
";",
"p",
".",
"activeFormattingElements",
".",
"insertElementAfterBookmark",
"(",
"newElement",
",",
"formattingElementEntry",
".",
"token",
")",
";",
"p",
".",
"activeFormattingElements",
".",
"removeEntry",
"(",
"formattingElementEntry",
")",
";",
"p",
".",
"openElements",
".",
"remove",
"(",
"formattingElementEntry",
".",
"element",
")",
";",
"p",
".",
"openElements",
".",
"insertAfter",
"(",
"furthestBlock",
",",
"newElement",
")",
";",
"}"
] |
Steps 15-19 of the algorithm
|
[
"Steps",
"15",
"-",
"19",
"of",
"the",
"algorithm"
] |
fff571f3277eadff45c3d60a4c2953ad4dbb16af
|
https://github.com/inikulin/parse5/blob/fff571f3277eadff45c3d60a4c2953ad4dbb16af/packages/parse5/lib/parser/index.js#L996-L1009
|
11,127
|
ansman/validate.js
|
validate.js
|
function(errors, options) {
errors = v.pruneEmptyErrors(errors, options);
errors = v.expandMultipleErrors(errors, options);
errors = v.convertErrorMessages(errors, options);
var format = options.format || "grouped";
if (typeof v.formatters[format] === 'function') {
errors = v.formatters[format](errors);
} else {
throw new Error(v.format("Unknown format %{format}", options));
}
return v.isEmpty(errors) ? undefined : errors;
}
|
javascript
|
function(errors, options) {
errors = v.pruneEmptyErrors(errors, options);
errors = v.expandMultipleErrors(errors, options);
errors = v.convertErrorMessages(errors, options);
var format = options.format || "grouped";
if (typeof v.formatters[format] === 'function') {
errors = v.formatters[format](errors);
} else {
throw new Error(v.format("Unknown format %{format}", options));
}
return v.isEmpty(errors) ? undefined : errors;
}
|
[
"function",
"(",
"errors",
",",
"options",
")",
"{",
"errors",
"=",
"v",
".",
"pruneEmptyErrors",
"(",
"errors",
",",
"options",
")",
";",
"errors",
"=",
"v",
".",
"expandMultipleErrors",
"(",
"errors",
",",
"options",
")",
";",
"errors",
"=",
"v",
".",
"convertErrorMessages",
"(",
"errors",
",",
"options",
")",
";",
"var",
"format",
"=",
"options",
".",
"format",
"||",
"\"grouped\"",
";",
"if",
"(",
"typeof",
"v",
".",
"formatters",
"[",
"format",
"]",
"===",
"'function'",
")",
"{",
"errors",
"=",
"v",
".",
"formatters",
"[",
"format",
"]",
"(",
"errors",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"Error",
"(",
"v",
".",
"format",
"(",
"\"Unknown format %{format}\"",
",",
"options",
")",
")",
";",
"}",
"return",
"v",
".",
"isEmpty",
"(",
"errors",
")",
"?",
"undefined",
":",
"errors",
";",
"}"
] |
Takes the output from runValidations and converts it to the correct output format.
|
[
"Takes",
"the",
"output",
"from",
"runValidations",
"and",
"converts",
"it",
"to",
"the",
"correct",
"output",
"format",
"."
] |
c7553ffe9df4a3474e604a3f354cbc9d17190259
|
https://github.com/ansman/validate.js/blob/c7553ffe9df4a3474e604a3f354cbc9d17190259/validate.js#L144-L158
|
|
11,128
|
ansman/validate.js
|
validate.js
|
function(attributes, constraints, options) {
options = v.extend({}, v.async.options, options);
var WrapErrors = options.wrapErrors || function(errors) {
return errors;
};
// Removes unknown attributes
if (options.cleanAttributes !== false) {
attributes = v.cleanAttributes(attributes, constraints);
}
var results = v.runValidations(attributes, constraints, options);
return new v.Promise(function(resolve, reject) {
v.waitForResults(results).then(function() {
var errors = v.processValidationResults(results, options);
if (errors) {
reject(new WrapErrors(errors, options, attributes, constraints));
} else {
resolve(attributes);
}
}, function(err) {
reject(err);
});
});
}
|
javascript
|
function(attributes, constraints, options) {
options = v.extend({}, v.async.options, options);
var WrapErrors = options.wrapErrors || function(errors) {
return errors;
};
// Removes unknown attributes
if (options.cleanAttributes !== false) {
attributes = v.cleanAttributes(attributes, constraints);
}
var results = v.runValidations(attributes, constraints, options);
return new v.Promise(function(resolve, reject) {
v.waitForResults(results).then(function() {
var errors = v.processValidationResults(results, options);
if (errors) {
reject(new WrapErrors(errors, options, attributes, constraints));
} else {
resolve(attributes);
}
}, function(err) {
reject(err);
});
});
}
|
[
"function",
"(",
"attributes",
",",
"constraints",
",",
"options",
")",
"{",
"options",
"=",
"v",
".",
"extend",
"(",
"{",
"}",
",",
"v",
".",
"async",
".",
"options",
",",
"options",
")",
";",
"var",
"WrapErrors",
"=",
"options",
".",
"wrapErrors",
"||",
"function",
"(",
"errors",
")",
"{",
"return",
"errors",
";",
"}",
";",
"// Removes unknown attributes",
"if",
"(",
"options",
".",
"cleanAttributes",
"!==",
"false",
")",
"{",
"attributes",
"=",
"v",
".",
"cleanAttributes",
"(",
"attributes",
",",
"constraints",
")",
";",
"}",
"var",
"results",
"=",
"v",
".",
"runValidations",
"(",
"attributes",
",",
"constraints",
",",
"options",
")",
";",
"return",
"new",
"v",
".",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"v",
".",
"waitForResults",
"(",
"results",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"errors",
"=",
"v",
".",
"processValidationResults",
"(",
"results",
",",
"options",
")",
";",
"if",
"(",
"errors",
")",
"{",
"reject",
"(",
"new",
"WrapErrors",
"(",
"errors",
",",
"options",
",",
"attributes",
",",
"constraints",
")",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"attributes",
")",
";",
"}",
"}",
",",
"function",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Runs the validations with support for promises. This function will return a promise that is settled when all the validation promises have been completed. It can be called even if no validations returned a promise.
|
[
"Runs",
"the",
"validations",
"with",
"support",
"for",
"promises",
".",
"This",
"function",
"will",
"return",
"a",
"promise",
"that",
"is",
"settled",
"when",
"all",
"the",
"validation",
"promises",
"have",
"been",
"completed",
".",
"It",
"can",
"be",
"called",
"even",
"if",
"no",
"validations",
"returned",
"a",
"promise",
"."
] |
c7553ffe9df4a3474e604a3f354cbc9d17190259
|
https://github.com/ansman/validate.js/blob/c7553ffe9df4a3474e604a3f354cbc9d17190259/validate.js#L164-L190
|
|
11,129
|
ansman/validate.js
|
validate.js
|
function(results) {
// Create a sequence of all the results starting with a resolved promise.
return results.reduce(function(memo, result) {
// If this result isn't a promise skip it in the sequence.
if (!v.isPromise(result.error)) {
return memo;
}
return memo.then(function() {
return result.error.then(function(error) {
result.error = error || null;
});
});
}, new v.Promise(function(r) { r(); })); // A resolved promise
}
|
javascript
|
function(results) {
// Create a sequence of all the results starting with a resolved promise.
return results.reduce(function(memo, result) {
// If this result isn't a promise skip it in the sequence.
if (!v.isPromise(result.error)) {
return memo;
}
return memo.then(function() {
return result.error.then(function(error) {
result.error = error || null;
});
});
}, new v.Promise(function(r) { r(); })); // A resolved promise
}
|
[
"function",
"(",
"results",
")",
"{",
"// Create a sequence of all the results starting with a resolved promise.",
"return",
"results",
".",
"reduce",
"(",
"function",
"(",
"memo",
",",
"result",
")",
"{",
"// If this result isn't a promise skip it in the sequence.",
"if",
"(",
"!",
"v",
".",
"isPromise",
"(",
"result",
".",
"error",
")",
")",
"{",
"return",
"memo",
";",
"}",
"return",
"memo",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"result",
".",
"error",
".",
"then",
"(",
"function",
"(",
"error",
")",
"{",
"result",
".",
"error",
"=",
"error",
"||",
"null",
";",
"}",
")",
";",
"}",
")",
";",
"}",
",",
"new",
"v",
".",
"Promise",
"(",
"function",
"(",
"r",
")",
"{",
"r",
"(",
")",
";",
"}",
")",
")",
";",
"// A resolved promise",
"}"
] |
Returns a promise that is resolved when all promises in the results array are settled. The promise returned from this function is always resolved, never rejected. This function modifies the input argument, it replaces the promises with the value returned from the promise.
|
[
"Returns",
"a",
"promise",
"that",
"is",
"resolved",
"when",
"all",
"promises",
"in",
"the",
"results",
"array",
"are",
"settled",
".",
"The",
"promise",
"returned",
"from",
"this",
"function",
"is",
"always",
"resolved",
"never",
"rejected",
".",
"This",
"function",
"modifies",
"the",
"input",
"argument",
"it",
"replaces",
"the",
"promises",
"with",
"the",
"value",
"returned",
"from",
"the",
"promise",
"."
] |
c7553ffe9df4a3474e604a3f354cbc9d17190259
|
https://github.com/ansman/validate.js/blob/c7553ffe9df4a3474e604a3f354cbc9d17190259/validate.js#L205-L219
|
|
11,130
|
ansman/validate.js
|
validate.js
|
function(value) {
return v.isObject(value) && !v.isArray(value) && !v.isFunction(value);
}
|
javascript
|
function(value) {
return v.isObject(value) && !v.isArray(value) && !v.isFunction(value);
}
|
[
"function",
"(",
"value",
")",
"{",
"return",
"v",
".",
"isObject",
"(",
"value",
")",
"&&",
"!",
"v",
".",
"isArray",
"(",
"value",
")",
"&&",
"!",
"v",
".",
"isFunction",
"(",
"value",
")",
";",
"}"
] |
Checks if the object is a hash, which is equivalent to an object that is neither an array nor a function.
|
[
"Checks",
"if",
"the",
"object",
"is",
"a",
"hash",
"which",
"is",
"equivalent",
"to",
"an",
"object",
"that",
"is",
"neither",
"an",
"array",
"nor",
"a",
"function",
"."
] |
c7553ffe9df4a3474e604a3f354cbc9d17190259
|
https://github.com/ansman/validate.js/blob/c7553ffe9df4a3474e604a3f354cbc9d17190259/validate.js#L425-L427
|
|
11,131
|
ansman/validate.js
|
validate.js
|
function(errors, options) {
options = options || {};
var ret = []
, prettify = options.prettify || v.prettify;
errors.forEach(function(errorInfo) {
var error = v.result(errorInfo.error,
errorInfo.value,
errorInfo.attribute,
errorInfo.options,
errorInfo.attributes,
errorInfo.globalOptions);
if (!v.isString(error)) {
ret.push(errorInfo);
return;
}
if (error[0] === '^') {
error = error.slice(1);
} else if (options.fullMessages !== false) {
error = v.capitalize(prettify(errorInfo.attribute)) + " " + error;
}
error = error.replace(/\\\^/g, "^");
error = v.format(error, {
value: v.stringifyValue(errorInfo.value, options)
});
ret.push(v.extend({}, errorInfo, {error: error}));
});
return ret;
}
|
javascript
|
function(errors, options) {
options = options || {};
var ret = []
, prettify = options.prettify || v.prettify;
errors.forEach(function(errorInfo) {
var error = v.result(errorInfo.error,
errorInfo.value,
errorInfo.attribute,
errorInfo.options,
errorInfo.attributes,
errorInfo.globalOptions);
if (!v.isString(error)) {
ret.push(errorInfo);
return;
}
if (error[0] === '^') {
error = error.slice(1);
} else if (options.fullMessages !== false) {
error = v.capitalize(prettify(errorInfo.attribute)) + " " + error;
}
error = error.replace(/\\\^/g, "^");
error = v.format(error, {
value: v.stringifyValue(errorInfo.value, options)
});
ret.push(v.extend({}, errorInfo, {error: error}));
});
return ret;
}
|
[
"function",
"(",
"errors",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"ret",
"=",
"[",
"]",
",",
"prettify",
"=",
"options",
".",
"prettify",
"||",
"v",
".",
"prettify",
";",
"errors",
".",
"forEach",
"(",
"function",
"(",
"errorInfo",
")",
"{",
"var",
"error",
"=",
"v",
".",
"result",
"(",
"errorInfo",
".",
"error",
",",
"errorInfo",
".",
"value",
",",
"errorInfo",
".",
"attribute",
",",
"errorInfo",
".",
"options",
",",
"errorInfo",
".",
"attributes",
",",
"errorInfo",
".",
"globalOptions",
")",
";",
"if",
"(",
"!",
"v",
".",
"isString",
"(",
"error",
")",
")",
"{",
"ret",
".",
"push",
"(",
"errorInfo",
")",
";",
"return",
";",
"}",
"if",
"(",
"error",
"[",
"0",
"]",
"===",
"'^'",
")",
"{",
"error",
"=",
"error",
".",
"slice",
"(",
"1",
")",
";",
"}",
"else",
"if",
"(",
"options",
".",
"fullMessages",
"!==",
"false",
")",
"{",
"error",
"=",
"v",
".",
"capitalize",
"(",
"prettify",
"(",
"errorInfo",
".",
"attribute",
")",
")",
"+",
"\" \"",
"+",
"error",
";",
"}",
"error",
"=",
"error",
".",
"replace",
"(",
"/",
"\\\\\\^",
"/",
"g",
",",
"\"^\"",
")",
";",
"error",
"=",
"v",
".",
"format",
"(",
"error",
",",
"{",
"value",
":",
"v",
".",
"stringifyValue",
"(",
"errorInfo",
".",
"value",
",",
"options",
")",
"}",
")",
";",
"ret",
".",
"push",
"(",
"v",
".",
"extend",
"(",
"{",
"}",
",",
"errorInfo",
",",
"{",
"error",
":",
"error",
"}",
")",
")",
";",
"}",
")",
";",
"return",
"ret",
";",
"}"
] |
Converts the error mesages by prepending the attribute name unless the message is prefixed by ^
|
[
"Converts",
"the",
"error",
"mesages",
"by",
"prepending",
"the",
"attribute",
"name",
"unless",
"the",
"message",
"is",
"prefixed",
"by",
"^"
] |
c7553ffe9df4a3474e604a3f354cbc9d17190259
|
https://github.com/ansman/validate.js/blob/c7553ffe9df4a3474e604a3f354cbc9d17190259/validate.js#L627-L657
|
|
11,132
|
ansman/validate.js
|
validate.js
|
function(value, options) {
options = v.extend({}, this.options, options);
if (options.allowEmpty !== false ? !v.isDefined(value) : v.isEmpty(value)) {
return options.message || this.message || "can't be blank";
}
}
|
javascript
|
function(value, options) {
options = v.extend({}, this.options, options);
if (options.allowEmpty !== false ? !v.isDefined(value) : v.isEmpty(value)) {
return options.message || this.message || "can't be blank";
}
}
|
[
"function",
"(",
"value",
",",
"options",
")",
"{",
"options",
"=",
"v",
".",
"extend",
"(",
"{",
"}",
",",
"this",
".",
"options",
",",
"options",
")",
";",
"if",
"(",
"options",
".",
"allowEmpty",
"!==",
"false",
"?",
"!",
"v",
".",
"isDefined",
"(",
"value",
")",
":",
"v",
".",
"isEmpty",
"(",
"value",
")",
")",
"{",
"return",
"options",
".",
"message",
"||",
"this",
".",
"message",
"||",
"\"can't be blank\"",
";",
"}",
"}"
] |
Presence validates that the value isn't empty
|
[
"Presence",
"validates",
"that",
"the",
"value",
"isn",
"t",
"empty"
] |
c7553ffe9df4a3474e604a3f354cbc9d17190259
|
https://github.com/ansman/validate.js/blob/c7553ffe9df4a3474e604a3f354cbc9d17190259/validate.js#L767-L772
|
|
11,133
|
ansman/validate.js
|
validate.js
|
function(value, options) {
if (!v.isDefined(value)) {
return;
}
options = v.extend({}, this.options, options);
var message = options.message || this.message || "is not a valid url"
, schemes = options.schemes || this.schemes || ['http', 'https']
, allowLocal = options.allowLocal || this.allowLocal || false
, allowDataUrl = options.allowDataUrl || this.allowDataUrl || false;
if (!v.isString(value)) {
return message;
}
// https://gist.github.com/dperini/729294
var regex =
"^" +
// protocol identifier
"(?:(?:" + schemes.join("|") + ")://)" +
// user:pass authentication
"(?:\\S+(?::\\S*)?@)?" +
"(?:";
var tld = "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))";
if (allowLocal) {
tld += "?";
} else {
regex +=
// IP address exclusion
// private & local networks
"(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})";
}
regex +=
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
// host name
"(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
// domain name
"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
tld +
")" +
// port number
"(?::\\d{2,5})?" +
// resource path
"(?:[/?#]\\S*)?" +
"$";
if (allowDataUrl) {
// RFC 2397
var mediaType = "\\w+\\/[-+.\\w]+(?:;[\\w=]+)*";
var urlchar = "[A-Za-z0-9-_.!~\\*'();\\/?:@&=+$,%]*";
var dataurl = "data:(?:"+mediaType+")?(?:;base64)?,"+urlchar;
regex = "(?:"+regex+")|(?:^"+dataurl+"$)";
}
var PATTERN = new RegExp(regex, 'i');
if (!PATTERN.exec(value)) {
return message;
}
}
|
javascript
|
function(value, options) {
if (!v.isDefined(value)) {
return;
}
options = v.extend({}, this.options, options);
var message = options.message || this.message || "is not a valid url"
, schemes = options.schemes || this.schemes || ['http', 'https']
, allowLocal = options.allowLocal || this.allowLocal || false
, allowDataUrl = options.allowDataUrl || this.allowDataUrl || false;
if (!v.isString(value)) {
return message;
}
// https://gist.github.com/dperini/729294
var regex =
"^" +
// protocol identifier
"(?:(?:" + schemes.join("|") + ")://)" +
// user:pass authentication
"(?:\\S+(?::\\S*)?@)?" +
"(?:";
var tld = "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))";
if (allowLocal) {
tld += "?";
} else {
regex +=
// IP address exclusion
// private & local networks
"(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})";
}
regex +=
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
// host name
"(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
// domain name
"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
tld +
")" +
// port number
"(?::\\d{2,5})?" +
// resource path
"(?:[/?#]\\S*)?" +
"$";
if (allowDataUrl) {
// RFC 2397
var mediaType = "\\w+\\/[-+.\\w]+(?:;[\\w=]+)*";
var urlchar = "[A-Za-z0-9-_.!~\\*'();\\/?:@&=+$,%]*";
var dataurl = "data:(?:"+mediaType+")?(?:;base64)?,"+urlchar;
regex = "(?:"+regex+")|(?:^"+dataurl+"$)";
}
var PATTERN = new RegExp(regex, 'i');
if (!PATTERN.exec(value)) {
return message;
}
}
|
[
"function",
"(",
"value",
",",
"options",
")",
"{",
"if",
"(",
"!",
"v",
".",
"isDefined",
"(",
"value",
")",
")",
"{",
"return",
";",
"}",
"options",
"=",
"v",
".",
"extend",
"(",
"{",
"}",
",",
"this",
".",
"options",
",",
"options",
")",
";",
"var",
"message",
"=",
"options",
".",
"message",
"||",
"this",
".",
"message",
"||",
"\"is not a valid url\"",
",",
"schemes",
"=",
"options",
".",
"schemes",
"||",
"this",
".",
"schemes",
"||",
"[",
"'http'",
",",
"'https'",
"]",
",",
"allowLocal",
"=",
"options",
".",
"allowLocal",
"||",
"this",
".",
"allowLocal",
"||",
"false",
",",
"allowDataUrl",
"=",
"options",
".",
"allowDataUrl",
"||",
"this",
".",
"allowDataUrl",
"||",
"false",
";",
"if",
"(",
"!",
"v",
".",
"isString",
"(",
"value",
")",
")",
"{",
"return",
"message",
";",
"}",
"// https://gist.github.com/dperini/729294",
"var",
"regex",
"=",
"\"^\"",
"+",
"// protocol identifier",
"\"(?:(?:\"",
"+",
"schemes",
".",
"join",
"(",
"\"|\"",
")",
"+",
"\")://)\"",
"+",
"// user:pass authentication",
"\"(?:\\\\S+(?::\\\\S*)?@)?\"",
"+",
"\"(?:\"",
";",
"var",
"tld",
"=",
"\"(?:\\\\.(?:[a-z\\\\u00a1-\\\\uffff]{2,}))\"",
";",
"if",
"(",
"allowLocal",
")",
"{",
"tld",
"+=",
"\"?\"",
";",
"}",
"else",
"{",
"regex",
"+=",
"// IP address exclusion",
"// private & local networks",
"\"(?!(?:10|127)(?:\\\\.\\\\d{1,3}){3})\"",
"+",
"\"(?!(?:169\\\\.254|192\\\\.168)(?:\\\\.\\\\d{1,3}){2})\"",
"+",
"\"(?!172\\\\.(?:1[6-9]|2\\\\d|3[0-1])(?:\\\\.\\\\d{1,3}){2})\"",
";",
"}",
"regex",
"+=",
"// IP address dotted notation octets",
"// excludes loopback network 0.0.0.0",
"// excludes reserved space >= 224.0.0.0",
"// excludes network & broacast addresses",
"// (first & last IP address of each class)",
"\"(?:[1-9]\\\\d?|1\\\\d\\\\d|2[01]\\\\d|22[0-3])\"",
"+",
"\"(?:\\\\.(?:1?\\\\d{1,2}|2[0-4]\\\\d|25[0-5])){2}\"",
"+",
"\"(?:\\\\.(?:[1-9]\\\\d?|1\\\\d\\\\d|2[0-4]\\\\d|25[0-4]))\"",
"+",
"\"|\"",
"+",
"// host name",
"\"(?:(?:[a-z\\\\u00a1-\\\\uffff0-9]-*)*[a-z\\\\u00a1-\\\\uffff0-9]+)\"",
"+",
"// domain name",
"\"(?:\\\\.(?:[a-z\\\\u00a1-\\\\uffff0-9]-*)*[a-z\\\\u00a1-\\\\uffff0-9]+)*\"",
"+",
"tld",
"+",
"\")\"",
"+",
"// port number",
"\"(?::\\\\d{2,5})?\"",
"+",
"// resource path",
"\"(?:[/?#]\\\\S*)?\"",
"+",
"\"$\"",
";",
"if",
"(",
"allowDataUrl",
")",
"{",
"// RFC 2397",
"var",
"mediaType",
"=",
"\"\\\\w+\\\\/[-+.\\\\w]+(?:;[\\\\w=]+)*\"",
";",
"var",
"urlchar",
"=",
"\"[A-Za-z0-9-_.!~\\\\*'();\\\\/?:@&=+$,%]*\"",
";",
"var",
"dataurl",
"=",
"\"data:(?:\"",
"+",
"mediaType",
"+",
"\")?(?:;base64)?,\"",
"+",
"urlchar",
";",
"regex",
"=",
"\"(?:\"",
"+",
"regex",
"+",
"\")|(?:^\"",
"+",
"dataurl",
"+",
"\"$)\"",
";",
"}",
"var",
"PATTERN",
"=",
"new",
"RegExp",
"(",
"regex",
",",
"'i'",
")",
";",
"if",
"(",
"!",
"PATTERN",
".",
"exec",
"(",
"value",
")",
")",
"{",
"return",
"message",
";",
"}",
"}"
] |
A URL validator that is used to validate URLs with the ability to restrict schemes and some domains.
|
[
"A",
"URL",
"validator",
"that",
"is",
"used",
"to",
"validate",
"URLs",
"with",
"the",
"ability",
"to",
"restrict",
"schemes",
"and",
"some",
"domains",
"."
] |
c7553ffe9df4a3474e604a3f354cbc9d17190259
|
https://github.com/ansman/validate.js/blob/c7553ffe9df4a3474e604a3f354cbc9d17190259/validate.js#L1093-L1164
|
|
11,134
|
YvesCoding/vuescroll
|
src/mode/shared/bar.js
|
getRgbAColor
|
function getRgbAColor(color, opacity) {
const id = color + '&' + opacity;
if (colorCache[id]) {
return colorCache[id];
}
const div = document.createElement('div');
div.style.background = color;
document.body.appendChild(div);
const computedColor = window.getComputedStyle(div).backgroundColor;
document.body.removeChild(div);
/* istanbul ignore if */
if (!rgbReg.test(computedColor)) {
return color;
}
return (colorCache[id] = `rgba(${
extractRgbColor.exec(computedColor)[1]
}, ${opacity})`);
}
|
javascript
|
function getRgbAColor(color, opacity) {
const id = color + '&' + opacity;
if (colorCache[id]) {
return colorCache[id];
}
const div = document.createElement('div');
div.style.background = color;
document.body.appendChild(div);
const computedColor = window.getComputedStyle(div).backgroundColor;
document.body.removeChild(div);
/* istanbul ignore if */
if (!rgbReg.test(computedColor)) {
return color;
}
return (colorCache[id] = `rgba(${
extractRgbColor.exec(computedColor)[1]
}, ${opacity})`);
}
|
[
"function",
"getRgbAColor",
"(",
"color",
",",
"opacity",
")",
"{",
"const",
"id",
"=",
"color",
"+",
"'&'",
"+",
"opacity",
";",
"if",
"(",
"colorCache",
"[",
"id",
"]",
")",
"{",
"return",
"colorCache",
"[",
"id",
"]",
";",
"}",
"const",
"div",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"div",
".",
"style",
".",
"background",
"=",
"color",
";",
"document",
".",
"body",
".",
"appendChild",
"(",
"div",
")",
";",
"const",
"computedColor",
"=",
"window",
".",
"getComputedStyle",
"(",
"div",
")",
".",
"backgroundColor",
";",
"document",
".",
"body",
".",
"removeChild",
"(",
"div",
")",
";",
"/* istanbul ignore if */",
"if",
"(",
"!",
"rgbReg",
".",
"test",
"(",
"computedColor",
")",
")",
"{",
"return",
"color",
";",
"}",
"return",
"(",
"colorCache",
"[",
"id",
"]",
"=",
"`",
"${",
"extractRgbColor",
".",
"exec",
"(",
"computedColor",
")",
"[",
"1",
"]",
"}",
"${",
"opacity",
"}",
"`",
")",
";",
"}"
] |
Transform a common color int oa `rgbA` color
|
[
"Transform",
"a",
"common",
"color",
"int",
"oa",
"rgbA",
"color"
] |
8e91550833db7e94b334dfddba20b876c9b1e59c
|
https://github.com/YvesCoding/vuescroll/blob/8e91550833db7e94b334dfddba20b876c9b1e59c/src/mode/shared/bar.js#L167-L187
|
11,135
|
YvesCoding/vuescroll
|
src/mode/slide/slide-panel.js
|
createTipDom
|
function createTipDom(h, context, type, tip) {
const stage = context.vuescroll.state[`${type}Stage`];
let dom = null;
// Return user specified animation dom
/* istanbul ignore if */
if ((dom = context.$slots[`${type}-${stage}`])) {
return dom;
}
switch (stage) {
// The dom will show at deactive stage
case 'deactive':
case 'active':
{
let className = 'active';
if (stage == 'deactive') {
className += ' deactive';
}
dom = (
<svg
class={className}
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
viewBox="0 0 1000 1000"
enable-background="new 0 0 1000 1000"
xmlSpace="preserve"
>
<metadata> Svg Vector Icons : http://www.sfont.cn </metadata>
<g>
<g transform="matrix(1 0 0 -1 0 1008)">
<path d="M10,543l490,455l490-455L885,438L570,735.5V18H430v717.5L115,438L10,543z" />
</g>
</g>
</svg>
);
}
break;
case 'start':
dom = (
<svg viewBox="0 0 50 50" class="start">
<circle stroke="true" cx="25" cy="25" r="20" class="bg-path" />
<circle cx="25" cy="25" r="20" class="active-path" />
</svg>
);
break;
case 'beforeDeactive':
dom = (
<svg
viewBox="0 0 1024 1024"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
p-id="3562"
>
<path
d="M512 0C229.706831 0 0 229.667446 0 512s229.667446 512 512 512c282.293169 0 512-229.667446 512-512S794.332554 0 512 0z m282.994215 353.406031L433.2544 715.145846a31.484062 31.484062 0 0 1-22.275938 9.231754h-0.4096a31.586462 31.586462 0 0 1-22.449231-9.814646L228.430769 546.327631a31.507692 31.507692 0 0 1 45.701908-43.386093l137.4208 144.785724L750.442338 308.854154a31.507692 31.507692 0 1 1 44.551877 44.551877z"
fill=""
p-id="3563"
/>
</svg>
);
break;
}
return [dom, tip];
}
|
javascript
|
function createTipDom(h, context, type, tip) {
const stage = context.vuescroll.state[`${type}Stage`];
let dom = null;
// Return user specified animation dom
/* istanbul ignore if */
if ((dom = context.$slots[`${type}-${stage}`])) {
return dom;
}
switch (stage) {
// The dom will show at deactive stage
case 'deactive':
case 'active':
{
let className = 'active';
if (stage == 'deactive') {
className += ' deactive';
}
dom = (
<svg
class={className}
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
viewBox="0 0 1000 1000"
enable-background="new 0 0 1000 1000"
xmlSpace="preserve"
>
<metadata> Svg Vector Icons : http://www.sfont.cn </metadata>
<g>
<g transform="matrix(1 0 0 -1 0 1008)">
<path d="M10,543l490,455l490-455L885,438L570,735.5V18H430v717.5L115,438L10,543z" />
</g>
</g>
</svg>
);
}
break;
case 'start':
dom = (
<svg viewBox="0 0 50 50" class="start">
<circle stroke="true" cx="25" cy="25" r="20" class="bg-path" />
<circle cx="25" cy="25" r="20" class="active-path" />
</svg>
);
break;
case 'beforeDeactive':
dom = (
<svg
viewBox="0 0 1024 1024"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
p-id="3562"
>
<path
d="M512 0C229.706831 0 0 229.667446 0 512s229.667446 512 512 512c282.293169 0 512-229.667446 512-512S794.332554 0 512 0z m282.994215 353.406031L433.2544 715.145846a31.484062 31.484062 0 0 1-22.275938 9.231754h-0.4096a31.586462 31.586462 0 0 1-22.449231-9.814646L228.430769 546.327631a31.507692 31.507692 0 0 1 45.701908-43.386093l137.4208 144.785724L750.442338 308.854154a31.507692 31.507692 0 1 1 44.551877 44.551877z"
fill=""
p-id="3563"
/>
</svg>
);
break;
}
return [dom, tip];
}
|
[
"function",
"createTipDom",
"(",
"h",
",",
"context",
",",
"type",
",",
"tip",
")",
"{",
"const",
"stage",
"=",
"context",
".",
"vuescroll",
".",
"state",
"[",
"`",
"${",
"type",
"}",
"`",
"]",
";",
"let",
"dom",
"=",
"null",
";",
"// Return user specified animation dom",
"/* istanbul ignore if */",
"if",
"(",
"(",
"dom",
"=",
"context",
".",
"$slots",
"[",
"`",
"${",
"type",
"}",
"${",
"stage",
"}",
"`",
"]",
")",
")",
"{",
"return",
"dom",
";",
"}",
"switch",
"(",
"stage",
")",
"{",
"// The dom will show at deactive stage",
"case",
"'deactive'",
":",
"case",
"'active'",
":",
"{",
"let",
"className",
"=",
"'active'",
";",
"if",
"(",
"stage",
"==",
"'deactive'",
")",
"{",
"className",
"+=",
"' deactive'",
";",
"}",
"dom",
"=",
"(",
"<",
"svg",
"class",
"=",
"{",
"className",
"}",
"version",
"=",
"\"1.1\"",
"xmlns",
"=",
"\"http://www.w3.org/2000/svg\"",
"xmlnsXlink",
"=",
"\"http://www.w3.org/1999/xlink\"",
"x",
"=",
"\"0px\"",
"y",
"=",
"\"0px\"",
"viewBox",
"=",
"\"0 0 1000 1000\"",
"enable-background",
"=",
"\"new 0 0 1000 1000\"",
"xmlSpace",
"=",
"\"preserve\"",
">",
"\n ",
"<",
"metadata",
">",
" Svg Vector Icons : http://www.sfont.cn ",
"<",
"/",
"metadata",
">",
"\n ",
"<",
"g",
">",
"\n ",
"<",
"g",
"transform",
"=",
"\"matrix(1 0 0 -1 0 1008)\"",
">",
"\n ",
"<",
"path",
"d",
"=",
"\"M10,543l490,455l490-455L885,438L570,735.5V18H430v717.5L115,438L10,543z\"",
"/",
">",
"\n ",
"<",
"/",
"g",
">",
"\n ",
"<",
"/",
"g",
">",
"\n ",
"<",
"/",
"svg",
">",
")",
";",
"}",
"break",
";",
"case",
"'start'",
":",
"dom",
"=",
"(",
"<",
"svg",
"viewBox",
"=",
"\"0 0 50 50\"",
"class",
"=",
"\"start\"",
">",
"\n ",
"<",
"circle",
"stroke",
"=",
"\"true\"",
"cx",
"=",
"\"25\"",
"cy",
"=",
"\"25\"",
"r",
"=",
"\"20\"",
"class",
"=",
"\"bg-path\"",
"/",
">",
"\n ",
"<",
"circle",
"cx",
"=",
"\"25\"",
"cy",
"=",
"\"25\"",
"r",
"=",
"\"20\"",
"class",
"=",
"\"active-path\"",
"/",
">",
"\n ",
"<",
"/",
"svg",
">",
")",
";",
"break",
";",
"case",
"'beforeDeactive'",
":",
"dom",
"=",
"(",
"<",
"svg",
"viewBox",
"=",
"\"0 0 1024 1024\"",
"version",
"=",
"\"1.1\"",
"xmlns",
"=",
"\"http://www.w3.org/2000/svg\"",
"p-id",
"=",
"\"3562\"",
">",
"\n ",
"<",
"path",
"d",
"=",
"\"M512 0C229.706831 0 0 229.667446 0 512s229.667446 512 512 512c282.293169 0 512-229.667446 512-512S794.332554 0 512 0z m282.994215 353.406031L433.2544 715.145846a31.484062 31.484062 0 0 1-22.275938 9.231754h-0.4096a31.586462 31.586462 0 0 1-22.449231-9.814646L228.430769 546.327631a31.507692 31.507692 0 0 1 45.701908-43.386093l137.4208 144.785724L750.442338 308.854154a31.507692 31.507692 0 1 1 44.551877 44.551877z\"",
"fill",
"=",
"\"\"",
"p-id",
"=",
"\"3563\"",
"/",
">",
"\n ",
"<",
"/",
"svg",
">",
")",
";",
"break",
";",
"}",
"return",
"[",
"dom",
",",
"tip",
"]",
";",
"}"
] |
Create load or refresh tip dom of each stages
|
[
"Create",
"load",
"or",
"refresh",
"tip",
"dom",
"of",
"each",
"stages"
] |
8e91550833db7e94b334dfddba20b876c9b1e59c
|
https://github.com/YvesCoding/vuescroll/blob/8e91550833db7e94b334dfddba20b876c9b1e59c/src/mode/slide/slide-panel.js#L104-L171
|
11,136
|
YvesCoding/vuescroll
|
src/mode/mix/config.js
|
configValidator
|
function configValidator(ops) {
let renderError = false;
const { vuescroll } = ops;
// validate modes
if (!~modes.indexOf(vuescroll.mode)) {
error(
`Unknown mode: ${
vuescroll.mode
},the vuescroll's option "mode" should be one of the ${modes}`
);
renderError = true;
}
return renderError;
}
|
javascript
|
function configValidator(ops) {
let renderError = false;
const { vuescroll } = ops;
// validate modes
if (!~modes.indexOf(vuescroll.mode)) {
error(
`Unknown mode: ${
vuescroll.mode
},the vuescroll's option "mode" should be one of the ${modes}`
);
renderError = true;
}
return renderError;
}
|
[
"function",
"configValidator",
"(",
"ops",
")",
"{",
"let",
"renderError",
"=",
"false",
";",
"const",
"{",
"vuescroll",
"}",
"=",
"ops",
";",
"// validate modes",
"if",
"(",
"!",
"~",
"modes",
".",
"indexOf",
"(",
"vuescroll",
".",
"mode",
")",
")",
"{",
"error",
"(",
"`",
"${",
"vuescroll",
".",
"mode",
"}",
"${",
"modes",
"}",
"`",
")",
";",
"renderError",
"=",
"true",
";",
"}",
"return",
"renderError",
";",
"}"
] |
validate the options
@export
@param {any} ops
|
[
"validate",
"the",
"options"
] |
8e91550833db7e94b334dfddba20b876c9b1e59c
|
https://github.com/YvesCoding/vuescroll/blob/8e91550833db7e94b334dfddba20b876c9b1e59c/src/mode/mix/config.js#L21-L36
|
11,137
|
Azure/azure-storage-node
|
lib/common/streams/batchoperation.js
|
BatchOperation
|
function BatchOperation(name, options) {
if (!options) {
options = {};
}
this.name = name;
this.logger = options.logger || new Logger(Logger.LogLevels.INFO);
this.operationMemoryUsage = options.operationMemoryUsage || DEFAULT_OPERATION_MEMORY_USAGE;
this.callbackInOrder = options.callbackInOrder === true;
this.callInOrder = options.callInOrder === true;
this._currentOperationId = this.callbackInOrder ? 1 : -1;
this.concurrency = DEFAULT_GLOBAL_CONCURRENCY;
this.enableReuseSocket = (nodeVersion.major > 0 || nodeVersion.minor >= 10) && options.enableReuseSocket;
this._emitter = new EventEmitter();
this._enableComplete = false;
this._ended = false;
this._error = null;
this._paused = false;
//Total operations count(queued and active and connected)
this._totalOperation = 0;
//Action operations count(The operations which are connecting to remote or executing callback or queued for executing)
this._activeOperation = 0;
//Queued operations count(The operations which are connecting to remote or queued for executing)
this._queuedOperation = 0;
//finished operation should be removed from this array
this._operations = [];
}
|
javascript
|
function BatchOperation(name, options) {
if (!options) {
options = {};
}
this.name = name;
this.logger = options.logger || new Logger(Logger.LogLevels.INFO);
this.operationMemoryUsage = options.operationMemoryUsage || DEFAULT_OPERATION_MEMORY_USAGE;
this.callbackInOrder = options.callbackInOrder === true;
this.callInOrder = options.callInOrder === true;
this._currentOperationId = this.callbackInOrder ? 1 : -1;
this.concurrency = DEFAULT_GLOBAL_CONCURRENCY;
this.enableReuseSocket = (nodeVersion.major > 0 || nodeVersion.minor >= 10) && options.enableReuseSocket;
this._emitter = new EventEmitter();
this._enableComplete = false;
this._ended = false;
this._error = null;
this._paused = false;
//Total operations count(queued and active and connected)
this._totalOperation = 0;
//Action operations count(The operations which are connecting to remote or executing callback or queued for executing)
this._activeOperation = 0;
//Queued operations count(The operations which are connecting to remote or queued for executing)
this._queuedOperation = 0;
//finished operation should be removed from this array
this._operations = [];
}
|
[
"function",
"BatchOperation",
"(",
"name",
",",
"options",
")",
"{",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"logger",
"=",
"options",
".",
"logger",
"||",
"new",
"Logger",
"(",
"Logger",
".",
"LogLevels",
".",
"INFO",
")",
";",
"this",
".",
"operationMemoryUsage",
"=",
"options",
".",
"operationMemoryUsage",
"||",
"DEFAULT_OPERATION_MEMORY_USAGE",
";",
"this",
".",
"callbackInOrder",
"=",
"options",
".",
"callbackInOrder",
"===",
"true",
";",
"this",
".",
"callInOrder",
"=",
"options",
".",
"callInOrder",
"===",
"true",
";",
"this",
".",
"_currentOperationId",
"=",
"this",
".",
"callbackInOrder",
"?",
"1",
":",
"-",
"1",
";",
"this",
".",
"concurrency",
"=",
"DEFAULT_GLOBAL_CONCURRENCY",
";",
"this",
".",
"enableReuseSocket",
"=",
"(",
"nodeVersion",
".",
"major",
">",
"0",
"||",
"nodeVersion",
".",
"minor",
">=",
"10",
")",
"&&",
"options",
".",
"enableReuseSocket",
";",
"this",
".",
"_emitter",
"=",
"new",
"EventEmitter",
"(",
")",
";",
"this",
".",
"_enableComplete",
"=",
"false",
";",
"this",
".",
"_ended",
"=",
"false",
";",
"this",
".",
"_error",
"=",
"null",
";",
"this",
".",
"_paused",
"=",
"false",
";",
"//Total operations count(queued and active and connected)",
"this",
".",
"_totalOperation",
"=",
"0",
";",
"//Action operations count(The operations which are connecting to remote or executing callback or queued for executing)",
"this",
".",
"_activeOperation",
"=",
"0",
";",
"//Queued operations count(The operations which are connecting to remote or queued for executing)",
"this",
".",
"_queuedOperation",
"=",
"0",
";",
"//finished operation should be removed from this array",
"this",
".",
"_operations",
"=",
"[",
"]",
";",
"}"
] |
Concurrently execute batch operations and call operation callback randomly or in sequence.
Random mode is for uploading.
1. Fire user callback when the operation is done.
Sequence mode is for downloading.
1. Fire user callback when the operation is done and all previous operations and callback has finished.
2. BatchOperation guarantees the user callback is fired one by one.
3. The next user callback can't be fired until the current one is completed.
|
[
"Concurrently",
"execute",
"batch",
"operations",
"and",
"call",
"operation",
"callback",
"randomly",
"or",
"in",
"sequence",
".",
"Random",
"mode",
"is",
"for",
"uploading",
".",
"1",
".",
"Fire",
"user",
"callback",
"when",
"the",
"operation",
"is",
"done",
".",
"Sequence",
"mode",
"is",
"for",
"downloading",
".",
"1",
".",
"Fire",
"user",
"callback",
"when",
"the",
"operation",
"is",
"done",
"and",
"all",
"previous",
"operations",
"and",
"callback",
"has",
"finished",
".",
"2",
".",
"BatchOperation",
"guarantees",
"the",
"user",
"callback",
"is",
"fired",
"one",
"by",
"one",
".",
"3",
".",
"The",
"next",
"user",
"callback",
"can",
"t",
"be",
"fired",
"until",
"the",
"current",
"one",
"is",
"completed",
"."
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/lib/common/streams/batchoperation.js#L48-L79
|
11,138
|
Azure/azure-storage-node
|
lib/common/streams/batchoperation.js
|
RestOperation
|
function RestOperation(serviceClient, operation) {
this.status = OperationState.Inited;
this.operationId = -1;
this._callbackArguments = null;
// setup callback and args
this._userCallback = arguments[arguments.length - 1];
var sliceEnd = arguments.length;
if(azureutil.objectIsFunction(this._userCallback)) {
sliceEnd--;
} else {
this._userCallback = null;
}
var operationArguments = Array.prototype.slice.call(arguments).slice(2, sliceEnd);
this.run = function(cb) {
var func = serviceClient[operation];
if(!func) {
throw new ArgumentError('operation', util.format('Unknown operation %s in serviceclient', operation));
} else {
if(!cb) cb = this._userCallback;
operationArguments.push(cb);
this.status = OperationState.RUNNING;
func.apply(serviceClient, operationArguments);
operationArguments = operation = null;
}
};
this._fireUserCallback = function () {
if(this._userCallback) {
this._userCallback.apply(null, this._callbackArguments);
}
};
}
|
javascript
|
function RestOperation(serviceClient, operation) {
this.status = OperationState.Inited;
this.operationId = -1;
this._callbackArguments = null;
// setup callback and args
this._userCallback = arguments[arguments.length - 1];
var sliceEnd = arguments.length;
if(azureutil.objectIsFunction(this._userCallback)) {
sliceEnd--;
} else {
this._userCallback = null;
}
var operationArguments = Array.prototype.slice.call(arguments).slice(2, sliceEnd);
this.run = function(cb) {
var func = serviceClient[operation];
if(!func) {
throw new ArgumentError('operation', util.format('Unknown operation %s in serviceclient', operation));
} else {
if(!cb) cb = this._userCallback;
operationArguments.push(cb);
this.status = OperationState.RUNNING;
func.apply(serviceClient, operationArguments);
operationArguments = operation = null;
}
};
this._fireUserCallback = function () {
if(this._userCallback) {
this._userCallback.apply(null, this._callbackArguments);
}
};
}
|
[
"function",
"RestOperation",
"(",
"serviceClient",
",",
"operation",
")",
"{",
"this",
".",
"status",
"=",
"OperationState",
".",
"Inited",
";",
"this",
".",
"operationId",
"=",
"-",
"1",
";",
"this",
".",
"_callbackArguments",
"=",
"null",
";",
"// setup callback and args",
"this",
".",
"_userCallback",
"=",
"arguments",
"[",
"arguments",
".",
"length",
"-",
"1",
"]",
";",
"var",
"sliceEnd",
"=",
"arguments",
".",
"length",
";",
"if",
"(",
"azureutil",
".",
"objectIsFunction",
"(",
"this",
".",
"_userCallback",
")",
")",
"{",
"sliceEnd",
"--",
";",
"}",
"else",
"{",
"this",
".",
"_userCallback",
"=",
"null",
";",
"}",
"var",
"operationArguments",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
".",
"slice",
"(",
"2",
",",
"sliceEnd",
")",
";",
"this",
".",
"run",
"=",
"function",
"(",
"cb",
")",
"{",
"var",
"func",
"=",
"serviceClient",
"[",
"operation",
"]",
";",
"if",
"(",
"!",
"func",
")",
"{",
"throw",
"new",
"ArgumentError",
"(",
"'operation'",
",",
"util",
".",
"format",
"(",
"'Unknown operation %s in serviceclient'",
",",
"operation",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"cb",
")",
"cb",
"=",
"this",
".",
"_userCallback",
";",
"operationArguments",
".",
"push",
"(",
"cb",
")",
";",
"this",
".",
"status",
"=",
"OperationState",
".",
"RUNNING",
";",
"func",
".",
"apply",
"(",
"serviceClient",
",",
"operationArguments",
")",
";",
"operationArguments",
"=",
"operation",
"=",
"null",
";",
"}",
"}",
";",
"this",
".",
"_fireUserCallback",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_userCallback",
")",
"{",
"this",
".",
"_userCallback",
".",
"apply",
"(",
"null",
",",
"this",
".",
"_callbackArguments",
")",
";",
"}",
"}",
";",
"}"
] |
Rest operation in sdk
|
[
"Rest",
"operation",
"in",
"sdk"
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/lib/common/streams/batchoperation.js#L355-L388
|
11,139
|
Azure/azure-storage-node
|
lib/common/streams/batchoperation.js
|
CommonOperation
|
function CommonOperation(operationFunc, callback) {
this.status = OperationState.Inited;
this.operationId = -1;
this._callbackArguments = null;
var sliceStart = 2;
if (azureutil.objectIsFunction(callback)) {
this._userCallback = callback;
} else {
this._userCallback = null;
sliceStart = 1;
}
var operationArguments = Array.prototype.slice.call(arguments).slice(sliceStart);
this.run = function (cb) {
if (!cb) cb = this._userCallback;
operationArguments.push(cb);
this.status = OperationState.RUNNING;
operationFunc.apply(null, operationArguments);
operationArguments = operationFunc = null;
};
this._fireUserCallback = function () {
if (this._userCallback) {
this._userCallback.apply(null, this._callbackArguments);
}
this._userCallback = this._callbackArguments = null;
};
}
|
javascript
|
function CommonOperation(operationFunc, callback) {
this.status = OperationState.Inited;
this.operationId = -1;
this._callbackArguments = null;
var sliceStart = 2;
if (azureutil.objectIsFunction(callback)) {
this._userCallback = callback;
} else {
this._userCallback = null;
sliceStart = 1;
}
var operationArguments = Array.prototype.slice.call(arguments).slice(sliceStart);
this.run = function (cb) {
if (!cb) cb = this._userCallback;
operationArguments.push(cb);
this.status = OperationState.RUNNING;
operationFunc.apply(null, operationArguments);
operationArguments = operationFunc = null;
};
this._fireUserCallback = function () {
if (this._userCallback) {
this._userCallback.apply(null, this._callbackArguments);
}
this._userCallback = this._callbackArguments = null;
};
}
|
[
"function",
"CommonOperation",
"(",
"operationFunc",
",",
"callback",
")",
"{",
"this",
".",
"status",
"=",
"OperationState",
".",
"Inited",
";",
"this",
".",
"operationId",
"=",
"-",
"1",
";",
"this",
".",
"_callbackArguments",
"=",
"null",
";",
"var",
"sliceStart",
"=",
"2",
";",
"if",
"(",
"azureutil",
".",
"objectIsFunction",
"(",
"callback",
")",
")",
"{",
"this",
".",
"_userCallback",
"=",
"callback",
";",
"}",
"else",
"{",
"this",
".",
"_userCallback",
"=",
"null",
";",
"sliceStart",
"=",
"1",
";",
"}",
"var",
"operationArguments",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
".",
"slice",
"(",
"sliceStart",
")",
";",
"this",
".",
"run",
"=",
"function",
"(",
"cb",
")",
"{",
"if",
"(",
"!",
"cb",
")",
"cb",
"=",
"this",
".",
"_userCallback",
";",
"operationArguments",
".",
"push",
"(",
"cb",
")",
";",
"this",
".",
"status",
"=",
"OperationState",
".",
"RUNNING",
";",
"operationFunc",
".",
"apply",
"(",
"null",
",",
"operationArguments",
")",
";",
"operationArguments",
"=",
"operationFunc",
"=",
"null",
";",
"}",
";",
"this",
".",
"_fireUserCallback",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_userCallback",
")",
"{",
"this",
".",
"_userCallback",
".",
"apply",
"(",
"null",
",",
"this",
".",
"_callbackArguments",
")",
";",
"}",
"this",
".",
"_userCallback",
"=",
"this",
".",
"_callbackArguments",
"=",
"null",
";",
"}",
";",
"}"
] |
Common operation wrapper
|
[
"Common",
"operation",
"wrapper"
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/lib/common/streams/batchoperation.js#L395-L421
|
11,140
|
Azure/azure-storage-node
|
lib/services/file/internal/filerangestream.js
|
FileRangeStream
|
function FileRangeStream(fileServiceClient, share, directory, file, options) {
FileRangeStream['super_'].call(this, fileServiceClient, null, null, options);
this._lengthHeader = Constants.HeaderConstants.FILE_CONTENT_LENGTH;
if (options.minRangeSize) {
this._minRangeSize = options.minRangeSize;
} else {
this._minRangeSize = Constants.FileConstants.MIN_WRITE_FILE_SIZE_IN_BYTES;
}
if (options.maxRangeSize) {
this._maxRangeSize = options.maxRangeSize;
} else {
this._maxRangeSize = Constants.FileConstants.DEFAULT_WRITE_SIZE_IN_BYTES;
}
this._listFunc = fileServiceClient.listRanges;
this._resourcePath.push(share);
this._resourcePath.push(directory);
this._resourcePath.push(file);
}
|
javascript
|
function FileRangeStream(fileServiceClient, share, directory, file, options) {
FileRangeStream['super_'].call(this, fileServiceClient, null, null, options);
this._lengthHeader = Constants.HeaderConstants.FILE_CONTENT_LENGTH;
if (options.minRangeSize) {
this._minRangeSize = options.minRangeSize;
} else {
this._minRangeSize = Constants.FileConstants.MIN_WRITE_FILE_SIZE_IN_BYTES;
}
if (options.maxRangeSize) {
this._maxRangeSize = options.maxRangeSize;
} else {
this._maxRangeSize = Constants.FileConstants.DEFAULT_WRITE_SIZE_IN_BYTES;
}
this._listFunc = fileServiceClient.listRanges;
this._resourcePath.push(share);
this._resourcePath.push(directory);
this._resourcePath.push(file);
}
|
[
"function",
"FileRangeStream",
"(",
"fileServiceClient",
",",
"share",
",",
"directory",
",",
"file",
",",
"options",
")",
"{",
"FileRangeStream",
"[",
"'super_'",
"]",
".",
"call",
"(",
"this",
",",
"fileServiceClient",
",",
"null",
",",
"null",
",",
"options",
")",
";",
"this",
".",
"_lengthHeader",
"=",
"Constants",
".",
"HeaderConstants",
".",
"FILE_CONTENT_LENGTH",
";",
"if",
"(",
"options",
".",
"minRangeSize",
")",
"{",
"this",
".",
"_minRangeSize",
"=",
"options",
".",
"minRangeSize",
";",
"}",
"else",
"{",
"this",
".",
"_minRangeSize",
"=",
"Constants",
".",
"FileConstants",
".",
"MIN_WRITE_FILE_SIZE_IN_BYTES",
";",
"}",
"if",
"(",
"options",
".",
"maxRangeSize",
")",
"{",
"this",
".",
"_maxRangeSize",
"=",
"options",
".",
"maxRangeSize",
";",
"}",
"else",
"{",
"this",
".",
"_maxRangeSize",
"=",
"Constants",
".",
"FileConstants",
".",
"DEFAULT_WRITE_SIZE_IN_BYTES",
";",
"}",
"this",
".",
"_listFunc",
"=",
"fileServiceClient",
".",
"listRanges",
";",
"this",
".",
"_resourcePath",
".",
"push",
"(",
"share",
")",
";",
"this",
".",
"_resourcePath",
".",
"push",
"(",
"directory",
")",
";",
"this",
".",
"_resourcePath",
".",
"push",
"(",
"file",
")",
";",
"}"
] |
File range stream
|
[
"File",
"range",
"stream"
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/lib/services/file/internal/filerangestream.js#L24-L42
|
11,141
|
Azure/azure-storage-node
|
examples/samples/sassample.js
|
function () {
var options = { publicAccessLevel: BlobUtilities.BlobContainerPublicAccessType.CONTAINER };
blobService.setContainerAcl(container, signedIdentifiers, options, function(error) {
if (error) {
console.log(error);
} else {
console.log('Uploaded the permissions for the container ' + container);
callback();
}
});
}
|
javascript
|
function () {
var options = { publicAccessLevel: BlobUtilities.BlobContainerPublicAccessType.CONTAINER };
blobService.setContainerAcl(container, signedIdentifiers, options, function(error) {
if (error) {
console.log(error);
} else {
console.log('Uploaded the permissions for the container ' + container);
callback();
}
});
}
|
[
"function",
"(",
")",
"{",
"var",
"options",
"=",
"{",
"publicAccessLevel",
":",
"BlobUtilities",
".",
"BlobContainerPublicAccessType",
".",
"CONTAINER",
"}",
";",
"blobService",
".",
"setContainerAcl",
"(",
"container",
",",
"signedIdentifiers",
",",
"options",
",",
"function",
"(",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"console",
".",
"log",
"(",
"error",
")",
";",
"}",
"else",
"{",
"console",
".",
"log",
"(",
"'Uploaded the permissions for the container '",
"+",
"container",
")",
";",
"callback",
"(",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Wait 30 seconds for the container acl to be processed
|
[
"Wait",
"30",
"seconds",
"for",
"the",
"container",
"acl",
"to",
"be",
"processed"
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/examples/samples/sassample.js#L161-L171
|
|
11,142
|
Azure/azure-storage-node
|
examples/samples/retrypolicysample.js
|
setRetries
|
function setRetries() {
console.log('Starting Sample 1 - setRetries.');
// By default, no retry will be performed with all kinds of services created
// by Azure storage client library for Node.js.
var blobServiceWithoutRetry = azure.createBlobService();
console.log('BlobService instance created, no retry will be performed by default.');
// There are two pre-written retry policies: ExponentialRetryPolicyFilter
// and LinearRetryPolicyFilter can be used with modifiable settings.
// Use an exponential retry with customized settings.
var fileServiceWithExponentialRetry = azure.createFileService().withFilter(
new azure.ExponentialRetryPolicyFilter(
3, // retryCount is set to 3 times.
4000, // retryInterval is set to 4 seconds.
3000, // minRetryInterval is set to 3 seconds.
120000 // maxRetryInterval is set to 120 seconds.
));
console.log('FileService instance created and associated with ExponentialRetryPolicyFilter.');
console.log(' Retries will be performed with exponential back-off.');
// Use a default linear retry policy.
var tableServiceWithLinearRetry = azure.createTableService().withFilter(
new azure.LinearRetryPolicyFilter()); // By default, retryCount is set to 3 times and retryInterval is set to 30 seconds.
console.log('TableService instance created and associated with LinearRetryPolicyFilter,');
console.log(' Retries will be performed with linear back-off.');
console.log('Ending Sample 1 - setRetries.');
}
|
javascript
|
function setRetries() {
console.log('Starting Sample 1 - setRetries.');
// By default, no retry will be performed with all kinds of services created
// by Azure storage client library for Node.js.
var blobServiceWithoutRetry = azure.createBlobService();
console.log('BlobService instance created, no retry will be performed by default.');
// There are two pre-written retry policies: ExponentialRetryPolicyFilter
// and LinearRetryPolicyFilter can be used with modifiable settings.
// Use an exponential retry with customized settings.
var fileServiceWithExponentialRetry = azure.createFileService().withFilter(
new azure.ExponentialRetryPolicyFilter(
3, // retryCount is set to 3 times.
4000, // retryInterval is set to 4 seconds.
3000, // minRetryInterval is set to 3 seconds.
120000 // maxRetryInterval is set to 120 seconds.
));
console.log('FileService instance created and associated with ExponentialRetryPolicyFilter.');
console.log(' Retries will be performed with exponential back-off.');
// Use a default linear retry policy.
var tableServiceWithLinearRetry = azure.createTableService().withFilter(
new azure.LinearRetryPolicyFilter()); // By default, retryCount is set to 3 times and retryInterval is set to 30 seconds.
console.log('TableService instance created and associated with LinearRetryPolicyFilter,');
console.log(' Retries will be performed with linear back-off.');
console.log('Ending Sample 1 - setRetries.');
}
|
[
"function",
"setRetries",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'Starting Sample 1 - setRetries.'",
")",
";",
"// By default, no retry will be performed with all kinds of services created",
"// by Azure storage client library for Node.js.",
"var",
"blobServiceWithoutRetry",
"=",
"azure",
".",
"createBlobService",
"(",
")",
";",
"console",
".",
"log",
"(",
"'BlobService instance created, no retry will be performed by default.'",
")",
";",
"// There are two pre-written retry policies: ExponentialRetryPolicyFilter",
"// and LinearRetryPolicyFilter can be used with modifiable settings.",
"// Use an exponential retry with customized settings.",
"var",
"fileServiceWithExponentialRetry",
"=",
"azure",
".",
"createFileService",
"(",
")",
".",
"withFilter",
"(",
"new",
"azure",
".",
"ExponentialRetryPolicyFilter",
"(",
"3",
",",
"// retryCount is set to 3 times.",
"4000",
",",
"// retryInterval is set to 4 seconds.",
"3000",
",",
"// minRetryInterval is set to 3 seconds.",
"120000",
"// maxRetryInterval is set to 120 seconds.",
")",
")",
";",
"console",
".",
"log",
"(",
"'FileService instance created and associated with ExponentialRetryPolicyFilter.'",
")",
";",
"console",
".",
"log",
"(",
"' Retries will be performed with exponential back-off.'",
")",
";",
"// Use a default linear retry policy.",
"var",
"tableServiceWithLinearRetry",
"=",
"azure",
".",
"createTableService",
"(",
")",
".",
"withFilter",
"(",
"new",
"azure",
".",
"LinearRetryPolicyFilter",
"(",
")",
")",
";",
"// By default, retryCount is set to 3 times and retryInterval is set to 30 seconds.",
"console",
".",
"log",
"(",
"'TableService instance created and associated with LinearRetryPolicyFilter,'",
")",
";",
"console",
".",
"log",
"(",
"' Retries will be performed with linear back-off.'",
")",
";",
"console",
".",
"log",
"(",
"'Ending Sample 1 - setRetries.'",
")",
";",
"}"
] |
Demonstrate how to use pre-written retry policies.
By default, no retry will be performed with service instances newly created.
Several pre-written retry policies are available with modifiable settings,
and can be used through associating filter.
|
[
"Demonstrate",
"how",
"to",
"use",
"pre",
"-",
"written",
"retry",
"policies",
".",
"By",
"default",
"no",
"retry",
"will",
"be",
"performed",
"with",
"service",
"instances",
"newly",
"created",
".",
"Several",
"pre",
"-",
"written",
"retry",
"policies",
"are",
"available",
"with",
"modifiable",
"settings",
"and",
"can",
"be",
"used",
"through",
"associating",
"filter",
"."
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/examples/samples/retrypolicysample.js#L54-L82
|
11,143
|
Azure/azure-storage-node
|
examples/samples/retrypolicysample.js
|
setCustomRetryPolicy
|
function setCustomRetryPolicy() {
console.log('Starting Sample 2 - setCustomRetryPolicy.');
// Step 1 : Set the retry policy to customized retry policy which will
// not retry on any failing status code other than the excepted one.
var retryOnContainerBeingDeleted = new RetryPolicyFilter();
retryOnContainerBeingDeleted.retryCount = 5;
retryOnContainerBeingDeleted.retryInterval = 5000;
retryOnContainerBeingDeleted.shouldRetry = function (statusCode, retryData) {
console.log(' Made the request at ' + new Date().toUTCString() + ', received StatusCode: ' + statusCode);
var retryInfo = {};
// retries on any bad status code other than 409
if (statusCode >= 300 && statusCode !== 409 && statusCode !== 500) {
retryInfo.retryable = false;
} else {
var currentCount = (retryData && retryData.retryCount) ? retryData.retryCount : 0;
retryInfo = {
retryInterval: this.retryInterval + 2000 * currentCount,
retryable: currentCount < this.retryCount
};
}
return retryInfo;
};
blobService = azure.createBlobService().withFilter(retryOnContainerBeingDeleted);
// optionally set a proxy
/*var proxy = {
protocol: 'http:',
host: '127.0.0.1',
port: 8888
};
blobService.setProxy(proxy);*/
// Step 2: Create the container
createContainer(function () {
// Step 3: Fetch attributes from the container using LocationMode.SECONDARY_THEN_PRIMARY
fetchAttributesContainer(function () {
// Step 4: Lease the container
leaseContainer(function () {
// Step 5: Lease the container again, retrying until it succeeds
leaseContainer(function () {
// Step 6: Delete the container
deleteContainer(function () {
console.log('Ending Sample 2 - setCustomRetryPolicy.');
});
});
});
});
});
}
|
javascript
|
function setCustomRetryPolicy() {
console.log('Starting Sample 2 - setCustomRetryPolicy.');
// Step 1 : Set the retry policy to customized retry policy which will
// not retry on any failing status code other than the excepted one.
var retryOnContainerBeingDeleted = new RetryPolicyFilter();
retryOnContainerBeingDeleted.retryCount = 5;
retryOnContainerBeingDeleted.retryInterval = 5000;
retryOnContainerBeingDeleted.shouldRetry = function (statusCode, retryData) {
console.log(' Made the request at ' + new Date().toUTCString() + ', received StatusCode: ' + statusCode);
var retryInfo = {};
// retries on any bad status code other than 409
if (statusCode >= 300 && statusCode !== 409 && statusCode !== 500) {
retryInfo.retryable = false;
} else {
var currentCount = (retryData && retryData.retryCount) ? retryData.retryCount : 0;
retryInfo = {
retryInterval: this.retryInterval + 2000 * currentCount,
retryable: currentCount < this.retryCount
};
}
return retryInfo;
};
blobService = azure.createBlobService().withFilter(retryOnContainerBeingDeleted);
// optionally set a proxy
/*var proxy = {
protocol: 'http:',
host: '127.0.0.1',
port: 8888
};
blobService.setProxy(proxy);*/
// Step 2: Create the container
createContainer(function () {
// Step 3: Fetch attributes from the container using LocationMode.SECONDARY_THEN_PRIMARY
fetchAttributesContainer(function () {
// Step 4: Lease the container
leaseContainer(function () {
// Step 5: Lease the container again, retrying until it succeeds
leaseContainer(function () {
// Step 6: Delete the container
deleteContainer(function () {
console.log('Ending Sample 2 - setCustomRetryPolicy.');
});
});
});
});
});
}
|
[
"function",
"setCustomRetryPolicy",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'Starting Sample 2 - setCustomRetryPolicy.'",
")",
";",
"// Step 1 : Set the retry policy to customized retry policy which will",
"// not retry on any failing status code other than the excepted one.",
"var",
"retryOnContainerBeingDeleted",
"=",
"new",
"RetryPolicyFilter",
"(",
")",
";",
"retryOnContainerBeingDeleted",
".",
"retryCount",
"=",
"5",
";",
"retryOnContainerBeingDeleted",
".",
"retryInterval",
"=",
"5000",
";",
"retryOnContainerBeingDeleted",
".",
"shouldRetry",
"=",
"function",
"(",
"statusCode",
",",
"retryData",
")",
"{",
"console",
".",
"log",
"(",
"' Made the request at '",
"+",
"new",
"Date",
"(",
")",
".",
"toUTCString",
"(",
")",
"+",
"', received StatusCode: '",
"+",
"statusCode",
")",
";",
"var",
"retryInfo",
"=",
"{",
"}",
";",
"// retries on any bad status code other than 409 ",
"if",
"(",
"statusCode",
">=",
"300",
"&&",
"statusCode",
"!==",
"409",
"&&",
"statusCode",
"!==",
"500",
")",
"{",
"retryInfo",
".",
"retryable",
"=",
"false",
";",
"}",
"else",
"{",
"var",
"currentCount",
"=",
"(",
"retryData",
"&&",
"retryData",
".",
"retryCount",
")",
"?",
"retryData",
".",
"retryCount",
":",
"0",
";",
"retryInfo",
"=",
"{",
"retryInterval",
":",
"this",
".",
"retryInterval",
"+",
"2000",
"*",
"currentCount",
",",
"retryable",
":",
"currentCount",
"<",
"this",
".",
"retryCount",
"}",
";",
"}",
"return",
"retryInfo",
";",
"}",
";",
"blobService",
"=",
"azure",
".",
"createBlobService",
"(",
")",
".",
"withFilter",
"(",
"retryOnContainerBeingDeleted",
")",
";",
"// optionally set a proxy",
"/*var proxy = {\n protocol: 'http:',\n host: '127.0.0.1',\n port: 8888\n };\n\n blobService.setProxy(proxy);*/",
"// Step 2: Create the container",
"createContainer",
"(",
"function",
"(",
")",
"{",
"// Step 3: Fetch attributes from the container using LocationMode.SECONDARY_THEN_PRIMARY",
"fetchAttributesContainer",
"(",
"function",
"(",
")",
"{",
"// Step 4: Lease the container",
"leaseContainer",
"(",
"function",
"(",
")",
"{",
"// Step 5: Lease the container again, retrying until it succeeds",
"leaseContainer",
"(",
"function",
"(",
")",
"{",
"// Step 6: Delete the container",
"deleteContainer",
"(",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'Ending Sample 2 - setCustomRetryPolicy.'",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Demonstrate how to use custom retry policy.
Any custom retry logic may be used by simply creating and setting RetryPolicyFilter instance.
|
[
"Demonstrate",
"how",
"to",
"use",
"custom",
"retry",
"policy",
".",
"Any",
"custom",
"retry",
"logic",
"may",
"be",
"used",
"by",
"simply",
"creating",
"and",
"setting",
"RetryPolicyFilter",
"instance",
"."
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/examples/samples/retrypolicysample.js#L88-L149
|
11,144
|
Azure/azure-storage-node
|
lib/common/streams/filereadstream.js
|
FileReadStream
|
function FileReadStream(path, options) {
stream.Stream.call(this);
this.readable = true;
if(!options) {
options = {};
}
this._destroyed = false;
this._streamEnded = false;
this._fd = null;
this._fileName = undefined;
this._highWaterMark = options.highWaterMark || bufferSize;
this._offset = 0;
this._paused = undefined;
this._allocator = options.allocator;
this._fileName = path;
this._md5hash = null;
this._md5sum = undefined;
if (options.calcContentMd5) {
this._md5hash = new Md5Wrapper().createMd5Hash();
}
this._open();
}
|
javascript
|
function FileReadStream(path, options) {
stream.Stream.call(this);
this.readable = true;
if(!options) {
options = {};
}
this._destroyed = false;
this._streamEnded = false;
this._fd = null;
this._fileName = undefined;
this._highWaterMark = options.highWaterMark || bufferSize;
this._offset = 0;
this._paused = undefined;
this._allocator = options.allocator;
this._fileName = path;
this._md5hash = null;
this._md5sum = undefined;
if (options.calcContentMd5) {
this._md5hash = new Md5Wrapper().createMd5Hash();
}
this._open();
}
|
[
"function",
"FileReadStream",
"(",
"path",
",",
"options",
")",
"{",
"stream",
".",
"Stream",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"readable",
"=",
"true",
";",
"if",
"(",
"!",
"options",
")",
"{",
"options",
"=",
"{",
"}",
";",
"}",
"this",
".",
"_destroyed",
"=",
"false",
";",
"this",
".",
"_streamEnded",
"=",
"false",
";",
"this",
".",
"_fd",
"=",
"null",
";",
"this",
".",
"_fileName",
"=",
"undefined",
";",
"this",
".",
"_highWaterMark",
"=",
"options",
".",
"highWaterMark",
"||",
"bufferSize",
";",
"this",
".",
"_offset",
"=",
"0",
";",
"this",
".",
"_paused",
"=",
"undefined",
";",
"this",
".",
"_allocator",
"=",
"options",
".",
"allocator",
";",
"this",
".",
"_fileName",
"=",
"path",
";",
"this",
".",
"_md5hash",
"=",
"null",
";",
"this",
".",
"_md5sum",
"=",
"undefined",
";",
"if",
"(",
"options",
".",
"calcContentMd5",
")",
"{",
"this",
".",
"_md5hash",
"=",
"new",
"Md5Wrapper",
"(",
")",
".",
"createMd5Hash",
"(",
")",
";",
"}",
"this",
".",
"_open",
"(",
")",
";",
"}"
] |
File read stream
1. Calculate md5
2. Track reading offset
3. Work with customize memory allocator
4. Buffer data from stream.
@param {object} options stream.Readable options
|
[
"File",
"read",
"stream",
"1",
".",
"Calculate",
"md5",
"2",
".",
"Track",
"reading",
"offset",
"3",
".",
"Work",
"with",
"customize",
"memory",
"allocator",
"4",
".",
"Buffer",
"data",
"from",
"stream",
"."
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/lib/common/streams/filereadstream.js#L36-L62
|
11,145
|
Azure/azure-storage-node
|
lib/common/streams/speedsummary.js
|
toHumanReadableSize
|
function toHumanReadableSize(size, len) {
if(!size) return '0B';
if (!len || len <= 0) {
len = 2;
}
var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor( Math.log(size) / Math.log(1024));
return (size/Math.pow(1024, i)).toFixed(len) + units[i];
}
|
javascript
|
function toHumanReadableSize(size, len) {
if(!size) return '0B';
if (!len || len <= 0) {
len = 2;
}
var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor( Math.log(size) / Math.log(1024));
return (size/Math.pow(1024, i)).toFixed(len) + units[i];
}
|
[
"function",
"toHumanReadableSize",
"(",
"size",
",",
"len",
")",
"{",
"if",
"(",
"!",
"size",
")",
"return",
"'0B'",
";",
"if",
"(",
"!",
"len",
"||",
"len",
"<=",
"0",
")",
"{",
"len",
"=",
"2",
";",
"}",
"var",
"units",
"=",
"[",
"'B'",
",",
"'KB'",
",",
"'MB'",
",",
"'GB'",
",",
"'TB'",
",",
"'PB'",
",",
"'EB'",
",",
"'ZB'",
",",
"'YB'",
"]",
";",
"var",
"i",
"=",
"Math",
".",
"floor",
"(",
"Math",
".",
"log",
"(",
"size",
")",
"/",
"Math",
".",
"log",
"(",
"1024",
")",
")",
";",
"return",
"(",
"size",
"/",
"Math",
".",
"pow",
"(",
"1024",
",",
"i",
")",
")",
".",
"toFixed",
"(",
"len",
")",
"+",
"units",
"[",
"i",
"]",
";",
"}"
] |
Convert the size to human readable size
|
[
"Convert",
"the",
"size",
"to",
"human",
"readable",
"size"
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/lib/common/streams/speedsummary.js#L42-L50
|
11,146
|
Azure/azure-storage-node
|
lib/common/services/storageservicesettings.js
|
StorageServiceSettings
|
function StorageServiceSettings(name, key, sasToken, blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint, usePathStyleUri, token) {
this._name = name;
this._key = key;
if (sasToken && sasToken[0] === '?') {
this._sasToken = sasToken.slice(1);
} else {
this._sasToken = sasToken;
}
this._blobEndpoint = blobEndpoint;
this._queueEndpoint = queueEndpoint;
this._tableEndpoint = tableEndpoint;
this._fileEndpoint = fileEndpoint;
if (usePathStyleUri) {
this._usePathStyleUri = usePathStyleUri;
} else {
this._usePathStyleUri = false;
}
this._token = token;
}
|
javascript
|
function StorageServiceSettings(name, key, sasToken, blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint, usePathStyleUri, token) {
this._name = name;
this._key = key;
if (sasToken && sasToken[0] === '?') {
this._sasToken = sasToken.slice(1);
} else {
this._sasToken = sasToken;
}
this._blobEndpoint = blobEndpoint;
this._queueEndpoint = queueEndpoint;
this._tableEndpoint = tableEndpoint;
this._fileEndpoint = fileEndpoint;
if (usePathStyleUri) {
this._usePathStyleUri = usePathStyleUri;
} else {
this._usePathStyleUri = false;
}
this._token = token;
}
|
[
"function",
"StorageServiceSettings",
"(",
"name",
",",
"key",
",",
"sasToken",
",",
"blobEndpoint",
",",
"queueEndpoint",
",",
"tableEndpoint",
",",
"fileEndpoint",
",",
"usePathStyleUri",
",",
"token",
")",
"{",
"this",
".",
"_name",
"=",
"name",
";",
"this",
".",
"_key",
"=",
"key",
";",
"if",
"(",
"sasToken",
"&&",
"sasToken",
"[",
"0",
"]",
"===",
"'?'",
")",
"{",
"this",
".",
"_sasToken",
"=",
"sasToken",
".",
"slice",
"(",
"1",
")",
";",
"}",
"else",
"{",
"this",
".",
"_sasToken",
"=",
"sasToken",
";",
"}",
"this",
".",
"_blobEndpoint",
"=",
"blobEndpoint",
";",
"this",
".",
"_queueEndpoint",
"=",
"queueEndpoint",
";",
"this",
".",
"_tableEndpoint",
"=",
"tableEndpoint",
";",
"this",
".",
"_fileEndpoint",
"=",
"fileEndpoint",
";",
"if",
"(",
"usePathStyleUri",
")",
"{",
"this",
".",
"_usePathStyleUri",
"=",
"usePathStyleUri",
";",
"}",
"else",
"{",
"this",
".",
"_usePathStyleUri",
"=",
"false",
";",
"}",
"this",
".",
"_token",
"=",
"token",
";",
"}"
] |
Creates new storage service settings instance.
@param {string} name The storage service name.
@param {string} key The storage service key.
@param {string} sasToken The storage service shared access signature token.
@param {string} blobEndpoint The storage service blob endpoint.
@param {string} queueEndpoint The storage service queue endpoint.
@param {string} tableEndpoint The storage service table endpoint.
@param {string} fileEndpoint The storage service file endpoint.
@param {bool} usePathStyleUri Boolean value indicating wether to use path style uri or not.
@param {TokenCredential} [token] The {@link TokenCredential} object.
|
[
"Creates",
"new",
"storage",
"service",
"settings",
"instance",
"."
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/lib/common/services/storageservicesettings.js#L91-L113
|
11,147
|
Azure/azure-storage-node
|
lib/services/table/models/batchresult.js
|
BatchResult
|
function BatchResult(tableService, table, operations) {
this.tableService = tableService;
this.table = table;
this.operations = operations;
this.batchBoundary = 'batch_' + BatchResult._getBoundary();
this.changesetBoundary = 'changeset_' + BatchResult._getBoundary();
}
|
javascript
|
function BatchResult(tableService, table, operations) {
this.tableService = tableService;
this.table = table;
this.operations = operations;
this.batchBoundary = 'batch_' + BatchResult._getBoundary();
this.changesetBoundary = 'changeset_' + BatchResult._getBoundary();
}
|
[
"function",
"BatchResult",
"(",
"tableService",
",",
"table",
",",
"operations",
")",
"{",
"this",
".",
"tableService",
"=",
"tableService",
";",
"this",
".",
"table",
"=",
"table",
";",
"this",
".",
"operations",
"=",
"operations",
";",
"this",
".",
"batchBoundary",
"=",
"'batch_'",
"+",
"BatchResult",
".",
"_getBoundary",
"(",
")",
";",
"this",
".",
"changesetBoundary",
"=",
"'changeset_'",
"+",
"BatchResult",
".",
"_getBoundary",
"(",
")",
";",
"}"
] |
Creates a new BatchResult.
@param {TableService} tableService The table service.
@param {string} table The table name.
@param {array} operations The array of batch operations.
@constructor
@ignore
|
[
"Creates",
"a",
"new",
"BatchResult",
"."
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/lib/services/table/models/batchresult.js#L39-L45
|
11,148
|
Azure/azure-storage-node
|
lib/common/services/storageserviceclient.js
|
StorageServiceClient
|
function StorageServiceClient(storageAccount, storageAccessKey, host, usePathStyleUri, sas, token) {
StorageServiceClient['super_'].call(this);
if(storageAccount && storageAccessKey) {
// account and key
this.storageAccount = storageAccount;
this.storageAccessKey = storageAccessKey;
this.storageCredentials = new SharedKey(this.storageAccount, this.storageAccessKey, usePathStyleUri);
} else if (sas) {
// sas
this.sasToken = sas;
this.storageCredentials = new SharedAccessSignature(sas);
} else if (token) {
// access token
this.token = token;
this.storageCredentials = new TokenSigner(token);
} else {
// anonymous
this.anonymous = true;
this.storageCredentials = {
signRequest: function(webResource, callback){
// no op, anonymous access
callback(null);
}
};
}
if(host){
this.setHost(host);
}
this.apiVersion = HeaderConstants.TARGET_STORAGE_VERSION;
this.usePathStyleUri = usePathStyleUri;
this._initDefaultFilter();
/**
* The logger of the service. To change the log level of the services, set the `[logger.level]{@link Logger#level}`.
* @name StorageServiceClient#logger
* @type Logger
* */
this.logger = new Logger(Logger.LogLevels.INFO);
this._setDefaultProxy();
this.xml2jsSettings = StorageServiceClient._getDefaultXml2jsSettings();
this.defaultLocationMode = StorageUtilities.LocationMode.PRIMARY_ONLY;
}
|
javascript
|
function StorageServiceClient(storageAccount, storageAccessKey, host, usePathStyleUri, sas, token) {
StorageServiceClient['super_'].call(this);
if(storageAccount && storageAccessKey) {
// account and key
this.storageAccount = storageAccount;
this.storageAccessKey = storageAccessKey;
this.storageCredentials = new SharedKey(this.storageAccount, this.storageAccessKey, usePathStyleUri);
} else if (sas) {
// sas
this.sasToken = sas;
this.storageCredentials = new SharedAccessSignature(sas);
} else if (token) {
// access token
this.token = token;
this.storageCredentials = new TokenSigner(token);
} else {
// anonymous
this.anonymous = true;
this.storageCredentials = {
signRequest: function(webResource, callback){
// no op, anonymous access
callback(null);
}
};
}
if(host){
this.setHost(host);
}
this.apiVersion = HeaderConstants.TARGET_STORAGE_VERSION;
this.usePathStyleUri = usePathStyleUri;
this._initDefaultFilter();
/**
* The logger of the service. To change the log level of the services, set the `[logger.level]{@link Logger#level}`.
* @name StorageServiceClient#logger
* @type Logger
* */
this.logger = new Logger(Logger.LogLevels.INFO);
this._setDefaultProxy();
this.xml2jsSettings = StorageServiceClient._getDefaultXml2jsSettings();
this.defaultLocationMode = StorageUtilities.LocationMode.PRIMARY_ONLY;
}
|
[
"function",
"StorageServiceClient",
"(",
"storageAccount",
",",
"storageAccessKey",
",",
"host",
",",
"usePathStyleUri",
",",
"sas",
",",
"token",
")",
"{",
"StorageServiceClient",
"[",
"'super_'",
"]",
".",
"call",
"(",
"this",
")",
";",
"if",
"(",
"storageAccount",
"&&",
"storageAccessKey",
")",
"{",
"// account and key",
"this",
".",
"storageAccount",
"=",
"storageAccount",
";",
"this",
".",
"storageAccessKey",
"=",
"storageAccessKey",
";",
"this",
".",
"storageCredentials",
"=",
"new",
"SharedKey",
"(",
"this",
".",
"storageAccount",
",",
"this",
".",
"storageAccessKey",
",",
"usePathStyleUri",
")",
";",
"}",
"else",
"if",
"(",
"sas",
")",
"{",
"// sas",
"this",
".",
"sasToken",
"=",
"sas",
";",
"this",
".",
"storageCredentials",
"=",
"new",
"SharedAccessSignature",
"(",
"sas",
")",
";",
"}",
"else",
"if",
"(",
"token",
")",
"{",
"// access token",
"this",
".",
"token",
"=",
"token",
";",
"this",
".",
"storageCredentials",
"=",
"new",
"TokenSigner",
"(",
"token",
")",
";",
"}",
"else",
"{",
"// anonymous",
"this",
".",
"anonymous",
"=",
"true",
";",
"this",
".",
"storageCredentials",
"=",
"{",
"signRequest",
":",
"function",
"(",
"webResource",
",",
"callback",
")",
"{",
"// no op, anonymous access",
"callback",
"(",
"null",
")",
";",
"}",
"}",
";",
"}",
"if",
"(",
"host",
")",
"{",
"this",
".",
"setHost",
"(",
"host",
")",
";",
"}",
"this",
".",
"apiVersion",
"=",
"HeaderConstants",
".",
"TARGET_STORAGE_VERSION",
";",
"this",
".",
"usePathStyleUri",
"=",
"usePathStyleUri",
";",
"this",
".",
"_initDefaultFilter",
"(",
")",
";",
"/**\n * The logger of the service. To change the log level of the services, set the `[logger.level]{@link Logger#level}`.\n * @name StorageServiceClient#logger\n * @type Logger\n * */",
"this",
".",
"logger",
"=",
"new",
"Logger",
"(",
"Logger",
".",
"LogLevels",
".",
"INFO",
")",
";",
"this",
".",
"_setDefaultProxy",
"(",
")",
";",
"this",
".",
"xml2jsSettings",
"=",
"StorageServiceClient",
".",
"_getDefaultXml2jsSettings",
"(",
")",
";",
"this",
".",
"defaultLocationMode",
"=",
"StorageUtilities",
".",
"LocationMode",
".",
"PRIMARY_ONLY",
";",
"}"
] |
Creates a new StorageServiceClient object.
@class
The StorageServiceClient class is the base class of all the service classes.
@constructor
@param {string} storageAccount The storage account.
@param {string} storageAccessKey The storage access key.
@param {object} host The host for the service.
@param {bool} usePathStyleUri Boolean value indicating wether to use path style uris.
@param {string} sas The Shared Access Signature string.
@param {TokenCredential} [token] The {@link TokenCredential} object, which can be created with an OAuth access token string.
|
[
"Creates",
"a",
"new",
"StorageServiceClient",
"object",
"."
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/lib/common/services/storageserviceclient.js#L75-L122
|
11,149
|
Azure/azure-storage-node
|
lib/common/services/storageserviceclient.js
|
function (postPostRequestOptions, parentFilterCallback) {
// The parentFilterNext is the filter next to the merged filter.
// For 2 filters, that'd be the actual operation.
parentFilterNext(postPostRequestOptions, function (responseObject, responseCallback, finalCallback) {
parentFilterCallback(responseObject, finalCallback, function (postResponseObject) {
newFilterCallback(postResponseObject, responseCallback, finalCallback);
});
});
}
|
javascript
|
function (postPostRequestOptions, parentFilterCallback) {
// The parentFilterNext is the filter next to the merged filter.
// For 2 filters, that'd be the actual operation.
parentFilterNext(postPostRequestOptions, function (responseObject, responseCallback, finalCallback) {
parentFilterCallback(responseObject, finalCallback, function (postResponseObject) {
newFilterCallback(postResponseObject, responseCallback, finalCallback);
});
});
}
|
[
"function",
"(",
"postPostRequestOptions",
",",
"parentFilterCallback",
")",
"{",
"// The parentFilterNext is the filter next to the merged filter.",
"// For 2 filters, that'd be the actual operation.",
"parentFilterNext",
"(",
"postPostRequestOptions",
",",
"function",
"(",
"responseObject",
",",
"responseCallback",
",",
"finalCallback",
")",
"{",
"parentFilterCallback",
"(",
"responseObject",
",",
"finalCallback",
",",
"function",
"(",
"postResponseObject",
")",
"{",
"newFilterCallback",
"(",
"postResponseObject",
",",
"responseCallback",
",",
"finalCallback",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
handle parent filter pre and get Parent filter post
|
[
"handle",
"parent",
"filter",
"pre",
"and",
"get",
"Parent",
"filter",
"post"
] |
1e315487b8801b8357b8974c7d925313cb143483
|
https://github.com/Azure/azure-storage-node/blob/1e315487b8801b8357b8974c7d925313cb143483/lib/common/services/storageserviceclient.js#L796-L804
|
|
11,150
|
astefanutti/decktape
|
decktape.js
|
parseXObject
|
function parseXObject(xObject) {
const objectId = xObject.getObjectID();
const pdfStreamInput = cpyCxtParser.parseNewObject(objectId);
const xObjectDictionary = pdfStreamInput.getDictionary().toJSObject();
if (xObjectDictionary.Subtype.value === 'Image') {
// Create a hash of the compressed stream instead of using
// startReadingFromStream(pdfStreamInput) to skip uneeded decoding
const stream = cpyCxtParser.getParserStream();
stream.setPosition(pdfStreamInput.getStreamContentStart());
const digest = crypto.createHash('SHA1')
.update(Buffer.from(stream.read(pdfStreamInput.getDictionary().toJSObject().Length.value)))
.digest('hex');
if (!context.pdfXObjects[digest]) {
xObjects[digest] = objectId;
} else {
const replacement = {};
replacement[objectId] = context.pdfXObjects[digest];
cpyCxt.replaceSourceObjects(replacement);
}
} else {
parseResources(xObjectDictionary);
}
}
|
javascript
|
function parseXObject(xObject) {
const objectId = xObject.getObjectID();
const pdfStreamInput = cpyCxtParser.parseNewObject(objectId);
const xObjectDictionary = pdfStreamInput.getDictionary().toJSObject();
if (xObjectDictionary.Subtype.value === 'Image') {
// Create a hash of the compressed stream instead of using
// startReadingFromStream(pdfStreamInput) to skip uneeded decoding
const stream = cpyCxtParser.getParserStream();
stream.setPosition(pdfStreamInput.getStreamContentStart());
const digest = crypto.createHash('SHA1')
.update(Buffer.from(stream.read(pdfStreamInput.getDictionary().toJSObject().Length.value)))
.digest('hex');
if (!context.pdfXObjects[digest]) {
xObjects[digest] = objectId;
} else {
const replacement = {};
replacement[objectId] = context.pdfXObjects[digest];
cpyCxt.replaceSourceObjects(replacement);
}
} else {
parseResources(xObjectDictionary);
}
}
|
[
"function",
"parseXObject",
"(",
"xObject",
")",
"{",
"const",
"objectId",
"=",
"xObject",
".",
"getObjectID",
"(",
")",
";",
"const",
"pdfStreamInput",
"=",
"cpyCxtParser",
".",
"parseNewObject",
"(",
"objectId",
")",
";",
"const",
"xObjectDictionary",
"=",
"pdfStreamInput",
".",
"getDictionary",
"(",
")",
".",
"toJSObject",
"(",
")",
";",
"if",
"(",
"xObjectDictionary",
".",
"Subtype",
".",
"value",
"===",
"'Image'",
")",
"{",
"// Create a hash of the compressed stream instead of using",
"// startReadingFromStream(pdfStreamInput) to skip uneeded decoding",
"const",
"stream",
"=",
"cpyCxtParser",
".",
"getParserStream",
"(",
")",
";",
"stream",
".",
"setPosition",
"(",
"pdfStreamInput",
".",
"getStreamContentStart",
"(",
")",
")",
";",
"const",
"digest",
"=",
"crypto",
".",
"createHash",
"(",
"'SHA1'",
")",
".",
"update",
"(",
"Buffer",
".",
"from",
"(",
"stream",
".",
"read",
"(",
"pdfStreamInput",
".",
"getDictionary",
"(",
")",
".",
"toJSObject",
"(",
")",
".",
"Length",
".",
"value",
")",
")",
")",
".",
"digest",
"(",
"'hex'",
")",
";",
"if",
"(",
"!",
"context",
".",
"pdfXObjects",
"[",
"digest",
"]",
")",
"{",
"xObjects",
"[",
"digest",
"]",
"=",
"objectId",
";",
"}",
"else",
"{",
"const",
"replacement",
"=",
"{",
"}",
";",
"replacement",
"[",
"objectId",
"]",
"=",
"context",
".",
"pdfXObjects",
"[",
"digest",
"]",
";",
"cpyCxt",
".",
"replaceSourceObjects",
"(",
"replacement",
")",
";",
"}",
"}",
"else",
"{",
"parseResources",
"(",
"xObjectDictionary",
")",
";",
"}",
"}"
] |
Consolidate duplicate images
|
[
"Consolidate",
"duplicate",
"images"
] |
e7e666f6276e9d818e8738531a8cfb4a5c680fa2
|
https://github.com/astefanutti/decktape/blob/e7e666f6276e9d818e8738531a8cfb4a5c680fa2/decktape.js#L382-L404
|
11,151
|
astefanutti/decktape
|
decktape.js
|
parseFont
|
function parseFont(fontObject) {
const pdfStreamInput = cpyCxtParser.parseNewObject(fontObject.getObjectID());
const fontDictionary = pdfStreamInput.toJSObject();
// See "Introduction to Font Data Structures" from PDF specification
if (fontDictionary.Subtype.value === 'Type0') {
// TODO: properly support composite fonts with multiple descendants
const descendant = cpyCxtParser
.parseNewObject(fontDictionary.DescendantFonts.toJSArray()[0].getObjectID())
.toJSObject();
if (descendant.Subtype.value == 'CIDFontType2') {
const descriptor = cpyCxtParser
.parseNewObject(descendant.FontDescriptor.getObjectID())
.toJSObject();
const id = descriptor.FontFile2.getObjectID();
const buffer = readStream(cpyCxtParser.parseNewObject(id));
const font = Font.create(buffer, { type: 'ttf', hinting: true });
// PDF font name does not contain sub family on Windows 10 so a more robust key
// is computed from the font metadata
const name = descriptor.FontName.value + ' - ' + fontMetadataKey(font.data.name);
if (context.pdfFonts[name]) {
const f = context.pdfFonts[name].font;
font.data.glyf.forEach((g, i) => {
if (g.contours && g.contours.length > 0) {
if (!f.data.glyf[i].contours || f.data.glyf[i].contours.length === 0) {
f.data.glyf[i] = g;
}
} else if (g.compound) {
if (typeof f.data.glyf[i].compound === 'undefined'
&& f.data.glyf[i].contours.length === 0) {
f.data.glyf[i] = g;
}
}
});
const replacement = {};
replacement[id] = context.pdfFonts[name].id;
cpyCxt.replaceSourceObjects(replacement);
} else {
const xObjectId = printer.getObjectsContext().allocateNewObjectID();
context.pdfFonts[name] = { id: xObjectId, font: font };
const replacement = {};
replacement[id] = xObjectId;
cpyCxt.replaceSourceObjects(replacement);
}
}
}
}
|
javascript
|
function parseFont(fontObject) {
const pdfStreamInput = cpyCxtParser.parseNewObject(fontObject.getObjectID());
const fontDictionary = pdfStreamInput.toJSObject();
// See "Introduction to Font Data Structures" from PDF specification
if (fontDictionary.Subtype.value === 'Type0') {
// TODO: properly support composite fonts with multiple descendants
const descendant = cpyCxtParser
.parseNewObject(fontDictionary.DescendantFonts.toJSArray()[0].getObjectID())
.toJSObject();
if (descendant.Subtype.value == 'CIDFontType2') {
const descriptor = cpyCxtParser
.parseNewObject(descendant.FontDescriptor.getObjectID())
.toJSObject();
const id = descriptor.FontFile2.getObjectID();
const buffer = readStream(cpyCxtParser.parseNewObject(id));
const font = Font.create(buffer, { type: 'ttf', hinting: true });
// PDF font name does not contain sub family on Windows 10 so a more robust key
// is computed from the font metadata
const name = descriptor.FontName.value + ' - ' + fontMetadataKey(font.data.name);
if (context.pdfFonts[name]) {
const f = context.pdfFonts[name].font;
font.data.glyf.forEach((g, i) => {
if (g.contours && g.contours.length > 0) {
if (!f.data.glyf[i].contours || f.data.glyf[i].contours.length === 0) {
f.data.glyf[i] = g;
}
} else if (g.compound) {
if (typeof f.data.glyf[i].compound === 'undefined'
&& f.data.glyf[i].contours.length === 0) {
f.data.glyf[i] = g;
}
}
});
const replacement = {};
replacement[id] = context.pdfFonts[name].id;
cpyCxt.replaceSourceObjects(replacement);
} else {
const xObjectId = printer.getObjectsContext().allocateNewObjectID();
context.pdfFonts[name] = { id: xObjectId, font: font };
const replacement = {};
replacement[id] = xObjectId;
cpyCxt.replaceSourceObjects(replacement);
}
}
}
}
|
[
"function",
"parseFont",
"(",
"fontObject",
")",
"{",
"const",
"pdfStreamInput",
"=",
"cpyCxtParser",
".",
"parseNewObject",
"(",
"fontObject",
".",
"getObjectID",
"(",
")",
")",
";",
"const",
"fontDictionary",
"=",
"pdfStreamInput",
".",
"toJSObject",
"(",
")",
";",
"// See \"Introduction to Font Data Structures\" from PDF specification",
"if",
"(",
"fontDictionary",
".",
"Subtype",
".",
"value",
"===",
"'Type0'",
")",
"{",
"// TODO: properly support composite fonts with multiple descendants",
"const",
"descendant",
"=",
"cpyCxtParser",
".",
"parseNewObject",
"(",
"fontDictionary",
".",
"DescendantFonts",
".",
"toJSArray",
"(",
")",
"[",
"0",
"]",
".",
"getObjectID",
"(",
")",
")",
".",
"toJSObject",
"(",
")",
";",
"if",
"(",
"descendant",
".",
"Subtype",
".",
"value",
"==",
"'CIDFontType2'",
")",
"{",
"const",
"descriptor",
"=",
"cpyCxtParser",
".",
"parseNewObject",
"(",
"descendant",
".",
"FontDescriptor",
".",
"getObjectID",
"(",
")",
")",
".",
"toJSObject",
"(",
")",
";",
"const",
"id",
"=",
"descriptor",
".",
"FontFile2",
".",
"getObjectID",
"(",
")",
";",
"const",
"buffer",
"=",
"readStream",
"(",
"cpyCxtParser",
".",
"parseNewObject",
"(",
"id",
")",
")",
";",
"const",
"font",
"=",
"Font",
".",
"create",
"(",
"buffer",
",",
"{",
"type",
":",
"'ttf'",
",",
"hinting",
":",
"true",
"}",
")",
";",
"// PDF font name does not contain sub family on Windows 10 so a more robust key",
"// is computed from the font metadata",
"const",
"name",
"=",
"descriptor",
".",
"FontName",
".",
"value",
"+",
"' - '",
"+",
"fontMetadataKey",
"(",
"font",
".",
"data",
".",
"name",
")",
";",
"if",
"(",
"context",
".",
"pdfFonts",
"[",
"name",
"]",
")",
"{",
"const",
"f",
"=",
"context",
".",
"pdfFonts",
"[",
"name",
"]",
".",
"font",
";",
"font",
".",
"data",
".",
"glyf",
".",
"forEach",
"(",
"(",
"g",
",",
"i",
")",
"=>",
"{",
"if",
"(",
"g",
".",
"contours",
"&&",
"g",
".",
"contours",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"!",
"f",
".",
"data",
".",
"glyf",
"[",
"i",
"]",
".",
"contours",
"||",
"f",
".",
"data",
".",
"glyf",
"[",
"i",
"]",
".",
"contours",
".",
"length",
"===",
"0",
")",
"{",
"f",
".",
"data",
".",
"glyf",
"[",
"i",
"]",
"=",
"g",
";",
"}",
"}",
"else",
"if",
"(",
"g",
".",
"compound",
")",
"{",
"if",
"(",
"typeof",
"f",
".",
"data",
".",
"glyf",
"[",
"i",
"]",
".",
"compound",
"===",
"'undefined'",
"&&",
"f",
".",
"data",
".",
"glyf",
"[",
"i",
"]",
".",
"contours",
".",
"length",
"===",
"0",
")",
"{",
"f",
".",
"data",
".",
"glyf",
"[",
"i",
"]",
"=",
"g",
";",
"}",
"}",
"}",
")",
";",
"const",
"replacement",
"=",
"{",
"}",
";",
"replacement",
"[",
"id",
"]",
"=",
"context",
".",
"pdfFonts",
"[",
"name",
"]",
".",
"id",
";",
"cpyCxt",
".",
"replaceSourceObjects",
"(",
"replacement",
")",
";",
"}",
"else",
"{",
"const",
"xObjectId",
"=",
"printer",
".",
"getObjectsContext",
"(",
")",
".",
"allocateNewObjectID",
"(",
")",
";",
"context",
".",
"pdfFonts",
"[",
"name",
"]",
"=",
"{",
"id",
":",
"xObjectId",
",",
"font",
":",
"font",
"}",
";",
"const",
"replacement",
"=",
"{",
"}",
";",
"replacement",
"[",
"id",
"]",
"=",
"xObjectId",
";",
"cpyCxt",
".",
"replaceSourceObjects",
"(",
"replacement",
")",
";",
"}",
"}",
"}",
"}"
] |
Consolidate duplicate fonts
|
[
"Consolidate",
"duplicate",
"fonts"
] |
e7e666f6276e9d818e8738531a8cfb4a5c680fa2
|
https://github.com/astefanutti/decktape/blob/e7e666f6276e9d818e8738531a8cfb4a5c680fa2/decktape.js#L407-L452
|
11,152
|
depcheck/depcheck
|
src/special/gulp-load-plugins.js
|
getReferences
|
function getReferences(path, variableName) {
const bindings = path.scope.getBinding(variableName);
const references = bindings.referencePaths;
return references;
}
|
javascript
|
function getReferences(path, variableName) {
const bindings = path.scope.getBinding(variableName);
const references = bindings.referencePaths;
return references;
}
|
[
"function",
"getReferences",
"(",
"path",
",",
"variableName",
")",
"{",
"const",
"bindings",
"=",
"path",
".",
"scope",
".",
"getBinding",
"(",
"variableName",
")",
";",
"const",
"references",
"=",
"bindings",
".",
"referencePaths",
";",
"return",
"references",
";",
"}"
] |
Get the references to the variable in the path scope.
@example Within the path scope, returns references to `loadPlugins` variable.
|
[
"Get",
"the",
"references",
"to",
"the",
"variable",
"in",
"the",
"path",
"scope",
"."
] |
2a877930e3f7033d4f8ac99d412182a7edca4b9b
|
https://github.com/depcheck/depcheck/blob/2a877930e3f7033d4f8ac99d412182a7edca4b9b/src/special/gulp-load-plugins.js#L34-L38
|
11,153
|
depcheck/depcheck
|
src/special/gulp-load-plugins.js
|
getIdentifierVariableName
|
function getIdentifierVariableName(path) {
if (
path.isIdentifier()
&& path.parentPath.isCallExpression()
&& path.parentPath.parentPath.isVariableDeclarator()
) {
const variableName = path.parentPath.parentPath.node.id.name;
return variableName;
}
return '';
}
|
javascript
|
function getIdentifierVariableName(path) {
if (
path.isIdentifier()
&& path.parentPath.isCallExpression()
&& path.parentPath.parentPath.isVariableDeclarator()
) {
const variableName = path.parentPath.parentPath.node.id.name;
return variableName;
}
return '';
}
|
[
"function",
"getIdentifierVariableName",
"(",
"path",
")",
"{",
"if",
"(",
"path",
".",
"isIdentifier",
"(",
")",
"&&",
"path",
".",
"parentPath",
".",
"isCallExpression",
"(",
")",
"&&",
"path",
".",
"parentPath",
".",
"parentPath",
".",
"isVariableDeclarator",
"(",
")",
")",
"{",
"const",
"variableName",
"=",
"path",
".",
"parentPath",
".",
"parentPath",
".",
"node",
".",
"id",
".",
"name",
";",
"return",
"variableName",
";",
"}",
"return",
"''",
";",
"}"
] |
Get the variable name from the variable assigned declaration.
@example With code `$ = loadPlugins()` and `loadPlugins` as path, returns the string `$`.
|
[
"Get",
"the",
"variable",
"name",
"from",
"the",
"variable",
"assigned",
"declaration",
"."
] |
2a877930e3f7033d4f8ac99d412182a7edca4b9b
|
https://github.com/depcheck/depcheck/blob/2a877930e3f7033d4f8ac99d412182a7edca4b9b/src/special/gulp-load-plugins.js#L44-L55
|
11,154
|
depcheck/depcheck
|
src/special/gulp-load-plugins.js
|
getPackageName
|
function getPackageName(content, pluginLookup, identifierPath) {
let memberPath = identifierPath.parentPath;
while (memberPath.isMemberExpression()) {
const code = content.slice(identifierPath.node.end, memberPath.node.end);
const pluginName = pluginLookup[code];
if (pluginName) {
return pluginName;
}
memberPath = memberPath.parentPath;
}
return '';
}
|
javascript
|
function getPackageName(content, pluginLookup, identifierPath) {
let memberPath = identifierPath.parentPath;
while (memberPath.isMemberExpression()) {
const code = content.slice(identifierPath.node.end, memberPath.node.end);
const pluginName = pluginLookup[code];
if (pluginName) {
return pluginName;
}
memberPath = memberPath.parentPath;
}
return '';
}
|
[
"function",
"getPackageName",
"(",
"content",
",",
"pluginLookup",
",",
"identifierPath",
")",
"{",
"let",
"memberPath",
"=",
"identifierPath",
".",
"parentPath",
";",
"while",
"(",
"memberPath",
".",
"isMemberExpression",
"(",
")",
")",
"{",
"const",
"code",
"=",
"content",
".",
"slice",
"(",
"identifierPath",
".",
"node",
".",
"end",
",",
"memberPath",
".",
"node",
".",
"end",
")",
";",
"const",
"pluginName",
"=",
"pluginLookup",
"[",
"code",
"]",
";",
"if",
"(",
"pluginName",
")",
"{",
"return",
"pluginName",
";",
"}",
"memberPath",
"=",
"memberPath",
".",
"parentPath",
";",
"}",
"return",
"''",
";",
"}"
] |
Get the package name from the identifier call path.
@example With code `$.jshint()` and `$` as path, returns `gulp-jshint` string.
|
[
"Get",
"the",
"package",
"name",
"from",
"the",
"identifier",
"call",
"path",
"."
] |
2a877930e3f7033d4f8ac99d412182a7edca4b9b
|
https://github.com/depcheck/depcheck/blob/2a877930e3f7033d4f8ac99d412182a7edca4b9b/src/special/gulp-load-plugins.js#L78-L91
|
11,155
|
depcheck/depcheck
|
src/special/gulp-load-plugins.js
|
check
|
function check(content, deps, path) {
if (
// Pattern: import plugins from 'gulp-load-plugins', $ = plugins(), $.jshint()
importDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isImportDeclaration()
&& path.get('specifiers')[0]
&& path.get('specifiers')[0].isImportDefaultSpecifier()
&& path.get('specifiers')[0].get('local').isIdentifier()
) {
const importVariableName = path.get('specifiers')[0].get('local').node.name;
const identifierReferences = getIdentifierReferences(path, importVariableName);
const packageNames = identifierReferences.map(r => getPackageName(content, deps, r));
return packageNames;
}
if (
// Pattern: plugins = require('gulp-load-plugins'), $ = plugins(), $.jshint()
requireDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isCallExpression()
&& path.parentPath.isVariableDeclarator()
&& path.parentPath.get('id').isIdentifier()
) {
const requireVariableName = path.parentPath.get('id').node.name;
const identifierReferences = getIdentifierReferences(path, requireVariableName);
const packageNames = identifierReferences.map(r => getPackageName(content, deps, r));
return packageNames;
}
if (
// Pattern: $ = require('gulp-load-plugins')(), $.jshint()
requireDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isCallExpression()
&& path.parentPath.isCallExpression()
&& path.parentPath.parentPath.isVariableDeclarator()
&& path.parentPath.parentPath.get('id').isIdentifier()
) {
const requireVariableName = path.parentPath.parentPath.get('id').node.name;
const identifierReferences = getReferences(path, requireVariableName);
const packageNames = identifierReferences.map(r => getPackageName(content, deps, r));
return packageNames;
}
if (
// Pattern: require('gulp-load-plugins')().thisPlugin()
requireDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isCallExpression()
&& path.parentPath.isCallExpression()
&& path.parentPath.parentPath.isMemberExpression()
) {
const packageName = getPackageName(content, deps, path.parentPath);
return [packageName];
}
return [];
}
|
javascript
|
function check(content, deps, path) {
if (
// Pattern: import plugins from 'gulp-load-plugins', $ = plugins(), $.jshint()
importDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isImportDeclaration()
&& path.get('specifiers')[0]
&& path.get('specifiers')[0].isImportDefaultSpecifier()
&& path.get('specifiers')[0].get('local').isIdentifier()
) {
const importVariableName = path.get('specifiers')[0].get('local').node.name;
const identifierReferences = getIdentifierReferences(path, importVariableName);
const packageNames = identifierReferences.map(r => getPackageName(content, deps, r));
return packageNames;
}
if (
// Pattern: plugins = require('gulp-load-plugins'), $ = plugins(), $.jshint()
requireDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isCallExpression()
&& path.parentPath.isVariableDeclarator()
&& path.parentPath.get('id').isIdentifier()
) {
const requireVariableName = path.parentPath.get('id').node.name;
const identifierReferences = getIdentifierReferences(path, requireVariableName);
const packageNames = identifierReferences.map(r => getPackageName(content, deps, r));
return packageNames;
}
if (
// Pattern: $ = require('gulp-load-plugins')(), $.jshint()
requireDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isCallExpression()
&& path.parentPath.isCallExpression()
&& path.parentPath.parentPath.isVariableDeclarator()
&& path.parentPath.parentPath.get('id').isIdentifier()
) {
const requireVariableName = path.parentPath.parentPath.get('id').node.name;
const identifierReferences = getReferences(path, requireVariableName);
const packageNames = identifierReferences.map(r => getPackageName(content, deps, r));
return packageNames;
}
if (
// Pattern: require('gulp-load-plugins')().thisPlugin()
requireDetector(path.node)[0] === 'gulp-load-plugins'
&& path.isCallExpression()
&& path.parentPath.isCallExpression()
&& path.parentPath.parentPath.isMemberExpression()
) {
const packageName = getPackageName(content, deps, path.parentPath);
return [packageName];
}
return [];
}
|
[
"function",
"check",
"(",
"content",
",",
"deps",
",",
"path",
")",
"{",
"if",
"(",
"// Pattern: import plugins from 'gulp-load-plugins', $ = plugins(), $.jshint()",
"importDetector",
"(",
"path",
".",
"node",
")",
"[",
"0",
"]",
"===",
"'gulp-load-plugins'",
"&&",
"path",
".",
"isImportDeclaration",
"(",
")",
"&&",
"path",
".",
"get",
"(",
"'specifiers'",
")",
"[",
"0",
"]",
"&&",
"path",
".",
"get",
"(",
"'specifiers'",
")",
"[",
"0",
"]",
".",
"isImportDefaultSpecifier",
"(",
")",
"&&",
"path",
".",
"get",
"(",
"'specifiers'",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'local'",
")",
".",
"isIdentifier",
"(",
")",
")",
"{",
"const",
"importVariableName",
"=",
"path",
".",
"get",
"(",
"'specifiers'",
")",
"[",
"0",
"]",
".",
"get",
"(",
"'local'",
")",
".",
"node",
".",
"name",
";",
"const",
"identifierReferences",
"=",
"getIdentifierReferences",
"(",
"path",
",",
"importVariableName",
")",
";",
"const",
"packageNames",
"=",
"identifierReferences",
".",
"map",
"(",
"r",
"=>",
"getPackageName",
"(",
"content",
",",
"deps",
",",
"r",
")",
")",
";",
"return",
"packageNames",
";",
"}",
"if",
"(",
"// Pattern: plugins = require('gulp-load-plugins'), $ = plugins(), $.jshint()",
"requireDetector",
"(",
"path",
".",
"node",
")",
"[",
"0",
"]",
"===",
"'gulp-load-plugins'",
"&&",
"path",
".",
"isCallExpression",
"(",
")",
"&&",
"path",
".",
"parentPath",
".",
"isVariableDeclarator",
"(",
")",
"&&",
"path",
".",
"parentPath",
".",
"get",
"(",
"'id'",
")",
".",
"isIdentifier",
"(",
")",
")",
"{",
"const",
"requireVariableName",
"=",
"path",
".",
"parentPath",
".",
"get",
"(",
"'id'",
")",
".",
"node",
".",
"name",
";",
"const",
"identifierReferences",
"=",
"getIdentifierReferences",
"(",
"path",
",",
"requireVariableName",
")",
";",
"const",
"packageNames",
"=",
"identifierReferences",
".",
"map",
"(",
"r",
"=>",
"getPackageName",
"(",
"content",
",",
"deps",
",",
"r",
")",
")",
";",
"return",
"packageNames",
";",
"}",
"if",
"(",
"// Pattern: $ = require('gulp-load-plugins')(), $.jshint()",
"requireDetector",
"(",
"path",
".",
"node",
")",
"[",
"0",
"]",
"===",
"'gulp-load-plugins'",
"&&",
"path",
".",
"isCallExpression",
"(",
")",
"&&",
"path",
".",
"parentPath",
".",
"isCallExpression",
"(",
")",
"&&",
"path",
".",
"parentPath",
".",
"parentPath",
".",
"isVariableDeclarator",
"(",
")",
"&&",
"path",
".",
"parentPath",
".",
"parentPath",
".",
"get",
"(",
"'id'",
")",
".",
"isIdentifier",
"(",
")",
")",
"{",
"const",
"requireVariableName",
"=",
"path",
".",
"parentPath",
".",
"parentPath",
".",
"get",
"(",
"'id'",
")",
".",
"node",
".",
"name",
";",
"const",
"identifierReferences",
"=",
"getReferences",
"(",
"path",
",",
"requireVariableName",
")",
";",
"const",
"packageNames",
"=",
"identifierReferences",
".",
"map",
"(",
"r",
"=>",
"getPackageName",
"(",
"content",
",",
"deps",
",",
"r",
")",
")",
";",
"return",
"packageNames",
";",
"}",
"if",
"(",
"// Pattern: require('gulp-load-plugins')().thisPlugin()",
"requireDetector",
"(",
"path",
".",
"node",
")",
"[",
"0",
"]",
"===",
"'gulp-load-plugins'",
"&&",
"path",
".",
"isCallExpression",
"(",
")",
"&&",
"path",
".",
"parentPath",
".",
"isCallExpression",
"(",
")",
"&&",
"path",
".",
"parentPath",
".",
"parentPath",
".",
"isMemberExpression",
"(",
")",
")",
"{",
"const",
"packageName",
"=",
"getPackageName",
"(",
"content",
",",
"deps",
",",
"path",
".",
"parentPath",
")",
";",
"return",
"[",
"packageName",
"]",
";",
"}",
"return",
"[",
"]",
";",
"}"
] |
Get the gulp packages found from the path. This is the entry for traverse.
|
[
"Get",
"the",
"gulp",
"packages",
"found",
"from",
"the",
"path",
".",
"This",
"is",
"the",
"entry",
"for",
"traverse",
"."
] |
2a877930e3f7033d4f8ac99d412182a7edca4b9b
|
https://github.com/depcheck/depcheck/blob/2a877930e3f7033d4f8ac99d412182a7edca4b9b/src/special/gulp-load-plugins.js#L96-L150
|
11,156
|
shakiba/planck.js
|
lib/Manifold.js
|
Manifold
|
function Manifold() {
this.type;
this.localNormal = Vec2.zero();
this.localPoint = Vec2.zero();
this.points = [ new ManifoldPoint(), new ManifoldPoint() ];
this.pointCount = 0;
}
|
javascript
|
function Manifold() {
this.type;
this.localNormal = Vec2.zero();
this.localPoint = Vec2.zero();
this.points = [ new ManifoldPoint(), new ManifoldPoint() ];
this.pointCount = 0;
}
|
[
"function",
"Manifold",
"(",
")",
"{",
"this",
".",
"type",
";",
"this",
".",
"localNormal",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"localPoint",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"points",
"=",
"[",
"new",
"ManifoldPoint",
"(",
")",
",",
"new",
"ManifoldPoint",
"(",
")",
"]",
";",
"this",
".",
"pointCount",
"=",
"0",
";",
"}"
] |
A manifold for two touching convex shapes. Manifolds are created in `evaluate`
method of Contact subclasses.
Supported manifold types are e_faceA or e_faceB for clip point versus plane
with radius and e_circles point versus point with radius.
We store contacts in this way so that position correction can account for
movement, which is critical for continuous physics. All contact scenarios
must be expressed in one of these types. This structure is stored across time
steps, so we keep it small.
@prop type e_circle, e_faceA, e_faceB
@prop localPoint Usage depends on manifold type:<br>
e_circles: the local center of circleA <br>
e_faceA: the center of faceA <br>
e_faceB: the center of faceB
@prop localNormal Usage depends on manifold type:<br>
e_circles: not used <br>
e_faceA: the normal on polygonA <br>
e_faceB: the normal on polygonB
@prop points The points of contact {ManifoldPoint[]}
@prop pointCount The number of manifold points
|
[
"A",
"manifold",
"for",
"two",
"touching",
"convex",
"shapes",
".",
"Manifolds",
"are",
"created",
"in",
"evaluate",
"method",
"of",
"Contact",
"subclasses",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/Manifold.js#L69-L75
|
11,157
|
shakiba/planck.js
|
lib/Manifold.js
|
getPointStates
|
function getPointStates(state1, state2, manifold1, manifold2) {
// for (var i = 0; i < Settings.maxManifoldPoints; ++i) {
// state1[i] = PointState.nullState;
// state2[i] = PointState.nullState;
// }
// Detect persists and removes.
for (var i = 0; i < manifold1.pointCount; ++i) {
var id = manifold1.points[i].id;// ContactID
state1[i] = PointState.removeState;
for (var j = 0; j < manifold2.pointCount; ++j) {
if (manifold2.points[j].id.key == id.key) {
state1[i] = PointState.persistState;
break;
}
}
}
// Detect persists and adds.
for (var i = 0; i < manifold2.pointCount; ++i) {
var id = manifold2.points[i].id;// ContactID
state2[i] = PointState.addState;
for (var j = 0; j < manifold1.pointCount; ++j) {
if (manifold1.points[j].id.key == id.key) {
state2[i] = PointState.persistState;
break;
}
}
}
}
|
javascript
|
function getPointStates(state1, state2, manifold1, manifold2) {
// for (var i = 0; i < Settings.maxManifoldPoints; ++i) {
// state1[i] = PointState.nullState;
// state2[i] = PointState.nullState;
// }
// Detect persists and removes.
for (var i = 0; i < manifold1.pointCount; ++i) {
var id = manifold1.points[i].id;// ContactID
state1[i] = PointState.removeState;
for (var j = 0; j < manifold2.pointCount; ++j) {
if (manifold2.points[j].id.key == id.key) {
state1[i] = PointState.persistState;
break;
}
}
}
// Detect persists and adds.
for (var i = 0; i < manifold2.pointCount; ++i) {
var id = manifold2.points[i].id;// ContactID
state2[i] = PointState.addState;
for (var j = 0; j < manifold1.pointCount; ++j) {
if (manifold1.points[j].id.key == id.key) {
state2[i] = PointState.persistState;
break;
}
}
}
}
|
[
"function",
"getPointStates",
"(",
"state1",
",",
"state2",
",",
"manifold1",
",",
"manifold2",
")",
"{",
"// for (var i = 0; i < Settings.maxManifoldPoints; ++i) {",
"// state1[i] = PointState.nullState;",
"// state2[i] = PointState.nullState;",
"// }",
"// Detect persists and removes.",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"manifold1",
".",
"pointCount",
";",
"++",
"i",
")",
"{",
"var",
"id",
"=",
"manifold1",
".",
"points",
"[",
"i",
"]",
".",
"id",
";",
"// ContactID",
"state1",
"[",
"i",
"]",
"=",
"PointState",
".",
"removeState",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"manifold2",
".",
"pointCount",
";",
"++",
"j",
")",
"{",
"if",
"(",
"manifold2",
".",
"points",
"[",
"j",
"]",
".",
"id",
".",
"key",
"==",
"id",
".",
"key",
")",
"{",
"state1",
"[",
"i",
"]",
"=",
"PointState",
".",
"persistState",
";",
"break",
";",
"}",
"}",
"}",
"// Detect persists and adds.",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"manifold2",
".",
"pointCount",
";",
"++",
"i",
")",
"{",
"var",
"id",
"=",
"manifold2",
".",
"points",
"[",
"i",
"]",
".",
"id",
";",
"// ContactID",
"state2",
"[",
"i",
"]",
"=",
"PointState",
".",
"addState",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"manifold1",
".",
"pointCount",
";",
"++",
"j",
")",
"{",
"if",
"(",
"manifold1",
".",
"points",
"[",
"j",
"]",
".",
"id",
".",
"key",
"==",
"id",
".",
"key",
")",
"{",
"state2",
"[",
"i",
"]",
"=",
"PointState",
".",
"persistState",
";",
"break",
";",
"}",
"}",
"}",
"}"
] |
Compute the point states given two manifolds. The states pertain to the
transition from manifold1 to manifold2. So state1 is either persist or remove
while state2 is either add or persist.
@param {PointState[Settings.maxManifoldPoints]} state1
@param {PointState[Settings.maxManifoldPoints]} state2
|
[
"Compute",
"the",
"point",
"states",
"given",
"two",
"manifolds",
".",
"The",
"states",
"pertain",
"to",
"the",
"transition",
"from",
"manifold1",
"to",
"manifold2",
".",
"So",
"state1",
"is",
"either",
"persist",
"or",
"remove",
"while",
"state2",
"is",
"either",
"add",
"or",
"persist",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/Manifold.js#L259-L292
|
11,158
|
shakiba/planck.js
|
lib/Manifold.js
|
clipSegmentToLine
|
function clipSegmentToLine(vOut, vIn, normal, offset, vertexIndexA) {
// Start with no output points
var numOut = 0;
// Calculate the distance of end points to the line
var distance0 = Vec2.dot(normal, vIn[0].v) - offset;
var distance1 = Vec2.dot(normal, vIn[1].v) - offset;
// If the points are behind the plane
if (distance0 <= 0.0)
vOut[numOut++].set(vIn[0]);
if (distance1 <= 0.0)
vOut[numOut++].set(vIn[1]);
// If the points are on different sides of the plane
if (distance0 * distance1 < 0.0) {
// Find intersection point of edge and plane
var interp = distance0 / (distance0 - distance1);
vOut[numOut].v.setCombine(1 - interp, vIn[0].v, interp, vIn[1].v);
// VertexA is hitting edgeB.
vOut[numOut].id.cf.indexA = vertexIndexA;
vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB;
vOut[numOut].id.cf.typeA = Manifold.e_vertex;
vOut[numOut].id.cf.typeB = Manifold.e_face;
++numOut;
}
return numOut;
}
|
javascript
|
function clipSegmentToLine(vOut, vIn, normal, offset, vertexIndexA) {
// Start with no output points
var numOut = 0;
// Calculate the distance of end points to the line
var distance0 = Vec2.dot(normal, vIn[0].v) - offset;
var distance1 = Vec2.dot(normal, vIn[1].v) - offset;
// If the points are behind the plane
if (distance0 <= 0.0)
vOut[numOut++].set(vIn[0]);
if (distance1 <= 0.0)
vOut[numOut++].set(vIn[1]);
// If the points are on different sides of the plane
if (distance0 * distance1 < 0.0) {
// Find intersection point of edge and plane
var interp = distance0 / (distance0 - distance1);
vOut[numOut].v.setCombine(1 - interp, vIn[0].v, interp, vIn[1].v);
// VertexA is hitting edgeB.
vOut[numOut].id.cf.indexA = vertexIndexA;
vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB;
vOut[numOut].id.cf.typeA = Manifold.e_vertex;
vOut[numOut].id.cf.typeB = Manifold.e_face;
++numOut;
}
return numOut;
}
|
[
"function",
"clipSegmentToLine",
"(",
"vOut",
",",
"vIn",
",",
"normal",
",",
"offset",
",",
"vertexIndexA",
")",
"{",
"// Start with no output points",
"var",
"numOut",
"=",
"0",
";",
"// Calculate the distance of end points to the line",
"var",
"distance0",
"=",
"Vec2",
".",
"dot",
"(",
"normal",
",",
"vIn",
"[",
"0",
"]",
".",
"v",
")",
"-",
"offset",
";",
"var",
"distance1",
"=",
"Vec2",
".",
"dot",
"(",
"normal",
",",
"vIn",
"[",
"1",
"]",
".",
"v",
")",
"-",
"offset",
";",
"// If the points are behind the plane",
"if",
"(",
"distance0",
"<=",
"0.0",
")",
"vOut",
"[",
"numOut",
"++",
"]",
".",
"set",
"(",
"vIn",
"[",
"0",
"]",
")",
";",
"if",
"(",
"distance1",
"<=",
"0.0",
")",
"vOut",
"[",
"numOut",
"++",
"]",
".",
"set",
"(",
"vIn",
"[",
"1",
"]",
")",
";",
"// If the points are on different sides of the plane",
"if",
"(",
"distance0",
"*",
"distance1",
"<",
"0.0",
")",
"{",
"// Find intersection point of edge and plane",
"var",
"interp",
"=",
"distance0",
"/",
"(",
"distance0",
"-",
"distance1",
")",
";",
"vOut",
"[",
"numOut",
"]",
".",
"v",
".",
"setCombine",
"(",
"1",
"-",
"interp",
",",
"vIn",
"[",
"0",
"]",
".",
"v",
",",
"interp",
",",
"vIn",
"[",
"1",
"]",
".",
"v",
")",
";",
"// VertexA is hitting edgeB.",
"vOut",
"[",
"numOut",
"]",
".",
"id",
".",
"cf",
".",
"indexA",
"=",
"vertexIndexA",
";",
"vOut",
"[",
"numOut",
"]",
".",
"id",
".",
"cf",
".",
"indexB",
"=",
"vIn",
"[",
"0",
"]",
".",
"id",
".",
"cf",
".",
"indexB",
";",
"vOut",
"[",
"numOut",
"]",
".",
"id",
".",
"cf",
".",
"typeA",
"=",
"Manifold",
".",
"e_vertex",
";",
"vOut",
"[",
"numOut",
"]",
".",
"id",
".",
"cf",
".",
"typeB",
"=",
"Manifold",
".",
"e_face",
";",
"++",
"numOut",
";",
"}",
"return",
"numOut",
";",
"}"
] |
Clipping for contact manifolds. Sutherland-Hodgman clipping.
@param {ClipVertex[2]} vOut
@param {ClipVertex[2]} vIn
|
[
"Clipping",
"for",
"contact",
"manifolds",
".",
"Sutherland",
"-",
"Hodgman",
"clipping",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/Manifold.js#L316-L345
|
11,159
|
shakiba/planck.js
|
lib/joint/MotorJoint.js
|
MotorJoint
|
function MotorJoint(def, bodyA, bodyB) {
if (!(this instanceof MotorJoint)) {
return new MotorJoint(def, bodyA, bodyB);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = MotorJoint.TYPE;
this.m_linearOffset = def.linearOffset ? def.linearOffset : bodyA.getLocalPoint(bodyB.getPosition());
var angleA = bodyA.getAngle();
var angleB = bodyB.getAngle();
this.m_angularOffset = angleB - angleA;
this.m_linearImpulse = Vec2.zero();
this.m_angularImpulse = 0.0;
this.m_maxForce = def.maxForce;
this.m_maxTorque = def.maxTorque;
this.m_correctionFactor = def.correctionFactor;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_linearError; // Vec2
this.m_angularError; // float
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_linearMass; // Mat22
this.m_angularMass; // float
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
}
|
javascript
|
function MotorJoint(def, bodyA, bodyB) {
if (!(this instanceof MotorJoint)) {
return new MotorJoint(def, bodyA, bodyB);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = MotorJoint.TYPE;
this.m_linearOffset = def.linearOffset ? def.linearOffset : bodyA.getLocalPoint(bodyB.getPosition());
var angleA = bodyA.getAngle();
var angleB = bodyB.getAngle();
this.m_angularOffset = angleB - angleA;
this.m_linearImpulse = Vec2.zero();
this.m_angularImpulse = 0.0;
this.m_maxForce = def.maxForce;
this.m_maxTorque = def.maxTorque;
this.m_correctionFactor = def.correctionFactor;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_linearError; // Vec2
this.m_angularError; // float
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_linearMass; // Mat22
this.m_angularMass; // float
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
}
|
[
"function",
"MotorJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"MotorJoint",
")",
")",
"{",
"return",
"new",
"MotorJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
")",
";",
"}",
"def",
"=",
"options",
"(",
"def",
",",
"DEFAULTS",
")",
";",
"Joint",
".",
"call",
"(",
"this",
",",
"def",
",",
"bodyA",
",",
"bodyB",
")",
";",
"bodyA",
"=",
"this",
".",
"m_bodyA",
";",
"bodyB",
"=",
"this",
".",
"m_bodyB",
";",
"this",
".",
"m_type",
"=",
"MotorJoint",
".",
"TYPE",
";",
"this",
".",
"m_linearOffset",
"=",
"def",
".",
"linearOffset",
"?",
"def",
".",
"linearOffset",
":",
"bodyA",
".",
"getLocalPoint",
"(",
"bodyB",
".",
"getPosition",
"(",
")",
")",
";",
"var",
"angleA",
"=",
"bodyA",
".",
"getAngle",
"(",
")",
";",
"var",
"angleB",
"=",
"bodyB",
".",
"getAngle",
"(",
")",
";",
"this",
".",
"m_angularOffset",
"=",
"angleB",
"-",
"angleA",
";",
"this",
".",
"m_linearImpulse",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_angularImpulse",
"=",
"0.0",
";",
"this",
".",
"m_maxForce",
"=",
"def",
".",
"maxForce",
";",
"this",
".",
"m_maxTorque",
"=",
"def",
".",
"maxTorque",
";",
"this",
".",
"m_correctionFactor",
"=",
"def",
".",
"correctionFactor",
";",
"// Solver temp",
"this",
".",
"m_rA",
";",
"// Vec2",
"this",
".",
"m_rB",
";",
"// Vec2",
"this",
".",
"m_localCenterA",
";",
"// Vec2",
"this",
".",
"m_localCenterB",
";",
"// Vec2",
"this",
".",
"m_linearError",
";",
"// Vec2",
"this",
".",
"m_angularError",
";",
"// float",
"this",
".",
"m_invMassA",
";",
"// float",
"this",
".",
"m_invMassB",
";",
"// float",
"this",
".",
"m_invIA",
";",
"// float",
"this",
".",
"m_invIB",
";",
"// float",
"this",
".",
"m_linearMass",
";",
"// Mat22",
"this",
".",
"m_angularMass",
";",
"// float",
"// Point-to-point constraint",
"// Cdot = v2 - v1",
"// = v2 + cross(w2, r2) - v1 - cross(w1, r1)",
"// J = [-I -r1_skew I r2_skew ]",
"// Identity used:",
"// w k % (rx i + ry j) = w * (-ry i + rx j)",
"// Angle constraint",
"// Cdot = w2 - w1",
"// J = [0 0 -1 0 0 1]",
"// K = invI1 + invI2",
"}"
] |
A motor joint is used to control the relative motion between two bodies. A
typical usage is to control the movement of a dynamic body with respect to
the ground.
@param {MotorJointDef} def
@param {Body} bodyA
@param {Body} bodyB
|
[
"A",
"motor",
"joint",
"is",
"used",
"to",
"control",
"the",
"relative",
"motion",
"between",
"two",
"bodies",
".",
"A",
"typical",
"usage",
"is",
"to",
"control",
"the",
"movement",
"of",
"a",
"dynamic",
"body",
"with",
"respect",
"to",
"the",
"ground",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/joint/MotorJoint.js#L76-L126
|
11,160
|
shakiba/planck.js
|
lib/joint/WeldJoint.js
|
WeldJoint
|
function WeldJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof WeldJoint)) {
return new WeldJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = WeldJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero();
this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle();
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_impulse = Vec3();
this.m_bias = 0.0;
this.m_gamma = 0.0;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_mass = new Mat33();
// Point-to-point constraint
// C = p2 - p1
// Cdot = v2 - v1
// / = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// C = angle2 - angle1 - referenceAngle
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
}
|
javascript
|
function WeldJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof WeldJoint)) {
return new WeldJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = WeldJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero();
this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle();
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_impulse = Vec3();
this.m_bias = 0.0;
this.m_gamma = 0.0;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_mass = new Mat33();
// Point-to-point constraint
// C = p2 - p1
// Cdot = v2 - v1
// / = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// C = angle2 - angle1 - referenceAngle
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
}
|
[
"function",
"WeldJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"anchor",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"WeldJoint",
")",
")",
"{",
"return",
"new",
"WeldJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"anchor",
")",
";",
"}",
"def",
"=",
"options",
"(",
"def",
",",
"DEFAULTS",
")",
";",
"Joint",
".",
"call",
"(",
"this",
",",
"def",
",",
"bodyA",
",",
"bodyB",
")",
";",
"bodyA",
"=",
"this",
".",
"m_bodyA",
";",
"bodyB",
"=",
"this",
".",
"m_bodyB",
";",
"this",
".",
"m_type",
"=",
"WeldJoint",
".",
"TYPE",
";",
"this",
".",
"m_localAnchorA",
"=",
"anchor",
"?",
"bodyA",
".",
"getLocalPoint",
"(",
"anchor",
")",
":",
"def",
".",
"localAnchorA",
"||",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_localAnchorB",
"=",
"anchor",
"?",
"bodyB",
".",
"getLocalPoint",
"(",
"anchor",
")",
":",
"def",
".",
"localAnchorB",
"||",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_referenceAngle",
"=",
"Math",
".",
"isFinite",
"(",
"def",
".",
"referenceAngle",
")",
"?",
"def",
".",
"referenceAngle",
":",
"bodyB",
".",
"getAngle",
"(",
")",
"-",
"bodyA",
".",
"getAngle",
"(",
")",
";",
"this",
".",
"m_frequencyHz",
"=",
"def",
".",
"frequencyHz",
";",
"this",
".",
"m_dampingRatio",
"=",
"def",
".",
"dampingRatio",
";",
"this",
".",
"m_impulse",
"=",
"Vec3",
"(",
")",
";",
"this",
".",
"m_bias",
"=",
"0.0",
";",
"this",
".",
"m_gamma",
"=",
"0.0",
";",
"// Solver temp",
"this",
".",
"m_rA",
";",
"// Vec2",
"this",
".",
"m_rB",
";",
"// Vec2",
"this",
".",
"m_localCenterA",
";",
"// Vec2",
"this",
".",
"m_localCenterB",
";",
"// Vec2",
"this",
".",
"m_invMassA",
";",
"// float",
"this",
".",
"m_invMassB",
";",
"// float",
"this",
".",
"m_invIA",
";",
"// float",
"this",
".",
"m_invIB",
";",
"// float",
"this",
".",
"m_mass",
"=",
"new",
"Mat33",
"(",
")",
";",
"// Point-to-point constraint",
"// C = p2 - p1",
"// Cdot = v2 - v1",
"// / = v2 + cross(w2, r2) - v1 - cross(w1, r1)",
"// J = [-I -r1_skew I r2_skew ]",
"// Identity used:",
"// w k % (rx i + ry j) = w * (-ry i + rx j)",
"// Angle constraint",
"// C = angle2 - angle1 - referenceAngle",
"// Cdot = w2 - w1",
"// J = [0 0 -1 0 0 1]",
"// K = invI1 + invI2",
"}"
] |
A weld joint essentially glues two bodies together. A weld joint may distort
somewhat because the island constraint solver is approximate.
@param {WeldJointDef} def
@param {Body} bodyA
@param {Body} bodyB
|
[
"A",
"weld",
"joint",
"essentially",
"glues",
"two",
"bodies",
"together",
".",
"A",
"weld",
"joint",
"may",
"distort",
"somewhat",
"because",
"the",
"island",
"constraint",
"solver",
"is",
"approximate",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/joint/WeldJoint.js#L77-L125
|
11,161
|
shakiba/planck.js
|
lib/common/Mat33.js
|
Mat33
|
function Mat33(a, b, c) {
if (typeof a === 'object' && a !== null) {
this.ex = Vec3.clone(a);
this.ey = Vec3.clone(b);
this.ez = Vec3.clone(c);
} else {
this.ex = Vec3();
this.ey = Vec3();
this.ez = Vec3();
}
}
|
javascript
|
function Mat33(a, b, c) {
if (typeof a === 'object' && a !== null) {
this.ex = Vec3.clone(a);
this.ey = Vec3.clone(b);
this.ez = Vec3.clone(c);
} else {
this.ex = Vec3();
this.ey = Vec3();
this.ez = Vec3();
}
}
|
[
"function",
"Mat33",
"(",
"a",
",",
"b",
",",
"c",
")",
"{",
"if",
"(",
"typeof",
"a",
"===",
"'object'",
"&&",
"a",
"!==",
"null",
")",
"{",
"this",
".",
"ex",
"=",
"Vec3",
".",
"clone",
"(",
"a",
")",
";",
"this",
".",
"ey",
"=",
"Vec3",
".",
"clone",
"(",
"b",
")",
";",
"this",
".",
"ez",
"=",
"Vec3",
".",
"clone",
"(",
"c",
")",
";",
"}",
"else",
"{",
"this",
".",
"ex",
"=",
"Vec3",
"(",
")",
";",
"this",
".",
"ey",
"=",
"Vec3",
"(",
")",
";",
"this",
".",
"ez",
"=",
"Vec3",
"(",
")",
";",
"}",
"}"
] |
A 3-by-3 matrix. Stored in column-major order.
|
[
"A",
"3",
"-",
"by",
"-",
"3",
"matrix",
".",
"Stored",
"in",
"column",
"-",
"major",
"order",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/common/Mat33.js#L33-L43
|
11,162
|
shakiba/planck.js
|
lib/common/Mat22.js
|
Mat22
|
function Mat22(a, b, c, d) {
if (typeof a === 'object' && a !== null) {
this.ex = Vec2.clone(a);
this.ey = Vec2.clone(b);
} else if (typeof a === 'number') {
this.ex = Vec2.neo(a, c);
this.ey = Vec2.neo(b, d)
} else {
this.ex = Vec2.zero();
this.ey = Vec2.zero()
}
}
|
javascript
|
function Mat22(a, b, c, d) {
if (typeof a === 'object' && a !== null) {
this.ex = Vec2.clone(a);
this.ey = Vec2.clone(b);
} else if (typeof a === 'number') {
this.ex = Vec2.neo(a, c);
this.ey = Vec2.neo(b, d)
} else {
this.ex = Vec2.zero();
this.ey = Vec2.zero()
}
}
|
[
"function",
"Mat22",
"(",
"a",
",",
"b",
",",
"c",
",",
"d",
")",
"{",
"if",
"(",
"typeof",
"a",
"===",
"'object'",
"&&",
"a",
"!==",
"null",
")",
"{",
"this",
".",
"ex",
"=",
"Vec2",
".",
"clone",
"(",
"a",
")",
";",
"this",
".",
"ey",
"=",
"Vec2",
".",
"clone",
"(",
"b",
")",
";",
"}",
"else",
"if",
"(",
"typeof",
"a",
"===",
"'number'",
")",
"{",
"this",
".",
"ex",
"=",
"Vec2",
".",
"neo",
"(",
"a",
",",
"c",
")",
";",
"this",
".",
"ey",
"=",
"Vec2",
".",
"neo",
"(",
"b",
",",
"d",
")",
"}",
"else",
"{",
"this",
".",
"ex",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"ey",
"=",
"Vec2",
".",
"zero",
"(",
")",
"}",
"}"
] |
A 2-by-2 matrix. Stored in column-major order.
|
[
"A",
"2",
"-",
"by",
"-",
"2",
"matrix",
".",
"Stored",
"in",
"column",
"-",
"major",
"order",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/common/Mat22.js#L32-L43
|
11,163
|
shakiba/planck.js
|
lib/joint/RopeJoint.js
|
RopeJoint
|
function RopeJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof RopeJoint)) {
return new RopeJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = RopeJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.neo(-1.0, 0.0);
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.neo(1.0, 0.0);
this.m_maxLength = def.maxLength;
this.m_mass = 0.0;
this.m_impulse = 0.0;
this.m_length = 0.0;
this.m_state = inactiveLimit;
// Solver temp
this.m_u; // Vec2
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_mass; // float
// Limit:
// C = norm(pB - pA) - L
// u = (pB - pA) / norm(pB - pA)
// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA))
// J = [-u -cross(rA, u) u cross(rB, u)]
// K = J * invM * JT
// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2
}
|
javascript
|
function RopeJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof RopeJoint)) {
return new RopeJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = RopeJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.neo(-1.0, 0.0);
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.neo(1.0, 0.0);
this.m_maxLength = def.maxLength;
this.m_mass = 0.0;
this.m_impulse = 0.0;
this.m_length = 0.0;
this.m_state = inactiveLimit;
// Solver temp
this.m_u; // Vec2
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_mass; // float
// Limit:
// C = norm(pB - pA) - L
// u = (pB - pA) / norm(pB - pA)
// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA))
// J = [-u -cross(rA, u) u cross(rB, u)]
// K = J * invM * JT
// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2
}
|
[
"function",
"RopeJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"anchor",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"RopeJoint",
")",
")",
"{",
"return",
"new",
"RopeJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"anchor",
")",
";",
"}",
"def",
"=",
"options",
"(",
"def",
",",
"DEFAULTS",
")",
";",
"Joint",
".",
"call",
"(",
"this",
",",
"def",
",",
"bodyA",
",",
"bodyB",
")",
";",
"bodyA",
"=",
"this",
".",
"m_bodyA",
";",
"bodyB",
"=",
"this",
".",
"m_bodyB",
";",
"this",
".",
"m_type",
"=",
"RopeJoint",
".",
"TYPE",
";",
"this",
".",
"m_localAnchorA",
"=",
"anchor",
"?",
"bodyA",
".",
"getLocalPoint",
"(",
"anchor",
")",
":",
"def",
".",
"localAnchorA",
"||",
"Vec2",
".",
"neo",
"(",
"-",
"1.0",
",",
"0.0",
")",
";",
"this",
".",
"m_localAnchorB",
"=",
"anchor",
"?",
"bodyB",
".",
"getLocalPoint",
"(",
"anchor",
")",
":",
"def",
".",
"localAnchorB",
"||",
"Vec2",
".",
"neo",
"(",
"1.0",
",",
"0.0",
")",
";",
"this",
".",
"m_maxLength",
"=",
"def",
".",
"maxLength",
";",
"this",
".",
"m_mass",
"=",
"0.0",
";",
"this",
".",
"m_impulse",
"=",
"0.0",
";",
"this",
".",
"m_length",
"=",
"0.0",
";",
"this",
".",
"m_state",
"=",
"inactiveLimit",
";",
"// Solver temp",
"this",
".",
"m_u",
";",
"// Vec2",
"this",
".",
"m_rA",
";",
"// Vec2",
"this",
".",
"m_rB",
";",
"// Vec2",
"this",
".",
"m_localCenterA",
";",
"// Vec2",
"this",
".",
"m_localCenterB",
";",
"// Vec2",
"this",
".",
"m_invMassA",
";",
"// float",
"this",
".",
"m_invMassB",
";",
"// float",
"this",
".",
"m_invIA",
";",
"// float",
"this",
".",
"m_invIB",
";",
"// float",
"this",
".",
"m_mass",
";",
"// float",
"// Limit:",
"// C = norm(pB - pA) - L",
"// u = (pB - pA) / norm(pB - pA)",
"// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA))",
"// J = [-u -cross(rA, u) u cross(rB, u)]",
"// K = J * invM * JT",
"// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2",
"}"
] |
A rope joint enforces a maximum distance between two points on two bodies. It
has no other effect.
Warning: if you attempt to change the maximum length during the simulation
you will get some non-physical behavior.
A model that would allow you to dynamically modify the length would have some
sponginess, so I chose not to implement it that way. See DistanceJoint if you
want to dynamically control length.
@param {RopeJointDef} def
@param {Body} bodyA
@param {Body} bodyB
|
[
"A",
"rope",
"joint",
"enforces",
"a",
"maximum",
"distance",
"between",
"two",
"points",
"on",
"two",
"bodies",
".",
"It",
"has",
"no",
"other",
"effect",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/joint/RopeJoint.js#L85-L125
|
11,164
|
shakiba/planck.js
|
lib/shape/CollidePolygon.js
|
FindMaxSeparation
|
function FindMaxSeparation(poly1, xf1, poly2, xf2) {
var count1 = poly1.m_count;
var count2 = poly2.m_count;
var n1s = poly1.m_normals;
var v1s = poly1.m_vertices;
var v2s = poly2.m_vertices;
var xf = Transform.mulTXf(xf2, xf1);
var bestIndex = 0;
var maxSeparation = -Infinity;
for (var i = 0; i < count1; ++i) {
// Get poly1 normal in frame2.
var n = Rot.mulVec2(xf.q, n1s[i]);
var v1 = Transform.mulVec2(xf, v1s[i]);
// Find deepest point for normal i.
var si = Infinity;
for (var j = 0; j < count2; ++j) {
var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1);
if (sij < si) {
si = sij;
}
}
if (si > maxSeparation) {
maxSeparation = si;
bestIndex = i;
}
}
// used to keep last FindMaxSeparation call values
FindMaxSeparation._maxSeparation = maxSeparation;
FindMaxSeparation._bestIndex = bestIndex;
}
|
javascript
|
function FindMaxSeparation(poly1, xf1, poly2, xf2) {
var count1 = poly1.m_count;
var count2 = poly2.m_count;
var n1s = poly1.m_normals;
var v1s = poly1.m_vertices;
var v2s = poly2.m_vertices;
var xf = Transform.mulTXf(xf2, xf1);
var bestIndex = 0;
var maxSeparation = -Infinity;
for (var i = 0; i < count1; ++i) {
// Get poly1 normal in frame2.
var n = Rot.mulVec2(xf.q, n1s[i]);
var v1 = Transform.mulVec2(xf, v1s[i]);
// Find deepest point for normal i.
var si = Infinity;
for (var j = 0; j < count2; ++j) {
var sij = Vec2.dot(n, v2s[j]) - Vec2.dot(n, v1);
if (sij < si) {
si = sij;
}
}
if (si > maxSeparation) {
maxSeparation = si;
bestIndex = i;
}
}
// used to keep last FindMaxSeparation call values
FindMaxSeparation._maxSeparation = maxSeparation;
FindMaxSeparation._bestIndex = bestIndex;
}
|
[
"function",
"FindMaxSeparation",
"(",
"poly1",
",",
"xf1",
",",
"poly2",
",",
"xf2",
")",
"{",
"var",
"count1",
"=",
"poly1",
".",
"m_count",
";",
"var",
"count2",
"=",
"poly2",
".",
"m_count",
";",
"var",
"n1s",
"=",
"poly1",
".",
"m_normals",
";",
"var",
"v1s",
"=",
"poly1",
".",
"m_vertices",
";",
"var",
"v2s",
"=",
"poly2",
".",
"m_vertices",
";",
"var",
"xf",
"=",
"Transform",
".",
"mulTXf",
"(",
"xf2",
",",
"xf1",
")",
";",
"var",
"bestIndex",
"=",
"0",
";",
"var",
"maxSeparation",
"=",
"-",
"Infinity",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"count1",
";",
"++",
"i",
")",
"{",
"// Get poly1 normal in frame2.",
"var",
"n",
"=",
"Rot",
".",
"mulVec2",
"(",
"xf",
".",
"q",
",",
"n1s",
"[",
"i",
"]",
")",
";",
"var",
"v1",
"=",
"Transform",
".",
"mulVec2",
"(",
"xf",
",",
"v1s",
"[",
"i",
"]",
")",
";",
"// Find deepest point for normal i.",
"var",
"si",
"=",
"Infinity",
";",
"for",
"(",
"var",
"j",
"=",
"0",
";",
"j",
"<",
"count2",
";",
"++",
"j",
")",
"{",
"var",
"sij",
"=",
"Vec2",
".",
"dot",
"(",
"n",
",",
"v2s",
"[",
"j",
"]",
")",
"-",
"Vec2",
".",
"dot",
"(",
"n",
",",
"v1",
")",
";",
"if",
"(",
"sij",
"<",
"si",
")",
"{",
"si",
"=",
"sij",
";",
"}",
"}",
"if",
"(",
"si",
">",
"maxSeparation",
")",
"{",
"maxSeparation",
"=",
"si",
";",
"bestIndex",
"=",
"i",
";",
"}",
"}",
"// used to keep last FindMaxSeparation call values",
"FindMaxSeparation",
".",
"_maxSeparation",
"=",
"maxSeparation",
";",
"FindMaxSeparation",
".",
"_bestIndex",
"=",
"bestIndex",
";",
"}"
] |
Find the max separation between poly1 and poly2 using edge normals from
poly1.
|
[
"Find",
"the",
"max",
"separation",
"between",
"poly1",
"and",
"poly2",
"using",
"edge",
"normals",
"from",
"poly1",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/shape/CollidePolygon.js#L49-L82
|
11,165
|
shakiba/planck.js
|
lib/shape/PolygonShape.js
|
PolygonShape
|
function PolygonShape(vertices) {
if (!(this instanceof PolygonShape)) {
return new PolygonShape(vertices);
}
PolygonShape._super.call(this);
this.m_type = PolygonShape.TYPE;
this.m_radius = Settings.polygonRadius;
this.m_centroid = Vec2.zero();
this.m_vertices = []; // Vec2[Settings.maxPolygonVertices]
this.m_normals = []; // Vec2[Settings.maxPolygonVertices]
this.m_count = 0;
if (vertices && vertices.length) {
this._set(vertices);
}
}
|
javascript
|
function PolygonShape(vertices) {
if (!(this instanceof PolygonShape)) {
return new PolygonShape(vertices);
}
PolygonShape._super.call(this);
this.m_type = PolygonShape.TYPE;
this.m_radius = Settings.polygonRadius;
this.m_centroid = Vec2.zero();
this.m_vertices = []; // Vec2[Settings.maxPolygonVertices]
this.m_normals = []; // Vec2[Settings.maxPolygonVertices]
this.m_count = 0;
if (vertices && vertices.length) {
this._set(vertices);
}
}
|
[
"function",
"PolygonShape",
"(",
"vertices",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"PolygonShape",
")",
")",
"{",
"return",
"new",
"PolygonShape",
"(",
"vertices",
")",
";",
"}",
"PolygonShape",
".",
"_super",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"m_type",
"=",
"PolygonShape",
".",
"TYPE",
";",
"this",
".",
"m_radius",
"=",
"Settings",
".",
"polygonRadius",
";",
"this",
".",
"m_centroid",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_vertices",
"=",
"[",
"]",
";",
"// Vec2[Settings.maxPolygonVertices]",
"this",
".",
"m_normals",
"=",
"[",
"]",
";",
"// Vec2[Settings.maxPolygonVertices]",
"this",
".",
"m_count",
"=",
"0",
";",
"if",
"(",
"vertices",
"&&",
"vertices",
".",
"length",
")",
"{",
"this",
".",
"_set",
"(",
"vertices",
")",
";",
"}",
"}"
] |
A convex polygon. It is assumed that the interior of the polygon is to the
left of each edge. Polygons have a maximum number of vertices equal to
Settings.maxPolygonVertices. In most cases you should not need many vertices
for a convex polygon. extends Shape
|
[
"A",
"convex",
"polygon",
".",
"It",
"is",
"assumed",
"that",
"the",
"interior",
"of",
"the",
"polygon",
"is",
"to",
"the",
"left",
"of",
"each",
"edge",
".",
"Polygons",
"have",
"a",
"maximum",
"number",
"of",
"vertices",
"equal",
"to",
"Settings",
".",
"maxPolygonVertices",
".",
"In",
"most",
"cases",
"you",
"should",
"not",
"need",
"many",
"vertices",
"for",
"a",
"convex",
"polygon",
".",
"extends",
"Shape"
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/shape/PolygonShape.js#L48-L65
|
11,166
|
shakiba/planck.js
|
lib/joint/RevoluteJoint.js
|
RevoluteJoint
|
function RevoluteJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof RevoluteJoint)) {
return new RevoluteJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = RevoluteJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero();
this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle();
this.m_impulse = Vec3();
this.m_motorImpulse = 0.0;
this.m_lowerAngle = def.lowerAngle;
this.m_upperAngle = def.upperAngle;
this.m_maxMotorTorque = def.maxMotorTorque;
this.m_motorSpeed = def.motorSpeed;
this.m_enableLimit = def.enableLimit;
this.m_enableMotor = def.enableMotor;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
// effective mass for point-to-point constraint.
this.m_mass = new Mat33();
// effective mass for motor/limit angular constraint.
this.m_motorMass; // float
this.m_limitState = inactiveLimit;
// Point-to-point constraint
// C = p2 - p1
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Motor constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
}
|
javascript
|
function RevoluteJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof RevoluteJoint)) {
return new RevoluteJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = RevoluteJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero();
this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle();
this.m_impulse = Vec3();
this.m_motorImpulse = 0.0;
this.m_lowerAngle = def.lowerAngle;
this.m_upperAngle = def.upperAngle;
this.m_maxMotorTorque = def.maxMotorTorque;
this.m_motorSpeed = def.motorSpeed;
this.m_enableLimit = def.enableLimit;
this.m_enableMotor = def.enableMotor;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
// effective mass for point-to-point constraint.
this.m_mass = new Mat33();
// effective mass for motor/limit angular constraint.
this.m_motorMass; // float
this.m_limitState = inactiveLimit;
// Point-to-point constraint
// C = p2 - p1
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Motor constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
}
|
[
"function",
"RevoluteJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"anchor",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"RevoluteJoint",
")",
")",
"{",
"return",
"new",
"RevoluteJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"anchor",
")",
";",
"}",
"def",
"=",
"options",
"(",
"def",
",",
"DEFAULTS",
")",
";",
"Joint",
".",
"call",
"(",
"this",
",",
"def",
",",
"bodyA",
",",
"bodyB",
")",
";",
"bodyA",
"=",
"this",
".",
"m_bodyA",
";",
"bodyB",
"=",
"this",
".",
"m_bodyB",
";",
"this",
".",
"m_type",
"=",
"RevoluteJoint",
".",
"TYPE",
";",
"this",
".",
"m_localAnchorA",
"=",
"anchor",
"?",
"bodyA",
".",
"getLocalPoint",
"(",
"anchor",
")",
":",
"def",
".",
"localAnchorA",
"||",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_localAnchorB",
"=",
"anchor",
"?",
"bodyB",
".",
"getLocalPoint",
"(",
"anchor",
")",
":",
"def",
".",
"localAnchorB",
"||",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_referenceAngle",
"=",
"Math",
".",
"isFinite",
"(",
"def",
".",
"referenceAngle",
")",
"?",
"def",
".",
"referenceAngle",
":",
"bodyB",
".",
"getAngle",
"(",
")",
"-",
"bodyA",
".",
"getAngle",
"(",
")",
";",
"this",
".",
"m_impulse",
"=",
"Vec3",
"(",
")",
";",
"this",
".",
"m_motorImpulse",
"=",
"0.0",
";",
"this",
".",
"m_lowerAngle",
"=",
"def",
".",
"lowerAngle",
";",
"this",
".",
"m_upperAngle",
"=",
"def",
".",
"upperAngle",
";",
"this",
".",
"m_maxMotorTorque",
"=",
"def",
".",
"maxMotorTorque",
";",
"this",
".",
"m_motorSpeed",
"=",
"def",
".",
"motorSpeed",
";",
"this",
".",
"m_enableLimit",
"=",
"def",
".",
"enableLimit",
";",
"this",
".",
"m_enableMotor",
"=",
"def",
".",
"enableMotor",
";",
"// Solver temp",
"this",
".",
"m_rA",
";",
"// Vec2",
"this",
".",
"m_rB",
";",
"// Vec2",
"this",
".",
"m_localCenterA",
";",
"// Vec2",
"this",
".",
"m_localCenterB",
";",
"// Vec2",
"this",
".",
"m_invMassA",
";",
"// float",
"this",
".",
"m_invMassB",
";",
"// float",
"this",
".",
"m_invIA",
";",
"// float",
"this",
".",
"m_invIB",
";",
"// float",
"// effective mass for point-to-point constraint.",
"this",
".",
"m_mass",
"=",
"new",
"Mat33",
"(",
")",
";",
"// effective mass for motor/limit angular constraint.",
"this",
".",
"m_motorMass",
";",
"// float",
"this",
".",
"m_limitState",
"=",
"inactiveLimit",
";",
"// Point-to-point constraint",
"// C = p2 - p1",
"// Cdot = v2 - v1",
"// = v2 + cross(w2, r2) - v1 - cross(w1, r1)",
"// J = [-I -r1_skew I r2_skew ]",
"// Identity used:",
"// w k % (rx i + ry j) = w * (-ry i + rx j)",
"// Motor constraint",
"// Cdot = w2 - w1",
"// J = [0 0 -1 0 0 1]",
"// K = invI1 + invI2",
"}"
] |
A revolute joint constrains two bodies to share a common point while they are
free to rotate about the point. The relative rotation about the shared point
is the joint angle. You can limit the relative rotation with a joint limit
that specifies a lower and upper angle. You can use a motor to drive the
relative rotation about the shared point. A maximum motor torque is provided
so that infinite forces are not generated.
@param {RevoluteJointDef} def
@param {Body} bodyA
@param {Body} bodyB
|
[
"A",
"revolute",
"joint",
"constrains",
"two",
"bodies",
"to",
"share",
"a",
"common",
"point",
"while",
"they",
"are",
"free",
"to",
"rotate",
"about",
"the",
"point",
".",
"The",
"relative",
"rotation",
"about",
"the",
"shared",
"point",
"is",
"the",
"joint",
"angle",
".",
"You",
"can",
"limit",
"the",
"relative",
"rotation",
"with",
"a",
"joint",
"limit",
"that",
"specifies",
"a",
"lower",
"and",
"upper",
"angle",
".",
"You",
"can",
"use",
"a",
"motor",
"to",
"drive",
"the",
"relative",
"rotation",
"about",
"the",
"shared",
"point",
".",
"A",
"maximum",
"motor",
"torque",
"is",
"provided",
"so",
"that",
"infinite",
"forces",
"are",
"not",
"generated",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/joint/RevoluteJoint.js#L103-L156
|
11,167
|
shakiba/planck.js
|
lib/collision/Distance.js
|
DistanceInput
|
function DistanceInput() {
this.proxyA = new DistanceProxy();
this.proxyB = new DistanceProxy();
this.transformA = null;
this.transformB = null;
this.useRadii = false;
}
|
javascript
|
function DistanceInput() {
this.proxyA = new DistanceProxy();
this.proxyB = new DistanceProxy();
this.transformA = null;
this.transformB = null;
this.useRadii = false;
}
|
[
"function",
"DistanceInput",
"(",
")",
"{",
"this",
".",
"proxyA",
"=",
"new",
"DistanceProxy",
"(",
")",
";",
"this",
".",
"proxyB",
"=",
"new",
"DistanceProxy",
"(",
")",
";",
"this",
".",
"transformA",
"=",
"null",
";",
"this",
".",
"transformB",
"=",
"null",
";",
"this",
".",
"useRadii",
"=",
"false",
";",
"}"
] |
Input for Distance. You have to option to use the shape radii in the
computation. Even
|
[
"Input",
"for",
"Distance",
".",
"You",
"have",
"to",
"option",
"to",
"use",
"the",
"shape",
"radii",
"in",
"the",
"computation",
".",
"Even"
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/collision/Distance.js#L58-L64
|
11,168
|
shakiba/planck.js
|
lib/Joint.js
|
Joint
|
function Joint(def, bodyA, bodyB) {
bodyA = def.bodyA || bodyA;
bodyB = def.bodyB || bodyB;
_ASSERT && common.assert(bodyA);
_ASSERT && common.assert(bodyB);
_ASSERT && common.assert(bodyA != bodyB);
this.m_type = 'unknown-joint';
this.m_bodyA = bodyA;
this.m_bodyB = bodyB;
this.m_index = 0;
this.m_collideConnected = !!def.collideConnected;
this.m_prev = null;
this.m_next = null;
this.m_edgeA = new JointEdge();
this.m_edgeB = new JointEdge();
this.m_islandFlag = false;
this.m_userData = def.userData;
}
|
javascript
|
function Joint(def, bodyA, bodyB) {
bodyA = def.bodyA || bodyA;
bodyB = def.bodyB || bodyB;
_ASSERT && common.assert(bodyA);
_ASSERT && common.assert(bodyB);
_ASSERT && common.assert(bodyA != bodyB);
this.m_type = 'unknown-joint';
this.m_bodyA = bodyA;
this.m_bodyB = bodyB;
this.m_index = 0;
this.m_collideConnected = !!def.collideConnected;
this.m_prev = null;
this.m_next = null;
this.m_edgeA = new JointEdge();
this.m_edgeB = new JointEdge();
this.m_islandFlag = false;
this.m_userData = def.userData;
}
|
[
"function",
"Joint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
")",
"{",
"bodyA",
"=",
"def",
".",
"bodyA",
"||",
"bodyA",
";",
"bodyB",
"=",
"def",
".",
"bodyB",
"||",
"bodyB",
";",
"_ASSERT",
"&&",
"common",
".",
"assert",
"(",
"bodyA",
")",
";",
"_ASSERT",
"&&",
"common",
".",
"assert",
"(",
"bodyB",
")",
";",
"_ASSERT",
"&&",
"common",
".",
"assert",
"(",
"bodyA",
"!=",
"bodyB",
")",
";",
"this",
".",
"m_type",
"=",
"'unknown-joint'",
";",
"this",
".",
"m_bodyA",
"=",
"bodyA",
";",
"this",
".",
"m_bodyB",
"=",
"bodyB",
";",
"this",
".",
"m_index",
"=",
"0",
";",
"this",
".",
"m_collideConnected",
"=",
"!",
"!",
"def",
".",
"collideConnected",
";",
"this",
".",
"m_prev",
"=",
"null",
";",
"this",
".",
"m_next",
"=",
"null",
";",
"this",
".",
"m_edgeA",
"=",
"new",
"JointEdge",
"(",
")",
";",
"this",
".",
"m_edgeB",
"=",
"new",
"JointEdge",
"(",
")",
";",
"this",
".",
"m_islandFlag",
"=",
"false",
";",
"this",
".",
"m_userData",
"=",
"def",
".",
"userData",
";",
"}"
] |
The base joint class. Joints are used to constraint two bodies together in
various fashions. Some joints also feature limits and motors.
@param {JointDef} def
|
[
"The",
"base",
"joint",
"class",
".",
"Joints",
"are",
"used",
"to",
"constraint",
"two",
"bodies",
"together",
"in",
"various",
"fashions",
".",
"Some",
"joints",
"also",
"feature",
"limits",
"and",
"motors",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/Joint.js#L70-L94
|
11,169
|
shakiba/planck.js
|
lib/shape/ChainShape.js
|
ChainShape
|
function ChainShape(vertices, loop) {
if (!(this instanceof ChainShape)) {
return new ChainShape(vertices, loop);
}
ChainShape._super.call(this);
this.m_type = ChainShape.TYPE;
this.m_radius = Settings.polygonRadius;
this.m_vertices = [];
this.m_count = 0;
this.m_prevVertex = null;
this.m_nextVertex = null;
this.m_hasPrevVertex = false;
this.m_hasNextVertex = false;
this.m_isLoop = loop;
if (vertices && vertices.length) {
if (loop) {
this._createLoop(vertices);
} else {
this._createChain(vertices);
}
}
}
|
javascript
|
function ChainShape(vertices, loop) {
if (!(this instanceof ChainShape)) {
return new ChainShape(vertices, loop);
}
ChainShape._super.call(this);
this.m_type = ChainShape.TYPE;
this.m_radius = Settings.polygonRadius;
this.m_vertices = [];
this.m_count = 0;
this.m_prevVertex = null;
this.m_nextVertex = null;
this.m_hasPrevVertex = false;
this.m_hasNextVertex = false;
this.m_isLoop = loop;
if (vertices && vertices.length) {
if (loop) {
this._createLoop(vertices);
} else {
this._createChain(vertices);
}
}
}
|
[
"function",
"ChainShape",
"(",
"vertices",
",",
"loop",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"ChainShape",
")",
")",
"{",
"return",
"new",
"ChainShape",
"(",
"vertices",
",",
"loop",
")",
";",
"}",
"ChainShape",
".",
"_super",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"m_type",
"=",
"ChainShape",
".",
"TYPE",
";",
"this",
".",
"m_radius",
"=",
"Settings",
".",
"polygonRadius",
";",
"this",
".",
"m_vertices",
"=",
"[",
"]",
";",
"this",
".",
"m_count",
"=",
"0",
";",
"this",
".",
"m_prevVertex",
"=",
"null",
";",
"this",
".",
"m_nextVertex",
"=",
"null",
";",
"this",
".",
"m_hasPrevVertex",
"=",
"false",
";",
"this",
".",
"m_hasNextVertex",
"=",
"false",
";",
"this",
".",
"m_isLoop",
"=",
"loop",
";",
"if",
"(",
"vertices",
"&&",
"vertices",
".",
"length",
")",
"{",
"if",
"(",
"loop",
")",
"{",
"this",
".",
"_createLoop",
"(",
"vertices",
")",
";",
"}",
"else",
"{",
"this",
".",
"_createChain",
"(",
"vertices",
")",
";",
"}",
"}",
"}"
] |
A chain shape is a free form sequence of line segments. The chain has
two-sided collision, so you can use inside and outside collision. Therefore,
you may use any winding order. Connectivity information is used to create
smooth collisions.
WARNING: The chain will not collide properly if there are self-intersections.
|
[
"A",
"chain",
"shape",
"is",
"a",
"free",
"form",
"sequence",
"of",
"line",
"segments",
".",
"The",
"chain",
"has",
"two",
"-",
"sided",
"collision",
"so",
"you",
"can",
"use",
"inside",
"and",
"outside",
"collision",
".",
"Therefore",
"you",
"may",
"use",
"any",
"winding",
"order",
".",
"Connectivity",
"information",
"is",
"used",
"to",
"create",
"smooth",
"collisions",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/shape/ChainShape.js#L51-L76
|
11,170
|
shakiba/planck.js
|
lib/collision/TimeOfImpact.js
|
TOIInput
|
function TOIInput() {
this.proxyA = new DistanceProxy();
this.proxyB = new DistanceProxy();
this.sweepA = new Sweep();
this.sweepB = new Sweep();
this.tMax;
}
|
javascript
|
function TOIInput() {
this.proxyA = new DistanceProxy();
this.proxyB = new DistanceProxy();
this.sweepA = new Sweep();
this.sweepB = new Sweep();
this.tMax;
}
|
[
"function",
"TOIInput",
"(",
")",
"{",
"this",
".",
"proxyA",
"=",
"new",
"DistanceProxy",
"(",
")",
";",
"this",
".",
"proxyB",
"=",
"new",
"DistanceProxy",
"(",
")",
";",
"this",
".",
"sweepA",
"=",
"new",
"Sweep",
"(",
")",
";",
"this",
".",
"sweepB",
"=",
"new",
"Sweep",
"(",
")",
";",
"this",
".",
"tMax",
";",
"}"
] |
Input parameters for TimeOfImpact.
@prop {DistanceProxy} proxyA
@prop {DistanceProxy} proxyB
@prop {Sweep} sweepA
@prop {Sweep} sweepB
@prop tMax defines sweep interval [0, tMax]
|
[
"Input",
"parameters",
"for",
"TimeOfImpact",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/collision/TimeOfImpact.js#L60-L66
|
11,171
|
shakiba/planck.js
|
lib/shape/BoxShape.js
|
BoxShape
|
function BoxShape(hx, hy, center, angle) {
if (!(this instanceof BoxShape)) {
return new BoxShape(hx, hy, center, angle);
}
BoxShape._super.call(this);
this._setAsBox(hx, hy, center, angle);
}
|
javascript
|
function BoxShape(hx, hy, center, angle) {
if (!(this instanceof BoxShape)) {
return new BoxShape(hx, hy, center, angle);
}
BoxShape._super.call(this);
this._setAsBox(hx, hy, center, angle);
}
|
[
"function",
"BoxShape",
"(",
"hx",
",",
"hy",
",",
"center",
",",
"angle",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"BoxShape",
")",
")",
"{",
"return",
"new",
"BoxShape",
"(",
"hx",
",",
"hy",
",",
"center",
",",
"angle",
")",
";",
"}",
"BoxShape",
".",
"_super",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"_setAsBox",
"(",
"hx",
",",
"hy",
",",
"center",
",",
"angle",
")",
";",
"}"
] |
A rectangle polygon which extend PolygonShape.
|
[
"A",
"rectangle",
"polygon",
"which",
"extend",
"PolygonShape",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/shape/BoxShape.js#L37-L45
|
11,172
|
shakiba/planck.js
|
example/Asteroid.js
|
addAsteroids
|
function addAsteroids() {
while (asteroidBodies.length) {
var asteroidBody = asteroidBodies.shift();
world.destroyBody(asteroidBody);
// asteroidBody.uiRemove();
}
for (var i = 0; i < level; i++) {
var shipPosition = shipBody.getPosition();
var x = shipPosition.x;
var y = shipPosition.y;
// Aviod the ship!
while (Math.abs(x - shipPosition.x) < asteroidRadius * 2
&& Math.abs(y - shipPosition.y) < asteroidRadius * 2) {
x = rand(SPACE_WIDTH);
y = rand(SPACE_HEIGHT);
}
var vx = rand(asteroidSpeed);
var vy = rand(asteroidSpeed);
var va = rand(asteroidSpeed);
// Create asteroid body
var asteroidBody = makeAsteroidBody(x, y, vx, vy, va, 0);
asteroidBody.level = 1;
}
}
|
javascript
|
function addAsteroids() {
while (asteroidBodies.length) {
var asteroidBody = asteroidBodies.shift();
world.destroyBody(asteroidBody);
// asteroidBody.uiRemove();
}
for (var i = 0; i < level; i++) {
var shipPosition = shipBody.getPosition();
var x = shipPosition.x;
var y = shipPosition.y;
// Aviod the ship!
while (Math.abs(x - shipPosition.x) < asteroidRadius * 2
&& Math.abs(y - shipPosition.y) < asteroidRadius * 2) {
x = rand(SPACE_WIDTH);
y = rand(SPACE_HEIGHT);
}
var vx = rand(asteroidSpeed);
var vy = rand(asteroidSpeed);
var va = rand(asteroidSpeed);
// Create asteroid body
var asteroidBody = makeAsteroidBody(x, y, vx, vy, va, 0);
asteroidBody.level = 1;
}
}
|
[
"function",
"addAsteroids",
"(",
")",
"{",
"while",
"(",
"asteroidBodies",
".",
"length",
")",
"{",
"var",
"asteroidBody",
"=",
"asteroidBodies",
".",
"shift",
"(",
")",
";",
"world",
".",
"destroyBody",
"(",
"asteroidBody",
")",
";",
"// asteroidBody.uiRemove();",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"level",
";",
"i",
"++",
")",
"{",
"var",
"shipPosition",
"=",
"shipBody",
".",
"getPosition",
"(",
")",
";",
"var",
"x",
"=",
"shipPosition",
".",
"x",
";",
"var",
"y",
"=",
"shipPosition",
".",
"y",
";",
"// Aviod the ship!",
"while",
"(",
"Math",
".",
"abs",
"(",
"x",
"-",
"shipPosition",
".",
"x",
")",
"<",
"asteroidRadius",
"*",
"2",
"&&",
"Math",
".",
"abs",
"(",
"y",
"-",
"shipPosition",
".",
"y",
")",
"<",
"asteroidRadius",
"*",
"2",
")",
"{",
"x",
"=",
"rand",
"(",
"SPACE_WIDTH",
")",
";",
"y",
"=",
"rand",
"(",
"SPACE_HEIGHT",
")",
";",
"}",
"var",
"vx",
"=",
"rand",
"(",
"asteroidSpeed",
")",
";",
"var",
"vy",
"=",
"rand",
"(",
"asteroidSpeed",
")",
";",
"var",
"va",
"=",
"rand",
"(",
"asteroidSpeed",
")",
";",
"// Create asteroid body",
"var",
"asteroidBody",
"=",
"makeAsteroidBody",
"(",
"x",
",",
"y",
",",
"vx",
",",
"vy",
",",
"va",
",",
"0",
")",
";",
"asteroidBody",
".",
"level",
"=",
"1",
";",
"}",
"}"
] |
Adds some asteroids to the scene.
|
[
"Adds",
"some",
"asteroids",
"to",
"the",
"scene",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/example/Asteroid.js#L202-L229
|
11,173
|
shakiba/planck.js
|
example/Asteroid.js
|
wrap
|
function wrap(body) {
var p = body.getPosition();
p.x = wrapNumber(p.x, -SPACE_WIDTH / 2, SPACE_WIDTH / 2);
p.y = wrapNumber(p.y, -SPACE_HEIGHT / 2, SPACE_HEIGHT / 2);
body.setPosition(p);
}
|
javascript
|
function wrap(body) {
var p = body.getPosition();
p.x = wrapNumber(p.x, -SPACE_WIDTH / 2, SPACE_WIDTH / 2);
p.y = wrapNumber(p.y, -SPACE_HEIGHT / 2, SPACE_HEIGHT / 2);
body.setPosition(p);
}
|
[
"function",
"wrap",
"(",
"body",
")",
"{",
"var",
"p",
"=",
"body",
".",
"getPosition",
"(",
")",
";",
"p",
".",
"x",
"=",
"wrapNumber",
"(",
"p",
".",
"x",
",",
"-",
"SPACE_WIDTH",
"/",
"2",
",",
"SPACE_WIDTH",
"/",
"2",
")",
";",
"p",
".",
"y",
"=",
"wrapNumber",
"(",
"p",
".",
"y",
",",
"-",
"SPACE_HEIGHT",
"/",
"2",
",",
"SPACE_HEIGHT",
"/",
"2",
")",
";",
"body",
".",
"setPosition",
"(",
"p",
")",
";",
"}"
] |
If the body is out of space bounds, wrap it to the other side
|
[
"If",
"the",
"body",
"is",
"out",
"of",
"space",
"bounds",
"wrap",
"it",
"to",
"the",
"other",
"side"
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/example/Asteroid.js#L329-L334
|
11,174
|
shakiba/planck.js
|
lib/joint/DistanceJoint.js
|
DistanceJoint
|
function DistanceJoint(def, bodyA, bodyB, anchorA, anchorB) {
if (!(this instanceof DistanceJoint)) {
return new DistanceJoint(def, bodyA, bodyB, anchorA, anchorB);
}
// order of constructor arguments is changed in v0.2
if (bodyB && anchorA && ('m_type' in anchorA) && ('x' in bodyB) && ('y' in bodyB)) {
var temp = bodyB;
bodyB = anchorA;
anchorA = temp;
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = DistanceJoint.TYPE;
// Solver shared
this.m_localAnchorA = anchorA ? bodyA.getLocalPoint(anchorA) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchorB ? bodyB.getLocalPoint(anchorB) : def.localAnchorB || Vec2.zero();
this.m_length = Math.isFinite(def.length) ? def.length :
Vec2.distance(bodyA.getWorldPoint(this.m_localAnchorA), bodyB.getWorldPoint(this.m_localAnchorB));
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_impulse = 0.0;
this.m_gamma = 0.0;
this.m_bias = 0.0;
// Solver temp
this.m_u; // Vec2
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_mass;
// 1-D constrained system
// m (v2 - v1) = lambda
// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass.
// x2 = x1 + h * v2
// 1-D mass-damper-spring system
// m (v2 - v1) + h * d * v2 + h * k *
// C = norm(p2 - p1) - L
// u = (p2 - p1) / norm(p2 - p1)
// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
// J = [-u -cross(r1, u) u cross(r2, u)]
// K = J * invM * JT
// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
}
|
javascript
|
function DistanceJoint(def, bodyA, bodyB, anchorA, anchorB) {
if (!(this instanceof DistanceJoint)) {
return new DistanceJoint(def, bodyA, bodyB, anchorA, anchorB);
}
// order of constructor arguments is changed in v0.2
if (bodyB && anchorA && ('m_type' in anchorA) && ('x' in bodyB) && ('y' in bodyB)) {
var temp = bodyB;
bodyB = anchorA;
anchorA = temp;
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = DistanceJoint.TYPE;
// Solver shared
this.m_localAnchorA = anchorA ? bodyA.getLocalPoint(anchorA) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchorB ? bodyB.getLocalPoint(anchorB) : def.localAnchorB || Vec2.zero();
this.m_length = Math.isFinite(def.length) ? def.length :
Vec2.distance(bodyA.getWorldPoint(this.m_localAnchorA), bodyB.getWorldPoint(this.m_localAnchorB));
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_impulse = 0.0;
this.m_gamma = 0.0;
this.m_bias = 0.0;
// Solver temp
this.m_u; // Vec2
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA;
this.m_invMassB;
this.m_invIA;
this.m_invIB;
this.m_mass;
// 1-D constrained system
// m (v2 - v1) = lambda
// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass.
// x2 = x1 + h * v2
// 1-D mass-damper-spring system
// m (v2 - v1) + h * d * v2 + h * k *
// C = norm(p2 - p1) - L
// u = (p2 - p1) / norm(p2 - p1)
// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))
// J = [-u -cross(r1, u) u cross(r2, u)]
// K = J * invM * JT
// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2
}
|
[
"function",
"DistanceJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"anchorA",
",",
"anchorB",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"DistanceJoint",
")",
")",
"{",
"return",
"new",
"DistanceJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"anchorA",
",",
"anchorB",
")",
";",
"}",
"// order of constructor arguments is changed in v0.2",
"if",
"(",
"bodyB",
"&&",
"anchorA",
"&&",
"(",
"'m_type'",
"in",
"anchorA",
")",
"&&",
"(",
"'x'",
"in",
"bodyB",
")",
"&&",
"(",
"'y'",
"in",
"bodyB",
")",
")",
"{",
"var",
"temp",
"=",
"bodyB",
";",
"bodyB",
"=",
"anchorA",
";",
"anchorA",
"=",
"temp",
";",
"}",
"def",
"=",
"options",
"(",
"def",
",",
"DEFAULTS",
")",
";",
"Joint",
".",
"call",
"(",
"this",
",",
"def",
",",
"bodyA",
",",
"bodyB",
")",
";",
"bodyA",
"=",
"this",
".",
"m_bodyA",
";",
"bodyB",
"=",
"this",
".",
"m_bodyB",
";",
"this",
".",
"m_type",
"=",
"DistanceJoint",
".",
"TYPE",
";",
"// Solver shared",
"this",
".",
"m_localAnchorA",
"=",
"anchorA",
"?",
"bodyA",
".",
"getLocalPoint",
"(",
"anchorA",
")",
":",
"def",
".",
"localAnchorA",
"||",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_localAnchorB",
"=",
"anchorB",
"?",
"bodyB",
".",
"getLocalPoint",
"(",
"anchorB",
")",
":",
"def",
".",
"localAnchorB",
"||",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_length",
"=",
"Math",
".",
"isFinite",
"(",
"def",
".",
"length",
")",
"?",
"def",
".",
"length",
":",
"Vec2",
".",
"distance",
"(",
"bodyA",
".",
"getWorldPoint",
"(",
"this",
".",
"m_localAnchorA",
")",
",",
"bodyB",
".",
"getWorldPoint",
"(",
"this",
".",
"m_localAnchorB",
")",
")",
";",
"this",
".",
"m_frequencyHz",
"=",
"def",
".",
"frequencyHz",
";",
"this",
".",
"m_dampingRatio",
"=",
"def",
".",
"dampingRatio",
";",
"this",
".",
"m_impulse",
"=",
"0.0",
";",
"this",
".",
"m_gamma",
"=",
"0.0",
";",
"this",
".",
"m_bias",
"=",
"0.0",
";",
"// Solver temp",
"this",
".",
"m_u",
";",
"// Vec2",
"this",
".",
"m_rA",
";",
"// Vec2",
"this",
".",
"m_rB",
";",
"// Vec2",
"this",
".",
"m_localCenterA",
";",
"// Vec2",
"this",
".",
"m_localCenterB",
";",
"// Vec2",
"this",
".",
"m_invMassA",
";",
"this",
".",
"m_invMassB",
";",
"this",
".",
"m_invIA",
";",
"this",
".",
"m_invIB",
";",
"this",
".",
"m_mass",
";",
"// 1-D constrained system",
"// m (v2 - v1) = lambda",
"// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass.",
"// x2 = x1 + h * v2",
"// 1-D mass-damper-spring system",
"// m (v2 - v1) + h * d * v2 + h * k *",
"// C = norm(p2 - p1) - L",
"// u = (p2 - p1) / norm(p2 - p1)",
"// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1))",
"// J = [-u -cross(r1, u) u cross(r2, u)]",
"// K = J * invM * JT",
"// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2",
"}"
] |
A distance joint constrains two points on two bodies to remain at a fixed
distance from each other. You can view this as a massless, rigid rod.
@param {DistanceJointDef} def
@param {Body} bodyA
@param {Body} bodyB
@param {Vec2} anchorA Anchor A in global coordination.
@param {Vec2} anchorB Anchor B in global coordination.
|
[
"A",
"distance",
"joint",
"constrains",
"two",
"points",
"on",
"two",
"bodies",
"to",
"remain",
"at",
"a",
"fixed",
"distance",
"from",
"each",
"other",
".",
"You",
"can",
"view",
"this",
"as",
"a",
"massless",
"rigid",
"rod",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/joint/DistanceJoint.js#L81-L137
|
11,175
|
shakiba/planck.js
|
lib/joint/FrictionJoint.js
|
FrictionJoint
|
function FrictionJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof FrictionJoint)) {
return new FrictionJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = FrictionJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero();
// Solver shared
this.m_linearImpulse = Vec2.zero();
this.m_angularImpulse = 0.0;
this.m_maxForce = def.maxForce;
this.m_maxTorque = def.maxTorque;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_linearMass; // Mat22
this.m_angularMass; // float
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
}
|
javascript
|
function FrictionJoint(def, bodyA, bodyB, anchor) {
if (!(this instanceof FrictionJoint)) {
return new FrictionJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = FrictionJoint.TYPE;
this.m_localAnchorA = anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero();
this.m_localAnchorB = anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero();
// Solver shared
this.m_linearImpulse = Vec2.zero();
this.m_angularImpulse = 0.0;
this.m_maxForce = def.maxForce;
this.m_maxTorque = def.maxTorque;
// Solver temp
this.m_rA; // Vec2
this.m_rB; // Vec2
this.m_localCenterA; // Vec2
this.m_localCenterB; // Vec2
this.m_invMassA; // float
this.m_invMassB; // float
this.m_invIA; // float
this.m_invIB; // float
this.m_linearMass; // Mat22
this.m_angularMass; // float
// Point-to-point constraint
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Angle constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
}
|
[
"function",
"FrictionJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"anchor",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"FrictionJoint",
")",
")",
"{",
"return",
"new",
"FrictionJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"anchor",
")",
";",
"}",
"def",
"=",
"options",
"(",
"def",
",",
"DEFAULTS",
")",
";",
"Joint",
".",
"call",
"(",
"this",
",",
"def",
",",
"bodyA",
",",
"bodyB",
")",
";",
"bodyA",
"=",
"this",
".",
"m_bodyA",
";",
"bodyB",
"=",
"this",
".",
"m_bodyB",
";",
"this",
".",
"m_type",
"=",
"FrictionJoint",
".",
"TYPE",
";",
"this",
".",
"m_localAnchorA",
"=",
"anchor",
"?",
"bodyA",
".",
"getLocalPoint",
"(",
"anchor",
")",
":",
"def",
".",
"localAnchorA",
"||",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_localAnchorB",
"=",
"anchor",
"?",
"bodyB",
".",
"getLocalPoint",
"(",
"anchor",
")",
":",
"def",
".",
"localAnchorB",
"||",
"Vec2",
".",
"zero",
"(",
")",
";",
"// Solver shared",
"this",
".",
"m_linearImpulse",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_angularImpulse",
"=",
"0.0",
";",
"this",
".",
"m_maxForce",
"=",
"def",
".",
"maxForce",
";",
"this",
".",
"m_maxTorque",
"=",
"def",
".",
"maxTorque",
";",
"// Solver temp",
"this",
".",
"m_rA",
";",
"// Vec2",
"this",
".",
"m_rB",
";",
"// Vec2",
"this",
".",
"m_localCenterA",
";",
"// Vec2",
"this",
".",
"m_localCenterB",
";",
"// Vec2",
"this",
".",
"m_invMassA",
";",
"// float",
"this",
".",
"m_invMassB",
";",
"// float",
"this",
".",
"m_invIA",
";",
"// float",
"this",
".",
"m_invIB",
";",
"// float",
"this",
".",
"m_linearMass",
";",
"// Mat22",
"this",
".",
"m_angularMass",
";",
"// float",
"// Point-to-point constraint",
"// Cdot = v2 - v1",
"// = v2 + cross(w2, r2) - v1 - cross(w1, r1)",
"// J = [-I -r1_skew I r2_skew ]",
"// Identity used:",
"// w k % (rx i + ry j) = w * (-ry i + rx j)",
"// Angle constraint",
"// Cdot = w2 - w1",
"// J = [0 0 -1 0 0 1]",
"// K = invI1 + invI2",
"}"
] |
Friction joint. This is used for top-down friction. It provides 2D
translational friction and angular friction.
@param {FrictionJointDef} def
@param {Body} bodyA
@param {Body} bodyB
@param {Vec2} anchor Anchor in global coordination.
|
[
"Friction",
"joint",
".",
"This",
"is",
"used",
"for",
"top",
"-",
"down",
"friction",
".",
"It",
"provides",
"2D",
"translational",
"friction",
"and",
"angular",
"friction",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/joint/FrictionJoint.js#L74-L118
|
11,176
|
shakiba/planck.js
|
lib/joint/MouseJoint.js
|
MouseJoint
|
function MouseJoint(def, bodyA, bodyB, target) {
if (!(this instanceof MouseJoint)) {
return new MouseJoint(def, bodyA, bodyB, target);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = MouseJoint.TYPE;
_ASSERT && common.assert(Math.isFinite(def.maxForce) && def.maxForce >= 0.0);
_ASSERT && common.assert(Math.isFinite(def.frequencyHz) && def.frequencyHz >= 0.0);
_ASSERT && common.assert(Math.isFinite(def.dampingRatio) && def.dampingRatio >= 0.0);
this.m_targetA = target ? Vec2.clone(target) : def.target || Vec2.zero();
this.m_localAnchorB = Transform.mulTVec2(bodyB.getTransform(), this.m_targetA);
this.m_maxForce = def.maxForce;
this.m_impulse = Vec2.zero();
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_beta = 0.0;
this.m_gamma = 0.0;
// Solver temp
this.m_rB = Vec2.zero();
this.m_localCenterB = Vec2.zero();
this.m_invMassB = 0.0;
this.m_invIB = 0.0;
this.mass = new Mat22()
this.m_C = Vec2.zero();
// p = attached point, m = mouse point
// C = p - m
// Cdot = v
// = v + cross(w, r)
// J = [I r_skew]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
}
|
javascript
|
function MouseJoint(def, bodyA, bodyB, target) {
if (!(this instanceof MouseJoint)) {
return new MouseJoint(def, bodyA, bodyB, target);
}
def = options(def, DEFAULTS);
Joint.call(this, def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = MouseJoint.TYPE;
_ASSERT && common.assert(Math.isFinite(def.maxForce) && def.maxForce >= 0.0);
_ASSERT && common.assert(Math.isFinite(def.frequencyHz) && def.frequencyHz >= 0.0);
_ASSERT && common.assert(Math.isFinite(def.dampingRatio) && def.dampingRatio >= 0.0);
this.m_targetA = target ? Vec2.clone(target) : def.target || Vec2.zero();
this.m_localAnchorB = Transform.mulTVec2(bodyB.getTransform(), this.m_targetA);
this.m_maxForce = def.maxForce;
this.m_impulse = Vec2.zero();
this.m_frequencyHz = def.frequencyHz;
this.m_dampingRatio = def.dampingRatio;
this.m_beta = 0.0;
this.m_gamma = 0.0;
// Solver temp
this.m_rB = Vec2.zero();
this.m_localCenterB = Vec2.zero();
this.m_invMassB = 0.0;
this.m_invIB = 0.0;
this.mass = new Mat22()
this.m_C = Vec2.zero();
// p = attached point, m = mouse point
// C = p - m
// Cdot = v
// = v + cross(w, r)
// J = [I r_skew]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
}
|
[
"function",
"MouseJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"target",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"MouseJoint",
")",
")",
"{",
"return",
"new",
"MouseJoint",
"(",
"def",
",",
"bodyA",
",",
"bodyB",
",",
"target",
")",
";",
"}",
"def",
"=",
"options",
"(",
"def",
",",
"DEFAULTS",
")",
";",
"Joint",
".",
"call",
"(",
"this",
",",
"def",
",",
"bodyA",
",",
"bodyB",
")",
";",
"bodyA",
"=",
"this",
".",
"m_bodyA",
";",
"bodyB",
"=",
"this",
".",
"m_bodyB",
";",
"this",
".",
"m_type",
"=",
"MouseJoint",
".",
"TYPE",
";",
"_ASSERT",
"&&",
"common",
".",
"assert",
"(",
"Math",
".",
"isFinite",
"(",
"def",
".",
"maxForce",
")",
"&&",
"def",
".",
"maxForce",
">=",
"0.0",
")",
";",
"_ASSERT",
"&&",
"common",
".",
"assert",
"(",
"Math",
".",
"isFinite",
"(",
"def",
".",
"frequencyHz",
")",
"&&",
"def",
".",
"frequencyHz",
">=",
"0.0",
")",
";",
"_ASSERT",
"&&",
"common",
".",
"assert",
"(",
"Math",
".",
"isFinite",
"(",
"def",
".",
"dampingRatio",
")",
"&&",
"def",
".",
"dampingRatio",
">=",
"0.0",
")",
";",
"this",
".",
"m_targetA",
"=",
"target",
"?",
"Vec2",
".",
"clone",
"(",
"target",
")",
":",
"def",
".",
"target",
"||",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_localAnchorB",
"=",
"Transform",
".",
"mulTVec2",
"(",
"bodyB",
".",
"getTransform",
"(",
")",
",",
"this",
".",
"m_targetA",
")",
";",
"this",
".",
"m_maxForce",
"=",
"def",
".",
"maxForce",
";",
"this",
".",
"m_impulse",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_frequencyHz",
"=",
"def",
".",
"frequencyHz",
";",
"this",
".",
"m_dampingRatio",
"=",
"def",
".",
"dampingRatio",
";",
"this",
".",
"m_beta",
"=",
"0.0",
";",
"this",
".",
"m_gamma",
"=",
"0.0",
";",
"// Solver temp",
"this",
".",
"m_rB",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_localCenterB",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"m_invMassB",
"=",
"0.0",
";",
"this",
".",
"m_invIB",
"=",
"0.0",
";",
"this",
".",
"mass",
"=",
"new",
"Mat22",
"(",
")",
"this",
".",
"m_C",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"// p = attached point, m = mouse point",
"// C = p - m",
"// Cdot = v",
"// = v + cross(w, r)",
"// J = [I r_skew]",
"// Identity used:",
"// w k % (rx i + ry j) = w * (-ry i + rx j)",
"}"
] |
A mouse joint is used to make a point on a body track a specified world
point. This a soft constraint with a maximum force. This allows the
constraint to stretch and without applying huge forces.
NOTE: this joint is not documented in the manual because it was developed to
be used in the testbed. If you want to learn how to use the mouse joint, look
at the testbed.
@param {MouseJointDef} def
@param {Body} bodyA
@param {Body} bodyB
|
[
"A",
"mouse",
"joint",
"is",
"used",
"to",
"make",
"a",
"point",
"on",
"a",
"body",
"track",
"a",
"specified",
"world",
"point",
".",
"This",
"a",
"soft",
"constraint",
"with",
"a",
"maximum",
"force",
".",
"This",
"allows",
"the",
"constraint",
"to",
"stretch",
"and",
"without",
"applying",
"huge",
"forces",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/joint/MouseJoint.js#L83-L126
|
11,177
|
shakiba/planck.js
|
lib/Fixture.js
|
FixtureProxy
|
function FixtureProxy(fixture, childIndex) {
this.aabb = new AABB();
this.fixture = fixture;
this.childIndex = childIndex;
this.proxyId;
}
|
javascript
|
function FixtureProxy(fixture, childIndex) {
this.aabb = new AABB();
this.fixture = fixture;
this.childIndex = childIndex;
this.proxyId;
}
|
[
"function",
"FixtureProxy",
"(",
"fixture",
",",
"childIndex",
")",
"{",
"this",
".",
"aabb",
"=",
"new",
"AABB",
"(",
")",
";",
"this",
".",
"fixture",
"=",
"fixture",
";",
"this",
".",
"childIndex",
"=",
"childIndex",
";",
"this",
".",
"proxyId",
";",
"}"
] |
This proxy is used internally to connect shape children to the broad-phase.
|
[
"This",
"proxy",
"is",
"used",
"internally",
"to",
"connect",
"shape",
"children",
"to",
"the",
"broad",
"-",
"phase",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/Fixture.js#L70-L75
|
11,178
|
shakiba/planck.js
|
lib/Fixture.js
|
Fixture
|
function Fixture(body, shape, def) {
if (shape.shape) {
def = shape;
shape = shape.shape;
} else if (typeof def === 'number') {
def = {density : def};
}
def = options(def, FixtureDef);
this.m_body = body;
this.m_friction = def.friction;
this.m_restitution = def.restitution;
this.m_density = def.density;
this.m_isSensor = def.isSensor;
this.m_filterGroupIndex = def.filterGroupIndex;
this.m_filterCategoryBits = def.filterCategoryBits;
this.m_filterMaskBits = def.filterMaskBits;
// TODO validate shape
this.m_shape = shape; //.clone();
this.m_next = null;
this.m_proxies = [];
this.m_proxyCount = 0;
var childCount = this.m_shape.getChildCount();
for (var i = 0; i < childCount; ++i) {
this.m_proxies[i] = new FixtureProxy(this, i);
}
this.m_userData = def.userData;
}
|
javascript
|
function Fixture(body, shape, def) {
if (shape.shape) {
def = shape;
shape = shape.shape;
} else if (typeof def === 'number') {
def = {density : def};
}
def = options(def, FixtureDef);
this.m_body = body;
this.m_friction = def.friction;
this.m_restitution = def.restitution;
this.m_density = def.density;
this.m_isSensor = def.isSensor;
this.m_filterGroupIndex = def.filterGroupIndex;
this.m_filterCategoryBits = def.filterCategoryBits;
this.m_filterMaskBits = def.filterMaskBits;
// TODO validate shape
this.m_shape = shape; //.clone();
this.m_next = null;
this.m_proxies = [];
this.m_proxyCount = 0;
var childCount = this.m_shape.getChildCount();
for (var i = 0; i < childCount; ++i) {
this.m_proxies[i] = new FixtureProxy(this, i);
}
this.m_userData = def.userData;
}
|
[
"function",
"Fixture",
"(",
"body",
",",
"shape",
",",
"def",
")",
"{",
"if",
"(",
"shape",
".",
"shape",
")",
"{",
"def",
"=",
"shape",
";",
"shape",
"=",
"shape",
".",
"shape",
";",
"}",
"else",
"if",
"(",
"typeof",
"def",
"===",
"'number'",
")",
"{",
"def",
"=",
"{",
"density",
":",
"def",
"}",
";",
"}",
"def",
"=",
"options",
"(",
"def",
",",
"FixtureDef",
")",
";",
"this",
".",
"m_body",
"=",
"body",
";",
"this",
".",
"m_friction",
"=",
"def",
".",
"friction",
";",
"this",
".",
"m_restitution",
"=",
"def",
".",
"restitution",
";",
"this",
".",
"m_density",
"=",
"def",
".",
"density",
";",
"this",
".",
"m_isSensor",
"=",
"def",
".",
"isSensor",
";",
"this",
".",
"m_filterGroupIndex",
"=",
"def",
".",
"filterGroupIndex",
";",
"this",
".",
"m_filterCategoryBits",
"=",
"def",
".",
"filterCategoryBits",
";",
"this",
".",
"m_filterMaskBits",
"=",
"def",
".",
"filterMaskBits",
";",
"// TODO validate shape",
"this",
".",
"m_shape",
"=",
"shape",
";",
"//.clone();",
"this",
".",
"m_next",
"=",
"null",
";",
"this",
".",
"m_proxies",
"=",
"[",
"]",
";",
"this",
".",
"m_proxyCount",
"=",
"0",
";",
"var",
"childCount",
"=",
"this",
".",
"m_shape",
".",
"getChildCount",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"childCount",
";",
"++",
"i",
")",
"{",
"this",
".",
"m_proxies",
"[",
"i",
"]",
"=",
"new",
"FixtureProxy",
"(",
"this",
",",
"i",
")",
";",
"}",
"this",
".",
"m_userData",
"=",
"def",
".",
"userData",
";",
"}"
] |
A fixture is used to attach a shape to a body for collision detection. A
fixture inherits its transform from its parent. Fixtures hold additional
non-geometric data such as friction, collision filters, etc. Fixtures are
created via Body.createFixture.
@param {Body} body
@param {Shape|FixtureDef} shape Shape of fixture definition.
@param {FixtureDef|number} def Fixture definition or number.
|
[
"A",
"fixture",
"is",
"used",
"to",
"attach",
"a",
"shape",
"to",
"a",
"body",
"for",
"collision",
"detection",
".",
"A",
"fixture",
"inherits",
"its",
"transform",
"from",
"its",
"parent",
".",
"Fixtures",
"hold",
"additional",
"non",
"-",
"geometric",
"data",
"such",
"as",
"friction",
"collision",
"filters",
"etc",
".",
"Fixtures",
"are",
"created",
"via",
"Body",
".",
"createFixture",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/Fixture.js#L87-L123
|
11,179
|
shakiba/planck.js
|
lib/shape/CollideEdgePolygon.js
|
ReferenceFace
|
function ReferenceFace() {
this.i1, this.i2; // int
this.v1, this.v2; // v
this.normal = Vec2.zero();
this.sideNormal1 = Vec2.zero();
this.sideOffset1; // float
this.sideNormal2 = Vec2.zero();
this.sideOffset2; // float
}
|
javascript
|
function ReferenceFace() {
this.i1, this.i2; // int
this.v1, this.v2; // v
this.normal = Vec2.zero();
this.sideNormal1 = Vec2.zero();
this.sideOffset1; // float
this.sideNormal2 = Vec2.zero();
this.sideOffset2; // float
}
|
[
"function",
"ReferenceFace",
"(",
")",
"{",
"this",
".",
"i1",
",",
"this",
".",
"i2",
";",
"// int",
"this",
".",
"v1",
",",
"this",
".",
"v2",
";",
"// v",
"this",
".",
"normal",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"sideNormal1",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"sideOffset1",
";",
"// float",
"this",
".",
"sideNormal2",
"=",
"Vec2",
".",
"zero",
"(",
")",
";",
"this",
".",
"sideOffset2",
";",
"// float",
"}"
] |
Reference face used for clipping
|
[
"Reference",
"face",
"used",
"for",
"clipping"
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/shape/CollideEdgePolygon.js#L83-L91
|
11,180
|
shakiba/planck.js
|
lib/collision/DynamicTree.js
|
TreeNode
|
function TreeNode(id) {
this.id = id;
this.aabb = new AABB();
this.userData = null;
this.parent = null;
this.child1 = null;
this.child2 = null;
this.height = -1;
this.toString = function() {
return this.id + ": " + this.userData;
}
}
|
javascript
|
function TreeNode(id) {
this.id = id;
this.aabb = new AABB();
this.userData = null;
this.parent = null;
this.child1 = null;
this.child2 = null;
this.height = -1;
this.toString = function() {
return this.id + ": " + this.userData;
}
}
|
[
"function",
"TreeNode",
"(",
"id",
")",
"{",
"this",
".",
"id",
"=",
"id",
";",
"this",
".",
"aabb",
"=",
"new",
"AABB",
"(",
")",
";",
"this",
".",
"userData",
"=",
"null",
";",
"this",
".",
"parent",
"=",
"null",
";",
"this",
".",
"child1",
"=",
"null",
";",
"this",
".",
"child2",
"=",
"null",
";",
"this",
".",
"height",
"=",
"-",
"1",
";",
"this",
".",
"toString",
"=",
"function",
"(",
")",
"{",
"return",
"this",
".",
"id",
"+",
"\": \"",
"+",
"this",
".",
"userData",
";",
"}",
"}"
] |
A node in the dynamic tree. The client does not interact with this directly.
@prop {AABB} aabb Enlarged AABB
@prop {integer} height 0: leaf, -1: free node
|
[
"A",
"node",
"in",
"the",
"dynamic",
"tree",
".",
"The",
"client",
"does",
"not",
"interact",
"with",
"this",
"directly",
"."
] |
59c32eb8821a63b867b0bef4ccd066a0a4146a9b
|
https://github.com/shakiba/planck.js/blob/59c32eb8821a63b867b0bef4ccd066a0a4146a9b/lib/collision/DynamicTree.js#L38-L50
|
11,181
|
emmetio/emmet
|
lib/resolver/tagName.js
|
function(name) {
name = (name || '').toLowerCase();
if (name in elementMap)
return this.getMapping(name);
if (this.isInlineLevel(name))
return 'span';
return 'div';
}
|
javascript
|
function(name) {
name = (name || '').toLowerCase();
if (name in elementMap)
return this.getMapping(name);
if (this.isInlineLevel(name))
return 'span';
return 'div';
}
|
[
"function",
"(",
"name",
")",
"{",
"name",
"=",
"(",
"name",
"||",
"''",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"name",
"in",
"elementMap",
")",
"return",
"this",
".",
"getMapping",
"(",
"name",
")",
";",
"if",
"(",
"this",
".",
"isInlineLevel",
"(",
"name",
")",
")",
"return",
"'span'",
";",
"return",
"'div'",
";",
"}"
] |
Returns best matched child element name for passed parent's
tag name
@param {String} name
@returns {String}
@memberOf tagName
|
[
"Returns",
"best",
"matched",
"child",
"element",
"name",
"for",
"passed",
"parent",
"s",
"tag",
"name"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/tagName.js#L48-L58
|
|
11,182
|
emmetio/emmet
|
lib/resolver/tagName.js
|
function(name, collection) {
if (!elementTypes[collection])
elementTypes[collection] = [];
var col = this.getCollection(collection);
if (!~col.indexOf(name)) {
col.push(name);
}
}
|
javascript
|
function(name, collection) {
if (!elementTypes[collection])
elementTypes[collection] = [];
var col = this.getCollection(collection);
if (!~col.indexOf(name)) {
col.push(name);
}
}
|
[
"function",
"(",
"name",
",",
"collection",
")",
"{",
"if",
"(",
"!",
"elementTypes",
"[",
"collection",
"]",
")",
"elementTypes",
"[",
"collection",
"]",
"=",
"[",
"]",
";",
"var",
"col",
"=",
"this",
".",
"getCollection",
"(",
"collection",
")",
";",
"if",
"(",
"!",
"~",
"col",
".",
"indexOf",
"(",
"name",
")",
")",
"{",
"col",
".",
"push",
"(",
"name",
")",
";",
"}",
"}"
] |
Adds new element into collection
@param {String} name Element name
@param {String} collection Collection name
|
[
"Adds",
"new",
"element",
"into",
"collection"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/tagName.js#L129-L137
|
|
11,183
|
emmetio/emmet
|
lib/resolver/tagName.js
|
function(name, collection) {
if (collection in elementTypes) {
elementTypes[collection] = utils.without(this.getCollection(collection), name);
}
}
|
javascript
|
function(name, collection) {
if (collection in elementTypes) {
elementTypes[collection] = utils.without(this.getCollection(collection), name);
}
}
|
[
"function",
"(",
"name",
",",
"collection",
")",
"{",
"if",
"(",
"collection",
"in",
"elementTypes",
")",
"{",
"elementTypes",
"[",
"collection",
"]",
"=",
"utils",
".",
"without",
"(",
"this",
".",
"getCollection",
"(",
"collection",
")",
",",
"name",
")",
";",
"}",
"}"
] |
Removes element name from specified collection
@param {String} name Element name
@param {String} collection Collection name
@returns
|
[
"Removes",
"element",
"name",
"from",
"specified",
"collection"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/tagName.js#L145-L149
|
|
11,184
|
emmetio/emmet
|
lib/filter/comment.js
|
addComments
|
function addComments(node, templateBefore, templateAfter) {
// check if comments should be added
var trigger = prefs.get('filter.commentTrigger');
if (trigger != '*') {
var shouldAdd = utils.find(trigger.split(','), function(name) {
return !!node.attribute(utils.trim(name));
});
if (!shouldAdd) {
return;
}
}
var ctx = {
node: node,
name: node.name(),
padding: node.parent ? node.parent.padding : '',
attr: function(name, before, after) {
var attr = node.attribute(name);
if (attr) {
return (before || '') + attr + (after || '');
}
return '';
}
};
var nodeBefore = templateBefore ? templateBefore(ctx) : '';
var nodeAfter = templateAfter ? templateAfter(ctx) : '';
node.start = node.start.replace(/</, nodeBefore + '<');
node.end = node.end.replace(/>/, '>' + nodeAfter);
}
|
javascript
|
function addComments(node, templateBefore, templateAfter) {
// check if comments should be added
var trigger = prefs.get('filter.commentTrigger');
if (trigger != '*') {
var shouldAdd = utils.find(trigger.split(','), function(name) {
return !!node.attribute(utils.trim(name));
});
if (!shouldAdd) {
return;
}
}
var ctx = {
node: node,
name: node.name(),
padding: node.parent ? node.parent.padding : '',
attr: function(name, before, after) {
var attr = node.attribute(name);
if (attr) {
return (before || '') + attr + (after || '');
}
return '';
}
};
var nodeBefore = templateBefore ? templateBefore(ctx) : '';
var nodeAfter = templateAfter ? templateAfter(ctx) : '';
node.start = node.start.replace(/</, nodeBefore + '<');
node.end = node.end.replace(/>/, '>' + nodeAfter);
}
|
[
"function",
"addComments",
"(",
"node",
",",
"templateBefore",
",",
"templateAfter",
")",
"{",
"// check if comments should be added",
"var",
"trigger",
"=",
"prefs",
".",
"get",
"(",
"'filter.commentTrigger'",
")",
";",
"if",
"(",
"trigger",
"!=",
"'*'",
")",
"{",
"var",
"shouldAdd",
"=",
"utils",
".",
"find",
"(",
"trigger",
".",
"split",
"(",
"','",
")",
",",
"function",
"(",
"name",
")",
"{",
"return",
"!",
"!",
"node",
".",
"attribute",
"(",
"utils",
".",
"trim",
"(",
"name",
")",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"shouldAdd",
")",
"{",
"return",
";",
"}",
"}",
"var",
"ctx",
"=",
"{",
"node",
":",
"node",
",",
"name",
":",
"node",
".",
"name",
"(",
")",
",",
"padding",
":",
"node",
".",
"parent",
"?",
"node",
".",
"parent",
".",
"padding",
":",
"''",
",",
"attr",
":",
"function",
"(",
"name",
",",
"before",
",",
"after",
")",
"{",
"var",
"attr",
"=",
"node",
".",
"attribute",
"(",
"name",
")",
";",
"if",
"(",
"attr",
")",
"{",
"return",
"(",
"before",
"||",
"''",
")",
"+",
"attr",
"+",
"(",
"after",
"||",
"''",
")",
";",
"}",
"return",
"''",
";",
"}",
"}",
";",
"var",
"nodeBefore",
"=",
"templateBefore",
"?",
"templateBefore",
"(",
"ctx",
")",
":",
"''",
";",
"var",
"nodeAfter",
"=",
"templateAfter",
"?",
"templateAfter",
"(",
"ctx",
")",
":",
"''",
";",
"node",
".",
"start",
"=",
"node",
".",
"start",
".",
"replace",
"(",
"/",
"<",
"/",
",",
"nodeBefore",
"+",
"'<'",
")",
";",
"node",
".",
"end",
"=",
"node",
".",
"end",
".",
"replace",
"(",
"/",
">",
"/",
",",
"'>'",
"+",
"nodeAfter",
")",
";",
"}"
] |
Add comments to tag
@param {AbbreviationNode} node
|
[
"Add",
"comments",
"to",
"tag"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/filter/comment.js#L56-L88
|
11,185
|
emmetio/emmet
|
lib/parser/processor/tagName.js
|
resolveNodeNames
|
function resolveNodeNames(tree) {
tree.children.forEach(function(node) {
if (node.hasImplicitName() || node.data('forceNameResolving')) {
node._name = tagName.resolve(node.parent.name());
node.data('nameResolved', true);
}
resolveNodeNames(node);
});
return tree;
}
|
javascript
|
function resolveNodeNames(tree) {
tree.children.forEach(function(node) {
if (node.hasImplicitName() || node.data('forceNameResolving')) {
node._name = tagName.resolve(node.parent.name());
node.data('nameResolved', true);
}
resolveNodeNames(node);
});
return tree;
}
|
[
"function",
"resolveNodeNames",
"(",
"tree",
")",
"{",
"tree",
".",
"children",
".",
"forEach",
"(",
"function",
"(",
"node",
")",
"{",
"if",
"(",
"node",
".",
"hasImplicitName",
"(",
")",
"||",
"node",
".",
"data",
"(",
"'forceNameResolving'",
")",
")",
"{",
"node",
".",
"_name",
"=",
"tagName",
".",
"resolve",
"(",
"node",
".",
"parent",
".",
"name",
"(",
")",
")",
";",
"node",
".",
"data",
"(",
"'nameResolved'",
",",
"true",
")",
";",
"}",
"resolveNodeNames",
"(",
"node",
")",
";",
"}",
")",
";",
"return",
"tree",
";",
"}"
] |
Resolves implicit node names in parsed tree
@param {AbbreviationNode} tree
|
[
"Resolves",
"implicit",
"node",
"names",
"in",
"parsed",
"tree"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/parser/processor/tagName.js#L17-L27
|
11,186
|
emmetio/emmet
|
lib/resolver/css.js
|
isSingleProperty
|
function isSingleProperty(snippet) {
snippet = utils.trim(snippet);
// check if it doesn't contain a comment and a newline
if (/\/\*|\n|\r/.test(snippet)) {
return false;
}
// check if it's a valid snippet definition
if (!/^[a-z0-9\-]+\s*\:/i.test(snippet)) {
return false;
}
return snippet.replace(/\$\{.+?\}/g, '').split(':').length == 2;
}
|
javascript
|
function isSingleProperty(snippet) {
snippet = utils.trim(snippet);
// check if it doesn't contain a comment and a newline
if (/\/\*|\n|\r/.test(snippet)) {
return false;
}
// check if it's a valid snippet definition
if (!/^[a-z0-9\-]+\s*\:/i.test(snippet)) {
return false;
}
return snippet.replace(/\$\{.+?\}/g, '').split(':').length == 2;
}
|
[
"function",
"isSingleProperty",
"(",
"snippet",
")",
"{",
"snippet",
"=",
"utils",
".",
"trim",
"(",
"snippet",
")",
";",
"// check if it doesn't contain a comment and a newline",
"if",
"(",
"/",
"\\/\\*|\\n|\\r",
"/",
".",
"test",
"(",
"snippet",
")",
")",
"{",
"return",
"false",
";",
"}",
"// check if it's a valid snippet definition",
"if",
"(",
"!",
"/",
"^[a-z0-9\\-]+\\s*\\:",
"/",
"i",
".",
"test",
"(",
"snippet",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"snippet",
".",
"replace",
"(",
"/",
"\\$\\{.+?\\}",
"/",
"g",
",",
"''",
")",
".",
"split",
"(",
"':'",
")",
".",
"length",
"==",
"2",
";",
"}"
] |
Check if provided snippet contains only one CSS property and value.
@param {String} snippet
@returns {Boolean}
|
[
"Check",
"if",
"provided",
"snippet",
"contains",
"only",
"one",
"CSS",
"property",
"and",
"value",
"."
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L222-L236
|
11,187
|
emmetio/emmet
|
lib/resolver/css.js
|
normalizeValue
|
function normalizeValue(value) {
if (value.charAt(0) == '-' && !/^\-[\.\d]/.test(value)) {
value = value.replace(/^\-+/, '');
}
var ch = value.charAt(0);
if (ch == '#') {
return normalizeHexColor(value);
}
if (ch == '$') {
return utils.escapeText(value);
}
return getKeyword(value);
}
|
javascript
|
function normalizeValue(value) {
if (value.charAt(0) == '-' && !/^\-[\.\d]/.test(value)) {
value = value.replace(/^\-+/, '');
}
var ch = value.charAt(0);
if (ch == '#') {
return normalizeHexColor(value);
}
if (ch == '$') {
return utils.escapeText(value);
}
return getKeyword(value);
}
|
[
"function",
"normalizeValue",
"(",
"value",
")",
"{",
"if",
"(",
"value",
".",
"charAt",
"(",
"0",
")",
"==",
"'-'",
"&&",
"!",
"/",
"^\\-[\\.\\d]",
"/",
".",
"test",
"(",
"value",
")",
")",
"{",
"value",
"=",
"value",
".",
"replace",
"(",
"/",
"^\\-+",
"/",
",",
"''",
")",
";",
"}",
"var",
"ch",
"=",
"value",
".",
"charAt",
"(",
"0",
")",
";",
"if",
"(",
"ch",
"==",
"'#'",
")",
"{",
"return",
"normalizeHexColor",
"(",
"value",
")",
";",
"}",
"if",
"(",
"ch",
"==",
"'$'",
")",
"{",
"return",
"utils",
".",
"escapeText",
"(",
"value",
")",
";",
"}",
"return",
"getKeyword",
"(",
"value",
")",
";",
"}"
] |
Normalizes abbreviated value to final CSS one
@param {String} value
@returns {String}
|
[
"Normalizes",
"abbreviated",
"value",
"to",
"final",
"CSS",
"one"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L243-L258
|
11,188
|
emmetio/emmet
|
lib/resolver/css.js
|
toRgba
|
function toRgba(color, opacity) {
var r = parseInt(color.substr(0, 2), 16);
var g = parseInt(color.substr(2, 2), 16);
var b = parseInt(color.substr(4, 2), 16);
return 'rgba(' + [r, g, b, opacity].join(', ') + ')';
}
|
javascript
|
function toRgba(color, opacity) {
var r = parseInt(color.substr(0, 2), 16);
var g = parseInt(color.substr(2, 2), 16);
var b = parseInt(color.substr(4, 2), 16);
return 'rgba(' + [r, g, b, opacity].join(', ') + ')';
}
|
[
"function",
"toRgba",
"(",
"color",
",",
"opacity",
")",
"{",
"var",
"r",
"=",
"parseInt",
"(",
"color",
".",
"substr",
"(",
"0",
",",
"2",
")",
",",
"16",
")",
";",
"var",
"g",
"=",
"parseInt",
"(",
"color",
".",
"substr",
"(",
"2",
",",
"2",
")",
",",
"16",
")",
";",
"var",
"b",
"=",
"parseInt",
"(",
"color",
".",
"substr",
"(",
"4",
",",
"2",
")",
",",
"16",
")",
";",
"return",
"'rgba('",
"+",
"[",
"r",
",",
"g",
",",
"b",
",",
"opacity",
"]",
".",
"join",
"(",
"', '",
")",
"+",
"')'",
";",
"}"
] |
Transforms HEX color definition into RGBA one
@param {String} color HEX color, 6 characters
@param {String} opacity Opacity value
@return {String}
|
[
"Transforms",
"HEX",
"color",
"definition",
"into",
"RGBA",
"one"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L325-L331
|
11,189
|
emmetio/emmet
|
lib/resolver/css.js
|
hasPrefix
|
function hasPrefix(property, prefix) {
var info = vendorPrefixes[prefix];
if (!info)
info = utils.find(vendorPrefixes, function(data) {
return data.prefix == prefix;
});
return info && info.supports(property);
}
|
javascript
|
function hasPrefix(property, prefix) {
var info = vendorPrefixes[prefix];
if (!info)
info = utils.find(vendorPrefixes, function(data) {
return data.prefix == prefix;
});
return info && info.supports(property);
}
|
[
"function",
"hasPrefix",
"(",
"property",
",",
"prefix",
")",
"{",
"var",
"info",
"=",
"vendorPrefixes",
"[",
"prefix",
"]",
";",
"if",
"(",
"!",
"info",
")",
"info",
"=",
"utils",
".",
"find",
"(",
"vendorPrefixes",
",",
"function",
"(",
"data",
")",
"{",
"return",
"data",
".",
"prefix",
"==",
"prefix",
";",
"}",
")",
";",
"return",
"info",
"&&",
"info",
".",
"supports",
"(",
"property",
")",
";",
"}"
] |
Check if passed CSS property support specified vendor prefix
@param {String} property
@param {String} prefix
|
[
"Check",
"if",
"passed",
"CSS",
"property",
"support",
"specified",
"vendor",
"prefix"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L352-L361
|
11,190
|
emmetio/emmet
|
lib/resolver/css.js
|
findVendorPrefixes
|
function findVendorPrefixes(property) {
var prefixes = ciu.resolvePrefixes(property);
if (!prefixes) {
// Can I Use database is disabled or prefixes are not
// available for this property
prefixes = [];
Object.keys(vendorPrefixes).forEach(function(key) {
if (hasPrefix(property, key)) {
prefixes.push(vendorPrefixes[key].prefix);
}
});
if (!prefixes.length) {
prefixes = null;
}
}
return prefixes;
}
|
javascript
|
function findVendorPrefixes(property) {
var prefixes = ciu.resolvePrefixes(property);
if (!prefixes) {
// Can I Use database is disabled or prefixes are not
// available for this property
prefixes = [];
Object.keys(vendorPrefixes).forEach(function(key) {
if (hasPrefix(property, key)) {
prefixes.push(vendorPrefixes[key].prefix);
}
});
if (!prefixes.length) {
prefixes = null;
}
}
return prefixes;
}
|
[
"function",
"findVendorPrefixes",
"(",
"property",
")",
"{",
"var",
"prefixes",
"=",
"ciu",
".",
"resolvePrefixes",
"(",
"property",
")",
";",
"if",
"(",
"!",
"prefixes",
")",
"{",
"// Can I Use database is disabled or prefixes are not",
"// available for this property",
"prefixes",
"=",
"[",
"]",
";",
"Object",
".",
"keys",
"(",
"vendorPrefixes",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"hasPrefix",
"(",
"property",
",",
"key",
")",
")",
"{",
"prefixes",
".",
"push",
"(",
"vendorPrefixes",
"[",
"key",
"]",
".",
"prefix",
")",
";",
"}",
"}",
")",
";",
"if",
"(",
"!",
"prefixes",
".",
"length",
")",
"{",
"prefixes",
"=",
"null",
";",
"}",
"}",
"return",
"prefixes",
";",
"}"
] |
Finds available vendor prefixes for given CSS property.
Search is performed within Can I Use database and internal
property list
@param {String} property CSS property name
@return {Array} Array of resolved prefixes or null if
prefixes are not available for this property at all.
Empty array means prefixes are not available for current
user-define era
|
[
"Finds",
"available",
"vendor",
"prefixes",
"for",
"given",
"CSS",
"property",
".",
"Search",
"is",
"performed",
"within",
"Can",
"I",
"Use",
"database",
"and",
"internal",
"property",
"list"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L373-L391
|
11,191
|
emmetio/emmet
|
lib/resolver/css.js
|
findInternalPrefixes
|
function findInternalPrefixes(property, noAutofill) {
var result = [];
var prefixes = findVendorPrefixes(property);
if (prefixes) {
var prefixMap = {};
Object.keys(vendorPrefixes).forEach(function(key) {
prefixMap[vendorPrefixes[key].prefix] = key;
});
result = prefixes.map(function(prefix) {
return prefixMap[prefix];
});
}
if (!result.length && !noAutofill) {
// add all non-obsolete prefixes
Object.keys(vendorPrefixes).forEach(function(prefix) {
if (!vendorPrefixes[prefix].obsolete) {
result.push(prefix);
}
});
}
return result;
}
|
javascript
|
function findInternalPrefixes(property, noAutofill) {
var result = [];
var prefixes = findVendorPrefixes(property);
if (prefixes) {
var prefixMap = {};
Object.keys(vendorPrefixes).forEach(function(key) {
prefixMap[vendorPrefixes[key].prefix] = key;
});
result = prefixes.map(function(prefix) {
return prefixMap[prefix];
});
}
if (!result.length && !noAutofill) {
// add all non-obsolete prefixes
Object.keys(vendorPrefixes).forEach(function(prefix) {
if (!vendorPrefixes[prefix].obsolete) {
result.push(prefix);
}
});
}
return result;
}
|
[
"function",
"findInternalPrefixes",
"(",
"property",
",",
"noAutofill",
")",
"{",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"prefixes",
"=",
"findVendorPrefixes",
"(",
"property",
")",
";",
"if",
"(",
"prefixes",
")",
"{",
"var",
"prefixMap",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"vendorPrefixes",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"prefixMap",
"[",
"vendorPrefixes",
"[",
"key",
"]",
".",
"prefix",
"]",
"=",
"key",
";",
"}",
")",
";",
"result",
"=",
"prefixes",
".",
"map",
"(",
"function",
"(",
"prefix",
")",
"{",
"return",
"prefixMap",
"[",
"prefix",
"]",
";",
"}",
")",
";",
"}",
"if",
"(",
"!",
"result",
".",
"length",
"&&",
"!",
"noAutofill",
")",
"{",
"// add all non-obsolete prefixes",
"Object",
".",
"keys",
"(",
"vendorPrefixes",
")",
".",
"forEach",
"(",
"function",
"(",
"prefix",
")",
"{",
"if",
"(",
"!",
"vendorPrefixes",
"[",
"prefix",
"]",
".",
"obsolete",
")",
"{",
"result",
".",
"push",
"(",
"prefix",
")",
";",
"}",
"}",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Search for a list of supported prefixes for CSS property. This list
is used to generate all-prefixed snippet
@param {String} property CSS property name
@returns {Array}
|
[
"Search",
"for",
"a",
"list",
"of",
"supported",
"prefixes",
"for",
"CSS",
"property",
".",
"This",
"list",
"is",
"used",
"to",
"generate",
"all",
"-",
"prefixed",
"snippet"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L399-L424
|
11,192
|
emmetio/emmet
|
lib/resolver/css.js
|
formatProperty
|
function formatProperty(property, syntax) {
var ix = property.indexOf(':');
property = property.substring(0, ix).replace(/\s+$/, '')
+ getSyntaxPreference('valueSeparator', syntax)
+ utils.trim(property.substring(ix + 1));
return property.replace(/\s*;\s*$/, getSyntaxPreference('propertyEnd', syntax));
}
|
javascript
|
function formatProperty(property, syntax) {
var ix = property.indexOf(':');
property = property.substring(0, ix).replace(/\s+$/, '')
+ getSyntaxPreference('valueSeparator', syntax)
+ utils.trim(property.substring(ix + 1));
return property.replace(/\s*;\s*$/, getSyntaxPreference('propertyEnd', syntax));
}
|
[
"function",
"formatProperty",
"(",
"property",
",",
"syntax",
")",
"{",
"var",
"ix",
"=",
"property",
".",
"indexOf",
"(",
"':'",
")",
";",
"property",
"=",
"property",
".",
"substring",
"(",
"0",
",",
"ix",
")",
".",
"replace",
"(",
"/",
"\\s+$",
"/",
",",
"''",
")",
"+",
"getSyntaxPreference",
"(",
"'valueSeparator'",
",",
"syntax",
")",
"+",
"utils",
".",
"trim",
"(",
"property",
".",
"substring",
"(",
"ix",
"+",
"1",
")",
")",
";",
"return",
"property",
".",
"replace",
"(",
"/",
"\\s*;\\s*$",
"/",
",",
"getSyntaxPreference",
"(",
"'propertyEnd'",
",",
"syntax",
")",
")",
";",
"}"
] |
Format CSS property according to current syntax dialect
@param {String} property
@param {String} syntax
@returns {String}
|
[
"Format",
"CSS",
"property",
"according",
"to",
"current",
"syntax",
"dialect"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L456-L463
|
11,193
|
emmetio/emmet
|
lib/resolver/css.js
|
resolvePrefixedValues
|
function resolvePrefixedValues(snippetObj, isImportant, syntax) {
var prefixes = [];
var lookup = {};
var parts = cssEditTree.findParts(snippetObj.value);
parts.reverse();
parts.forEach(function(p) {
var partValue = p.substring(snippetObj.value);
(findVendorPrefixes(partValue) || []).forEach(function(prefix) {
if (!lookup[prefix]) {
lookup[prefix] = snippetObj.value;
prefixes.push(prefix);
}
lookup[prefix] = utils.replaceSubstring(lookup[prefix], '-' + prefix + '-' + partValue, p);
});
});
return prefixes.map(function(prefix) {
return transformSnippet(snippetObj.name + ':' + lookup[prefix], isImportant, syntax);
});
}
|
javascript
|
function resolvePrefixedValues(snippetObj, isImportant, syntax) {
var prefixes = [];
var lookup = {};
var parts = cssEditTree.findParts(snippetObj.value);
parts.reverse();
parts.forEach(function(p) {
var partValue = p.substring(snippetObj.value);
(findVendorPrefixes(partValue) || []).forEach(function(prefix) {
if (!lookup[prefix]) {
lookup[prefix] = snippetObj.value;
prefixes.push(prefix);
}
lookup[prefix] = utils.replaceSubstring(lookup[prefix], '-' + prefix + '-' + partValue, p);
});
});
return prefixes.map(function(prefix) {
return transformSnippet(snippetObj.name + ':' + lookup[prefix], isImportant, syntax);
});
}
|
[
"function",
"resolvePrefixedValues",
"(",
"snippetObj",
",",
"isImportant",
",",
"syntax",
")",
"{",
"var",
"prefixes",
"=",
"[",
"]",
";",
"var",
"lookup",
"=",
"{",
"}",
";",
"var",
"parts",
"=",
"cssEditTree",
".",
"findParts",
"(",
"snippetObj",
".",
"value",
")",
";",
"parts",
".",
"reverse",
"(",
")",
";",
"parts",
".",
"forEach",
"(",
"function",
"(",
"p",
")",
"{",
"var",
"partValue",
"=",
"p",
".",
"substring",
"(",
"snippetObj",
".",
"value",
")",
";",
"(",
"findVendorPrefixes",
"(",
"partValue",
")",
"||",
"[",
"]",
")",
".",
"forEach",
"(",
"function",
"(",
"prefix",
")",
"{",
"if",
"(",
"!",
"lookup",
"[",
"prefix",
"]",
")",
"{",
"lookup",
"[",
"prefix",
"]",
"=",
"snippetObj",
".",
"value",
";",
"prefixes",
".",
"push",
"(",
"prefix",
")",
";",
"}",
"lookup",
"[",
"prefix",
"]",
"=",
"utils",
".",
"replaceSubstring",
"(",
"lookup",
"[",
"prefix",
"]",
",",
"'-'",
"+",
"prefix",
"+",
"'-'",
"+",
"partValue",
",",
"p",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
"prefixes",
".",
"map",
"(",
"function",
"(",
"prefix",
")",
"{",
"return",
"transformSnippet",
"(",
"snippetObj",
".",
"name",
"+",
"':'",
"+",
"lookup",
"[",
"prefix",
"]",
",",
"isImportant",
",",
"syntax",
")",
";",
"}",
")",
";",
"}"
] |
Tries to produce properties with vendor-prefixed value
@param {Object} snippetObj Parsed snippet object
@return {Array} Array of properties with prefixed values
|
[
"Tries",
"to",
"produce",
"properties",
"with",
"vendor",
"-",
"prefixed",
"value"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L516-L537
|
11,194
|
emmetio/emmet
|
lib/resolver/css.js
|
function(abbr) {
if (abbr.charAt(0) != '-') {
return {
property: abbr,
prefixes: null
};
}
// abbreviation may either contain sequence of one-character prefixes
// or just dash, meaning that user wants to produce all possible
// prefixed properties
var i = 1, il = abbr.length, ch;
var prefixes = [];
while (i < il) {
ch = abbr.charAt(i);
if (ch == '-') {
// end-sequence character found, stop searching
i++;
break;
}
if (ch in vendorPrefixes) {
prefixes.push(ch);
} else {
// no prefix found, meaning user want to produce all
// vendor-prefixed properties
prefixes.length = 0;
i = 1;
break;
}
i++;
}
// reached end of abbreviation and no property name left
if (i == il -1) {
i = 1;
prefixes.length = 1;
}
return {
property: abbr.substring(i),
prefixes: prefixes.length ? prefixes : 'all'
};
}
|
javascript
|
function(abbr) {
if (abbr.charAt(0) != '-') {
return {
property: abbr,
prefixes: null
};
}
// abbreviation may either contain sequence of one-character prefixes
// or just dash, meaning that user wants to produce all possible
// prefixed properties
var i = 1, il = abbr.length, ch;
var prefixes = [];
while (i < il) {
ch = abbr.charAt(i);
if (ch == '-') {
// end-sequence character found, stop searching
i++;
break;
}
if (ch in vendorPrefixes) {
prefixes.push(ch);
} else {
// no prefix found, meaning user want to produce all
// vendor-prefixed properties
prefixes.length = 0;
i = 1;
break;
}
i++;
}
// reached end of abbreviation and no property name left
if (i == il -1) {
i = 1;
prefixes.length = 1;
}
return {
property: abbr.substring(i),
prefixes: prefixes.length ? prefixes : 'all'
};
}
|
[
"function",
"(",
"abbr",
")",
"{",
"if",
"(",
"abbr",
".",
"charAt",
"(",
"0",
")",
"!=",
"'-'",
")",
"{",
"return",
"{",
"property",
":",
"abbr",
",",
"prefixes",
":",
"null",
"}",
";",
"}",
"// abbreviation may either contain sequence of one-character prefixes",
"// or just dash, meaning that user wants to produce all possible",
"// prefixed properties",
"var",
"i",
"=",
"1",
",",
"il",
"=",
"abbr",
".",
"length",
",",
"ch",
";",
"var",
"prefixes",
"=",
"[",
"]",
";",
"while",
"(",
"i",
"<",
"il",
")",
"{",
"ch",
"=",
"abbr",
".",
"charAt",
"(",
"i",
")",
";",
"if",
"(",
"ch",
"==",
"'-'",
")",
"{",
"// end-sequence character found, stop searching",
"i",
"++",
";",
"break",
";",
"}",
"if",
"(",
"ch",
"in",
"vendorPrefixes",
")",
"{",
"prefixes",
".",
"push",
"(",
"ch",
")",
";",
"}",
"else",
"{",
"// no prefix found, meaning user want to produce all",
"// vendor-prefixed properties",
"prefixes",
".",
"length",
"=",
"0",
";",
"i",
"=",
"1",
";",
"break",
";",
"}",
"i",
"++",
";",
"}",
"// reached end of abbreviation and no property name left",
"if",
"(",
"i",
"==",
"il",
"-",
"1",
")",
"{",
"i",
"=",
"1",
";",
"prefixes",
".",
"length",
"=",
"1",
";",
"}",
"return",
"{",
"property",
":",
"abbr",
".",
"substring",
"(",
"i",
")",
",",
"prefixes",
":",
"prefixes",
".",
"length",
"?",
"prefixes",
":",
"'all'",
"}",
";",
"}"
] |
Extract vendor prefixes from abbreviation
@param {String} abbr
@returns {Object} Object containing array of prefixes and clean
abbreviation name
|
[
"Extract",
"vendor",
"prefixes",
"from",
"abbreviation"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L628-L673
|
|
11,195
|
emmetio/emmet
|
lib/resolver/css.js
|
function(abbr, syntax) {
syntax = syntax || 'css';
var i = 0, il = abbr.length, value = '', ch;
while (i < il) {
ch = abbr.charAt(i);
if (isNumeric(ch) || ch == '#' || ch == '$' || (ch == '-' && isNumeric(abbr.charAt(i + 1)))) {
value = abbr.substring(i);
break;
}
i++;
}
// try to find keywords in abbreviation
var property = abbr.substring(0, abbr.length - value.length);
var keywords = [];
// try to extract some commonly-used properties
while (~property.indexOf('-') && !resources.findSnippet(syntax, property)) {
var parts = property.split('-');
var lastPart = parts.pop();
if (!isValidKeyword(lastPart)) {
break;
}
keywords.unshift(lastPart);
property = parts.join('-');
}
return keywords.join('-') + value;
}
|
javascript
|
function(abbr, syntax) {
syntax = syntax || 'css';
var i = 0, il = abbr.length, value = '', ch;
while (i < il) {
ch = abbr.charAt(i);
if (isNumeric(ch) || ch == '#' || ch == '$' || (ch == '-' && isNumeric(abbr.charAt(i + 1)))) {
value = abbr.substring(i);
break;
}
i++;
}
// try to find keywords in abbreviation
var property = abbr.substring(0, abbr.length - value.length);
var keywords = [];
// try to extract some commonly-used properties
while (~property.indexOf('-') && !resources.findSnippet(syntax, property)) {
var parts = property.split('-');
var lastPart = parts.pop();
if (!isValidKeyword(lastPart)) {
break;
}
keywords.unshift(lastPart);
property = parts.join('-');
}
return keywords.join('-') + value;
}
|
[
"function",
"(",
"abbr",
",",
"syntax",
")",
"{",
"syntax",
"=",
"syntax",
"||",
"'css'",
";",
"var",
"i",
"=",
"0",
",",
"il",
"=",
"abbr",
".",
"length",
",",
"value",
"=",
"''",
",",
"ch",
";",
"while",
"(",
"i",
"<",
"il",
")",
"{",
"ch",
"=",
"abbr",
".",
"charAt",
"(",
"i",
")",
";",
"if",
"(",
"isNumeric",
"(",
"ch",
")",
"||",
"ch",
"==",
"'#'",
"||",
"ch",
"==",
"'$'",
"||",
"(",
"ch",
"==",
"'-'",
"&&",
"isNumeric",
"(",
"abbr",
".",
"charAt",
"(",
"i",
"+",
"1",
")",
")",
")",
")",
"{",
"value",
"=",
"abbr",
".",
"substring",
"(",
"i",
")",
";",
"break",
";",
"}",
"i",
"++",
";",
"}",
"// try to find keywords in abbreviation",
"var",
"property",
"=",
"abbr",
".",
"substring",
"(",
"0",
",",
"abbr",
".",
"length",
"-",
"value",
".",
"length",
")",
";",
"var",
"keywords",
"=",
"[",
"]",
";",
"// try to extract some commonly-used properties",
"while",
"(",
"~",
"property",
".",
"indexOf",
"(",
"'-'",
")",
"&&",
"!",
"resources",
".",
"findSnippet",
"(",
"syntax",
",",
"property",
")",
")",
"{",
"var",
"parts",
"=",
"property",
".",
"split",
"(",
"'-'",
")",
";",
"var",
"lastPart",
"=",
"parts",
".",
"pop",
"(",
")",
";",
"if",
"(",
"!",
"isValidKeyword",
"(",
"lastPart",
")",
")",
"{",
"break",
";",
"}",
"keywords",
".",
"unshift",
"(",
"lastPart",
")",
";",
"property",
"=",
"parts",
".",
"join",
"(",
"'-'",
")",
";",
"}",
"return",
"keywords",
".",
"join",
"(",
"'-'",
")",
"+",
"value",
";",
"}"
] |
Search for value substring in abbreviation
@param {String} abbr
@returns {String} Value substring
|
[
"Search",
"for",
"value",
"substring",
"in",
"abbreviation"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L680-L710
|
|
11,196
|
emmetio/emmet
|
lib/resolver/css.js
|
function(abbr) {
// search for value start
var abbrValues = this.findValuesInAbbreviation(abbr);
if (!abbrValues) {
return {
property: abbr,
values: null
};
}
return {
property: abbr.substring(0, abbr.length - abbrValues.length).replace(/-$/, ''),
values: this.parseValues(abbrValues)
};
}
|
javascript
|
function(abbr) {
// search for value start
var abbrValues = this.findValuesInAbbreviation(abbr);
if (!abbrValues) {
return {
property: abbr,
values: null
};
}
return {
property: abbr.substring(0, abbr.length - abbrValues.length).replace(/-$/, ''),
values: this.parseValues(abbrValues)
};
}
|
[
"function",
"(",
"abbr",
")",
"{",
"// search for value start",
"var",
"abbrValues",
"=",
"this",
".",
"findValuesInAbbreviation",
"(",
"abbr",
")",
";",
"if",
"(",
"!",
"abbrValues",
")",
"{",
"return",
"{",
"property",
":",
"abbr",
",",
"values",
":",
"null",
"}",
";",
"}",
"return",
"{",
"property",
":",
"abbr",
".",
"substring",
"(",
"0",
",",
"abbr",
".",
"length",
"-",
"abbrValues",
".",
"length",
")",
".",
"replace",
"(",
"/",
"-$",
"/",
",",
"''",
")",
",",
"values",
":",
"this",
".",
"parseValues",
"(",
"abbrValues",
")",
"}",
";",
"}"
] |
Extracts values from abbreviation
@param {String} abbr
@returns {Object} Object containing array of values and clean
abbreviation name
|
[
"Extracts",
"values",
"from",
"abbreviation"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L755-L769
|
|
11,197
|
emmetio/emmet
|
lib/resolver/css.js
|
function(value, property) {
property = (property || '').toLowerCase();
var unitlessProps = prefs.getArray('css.unitlessProperties');
return value.replace(/^(\-?[0-9\.]+)([a-z]*)$/, function(str, val, unit) {
if (!unit && (val == '0' || ~unitlessProps.indexOf(property)))
return val;
if (!unit)
return val.replace(/\.$/, '') + prefs.get(~val.indexOf('.') ? 'css.floatUnit' : 'css.intUnit');
return val + getUnit(unit);
});
}
|
javascript
|
function(value, property) {
property = (property || '').toLowerCase();
var unitlessProps = prefs.getArray('css.unitlessProperties');
return value.replace(/^(\-?[0-9\.]+)([a-z]*)$/, function(str, val, unit) {
if (!unit && (val == '0' || ~unitlessProps.indexOf(property)))
return val;
if (!unit)
return val.replace(/\.$/, '') + prefs.get(~val.indexOf('.') ? 'css.floatUnit' : 'css.intUnit');
return val + getUnit(unit);
});
}
|
[
"function",
"(",
"value",
",",
"property",
")",
"{",
"property",
"=",
"(",
"property",
"||",
"''",
")",
".",
"toLowerCase",
"(",
")",
";",
"var",
"unitlessProps",
"=",
"prefs",
".",
"getArray",
"(",
"'css.unitlessProperties'",
")",
";",
"return",
"value",
".",
"replace",
"(",
"/",
"^(\\-?[0-9\\.]+)([a-z]*)$",
"/",
",",
"function",
"(",
"str",
",",
"val",
",",
"unit",
")",
"{",
"if",
"(",
"!",
"unit",
"&&",
"(",
"val",
"==",
"'0'",
"||",
"~",
"unitlessProps",
".",
"indexOf",
"(",
"property",
")",
")",
")",
"return",
"val",
";",
"if",
"(",
"!",
"unit",
")",
"return",
"val",
".",
"replace",
"(",
"/",
"\\.$",
"/",
",",
"''",
")",
"+",
"prefs",
".",
"get",
"(",
"~",
"val",
".",
"indexOf",
"(",
"'.'",
")",
"?",
"'css.floatUnit'",
":",
"'css.intUnit'",
")",
";",
"return",
"val",
"+",
"getUnit",
"(",
"unit",
")",
";",
"}",
")",
";",
"}"
] |
Normalizes value, defined in abbreviation.
@param {String} value
@param {String} property
@returns {String}
|
[
"Normalizes",
"value",
"defined",
"in",
"abbreviation",
"."
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/resolver/css.js#L777-L789
|
|
11,198
|
emmetio/emmet
|
lib/utils/cssSections.js
|
function() {
if (this._name === null) {
var range = this.nameRange();
if (range) {
this._name = range.substring(this.source());
}
}
return this._name;
}
|
javascript
|
function() {
if (this._name === null) {
var range = this.nameRange();
if (range) {
this._name = range.substring(this.source());
}
}
return this._name;
}
|
[
"function",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_name",
"===",
"null",
")",
"{",
"var",
"range",
"=",
"this",
".",
"nameRange",
"(",
")",
";",
"if",
"(",
"range",
")",
"{",
"this",
".",
"_name",
"=",
"range",
".",
"substring",
"(",
"this",
".",
"source",
"(",
")",
")",
";",
"}",
"}",
"return",
"this",
".",
"_name",
";",
"}"
] |
Returns section name
@return {String}
|
[
"Returns",
"section",
"name"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/utils/cssSections.js#L108-L117
|
|
11,199
|
emmetio/emmet
|
lib/utils/cssSections.js
|
function() {
var out = [];
if (this.parent) {
// add current range if it is not root node
out.push(this.range);
}
this.children.forEach(function(child) {
out = out.concat(child.allRanges());
});
return out;
}
|
javascript
|
function() {
var out = [];
if (this.parent) {
// add current range if it is not root node
out.push(this.range);
}
this.children.forEach(function(child) {
out = out.concat(child.allRanges());
});
return out;
}
|
[
"function",
"(",
")",
"{",
"var",
"out",
"=",
"[",
"]",
";",
"if",
"(",
"this",
".",
"parent",
")",
"{",
"// add current range if it is not root node",
"out",
".",
"push",
"(",
"this",
".",
"range",
")",
";",
"}",
"this",
".",
"children",
".",
"forEach",
"(",
"function",
"(",
"child",
")",
"{",
"out",
"=",
"out",
".",
"concat",
"(",
"child",
".",
"allRanges",
"(",
")",
")",
";",
"}",
")",
";",
"return",
"out",
";",
"}"
] |
Returns current and all nested sections ranges
@return {Array}
|
[
"Returns",
"current",
"and",
"all",
"nested",
"sections",
"ranges"
] |
7c9a4623cea414c2f2cc9caebc13355d2bbd898d
|
https://github.com/emmetio/emmet/blob/7c9a4623cea414c2f2cc9caebc13355d2bbd898d/lib/utils/cssSections.js#L154-L166
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.