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
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
ecomfe/zrender
|
src/mixin/Eventful.js
|
function (event, query, handler, context) {
return on(this, event, query, handler, context, false);
}
|
javascript
|
function (event, query, handler, context) {
return on(this, event, query, handler, context, false);
}
|
[
"function",
"(",
"event",
",",
"query",
",",
"handler",
",",
"context",
")",
"{",
"return",
"on",
"(",
"this",
",",
"event",
",",
"query",
",",
"handler",
",",
"context",
",",
"false",
")",
";",
"}"
] |
Bind a handler.
@param {string} event The event name.
@param {string|Object} [query] Condition used on event filter.
@param {Function} handler The event handler.
@param {Object} [context]
|
[
"Bind",
"a",
"handler",
"."
] |
30321b57cba3149c30eacb0c1e18276f0f001b9f
|
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/mixin/Eventful.js#L57-L59
|
train
|
|
ecomfe/zrender
|
src/mixin/Eventful.js
|
function (event, handler) {
var _h = this._$handlers;
if (!event) {
this._$handlers = {};
return this;
}
if (handler) {
if (_h[event]) {
var newList = [];
for (var i = 0, l = _h[event].length; i < l; i++) {
if (_h[event][i].h !== handler) {
newList.push(_h[event][i]);
}
}
_h[event] = newList;
}
if (_h[event] && _h[event].length === 0) {
delete _h[event];
}
}
else {
delete _h[event];
}
return this;
}
|
javascript
|
function (event, handler) {
var _h = this._$handlers;
if (!event) {
this._$handlers = {};
return this;
}
if (handler) {
if (_h[event]) {
var newList = [];
for (var i = 0, l = _h[event].length; i < l; i++) {
if (_h[event][i].h !== handler) {
newList.push(_h[event][i]);
}
}
_h[event] = newList;
}
if (_h[event] && _h[event].length === 0) {
delete _h[event];
}
}
else {
delete _h[event];
}
return this;
}
|
[
"function",
"(",
"event",
",",
"handler",
")",
"{",
"var",
"_h",
"=",
"this",
".",
"_$handlers",
";",
"if",
"(",
"!",
"event",
")",
"{",
"this",
".",
"_$handlers",
"=",
"{",
"}",
";",
"return",
"this",
";",
"}",
"if",
"(",
"handler",
")",
"{",
"if",
"(",
"_h",
"[",
"event",
"]",
")",
"{",
"var",
"newList",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"_h",
"[",
"event",
"]",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"_h",
"[",
"event",
"]",
"[",
"i",
"]",
".",
"h",
"!==",
"handler",
")",
"{",
"newList",
".",
"push",
"(",
"_h",
"[",
"event",
"]",
"[",
"i",
"]",
")",
";",
"}",
"}",
"_h",
"[",
"event",
"]",
"=",
"newList",
";",
"}",
"if",
"(",
"_h",
"[",
"event",
"]",
"&&",
"_h",
"[",
"event",
"]",
".",
"length",
"===",
"0",
")",
"{",
"delete",
"_h",
"[",
"event",
"]",
";",
"}",
"}",
"else",
"{",
"delete",
"_h",
"[",
"event",
"]",
";",
"}",
"return",
"this",
";",
"}"
] |
Unbind a event.
@param {string} event The event name.
@param {Function} [handler] The event handler.
|
[
"Unbind",
"a",
"event",
"."
] |
30321b57cba3149c30eacb0c1e18276f0f001b9f
|
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/mixin/Eventful.js#L78-L106
|
train
|
|
ecomfe/zrender
|
src/mixin/Eventful.js
|
function (type) {
var _h = this._$handlers[type];
var eventProcessor = this._$eventProcessor;
if (_h) {
var args = arguments;
var argLen = args.length;
if (argLen > 3) {
args = arrySlice.call(args, 1);
}
var len = _h.length;
for (var i = 0; i < len;) {
var hItem = _h[i];
if (eventProcessor
&& eventProcessor.filter
&& hItem.query != null
&& !eventProcessor.filter(type, hItem.query)
) {
i++;
continue;
}
// Optimize advise from backbone
switch (argLen) {
case 1:
hItem.h.call(hItem.ctx);
break;
case 2:
hItem.h.call(hItem.ctx, args[1]);
break;
case 3:
hItem.h.call(hItem.ctx, args[1], args[2]);
break;
default:
// have more than 2 given arguments
hItem.h.apply(hItem.ctx, args);
break;
}
if (hItem.one) {
_h.splice(i, 1);
len--;
}
else {
i++;
}
}
}
eventProcessor && eventProcessor.afterTrigger
&& eventProcessor.afterTrigger(type);
return this;
}
|
javascript
|
function (type) {
var _h = this._$handlers[type];
var eventProcessor = this._$eventProcessor;
if (_h) {
var args = arguments;
var argLen = args.length;
if (argLen > 3) {
args = arrySlice.call(args, 1);
}
var len = _h.length;
for (var i = 0; i < len;) {
var hItem = _h[i];
if (eventProcessor
&& eventProcessor.filter
&& hItem.query != null
&& !eventProcessor.filter(type, hItem.query)
) {
i++;
continue;
}
// Optimize advise from backbone
switch (argLen) {
case 1:
hItem.h.call(hItem.ctx);
break;
case 2:
hItem.h.call(hItem.ctx, args[1]);
break;
case 3:
hItem.h.call(hItem.ctx, args[1], args[2]);
break;
default:
// have more than 2 given arguments
hItem.h.apply(hItem.ctx, args);
break;
}
if (hItem.one) {
_h.splice(i, 1);
len--;
}
else {
i++;
}
}
}
eventProcessor && eventProcessor.afterTrigger
&& eventProcessor.afterTrigger(type);
return this;
}
|
[
"function",
"(",
"type",
")",
"{",
"var",
"_h",
"=",
"this",
".",
"_$handlers",
"[",
"type",
"]",
";",
"var",
"eventProcessor",
"=",
"this",
".",
"_$eventProcessor",
";",
"if",
"(",
"_h",
")",
"{",
"var",
"args",
"=",
"arguments",
";",
"var",
"argLen",
"=",
"args",
".",
"length",
";",
"if",
"(",
"argLen",
">",
"3",
")",
"{",
"args",
"=",
"arrySlice",
".",
"call",
"(",
"args",
",",
"1",
")",
";",
"}",
"var",
"len",
"=",
"_h",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
")",
"{",
"var",
"hItem",
"=",
"_h",
"[",
"i",
"]",
";",
"if",
"(",
"eventProcessor",
"&&",
"eventProcessor",
".",
"filter",
"&&",
"hItem",
".",
"query",
"!=",
"null",
"&&",
"!",
"eventProcessor",
".",
"filter",
"(",
"type",
",",
"hItem",
".",
"query",
")",
")",
"{",
"i",
"++",
";",
"continue",
";",
"}",
"switch",
"(",
"argLen",
")",
"{",
"case",
"1",
":",
"hItem",
".",
"h",
".",
"call",
"(",
"hItem",
".",
"ctx",
")",
";",
"break",
";",
"case",
"2",
":",
"hItem",
".",
"h",
".",
"call",
"(",
"hItem",
".",
"ctx",
",",
"args",
"[",
"1",
"]",
")",
";",
"break",
";",
"case",
"3",
":",
"hItem",
".",
"h",
".",
"call",
"(",
"hItem",
".",
"ctx",
",",
"args",
"[",
"1",
"]",
",",
"args",
"[",
"2",
"]",
")",
";",
"break",
";",
"default",
":",
"hItem",
".",
"h",
".",
"apply",
"(",
"hItem",
".",
"ctx",
",",
"args",
")",
";",
"break",
";",
"}",
"if",
"(",
"hItem",
".",
"one",
")",
"{",
"_h",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"len",
"--",
";",
"}",
"else",
"{",
"i",
"++",
";",
"}",
"}",
"}",
"eventProcessor",
"&&",
"eventProcessor",
".",
"afterTrigger",
"&&",
"eventProcessor",
".",
"afterTrigger",
"(",
"type",
")",
";",
"return",
"this",
";",
"}"
] |
Dispatch a event.
@param {string} type The event name.
|
[
"Dispatch",
"a",
"event",
"."
] |
30321b57cba3149c30eacb0c1e18276f0f001b9f
|
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/mixin/Eventful.js#L113-L168
|
train
|
|
ecomfe/zrender
|
src/dom/HandlerProxy.js
|
function (event) {
event = normalizeEvent(this.dom, event);
var element = event.toElement || event.relatedTarget;
if (element !== this.dom) {
while (element && element.nodeType !== 9) {
// 忽略包含在root中的dom引起的mouseOut
if (element === this.dom) {
return;
}
element = element.parentNode;
}
}
this.trigger('mouseout', event);
}
|
javascript
|
function (event) {
event = normalizeEvent(this.dom, event);
var element = event.toElement || event.relatedTarget;
if (element !== this.dom) {
while (element && element.nodeType !== 9) {
// 忽略包含在root中的dom引起的mouseOut
if (element === this.dom) {
return;
}
element = element.parentNode;
}
}
this.trigger('mouseout', event);
}
|
[
"function",
"(",
"event",
")",
"{",
"event",
"=",
"normalizeEvent",
"(",
"this",
".",
"dom",
",",
"event",
")",
";",
"var",
"element",
"=",
"event",
".",
"toElement",
"||",
"event",
".",
"relatedTarget",
";",
"if",
"(",
"element",
"!==",
"this",
".",
"dom",
")",
"{",
"while",
"(",
"element",
"&&",
"element",
".",
"nodeType",
"!==",
"9",
")",
"{",
"if",
"(",
"element",
"===",
"this",
".",
"dom",
")",
"{",
"return",
";",
"}",
"element",
"=",
"element",
".",
"parentNode",
";",
"}",
"}",
"this",
".",
"trigger",
"(",
"'mouseout'",
",",
"event",
")",
";",
"}"
] |
Mouse out handler
@inner
@param {Event} event
|
[
"Mouse",
"out",
"handler"
] |
30321b57cba3149c30eacb0c1e18276f0f001b9f
|
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/dom/HandlerProxy.js#L81-L97
|
train
|
|
ecomfe/zrender
|
src/core/PathProxy.js
|
function (x1, y1, x2, y2, x3, y3) {
var dashSum = this._dashSum;
var offset = this._dashOffset;
var lineDash = this._lineDash;
var ctx = this._ctx;
var x0 = this._xi;
var y0 = this._yi;
var t;
var dx;
var dy;
var cubicAt = curve.cubicAt;
var bezierLen = 0;
var idx = this._dashIdx;
var nDash = lineDash.length;
var x;
var y;
var tmpLen = 0;
if (offset < 0) {
// Convert to positive offset
offset = dashSum + offset;
}
offset %= dashSum;
// Bezier approx length
for (t = 0; t < 1; t += 0.1) {
dx = cubicAt(x0, x1, x2, x3, t + 0.1)
- cubicAt(x0, x1, x2, x3, t);
dy = cubicAt(y0, y1, y2, y3, t + 0.1)
- cubicAt(y0, y1, y2, y3, t);
bezierLen += mathSqrt(dx * dx + dy * dy);
}
// Find idx after add offset
for (; idx < nDash; idx++) {
tmpLen += lineDash[idx];
if (tmpLen > offset) {
break;
}
}
t = (tmpLen - offset) / bezierLen;
while (t <= 1) {
x = cubicAt(x0, x1, x2, x3, t);
y = cubicAt(y0, y1, y2, y3, t);
// Use line to approximate dashed bezier
// Bad result if dash is long
idx % 2 ? ctx.moveTo(x, y)
: ctx.lineTo(x, y);
t += lineDash[idx] / bezierLen;
idx = (idx + 1) % nDash;
}
// Finish the last segment and calculate the new offset
(idx % 2 !== 0) && ctx.lineTo(x3, y3);
dx = x3 - x;
dy = y3 - y;
this._dashOffset = -mathSqrt(dx * dx + dy * dy);
}
|
javascript
|
function (x1, y1, x2, y2, x3, y3) {
var dashSum = this._dashSum;
var offset = this._dashOffset;
var lineDash = this._lineDash;
var ctx = this._ctx;
var x0 = this._xi;
var y0 = this._yi;
var t;
var dx;
var dy;
var cubicAt = curve.cubicAt;
var bezierLen = 0;
var idx = this._dashIdx;
var nDash = lineDash.length;
var x;
var y;
var tmpLen = 0;
if (offset < 0) {
// Convert to positive offset
offset = dashSum + offset;
}
offset %= dashSum;
// Bezier approx length
for (t = 0; t < 1; t += 0.1) {
dx = cubicAt(x0, x1, x2, x3, t + 0.1)
- cubicAt(x0, x1, x2, x3, t);
dy = cubicAt(y0, y1, y2, y3, t + 0.1)
- cubicAt(y0, y1, y2, y3, t);
bezierLen += mathSqrt(dx * dx + dy * dy);
}
// Find idx after add offset
for (; idx < nDash; idx++) {
tmpLen += lineDash[idx];
if (tmpLen > offset) {
break;
}
}
t = (tmpLen - offset) / bezierLen;
while (t <= 1) {
x = cubicAt(x0, x1, x2, x3, t);
y = cubicAt(y0, y1, y2, y3, t);
// Use line to approximate dashed bezier
// Bad result if dash is long
idx % 2 ? ctx.moveTo(x, y)
: ctx.lineTo(x, y);
t += lineDash[idx] / bezierLen;
idx = (idx + 1) % nDash;
}
// Finish the last segment and calculate the new offset
(idx % 2 !== 0) && ctx.lineTo(x3, y3);
dx = x3 - x;
dy = y3 - y;
this._dashOffset = -mathSqrt(dx * dx + dy * dy);
}
|
[
"function",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"x3",
",",
"y3",
")",
"{",
"var",
"dashSum",
"=",
"this",
".",
"_dashSum",
";",
"var",
"offset",
"=",
"this",
".",
"_dashOffset",
";",
"var",
"lineDash",
"=",
"this",
".",
"_lineDash",
";",
"var",
"ctx",
"=",
"this",
".",
"_ctx",
";",
"var",
"x0",
"=",
"this",
".",
"_xi",
";",
"var",
"y0",
"=",
"this",
".",
"_yi",
";",
"var",
"t",
";",
"var",
"dx",
";",
"var",
"dy",
";",
"var",
"cubicAt",
"=",
"curve",
".",
"cubicAt",
";",
"var",
"bezierLen",
"=",
"0",
";",
"var",
"idx",
"=",
"this",
".",
"_dashIdx",
";",
"var",
"nDash",
"=",
"lineDash",
".",
"length",
";",
"var",
"x",
";",
"var",
"y",
";",
"var",
"tmpLen",
"=",
"0",
";",
"if",
"(",
"offset",
"<",
"0",
")",
"{",
"offset",
"=",
"dashSum",
"+",
"offset",
";",
"}",
"offset",
"%=",
"dashSum",
";",
"for",
"(",
"t",
"=",
"0",
";",
"t",
"<",
"1",
";",
"t",
"+=",
"0.1",
")",
"{",
"dx",
"=",
"cubicAt",
"(",
"x0",
",",
"x1",
",",
"x2",
",",
"x3",
",",
"t",
"+",
"0.1",
")",
"-",
"cubicAt",
"(",
"x0",
",",
"x1",
",",
"x2",
",",
"x3",
",",
"t",
")",
";",
"dy",
"=",
"cubicAt",
"(",
"y0",
",",
"y1",
",",
"y2",
",",
"y3",
",",
"t",
"+",
"0.1",
")",
"-",
"cubicAt",
"(",
"y0",
",",
"y1",
",",
"y2",
",",
"y3",
",",
"t",
")",
";",
"bezierLen",
"+=",
"mathSqrt",
"(",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
")",
";",
"}",
"for",
"(",
";",
"idx",
"<",
"nDash",
";",
"idx",
"++",
")",
"{",
"tmpLen",
"+=",
"lineDash",
"[",
"idx",
"]",
";",
"if",
"(",
"tmpLen",
">",
"offset",
")",
"{",
"break",
";",
"}",
"}",
"t",
"=",
"(",
"tmpLen",
"-",
"offset",
")",
"/",
"bezierLen",
";",
"while",
"(",
"t",
"<=",
"1",
")",
"{",
"x",
"=",
"cubicAt",
"(",
"x0",
",",
"x1",
",",
"x2",
",",
"x3",
",",
"t",
")",
";",
"y",
"=",
"cubicAt",
"(",
"y0",
",",
"y1",
",",
"y2",
",",
"y3",
",",
"t",
")",
";",
"idx",
"%",
"2",
"?",
"ctx",
".",
"moveTo",
"(",
"x",
",",
"y",
")",
":",
"ctx",
".",
"lineTo",
"(",
"x",
",",
"y",
")",
";",
"t",
"+=",
"lineDash",
"[",
"idx",
"]",
"/",
"bezierLen",
";",
"idx",
"=",
"(",
"idx",
"+",
"1",
")",
"%",
"nDash",
";",
"}",
"(",
"idx",
"%",
"2",
"!==",
"0",
")",
"&&",
"ctx",
".",
"lineTo",
"(",
"x3",
",",
"y3",
")",
";",
"dx",
"=",
"x3",
"-",
"x",
";",
"dy",
"=",
"y3",
"-",
"y",
";",
"this",
".",
"_dashOffset",
"=",
"-",
"mathSqrt",
"(",
"dx",
"*",
"dx",
"+",
"dy",
"*",
"dy",
")",
";",
"}"
] |
Not accurate dashed line to
|
[
"Not",
"accurate",
"dashed",
"line",
"to"
] |
30321b57cba3149c30eacb0c1e18276f0f001b9f
|
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/core/PathProxy.js#L471-L535
|
train
|
|
ecomfe/zrender
|
src/graphic/Style.js
|
function (otherStyle, overwrite) {
if (otherStyle) {
for (var name in otherStyle) {
if (otherStyle.hasOwnProperty(name)
&& (overwrite === true
|| (
overwrite === false
? !this.hasOwnProperty(name)
: otherStyle[name] != null
)
)
) {
this[name] = otherStyle[name];
}
}
}
}
|
javascript
|
function (otherStyle, overwrite) {
if (otherStyle) {
for (var name in otherStyle) {
if (otherStyle.hasOwnProperty(name)
&& (overwrite === true
|| (
overwrite === false
? !this.hasOwnProperty(name)
: otherStyle[name] != null
)
)
) {
this[name] = otherStyle[name];
}
}
}
}
|
[
"function",
"(",
"otherStyle",
",",
"overwrite",
")",
"{",
"if",
"(",
"otherStyle",
")",
"{",
"for",
"(",
"var",
"name",
"in",
"otherStyle",
")",
"{",
"if",
"(",
"otherStyle",
".",
"hasOwnProperty",
"(",
"name",
")",
"&&",
"(",
"overwrite",
"===",
"true",
"||",
"(",
"overwrite",
"===",
"false",
"?",
"!",
"this",
".",
"hasOwnProperty",
"(",
"name",
")",
":",
"otherStyle",
"[",
"name",
"]",
"!=",
"null",
")",
")",
")",
"{",
"this",
"[",
"name",
"]",
"=",
"otherStyle",
"[",
"name",
"]",
";",
"}",
"}",
"}",
"}"
] |
Extend from other style
@param {zrender/graphic/Style} otherStyle
@param {boolean} overwrite true: overwrirte any way.
false: overwrite only when !target.hasOwnProperty
others: overwrite when property is not null/undefined.
|
[
"Extend",
"from",
"other",
"style"
] |
30321b57cba3149c30eacb0c1e18276f0f001b9f
|
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/graphic/Style.js#L424-L440
|
train
|
|
ecomfe/zrender
|
build/babel-plugin-transform-modules-commonjs-ec.js
|
normalizeModuleAndLoadMetadata
|
function normalizeModuleAndLoadMetadata(programPath) {
nameAnonymousExports(programPath);
const {local, source} = getModuleMetadata(programPath);
removeModuleDeclarations(programPath);
// Reuse the imported namespace name if there is one.
for (const [, metadata] of source) {
if (metadata.importsNamespace.size > 0) {
// This is kind of gross. If we stop using `loose: true` we should
// just make this destructuring assignment.
metadata.name = metadata.importsNamespace.values().next().value;
}
}
return {
exportName: 'exports',
exportNameListName: null,
local,
source
};
}
|
javascript
|
function normalizeModuleAndLoadMetadata(programPath) {
nameAnonymousExports(programPath);
const {local, source} = getModuleMetadata(programPath);
removeModuleDeclarations(programPath);
// Reuse the imported namespace name if there is one.
for (const [, metadata] of source) {
if (metadata.importsNamespace.size > 0) {
// This is kind of gross. If we stop using `loose: true` we should
// just make this destructuring assignment.
metadata.name = metadata.importsNamespace.values().next().value;
}
}
return {
exportName: 'exports',
exportNameListName: null,
local,
source
};
}
|
[
"function",
"normalizeModuleAndLoadMetadata",
"(",
"programPath",
")",
"{",
"nameAnonymousExports",
"(",
"programPath",
")",
";",
"const",
"{",
"local",
",",
"source",
"}",
"=",
"getModuleMetadata",
"(",
"programPath",
")",
";",
"removeModuleDeclarations",
"(",
"programPath",
")",
";",
"for",
"(",
"const",
"[",
",",
"metadata",
"]",
"of",
"source",
")",
"{",
"if",
"(",
"metadata",
".",
"importsNamespace",
".",
"size",
">",
"0",
")",
"{",
"metadata",
".",
"name",
"=",
"metadata",
".",
"importsNamespace",
".",
"values",
"(",
")",
".",
"next",
"(",
")",
".",
"value",
";",
"}",
"}",
"return",
"{",
"exportName",
":",
"'exports'",
",",
"exportNameListName",
":",
"null",
",",
"local",
",",
"source",
"}",
";",
"}"
] |
Remove all imports and exports from the file, and return all metadata
needed to reconstruct the module's behavior.
@return {ModuleMetadata}
|
[
"Remove",
"all",
"imports",
"and",
"exports",
"from",
"the",
"file",
"and",
"return",
"all",
"metadata",
"needed",
"to",
"reconstruct",
"the",
"module",
"s",
"behavior",
"."
] |
30321b57cba3149c30eacb0c1e18276f0f001b9f
|
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/build/babel-plugin-transform-modules-commonjs-ec.js#L70-L93
|
train
|
ecomfe/zrender
|
build/babel-plugin-transform-modules-commonjs-ec.js
|
nameAnonymousExports
|
function nameAnonymousExports(programPath) {
// Name anonymous exported locals.
programPath.get('body').forEach(child => {
if (!child.isExportDefaultDeclaration()) {
return;
}
// export default foo;
const declaration = child.get('declaration');
if (declaration.isFunctionDeclaration()) {
if (!declaration.node.id) {
declaration.node.id = declaration.scope.generateUidIdentifier('default');
}
}
else if (declaration.isClassDeclaration()) {
if (!declaration.node.id) {
declaration.node.id = declaration.scope.generateUidIdentifier('default');
}
}
else {
const id = declaration.scope.generateUidIdentifier('default');
const namedDecl = babelTypes.exportNamedDeclaration(null, [
babelTypes.exportSpecifier(babelTypes.identifier(id.name), babelTypes.identifier('default')),
]);
namedDecl._blockHoist = child.node._blockHoist;
const varDecl = babelTypes.variableDeclaration('var', [
babelTypes.variableDeclarator(id, declaration.node),
]);
varDecl._blockHoist = child.node._blockHoist;
child.replaceWithMultiple([namedDecl, varDecl]);
}
});
}
|
javascript
|
function nameAnonymousExports(programPath) {
// Name anonymous exported locals.
programPath.get('body').forEach(child => {
if (!child.isExportDefaultDeclaration()) {
return;
}
// export default foo;
const declaration = child.get('declaration');
if (declaration.isFunctionDeclaration()) {
if (!declaration.node.id) {
declaration.node.id = declaration.scope.generateUidIdentifier('default');
}
}
else if (declaration.isClassDeclaration()) {
if (!declaration.node.id) {
declaration.node.id = declaration.scope.generateUidIdentifier('default');
}
}
else {
const id = declaration.scope.generateUidIdentifier('default');
const namedDecl = babelTypes.exportNamedDeclaration(null, [
babelTypes.exportSpecifier(babelTypes.identifier(id.name), babelTypes.identifier('default')),
]);
namedDecl._blockHoist = child.node._blockHoist;
const varDecl = babelTypes.variableDeclaration('var', [
babelTypes.variableDeclarator(id, declaration.node),
]);
varDecl._blockHoist = child.node._blockHoist;
child.replaceWithMultiple([namedDecl, varDecl]);
}
});
}
|
[
"function",
"nameAnonymousExports",
"(",
"programPath",
")",
"{",
"programPath",
".",
"get",
"(",
"'body'",
")",
".",
"forEach",
"(",
"child",
"=>",
"{",
"if",
"(",
"!",
"child",
".",
"isExportDefaultDeclaration",
"(",
")",
")",
"{",
"return",
";",
"}",
"const",
"declaration",
"=",
"child",
".",
"get",
"(",
"'declaration'",
")",
";",
"if",
"(",
"declaration",
".",
"isFunctionDeclaration",
"(",
")",
")",
"{",
"if",
"(",
"!",
"declaration",
".",
"node",
".",
"id",
")",
"{",
"declaration",
".",
"node",
".",
"id",
"=",
"declaration",
".",
"scope",
".",
"generateUidIdentifier",
"(",
"'default'",
")",
";",
"}",
"}",
"else",
"if",
"(",
"declaration",
".",
"isClassDeclaration",
"(",
")",
")",
"{",
"if",
"(",
"!",
"declaration",
".",
"node",
".",
"id",
")",
"{",
"declaration",
".",
"node",
".",
"id",
"=",
"declaration",
".",
"scope",
".",
"generateUidIdentifier",
"(",
"'default'",
")",
";",
"}",
"}",
"else",
"{",
"const",
"id",
"=",
"declaration",
".",
"scope",
".",
"generateUidIdentifier",
"(",
"'default'",
")",
";",
"const",
"namedDecl",
"=",
"babelTypes",
".",
"exportNamedDeclaration",
"(",
"null",
",",
"[",
"babelTypes",
".",
"exportSpecifier",
"(",
"babelTypes",
".",
"identifier",
"(",
"id",
".",
"name",
")",
",",
"babelTypes",
".",
"identifier",
"(",
"'default'",
")",
")",
",",
"]",
")",
";",
"namedDecl",
".",
"_blockHoist",
"=",
"child",
".",
"node",
".",
"_blockHoist",
";",
"const",
"varDecl",
"=",
"babelTypes",
".",
"variableDeclaration",
"(",
"'var'",
",",
"[",
"babelTypes",
".",
"variableDeclarator",
"(",
"id",
",",
"declaration",
".",
"node",
")",
",",
"]",
")",
";",
"varDecl",
".",
"_blockHoist",
"=",
"child",
".",
"node",
".",
"_blockHoist",
";",
"child",
".",
"replaceWithMultiple",
"(",
"[",
"namedDecl",
",",
"varDecl",
"]",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Ensure that all exported values have local binding names.
|
[
"Ensure",
"that",
"all",
"exported",
"values",
"have",
"local",
"binding",
"names",
"."
] |
30321b57cba3149c30eacb0c1e18276f0f001b9f
|
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/build/babel-plugin-transform-modules-commonjs-ec.js#L368-L402
|
train
|
ecomfe/zrender
|
src/graphic/mixin/RectText.js
|
function (ctx, rect) {
var style = this.style;
rect = style.textRect || rect;
// Optimize, avoid normalize every time.
this.__dirty && textHelper.normalizeTextStyle(style, true);
var text = style.text;
// Convert to string
text != null && (text += '');
if (!textHelper.needDrawText(text, style)) {
return;
}
// FIXME
// Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
// but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
// text propably break the cache for its host elements.
ctx.save();
// Transform rect to view space
var transform = this.transform;
if (!style.transformText) {
if (transform) {
tmpRect.copy(rect);
tmpRect.applyTransform(transform);
rect = tmpRect;
}
}
else {
this.setTransform(ctx);
}
// transformText and textRotation can not be used at the same time.
textHelper.renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
ctx.restore();
}
|
javascript
|
function (ctx, rect) {
var style = this.style;
rect = style.textRect || rect;
// Optimize, avoid normalize every time.
this.__dirty && textHelper.normalizeTextStyle(style, true);
var text = style.text;
// Convert to string
text != null && (text += '');
if (!textHelper.needDrawText(text, style)) {
return;
}
// FIXME
// Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
// but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
// text propably break the cache for its host elements.
ctx.save();
// Transform rect to view space
var transform = this.transform;
if (!style.transformText) {
if (transform) {
tmpRect.copy(rect);
tmpRect.applyTransform(transform);
rect = tmpRect;
}
}
else {
this.setTransform(ctx);
}
// transformText and textRotation can not be used at the same time.
textHelper.renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
ctx.restore();
}
|
[
"function",
"(",
"ctx",
",",
"rect",
")",
"{",
"var",
"style",
"=",
"this",
".",
"style",
";",
"rect",
"=",
"style",
".",
"textRect",
"||",
"rect",
";",
"this",
".",
"__dirty",
"&&",
"textHelper",
".",
"normalizeTextStyle",
"(",
"style",
",",
"true",
")",
";",
"var",
"text",
"=",
"style",
".",
"text",
";",
"text",
"!=",
"null",
"&&",
"(",
"text",
"+=",
"''",
")",
";",
"if",
"(",
"!",
"textHelper",
".",
"needDrawText",
"(",
"text",
",",
"style",
")",
")",
"{",
"return",
";",
"}",
"ctx",
".",
"save",
"(",
")",
";",
"var",
"transform",
"=",
"this",
".",
"transform",
";",
"if",
"(",
"!",
"style",
".",
"transformText",
")",
"{",
"if",
"(",
"transform",
")",
"{",
"tmpRect",
".",
"copy",
"(",
"rect",
")",
";",
"tmpRect",
".",
"applyTransform",
"(",
"transform",
")",
";",
"rect",
"=",
"tmpRect",
";",
"}",
"}",
"else",
"{",
"this",
".",
"setTransform",
"(",
"ctx",
")",
";",
"}",
"textHelper",
".",
"renderText",
"(",
"this",
",",
"ctx",
",",
"text",
",",
"style",
",",
"rect",
",",
"WILL_BE_RESTORED",
")",
";",
"ctx",
".",
"restore",
"(",
")",
";",
"}"
] |
Draw text in a rect with specified position.
@param {CanvasRenderingContext2D} ctx
@param {Object} rect Displayable rect
|
[
"Draw",
"text",
"in",
"a",
"rect",
"with",
"specified",
"position",
"."
] |
30321b57cba3149c30eacb0c1e18276f0f001b9f
|
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/graphic/mixin/RectText.js#L23-L63
|
train
|
|
ecomfe/zrender
|
src/Element.js
|
function (zr) {
this.__zr = zr;
// 添加动画
var animators = this.animators;
if (animators) {
for (var i = 0; i < animators.length; i++) {
zr.animation.addAnimator(animators[i]);
}
}
if (this.clipPath) {
this.clipPath.addSelfToZr(zr);
}
}
|
javascript
|
function (zr) {
this.__zr = zr;
// 添加动画
var animators = this.animators;
if (animators) {
for (var i = 0; i < animators.length; i++) {
zr.animation.addAnimator(animators[i]);
}
}
if (this.clipPath) {
this.clipPath.addSelfToZr(zr);
}
}
|
[
"function",
"(",
"zr",
")",
"{",
"this",
".",
"__zr",
"=",
"zr",
";",
"var",
"animators",
"=",
"this",
".",
"animators",
";",
"if",
"(",
"animators",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"animators",
".",
"length",
";",
"i",
"++",
")",
"{",
"zr",
".",
"animation",
".",
"addAnimator",
"(",
"animators",
"[",
"i",
"]",
")",
";",
"}",
"}",
"if",
"(",
"this",
".",
"clipPath",
")",
"{",
"this",
".",
"clipPath",
".",
"addSelfToZr",
"(",
"zr",
")",
";",
"}",
"}"
] |
Add self from zrender instance.
Not recursively because it will be invoked when element added to storage.
@param {module:zrender/ZRender} zr
|
[
"Add",
"self",
"from",
"zrender",
"instance",
".",
"Not",
"recursively",
"because",
"it",
"will",
"be",
"invoked",
"when",
"element",
"added",
"to",
"storage",
"."
] |
30321b57cba3149c30eacb0c1e18276f0f001b9f
|
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/Element.js#L222-L235
|
train
|
|
ecomfe/zrender
|
src/Element.js
|
function (zr) {
this.__zr = null;
// 移除动画
var animators = this.animators;
if (animators) {
for (var i = 0; i < animators.length; i++) {
zr.animation.removeAnimator(animators[i]);
}
}
if (this.clipPath) {
this.clipPath.removeSelfFromZr(zr);
}
}
|
javascript
|
function (zr) {
this.__zr = null;
// 移除动画
var animators = this.animators;
if (animators) {
for (var i = 0; i < animators.length; i++) {
zr.animation.removeAnimator(animators[i]);
}
}
if (this.clipPath) {
this.clipPath.removeSelfFromZr(zr);
}
}
|
[
"function",
"(",
"zr",
")",
"{",
"this",
".",
"__zr",
"=",
"null",
";",
"var",
"animators",
"=",
"this",
".",
"animators",
";",
"if",
"(",
"animators",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"animators",
".",
"length",
";",
"i",
"++",
")",
"{",
"zr",
".",
"animation",
".",
"removeAnimator",
"(",
"animators",
"[",
"i",
"]",
")",
";",
"}",
"}",
"if",
"(",
"this",
".",
"clipPath",
")",
"{",
"this",
".",
"clipPath",
".",
"removeSelfFromZr",
"(",
"zr",
")",
";",
"}",
"}"
] |
Remove self from zrender instance.
Not recursively because it will be invoked when element added to storage.
@param {module:zrender/ZRender} zr
|
[
"Remove",
"self",
"from",
"zrender",
"instance",
".",
"Not",
"recursively",
"because",
"it",
"will",
"be",
"invoked",
"when",
"element",
"added",
"to",
"storage",
"."
] |
30321b57cba3149c30eacb0c1e18276f0f001b9f
|
https://github.com/ecomfe/zrender/blob/30321b57cba3149c30eacb0c1e18276f0f001b9f/src/Element.js#L242-L255
|
train
|
|
thomaspark/bootswatch
|
docs/_vendor/popper.js/dist/popper.js
|
getScrollParent
|
function getScrollParent(element) {
// Return body, `getScroll` will take care to get the correct `scrollTop` from it
if (!element) {
return document.body;
}
switch (element.nodeName) {
case 'HTML':
case 'BODY':
return element.ownerDocument.body;
case '#document':
return element.body;
}
// Firefox want us to check `-x` and `-y` variations as well
const { overflow, overflowX, overflowY } = getStyleComputedProperty(element);
if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) {
return element;
}
return getScrollParent(getParentNode(element));
}
|
javascript
|
function getScrollParent(element) {
// Return body, `getScroll` will take care to get the correct `scrollTop` from it
if (!element) {
return document.body;
}
switch (element.nodeName) {
case 'HTML':
case 'BODY':
return element.ownerDocument.body;
case '#document':
return element.body;
}
// Firefox want us to check `-x` and `-y` variations as well
const { overflow, overflowX, overflowY } = getStyleComputedProperty(element);
if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) {
return element;
}
return getScrollParent(getParentNode(element));
}
|
[
"function",
"getScrollParent",
"(",
"element",
")",
"{",
"if",
"(",
"!",
"element",
")",
"{",
"return",
"document",
".",
"body",
";",
"}",
"switch",
"(",
"element",
".",
"nodeName",
")",
"{",
"case",
"'HTML'",
":",
"case",
"'BODY'",
":",
"return",
"element",
".",
"ownerDocument",
".",
"body",
";",
"case",
"'#document'",
":",
"return",
"element",
".",
"body",
";",
"}",
"const",
"{",
"overflow",
",",
"overflowX",
",",
"overflowY",
"}",
"=",
"getStyleComputedProperty",
"(",
"element",
")",
";",
"if",
"(",
"/",
"(auto|scroll|overlay)",
"/",
".",
"test",
"(",
"overflow",
"+",
"overflowY",
"+",
"overflowX",
")",
")",
"{",
"return",
"element",
";",
"}",
"return",
"getScrollParent",
"(",
"getParentNode",
"(",
"element",
")",
")",
";",
"}"
] |
Returns the scrolling parent of the given element
@method
@memberof Popper.Utils
@argument {Element} element
@returns {Element} scroll parent
|
[
"Returns",
"the",
"scrolling",
"parent",
"of",
"the",
"given",
"element"
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L126-L147
|
train
|
thomaspark/bootswatch
|
docs/_vendor/popper.js/dist/popper.js
|
getOffsetParent
|
function getOffsetParent(element) {
if (!element) {
return document.documentElement;
}
const noOffsetParent = isIE(10) ? document.body : null;
// NOTE: 1 DOM access here
let offsetParent = element.offsetParent || null;
// Skip hidden elements which don't have an offsetParent
while (offsetParent === noOffsetParent && element.nextElementSibling) {
offsetParent = (element = element.nextElementSibling).offsetParent;
}
const nodeName = offsetParent && offsetParent.nodeName;
if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
return element ? element.ownerDocument.documentElement : document.documentElement;
}
// .offsetParent will return the closest TH, TD or TABLE in case
// no offsetParent is present, I hate this job...
if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
return getOffsetParent(offsetParent);
}
return offsetParent;
}
|
javascript
|
function getOffsetParent(element) {
if (!element) {
return document.documentElement;
}
const noOffsetParent = isIE(10) ? document.body : null;
// NOTE: 1 DOM access here
let offsetParent = element.offsetParent || null;
// Skip hidden elements which don't have an offsetParent
while (offsetParent === noOffsetParent && element.nextElementSibling) {
offsetParent = (element = element.nextElementSibling).offsetParent;
}
const nodeName = offsetParent && offsetParent.nodeName;
if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') {
return element ? element.ownerDocument.documentElement : document.documentElement;
}
// .offsetParent will return the closest TH, TD or TABLE in case
// no offsetParent is present, I hate this job...
if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') {
return getOffsetParent(offsetParent);
}
return offsetParent;
}
|
[
"function",
"getOffsetParent",
"(",
"element",
")",
"{",
"if",
"(",
"!",
"element",
")",
"{",
"return",
"document",
".",
"documentElement",
";",
"}",
"const",
"noOffsetParent",
"=",
"isIE",
"(",
"10",
")",
"?",
"document",
".",
"body",
":",
"null",
";",
"let",
"offsetParent",
"=",
"element",
".",
"offsetParent",
"||",
"null",
";",
"while",
"(",
"offsetParent",
"===",
"noOffsetParent",
"&&",
"element",
".",
"nextElementSibling",
")",
"{",
"offsetParent",
"=",
"(",
"element",
"=",
"element",
".",
"nextElementSibling",
")",
".",
"offsetParent",
";",
"}",
"const",
"nodeName",
"=",
"offsetParent",
"&&",
"offsetParent",
".",
"nodeName",
";",
"if",
"(",
"!",
"nodeName",
"||",
"nodeName",
"===",
"'BODY'",
"||",
"nodeName",
"===",
"'HTML'",
")",
"{",
"return",
"element",
"?",
"element",
".",
"ownerDocument",
".",
"documentElement",
":",
"document",
".",
"documentElement",
";",
"}",
"if",
"(",
"[",
"'TH'",
",",
"'TD'",
",",
"'TABLE'",
"]",
".",
"indexOf",
"(",
"offsetParent",
".",
"nodeName",
")",
"!==",
"-",
"1",
"&&",
"getStyleComputedProperty",
"(",
"offsetParent",
",",
"'position'",
")",
"===",
"'static'",
")",
"{",
"return",
"getOffsetParent",
"(",
"offsetParent",
")",
";",
"}",
"return",
"offsetParent",
";",
"}"
] |
Returns the offset parent of the given element
@method
@memberof Popper.Utils
@argument {Element} element
@returns {Element} offset parent
|
[
"Returns",
"the",
"offset",
"parent",
"of",
"the",
"given",
"element"
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L176-L203
|
train
|
thomaspark/bootswatch
|
docs/_vendor/popper.js/dist/popper.js
|
findCommonOffsetParent
|
function findCommonOffsetParent(element1, element2) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
return document.documentElement;
}
// Here we make sure to give as "start" the element that comes first in the DOM
const order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
const start = order ? element1 : element2;
const end = order ? element2 : element1;
// Get common ancestor container
const range = document.createRange();
range.setStart(start, 0);
range.setEnd(end, 0);
const { commonAncestorContainer } = range;
// Both nodes are inside #document
if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
return getOffsetParent(commonAncestorContainer);
}
// one of the nodes is inside shadowDOM, find which one
const element1root = getRoot(element1);
if (element1root.host) {
return findCommonOffsetParent(element1root.host, element2);
} else {
return findCommonOffsetParent(element1, getRoot(element2).host);
}
}
|
javascript
|
function findCommonOffsetParent(element1, element2) {
// This check is needed to avoid errors in case one of the elements isn't defined for any reason
if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) {
return document.documentElement;
}
// Here we make sure to give as "start" the element that comes first in the DOM
const order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING;
const start = order ? element1 : element2;
const end = order ? element2 : element1;
// Get common ancestor container
const range = document.createRange();
range.setStart(start, 0);
range.setEnd(end, 0);
const { commonAncestorContainer } = range;
// Both nodes are inside #document
if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) {
if (isOffsetContainer(commonAncestorContainer)) {
return commonAncestorContainer;
}
return getOffsetParent(commonAncestorContainer);
}
// one of the nodes is inside shadowDOM, find which one
const element1root = getRoot(element1);
if (element1root.host) {
return findCommonOffsetParent(element1root.host, element2);
} else {
return findCommonOffsetParent(element1, getRoot(element2).host);
}
}
|
[
"function",
"findCommonOffsetParent",
"(",
"element1",
",",
"element2",
")",
"{",
"if",
"(",
"!",
"element1",
"||",
"!",
"element1",
".",
"nodeType",
"||",
"!",
"element2",
"||",
"!",
"element2",
".",
"nodeType",
")",
"{",
"return",
"document",
".",
"documentElement",
";",
"}",
"const",
"order",
"=",
"element1",
".",
"compareDocumentPosition",
"(",
"element2",
")",
"&",
"Node",
".",
"DOCUMENT_POSITION_FOLLOWING",
";",
"const",
"start",
"=",
"order",
"?",
"element1",
":",
"element2",
";",
"const",
"end",
"=",
"order",
"?",
"element2",
":",
"element1",
";",
"const",
"range",
"=",
"document",
".",
"createRange",
"(",
")",
";",
"range",
".",
"setStart",
"(",
"start",
",",
"0",
")",
";",
"range",
".",
"setEnd",
"(",
"end",
",",
"0",
")",
";",
"const",
"{",
"commonAncestorContainer",
"}",
"=",
"range",
";",
"if",
"(",
"element1",
"!==",
"commonAncestorContainer",
"&&",
"element2",
"!==",
"commonAncestorContainer",
"||",
"start",
".",
"contains",
"(",
"end",
")",
")",
"{",
"if",
"(",
"isOffsetContainer",
"(",
"commonAncestorContainer",
")",
")",
"{",
"return",
"commonAncestorContainer",
";",
"}",
"return",
"getOffsetParent",
"(",
"commonAncestorContainer",
")",
";",
"}",
"const",
"element1root",
"=",
"getRoot",
"(",
"element1",
")",
";",
"if",
"(",
"element1root",
".",
"host",
")",
"{",
"return",
"findCommonOffsetParent",
"(",
"element1root",
".",
"host",
",",
"element2",
")",
";",
"}",
"else",
"{",
"return",
"findCommonOffsetParent",
"(",
"element1",
",",
"getRoot",
"(",
"element2",
")",
".",
"host",
")",
";",
"}",
"}"
] |
Finds the offset parent common to the two provided nodes
@method
@memberof Popper.Utils
@argument {Element} element1
@argument {Element} element2
@returns {Element} common offset parent
|
[
"Finds",
"the",
"offset",
"parent",
"common",
"to",
"the",
"two",
"provided",
"nodes"
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L236-L269
|
train
|
thomaspark/bootswatch
|
docs/_vendor/popper.js/dist/popper.js
|
computeAutoPlacement
|
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement, padding = 0) {
if (placement.indexOf('auto') === -1) {
return placement;
}
const boundaries = getBoundaries(popper, reference, padding, boundariesElement);
const rects = {
top: {
width: boundaries.width,
height: refRect.top - boundaries.top
},
right: {
width: boundaries.right - refRect.right,
height: boundaries.height
},
bottom: {
width: boundaries.width,
height: boundaries.bottom - refRect.bottom
},
left: {
width: refRect.left - boundaries.left,
height: boundaries.height
}
};
const sortedAreas = Object.keys(rects).map(key => _extends({
key
}, rects[key], {
area: getArea(rects[key])
})).sort((a, b) => b.area - a.area);
const filteredAreas = sortedAreas.filter(({ width, height }) => width >= popper.clientWidth && height >= popper.clientHeight);
const computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
const variation = placement.split('-')[1];
return computedPlacement + (variation ? `-${variation}` : '');
}
|
javascript
|
function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement, padding = 0) {
if (placement.indexOf('auto') === -1) {
return placement;
}
const boundaries = getBoundaries(popper, reference, padding, boundariesElement);
const rects = {
top: {
width: boundaries.width,
height: refRect.top - boundaries.top
},
right: {
width: boundaries.right - refRect.right,
height: boundaries.height
},
bottom: {
width: boundaries.width,
height: boundaries.bottom - refRect.bottom
},
left: {
width: refRect.left - boundaries.left,
height: boundaries.height
}
};
const sortedAreas = Object.keys(rects).map(key => _extends({
key
}, rects[key], {
area: getArea(rects[key])
})).sort((a, b) => b.area - a.area);
const filteredAreas = sortedAreas.filter(({ width, height }) => width >= popper.clientWidth && height >= popper.clientHeight);
const computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key;
const variation = placement.split('-')[1];
return computedPlacement + (variation ? `-${variation}` : '');
}
|
[
"function",
"computeAutoPlacement",
"(",
"placement",
",",
"refRect",
",",
"popper",
",",
"reference",
",",
"boundariesElement",
",",
"padding",
"=",
"0",
")",
"{",
"if",
"(",
"placement",
".",
"indexOf",
"(",
"'auto'",
")",
"===",
"-",
"1",
")",
"{",
"return",
"placement",
";",
"}",
"const",
"boundaries",
"=",
"getBoundaries",
"(",
"popper",
",",
"reference",
",",
"padding",
",",
"boundariesElement",
")",
";",
"const",
"rects",
"=",
"{",
"top",
":",
"{",
"width",
":",
"boundaries",
".",
"width",
",",
"height",
":",
"refRect",
".",
"top",
"-",
"boundaries",
".",
"top",
"}",
",",
"right",
":",
"{",
"width",
":",
"boundaries",
".",
"right",
"-",
"refRect",
".",
"right",
",",
"height",
":",
"boundaries",
".",
"height",
"}",
",",
"bottom",
":",
"{",
"width",
":",
"boundaries",
".",
"width",
",",
"height",
":",
"boundaries",
".",
"bottom",
"-",
"refRect",
".",
"bottom",
"}",
",",
"left",
":",
"{",
"width",
":",
"refRect",
".",
"left",
"-",
"boundaries",
".",
"left",
",",
"height",
":",
"boundaries",
".",
"height",
"}",
"}",
";",
"const",
"sortedAreas",
"=",
"Object",
".",
"keys",
"(",
"rects",
")",
".",
"map",
"(",
"key",
"=>",
"_extends",
"(",
"{",
"key",
"}",
",",
"rects",
"[",
"key",
"]",
",",
"{",
"area",
":",
"getArea",
"(",
"rects",
"[",
"key",
"]",
")",
"}",
")",
")",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"b",
".",
"area",
"-",
"a",
".",
"area",
")",
";",
"const",
"filteredAreas",
"=",
"sortedAreas",
".",
"filter",
"(",
"(",
"{",
"width",
",",
"height",
"}",
")",
"=>",
"width",
">=",
"popper",
".",
"clientWidth",
"&&",
"height",
">=",
"popper",
".",
"clientHeight",
")",
";",
"const",
"computedPlacement",
"=",
"filteredAreas",
".",
"length",
">",
"0",
"?",
"filteredAreas",
"[",
"0",
"]",
".",
"key",
":",
"sortedAreas",
"[",
"0",
"]",
".",
"key",
";",
"const",
"variation",
"=",
"placement",
".",
"split",
"(",
"'-'",
")",
"[",
"1",
"]",
";",
"return",
"computedPlacement",
"+",
"(",
"variation",
"?",
"`",
"${",
"variation",
"}",
"`",
":",
"''",
")",
";",
"}"
] |
Utility used to transform the `auto` placement to the placement with more
available space.
@method
@memberof Popper.Utils
@argument {Object} data - The data object generated by update method
@argument {Object} options - Modifiers configuration and options
@returns {Object} The data object, properly modified
|
[
"Utility",
"used",
"to",
"transform",
"the",
"auto",
"placement",
"to",
"the",
"placement",
"with",
"more",
"available",
"space",
"."
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L613-L652
|
train
|
thomaspark/bootswatch
|
docs/_vendor/popper.js/dist/popper.js
|
getOppositePlacement
|
function getOppositePlacement(placement) {
const hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
return placement.replace(/left|right|bottom|top/g, matched => hash[matched]);
}
|
javascript
|
function getOppositePlacement(placement) {
const hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' };
return placement.replace(/left|right|bottom|top/g, matched => hash[matched]);
}
|
[
"function",
"getOppositePlacement",
"(",
"placement",
")",
"{",
"const",
"hash",
"=",
"{",
"left",
":",
"'right'",
",",
"right",
":",
"'left'",
",",
"bottom",
":",
"'top'",
",",
"top",
":",
"'bottom'",
"}",
";",
"return",
"placement",
".",
"replace",
"(",
"/",
"left|right|bottom|top",
"/",
"g",
",",
"matched",
"=>",
"hash",
"[",
"matched",
"]",
")",
";",
"}"
] |
Get the opposite placement of the given one
@method
@memberof Popper.Utils
@argument {String} placement
@returns {String} flipped placement
|
[
"Get",
"the",
"opposite",
"placement",
"of",
"the",
"given",
"one"
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L695-L698
|
train
|
thomaspark/bootswatch
|
docs/_vendor/popper.js/dist/popper.js
|
getPopperOffsets
|
function getPopperOffsets(popper, referenceOffsets, placement) {
placement = placement.split('-')[0];
// Get popper node sizes
const popperRect = getOuterSizes(popper);
// Add position, width and height to our offsets object
const popperOffsets = {
width: popperRect.width,
height: popperRect.height
};
// depending by the popper placement we have to compute its offsets slightly differently
const isHoriz = ['right', 'left'].indexOf(placement) !== -1;
const mainSide = isHoriz ? 'top' : 'left';
const secondarySide = isHoriz ? 'left' : 'top';
const measurement = isHoriz ? 'height' : 'width';
const secondaryMeasurement = !isHoriz ? 'height' : 'width';
popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
if (placement === secondarySide) {
popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
} else {
popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
}
return popperOffsets;
}
|
javascript
|
function getPopperOffsets(popper, referenceOffsets, placement) {
placement = placement.split('-')[0];
// Get popper node sizes
const popperRect = getOuterSizes(popper);
// Add position, width and height to our offsets object
const popperOffsets = {
width: popperRect.width,
height: popperRect.height
};
// depending by the popper placement we have to compute its offsets slightly differently
const isHoriz = ['right', 'left'].indexOf(placement) !== -1;
const mainSide = isHoriz ? 'top' : 'left';
const secondarySide = isHoriz ? 'left' : 'top';
const measurement = isHoriz ? 'height' : 'width';
const secondaryMeasurement = !isHoriz ? 'height' : 'width';
popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2;
if (placement === secondarySide) {
popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
} else {
popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)];
}
return popperOffsets;
}
|
[
"function",
"getPopperOffsets",
"(",
"popper",
",",
"referenceOffsets",
",",
"placement",
")",
"{",
"placement",
"=",
"placement",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
";",
"const",
"popperRect",
"=",
"getOuterSizes",
"(",
"popper",
")",
";",
"const",
"popperOffsets",
"=",
"{",
"width",
":",
"popperRect",
".",
"width",
",",
"height",
":",
"popperRect",
".",
"height",
"}",
";",
"const",
"isHoriz",
"=",
"[",
"'right'",
",",
"'left'",
"]",
".",
"indexOf",
"(",
"placement",
")",
"!==",
"-",
"1",
";",
"const",
"mainSide",
"=",
"isHoriz",
"?",
"'top'",
":",
"'left'",
";",
"const",
"secondarySide",
"=",
"isHoriz",
"?",
"'left'",
":",
"'top'",
";",
"const",
"measurement",
"=",
"isHoriz",
"?",
"'height'",
":",
"'width'",
";",
"const",
"secondaryMeasurement",
"=",
"!",
"isHoriz",
"?",
"'height'",
":",
"'width'",
";",
"popperOffsets",
"[",
"mainSide",
"]",
"=",
"referenceOffsets",
"[",
"mainSide",
"]",
"+",
"referenceOffsets",
"[",
"measurement",
"]",
"/",
"2",
"-",
"popperRect",
"[",
"measurement",
"]",
"/",
"2",
";",
"if",
"(",
"placement",
"===",
"secondarySide",
")",
"{",
"popperOffsets",
"[",
"secondarySide",
"]",
"=",
"referenceOffsets",
"[",
"secondarySide",
"]",
"-",
"popperRect",
"[",
"secondaryMeasurement",
"]",
";",
"}",
"else",
"{",
"popperOffsets",
"[",
"secondarySide",
"]",
"=",
"referenceOffsets",
"[",
"getOppositePlacement",
"(",
"secondarySide",
")",
"]",
";",
"}",
"return",
"popperOffsets",
";",
"}"
] |
Get offsets to the popper
@method
@memberof Popper.Utils
@param {Object} position - CSS position the Popper will get applied
@param {HTMLElement} popper - the popper element
@param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
@param {String} placement - one of the valid placement options
@returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
|
[
"Get",
"offsets",
"to",
"the",
"popper"
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L710-L737
|
train
|
thomaspark/bootswatch
|
docs/_vendor/popper.js/dist/popper.js
|
isModifierEnabled
|
function isModifierEnabled(modifiers, modifierName) {
return modifiers.some(({ name, enabled }) => enabled && name === modifierName);
}
|
javascript
|
function isModifierEnabled(modifiers, modifierName) {
return modifiers.some(({ name, enabled }) => enabled && name === modifierName);
}
|
[
"function",
"isModifierEnabled",
"(",
"modifiers",
",",
"modifierName",
")",
"{",
"return",
"modifiers",
".",
"some",
"(",
"(",
"{",
"name",
",",
"enabled",
"}",
")",
"=>",
"enabled",
"&&",
"name",
"===",
"modifierName",
")",
";",
"}"
] |
Helper used to know if the given modifier is enabled.
@method
@memberof Popper.Utils
@returns {Boolean}
|
[
"Helper",
"used",
"to",
"know",
"if",
"the",
"given",
"modifier",
"is",
"enabled",
"."
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L870-L872
|
train
|
thomaspark/bootswatch
|
docs/_vendor/popper.js/dist/popper.js
|
getSupportedPropertyName
|
function getSupportedPropertyName(property) {
const prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
const upperProp = property.charAt(0).toUpperCase() + property.slice(1);
for (let i = 0; i < prefixes.length; i++) {
const prefix = prefixes[i];
const toCheck = prefix ? `${prefix}${upperProp}` : property;
if (typeof document.body.style[toCheck] !== 'undefined') {
return toCheck;
}
}
return null;
}
|
javascript
|
function getSupportedPropertyName(property) {
const prefixes = [false, 'ms', 'Webkit', 'Moz', 'O'];
const upperProp = property.charAt(0).toUpperCase() + property.slice(1);
for (let i = 0; i < prefixes.length; i++) {
const prefix = prefixes[i];
const toCheck = prefix ? `${prefix}${upperProp}` : property;
if (typeof document.body.style[toCheck] !== 'undefined') {
return toCheck;
}
}
return null;
}
|
[
"function",
"getSupportedPropertyName",
"(",
"property",
")",
"{",
"const",
"prefixes",
"=",
"[",
"false",
",",
"'ms'",
",",
"'Webkit'",
",",
"'Moz'",
",",
"'O'",
"]",
";",
"const",
"upperProp",
"=",
"property",
".",
"charAt",
"(",
"0",
")",
".",
"toUpperCase",
"(",
")",
"+",
"property",
".",
"slice",
"(",
"1",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"prefixes",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"prefix",
"=",
"prefixes",
"[",
"i",
"]",
";",
"const",
"toCheck",
"=",
"prefix",
"?",
"`",
"${",
"prefix",
"}",
"${",
"upperProp",
"}",
"`",
":",
"property",
";",
"if",
"(",
"typeof",
"document",
".",
"body",
".",
"style",
"[",
"toCheck",
"]",
"!==",
"'undefined'",
")",
"{",
"return",
"toCheck",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Get the prefixed supported property name
@method
@memberof Popper.Utils
@argument {String} property (camelCase)
@returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix)
|
[
"Get",
"the",
"prefixed",
"supported",
"property",
"name"
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L881-L893
|
train
|
thomaspark/bootswatch
|
docs/_vendor/popper.js/dist/popper.js
|
applyStyleOnLoad
|
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
// compute reference element offsets
const referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
const placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
popper.setAttribute('x-placement', placement);
// Apply `position` to popper before anything else because
// without the position applied we can't guarantee correct computations
setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' });
return options;
}
|
javascript
|
function applyStyleOnLoad(reference, popper, options, modifierOptions, state) {
// compute reference element offsets
const referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed);
// compute auto placement, store placement inside the data object,
// modifiers will be able to edit `placement` if needed
// and refer to originalPlacement to know the original value
const placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding);
popper.setAttribute('x-placement', placement);
// Apply `position` to popper before anything else because
// without the position applied we can't guarantee correct computations
setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' });
return options;
}
|
[
"function",
"applyStyleOnLoad",
"(",
"reference",
",",
"popper",
",",
"options",
",",
"modifierOptions",
",",
"state",
")",
"{",
"const",
"referenceOffsets",
"=",
"getReferenceOffsets",
"(",
"state",
",",
"popper",
",",
"reference",
",",
"options",
".",
"positionFixed",
")",
";",
"const",
"placement",
"=",
"computeAutoPlacement",
"(",
"options",
".",
"placement",
",",
"referenceOffsets",
",",
"popper",
",",
"reference",
",",
"options",
".",
"modifiers",
".",
"flip",
".",
"boundariesElement",
",",
"options",
".",
"modifiers",
".",
"flip",
".",
"padding",
")",
";",
"popper",
".",
"setAttribute",
"(",
"'x-placement'",
",",
"placement",
")",
";",
"setStyles",
"(",
"popper",
",",
"{",
"position",
":",
"options",
".",
"positionFixed",
"?",
"'fixed'",
":",
"'absolute'",
"}",
")",
";",
"return",
"options",
";",
"}"
] |
Set the x-placement attribute before everything else because it could be used
to add margins to the popper margins needs to be calculated to get the
correct popper offsets.
@method
@memberof Popper.modifiers
@param {HTMLElement} reference - The reference element used to position the popper
@param {HTMLElement} popper - The HTML element used as popper
@param {Object} options - Popper.js options
|
[
"Set",
"the",
"x",
"-",
"placement",
"attribute",
"before",
"everything",
"else",
"because",
"it",
"could",
"be",
"used",
"to",
"add",
"margins",
"to",
"the",
"popper",
"margins",
"needs",
"to",
"be",
"calculated",
"to",
"get",
"the",
"correct",
"popper",
"offsets",
"."
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L1102-L1118
|
train
|
thomaspark/bootswatch
|
docs/_vendor/popper.js/dist/popper.js
|
parseOffset
|
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {
const offsets = [0, 0];
// Use height if placement is left or right and index is 0 otherwise use width
// in this way the first offset will use an axis and the second one
// will use the other one
const useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;
// Split the offset string to obtain a list of values and operands
// The regex addresses values with the plus or minus sign in front (+10, -20, etc)
const fragments = offset.split(/(\+|\-)/).map(frag => frag.trim());
// Detect if the offset string contains a pair of values or a single one
// they could be separated by comma or space
const divider = fragments.indexOf(find(fragments, frag => frag.search(/,|\s/) !== -1));
if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');
}
// If divider is found, we divide the list of values and operands to divide
// them by ofset X and Y.
const splitRegex = /\s*,\s*|\s+/;
let ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];
// Convert the values with units to absolute pixels to allow our computations
ops = ops.map((op, index) => {
// Most of the units rely on the orientation of the popper
const measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';
let mergeWithPrevious = false;
return op
// This aggregates any `+` or `-` sign that aren't considered operators
// e.g.: 10 + +5 => [10, +, +5]
.reduce((a, b) => {
if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
a[a.length - 1] = b;
mergeWithPrevious = true;
return a;
} else if (mergeWithPrevious) {
a[a.length - 1] += b;
mergeWithPrevious = false;
return a;
} else {
return a.concat(b);
}
}, [])
// Here we convert the string values into number values (in px)
.map(str => toValue(str, measurement, popperOffsets, referenceOffsets));
});
// Loop trough the offsets arrays and execute the operations
ops.forEach((op, index) => {
op.forEach((frag, index2) => {
if (isNumeric(frag)) {
offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
}
});
});
return offsets;
}
|
javascript
|
function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) {
const offsets = [0, 0];
// Use height if placement is left or right and index is 0 otherwise use width
// in this way the first offset will use an axis and the second one
// will use the other one
const useHeight = ['right', 'left'].indexOf(basePlacement) !== -1;
// Split the offset string to obtain a list of values and operands
// The regex addresses values with the plus or minus sign in front (+10, -20, etc)
const fragments = offset.split(/(\+|\-)/).map(frag => frag.trim());
// Detect if the offset string contains a pair of values or a single one
// they could be separated by comma or space
const divider = fragments.indexOf(find(fragments, frag => frag.search(/,|\s/) !== -1));
if (fragments[divider] && fragments[divider].indexOf(',') === -1) {
console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.');
}
// If divider is found, we divide the list of values and operands to divide
// them by ofset X and Y.
const splitRegex = /\s*,\s*|\s+/;
let ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments];
// Convert the values with units to absolute pixels to allow our computations
ops = ops.map((op, index) => {
// Most of the units rely on the orientation of the popper
const measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width';
let mergeWithPrevious = false;
return op
// This aggregates any `+` or `-` sign that aren't considered operators
// e.g.: 10 + +5 => [10, +, +5]
.reduce((a, b) => {
if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) {
a[a.length - 1] = b;
mergeWithPrevious = true;
return a;
} else if (mergeWithPrevious) {
a[a.length - 1] += b;
mergeWithPrevious = false;
return a;
} else {
return a.concat(b);
}
}, [])
// Here we convert the string values into number values (in px)
.map(str => toValue(str, measurement, popperOffsets, referenceOffsets));
});
// Loop trough the offsets arrays and execute the operations
ops.forEach((op, index) => {
op.forEach((frag, index2) => {
if (isNumeric(frag)) {
offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1);
}
});
});
return offsets;
}
|
[
"function",
"parseOffset",
"(",
"offset",
",",
"popperOffsets",
",",
"referenceOffsets",
",",
"basePlacement",
")",
"{",
"const",
"offsets",
"=",
"[",
"0",
",",
"0",
"]",
";",
"const",
"useHeight",
"=",
"[",
"'right'",
",",
"'left'",
"]",
".",
"indexOf",
"(",
"basePlacement",
")",
"!==",
"-",
"1",
";",
"const",
"fragments",
"=",
"offset",
".",
"split",
"(",
"/",
"(\\+|\\-)",
"/",
")",
".",
"map",
"(",
"frag",
"=>",
"frag",
".",
"trim",
"(",
")",
")",
";",
"const",
"divider",
"=",
"fragments",
".",
"indexOf",
"(",
"find",
"(",
"fragments",
",",
"frag",
"=>",
"frag",
".",
"search",
"(",
"/",
",|\\s",
"/",
")",
"!==",
"-",
"1",
")",
")",
";",
"if",
"(",
"fragments",
"[",
"divider",
"]",
"&&",
"fragments",
"[",
"divider",
"]",
".",
"indexOf",
"(",
"','",
")",
"===",
"-",
"1",
")",
"{",
"console",
".",
"warn",
"(",
"'Offsets separated by white space(s) are deprecated, use a comma (,) instead.'",
")",
";",
"}",
"const",
"splitRegex",
"=",
"/",
"\\s*,\\s*|\\s+",
"/",
";",
"let",
"ops",
"=",
"divider",
"!==",
"-",
"1",
"?",
"[",
"fragments",
".",
"slice",
"(",
"0",
",",
"divider",
")",
".",
"concat",
"(",
"[",
"fragments",
"[",
"divider",
"]",
".",
"split",
"(",
"splitRegex",
")",
"[",
"0",
"]",
"]",
")",
",",
"[",
"fragments",
"[",
"divider",
"]",
".",
"split",
"(",
"splitRegex",
")",
"[",
"1",
"]",
"]",
".",
"concat",
"(",
"fragments",
".",
"slice",
"(",
"divider",
"+",
"1",
")",
")",
"]",
":",
"[",
"fragments",
"]",
";",
"ops",
"=",
"ops",
".",
"map",
"(",
"(",
"op",
",",
"index",
")",
"=>",
"{",
"const",
"measurement",
"=",
"(",
"index",
"===",
"1",
"?",
"!",
"useHeight",
":",
"useHeight",
")",
"?",
"'height'",
":",
"'width'",
";",
"let",
"mergeWithPrevious",
"=",
"false",
";",
"return",
"op",
".",
"reduce",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"if",
"(",
"a",
"[",
"a",
".",
"length",
"-",
"1",
"]",
"===",
"''",
"&&",
"[",
"'+'",
",",
"'-'",
"]",
".",
"indexOf",
"(",
"b",
")",
"!==",
"-",
"1",
")",
"{",
"a",
"[",
"a",
".",
"length",
"-",
"1",
"]",
"=",
"b",
";",
"mergeWithPrevious",
"=",
"true",
";",
"return",
"a",
";",
"}",
"else",
"if",
"(",
"mergeWithPrevious",
")",
"{",
"a",
"[",
"a",
".",
"length",
"-",
"1",
"]",
"+=",
"b",
";",
"mergeWithPrevious",
"=",
"false",
";",
"return",
"a",
";",
"}",
"else",
"{",
"return",
"a",
".",
"concat",
"(",
"b",
")",
";",
"}",
"}",
",",
"[",
"]",
")",
".",
"map",
"(",
"str",
"=>",
"toValue",
"(",
"str",
",",
"measurement",
",",
"popperOffsets",
",",
"referenceOffsets",
")",
")",
";",
"}",
")",
";",
"ops",
".",
"forEach",
"(",
"(",
"op",
",",
"index",
")",
"=>",
"{",
"op",
".",
"forEach",
"(",
"(",
"frag",
",",
"index2",
")",
"=>",
"{",
"if",
"(",
"isNumeric",
"(",
"frag",
")",
")",
"{",
"offsets",
"[",
"index",
"]",
"+=",
"frag",
"*",
"(",
"op",
"[",
"index2",
"-",
"1",
"]",
"===",
"'-'",
"?",
"-",
"1",
":",
"1",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"return",
"offsets",
";",
"}"
] |
Parse an `offset` string to extrapolate `x` and `y` numeric offsets.
@function
@memberof {modifiers~offset}
@private
@argument {String} offset
@argument {Object} popperOffsets
@argument {Object} referenceOffsets
@argument {String} basePlacement
@returns {Array} a two cells array with x and y offsets in numbers
|
[
"Parse",
"an",
"offset",
"string",
"to",
"extrapolate",
"x",
"and",
"y",
"numeric",
"offsets",
"."
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/_vendor/popper.js/dist/popper.js#L1617-L1676
|
train
|
thomaspark/bootswatch
|
docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js
|
addElements
|
function addElements(newElements, ownerDocument) {
var elements = html5.elements;
if(typeof elements != 'string'){
elements = elements.join(' ');
}
if(typeof newElements != 'string'){
newElements = newElements.join(' ');
}
html5.elements = elements +' '+ newElements;
shivDocument(ownerDocument);
}
|
javascript
|
function addElements(newElements, ownerDocument) {
var elements = html5.elements;
if(typeof elements != 'string'){
elements = elements.join(' ');
}
if(typeof newElements != 'string'){
newElements = newElements.join(' ');
}
html5.elements = elements +' '+ newElements;
shivDocument(ownerDocument);
}
|
[
"function",
"addElements",
"(",
"newElements",
",",
"ownerDocument",
")",
"{",
"var",
"elements",
"=",
"html5",
".",
"elements",
";",
"if",
"(",
"typeof",
"elements",
"!=",
"'string'",
")",
"{",
"elements",
"=",
"elements",
".",
"join",
"(",
"' '",
")",
";",
"}",
"if",
"(",
"typeof",
"newElements",
"!=",
"'string'",
")",
"{",
"newElements",
"=",
"newElements",
".",
"join",
"(",
"' '",
")",
";",
"}",
"html5",
".",
"elements",
"=",
"elements",
"+",
"' '",
"+",
"newElements",
";",
"shivDocument",
"(",
"ownerDocument",
")",
";",
"}"
] |
Extends the built-in list of html5 elements
@memberOf html5
@param {String|Array} newElements whitespace separated list or array of new element names to shiv
@param {Document} ownerDocument The context document.
|
[
"Extends",
"the",
"built",
"-",
"in",
"list",
"of",
"html5",
"elements"
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js#L91-L101
|
train
|
thomaspark/bootswatch
|
docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js
|
getExpandoData
|
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
|
javascript
|
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
|
[
"function",
"getExpandoData",
"(",
"ownerDocument",
")",
"{",
"var",
"data",
"=",
"expandoData",
"[",
"ownerDocument",
"[",
"expando",
"]",
"]",
";",
"if",
"(",
"!",
"data",
")",
"{",
"data",
"=",
"{",
"}",
";",
"expanID",
"++",
";",
"ownerDocument",
"[",
"expando",
"]",
"=",
"expanID",
";",
"expandoData",
"[",
"expanID",
"]",
"=",
"data",
";",
"}",
"return",
"data",
";",
"}"
] |
Returns the data associated to the given document
@private
@param {Document} ownerDocument The document.
@returns {Object} An object of data.
|
[
"Returns",
"the",
"data",
"associated",
"to",
"the",
"given",
"document"
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js#L109-L118
|
train
|
thomaspark/bootswatch
|
docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js
|
createElement
|
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
// Avoid adding some elements to fragments in IE < 9 because
// * Attributes like `name` or `type` cannot be set/changed once an element
// is inserted into a document/fragment
// * Link elements with `src` attributes that are inaccessible, as with
// a 403 response, will cause the tab/window to crash
// * Script elements appended to fragments will execute when their `src`
// or `text` property is set
return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
}
|
javascript
|
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
// Avoid adding some elements to fragments in IE < 9 because
// * Attributes like `name` or `type` cannot be set/changed once an element
// is inserted into a document/fragment
// * Link elements with `src` attributes that are inaccessible, as with
// a 403 response, will cause the tab/window to crash
// * Script elements appended to fragments will execute when their `src`
// or `text` property is set
return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
}
|
[
"function",
"createElement",
"(",
"nodeName",
",",
"ownerDocument",
",",
"data",
")",
"{",
"if",
"(",
"!",
"ownerDocument",
")",
"{",
"ownerDocument",
"=",
"document",
";",
"}",
"if",
"(",
"supportsUnknownElements",
")",
"{",
"return",
"ownerDocument",
".",
"createElement",
"(",
"nodeName",
")",
";",
"}",
"if",
"(",
"!",
"data",
")",
"{",
"data",
"=",
"getExpandoData",
"(",
"ownerDocument",
")",
";",
"}",
"var",
"node",
";",
"if",
"(",
"data",
".",
"cache",
"[",
"nodeName",
"]",
")",
"{",
"node",
"=",
"data",
".",
"cache",
"[",
"nodeName",
"]",
".",
"cloneNode",
"(",
")",
";",
"}",
"else",
"if",
"(",
"saveClones",
".",
"test",
"(",
"nodeName",
")",
")",
"{",
"node",
"=",
"(",
"data",
".",
"cache",
"[",
"nodeName",
"]",
"=",
"data",
".",
"createElem",
"(",
"nodeName",
")",
")",
".",
"cloneNode",
"(",
")",
";",
"}",
"else",
"{",
"node",
"=",
"data",
".",
"createElem",
"(",
"nodeName",
")",
";",
"}",
"return",
"node",
".",
"canHaveChildren",
"&&",
"!",
"reSkip",
".",
"test",
"(",
"nodeName",
")",
"&&",
"!",
"node",
".",
"tagUrn",
"?",
"data",
".",
"frag",
".",
"appendChild",
"(",
"node",
")",
":",
"node",
";",
"}"
] |
returns a shived element for the given nodeName and document
@memberOf html5
@param {String} nodeName name of the element
@param {Document} ownerDocument The context document.
@returns {Object} The shived element.
|
[
"returns",
"a",
"shived",
"element",
"for",
"the",
"given",
"nodeName",
"and",
"document"
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js#L127-L155
|
train
|
thomaspark/bootswatch
|
docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js
|
createDocumentFragment
|
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i<l;i++){
clone.createElement(elems[i]);
}
return clone;
}
|
javascript
|
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i<l;i++){
clone.createElement(elems[i]);
}
return clone;
}
|
[
"function",
"createDocumentFragment",
"(",
"ownerDocument",
",",
"data",
")",
"{",
"if",
"(",
"!",
"ownerDocument",
")",
"{",
"ownerDocument",
"=",
"document",
";",
"}",
"if",
"(",
"supportsUnknownElements",
")",
"{",
"return",
"ownerDocument",
".",
"createDocumentFragment",
"(",
")",
";",
"}",
"data",
"=",
"data",
"||",
"getExpandoData",
"(",
"ownerDocument",
")",
";",
"var",
"clone",
"=",
"data",
".",
"frag",
".",
"cloneNode",
"(",
")",
",",
"i",
"=",
"0",
",",
"elems",
"=",
"getElements",
"(",
")",
",",
"l",
"=",
"elems",
".",
"length",
";",
"for",
"(",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"clone",
".",
"createElement",
"(",
"elems",
"[",
"i",
"]",
")",
";",
"}",
"return",
"clone",
";",
"}"
] |
returns a shived DocumentFragment for the given document
@memberOf html5
@param {Document} ownerDocument The context document.
@returns {Object} The shived DocumentFragment.
|
[
"returns",
"a",
"shived",
"DocumentFragment",
"for",
"the",
"given",
"document"
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js#L163-L179
|
train
|
thomaspark/bootswatch
|
docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js
|
createWrapper
|
function createWrapper(element) {
var node,
nodes = element.attributes,
index = nodes.length,
wrapper = element.ownerDocument.createElement(shivNamespace + ':' + element.nodeName);
// copy element attributes to the wrapper
while (index--) {
node = nodes[index];
node.specified && wrapper.setAttribute(node.nodeName, node.nodeValue);
}
// copy element styles to the wrapper
wrapper.style.cssText = element.style.cssText;
return wrapper;
}
|
javascript
|
function createWrapper(element) {
var node,
nodes = element.attributes,
index = nodes.length,
wrapper = element.ownerDocument.createElement(shivNamespace + ':' + element.nodeName);
// copy element attributes to the wrapper
while (index--) {
node = nodes[index];
node.specified && wrapper.setAttribute(node.nodeName, node.nodeValue);
}
// copy element styles to the wrapper
wrapper.style.cssText = element.style.cssText;
return wrapper;
}
|
[
"function",
"createWrapper",
"(",
"element",
")",
"{",
"var",
"node",
",",
"nodes",
"=",
"element",
".",
"attributes",
",",
"index",
"=",
"nodes",
".",
"length",
",",
"wrapper",
"=",
"element",
".",
"ownerDocument",
".",
"createElement",
"(",
"shivNamespace",
"+",
"':'",
"+",
"element",
".",
"nodeName",
")",
";",
"while",
"(",
"index",
"--",
")",
"{",
"node",
"=",
"nodes",
"[",
"index",
"]",
";",
"node",
".",
"specified",
"&&",
"wrapper",
".",
"setAttribute",
"(",
"node",
".",
"nodeName",
",",
"node",
".",
"nodeValue",
")",
";",
"}",
"wrapper",
".",
"style",
".",
"cssText",
"=",
"element",
".",
"style",
".",
"cssText",
";",
"return",
"wrapper",
";",
"}"
] |
Creates a printable wrapper for the given element.
@private
@param {Element} element The element.
@returns {Element} The wrapper.
|
[
"Creates",
"a",
"printable",
"wrapper",
"for",
"the",
"given",
"element",
"."
] |
a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd
|
https://github.com/thomaspark/bootswatch/blob/a913e4992dad8f7bf38df2e1d3f4cc6bfe5f26dd/docs/3/bower_components/html5shiv/dist/html5shiv-printshiv.js#L374-L388
|
train
|
spencermountain/compromise
|
src/terms/index.js
|
function(arr, world, refText, refTerms) {
this.terms = arr;
this.world = world || w;
this.refText = refText;
this._refTerms = refTerms;
this.get = n => {
return this.terms[n];
};
//apply getters
let keys = Object.keys(getters);
for (let i = 0; i < keys.length; i++) {
Object.defineProperty(this, keys[i], getters[keys[i]]);
}
}
|
javascript
|
function(arr, world, refText, refTerms) {
this.terms = arr;
this.world = world || w;
this.refText = refText;
this._refTerms = refTerms;
this.get = n => {
return this.terms[n];
};
//apply getters
let keys = Object.keys(getters);
for (let i = 0; i < keys.length; i++) {
Object.defineProperty(this, keys[i], getters[keys[i]]);
}
}
|
[
"function",
"(",
"arr",
",",
"world",
",",
"refText",
",",
"refTerms",
")",
"{",
"this",
".",
"terms",
"=",
"arr",
";",
"this",
".",
"world",
"=",
"world",
"||",
"w",
";",
"this",
".",
"refText",
"=",
"refText",
";",
"this",
".",
"_refTerms",
"=",
"refTerms",
";",
"this",
".",
"get",
"=",
"n",
"=>",
"{",
"return",
"this",
".",
"terms",
"[",
"n",
"]",
";",
"}",
";",
"let",
"keys",
"=",
"Object",
".",
"keys",
"(",
"getters",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"this",
",",
"keys",
"[",
"i",
"]",
",",
"getters",
"[",
"keys",
"[",
"i",
"]",
"]",
")",
";",
"}",
"}"
] |
Terms is an array of Term objects, and methods that wrap around them
|
[
"Terms",
"is",
"an",
"array",
"of",
"Term",
"objects",
"and",
"methods",
"that",
"wrap",
"around",
"them"
] |
526b1cab28a45ccbb430fbf2824db420acd587cf
|
https://github.com/spencermountain/compromise/blob/526b1cab28a45ccbb430fbf2824db420acd587cf/src/terms/index.js#L7-L20
|
train
|
|
spencermountain/compromise
|
src/text/methods/sort/methods.js
|
function(arr) {
arr = arr.sort((a, b) => {
if (a.index > b.index) {
return 1;
}
if (a.index === b.index) {
return 0;
}
return -1;
});
//return ts objects
return arr.map((o) => o.ts);
}
|
javascript
|
function(arr) {
arr = arr.sort((a, b) => {
if (a.index > b.index) {
return 1;
}
if (a.index === b.index) {
return 0;
}
return -1;
});
//return ts objects
return arr.map((o) => o.ts);
}
|
[
"function",
"(",
"arr",
")",
"{",
"arr",
"=",
"arr",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"if",
"(",
"a",
".",
"index",
">",
"b",
".",
"index",
")",
"{",
"return",
"1",
";",
"}",
"if",
"(",
"a",
".",
"index",
"===",
"b",
".",
"index",
")",
"{",
"return",
"0",
";",
"}",
"return",
"-",
"1",
";",
"}",
")",
";",
"return",
"arr",
".",
"map",
"(",
"(",
"o",
")",
"=>",
"o",
".",
"ts",
")",
";",
"}"
] |
perform sort on pre-computed values
|
[
"perform",
"sort",
"on",
"pre",
"-",
"computed",
"values"
] |
526b1cab28a45ccbb430fbf2824db420acd587cf
|
https://github.com/spencermountain/compromise/blob/526b1cab28a45ccbb430fbf2824db420acd587cf/src/text/methods/sort/methods.js#L4-L16
|
train
|
|
spencermountain/compromise
|
src/index.js
|
function(str, lex) {
if (lex) {
w.plugin({
words: lex
});
}
let doc = buildText(str, w);
doc.tagger();
return doc;
}
|
javascript
|
function(str, lex) {
if (lex) {
w.plugin({
words: lex
});
}
let doc = buildText(str, w);
doc.tagger();
return doc;
}
|
[
"function",
"(",
"str",
",",
"lex",
")",
"{",
"if",
"(",
"lex",
")",
"{",
"w",
".",
"plugin",
"(",
"{",
"words",
":",
"lex",
"}",
")",
";",
"}",
"let",
"doc",
"=",
"buildText",
"(",
"str",
",",
"w",
")",
";",
"doc",
".",
"tagger",
"(",
")",
";",
"return",
"doc",
";",
"}"
] |
the main function
|
[
"the",
"main",
"function"
] |
526b1cab28a45ccbb430fbf2824db420acd587cf
|
https://github.com/spencermountain/compromise/blob/526b1cab28a45ccbb430fbf2824db420acd587cf/src/index.js#L10-L19
|
train
|
|
spencermountain/compromise
|
src/index.js
|
function(str, lex) {
if (lex) {
w2.plugin({
words: lex
});
}
let doc = buildText(str, w2);
doc.tagger();
return doc;
}
|
javascript
|
function(str, lex) {
if (lex) {
w2.plugin({
words: lex
});
}
let doc = buildText(str, w2);
doc.tagger();
return doc;
}
|
[
"function",
"(",
"str",
",",
"lex",
")",
"{",
"if",
"(",
"lex",
")",
"{",
"w2",
".",
"plugin",
"(",
"{",
"words",
":",
"lex",
"}",
")",
";",
"}",
"let",
"doc",
"=",
"buildText",
"(",
"str",
",",
"w2",
")",
";",
"doc",
".",
"tagger",
"(",
")",
";",
"return",
"doc",
";",
"}"
] |
this is weird, but it's okay
|
[
"this",
"is",
"weird",
"but",
"it",
"s",
"okay"
] |
526b1cab28a45ccbb430fbf2824db420acd587cf
|
https://github.com/spencermountain/compromise/blob/526b1cab28a45ccbb430fbf2824db420acd587cf/src/index.js#L76-L85
|
train
|
|
google/code-prettify
|
js-modules/prettify.js
|
registerLangHandler
|
function registerLangHandler(handler, fileExtensions) {
for (var i = fileExtensions.length; --i >= 0;) {
var ext = fileExtensions[i];
if (!langHandlerRegistry.hasOwnProperty(ext)) {
langHandlerRegistry[ext] = handler;
} else if (win['console']) {
console['warn']('cannot override language handler %s', ext);
}
}
}
|
javascript
|
function registerLangHandler(handler, fileExtensions) {
for (var i = fileExtensions.length; --i >= 0;) {
var ext = fileExtensions[i];
if (!langHandlerRegistry.hasOwnProperty(ext)) {
langHandlerRegistry[ext] = handler;
} else if (win['console']) {
console['warn']('cannot override language handler %s', ext);
}
}
}
|
[
"function",
"registerLangHandler",
"(",
"handler",
",",
"fileExtensions",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"fileExtensions",
".",
"length",
";",
"--",
"i",
">=",
"0",
";",
")",
"{",
"var",
"ext",
"=",
"fileExtensions",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"langHandlerRegistry",
".",
"hasOwnProperty",
"(",
"ext",
")",
")",
"{",
"langHandlerRegistry",
"[",
"ext",
"]",
"=",
"handler",
";",
"}",
"else",
"if",
"(",
"win",
"[",
"'console'",
"]",
")",
"{",
"console",
"[",
"'warn'",
"]",
"(",
"'cannot override language handler %s'",
",",
"ext",
")",
";",
"}",
"}",
"}"
] |
Register a language handler for the given file extensions.
@param {function (JobT)} handler a function from source code to a list
of decorations. Takes a single argument job which describes the
state of the computation and attaches the decorations to it.
@param {Array.<string>} fileExtensions
|
[
"Register",
"a",
"language",
"handler",
"for",
"the",
"given",
"file",
"extensions",
"."
] |
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
|
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/js-modules/prettify.js#L679-L688
|
train
|
google/code-prettify
|
js-modules/prettify.js
|
$prettyPrintOne
|
function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
/** @type{number|boolean} */
var nl = opt_numberLines || false;
/** @type{string|null} */
var langExtension = opt_langExtension || null;
/** @type{!Element} */
var container = document.createElement('div');
// This could cause images to load and onload listeners to fire.
// E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
// We assume that the inner HTML is from a trusted source.
// The pre-tag is required for IE8 which strips newlines from innerHTML
// when it is injected into a <pre> tag.
// http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
// http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
container = /** @type{!Element} */(container.firstChild);
if (nl) {
numberLines(container, nl, true);
}
/** @type{JobT} */
var job = {
langExtension: langExtension,
numberLines: nl,
sourceNode: container,
pre: 1,
sourceCode: null,
basePos: null,
spans: null,
decorations: null
};
applyDecorator(job);
return container.innerHTML;
}
|
javascript
|
function $prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
/** @type{number|boolean} */
var nl = opt_numberLines || false;
/** @type{string|null} */
var langExtension = opt_langExtension || null;
/** @type{!Element} */
var container = document.createElement('div');
// This could cause images to load and onload listeners to fire.
// E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
// We assume that the inner HTML is from a trusted source.
// The pre-tag is required for IE8 which strips newlines from innerHTML
// when it is injected into a <pre> tag.
// http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
// http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
container = /** @type{!Element} */(container.firstChild);
if (nl) {
numberLines(container, nl, true);
}
/** @type{JobT} */
var job = {
langExtension: langExtension,
numberLines: nl,
sourceNode: container,
pre: 1,
sourceCode: null,
basePos: null,
spans: null,
decorations: null
};
applyDecorator(job);
return container.innerHTML;
}
|
[
"function",
"$prettyPrintOne",
"(",
"sourceCodeHtml",
",",
"opt_langExtension",
",",
"opt_numberLines",
")",
"{",
"var",
"nl",
"=",
"opt_numberLines",
"||",
"false",
";",
"var",
"langExtension",
"=",
"opt_langExtension",
"||",
"null",
";",
"var",
"container",
"=",
"document",
".",
"createElement",
"(",
"'div'",
")",
";",
"container",
".",
"innerHTML",
"=",
"'<pre>'",
"+",
"sourceCodeHtml",
"+",
"'</pre>'",
";",
"container",
"=",
"(",
"container",
".",
"firstChild",
")",
";",
"if",
"(",
"nl",
")",
"{",
"numberLines",
"(",
"container",
",",
"nl",
",",
"true",
")",
";",
"}",
"var",
"job",
"=",
"{",
"langExtension",
":",
"langExtension",
",",
"numberLines",
":",
"nl",
",",
"sourceNode",
":",
"container",
",",
"pre",
":",
"1",
",",
"sourceCode",
":",
"null",
",",
"basePos",
":",
"null",
",",
"spans",
":",
"null",
",",
"decorations",
":",
"null",
"}",
";",
"applyDecorator",
"(",
"job",
")",
";",
"return",
"container",
".",
"innerHTML",
";",
"}"
] |
Pretty print a chunk of code.
@param sourceCodeHtml {string} The HTML to pretty print.
@param opt_langExtension {string} The language name to use.
Typically, a filename extension like 'cpp' or 'java'.
@param opt_numberLines {number|boolean} True to number lines,
or the 1-indexed number of the first line in sourceCodeHtml.
|
[
"Pretty",
"print",
"a",
"chunk",
"of",
"code",
"."
] |
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
|
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/js-modules/prettify.js#L833-L866
|
train
|
google/code-prettify
|
js-modules/run_prettify.js
|
loadStylesheetsFallingBack
|
function loadStylesheetsFallingBack(stylesheets) {
var n = stylesheets.length;
function load(i) {
if (i === n) { return; }
var link = doc.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
if (i + 1 < n) {
// http://pieisgood.org/test/script-link-events/ indicates that many
// versions of IE do not support onerror on <link>s, though
// http://msdn.microsoft.com/en-us/library/ie/ms535848(v=vs.85).aspx
// indicates that recent IEs do support error.
link.error = link.onerror = function () { load(i + 1); };
}
link.href = stylesheets[i];
head.appendChild(link);
}
load(0);
}
|
javascript
|
function loadStylesheetsFallingBack(stylesheets) {
var n = stylesheets.length;
function load(i) {
if (i === n) { return; }
var link = doc.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
if (i + 1 < n) {
// http://pieisgood.org/test/script-link-events/ indicates that many
// versions of IE do not support onerror on <link>s, though
// http://msdn.microsoft.com/en-us/library/ie/ms535848(v=vs.85).aspx
// indicates that recent IEs do support error.
link.error = link.onerror = function () { load(i + 1); };
}
link.href = stylesheets[i];
head.appendChild(link);
}
load(0);
}
|
[
"function",
"loadStylesheetsFallingBack",
"(",
"stylesheets",
")",
"{",
"var",
"n",
"=",
"stylesheets",
".",
"length",
";",
"function",
"load",
"(",
"i",
")",
"{",
"if",
"(",
"i",
"===",
"n",
")",
"{",
"return",
";",
"}",
"var",
"link",
"=",
"doc",
".",
"createElement",
"(",
"'link'",
")",
";",
"link",
".",
"rel",
"=",
"'stylesheet'",
";",
"link",
".",
"type",
"=",
"'text/css'",
";",
"if",
"(",
"i",
"+",
"1",
"<",
"n",
")",
"{",
"link",
".",
"error",
"=",
"link",
".",
"onerror",
"=",
"function",
"(",
")",
"{",
"load",
"(",
"i",
"+",
"1",
")",
";",
"}",
";",
"}",
"link",
".",
"href",
"=",
"stylesheets",
"[",
"i",
"]",
";",
"head",
".",
"appendChild",
"(",
"link",
")",
";",
"}",
"load",
"(",
"0",
")",
";",
"}"
] |
Given a list of URLs to stylesheets, loads the first that loads without triggering an error event.
|
[
"Given",
"a",
"list",
"of",
"URLs",
"to",
"stylesheets",
"loads",
"the",
"first",
"that",
"loads",
"without",
"triggering",
"an",
"error",
"event",
"."
] |
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
|
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/js-modules/run_prettify.js#L122-L140
|
train
|
google/code-prettify
|
js-modules/run_prettify.js
|
onLangsLoaded
|
function onLangsLoaded() {
if (autorun) {
contentLoaded(
function () {
var n = callbacks.length;
var callback = n ? function () {
for (var i = 0; i < n; ++i) {
(function (i) {
win.setTimeout(
function () {
win['exports'][callbacks[i]].apply(win, arguments);
}, 0);
})(i);
}
} : void 0;
prettyPrint(callback);
});
}
}
|
javascript
|
function onLangsLoaded() {
if (autorun) {
contentLoaded(
function () {
var n = callbacks.length;
var callback = n ? function () {
for (var i = 0; i < n; ++i) {
(function (i) {
win.setTimeout(
function () {
win['exports'][callbacks[i]].apply(win, arguments);
}, 0);
})(i);
}
} : void 0;
prettyPrint(callback);
});
}
}
|
[
"function",
"onLangsLoaded",
"(",
")",
"{",
"if",
"(",
"autorun",
")",
"{",
"contentLoaded",
"(",
"function",
"(",
")",
"{",
"var",
"n",
"=",
"callbacks",
".",
"length",
";",
"var",
"callback",
"=",
"n",
"?",
"function",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"++",
"i",
")",
"{",
"(",
"function",
"(",
"i",
")",
"{",
"win",
".",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"win",
"[",
"'exports'",
"]",
"[",
"callbacks",
"[",
"i",
"]",
"]",
".",
"apply",
"(",
"win",
",",
"arguments",
")",
";",
"}",
",",
"0",
")",
";",
"}",
")",
"(",
"i",
")",
";",
"}",
"}",
":",
"void",
"0",
";",
"prettyPrint",
"(",
"callback",
")",
";",
"}",
")",
";",
"}",
"}"
] |
If this script is deferred or async and the document is already loaded we need to wait for language handlers to load before performing any autorun.
|
[
"If",
"this",
"script",
"is",
"deferred",
"or",
"async",
"and",
"the",
"document",
"is",
"already",
"loaded",
"we",
"need",
"to",
"wait",
"for",
"language",
"handlers",
"to",
"load",
"before",
"performing",
"any",
"autorun",
"."
] |
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
|
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/js-modules/run_prettify.js#L240-L258
|
train
|
google/code-prettify
|
tasks/aliases.js
|
syncTimestamp
|
function syncTimestamp(src, dest, timestamp) {
if (timestamp) {
var stat = fs.lstatSync(src);
var fd = fs.openSync(dest, process.platform === 'win32' ? 'r+' : 'r');
fs.futimesSync(fd, stat.atime, stat.mtime);
fs.closeSync(fd);
}
}
|
javascript
|
function syncTimestamp(src, dest, timestamp) {
if (timestamp) {
var stat = fs.lstatSync(src);
var fd = fs.openSync(dest, process.platform === 'win32' ? 'r+' : 'r');
fs.futimesSync(fd, stat.atime, stat.mtime);
fs.closeSync(fd);
}
}
|
[
"function",
"syncTimestamp",
"(",
"src",
",",
"dest",
",",
"timestamp",
")",
"{",
"if",
"(",
"timestamp",
")",
"{",
"var",
"stat",
"=",
"fs",
".",
"lstatSync",
"(",
"src",
")",
";",
"var",
"fd",
"=",
"fs",
".",
"openSync",
"(",
"dest",
",",
"process",
".",
"platform",
"===",
"'win32'",
"?",
"'r+'",
":",
"'r'",
")",
";",
"fs",
".",
"futimesSync",
"(",
"fd",
",",
"stat",
".",
"atime",
",",
"stat",
".",
"mtime",
")",
";",
"fs",
".",
"closeSync",
"(",
"fd",
")",
";",
"}",
"}"
] |
Copy timestamp from source to destination file.
@param {string} src
@param {string} dest
@param {boolean} timestamp
|
[
"Copy",
"timestamp",
"from",
"source",
"to",
"destination",
"file",
"."
] |
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
|
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/tasks/aliases.js#L21-L28
|
train
|
google/code-prettify
|
tasks/aliases.js
|
syncMod
|
function syncMod(src, dest, mode) {
if (mode !== false) {
fs.chmodSync(dest, (mode === true) ? fs.lstatSync(src).mode : mode);
}
}
|
javascript
|
function syncMod(src, dest, mode) {
if (mode !== false) {
fs.chmodSync(dest, (mode === true) ? fs.lstatSync(src).mode : mode);
}
}
|
[
"function",
"syncMod",
"(",
"src",
",",
"dest",
",",
"mode",
")",
"{",
"if",
"(",
"mode",
"!==",
"false",
")",
"{",
"fs",
".",
"chmodSync",
"(",
"dest",
",",
"(",
"mode",
"===",
"true",
")",
"?",
"fs",
".",
"lstatSync",
"(",
"src",
")",
".",
"mode",
":",
"mode",
")",
";",
"}",
"}"
] |
Copy file mode from source to destination.
@param {string} src
@param {string} dest
@param {boolean|number} mode
|
[
"Copy",
"file",
"mode",
"from",
"source",
"to",
"destination",
"."
] |
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
|
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/tasks/aliases.js#L36-L40
|
train
|
google/code-prettify
|
js-modules/numberLines.js
|
breakAfter
|
function breakAfter(lineEndNode) {
// If there's nothing to the right, then we can skip ending the line
// here, and move root-wards since splitting just before an end-tag
// would require us to create a bunch of empty copies.
while (!lineEndNode.nextSibling) {
lineEndNode = lineEndNode.parentNode;
if (!lineEndNode) { return; }
}
function breakLeftOf(limit, copy) {
// Clone shallowly if this node needs to be on both sides of the break.
var rightSide = copy ? limit.cloneNode(false) : limit;
var parent = limit.parentNode;
if (parent) {
// We clone the parent chain.
// This helps us resurrect important styling elements that cross lines.
// E.g. in <i>Foo<br>Bar</i>
// should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
var parentClone = breakLeftOf(parent, 1);
// Move the clone and everything to the right of the original
// onto the cloned parent.
var next = limit.nextSibling;
parentClone.appendChild(rightSide);
for (var sibling = next; sibling; sibling = next) {
next = sibling.nextSibling;
parentClone.appendChild(sibling);
}
}
return rightSide;
}
var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
// Walk the parent chain until we reach an unattached LI.
for (var parent;
// Check nodeType since IE invents document fragments.
(parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
copiedListItem = parent;
}
// Put it on the list of lines for later processing.
listItems.push(copiedListItem);
}
|
javascript
|
function breakAfter(lineEndNode) {
// If there's nothing to the right, then we can skip ending the line
// here, and move root-wards since splitting just before an end-tag
// would require us to create a bunch of empty copies.
while (!lineEndNode.nextSibling) {
lineEndNode = lineEndNode.parentNode;
if (!lineEndNode) { return; }
}
function breakLeftOf(limit, copy) {
// Clone shallowly if this node needs to be on both sides of the break.
var rightSide = copy ? limit.cloneNode(false) : limit;
var parent = limit.parentNode;
if (parent) {
// We clone the parent chain.
// This helps us resurrect important styling elements that cross lines.
// E.g. in <i>Foo<br>Bar</i>
// should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
var parentClone = breakLeftOf(parent, 1);
// Move the clone and everything to the right of the original
// onto the cloned parent.
var next = limit.nextSibling;
parentClone.appendChild(rightSide);
for (var sibling = next; sibling; sibling = next) {
next = sibling.nextSibling;
parentClone.appendChild(sibling);
}
}
return rightSide;
}
var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
// Walk the parent chain until we reach an unattached LI.
for (var parent;
// Check nodeType since IE invents document fragments.
(parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
copiedListItem = parent;
}
// Put it on the list of lines for later processing.
listItems.push(copiedListItem);
}
|
[
"function",
"breakAfter",
"(",
"lineEndNode",
")",
"{",
"while",
"(",
"!",
"lineEndNode",
".",
"nextSibling",
")",
"{",
"lineEndNode",
"=",
"lineEndNode",
".",
"parentNode",
";",
"if",
"(",
"!",
"lineEndNode",
")",
"{",
"return",
";",
"}",
"}",
"function",
"breakLeftOf",
"(",
"limit",
",",
"copy",
")",
"{",
"var",
"rightSide",
"=",
"copy",
"?",
"limit",
".",
"cloneNode",
"(",
"false",
")",
":",
"limit",
";",
"var",
"parent",
"=",
"limit",
".",
"parentNode",
";",
"if",
"(",
"parent",
")",
"{",
"var",
"parentClone",
"=",
"breakLeftOf",
"(",
"parent",
",",
"1",
")",
";",
"var",
"next",
"=",
"limit",
".",
"nextSibling",
";",
"parentClone",
".",
"appendChild",
"(",
"rightSide",
")",
";",
"for",
"(",
"var",
"sibling",
"=",
"next",
";",
"sibling",
";",
"sibling",
"=",
"next",
")",
"{",
"next",
"=",
"sibling",
".",
"nextSibling",
";",
"parentClone",
".",
"appendChild",
"(",
"sibling",
")",
";",
"}",
"}",
"return",
"rightSide",
";",
"}",
"var",
"copiedListItem",
"=",
"breakLeftOf",
"(",
"lineEndNode",
".",
"nextSibling",
",",
"0",
")",
";",
"for",
"(",
"var",
"parent",
";",
"(",
"parent",
"=",
"copiedListItem",
".",
"parentNode",
")",
"&&",
"parent",
".",
"nodeType",
"===",
"1",
";",
")",
"{",
"copiedListItem",
"=",
"parent",
";",
"}",
"listItems",
".",
"push",
"(",
"copiedListItem",
")",
";",
"}"
] |
Split a line after the given node.
|
[
"Split",
"a",
"line",
"after",
"the",
"given",
"node",
"."
] |
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
|
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/js-modules/numberLines.js#L66-L107
|
train
|
google/code-prettify
|
tasks/lib/lang-aliases.js
|
createSandbox
|
function createSandbox() {
// collect registered language extensions
var sandbox = {};
sandbox.extensions = [];
// mock prettify.js API
sandbox.window = {};
sandbox.window.PR = sandbox.PR = {
registerLangHandler: function (handler, exts) {
sandbox.extensions = sandbox.extensions.concat(exts);
},
createSimpleLexer: function (sPatterns, fPatterns) {
return function (job) {};
},
sourceDecorator: function (options) {
return function (job) {};
},
prettyPrintOne: function (src, lang, ln) {
return src;
},
prettyPrint: function (done, root) {},
PR_ATTRIB_NAME: 'atn',
PR_ATTRIB_VALUE: 'atv',
PR_COMMENT: 'com',
PR_DECLARATION: 'dec',
PR_KEYWORD: 'kwd',
PR_LITERAL: 'lit',
PR_NOCODE: 'nocode',
PR_PLAIN: 'pln',
PR_PUNCTUATION: 'pun',
PR_SOURCE: 'src',
PR_STRING: 'str',
PR_TAG: 'tag',
PR_TYPE: 'typ'
};
return sandbox;
}
|
javascript
|
function createSandbox() {
// collect registered language extensions
var sandbox = {};
sandbox.extensions = [];
// mock prettify.js API
sandbox.window = {};
sandbox.window.PR = sandbox.PR = {
registerLangHandler: function (handler, exts) {
sandbox.extensions = sandbox.extensions.concat(exts);
},
createSimpleLexer: function (sPatterns, fPatterns) {
return function (job) {};
},
sourceDecorator: function (options) {
return function (job) {};
},
prettyPrintOne: function (src, lang, ln) {
return src;
},
prettyPrint: function (done, root) {},
PR_ATTRIB_NAME: 'atn',
PR_ATTRIB_VALUE: 'atv',
PR_COMMENT: 'com',
PR_DECLARATION: 'dec',
PR_KEYWORD: 'kwd',
PR_LITERAL: 'lit',
PR_NOCODE: 'nocode',
PR_PLAIN: 'pln',
PR_PUNCTUATION: 'pun',
PR_SOURCE: 'src',
PR_STRING: 'str',
PR_TAG: 'tag',
PR_TYPE: 'typ'
};
return sandbox;
}
|
[
"function",
"createSandbox",
"(",
")",
"{",
"var",
"sandbox",
"=",
"{",
"}",
";",
"sandbox",
".",
"extensions",
"=",
"[",
"]",
";",
"sandbox",
".",
"window",
"=",
"{",
"}",
";",
"sandbox",
".",
"window",
".",
"PR",
"=",
"sandbox",
".",
"PR",
"=",
"{",
"registerLangHandler",
":",
"function",
"(",
"handler",
",",
"exts",
")",
"{",
"sandbox",
".",
"extensions",
"=",
"sandbox",
".",
"extensions",
".",
"concat",
"(",
"exts",
")",
";",
"}",
",",
"createSimpleLexer",
":",
"function",
"(",
"sPatterns",
",",
"fPatterns",
")",
"{",
"return",
"function",
"(",
"job",
")",
"{",
"}",
";",
"}",
",",
"sourceDecorator",
":",
"function",
"(",
"options",
")",
"{",
"return",
"function",
"(",
"job",
")",
"{",
"}",
";",
"}",
",",
"prettyPrintOne",
":",
"function",
"(",
"src",
",",
"lang",
",",
"ln",
")",
"{",
"return",
"src",
";",
"}",
",",
"prettyPrint",
":",
"function",
"(",
"done",
",",
"root",
")",
"{",
"}",
",",
"PR_ATTRIB_NAME",
":",
"'atn'",
",",
"PR_ATTRIB_VALUE",
":",
"'atv'",
",",
"PR_COMMENT",
":",
"'com'",
",",
"PR_DECLARATION",
":",
"'dec'",
",",
"PR_KEYWORD",
":",
"'kwd'",
",",
"PR_LITERAL",
":",
"'lit'",
",",
"PR_NOCODE",
":",
"'nocode'",
",",
"PR_PLAIN",
":",
"'pln'",
",",
"PR_PUNCTUATION",
":",
"'pun'",
",",
"PR_SOURCE",
":",
"'src'",
",",
"PR_STRING",
":",
"'str'",
",",
"PR_TAG",
":",
"'tag'",
",",
"PR_TYPE",
":",
"'typ'",
"}",
";",
"return",
"sandbox",
";",
"}"
] |
Returns a mock object PR of the prettify API. This is used to collect
registered language file extensions.
@return {Object} PR object with an additional `extensions` property.
|
[
"Returns",
"a",
"mock",
"object",
"PR",
"of",
"the",
"prettify",
"API",
".",
"This",
"is",
"used",
"to",
"collect",
"registered",
"language",
"file",
"extensions",
"."
] |
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
|
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/tasks/lib/lang-aliases.js#L19-L54
|
train
|
google/code-prettify
|
tasks/lib/lang-aliases.js
|
runLanguageHandler
|
function runLanguageHandler(src) {
// execute source code in an isolated sandbox with a mock PR object
var sandbox = createSandbox();
vm.runInNewContext(fs.readFileSync(src), sandbox, {
filename: src
});
// language name
var lang = path.basename(src, path.extname(src)).replace(/^lang-/, '');
// collect and filter extensions
var exts = sandbox.extensions.map(function (ext) {
// case-insensitive names
return ext.toLowerCase();
}).filter(function (ext) {
// skip self, and internal names like foo-bar-baz or lang.foo
return ext !== lang && !/\W/.test(ext);
});
exts = exts.filter(function (ext, pos) {
// remove duplicates
return exts.indexOf(ext) === pos;
});
return exts;
}
|
javascript
|
function runLanguageHandler(src) {
// execute source code in an isolated sandbox with a mock PR object
var sandbox = createSandbox();
vm.runInNewContext(fs.readFileSync(src), sandbox, {
filename: src
});
// language name
var lang = path.basename(src, path.extname(src)).replace(/^lang-/, '');
// collect and filter extensions
var exts = sandbox.extensions.map(function (ext) {
// case-insensitive names
return ext.toLowerCase();
}).filter(function (ext) {
// skip self, and internal names like foo-bar-baz or lang.foo
return ext !== lang && !/\W/.test(ext);
});
exts = exts.filter(function (ext, pos) {
// remove duplicates
return exts.indexOf(ext) === pos;
});
return exts;
}
|
[
"function",
"runLanguageHandler",
"(",
"src",
")",
"{",
"var",
"sandbox",
"=",
"createSandbox",
"(",
")",
";",
"vm",
".",
"runInNewContext",
"(",
"fs",
".",
"readFileSync",
"(",
"src",
")",
",",
"sandbox",
",",
"{",
"filename",
":",
"src",
"}",
")",
";",
"var",
"lang",
"=",
"path",
".",
"basename",
"(",
"src",
",",
"path",
".",
"extname",
"(",
"src",
")",
")",
".",
"replace",
"(",
"/",
"^lang-",
"/",
",",
"''",
")",
";",
"var",
"exts",
"=",
"sandbox",
".",
"extensions",
".",
"map",
"(",
"function",
"(",
"ext",
")",
"{",
"return",
"ext",
".",
"toLowerCase",
"(",
")",
";",
"}",
")",
".",
"filter",
"(",
"function",
"(",
"ext",
")",
"{",
"return",
"ext",
"!==",
"lang",
"&&",
"!",
"/",
"\\W",
"/",
".",
"test",
"(",
"ext",
")",
";",
"}",
")",
";",
"exts",
"=",
"exts",
".",
"filter",
"(",
"function",
"(",
"ext",
",",
"pos",
")",
"{",
"return",
"exts",
".",
"indexOf",
"(",
"ext",
")",
"===",
"pos",
";",
"}",
")",
";",
"return",
"exts",
";",
"}"
] |
Runs a language handler file under VM to collect extensions.
Given a lang-*.js file, runs the language handler in a fake context where
PR.registerLangHandler collects handler names without doing anything else.
This is later used to makes copies of the JS extension under all its
registered language names lang-<EXT>.js
@param {string} src path to lang-xxx.js language handler
@return {Array<string>} registered file extensions
|
[
"Runs",
"a",
"language",
"handler",
"file",
"under",
"VM",
"to",
"collect",
"extensions",
"."
] |
e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc
|
https://github.com/google/code-prettify/blob/e14ed1c3c40f78fca2a11af4cb0fa251f6f997fc/tasks/lib/lang-aliases.js#L67-L90
|
train
|
avajs/ava
|
lib/babel-pipeline.js
|
makeValueChecker
|
function makeValueChecker(ref) {
const expected = require(ref);
return ({value}) => value === expected || value === expected.default;
}
|
javascript
|
function makeValueChecker(ref) {
const expected = require(ref);
return ({value}) => value === expected || value === expected.default;
}
|
[
"function",
"makeValueChecker",
"(",
"ref",
")",
"{",
"const",
"expected",
"=",
"require",
"(",
"ref",
")",
";",
"return",
"(",
"{",
"value",
"}",
")",
"=>",
"value",
"===",
"expected",
"||",
"value",
"===",
"expected",
".",
"default",
";",
"}"
] |
Compare actual values rather than file paths, which should be more reliable.
|
[
"Compare",
"actual",
"values",
"rather",
"than",
"file",
"paths",
"which",
"should",
"be",
"more",
"reliable",
"."
] |
08e99e516e13af75d3ebe70f12194a89b610217c
|
https://github.com/avajs/ava/blob/08e99e516e13af75d3ebe70f12194a89b610217c/lib/babel-pipeline.js#L64-L67
|
train
|
shipshapecode/shepherd
|
src/js/utils/dom.js
|
getElementFromObject
|
function getElementFromObject(attachTo) {
const op = attachTo.element;
if (op instanceof HTMLElement) {
return op;
}
return document.querySelector(op);
}
|
javascript
|
function getElementFromObject(attachTo) {
const op = attachTo.element;
if (op instanceof HTMLElement) {
return op;
}
return document.querySelector(op);
}
|
[
"function",
"getElementFromObject",
"(",
"attachTo",
")",
"{",
"const",
"op",
"=",
"attachTo",
".",
"element",
";",
"if",
"(",
"op",
"instanceof",
"HTMLElement",
")",
"{",
"return",
"op",
";",
"}",
"return",
"document",
".",
"querySelector",
"(",
"op",
")",
";",
"}"
] |
Get the element from an option object
@method getElementFromObject
@param Object attachTo
@returns {Element}
@private
|
[
"Get",
"the",
"element",
"from",
"an",
"option",
"object"
] |
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
|
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/dom.js#L22-L30
|
train
|
shipshapecode/shepherd
|
src/js/utils/dom.js
|
getElementForStep
|
function getElementForStep(step) {
const { options: { attachTo } } = step;
if (!attachTo) {
return null;
}
const type = typeof attachTo;
let element;
if (type === 'string') {
element = getElementFromString(attachTo);
} else if (type === 'object') {
element = getElementFromObject(attachTo);
} else {
/* istanbul ignore next: cannot test undefined attachTo, but it does work! */
element = null;
}
return element;
}
|
javascript
|
function getElementForStep(step) {
const { options: { attachTo } } = step;
if (!attachTo) {
return null;
}
const type = typeof attachTo;
let element;
if (type === 'string') {
element = getElementFromString(attachTo);
} else if (type === 'object') {
element = getElementFromObject(attachTo);
} else {
/* istanbul ignore next: cannot test undefined attachTo, but it does work! */
element = null;
}
return element;
}
|
[
"function",
"getElementForStep",
"(",
"step",
")",
"{",
"const",
"{",
"options",
":",
"{",
"attachTo",
"}",
"}",
"=",
"step",
";",
"if",
"(",
"!",
"attachTo",
")",
"{",
"return",
"null",
";",
"}",
"const",
"type",
"=",
"typeof",
"attachTo",
";",
"let",
"element",
";",
"if",
"(",
"type",
"===",
"'string'",
")",
"{",
"element",
"=",
"getElementFromString",
"(",
"attachTo",
")",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'object'",
")",
"{",
"element",
"=",
"getElementFromObject",
"(",
"attachTo",
")",
";",
"}",
"else",
"{",
"element",
"=",
"null",
";",
"}",
"return",
"element",
";",
"}"
] |
Return the element for a step
@method getElementForStep
@param step step the step to get an element for
@returns {Element} the element for this step
@private
|
[
"Return",
"the",
"element",
"for",
"a",
"step"
] |
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
|
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/dom.js#L40-L60
|
train
|
shipshapecode/shepherd
|
src/js/utils/general.js
|
_makeTippyInstance
|
function _makeTippyInstance(attachToOptions) {
if (!attachToOptions.element) {
return _makeCenteredTippy.call(this);
}
const tippyOptions = _makeAttachedTippyOptions.call(this, attachToOptions);
return tippy(attachToOptions.element, tippyOptions);
}
|
javascript
|
function _makeTippyInstance(attachToOptions) {
if (!attachToOptions.element) {
return _makeCenteredTippy.call(this);
}
const tippyOptions = _makeAttachedTippyOptions.call(this, attachToOptions);
return tippy(attachToOptions.element, tippyOptions);
}
|
[
"function",
"_makeTippyInstance",
"(",
"attachToOptions",
")",
"{",
"if",
"(",
"!",
"attachToOptions",
".",
"element",
")",
"{",
"return",
"_makeCenteredTippy",
".",
"call",
"(",
"this",
")",
";",
"}",
"const",
"tippyOptions",
"=",
"_makeAttachedTippyOptions",
".",
"call",
"(",
"this",
",",
"attachToOptions",
")",
";",
"return",
"tippy",
"(",
"attachToOptions",
".",
"element",
",",
"tippyOptions",
")",
";",
"}"
] |
Generates a `Tippy` instance from a set of base `attachTo` options
@return {tippy} The final tippy instance
@private
|
[
"Generates",
"a",
"Tippy",
"instance",
"from",
"a",
"set",
"of",
"base",
"attachTo",
"options"
] |
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
|
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/general.js#L192-L200
|
train
|
shipshapecode/shepherd
|
src/js/utils/general.js
|
_makeAttachedTippyOptions
|
function _makeAttachedTippyOptions(attachToOptions) {
const resultingTippyOptions = {
content: this.el,
flipOnUpdate: true,
placement: attachToOptions.on || 'right'
};
Object.assign(resultingTippyOptions, this.options.tippyOptions);
if (this.options.title) {
const existingTheme = resultingTippyOptions.theme;
resultingTippyOptions.theme = existingTheme ? `${existingTheme} shepherd-has-title` : 'shepherd-has-title';
}
if (this.options.tippyOptions && this.options.tippyOptions.popperOptions) {
Object.assign(defaultPopperOptions, this.options.tippyOptions.popperOptions);
}
resultingTippyOptions.popperOptions = defaultPopperOptions;
return resultingTippyOptions;
}
|
javascript
|
function _makeAttachedTippyOptions(attachToOptions) {
const resultingTippyOptions = {
content: this.el,
flipOnUpdate: true,
placement: attachToOptions.on || 'right'
};
Object.assign(resultingTippyOptions, this.options.tippyOptions);
if (this.options.title) {
const existingTheme = resultingTippyOptions.theme;
resultingTippyOptions.theme = existingTheme ? `${existingTheme} shepherd-has-title` : 'shepherd-has-title';
}
if (this.options.tippyOptions && this.options.tippyOptions.popperOptions) {
Object.assign(defaultPopperOptions, this.options.tippyOptions.popperOptions);
}
resultingTippyOptions.popperOptions = defaultPopperOptions;
return resultingTippyOptions;
}
|
[
"function",
"_makeAttachedTippyOptions",
"(",
"attachToOptions",
")",
"{",
"const",
"resultingTippyOptions",
"=",
"{",
"content",
":",
"this",
".",
"el",
",",
"flipOnUpdate",
":",
"true",
",",
"placement",
":",
"attachToOptions",
".",
"on",
"||",
"'right'",
"}",
";",
"Object",
".",
"assign",
"(",
"resultingTippyOptions",
",",
"this",
".",
"options",
".",
"tippyOptions",
")",
";",
"if",
"(",
"this",
".",
"options",
".",
"title",
")",
"{",
"const",
"existingTheme",
"=",
"resultingTippyOptions",
".",
"theme",
";",
"resultingTippyOptions",
".",
"theme",
"=",
"existingTheme",
"?",
"`",
"${",
"existingTheme",
"}",
"`",
":",
"'shepherd-has-title'",
";",
"}",
"if",
"(",
"this",
".",
"options",
".",
"tippyOptions",
"&&",
"this",
".",
"options",
".",
"tippyOptions",
".",
"popperOptions",
")",
"{",
"Object",
".",
"assign",
"(",
"defaultPopperOptions",
",",
"this",
".",
"options",
".",
"tippyOptions",
".",
"popperOptions",
")",
";",
"}",
"resultingTippyOptions",
".",
"popperOptions",
"=",
"defaultPopperOptions",
";",
"return",
"resultingTippyOptions",
";",
"}"
] |
Generates the hash of options that will be passed to `Tippy` instances
target an element in the DOM.
@param {Object} attachToOptions The local `attachTo` options
@return {Object} The final tippy options object
@private
|
[
"Generates",
"the",
"hash",
"of",
"options",
"that",
"will",
"be",
"passed",
"to",
"Tippy",
"instances",
"target",
"an",
"element",
"in",
"the",
"DOM",
"."
] |
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
|
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/general.js#L210-L231
|
train
|
shipshapecode/shepherd
|
src/js/utils/bind.js
|
_setupAdvanceOnHandler
|
function _setupAdvanceOnHandler(selector) {
return (event) => {
if (this.isOpen()) {
const targetIsEl = this.el && event.target === this.el;
const targetIsSelector = !isUndefined(selector) && event.target.matches(selector);
if (targetIsSelector || targetIsEl) {
this.tour.next();
}
}
};
}
|
javascript
|
function _setupAdvanceOnHandler(selector) {
return (event) => {
if (this.isOpen()) {
const targetIsEl = this.el && event.target === this.el;
const targetIsSelector = !isUndefined(selector) && event.target.matches(selector);
if (targetIsSelector || targetIsEl) {
this.tour.next();
}
}
};
}
|
[
"function",
"_setupAdvanceOnHandler",
"(",
"selector",
")",
"{",
"return",
"(",
"event",
")",
"=>",
"{",
"if",
"(",
"this",
".",
"isOpen",
"(",
")",
")",
"{",
"const",
"targetIsEl",
"=",
"this",
".",
"el",
"&&",
"event",
".",
"target",
"===",
"this",
".",
"el",
";",
"const",
"targetIsSelector",
"=",
"!",
"isUndefined",
"(",
"selector",
")",
"&&",
"event",
".",
"target",
".",
"matches",
"(",
"selector",
")",
";",
"if",
"(",
"targetIsSelector",
"||",
"targetIsEl",
")",
"{",
"this",
".",
"tour",
".",
"next",
"(",
")",
";",
"}",
"}",
"}",
";",
"}"
] |
Sets up the handler to determine if we should advance the tour
@private
|
[
"Sets",
"up",
"the",
"handler",
"to",
"determine",
"if",
"we",
"should",
"advance",
"the",
"tour"
] |
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
|
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/bind.js#L8-L19
|
train
|
shipshapecode/shepherd
|
src/js/utils/modal.js
|
positionModalOpening
|
function positionModalOpening(targetElement, openingElement) {
if (targetElement.getBoundingClientRect && openingElement instanceof SVGElement) {
const { x, y, width, height, left, top } = targetElement.getBoundingClientRect();
// getBoundingClientRect is not consistent. Some browsers use x and y, while others use left and top
_setAttributes(openingElement, { x: x || left, y: y || top, width, height });
}
}
|
javascript
|
function positionModalOpening(targetElement, openingElement) {
if (targetElement.getBoundingClientRect && openingElement instanceof SVGElement) {
const { x, y, width, height, left, top } = targetElement.getBoundingClientRect();
// getBoundingClientRect is not consistent. Some browsers use x and y, while others use left and top
_setAttributes(openingElement, { x: x || left, y: y || top, width, height });
}
}
|
[
"function",
"positionModalOpening",
"(",
"targetElement",
",",
"openingElement",
")",
"{",
"if",
"(",
"targetElement",
".",
"getBoundingClientRect",
"&&",
"openingElement",
"instanceof",
"SVGElement",
")",
"{",
"const",
"{",
"x",
",",
"y",
",",
"width",
",",
"height",
",",
"left",
",",
"top",
"}",
"=",
"targetElement",
".",
"getBoundingClientRect",
"(",
")",
";",
"_setAttributes",
"(",
"openingElement",
",",
"{",
"x",
":",
"x",
"||",
"left",
",",
"y",
":",
"y",
"||",
"top",
",",
"width",
",",
"height",
"}",
")",
";",
"}",
"}"
] |
Uses the bounds of the element we want the opening overtop of to set the dimensions of the opening and position it
@param {HTMLElement} targetElement The element the opening will expose
@param {SVGElement} openingElement The svg mask for the opening
|
[
"Uses",
"the",
"bounds",
"of",
"the",
"element",
"we",
"want",
"the",
"opening",
"overtop",
"of",
"to",
"set",
"the",
"dimensions",
"of",
"the",
"opening",
"and",
"position",
"it"
] |
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
|
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/modal.js#L131-L138
|
train
|
shipshapecode/shepherd
|
src/js/utils/modal.js
|
toggleShepherdModalClass
|
function toggleShepherdModalClass(currentElement) {
const shepherdModal = document.querySelector(`${classNames.modalTarget}`);
if (shepherdModal) {
shepherdModal.classList.remove(classNames.modalTarget);
}
currentElement.classList.add(classNames.modalTarget);
}
|
javascript
|
function toggleShepherdModalClass(currentElement) {
const shepherdModal = document.querySelector(`${classNames.modalTarget}`);
if (shepherdModal) {
shepherdModal.classList.remove(classNames.modalTarget);
}
currentElement.classList.add(classNames.modalTarget);
}
|
[
"function",
"toggleShepherdModalClass",
"(",
"currentElement",
")",
"{",
"const",
"shepherdModal",
"=",
"document",
".",
"querySelector",
"(",
"`",
"${",
"classNames",
".",
"modalTarget",
"}",
"`",
")",
";",
"if",
"(",
"shepherdModal",
")",
"{",
"shepherdModal",
".",
"classList",
".",
"remove",
"(",
"classNames",
".",
"modalTarget",
")",
";",
"}",
"currentElement",
".",
"classList",
".",
"add",
"(",
"classNames",
".",
"modalTarget",
")",
";",
"}"
] |
Remove any leftover modal target classes and add the modal target class to the currentElement
@param {HTMLElement} currentElement The element for the current step
|
[
"Remove",
"any",
"leftover",
"modal",
"target",
"classes",
"and",
"add",
"the",
"modal",
"target",
"class",
"to",
"the",
"currentElement"
] |
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
|
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/modal.js#L167-L175
|
train
|
shipshapecode/shepherd
|
src/js/utils/modal.js
|
_setAttributes
|
function _setAttributes(el, attrs) {
Object.keys(attrs).forEach((key) => {
el.setAttribute(key, attrs[key]);
});
}
|
javascript
|
function _setAttributes(el, attrs) {
Object.keys(attrs).forEach((key) => {
el.setAttribute(key, attrs[key]);
});
}
|
[
"function",
"_setAttributes",
"(",
"el",
",",
"attrs",
")",
"{",
"Object",
".",
"keys",
"(",
"attrs",
")",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"el",
".",
"setAttribute",
"(",
"key",
",",
"attrs",
"[",
"key",
"]",
")",
";",
"}",
")",
";",
"}"
] |
Set multiple attributes on an element, via a hash
@param {HTMLElement|SVGElement} el The element to set the attributes on
@param {Object} attrs A hash of key value pairs for attributes to set
@private
|
[
"Set",
"multiple",
"attributes",
"on",
"an",
"element",
"via",
"a",
"hash"
] |
0cb1c63fb07b58796358f6d33da5f6405e2b05f4
|
https://github.com/shipshapecode/shepherd/blob/0cb1c63fb07b58796358f6d33da5f6405e2b05f4/src/js/utils/modal.js#L183-L187
|
train
|
markdown-it/markdown-it
|
lib/common/utils.js
|
arrayReplaceAt
|
function arrayReplaceAt(src, pos, newElements) {
return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1));
}
|
javascript
|
function arrayReplaceAt(src, pos, newElements) {
return [].concat(src.slice(0, pos), newElements, src.slice(pos + 1));
}
|
[
"function",
"arrayReplaceAt",
"(",
"src",
",",
"pos",
",",
"newElements",
")",
"{",
"return",
"[",
"]",
".",
"concat",
"(",
"src",
".",
"slice",
"(",
"0",
",",
"pos",
")",
",",
"newElements",
",",
"src",
".",
"slice",
"(",
"pos",
"+",
"1",
")",
")",
";",
"}"
] |
Remove element from array and put another array at those position. Useful for some operations with tokens
|
[
"Remove",
"element",
"from",
"array",
"and",
"put",
"another",
"array",
"at",
"those",
"position",
".",
"Useful",
"for",
"some",
"operations",
"with",
"tokens"
] |
ba6830ba13fb92953a91fb90318964ccd15b82c4
|
https://github.com/markdown-it/markdown-it/blob/ba6830ba13fb92953a91fb90318964ccd15b82c4/lib/common/utils.js#L38-L40
|
train
|
zalmoxisus/redux-devtools-extension
|
src/app/middlewares/api.js
|
messaging
|
function messaging(request, sender, sendResponse) {
let tabId = getId(sender);
if (!tabId) return;
if (sender.frameId) tabId = `${tabId}-${sender.frameId}`;
if (request.type === 'STOP') {
if (!Object.keys(window.store.getState().instances.connections).length) {
window.store.dispatch({ type: DISCONNECTED });
}
return;
}
if (request.type === 'OPEN_OPTIONS') {
chrome.runtime.openOptionsPage();
return;
}
if (request.type === 'GET_OPTIONS') {
window.syncOptions.get(options => {
sendResponse({ options });
});
return;
}
if (request.type === 'GET_REPORT') {
getReport(request.payload, tabId, request.instanceId);
return;
}
if (request.type === 'OPEN') {
let position = 'devtools-left';
if (['remote', 'panel', 'left', 'right', 'bottom'].indexOf(request.position) !== -1) {
position = 'devtools-' + request.position;
}
openDevToolsWindow(position);
return;
}
if (request.type === 'ERROR') {
if (request.payload) {
toMonitors(request, tabId);
return;
}
if (!request.message) return;
const reducerError = getReducerError();
chrome.notifications.create('app-error', {
type: 'basic',
title: reducerError ? 'An error occurred in the reducer' : 'An error occurred in the app',
message: reducerError || request.message,
iconUrl: 'img/logo/48x48.png',
isClickable: !!reducerError
});
return;
}
const action = { type: UPDATE_STATE, request, id: tabId };
const instanceId = `${tabId}/${request.instanceId}`;
if (request.split) {
if (request.split === 'start') {
chunks[instanceId] = request;
return;
}
if (request.split === 'chunk') {
chunks[instanceId][request.chunk[0]] = (chunks[instanceId][request.chunk[0]] || '') + request.chunk[1];
return;
}
action.request = chunks[instanceId];
delete chunks[instanceId];
}
if (request.instanceId) {
action.request.instanceId = instanceId;
}
window.store.dispatch(action);
if (request.type === 'EXPORT') {
toMonitors(action, tabId, true);
} else {
toMonitors(action, tabId);
}
}
|
javascript
|
function messaging(request, sender, sendResponse) {
let tabId = getId(sender);
if (!tabId) return;
if (sender.frameId) tabId = `${tabId}-${sender.frameId}`;
if (request.type === 'STOP') {
if (!Object.keys(window.store.getState().instances.connections).length) {
window.store.dispatch({ type: DISCONNECTED });
}
return;
}
if (request.type === 'OPEN_OPTIONS') {
chrome.runtime.openOptionsPage();
return;
}
if (request.type === 'GET_OPTIONS') {
window.syncOptions.get(options => {
sendResponse({ options });
});
return;
}
if (request.type === 'GET_REPORT') {
getReport(request.payload, tabId, request.instanceId);
return;
}
if (request.type === 'OPEN') {
let position = 'devtools-left';
if (['remote', 'panel', 'left', 'right', 'bottom'].indexOf(request.position) !== -1) {
position = 'devtools-' + request.position;
}
openDevToolsWindow(position);
return;
}
if (request.type === 'ERROR') {
if (request.payload) {
toMonitors(request, tabId);
return;
}
if (!request.message) return;
const reducerError = getReducerError();
chrome.notifications.create('app-error', {
type: 'basic',
title: reducerError ? 'An error occurred in the reducer' : 'An error occurred in the app',
message: reducerError || request.message,
iconUrl: 'img/logo/48x48.png',
isClickable: !!reducerError
});
return;
}
const action = { type: UPDATE_STATE, request, id: tabId };
const instanceId = `${tabId}/${request.instanceId}`;
if (request.split) {
if (request.split === 'start') {
chunks[instanceId] = request;
return;
}
if (request.split === 'chunk') {
chunks[instanceId][request.chunk[0]] = (chunks[instanceId][request.chunk[0]] || '') + request.chunk[1];
return;
}
action.request = chunks[instanceId];
delete chunks[instanceId];
}
if (request.instanceId) {
action.request.instanceId = instanceId;
}
window.store.dispatch(action);
if (request.type === 'EXPORT') {
toMonitors(action, tabId, true);
} else {
toMonitors(action, tabId);
}
}
|
[
"function",
"messaging",
"(",
"request",
",",
"sender",
",",
"sendResponse",
")",
"{",
"let",
"tabId",
"=",
"getId",
"(",
"sender",
")",
";",
"if",
"(",
"!",
"tabId",
")",
"return",
";",
"if",
"(",
"sender",
".",
"frameId",
")",
"tabId",
"=",
"`",
"${",
"tabId",
"}",
"${",
"sender",
".",
"frameId",
"}",
"`",
";",
"if",
"(",
"request",
".",
"type",
"===",
"'STOP'",
")",
"{",
"if",
"(",
"!",
"Object",
".",
"keys",
"(",
"window",
".",
"store",
".",
"getState",
"(",
")",
".",
"instances",
".",
"connections",
")",
".",
"length",
")",
"{",
"window",
".",
"store",
".",
"dispatch",
"(",
"{",
"type",
":",
"DISCONNECTED",
"}",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"request",
".",
"type",
"===",
"'OPEN_OPTIONS'",
")",
"{",
"chrome",
".",
"runtime",
".",
"openOptionsPage",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"request",
".",
"type",
"===",
"'GET_OPTIONS'",
")",
"{",
"window",
".",
"syncOptions",
".",
"get",
"(",
"options",
"=>",
"{",
"sendResponse",
"(",
"{",
"options",
"}",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"if",
"(",
"request",
".",
"type",
"===",
"'GET_REPORT'",
")",
"{",
"getReport",
"(",
"request",
".",
"payload",
",",
"tabId",
",",
"request",
".",
"instanceId",
")",
";",
"return",
";",
"}",
"if",
"(",
"request",
".",
"type",
"===",
"'OPEN'",
")",
"{",
"let",
"position",
"=",
"'devtools-left'",
";",
"if",
"(",
"[",
"'remote'",
",",
"'panel'",
",",
"'left'",
",",
"'right'",
",",
"'bottom'",
"]",
".",
"indexOf",
"(",
"request",
".",
"position",
")",
"!==",
"-",
"1",
")",
"{",
"position",
"=",
"'devtools-'",
"+",
"request",
".",
"position",
";",
"}",
"openDevToolsWindow",
"(",
"position",
")",
";",
"return",
";",
"}",
"if",
"(",
"request",
".",
"type",
"===",
"'ERROR'",
")",
"{",
"if",
"(",
"request",
".",
"payload",
")",
"{",
"toMonitors",
"(",
"request",
",",
"tabId",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"request",
".",
"message",
")",
"return",
";",
"const",
"reducerError",
"=",
"getReducerError",
"(",
")",
";",
"chrome",
".",
"notifications",
".",
"create",
"(",
"'app-error'",
",",
"{",
"type",
":",
"'basic'",
",",
"title",
":",
"reducerError",
"?",
"'An error occurred in the reducer'",
":",
"'An error occurred in the app'",
",",
"message",
":",
"reducerError",
"||",
"request",
".",
"message",
",",
"iconUrl",
":",
"'img/logo/48x48.png'",
",",
"isClickable",
":",
"!",
"!",
"reducerError",
"}",
")",
";",
"return",
";",
"}",
"const",
"action",
"=",
"{",
"type",
":",
"UPDATE_STATE",
",",
"request",
",",
"id",
":",
"tabId",
"}",
";",
"const",
"instanceId",
"=",
"`",
"${",
"tabId",
"}",
"${",
"request",
".",
"instanceId",
"}",
"`",
";",
"if",
"(",
"request",
".",
"split",
")",
"{",
"if",
"(",
"request",
".",
"split",
"===",
"'start'",
")",
"{",
"chunks",
"[",
"instanceId",
"]",
"=",
"request",
";",
"return",
";",
"}",
"if",
"(",
"request",
".",
"split",
"===",
"'chunk'",
")",
"{",
"chunks",
"[",
"instanceId",
"]",
"[",
"request",
".",
"chunk",
"[",
"0",
"]",
"]",
"=",
"(",
"chunks",
"[",
"instanceId",
"]",
"[",
"request",
".",
"chunk",
"[",
"0",
"]",
"]",
"||",
"''",
")",
"+",
"request",
".",
"chunk",
"[",
"1",
"]",
";",
"return",
";",
"}",
"action",
".",
"request",
"=",
"chunks",
"[",
"instanceId",
"]",
";",
"delete",
"chunks",
"[",
"instanceId",
"]",
";",
"}",
"if",
"(",
"request",
".",
"instanceId",
")",
"{",
"action",
".",
"request",
".",
"instanceId",
"=",
"instanceId",
";",
"}",
"window",
".",
"store",
".",
"dispatch",
"(",
"action",
")",
";",
"if",
"(",
"request",
".",
"type",
"===",
"'EXPORT'",
")",
"{",
"toMonitors",
"(",
"action",
",",
"tabId",
",",
"true",
")",
";",
"}",
"else",
"{",
"toMonitors",
"(",
"action",
",",
"tabId",
")",
";",
"}",
"}"
] |
Receive messages from content scripts
|
[
"Receive",
"messages",
"from",
"content",
"scripts"
] |
d127175196388c9b1f874b04b2792cf487c5d5e0
|
https://github.com/zalmoxisus/redux-devtools-extension/blob/d127175196388c9b1f874b04b2792cf487c5d5e0/src/app/middlewares/api.js#L79-L153
|
train
|
zalmoxisus/redux-devtools-extension
|
src/browser/extension/inject/contentScript.js
|
handleMessages
|
function handleMessages(event) {
if (!isAllowed()) return;
if (!event || event.source !== window || typeof event.data !== 'object') return;
const message = event.data;
if (message.source !== pageSource) return;
if (message.type === 'DISCONNECT') {
if (bg) {
bg.disconnect();
connected = false;
}
return;
}
tryCatch(send, message);
}
|
javascript
|
function handleMessages(event) {
if (!isAllowed()) return;
if (!event || event.source !== window || typeof event.data !== 'object') return;
const message = event.data;
if (message.source !== pageSource) return;
if (message.type === 'DISCONNECT') {
if (bg) {
bg.disconnect();
connected = false;
}
return;
}
tryCatch(send, message);
}
|
[
"function",
"handleMessages",
"(",
"event",
")",
"{",
"if",
"(",
"!",
"isAllowed",
"(",
")",
")",
"return",
";",
"if",
"(",
"!",
"event",
"||",
"event",
".",
"source",
"!==",
"window",
"||",
"typeof",
"event",
".",
"data",
"!==",
"'object'",
")",
"return",
";",
"const",
"message",
"=",
"event",
".",
"data",
";",
"if",
"(",
"message",
".",
"source",
"!==",
"pageSource",
")",
"return",
";",
"if",
"(",
"message",
".",
"type",
"===",
"'DISCONNECT'",
")",
"{",
"if",
"(",
"bg",
")",
"{",
"bg",
".",
"disconnect",
"(",
")",
";",
"connected",
"=",
"false",
";",
"}",
"return",
";",
"}",
"tryCatch",
"(",
"send",
",",
"message",
")",
";",
"}"
] |
Resend messages from the page to the background script
|
[
"Resend",
"messages",
"from",
"the",
"page",
"to",
"the",
"background",
"script"
] |
d127175196388c9b1f874b04b2792cf487c5d5e0
|
https://github.com/zalmoxisus/redux-devtools-extension/blob/d127175196388c9b1f874b04b2792cf487c5d5e0/src/browser/extension/inject/contentScript.js#L102-L116
|
train
|
google/closure-library
|
closure/goog/dom/uri.js
|
normalizeUri
|
function normalizeUri(uri) {
const anchor = createElement(TagName.A);
// This is safe even though the URL might be untrustworthy.
// The SafeURL is only used to set the href of an HTMLAnchorElement
// that is never added to the DOM. Therefore, the user cannot navigate
// to this URL.
const safeUrl =
uncheckedconversions.safeUrlFromStringKnownToSatisfyTypeContract(
Const.from('This URL is never added to the DOM'), uri);
setAnchorHref(anchor, safeUrl);
return anchor.href;
}
|
javascript
|
function normalizeUri(uri) {
const anchor = createElement(TagName.A);
// This is safe even though the URL might be untrustworthy.
// The SafeURL is only used to set the href of an HTMLAnchorElement
// that is never added to the DOM. Therefore, the user cannot navigate
// to this URL.
const safeUrl =
uncheckedconversions.safeUrlFromStringKnownToSatisfyTypeContract(
Const.from('This URL is never added to the DOM'), uri);
setAnchorHref(anchor, safeUrl);
return anchor.href;
}
|
[
"function",
"normalizeUri",
"(",
"uri",
")",
"{",
"const",
"anchor",
"=",
"createElement",
"(",
"TagName",
".",
"A",
")",
";",
"const",
"safeUrl",
"=",
"uncheckedconversions",
".",
"safeUrlFromStringKnownToSatisfyTypeContract",
"(",
"Const",
".",
"from",
"(",
"'This URL is never added to the DOM'",
")",
",",
"uri",
")",
";",
"setAnchorHref",
"(",
"anchor",
",",
"safeUrl",
")",
";",
"return",
"anchor",
".",
"href",
";",
"}"
] |
Normalizes a URL by assigning it to an anchor element and reading back href.
This converts relative URLs to absolute, and cleans up whitespace.
@param {string} uri A string containing a URI.
@return {string} Normalized, absolute form of uri.
|
[
"Normalizes",
"a",
"URL",
"by",
"assigning",
"it",
"to",
"an",
"anchor",
"element",
"and",
"reading",
"back",
"href",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/dom/uri.js#L30-L41
|
train
|
google/closure-library
|
browser_capabilities.js
|
getBrowserName
|
function getBrowserName(browserCap) {
var name = browserCap.browserName == 'internet explorer' ?
'ie' :
browserCap.browserName;
var version = browserCap.version || '-latest';
return name + version;
}
|
javascript
|
function getBrowserName(browserCap) {
var name = browserCap.browserName == 'internet explorer' ?
'ie' :
browserCap.browserName;
var version = browserCap.version || '-latest';
return name + version;
}
|
[
"function",
"getBrowserName",
"(",
"browserCap",
")",
"{",
"var",
"name",
"=",
"browserCap",
".",
"browserName",
"==",
"'internet explorer'",
"?",
"'ie'",
":",
"browserCap",
".",
"browserName",
";",
"var",
"version",
"=",
"browserCap",
".",
"version",
"||",
"'-latest'",
";",
"return",
"name",
"+",
"version",
";",
"}"
] |
Returns a versioned name for the given capability object.
@param {!Object} browserCap
@return {string}
|
[
"Returns",
"a",
"versioned",
"name",
"for",
"the",
"given",
"capability",
"object",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/browser_capabilities.js#L22-L28
|
train
|
google/closure-library
|
browser_capabilities.js
|
getJobName
|
function getJobName(browserCap) {
var browserName = getBrowserName(browserCap);
return process.env.TRAVIS_PULL_REQUEST == 'false' ?
'CO-' + process.env.TRAVIS_BRANCH + '-' + browserName :
'PR-' + process.env.TRAVIS_PULL_REQUEST + '-' + browserName + '-' +
process.env.TRAVIS_BRANCH;
}
|
javascript
|
function getJobName(browserCap) {
var browserName = getBrowserName(browserCap);
return process.env.TRAVIS_PULL_REQUEST == 'false' ?
'CO-' + process.env.TRAVIS_BRANCH + '-' + browserName :
'PR-' + process.env.TRAVIS_PULL_REQUEST + '-' + browserName + '-' +
process.env.TRAVIS_BRANCH;
}
|
[
"function",
"getJobName",
"(",
"browserCap",
")",
"{",
"var",
"browserName",
"=",
"getBrowserName",
"(",
"browserCap",
")",
";",
"return",
"process",
".",
"env",
".",
"TRAVIS_PULL_REQUEST",
"==",
"'false'",
"?",
"'CO-'",
"+",
"process",
".",
"env",
".",
"TRAVIS_BRANCH",
"+",
"'-'",
"+",
"browserName",
":",
"'PR-'",
"+",
"process",
".",
"env",
".",
"TRAVIS_PULL_REQUEST",
"+",
"'-'",
"+",
"browserName",
"+",
"'-'",
"+",
"process",
".",
"env",
".",
"TRAVIS_BRANCH",
";",
"}"
] |
Returns the travis job name for the given capability object.
@param {!Object} browserCap
@return {string}
|
[
"Returns",
"the",
"travis",
"job",
"name",
"for",
"the",
"given",
"capability",
"object",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/browser_capabilities.js#L35-L42
|
train
|
google/closure-library
|
browser_capabilities.js
|
getBrowserCapabilities
|
function getBrowserCapabilities(browsers) {
for (var i = 0; i < browsers.length; i++) {
var b = browsers[i];
b['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
b['build'] = process.env.TRAVIS_BUILD_NUMBER;
b['name'] = getJobName(b);
}
return browsers;
}
|
javascript
|
function getBrowserCapabilities(browsers) {
for (var i = 0; i < browsers.length; i++) {
var b = browsers[i];
b['tunnel-identifier'] = process.env.TRAVIS_JOB_NUMBER;
b['build'] = process.env.TRAVIS_BUILD_NUMBER;
b['name'] = getJobName(b);
}
return browsers;
}
|
[
"function",
"getBrowserCapabilities",
"(",
"browsers",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"browsers",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"b",
"=",
"browsers",
"[",
"i",
"]",
";",
"b",
"[",
"'tunnel-identifier'",
"]",
"=",
"process",
".",
"env",
".",
"TRAVIS_JOB_NUMBER",
";",
"b",
"[",
"'build'",
"]",
"=",
"process",
".",
"env",
".",
"TRAVIS_BUILD_NUMBER",
";",
"b",
"[",
"'name'",
"]",
"=",
"getJobName",
"(",
"b",
")",
";",
"}",
"return",
"browsers",
";",
"}"
] |
Adds 'name', 'build', and 'tunnel-identifier' properties to all elements,
based on runtime information from the environment.
@param {!Array<!Object>} browsers
@return {!Array<!Object>} The original array, whose objects are augmented.
|
[
"Adds",
"name",
"build",
"and",
"tunnel",
"-",
"identifier",
"properties",
"to",
"all",
"elements",
"based",
"on",
"runtime",
"information",
"from",
"the",
"environment",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/browser_capabilities.js#L50-L58
|
train
|
google/closure-library
|
closure/goog/html/sanitizer/noclobber.js
|
prototypeMethodOrNull
|
function prototypeMethodOrNull(className, method) {
var ctor = goog.global[className];
return (ctor && ctor.prototype && ctor.prototype[method]) || null;
}
|
javascript
|
function prototypeMethodOrNull(className, method) {
var ctor = goog.global[className];
return (ctor && ctor.prototype && ctor.prototype[method]) || null;
}
|
[
"function",
"prototypeMethodOrNull",
"(",
"className",
",",
"method",
")",
"{",
"var",
"ctor",
"=",
"goog",
".",
"global",
"[",
"className",
"]",
";",
"return",
"(",
"ctor",
"&&",
"ctor",
".",
"prototype",
"&&",
"ctor",
".",
"prototype",
"[",
"method",
"]",
")",
"||",
"null",
";",
"}"
] |
Shorthand for `DOMInterface.prototype.method` to improve readability
during initialization of `Methods`.
@param {string} className
@param {string} method
@return {?Function}
|
[
"Shorthand",
"for",
"DOMInterface",
".",
"prototype",
".",
"method",
"to",
"improve",
"readability",
"during",
"initialization",
"of",
"Methods",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/noclobber.js#L73-L76
|
train
|
google/closure-library
|
closure/goog/html/sanitizer/noclobber.js
|
genericPropertyGet
|
function genericPropertyGet(fn, object, fallbackPropertyName, fallbackTest) {
if (fn) {
return fn.apply(object);
}
var propertyValue = object[fallbackPropertyName];
if (!fallbackTest(propertyValue)) {
throw new Error('Clobbering detected');
}
return propertyValue;
}
|
javascript
|
function genericPropertyGet(fn, object, fallbackPropertyName, fallbackTest) {
if (fn) {
return fn.apply(object);
}
var propertyValue = object[fallbackPropertyName];
if (!fallbackTest(propertyValue)) {
throw new Error('Clobbering detected');
}
return propertyValue;
}
|
[
"function",
"genericPropertyGet",
"(",
"fn",
",",
"object",
",",
"fallbackPropertyName",
",",
"fallbackTest",
")",
"{",
"if",
"(",
"fn",
")",
"{",
"return",
"fn",
".",
"apply",
"(",
"object",
")",
";",
"}",
"var",
"propertyValue",
"=",
"object",
"[",
"fallbackPropertyName",
"]",
";",
"if",
"(",
"!",
"fallbackTest",
"(",
"propertyValue",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Clobbering detected'",
")",
";",
"}",
"return",
"propertyValue",
";",
"}"
] |
Calls the provided DOM property descriptor and returns its result. If the
descriptor is not available, use fallbackPropertyName to get the property
value in a clobber-vulnerable way, and use fallbackTest to check if the
property was clobbered, throwing an exception if so.
@param {?Function} fn
@param {*} object
@param {string} fallbackPropertyName
@param {function(*):boolean} fallbackTest
@return {?}
|
[
"Calls",
"the",
"provided",
"DOM",
"property",
"descriptor",
"and",
"returns",
"its",
"result",
".",
"If",
"the",
"descriptor",
"is",
"not",
"available",
"use",
"fallbackPropertyName",
"to",
"get",
"the",
"property",
"value",
"in",
"a",
"clobber",
"-",
"vulnerable",
"way",
"and",
"use",
"fallbackTest",
"to",
"check",
"if",
"the",
"property",
"was",
"clobbered",
"throwing",
"an",
"exception",
"if",
"so",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/noclobber.js#L123-L132
|
train
|
google/closure-library
|
closure/goog/html/sanitizer/noclobber.js
|
genericMethodCall
|
function genericMethodCall(fn, object, fallbackMethodName, args) {
if (fn) {
return fn.apply(object, args);
}
// IE8 and IE9 will return 'object' for
// CSSStyleDeclaration.(get|set)Attribute, so we can't use typeof.
if (userAgentProduct.IE && document.documentMode < 10) {
if (!object[fallbackMethodName].call) {
throw new Error('IE Clobbering detected');
}
} else if (typeof object[fallbackMethodName] != 'function') {
throw new Error('Clobbering detected');
}
return object[fallbackMethodName].apply(object, args);
}
|
javascript
|
function genericMethodCall(fn, object, fallbackMethodName, args) {
if (fn) {
return fn.apply(object, args);
}
// IE8 and IE9 will return 'object' for
// CSSStyleDeclaration.(get|set)Attribute, so we can't use typeof.
if (userAgentProduct.IE && document.documentMode < 10) {
if (!object[fallbackMethodName].call) {
throw new Error('IE Clobbering detected');
}
} else if (typeof object[fallbackMethodName] != 'function') {
throw new Error('Clobbering detected');
}
return object[fallbackMethodName].apply(object, args);
}
|
[
"function",
"genericMethodCall",
"(",
"fn",
",",
"object",
",",
"fallbackMethodName",
",",
"args",
")",
"{",
"if",
"(",
"fn",
")",
"{",
"return",
"fn",
".",
"apply",
"(",
"object",
",",
"args",
")",
";",
"}",
"if",
"(",
"userAgentProduct",
".",
"IE",
"&&",
"document",
".",
"documentMode",
"<",
"10",
")",
"{",
"if",
"(",
"!",
"object",
"[",
"fallbackMethodName",
"]",
".",
"call",
")",
"{",
"throw",
"new",
"Error",
"(",
"'IE Clobbering detected'",
")",
";",
"}",
"}",
"else",
"if",
"(",
"typeof",
"object",
"[",
"fallbackMethodName",
"]",
"!=",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Clobbering detected'",
")",
";",
"}",
"return",
"object",
"[",
"fallbackMethodName",
"]",
".",
"apply",
"(",
"object",
",",
"args",
")",
";",
"}"
] |
Calls the provided DOM prototype method and returns its result. If the
method is not available, use fallbackMethodName to call the method in a
clobber-vulnerable way, and use fallbackTest to check if the
method was clobbered, throwing an exception if so.
@param {?Function} fn
@param {*} object
@param {string} fallbackMethodName
@param {!Array<*>} args
@return {?}
|
[
"Calls",
"the",
"provided",
"DOM",
"prototype",
"method",
"and",
"returns",
"its",
"result",
".",
"If",
"the",
"method",
"is",
"not",
"available",
"use",
"fallbackMethodName",
"to",
"call",
"the",
"method",
"in",
"a",
"clobber",
"-",
"vulnerable",
"way",
"and",
"use",
"fallbackTest",
"to",
"check",
"if",
"the",
"method",
"was",
"clobbered",
"throwing",
"an",
"exception",
"if",
"so",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/noclobber.js#L145-L159
|
train
|
google/closure-library
|
closure/goog/html/sanitizer/noclobber.js
|
getCssPropertyValue
|
function getCssPropertyValue(cssStyle, propName) {
return genericMethodCall(
Methods.GET_PROPERTY_VALUE, cssStyle,
cssStyle.getPropertyValue ? 'getPropertyValue' : 'getAttribute',
[propName]) ||
'';
}
|
javascript
|
function getCssPropertyValue(cssStyle, propName) {
return genericMethodCall(
Methods.GET_PROPERTY_VALUE, cssStyle,
cssStyle.getPropertyValue ? 'getPropertyValue' : 'getAttribute',
[propName]) ||
'';
}
|
[
"function",
"getCssPropertyValue",
"(",
"cssStyle",
",",
"propName",
")",
"{",
"return",
"genericMethodCall",
"(",
"Methods",
".",
"GET_PROPERTY_VALUE",
",",
"cssStyle",
",",
"cssStyle",
".",
"getPropertyValue",
"?",
"'getPropertyValue'",
":",
"'getAttribute'",
",",
"[",
"propName",
"]",
")",
"||",
"''",
";",
"}"
] |
Provides a way cross-browser way to get a CSS value from a CSS declaration.
@param {!CSSStyleDeclaration} cssStyle A CSS style object.
@param {string} propName A property name.
@return {string} Value of the property as parsed by the browser.
@supported IE8 and newer.
|
[
"Provides",
"a",
"way",
"cross",
"-",
"browser",
"way",
"to",
"get",
"a",
"CSS",
"value",
"from",
"a",
"CSS",
"declaration",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/noclobber.js#L421-L427
|
train
|
google/closure-library
|
closure/goog/html/sanitizer/noclobber.js
|
setCssProperty
|
function setCssProperty(cssStyle, propName, sanitizedValue) {
genericMethodCall(
Methods.SET_PROPERTY, cssStyle,
cssStyle.setProperty ? 'setProperty' : 'setAttribute',
[propName, sanitizedValue]);
}
|
javascript
|
function setCssProperty(cssStyle, propName, sanitizedValue) {
genericMethodCall(
Methods.SET_PROPERTY, cssStyle,
cssStyle.setProperty ? 'setProperty' : 'setAttribute',
[propName, sanitizedValue]);
}
|
[
"function",
"setCssProperty",
"(",
"cssStyle",
",",
"propName",
",",
"sanitizedValue",
")",
"{",
"genericMethodCall",
"(",
"Methods",
".",
"SET_PROPERTY",
",",
"cssStyle",
",",
"cssStyle",
".",
"setProperty",
"?",
"'setProperty'",
":",
"'setAttribute'",
",",
"[",
"propName",
",",
"sanitizedValue",
"]",
")",
";",
"}"
] |
Provides a cross-browser way to set a CSS value on a CSS declaration.
@param {!CSSStyleDeclaration} cssStyle A CSS style object.
@param {string} propName A property name.
@param {string} sanitizedValue Sanitized value of the property to be set
on the CSS style object.
@supported IE8 and newer.
|
[
"Provides",
"a",
"cross",
"-",
"browser",
"way",
"to",
"set",
"a",
"CSS",
"value",
"on",
"a",
"CSS",
"declaration",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/noclobber.js#L437-L442
|
train
|
google/closure-library
|
closure/goog/structs/avltree.js
|
function(value, opt_parent) {
/**
* The value stored by the node.
*
* @type {T}
*/
this.value = value;
/**
* The node's parent. Null if the node is the root.
*
* @type {?Node<T>}
*/
this.parent = opt_parent ? opt_parent : null;
/**
* The number of nodes in the subtree rooted at this node.
*
* @type {number}
*/
this.count = 1;
/**
* The node's left child. Null if the node does not have a left child.
*
* @type {?Node<T>}
*/
this.left = null;
/**
* The node's right child. Null if the node does not have a right child.
*
* @type {?Node<T>}
*/
this.right = null;
/**
* Height of this node.
*
* @type {number}
*/
this.height = 1;
}
|
javascript
|
function(value, opt_parent) {
/**
* The value stored by the node.
*
* @type {T}
*/
this.value = value;
/**
* The node's parent. Null if the node is the root.
*
* @type {?Node<T>}
*/
this.parent = opt_parent ? opt_parent : null;
/**
* The number of nodes in the subtree rooted at this node.
*
* @type {number}
*/
this.count = 1;
/**
* The node's left child. Null if the node does not have a left child.
*
* @type {?Node<T>}
*/
this.left = null;
/**
* The node's right child. Null if the node does not have a right child.
*
* @type {?Node<T>}
*/
this.right = null;
/**
* Height of this node.
*
* @type {number}
*/
this.height = 1;
}
|
[
"function",
"(",
"value",
",",
"opt_parent",
")",
"{",
"this",
".",
"value",
"=",
"value",
";",
"this",
".",
"parent",
"=",
"opt_parent",
"?",
"opt_parent",
":",
"null",
";",
"this",
".",
"count",
"=",
"1",
";",
"this",
".",
"left",
"=",
"null",
";",
"this",
".",
"right",
"=",
"null",
";",
"this",
".",
"height",
"=",
"1",
";",
"}"
] |
Constructs an AVL-Tree node with the specified value. If no parent is
specified, the node's parent is assumed to be null. The node's height
defaults to 1 and its children default to null.
@param {T} value Value to store in the node.
@param {Node<T>=} opt_parent Optional parent node.
@constructor
@final
@template T
|
[
"Constructs",
"an",
"AVL",
"-",
"Tree",
"node",
"with",
"the",
"specified",
"value",
".",
"If",
"no",
"parent",
"is",
"specified",
"the",
"node",
"s",
"parent",
"is",
"assumed",
"to",
"be",
"null",
".",
"The",
"node",
"s",
"height",
"defaults",
"to",
"1",
"and",
"its",
"children",
"default",
"to",
"null",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/structs/avltree.js#L843-L885
|
train
|
|
google/closure-library
|
closure/goog/net/streams/pbstreamparser.js
|
finishMessage
|
function finishMessage() {
if (parser.tag_ < Parser.PADDING_TAG_) {
var message = {};
message[parser.tag_] = parser.messageBuffer_;
parser.result_.push(message);
}
parser.state_ = Parser.State_.INIT;
}
|
javascript
|
function finishMessage() {
if (parser.tag_ < Parser.PADDING_TAG_) {
var message = {};
message[parser.tag_] = parser.messageBuffer_;
parser.result_.push(message);
}
parser.state_ = Parser.State_.INIT;
}
|
[
"function",
"finishMessage",
"(",
")",
"{",
"if",
"(",
"parser",
".",
"tag_",
"<",
"Parser",
".",
"PADDING_TAG_",
")",
"{",
"var",
"message",
"=",
"{",
"}",
";",
"message",
"[",
"parser",
".",
"tag_",
"]",
"=",
"parser",
".",
"messageBuffer_",
";",
"parser",
".",
"result_",
".",
"push",
"(",
"message",
")",
";",
"}",
"parser",
".",
"state_",
"=",
"Parser",
".",
"State_",
".",
"INIT",
";",
"}"
] |
Finishes up building the current message and resets parser state
|
[
"Finishes",
"up",
"building",
"the",
"current",
"message",
"and",
"resets",
"parser",
"state"
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/net/streams/pbstreamparser.js#L289-L296
|
train
|
google/closure-library
|
protractor_spec.js
|
function(testPath) {
var testStartTime = +new Date();
var waitForTest = function(resolve, reject) {
// executeScript runs the passed method in the "window" context of
// the current test. JSUnit exposes hooks into the test's status through
// the "G_testRunner" global object.
browser
.executeScript(function() {
if (window['G_testRunner'] &&
window['G_testRunner']['isFinished']()) {
var status = {};
status['isFinished'] = true;
status['isSuccess'] = window['G_testRunner']['isSuccess']();
status['report'] = window['G_testRunner']['getReport']();
return status;
} else {
return {'isFinished': false};
}
})
.then(
function(status) {
if (status && status.isFinished) {
resolve(status);
} else {
var currTime = +new Date();
if (currTime - testStartTime > TEST_TIMEOUT) {
status.isSuccess = false;
status.report = testPath + ' timed out after ' +
(TEST_TIMEOUT / 1000) + 's!';
// resolve so tests continue running.
resolve(status);
} else {
// Check every 300ms for completion.
setTimeout(
waitForTest.bind(undefined, resolve, reject), 300);
}
}
},
function(err) {
reject(err);
});
};
return new Promise(function(resolve, reject) {
waitForTest(resolve, reject);
});
}
|
javascript
|
function(testPath) {
var testStartTime = +new Date();
var waitForTest = function(resolve, reject) {
// executeScript runs the passed method in the "window" context of
// the current test. JSUnit exposes hooks into the test's status through
// the "G_testRunner" global object.
browser
.executeScript(function() {
if (window['G_testRunner'] &&
window['G_testRunner']['isFinished']()) {
var status = {};
status['isFinished'] = true;
status['isSuccess'] = window['G_testRunner']['isSuccess']();
status['report'] = window['G_testRunner']['getReport']();
return status;
} else {
return {'isFinished': false};
}
})
.then(
function(status) {
if (status && status.isFinished) {
resolve(status);
} else {
var currTime = +new Date();
if (currTime - testStartTime > TEST_TIMEOUT) {
status.isSuccess = false;
status.report = testPath + ' timed out after ' +
(TEST_TIMEOUT / 1000) + 's!';
// resolve so tests continue running.
resolve(status);
} else {
// Check every 300ms for completion.
setTimeout(
waitForTest.bind(undefined, resolve, reject), 300);
}
}
},
function(err) {
reject(err);
});
};
return new Promise(function(resolve, reject) {
waitForTest(resolve, reject);
});
}
|
[
"function",
"(",
"testPath",
")",
"{",
"var",
"testStartTime",
"=",
"+",
"new",
"Date",
"(",
")",
";",
"var",
"waitForTest",
"=",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"browser",
".",
"executeScript",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"window",
"[",
"'G_testRunner'",
"]",
"&&",
"window",
"[",
"'G_testRunner'",
"]",
"[",
"'isFinished'",
"]",
"(",
")",
")",
"{",
"var",
"status",
"=",
"{",
"}",
";",
"status",
"[",
"'isFinished'",
"]",
"=",
"true",
";",
"status",
"[",
"'isSuccess'",
"]",
"=",
"window",
"[",
"'G_testRunner'",
"]",
"[",
"'isSuccess'",
"]",
"(",
")",
";",
"status",
"[",
"'report'",
"]",
"=",
"window",
"[",
"'G_testRunner'",
"]",
"[",
"'getReport'",
"]",
"(",
")",
";",
"return",
"status",
";",
"}",
"else",
"{",
"return",
"{",
"'isFinished'",
":",
"false",
"}",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"status",
")",
"{",
"if",
"(",
"status",
"&&",
"status",
".",
"isFinished",
")",
"{",
"resolve",
"(",
"status",
")",
";",
"}",
"else",
"{",
"var",
"currTime",
"=",
"+",
"new",
"Date",
"(",
")",
";",
"if",
"(",
"currTime",
"-",
"testStartTime",
">",
"TEST_TIMEOUT",
")",
"{",
"status",
".",
"isSuccess",
"=",
"false",
";",
"status",
".",
"report",
"=",
"testPath",
"+",
"' timed out after '",
"+",
"(",
"TEST_TIMEOUT",
"/",
"1000",
")",
"+",
"'s!'",
";",
"resolve",
"(",
"status",
")",
";",
"}",
"else",
"{",
"setTimeout",
"(",
"waitForTest",
".",
"bind",
"(",
"undefined",
",",
"resolve",
",",
"reject",
")",
",",
"300",
")",
";",
"}",
"}",
"}",
",",
"function",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
";",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"waitForTest",
"(",
"resolve",
",",
"reject",
")",
";",
"}",
")",
";",
"}"
] |
Polls currently loaded test page for test completion. Returns Promise that will resolve when test is finished.
|
[
"Polls",
"currently",
"loaded",
"test",
"page",
"for",
"test",
"completion",
".",
"Returns",
"Promise",
"that",
"will",
"resolve",
"when",
"test",
"is",
"finished",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/protractor_spec.js#L65-L112
|
train
|
|
google/closure-library
|
protractor_spec.js
|
function(testPath) {
return browser.navigate()
.to(TEST_SERVER + '/' + testPath)
.then(function() {
return waitForTestSuiteCompletion(testPath);
})
.then(function(status) {
if (!status.isSuccess) {
failureReports.push(status.report);
}
return status;
});
}
|
javascript
|
function(testPath) {
return browser.navigate()
.to(TEST_SERVER + '/' + testPath)
.then(function() {
return waitForTestSuiteCompletion(testPath);
})
.then(function(status) {
if (!status.isSuccess) {
failureReports.push(status.report);
}
return status;
});
}
|
[
"function",
"(",
"testPath",
")",
"{",
"return",
"browser",
".",
"navigate",
"(",
")",
".",
"to",
"(",
"TEST_SERVER",
"+",
"'/'",
"+",
"testPath",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"waitForTestSuiteCompletion",
"(",
"testPath",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
"status",
")",
"{",
"if",
"(",
"!",
"status",
".",
"isSuccess",
")",
"{",
"failureReports",
".",
"push",
"(",
"status",
".",
"report",
")",
";",
"}",
"return",
"status",
";",
"}",
")",
";",
"}"
] |
Navigates to testPath to invoke tests. Upon completion inspects returned test status and keeps track of the total number failed tests.
|
[
"Navigates",
"to",
"testPath",
"to",
"invoke",
"tests",
".",
"Upon",
"completion",
"inspects",
"returned",
"test",
"status",
"and",
"keeps",
"track",
"of",
"the",
"total",
"number",
"failed",
"tests",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/protractor_spec.js#L119-L132
|
train
|
|
google/closure-library
|
closure/goog/html/cssspecificity.js
|
getSpecificity
|
function getSpecificity(selector) {
if (userAgentProduct.IE && !userAgent.isVersionOrHigher(9)) {
// IE8 has buggy regex support.
return [0, 0, 0, 0];
}
var specificity = specificityCache.hasOwnProperty(selector) ?
specificityCache[selector] :
null;
if (specificity) {
return specificity;
}
if (Object.keys(specificityCache).length > (1 << 16)) {
// Limit the size of cache to (1 << 16) == 65536. Normally HTML pages don't
// have such numbers of selectors.
specificityCache = {};
}
specificity = calculateSpecificity(selector);
specificityCache[selector] = specificity;
return specificity;
}
|
javascript
|
function getSpecificity(selector) {
if (userAgentProduct.IE && !userAgent.isVersionOrHigher(9)) {
// IE8 has buggy regex support.
return [0, 0, 0, 0];
}
var specificity = specificityCache.hasOwnProperty(selector) ?
specificityCache[selector] :
null;
if (specificity) {
return specificity;
}
if (Object.keys(specificityCache).length > (1 << 16)) {
// Limit the size of cache to (1 << 16) == 65536. Normally HTML pages don't
// have such numbers of selectors.
specificityCache = {};
}
specificity = calculateSpecificity(selector);
specificityCache[selector] = specificity;
return specificity;
}
|
[
"function",
"getSpecificity",
"(",
"selector",
")",
"{",
"if",
"(",
"userAgentProduct",
".",
"IE",
"&&",
"!",
"userAgent",
".",
"isVersionOrHigher",
"(",
"9",
")",
")",
"{",
"return",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
";",
"}",
"var",
"specificity",
"=",
"specificityCache",
".",
"hasOwnProperty",
"(",
"selector",
")",
"?",
"specificityCache",
"[",
"selector",
"]",
":",
"null",
";",
"if",
"(",
"specificity",
")",
"{",
"return",
"specificity",
";",
"}",
"if",
"(",
"Object",
".",
"keys",
"(",
"specificityCache",
")",
".",
"length",
">",
"(",
"1",
"<<",
"16",
")",
")",
"{",
"specificityCache",
"=",
"{",
"}",
";",
"}",
"specificity",
"=",
"calculateSpecificity",
"(",
"selector",
")",
";",
"specificityCache",
"[",
"selector",
"]",
"=",
"specificity",
";",
"return",
"specificity",
";",
"}"
] |
Calculates the specificity of CSS selectors, using a global cache if
supported.
@see http://www.w3.org/TR/css3-selectors/#specificity
@see https://specificity.keegan.st/
@param {string} selector The CSS selector.
@return {!Array<number>} The CSS specificity.
@supported IE9+, other browsers.
|
[
"Calculates",
"the",
"specificity",
"of",
"CSS",
"selectors",
"using",
"a",
"global",
"cache",
"if",
"supported",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/cssspecificity.js#L39-L58
|
train
|
google/closure-library
|
closure/goog/html/cssspecificity.js
|
replaceWithEmptyText
|
function replaceWithEmptyText(selector, specificity, regex, typeIndex) {
return selector.replace(regex, function(match) {
specificity[typeIndex] += 1;
// Replace this simple selector with whitespace so it won't be counted
// in further simple selectors.
return Array(match.length + 1).join(' ');
});
}
|
javascript
|
function replaceWithEmptyText(selector, specificity, regex, typeIndex) {
return selector.replace(regex, function(match) {
specificity[typeIndex] += 1;
// Replace this simple selector with whitespace so it won't be counted
// in further simple selectors.
return Array(match.length + 1).join(' ');
});
}
|
[
"function",
"replaceWithEmptyText",
"(",
"selector",
",",
"specificity",
",",
"regex",
",",
"typeIndex",
")",
"{",
"return",
"selector",
".",
"replace",
"(",
"regex",
",",
"function",
"(",
"match",
")",
"{",
"specificity",
"[",
"typeIndex",
"]",
"+=",
"1",
";",
"return",
"Array",
"(",
"match",
".",
"length",
"+",
"1",
")",
".",
"join",
"(",
"' '",
")",
";",
"}",
")",
";",
"}"
] |
Find matches for a regular expression in the selector and increase count.
@param {string} selector The selector to match the regex with.
@param {!Array<number>} specificity The current specificity.
@param {!RegExp} regex The regular expression.
@param {number} typeIndex Index of type count.
@return {string}
|
[
"Find",
"matches",
"for",
"a",
"regular",
"expression",
"in",
"the",
"selector",
"and",
"increase",
"count",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/cssspecificity.js#L68-L75
|
train
|
google/closure-library
|
closure/goog/html/cssspecificity.js
|
replaceWithPlainText
|
function replaceWithPlainText(selector, regex) {
return selector.replace(regex, function(match) {
return Array(match.length + 1).join('A');
});
}
|
javascript
|
function replaceWithPlainText(selector, regex) {
return selector.replace(regex, function(match) {
return Array(match.length + 1).join('A');
});
}
|
[
"function",
"replaceWithPlainText",
"(",
"selector",
",",
"regex",
")",
"{",
"return",
"selector",
".",
"replace",
"(",
"regex",
",",
"function",
"(",
"match",
")",
"{",
"return",
"Array",
"(",
"match",
".",
"length",
"+",
"1",
")",
".",
"join",
"(",
"'A'",
")",
";",
"}",
")",
";",
"}"
] |
Replace escaped characters with plain text, using the "A" character.
@see https://www.w3.org/TR/CSS21/syndata.html#characters
@param {string} selector
@param {!RegExp} regex
@return {string}
|
[
"Replace",
"escaped",
"characters",
"with",
"plain",
"text",
"using",
"the",
"A",
"character",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/cssspecificity.js#L84-L88
|
train
|
google/closure-library
|
closure/goog/html/cssspecificity.js
|
calculateSpecificity
|
function calculateSpecificity(selector) {
var specificity = [0, 0, 0, 0];
// Cannot use RegExp literals for all regular expressions, IE does not accept
// the syntax.
// Matches a backslash followed by six hexadecimal digits followed by an
// optional single whitespace character.
var escapeHexadecimalRegex = new RegExp('\\\\[0-9A-Fa-f]{6}\\s?', 'g');
// Matches a backslash followed by fewer than six hexadecimal digits
// followed by a mandatory single whitespace character.
var escapeHexadecimalRegex2 = new RegExp('\\\\[0-9A-Fa-f]{1,5}\\s', 'g');
// Matches a backslash followed by any character
var escapeSpecialCharacter = /\\./g;
selector = replaceWithPlainText(selector, escapeHexadecimalRegex);
selector = replaceWithPlainText(selector, escapeHexadecimalRegex2);
selector = replaceWithPlainText(selector, escapeSpecialCharacter);
// Remove the negation pseudo-class (:not) but leave its argument because
// specificity is calculated on its argument.
var pseudoClassWithNotRegex = new RegExp(':not\\(([^\\)]*)\\)', 'g');
selector = selector.replace(pseudoClassWithNotRegex, ' $1 ');
// Remove anything after a left brace in case a user has pasted in a rule,
// not just a selector.
var rulesRegex = new RegExp('{[^]*', 'gm');
selector = selector.replace(rulesRegex, '');
// The following regular expressions assume that selectors matching the
// preceding regular expressions have been removed.
// SPECIFICITY 2: Counts attribute selectors.
var attributeRegex = new RegExp('(\\[[^\\]]+\\])', 'g');
selector = replaceWithEmptyText(selector, specificity, attributeRegex, 2);
// SPECIFICITY 1: Counts ID selectors.
var idRegex = new RegExp('(#[^\\#\\s\\+>~\\.\\[:]+)', 'g');
selector = replaceWithEmptyText(selector, specificity, idRegex, 1);
// SPECIFICITY 2: Counts class selectors.
var classRegex = new RegExp('(\\.[^\\s\\+>~\\.\\[:]+)', 'g');
selector = replaceWithEmptyText(selector, specificity, classRegex, 2);
// SPECIFICITY 3: Counts pseudo-element selectors.
var pseudoElementRegex =
/(::[^\s\+>~\.\[:]+|:first-line|:first-letter|:before|:after)/gi;
selector = replaceWithEmptyText(selector, specificity, pseudoElementRegex, 3);
// SPECIFICITY 2: Counts pseudo-class selectors.
// A regex for pseudo classes with brackets. For example:
// :nth-child()
// :nth-last-child()
// :nth-of-type()
// :nth-last-type()
// :lang()
var pseudoClassWithBracketsRegex = /(:[\w-]+\([^\)]*\))/gi;
selector = replaceWithEmptyText(
selector, specificity, pseudoClassWithBracketsRegex, 2);
// A regex for other pseudo classes, which don't have brackets.
var pseudoClassRegex = /(:[^\s\+>~\.\[:]+)/g;
selector = replaceWithEmptyText(selector, specificity, pseudoClassRegex, 2);
// Remove universal selector and separator characters.
selector = selector.replace(/[\*\s\+>~]/g, ' ');
// Remove any stray dots or hashes which aren't attached to words.
// These may be present if the user is live-editing this selector.
selector = selector.replace(/[#\.]/g, ' ');
// SPECIFICITY 3: The only things left should be element selectors.
var elementRegex = /([^\s\+>~\.\[:]+)/g;
selector = replaceWithEmptyText(selector, specificity, elementRegex, 3);
return specificity;
}
|
javascript
|
function calculateSpecificity(selector) {
var specificity = [0, 0, 0, 0];
// Cannot use RegExp literals for all regular expressions, IE does not accept
// the syntax.
// Matches a backslash followed by six hexadecimal digits followed by an
// optional single whitespace character.
var escapeHexadecimalRegex = new RegExp('\\\\[0-9A-Fa-f]{6}\\s?', 'g');
// Matches a backslash followed by fewer than six hexadecimal digits
// followed by a mandatory single whitespace character.
var escapeHexadecimalRegex2 = new RegExp('\\\\[0-9A-Fa-f]{1,5}\\s', 'g');
// Matches a backslash followed by any character
var escapeSpecialCharacter = /\\./g;
selector = replaceWithPlainText(selector, escapeHexadecimalRegex);
selector = replaceWithPlainText(selector, escapeHexadecimalRegex2);
selector = replaceWithPlainText(selector, escapeSpecialCharacter);
// Remove the negation pseudo-class (:not) but leave its argument because
// specificity is calculated on its argument.
var pseudoClassWithNotRegex = new RegExp(':not\\(([^\\)]*)\\)', 'g');
selector = selector.replace(pseudoClassWithNotRegex, ' $1 ');
// Remove anything after a left brace in case a user has pasted in a rule,
// not just a selector.
var rulesRegex = new RegExp('{[^]*', 'gm');
selector = selector.replace(rulesRegex, '');
// The following regular expressions assume that selectors matching the
// preceding regular expressions have been removed.
// SPECIFICITY 2: Counts attribute selectors.
var attributeRegex = new RegExp('(\\[[^\\]]+\\])', 'g');
selector = replaceWithEmptyText(selector, specificity, attributeRegex, 2);
// SPECIFICITY 1: Counts ID selectors.
var idRegex = new RegExp('(#[^\\#\\s\\+>~\\.\\[:]+)', 'g');
selector = replaceWithEmptyText(selector, specificity, idRegex, 1);
// SPECIFICITY 2: Counts class selectors.
var classRegex = new RegExp('(\\.[^\\s\\+>~\\.\\[:]+)', 'g');
selector = replaceWithEmptyText(selector, specificity, classRegex, 2);
// SPECIFICITY 3: Counts pseudo-element selectors.
var pseudoElementRegex =
/(::[^\s\+>~\.\[:]+|:first-line|:first-letter|:before|:after)/gi;
selector = replaceWithEmptyText(selector, specificity, pseudoElementRegex, 3);
// SPECIFICITY 2: Counts pseudo-class selectors.
// A regex for pseudo classes with brackets. For example:
// :nth-child()
// :nth-last-child()
// :nth-of-type()
// :nth-last-type()
// :lang()
var pseudoClassWithBracketsRegex = /(:[\w-]+\([^\)]*\))/gi;
selector = replaceWithEmptyText(
selector, specificity, pseudoClassWithBracketsRegex, 2);
// A regex for other pseudo classes, which don't have brackets.
var pseudoClassRegex = /(:[^\s\+>~\.\[:]+)/g;
selector = replaceWithEmptyText(selector, specificity, pseudoClassRegex, 2);
// Remove universal selector and separator characters.
selector = selector.replace(/[\*\s\+>~]/g, ' ');
// Remove any stray dots or hashes which aren't attached to words.
// These may be present if the user is live-editing this selector.
selector = selector.replace(/[#\.]/g, ' ');
// SPECIFICITY 3: The only things left should be element selectors.
var elementRegex = /([^\s\+>~\.\[:]+)/g;
selector = replaceWithEmptyText(selector, specificity, elementRegex, 3);
return specificity;
}
|
[
"function",
"calculateSpecificity",
"(",
"selector",
")",
"{",
"var",
"specificity",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
"]",
";",
"var",
"escapeHexadecimalRegex",
"=",
"new",
"RegExp",
"(",
"'\\\\\\\\[0-9A-Fa-f]{6}\\\\s?'",
",",
"\\\\",
")",
";",
"\\\\",
"\\\\",
"'g'",
"var",
"escapeHexadecimalRegex2",
"=",
"new",
"RegExp",
"(",
"'\\\\\\\\[0-9A-Fa-f]{1,5}\\\\s'",
",",
"\\\\",
")",
";",
"\\\\",
"\\\\",
"'g'",
"var",
"escapeSpecialCharacter",
"=",
"/",
"\\\\.",
"/",
"g",
";",
"selector",
"=",
"replaceWithPlainText",
"(",
"selector",
",",
"escapeHexadecimalRegex",
")",
";",
"selector",
"=",
"replaceWithPlainText",
"(",
"selector",
",",
"escapeHexadecimalRegex2",
")",
";",
"selector",
"=",
"replaceWithPlainText",
"(",
"selector",
",",
"escapeSpecialCharacter",
")",
";",
"var",
"pseudoClassWithNotRegex",
"=",
"new",
"RegExp",
"(",
"':not\\\\(([^\\\\)]*)\\\\)'",
",",
"\\\\",
")",
";",
"\\\\",
"\\\\",
"'g'",
"selector",
"=",
"selector",
".",
"replace",
"(",
"pseudoClassWithNotRegex",
",",
"' $1 '",
")",
";",
"var",
"rulesRegex",
"=",
"new",
"RegExp",
"(",
"'{[^]*'",
",",
"'gm'",
")",
";",
"selector",
"=",
"selector",
".",
"replace",
"(",
"rulesRegex",
",",
"''",
")",
";",
"var",
"attributeRegex",
"=",
"new",
"RegExp",
"(",
"'(\\\\[[^\\\\]]+\\\\])'",
",",
"\\\\",
")",
";",
"\\\\",
"\\\\",
"'g'",
"selector",
"=",
"replaceWithEmptyText",
"(",
"selector",
",",
"specificity",
",",
"attributeRegex",
",",
"2",
")",
";",
"var",
"idRegex",
"=",
"new",
"RegExp",
"(",
"'(#[^\\\\#\\\\s\\\\+>~\\\\.\\\\[:]+)'",
",",
"\\\\",
")",
";",
"\\\\",
"\\\\",
"}"
] |
Calculates the specificity of CSS selectors
@see http://www.w3.org/TR/css3-selectors/#specificity
@see https://github.com/keeganstreet/specificity
@see https://specificity.keegan.st/
@param {string} selector
@return {!Array<number>} The CSS specificity.
|
[
"Calculates",
"the",
"specificity",
"of",
"CSS",
"selectors"
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/cssspecificity.js#L98-L172
|
train
|
google/closure-library
|
doc/js/article.js
|
function(prefix, string) {
return string.substring(0, prefix.length) == prefix ?
string.substring(prefix.length) :
'';
}
|
javascript
|
function(prefix, string) {
return string.substring(0, prefix.length) == prefix ?
string.substring(prefix.length) :
'';
}
|
[
"function",
"(",
"prefix",
",",
"string",
")",
"{",
"return",
"string",
".",
"substring",
"(",
"0",
",",
"prefix",
".",
"length",
")",
"==",
"prefix",
"?",
"string",
".",
"substring",
"(",
"prefix",
".",
"length",
")",
":",
"''",
";",
"}"
] |
Checks for a prefix, returns everything after it if it exists
|
[
"Checks",
"for",
"a",
"prefix",
"returns",
"everything",
"after",
"it",
"if",
"it",
"exists"
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/doc/js/article.js#L292-L296
|
train
|
|
google/closure-library
|
closure/goog/base.js
|
fetchInOwnScriptThenLoad
|
function fetchInOwnScriptThenLoad() {
/** @type {!HTMLDocument} */
var doc = goog.global.document;
var key = goog.Dependency.registerCallback_(function() {
goog.Dependency.unregisterCallback_(key);
load();
});
var script = '<script type="text/javascript">' +
goog.protectScriptTag_('goog.Dependency.callback_("' + key + '");') +
'</' +
'script>';
doc.write(
goog.TRUSTED_TYPES_POLICY_ ?
goog.TRUSTED_TYPES_POLICY_.createHTML(script) :
script);
}
|
javascript
|
function fetchInOwnScriptThenLoad() {
/** @type {!HTMLDocument} */
var doc = goog.global.document;
var key = goog.Dependency.registerCallback_(function() {
goog.Dependency.unregisterCallback_(key);
load();
});
var script = '<script type="text/javascript">' +
goog.protectScriptTag_('goog.Dependency.callback_("' + key + '");') +
'</' +
'script>';
doc.write(
goog.TRUSTED_TYPES_POLICY_ ?
goog.TRUSTED_TYPES_POLICY_.createHTML(script) :
script);
}
|
[
"function",
"fetchInOwnScriptThenLoad",
"(",
")",
"{",
"var",
"doc",
"=",
"goog",
".",
"global",
".",
"document",
";",
"var",
"key",
"=",
"goog",
".",
"Dependency",
".",
"registerCallback_",
"(",
"function",
"(",
")",
"{",
"goog",
".",
"Dependency",
".",
"unregisterCallback_",
"(",
"key",
")",
";",
"load",
"(",
")",
";",
"}",
")",
";",
"var",
"script",
"=",
"'<script type=\"text/javascript\">'",
"+",
"goog",
".",
"protectScriptTag_",
"(",
"'goog.Dependency.callback_(\"'",
"+",
"key",
"+",
"'\");'",
")",
"+",
"'</'",
"+",
"'script>'",
";",
"doc",
".",
"write",
"(",
"goog",
".",
"TRUSTED_TYPES_POLICY_",
"?",
"goog",
".",
"TRUSTED_TYPES_POLICY_",
".",
"createHTML",
"(",
"script",
")",
":",
"script",
")",
";",
"}"
] |
Do not fetch now; in FireFox 47 the synchronous XHR doesn't block all events. If we fetched now and then document.write'd the contents the document.write would be an eval and would execute too soon! Instead write a script tag to fetch and eval synchronously at the correct time.
|
[
"Do",
"not",
"fetch",
"now",
";",
"in",
"FireFox",
"47",
"the",
"synchronous",
"XHR",
"doesn",
"t",
"block",
"all",
"events",
".",
"If",
"we",
"fetched",
"now",
"and",
"then",
"document",
".",
"write",
"d",
"the",
"contents",
"the",
"document",
".",
"write",
"would",
"be",
"an",
"eval",
"and",
"would",
"execute",
"too",
"soon!",
"Instead",
"write",
"a",
"script",
"tag",
"to",
"fetch",
"and",
"eval",
"synchronously",
"at",
"the",
"correct",
"time",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/base.js#L3752-L3769
|
train
|
google/closure-library
|
closure/goog/html/sanitizer/csspropertysanitizer.js
|
getSafeUri
|
function getSafeUri(uri, propName, uriRewriter) {
if (!uriRewriter) {
return null;
}
var safeUri = uriRewriter(uri, propName);
if (safeUri && SafeUrl.unwrap(safeUri) != SafeUrl.INNOCUOUS_STRING) {
return 'url("' +
SafeUrl.unwrap(safeUri).replace(NORM_URL_REGEXP, normalizeUrlChar) +
'")';
}
return null;
}
|
javascript
|
function getSafeUri(uri, propName, uriRewriter) {
if (!uriRewriter) {
return null;
}
var safeUri = uriRewriter(uri, propName);
if (safeUri && SafeUrl.unwrap(safeUri) != SafeUrl.INNOCUOUS_STRING) {
return 'url("' +
SafeUrl.unwrap(safeUri).replace(NORM_URL_REGEXP, normalizeUrlChar) +
'")';
}
return null;
}
|
[
"function",
"getSafeUri",
"(",
"uri",
",",
"propName",
",",
"uriRewriter",
")",
"{",
"if",
"(",
"!",
"uriRewriter",
")",
"{",
"return",
"null",
";",
"}",
"var",
"safeUri",
"=",
"uriRewriter",
"(",
"uri",
",",
"propName",
")",
";",
"if",
"(",
"safeUri",
"&&",
"SafeUrl",
".",
"unwrap",
"(",
"safeUri",
")",
"!=",
"SafeUrl",
".",
"INNOCUOUS_STRING",
")",
"{",
"return",
"'url(\"'",
"+",
"SafeUrl",
".",
"unwrap",
"(",
"safeUri",
")",
".",
"replace",
"(",
"NORM_URL_REGEXP",
",",
"normalizeUrlChar",
")",
"+",
"'\")'",
";",
"}",
"return",
"null",
";",
"}"
] |
Constructs a safe URI from a given URI and prop using a given uriRewriter
function.
@param {string} uri URI to be sanitized.
@param {string} propName Property name which contained the URI.
@param {?function(string, string):?SafeUrl} uriRewriter A URI rewriter that
returns a {@link SafeUrl}.
@return {?string} Safe URI for use in CSS.
|
[
"Constructs",
"a",
"safe",
"URI",
"from",
"a",
"given",
"URI",
"and",
"prop",
"using",
"a",
"given",
"uriRewriter",
"function",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/html/sanitizer/csspropertysanitizer.js#L92-L103
|
train
|
google/closure-library
|
closure/goog/labs/net/webchannel/forwardchannelrequestpool.js
|
function(opt_maxPoolSize) {
/**
* The max pool size as configured.
*
* @private {number}
*/
this.maxPoolSizeConfigured_ =
opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_;
/**
* The current size limit of the request pool. This limit is meant to be
* read-only after the channel is fully opened.
*
* If SPDY or HTTP2 is enabled, set it to the max pool size, which is also
* configurable.
*
* @private {number}
*/
this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ?
this.maxPoolSizeConfigured_ :
1;
/**
* The container for all the pending request objects.
*
* @private {Set<ChannelRequest>}
*/
this.requestPool_ = null;
if (this.maxSize_ > 1) {
this.requestPool_ = new Set();
}
/**
* The single request object when the pool size is limited to one.
*
* @private {ChannelRequest}
*/
this.request_ = null;
/**
* Saved pending messages when the pool is cancelled.
*
* @private {!Array<Wire.QueuedMap>}
*/
this.pendingMessages_ = [];
}
|
javascript
|
function(opt_maxPoolSize) {
/**
* The max pool size as configured.
*
* @private {number}
*/
this.maxPoolSizeConfigured_ =
opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_;
/**
* The current size limit of the request pool. This limit is meant to be
* read-only after the channel is fully opened.
*
* If SPDY or HTTP2 is enabled, set it to the max pool size, which is also
* configurable.
*
* @private {number}
*/
this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ?
this.maxPoolSizeConfigured_ :
1;
/**
* The container for all the pending request objects.
*
* @private {Set<ChannelRequest>}
*/
this.requestPool_ = null;
if (this.maxSize_ > 1) {
this.requestPool_ = new Set();
}
/**
* The single request object when the pool size is limited to one.
*
* @private {ChannelRequest}
*/
this.request_ = null;
/**
* Saved pending messages when the pool is cancelled.
*
* @private {!Array<Wire.QueuedMap>}
*/
this.pendingMessages_ = [];
}
|
[
"function",
"(",
"opt_maxPoolSize",
")",
"{",
"this",
".",
"maxPoolSizeConfigured_",
"=",
"opt_maxPoolSize",
"||",
"ForwardChannelRequestPool",
".",
"MAX_POOL_SIZE_",
";",
"this",
".",
"maxSize_",
"=",
"ForwardChannelRequestPool",
".",
"isSpdyOrHttp2Enabled_",
"(",
")",
"?",
"this",
".",
"maxPoolSizeConfigured_",
":",
"1",
";",
"this",
".",
"requestPool_",
"=",
"null",
";",
"if",
"(",
"this",
".",
"maxSize_",
">",
"1",
")",
"{",
"this",
".",
"requestPool_",
"=",
"new",
"Set",
"(",
")",
";",
"}",
"this",
".",
"request_",
"=",
"null",
";",
"this",
".",
"pendingMessages_",
"=",
"[",
"]",
";",
"}"
] |
This class represents the state of all forward channel requests.
@param {number=} opt_maxPoolSize The maximum pool size.
@struct @constructor @final
|
[
"This",
"class",
"represents",
"the",
"state",
"of",
"all",
"forward",
"channel",
"requests",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/labs/net/webchannel/forwardchannelrequestpool.js#L38-L84
|
train
|
|
google/closure-library
|
closure/goog/loader/activemodulemanager.js
|
get
|
function get() {
if (!moduleManager && getDefault) {
moduleManager = getDefault();
}
asserts.assert(
moduleManager != null, 'The module manager has not yet been set.');
return moduleManager;
}
|
javascript
|
function get() {
if (!moduleManager && getDefault) {
moduleManager = getDefault();
}
asserts.assert(
moduleManager != null, 'The module manager has not yet been set.');
return moduleManager;
}
|
[
"function",
"get",
"(",
")",
"{",
"if",
"(",
"!",
"moduleManager",
"&&",
"getDefault",
")",
"{",
"moduleManager",
"=",
"getDefault",
"(",
")",
";",
"}",
"asserts",
".",
"assert",
"(",
"moduleManager",
"!=",
"null",
",",
"'The module manager has not yet been set.'",
")",
";",
"return",
"moduleManager",
";",
"}"
] |
Gets the active module manager, instantiating one if necessary.
@return {!AbstractModuleManager}
|
[
"Gets",
"the",
"active",
"module",
"manager",
"instantiating",
"one",
"if",
"necessary",
"."
] |
97390e9ca4483cebb9628e06026139fbb3023d65
|
https://github.com/google/closure-library/blob/97390e9ca4483cebb9628e06026139fbb3023d65/closure/goog/loader/activemodulemanager.js#L36-L43
|
train
|
mrvautin/expressCart
|
lib/common.js
|
fixProductDates
|
function fixProductDates(products){
let index = 0;
products.forEach((product) => {
products[index].productAddedDate = new Date();
index++;
});
return products;
}
|
javascript
|
function fixProductDates(products){
let index = 0;
products.forEach((product) => {
products[index].productAddedDate = new Date();
index++;
});
return products;
}
|
[
"function",
"fixProductDates",
"(",
"products",
")",
"{",
"let",
"index",
"=",
"0",
";",
"products",
".",
"forEach",
"(",
"(",
"product",
")",
"=>",
"{",
"products",
"[",
"index",
"]",
".",
"productAddedDate",
"=",
"new",
"Date",
"(",
")",
";",
"index",
"++",
";",
"}",
")",
";",
"return",
"products",
";",
"}"
] |
Adds current date to product added date when smashing into DB
|
[
"Adds",
"current",
"date",
"to",
"product",
"added",
"date",
"when",
"smashing",
"into",
"DB"
] |
0b6071b6d963d786684fb9cfa7d1ccc499c3ce27
|
https://github.com/mrvautin/expressCart/blob/0b6071b6d963d786684fb9cfa7d1ccc499c3ce27/lib/common.js#L721-L728
|
train
|
NetEase/pomelo
|
template/web-server/public/js/lib/build/build.js
|
mixin
|
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
|
javascript
|
function mixin(obj) {
for (var key in Emitter.prototype) {
obj[key] = Emitter.prototype[key];
}
return obj;
}
|
[
"function",
"mixin",
"(",
"obj",
")",
"{",
"for",
"(",
"var",
"key",
"in",
"Emitter",
".",
"prototype",
")",
"{",
"obj",
"[",
"key",
"]",
"=",
"Emitter",
".",
"prototype",
"[",
"key",
"]",
";",
"}",
"return",
"obj",
";",
"}"
] |
Mixin the emitter properties.
@param {Object} obj
@return {Object}
@api private
|
[
"Mixin",
"the",
"emitter",
"properties",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/template/web-server/public/js/lib/build/build.js#L254-L259
|
train
|
NetEase/pomelo
|
template/web-server/public/js/lib/build/build.js
|
encode2UTF8
|
function encode2UTF8(charCode){
if(charCode <= 0x7f){
return [charCode];
}else if(charCode <= 0x7ff){
return [0xc0|(charCode>>6), 0x80|(charCode & 0x3f)];
}else{
return [0xe0|(charCode>>12), 0x80|((charCode & 0xfc0)>>6), 0x80|(charCode & 0x3f)];
}
}
|
javascript
|
function encode2UTF8(charCode){
if(charCode <= 0x7f){
return [charCode];
}else if(charCode <= 0x7ff){
return [0xc0|(charCode>>6), 0x80|(charCode & 0x3f)];
}else{
return [0xe0|(charCode>>12), 0x80|((charCode & 0xfc0)>>6), 0x80|(charCode & 0x3f)];
}
}
|
[
"function",
"encode2UTF8",
"(",
"charCode",
")",
"{",
"if",
"(",
"charCode",
"<=",
"0x7f",
")",
"{",
"return",
"[",
"charCode",
"]",
";",
"}",
"else",
"if",
"(",
"charCode",
"<=",
"0x7ff",
")",
"{",
"return",
"[",
"0xc0",
"|",
"(",
"charCode",
">>",
"6",
")",
",",
"0x80",
"|",
"(",
"charCode",
"&",
"0x3f",
")",
"]",
";",
"}",
"else",
"{",
"return",
"[",
"0xe0",
"|",
"(",
"charCode",
">>",
"12",
")",
",",
"0x80",
"|",
"(",
"(",
"charCode",
"&",
"0xfc0",
")",
">>",
"6",
")",
",",
"0x80",
"|",
"(",
"charCode",
"&",
"0x3f",
")",
"]",
";",
"}",
"}"
] |
Encode a unicode16 char code to utf8 bytes
|
[
"Encode",
"a",
"unicode16",
"char",
"code",
"to",
"utf8",
"bytes"
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/template/web-server/public/js/lib/build/build.js#L974-L982
|
train
|
NetEase/pomelo
|
lib/common/service/channelService.js
|
function(app, opts) {
opts = opts || {};
this.app = app;
this.channels = {};
this.prefix = opts.prefix;
this.store = opts.store;
this.broadcastFilter = opts.broadcastFilter;
this.channelRemote = new ChannelRemote(app);
}
|
javascript
|
function(app, opts) {
opts = opts || {};
this.app = app;
this.channels = {};
this.prefix = opts.prefix;
this.store = opts.store;
this.broadcastFilter = opts.broadcastFilter;
this.channelRemote = new ChannelRemote(app);
}
|
[
"function",
"(",
"app",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"app",
"=",
"app",
";",
"this",
".",
"channels",
"=",
"{",
"}",
";",
"this",
".",
"prefix",
"=",
"opts",
".",
"prefix",
";",
"this",
".",
"store",
"=",
"opts",
".",
"store",
";",
"this",
".",
"broadcastFilter",
"=",
"opts",
".",
"broadcastFilter",
";",
"this",
".",
"channelRemote",
"=",
"new",
"ChannelRemote",
"(",
"app",
")",
";",
"}"
] |
Create and maintain channels for server local.
ChannelService is created by channel component which is a default loaded
component of pomelo and channel service would be accessed by `app.get('channelService')`.
@class
@constructor
|
[
"Create",
"and",
"maintain",
"channels",
"for",
"server",
"local",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/common/service/channelService.js#L21-L29
|
train
|
|
NetEase/pomelo
|
lib/common/service/channelService.js
|
function(name, service) {
this.name = name;
this.groups = {}; // group map for uids. key: sid, value: [uid]
this.records = {}; // member records. key: uid
this.__channelService__ = service;
this.state = ST_INITED;
this.userAmount =0;
}
|
javascript
|
function(name, service) {
this.name = name;
this.groups = {}; // group map for uids. key: sid, value: [uid]
this.records = {}; // member records. key: uid
this.__channelService__ = service;
this.state = ST_INITED;
this.userAmount =0;
}
|
[
"function",
"(",
"name",
",",
"service",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"groups",
"=",
"{",
"}",
";",
"this",
".",
"records",
"=",
"{",
"}",
";",
"this",
".",
"__channelService__",
"=",
"service",
";",
"this",
".",
"state",
"=",
"ST_INITED",
";",
"this",
".",
"userAmount",
"=",
"0",
";",
"}"
] |
Channel maintains the receiver collection for a subject. You can
add users into a channel and then broadcast message to them by channel.
@class channel
@constructor
|
[
"Channel",
"maintains",
"the",
"receiver",
"collection",
"for",
"a",
"subject",
".",
"You",
"can",
"add",
"users",
"into",
"a",
"channel",
"and",
"then",
"broadcast",
"message",
"to",
"them",
"by",
"channel",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/common/service/channelService.js#L205-L212
|
train
|
|
NetEase/pomelo
|
lib/common/service/channelService.js
|
function(uid, sid, groups) {
if(!sid) {
logger.warn('ignore uid %j for sid not specified.', uid);
return false;
}
var group = groups[sid];
if(!group) {
group = [];
groups[sid] = group;
}
group.push(uid);
return true;
}
|
javascript
|
function(uid, sid, groups) {
if(!sid) {
logger.warn('ignore uid %j for sid not specified.', uid);
return false;
}
var group = groups[sid];
if(!group) {
group = [];
groups[sid] = group;
}
group.push(uid);
return true;
}
|
[
"function",
"(",
"uid",
",",
"sid",
",",
"groups",
")",
"{",
"if",
"(",
"!",
"sid",
")",
"{",
"logger",
".",
"warn",
"(",
"'ignore uid %j for sid not specified.'",
",",
"uid",
")",
";",
"return",
"false",
";",
"}",
"var",
"group",
"=",
"groups",
"[",
"sid",
"]",
";",
"if",
"(",
"!",
"group",
")",
"{",
"group",
"=",
"[",
"]",
";",
"groups",
"[",
"sid",
"]",
"=",
"group",
";",
"}",
"group",
".",
"push",
"(",
"uid",
")",
";",
"return",
"true",
";",
"}"
] |
add uid and sid into group. ignore any uid that uid not specified.
@param uid user id
@param sid server id
@param groups {Object} grouped uids, , key: sid, value: [uid]
|
[
"add",
"uid",
"and",
"sid",
"into",
"group",
".",
"ignore",
"any",
"uid",
"that",
"uid",
"not",
"specified",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/common/service/channelService.js#L340-L354
|
train
|
|
NetEase/pomelo
|
lib/common/service/sessionService.js
|
function(sid, frontendId, socket, service) {
EventEmitter.call(this);
this.id = sid; // r
this.frontendId = frontendId; // r
this.uid = null; // r
this.settings = {};
// private
this.__socket__ = socket;
this.__sessionService__ = service;
this.__state__ = ST_INITED;
}
|
javascript
|
function(sid, frontendId, socket, service) {
EventEmitter.call(this);
this.id = sid; // r
this.frontendId = frontendId; // r
this.uid = null; // r
this.settings = {};
// private
this.__socket__ = socket;
this.__sessionService__ = service;
this.__state__ = ST_INITED;
}
|
[
"function",
"(",
"sid",
",",
"frontendId",
",",
"socket",
",",
"service",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"id",
"=",
"sid",
";",
"this",
".",
"frontendId",
"=",
"frontendId",
";",
"this",
".",
"uid",
"=",
"null",
";",
"this",
".",
"settings",
"=",
"{",
"}",
";",
"this",
".",
"__socket__",
"=",
"socket",
";",
"this",
".",
"__sessionService__",
"=",
"service",
";",
"this",
".",
"__state__",
"=",
"ST_INITED",
";",
"}"
] |
Session maintains the relationship between client connection and user information.
There is a session associated with each client connection. And it should bind to a
user id after the client passes the identification.
Session is created in frontend server and should not be accessed in handler.
There is a proxy class called BackendSession in backend servers and FrontendSession
in frontend servers.
|
[
"Session",
"maintains",
"the",
"relationship",
"between",
"client",
"connection",
"and",
"user",
"information",
".",
"There",
"is",
"a",
"session",
"associated",
"with",
"each",
"client",
"connection",
".",
"And",
"it",
"should",
"bind",
"to",
"a",
"user",
"id",
"after",
"the",
"client",
"passes",
"the",
"identification",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/common/service/sessionService.js#L431-L442
|
train
|
|
NetEase/pomelo
|
lib/common/service/sessionService.js
|
function(session) {
EventEmitter.call(this);
clone(session, this, FRONTEND_SESSION_FIELDS);
// deep copy for settings
this.settings = dclone(session.settings);
this.__session__ = session;
}
|
javascript
|
function(session) {
EventEmitter.call(this);
clone(session, this, FRONTEND_SESSION_FIELDS);
// deep copy for settings
this.settings = dclone(session.settings);
this.__session__ = session;
}
|
[
"function",
"(",
"session",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"clone",
"(",
"session",
",",
"this",
",",
"FRONTEND_SESSION_FIELDS",
")",
";",
"this",
".",
"settings",
"=",
"dclone",
"(",
"session",
".",
"settings",
")",
";",
"this",
".",
"__session__",
"=",
"session",
";",
"}"
] |
Frontend session for frontend server.
|
[
"Frontend",
"session",
"for",
"frontend",
"server",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/common/service/sessionService.js#L557-L563
|
train
|
|
NetEase/pomelo
|
lib/connectors/hybrid/tcpsocket.js
|
function(socket, opts) {
if(!(this instanceof Socket)) {
return new Socket(socket, opts);
}
if(!socket || !opts) {
throw new Error('invalid socket or opts');
}
if(!opts.headSize || typeof opts.headHandler !== 'function') {
throw new Error('invalid opts.headSize or opts.headHandler');
}
// stream style interfaces.
// TODO: need to port to stream2 after node 0.9
Stream.call(this);
this.readable = true;
this.writeable = true;
this._socket = socket;
this.headSize = opts.headSize;
this.closeMethod = opts.closeMethod;
this.headBuffer = new Buffer(opts.headSize);
this.headHandler = opts.headHandler;
this.headOffset = 0;
this.packageOffset = 0;
this.packageSize = 0;
this.packageBuffer = null;
// bind event form the origin socket
this._socket.on('data', ondata.bind(null, this));
this._socket.on('end', onend.bind(null, this));
this._socket.on('error', this.emit.bind(this, 'error'));
this._socket.on('close', this.emit.bind(this, 'close'));
this.state = ST_HEAD;
}
|
javascript
|
function(socket, opts) {
if(!(this instanceof Socket)) {
return new Socket(socket, opts);
}
if(!socket || !opts) {
throw new Error('invalid socket or opts');
}
if(!opts.headSize || typeof opts.headHandler !== 'function') {
throw new Error('invalid opts.headSize or opts.headHandler');
}
// stream style interfaces.
// TODO: need to port to stream2 after node 0.9
Stream.call(this);
this.readable = true;
this.writeable = true;
this._socket = socket;
this.headSize = opts.headSize;
this.closeMethod = opts.closeMethod;
this.headBuffer = new Buffer(opts.headSize);
this.headHandler = opts.headHandler;
this.headOffset = 0;
this.packageOffset = 0;
this.packageSize = 0;
this.packageBuffer = null;
// bind event form the origin socket
this._socket.on('data', ondata.bind(null, this));
this._socket.on('end', onend.bind(null, this));
this._socket.on('error', this.emit.bind(this, 'error'));
this._socket.on('close', this.emit.bind(this, 'close'));
this.state = ST_HEAD;
}
|
[
"function",
"(",
"socket",
",",
"opts",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Socket",
")",
")",
"{",
"return",
"new",
"Socket",
"(",
"socket",
",",
"opts",
")",
";",
"}",
"if",
"(",
"!",
"socket",
"||",
"!",
"opts",
")",
"{",
"throw",
"new",
"Error",
"(",
"'invalid socket or opts'",
")",
";",
"}",
"if",
"(",
"!",
"opts",
".",
"headSize",
"||",
"typeof",
"opts",
".",
"headHandler",
"!==",
"'function'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'invalid opts.headSize or opts.headHandler'",
")",
";",
"}",
"Stream",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"readable",
"=",
"true",
";",
"this",
".",
"writeable",
"=",
"true",
";",
"this",
".",
"_socket",
"=",
"socket",
";",
"this",
".",
"headSize",
"=",
"opts",
".",
"headSize",
";",
"this",
".",
"closeMethod",
"=",
"opts",
".",
"closeMethod",
";",
"this",
".",
"headBuffer",
"=",
"new",
"Buffer",
"(",
"opts",
".",
"headSize",
")",
";",
"this",
".",
"headHandler",
"=",
"opts",
".",
"headHandler",
";",
"this",
".",
"headOffset",
"=",
"0",
";",
"this",
".",
"packageOffset",
"=",
"0",
";",
"this",
".",
"packageSize",
"=",
"0",
";",
"this",
".",
"packageBuffer",
"=",
"null",
";",
"this",
".",
"_socket",
".",
"on",
"(",
"'data'",
",",
"ondata",
".",
"bind",
"(",
"null",
",",
"this",
")",
")",
";",
"this",
".",
"_socket",
".",
"on",
"(",
"'end'",
",",
"onend",
".",
"bind",
"(",
"null",
",",
"this",
")",
")",
";",
"this",
".",
"_socket",
".",
"on",
"(",
"'error'",
",",
"this",
".",
"emit",
".",
"bind",
"(",
"this",
",",
"'error'",
")",
")",
";",
"this",
".",
"_socket",
".",
"on",
"(",
"'close'",
",",
"this",
".",
"emit",
".",
"bind",
"(",
"this",
",",
"'close'",
")",
")",
";",
"this",
".",
"state",
"=",
"ST_HEAD",
";",
"}"
] |
closed
Tcp socket wrapper with package compositing.
Collect the package from socket and emit a completed package with 'data' event.
Uniform with ws.WebSocket interfaces.
@param {Object} socket origin socket from node.js net module
@param {Object} opts options parameter.
opts.headSize size of package head
opts.headHandler(headBuffer) handler for package head. caculate and return body size from head data.
|
[
"closed",
"Tcp",
"socket",
"wrapper",
"with",
"package",
"compositing",
".",
"Collect",
"the",
"package",
"from",
"socket",
"and",
"emit",
"a",
"completed",
"package",
"with",
"data",
"event",
".",
"Uniform",
"with",
"ws",
".",
"WebSocket",
"interfaces",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/connectors/hybrid/tcpsocket.js#L24-L61
|
train
|
|
NetEase/pomelo
|
lib/connectors/hybrid/tcpsocket.js
|
function(socket, data, offset) {
var hlen = socket.headSize - socket.headOffset;
var dlen = data.length - offset;
var len = Math.min(hlen, dlen);
var dend = offset + len;
data.copy(socket.headBuffer, socket.headOffset, offset, dend);
socket.headOffset += len;
if(socket.headOffset === socket.headSize) {
// if head segment finished
var size = socket.headHandler(socket.headBuffer);
if(size < 0) {
throw new Error('invalid body size: ' + size);
}
// check if header contains a valid type
if(checkTypeData(socket.headBuffer[0])) {
socket.packageSize = size + socket.headSize;
socket.packageBuffer = new Buffer(socket.packageSize);
socket.headBuffer.copy(socket.packageBuffer, 0, 0, socket.headSize);
socket.packageOffset = socket.headSize;
socket.state = ST_BODY;
} else {
dend = data.length;
logger.error('close the connection with invalid head message, the remote ip is %s && port is %s && message is %j', socket._socket.remoteAddress, socket._socket.remotePort, data);
socket.close();
}
}
return dend;
}
|
javascript
|
function(socket, data, offset) {
var hlen = socket.headSize - socket.headOffset;
var dlen = data.length - offset;
var len = Math.min(hlen, dlen);
var dend = offset + len;
data.copy(socket.headBuffer, socket.headOffset, offset, dend);
socket.headOffset += len;
if(socket.headOffset === socket.headSize) {
// if head segment finished
var size = socket.headHandler(socket.headBuffer);
if(size < 0) {
throw new Error('invalid body size: ' + size);
}
// check if header contains a valid type
if(checkTypeData(socket.headBuffer[0])) {
socket.packageSize = size + socket.headSize;
socket.packageBuffer = new Buffer(socket.packageSize);
socket.headBuffer.copy(socket.packageBuffer, 0, 0, socket.headSize);
socket.packageOffset = socket.headSize;
socket.state = ST_BODY;
} else {
dend = data.length;
logger.error('close the connection with invalid head message, the remote ip is %s && port is %s && message is %j', socket._socket.remoteAddress, socket._socket.remotePort, data);
socket.close();
}
}
return dend;
}
|
[
"function",
"(",
"socket",
",",
"data",
",",
"offset",
")",
"{",
"var",
"hlen",
"=",
"socket",
".",
"headSize",
"-",
"socket",
".",
"headOffset",
";",
"var",
"dlen",
"=",
"data",
".",
"length",
"-",
"offset",
";",
"var",
"len",
"=",
"Math",
".",
"min",
"(",
"hlen",
",",
"dlen",
")",
";",
"var",
"dend",
"=",
"offset",
"+",
"len",
";",
"data",
".",
"copy",
"(",
"socket",
".",
"headBuffer",
",",
"socket",
".",
"headOffset",
",",
"offset",
",",
"dend",
")",
";",
"socket",
".",
"headOffset",
"+=",
"len",
";",
"if",
"(",
"socket",
".",
"headOffset",
"===",
"socket",
".",
"headSize",
")",
"{",
"var",
"size",
"=",
"socket",
".",
"headHandler",
"(",
"socket",
".",
"headBuffer",
")",
";",
"if",
"(",
"size",
"<",
"0",
")",
"{",
"throw",
"new",
"Error",
"(",
"'invalid body size: '",
"+",
"size",
")",
";",
"}",
"if",
"(",
"checkTypeData",
"(",
"socket",
".",
"headBuffer",
"[",
"0",
"]",
")",
")",
"{",
"socket",
".",
"packageSize",
"=",
"size",
"+",
"socket",
".",
"headSize",
";",
"socket",
".",
"packageBuffer",
"=",
"new",
"Buffer",
"(",
"socket",
".",
"packageSize",
")",
";",
"socket",
".",
"headBuffer",
".",
"copy",
"(",
"socket",
".",
"packageBuffer",
",",
"0",
",",
"0",
",",
"socket",
".",
"headSize",
")",
";",
"socket",
".",
"packageOffset",
"=",
"socket",
".",
"headSize",
";",
"socket",
".",
"state",
"=",
"ST_BODY",
";",
"}",
"else",
"{",
"dend",
"=",
"data",
".",
"length",
";",
"logger",
".",
"error",
"(",
"'close the connection with invalid head message, the remote ip is %s && port is %s && message is %j'",
",",
"socket",
".",
"_socket",
".",
"remoteAddress",
",",
"socket",
".",
"_socket",
".",
"remotePort",
",",
"data",
")",
";",
"socket",
".",
"close",
"(",
")",
";",
"}",
"}",
"return",
"dend",
";",
"}"
] |
Read head segment from data to socket.headBuffer.
@param {Object} socket Socket instance
@param {Object} data Buffer instance
@param {Number} offset offset read star from data
@return {Number} new offset of data after read
|
[
"Read",
"head",
"segment",
"from",
"data",
"to",
"socket",
".",
"headBuffer",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/connectors/hybrid/tcpsocket.js#L129-L160
|
train
|
|
NetEase/pomelo
|
lib/connectors/hybrid/tcpsocket.js
|
function(socket, data, offset) {
var blen = socket.packageSize - socket.packageOffset;
var dlen = data.length - offset;
var len = Math.min(blen, dlen);
var dend = offset + len;
data.copy(socket.packageBuffer, socket.packageOffset, offset, dend);
socket.packageOffset += len;
if(socket.packageOffset === socket.packageSize) {
// if all the package finished
var buffer = socket.packageBuffer;
socket.emit('message', buffer);
reset(socket);
}
return dend;
}
|
javascript
|
function(socket, data, offset) {
var blen = socket.packageSize - socket.packageOffset;
var dlen = data.length - offset;
var len = Math.min(blen, dlen);
var dend = offset + len;
data.copy(socket.packageBuffer, socket.packageOffset, offset, dend);
socket.packageOffset += len;
if(socket.packageOffset === socket.packageSize) {
// if all the package finished
var buffer = socket.packageBuffer;
socket.emit('message', buffer);
reset(socket);
}
return dend;
}
|
[
"function",
"(",
"socket",
",",
"data",
",",
"offset",
")",
"{",
"var",
"blen",
"=",
"socket",
".",
"packageSize",
"-",
"socket",
".",
"packageOffset",
";",
"var",
"dlen",
"=",
"data",
".",
"length",
"-",
"offset",
";",
"var",
"len",
"=",
"Math",
".",
"min",
"(",
"blen",
",",
"dlen",
")",
";",
"var",
"dend",
"=",
"offset",
"+",
"len",
";",
"data",
".",
"copy",
"(",
"socket",
".",
"packageBuffer",
",",
"socket",
".",
"packageOffset",
",",
"offset",
",",
"dend",
")",
";",
"socket",
".",
"packageOffset",
"+=",
"len",
";",
"if",
"(",
"socket",
".",
"packageOffset",
"===",
"socket",
".",
"packageSize",
")",
"{",
"var",
"buffer",
"=",
"socket",
".",
"packageBuffer",
";",
"socket",
".",
"emit",
"(",
"'message'",
",",
"buffer",
")",
";",
"reset",
"(",
"socket",
")",
";",
"}",
"return",
"dend",
";",
"}"
] |
Read body segment from data buffer to socket.packageBuffer;
@param {Object} socket Socket instance
@param {Object} data Buffer instance
@param {Number} offset offset read star from data
@return {Number} new offset of data after read
|
[
"Read",
"body",
"segment",
"from",
"data",
"buffer",
"to",
"socket",
".",
"packageBuffer",
";"
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/connectors/hybrid/tcpsocket.js#L170-L188
|
train
|
|
NetEase/pomelo
|
lib/server/server.js
|
function(isGlobal, server, msg, session, cb) {
var fm;
if(isGlobal) {
fm = server.globalFilterService;
} else {
fm = server.filterService;
}
if(fm) {
fm.beforeFilter(msg, session, cb);
} else {
utils.invokeCallback(cb);
}
}
|
javascript
|
function(isGlobal, server, msg, session, cb) {
var fm;
if(isGlobal) {
fm = server.globalFilterService;
} else {
fm = server.filterService;
}
if(fm) {
fm.beforeFilter(msg, session, cb);
} else {
utils.invokeCallback(cb);
}
}
|
[
"function",
"(",
"isGlobal",
",",
"server",
",",
"msg",
",",
"session",
",",
"cb",
")",
"{",
"var",
"fm",
";",
"if",
"(",
"isGlobal",
")",
"{",
"fm",
"=",
"server",
".",
"globalFilterService",
";",
"}",
"else",
"{",
"fm",
"=",
"server",
".",
"filterService",
";",
"}",
"if",
"(",
"fm",
")",
"{",
"fm",
".",
"beforeFilter",
"(",
"msg",
",",
"session",
",",
"cb",
")",
";",
"}",
"else",
"{",
"utils",
".",
"invokeCallback",
"(",
"cb",
")",
";",
"}",
"}"
] |
Fire before filter chain if any
|
[
"Fire",
"before",
"filter",
"chain",
"if",
"any"
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/server/server.js#L234-L246
|
train
|
|
NetEase/pomelo
|
lib/server/server.js
|
function(isGlobal, server, err, msg, session, resp, opts, cb) {
if(isGlobal) {
cb(err, resp, opts);
// after filter should not interfere response
afterFilter(isGlobal, server, err, msg, session, resp, opts, cb);
} else {
afterFilter(isGlobal, server, err, msg, session, resp, opts, cb);
}
}
|
javascript
|
function(isGlobal, server, err, msg, session, resp, opts, cb) {
if(isGlobal) {
cb(err, resp, opts);
// after filter should not interfere response
afterFilter(isGlobal, server, err, msg, session, resp, opts, cb);
} else {
afterFilter(isGlobal, server, err, msg, session, resp, opts, cb);
}
}
|
[
"function",
"(",
"isGlobal",
",",
"server",
",",
"err",
",",
"msg",
",",
"session",
",",
"resp",
",",
"opts",
",",
"cb",
")",
"{",
"if",
"(",
"isGlobal",
")",
"{",
"cb",
"(",
"err",
",",
"resp",
",",
"opts",
")",
";",
"afterFilter",
"(",
"isGlobal",
",",
"server",
",",
"err",
",",
"msg",
",",
"session",
",",
"resp",
",",
"opts",
",",
"cb",
")",
";",
"}",
"else",
"{",
"afterFilter",
"(",
"isGlobal",
",",
"server",
",",
"err",
",",
"msg",
",",
"session",
",",
"resp",
",",
"opts",
",",
"cb",
")",
";",
"}",
"}"
] |
Send response to client and fire after filter chain if any.
|
[
"Send",
"response",
"to",
"client",
"and",
"fire",
"after",
"filter",
"chain",
"if",
"any",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/server/server.js#L297-L305
|
train
|
|
NetEase/pomelo
|
lib/server/server.js
|
function(cron, crons, server) {
if(!containCron(cron.id, crons)) {
server.crons.push(cron);
} else {
logger.warn('cron is duplicated: %j', cron);
}
}
|
javascript
|
function(cron, crons, server) {
if(!containCron(cron.id, crons)) {
server.crons.push(cron);
} else {
logger.warn('cron is duplicated: %j', cron);
}
}
|
[
"function",
"(",
"cron",
",",
"crons",
",",
"server",
")",
"{",
"if",
"(",
"!",
"containCron",
"(",
"cron",
".",
"id",
",",
"crons",
")",
")",
"{",
"server",
".",
"crons",
".",
"push",
"(",
"cron",
")",
";",
"}",
"else",
"{",
"logger",
".",
"warn",
"(",
"'cron is duplicated: %j'",
",",
"cron",
")",
";",
"}",
"}"
] |
If cron is not in crons then put it in the array.
|
[
"If",
"cron",
"is",
"not",
"in",
"crons",
"then",
"put",
"it",
"in",
"the",
"array",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/server/server.js#L434-L440
|
train
|
|
NetEase/pomelo
|
lib/server/server.js
|
function(id, crons) {
for(var i=0, l=crons.length; i<l; i++) {
if(id === crons[i].id) {
return true;
}
}
return false;
}
|
javascript
|
function(id, crons) {
for(var i=0, l=crons.length; i<l; i++) {
if(id === crons[i].id) {
return true;
}
}
return false;
}
|
[
"function",
"(",
"id",
",",
"crons",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"crons",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"if",
"(",
"id",
"===",
"crons",
"[",
"i",
"]",
".",
"id",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Check if cron is in crons.
|
[
"Check",
"if",
"cron",
"is",
"in",
"crons",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/server/server.js#L445-L452
|
train
|
|
NetEase/pomelo
|
lib/connectors/hybrid/wsprocessor.js
|
function() {
EventEmitter.call(this);
this.httpServer = new HttpServer();
var self = this;
this.wsServer = new WebSocketServer({server: this.httpServer});
this.wsServer.on('connection', function(socket) {
// emit socket to outside
self.emit('connection', socket);
});
this.state = ST_STARTED;
}
|
javascript
|
function() {
EventEmitter.call(this);
this.httpServer = new HttpServer();
var self = this;
this.wsServer = new WebSocketServer({server: this.httpServer});
this.wsServer.on('connection', function(socket) {
// emit socket to outside
self.emit('connection', socket);
});
this.state = ST_STARTED;
}
|
[
"function",
"(",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"httpServer",
"=",
"new",
"HttpServer",
"(",
")",
";",
"var",
"self",
"=",
"this",
";",
"this",
".",
"wsServer",
"=",
"new",
"WebSocketServer",
"(",
"{",
"server",
":",
"this",
".",
"httpServer",
"}",
")",
";",
"this",
".",
"wsServer",
".",
"on",
"(",
"'connection'",
",",
"function",
"(",
"socket",
")",
"{",
"self",
".",
"emit",
"(",
"'connection'",
",",
"socket",
")",
";",
"}",
")",
";",
"this",
".",
"state",
"=",
"ST_STARTED",
";",
"}"
] |
websocket protocol processor
|
[
"websocket",
"protocol",
"processor"
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/connectors/hybrid/wsprocessor.js#L12-L25
|
train
|
|
NetEase/pomelo
|
lib/util/appUtil.js
|
function(app, args) {
app.set(Constants.RESERVED.ENV, args.env || process.env.NODE_ENV || Constants.RESERVED.ENV_DEV, true);
}
|
javascript
|
function(app, args) {
app.set(Constants.RESERVED.ENV, args.env || process.env.NODE_ENV || Constants.RESERVED.ENV_DEV, true);
}
|
[
"function",
"(",
"app",
",",
"args",
")",
"{",
"app",
".",
"set",
"(",
"Constants",
".",
"RESERVED",
".",
"ENV",
",",
"args",
".",
"env",
"||",
"process",
".",
"env",
".",
"NODE_ENV",
"||",
"Constants",
".",
"RESERVED",
".",
"ENV_DEV",
",",
"true",
")",
";",
"}"
] |
Setup enviroment.
|
[
"Setup",
"enviroment",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/util/appUtil.js#L193-L195
|
train
|
|
NetEase/pomelo
|
lib/util/appUtil.js
|
function(app) {
if (process.env.POMELO_LOGGER !== 'off') {
var env = app.get(Constants.RESERVED.ENV);
var originPath = path.join(app.getBase(), Constants.FILEPATH.LOG);
var presentPath = path.join(app.getBase(), Constants.FILEPATH.CONFIG_DIR, env, path.basename(Constants.FILEPATH.LOG));
if(fs.existsSync(originPath)) {
log.configure(app, originPath);
} else if(fs.existsSync(presentPath)) {
log.configure(app, presentPath);
} else {
logger.error('logger file path configuration is error.');
}
}
}
|
javascript
|
function(app) {
if (process.env.POMELO_LOGGER !== 'off') {
var env = app.get(Constants.RESERVED.ENV);
var originPath = path.join(app.getBase(), Constants.FILEPATH.LOG);
var presentPath = path.join(app.getBase(), Constants.FILEPATH.CONFIG_DIR, env, path.basename(Constants.FILEPATH.LOG));
if(fs.existsSync(originPath)) {
log.configure(app, originPath);
} else if(fs.existsSync(presentPath)) {
log.configure(app, presentPath);
} else {
logger.error('logger file path configuration is error.');
}
}
}
|
[
"function",
"(",
"app",
")",
"{",
"if",
"(",
"process",
".",
"env",
".",
"POMELO_LOGGER",
"!==",
"'off'",
")",
"{",
"var",
"env",
"=",
"app",
".",
"get",
"(",
"Constants",
".",
"RESERVED",
".",
"ENV",
")",
";",
"var",
"originPath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"getBase",
"(",
")",
",",
"Constants",
".",
"FILEPATH",
".",
"LOG",
")",
";",
"var",
"presentPath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"getBase",
"(",
")",
",",
"Constants",
".",
"FILEPATH",
".",
"CONFIG_DIR",
",",
"env",
",",
"path",
".",
"basename",
"(",
"Constants",
".",
"FILEPATH",
".",
"LOG",
")",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"originPath",
")",
")",
"{",
"log",
".",
"configure",
"(",
"app",
",",
"originPath",
")",
";",
"}",
"else",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"presentPath",
")",
")",
"{",
"log",
".",
"configure",
"(",
"app",
",",
"presentPath",
")",
";",
"}",
"else",
"{",
"logger",
".",
"error",
"(",
"'logger file path configuration is error.'",
")",
";",
"}",
"}",
"}"
] |
Configure custom logger.
|
[
"Configure",
"custom",
"logger",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/util/appUtil.js#L200-L213
|
train
|
|
NetEase/pomelo
|
lib/util/appUtil.js
|
function(app) {
var filePath = path.join(app.getBase(), Constants.FILEPATH.SERVER_DIR, app.serverType, Constants.FILEPATH.LIFECYCLE);
if(!fs.existsSync(filePath)) {
return;
}
var lifecycle = require(filePath);
for(var key in lifecycle) {
if(typeof lifecycle[key] === 'function') {
app.lifecycleCbs[key] = lifecycle[key];
} else {
logger.warn('lifecycle.js in %s is error format.', filePath);
}
}
}
|
javascript
|
function(app) {
var filePath = path.join(app.getBase(), Constants.FILEPATH.SERVER_DIR, app.serverType, Constants.FILEPATH.LIFECYCLE);
if(!fs.existsSync(filePath)) {
return;
}
var lifecycle = require(filePath);
for(var key in lifecycle) {
if(typeof lifecycle[key] === 'function') {
app.lifecycleCbs[key] = lifecycle[key];
} else {
logger.warn('lifecycle.js in %s is error format.', filePath);
}
}
}
|
[
"function",
"(",
"app",
")",
"{",
"var",
"filePath",
"=",
"path",
".",
"join",
"(",
"app",
".",
"getBase",
"(",
")",
",",
"Constants",
".",
"FILEPATH",
".",
"SERVER_DIR",
",",
"app",
".",
"serverType",
",",
"Constants",
".",
"FILEPATH",
".",
"LIFECYCLE",
")",
";",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"filePath",
")",
")",
"{",
"return",
";",
"}",
"var",
"lifecycle",
"=",
"require",
"(",
"filePath",
")",
";",
"for",
"(",
"var",
"key",
"in",
"lifecycle",
")",
"{",
"if",
"(",
"typeof",
"lifecycle",
"[",
"key",
"]",
"===",
"'function'",
")",
"{",
"app",
".",
"lifecycleCbs",
"[",
"key",
"]",
"=",
"lifecycle",
"[",
"key",
"]",
";",
"}",
"else",
"{",
"logger",
".",
"warn",
"(",
"'lifecycle.js in %s is error format.'",
",",
"filePath",
")",
";",
"}",
"}",
"}"
] |
Load lifecycle file.
|
[
"Load",
"lifecycle",
"file",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/util/appUtil.js#L249-L262
|
train
|
|
NetEase/pomelo
|
lib/components/remote.js
|
function(app) {
var paths = [];
var role;
// master server should not come here
if(app.isFrontend()) {
role = 'frontend';
} else {
role = 'backend';
}
var sysPath = pathUtil.getSysRemotePath(role), serverType = app.getServerType();
if(fs.existsSync(sysPath)) {
paths.push(pathUtil.remotePathRecord('sys', serverType, sysPath));
}
var userPath = pathUtil.getUserRemotePath(app.getBase(), serverType);
if(fs.existsSync(userPath)) {
paths.push(pathUtil.remotePathRecord('user', serverType, userPath));
}
return paths;
}
|
javascript
|
function(app) {
var paths = [];
var role;
// master server should not come here
if(app.isFrontend()) {
role = 'frontend';
} else {
role = 'backend';
}
var sysPath = pathUtil.getSysRemotePath(role), serverType = app.getServerType();
if(fs.existsSync(sysPath)) {
paths.push(pathUtil.remotePathRecord('sys', serverType, sysPath));
}
var userPath = pathUtil.getUserRemotePath(app.getBase(), serverType);
if(fs.existsSync(userPath)) {
paths.push(pathUtil.remotePathRecord('user', serverType, userPath));
}
return paths;
}
|
[
"function",
"(",
"app",
")",
"{",
"var",
"paths",
"=",
"[",
"]",
";",
"var",
"role",
";",
"if",
"(",
"app",
".",
"isFrontend",
"(",
")",
")",
"{",
"role",
"=",
"'frontend'",
";",
"}",
"else",
"{",
"role",
"=",
"'backend'",
";",
"}",
"var",
"sysPath",
"=",
"pathUtil",
".",
"getSysRemotePath",
"(",
"role",
")",
",",
"serverType",
"=",
"app",
".",
"getServerType",
"(",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"sysPath",
")",
")",
"{",
"paths",
".",
"push",
"(",
"pathUtil",
".",
"remotePathRecord",
"(",
"'sys'",
",",
"serverType",
",",
"sysPath",
")",
")",
";",
"}",
"var",
"userPath",
"=",
"pathUtil",
".",
"getUserRemotePath",
"(",
"app",
".",
"getBase",
"(",
")",
",",
"serverType",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"userPath",
")",
")",
"{",
"paths",
".",
"push",
"(",
"pathUtil",
".",
"remotePathRecord",
"(",
"'user'",
",",
"serverType",
",",
"userPath",
")",
")",
";",
"}",
"return",
"paths",
";",
"}"
] |
Get remote paths from application
@param {Object} app current application context
@return {Array} paths
|
[
"Get",
"remote",
"paths",
"from",
"application"
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/components/remote.js#L77-L98
|
train
|
|
NetEase/pomelo
|
lib/components/remote.js
|
function(app, opts) {
opts.paths = getRemotePaths(app);
opts.context = app;
if(!!opts.rpcServer) {
return opts.rpcServer.create(opts);
} else {
return RemoteServer.create(opts);
}
}
|
javascript
|
function(app, opts) {
opts.paths = getRemotePaths(app);
opts.context = app;
if(!!opts.rpcServer) {
return opts.rpcServer.create(opts);
} else {
return RemoteServer.create(opts);
}
}
|
[
"function",
"(",
"app",
",",
"opts",
")",
"{",
"opts",
".",
"paths",
"=",
"getRemotePaths",
"(",
"app",
")",
";",
"opts",
".",
"context",
"=",
"app",
";",
"if",
"(",
"!",
"!",
"opts",
".",
"rpcServer",
")",
"{",
"return",
"opts",
".",
"rpcServer",
".",
"create",
"(",
"opts",
")",
";",
"}",
"else",
"{",
"return",
"RemoteServer",
".",
"create",
"(",
"opts",
")",
";",
"}",
"}"
] |
Generate remote server instance
@param {Object} app current application context
@param {Object} opts contructor parameters for rpc Server
@return {Object} remote server instance
|
[
"Generate",
"remote",
"server",
"instance"
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/components/remote.js#L107-L115
|
train
|
|
NetEase/pomelo
|
lib/components/connector.js
|
function(app, opts) {
opts = opts || {};
this.app = app;
this.connector = getConnector(app, opts);
this.encode = opts.encode;
this.decode = opts.decode;
this.useCrypto = opts.useCrypto;
this.useHostFilter = opts.useHostFilter;
this.useAsyncCoder = opts.useAsyncCoder;
this.blacklistFun = opts.blacklistFun;
this.keys = {};
this.blacklist = [];
if (opts.useDict) {
app.load(pomelo.dictionary, app.get('dictionaryConfig'));
}
if (opts.useProtobuf) {
app.load(pomelo.protobuf, app.get('protobufConfig'));
}
// component dependencies
this.server = null;
this.session = null;
this.connection = null;
}
|
javascript
|
function(app, opts) {
opts = opts || {};
this.app = app;
this.connector = getConnector(app, opts);
this.encode = opts.encode;
this.decode = opts.decode;
this.useCrypto = opts.useCrypto;
this.useHostFilter = opts.useHostFilter;
this.useAsyncCoder = opts.useAsyncCoder;
this.blacklistFun = opts.blacklistFun;
this.keys = {};
this.blacklist = [];
if (opts.useDict) {
app.load(pomelo.dictionary, app.get('dictionaryConfig'));
}
if (opts.useProtobuf) {
app.load(pomelo.protobuf, app.get('protobufConfig'));
}
// component dependencies
this.server = null;
this.session = null;
this.connection = null;
}
|
[
"function",
"(",
"app",
",",
"opts",
")",
"{",
"opts",
"=",
"opts",
"||",
"{",
"}",
";",
"this",
".",
"app",
"=",
"app",
";",
"this",
".",
"connector",
"=",
"getConnector",
"(",
"app",
",",
"opts",
")",
";",
"this",
".",
"encode",
"=",
"opts",
".",
"encode",
";",
"this",
".",
"decode",
"=",
"opts",
".",
"decode",
";",
"this",
".",
"useCrypto",
"=",
"opts",
".",
"useCrypto",
";",
"this",
".",
"useHostFilter",
"=",
"opts",
".",
"useHostFilter",
";",
"this",
".",
"useAsyncCoder",
"=",
"opts",
".",
"useAsyncCoder",
";",
"this",
".",
"blacklistFun",
"=",
"opts",
".",
"blacklistFun",
";",
"this",
".",
"keys",
"=",
"{",
"}",
";",
"this",
".",
"blacklist",
"=",
"[",
"]",
";",
"if",
"(",
"opts",
".",
"useDict",
")",
"{",
"app",
".",
"load",
"(",
"pomelo",
".",
"dictionary",
",",
"app",
".",
"get",
"(",
"'dictionaryConfig'",
")",
")",
";",
"}",
"if",
"(",
"opts",
".",
"useProtobuf",
")",
"{",
"app",
".",
"load",
"(",
"pomelo",
".",
"protobuf",
",",
"app",
".",
"get",
"(",
"'protobufConfig'",
")",
")",
";",
"}",
"this",
".",
"server",
"=",
"null",
";",
"this",
".",
"session",
"=",
"null",
";",
"this",
".",
"connection",
"=",
"null",
";",
"}"
] |
Connector component. Receive client requests and attach session with socket.
@param {Object} app current application context
@param {Object} opts attach parameters
opts.connector {Object} provides low level network and protocol details implementation between server and clients.
|
[
"Connector",
"component",
".",
"Receive",
"client",
"requests",
"and",
"attach",
"session",
"with",
"socket",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/components/connector.js#L19-L44
|
train
|
|
NetEase/pomelo
|
lib/components/connector.js
|
function(self, socket) {
var app = self.app,
sid = socket.id;
var session = self.session.get(sid);
if (session) {
return session;
}
session = self.session.create(sid, app.getServerId(), socket);
logger.debug('[%s] getSession session is created with session id: %s', app.getServerId(), sid);
// bind events for session
socket.on('disconnect', session.closed.bind(session));
socket.on('error', session.closed.bind(session));
session.on('closed', onSessionClose.bind(null, app));
session.on('bind', function(uid) {
logger.debug('session on [%s] bind with uid: %s', self.app.serverId, uid);
// update connection statistics if necessary
if (self.connection) {
self.connection.addLoginedUser(uid, {
loginTime: Date.now(),
uid: uid,
address: socket.remoteAddress.ip + ':' + socket.remoteAddress.port
});
}
self.app.event.emit(events.BIND_SESSION, session);
});
session.on('unbind', function(uid) {
if (self.connection) {
self.connection.removeLoginedUser(uid);
}
self.app.event.emit(events.UNBIND_SESSION, session);
});
return session;
}
|
javascript
|
function(self, socket) {
var app = self.app,
sid = socket.id;
var session = self.session.get(sid);
if (session) {
return session;
}
session = self.session.create(sid, app.getServerId(), socket);
logger.debug('[%s] getSession session is created with session id: %s', app.getServerId(), sid);
// bind events for session
socket.on('disconnect', session.closed.bind(session));
socket.on('error', session.closed.bind(session));
session.on('closed', onSessionClose.bind(null, app));
session.on('bind', function(uid) {
logger.debug('session on [%s] bind with uid: %s', self.app.serverId, uid);
// update connection statistics if necessary
if (self.connection) {
self.connection.addLoginedUser(uid, {
loginTime: Date.now(),
uid: uid,
address: socket.remoteAddress.ip + ':' + socket.remoteAddress.port
});
}
self.app.event.emit(events.BIND_SESSION, session);
});
session.on('unbind', function(uid) {
if (self.connection) {
self.connection.removeLoginedUser(uid);
}
self.app.event.emit(events.UNBIND_SESSION, session);
});
return session;
}
|
[
"function",
"(",
"self",
",",
"socket",
")",
"{",
"var",
"app",
"=",
"self",
".",
"app",
",",
"sid",
"=",
"socket",
".",
"id",
";",
"var",
"session",
"=",
"self",
".",
"session",
".",
"get",
"(",
"sid",
")",
";",
"if",
"(",
"session",
")",
"{",
"return",
"session",
";",
"}",
"session",
"=",
"self",
".",
"session",
".",
"create",
"(",
"sid",
",",
"app",
".",
"getServerId",
"(",
")",
",",
"socket",
")",
";",
"logger",
".",
"debug",
"(",
"'[%s] getSession session is created with session id: %s'",
",",
"app",
".",
"getServerId",
"(",
")",
",",
"sid",
")",
";",
"socket",
".",
"on",
"(",
"'disconnect'",
",",
"session",
".",
"closed",
".",
"bind",
"(",
"session",
")",
")",
";",
"socket",
".",
"on",
"(",
"'error'",
",",
"session",
".",
"closed",
".",
"bind",
"(",
"session",
")",
")",
";",
"session",
".",
"on",
"(",
"'closed'",
",",
"onSessionClose",
".",
"bind",
"(",
"null",
",",
"app",
")",
")",
";",
"session",
".",
"on",
"(",
"'bind'",
",",
"function",
"(",
"uid",
")",
"{",
"logger",
".",
"debug",
"(",
"'session on [%s] bind with uid: %s'",
",",
"self",
".",
"app",
".",
"serverId",
",",
"uid",
")",
";",
"if",
"(",
"self",
".",
"connection",
")",
"{",
"self",
".",
"connection",
".",
"addLoginedUser",
"(",
"uid",
",",
"{",
"loginTime",
":",
"Date",
".",
"now",
"(",
")",
",",
"uid",
":",
"uid",
",",
"address",
":",
"socket",
".",
"remoteAddress",
".",
"ip",
"+",
"':'",
"+",
"socket",
".",
"remoteAddress",
".",
"port",
"}",
")",
";",
"}",
"self",
".",
"app",
".",
"event",
".",
"emit",
"(",
"events",
".",
"BIND_SESSION",
",",
"session",
")",
";",
"}",
")",
";",
"session",
".",
"on",
"(",
"'unbind'",
",",
"function",
"(",
"uid",
")",
"{",
"if",
"(",
"self",
".",
"connection",
")",
"{",
"self",
".",
"connection",
".",
"removeLoginedUser",
"(",
"uid",
")",
";",
"}",
"self",
".",
"app",
".",
"event",
".",
"emit",
"(",
"events",
".",
"UNBIND_SESSION",
",",
"session",
")",
";",
"}",
")",
";",
"return",
"session",
";",
"}"
] |
get session for current connection
|
[
"get",
"session",
"for",
"current",
"connection"
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/components/connector.js#L331-L367
|
train
|
|
NetEase/pomelo
|
lib/components/connector.js
|
function(route) {
if (!route) {
return null;
}
var idx = route.indexOf('.');
if (idx < 0) {
return null;
}
return route.substring(0, idx);
}
|
javascript
|
function(route) {
if (!route) {
return null;
}
var idx = route.indexOf('.');
if (idx < 0) {
return null;
}
return route.substring(0, idx);
}
|
[
"function",
"(",
"route",
")",
"{",
"if",
"(",
"!",
"route",
")",
"{",
"return",
"null",
";",
"}",
"var",
"idx",
"=",
"route",
".",
"indexOf",
"(",
"'.'",
")",
";",
"if",
"(",
"idx",
"<",
"0",
")",
"{",
"return",
"null",
";",
"}",
"return",
"route",
".",
"substring",
"(",
"0",
",",
"idx",
")",
";",
"}"
] |
Get server type form request message.
|
[
"Get",
"server",
"type",
"form",
"request",
"message",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/components/connector.js#L406-L415
|
train
|
|
NetEase/pomelo
|
lib/components/proxy.js
|
function(app, opts) {
this.app = app;
this.opts = opts;
this.client = genRpcClient(this.app, opts);
this.app.event.on(events.ADD_SERVERS, this.addServers.bind(this));
this.app.event.on(events.REMOVE_SERVERS, this.removeServers.bind(this));
this.app.event.on(events.REPLACE_SERVERS, this.replaceServers.bind(this));
}
|
javascript
|
function(app, opts) {
this.app = app;
this.opts = opts;
this.client = genRpcClient(this.app, opts);
this.app.event.on(events.ADD_SERVERS, this.addServers.bind(this));
this.app.event.on(events.REMOVE_SERVERS, this.removeServers.bind(this));
this.app.event.on(events.REPLACE_SERVERS, this.replaceServers.bind(this));
}
|
[
"function",
"(",
"app",
",",
"opts",
")",
"{",
"this",
".",
"app",
"=",
"app",
";",
"this",
".",
"opts",
"=",
"opts",
";",
"this",
".",
"client",
"=",
"genRpcClient",
"(",
"this",
".",
"app",
",",
"opts",
")",
";",
"this",
".",
"app",
".",
"event",
".",
"on",
"(",
"events",
".",
"ADD_SERVERS",
",",
"this",
".",
"addServers",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"app",
".",
"event",
".",
"on",
"(",
"events",
".",
"REMOVE_SERVERS",
",",
"this",
".",
"removeServers",
".",
"bind",
"(",
"this",
")",
")",
";",
"this",
".",
"app",
".",
"event",
".",
"on",
"(",
"events",
".",
"REPLACE_SERVERS",
",",
"this",
".",
"replaceServers",
".",
"bind",
"(",
"this",
")",
")",
";",
"}"
] |
Proxy component class
@param {Object} app current application context
@param {Object} opts construct parameters
|
[
"Proxy",
"component",
"class"
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/components/proxy.js#L45-L52
|
train
|
|
NetEase/pomelo
|
lib/components/proxy.js
|
function(app, opts) {
opts.context = app;
opts.routeContext = app;
if(!!opts.rpcClient) {
return opts.rpcClient.create(opts);
} else {
return Client.create(opts);
}
}
|
javascript
|
function(app, opts) {
opts.context = app;
opts.routeContext = app;
if(!!opts.rpcClient) {
return opts.rpcClient.create(opts);
} else {
return Client.create(opts);
}
}
|
[
"function",
"(",
"app",
",",
"opts",
")",
"{",
"opts",
".",
"context",
"=",
"app",
";",
"opts",
".",
"routeContext",
"=",
"app",
";",
"if",
"(",
"!",
"!",
"opts",
".",
"rpcClient",
")",
"{",
"return",
"opts",
".",
"rpcClient",
".",
"create",
"(",
"opts",
")",
";",
"}",
"else",
"{",
"return",
"Client",
".",
"create",
"(",
"opts",
")",
";",
"}",
"}"
] |
Generate rpc client
@param {Object} app current application context
@param {Object} opts contructor parameters for rpc client
@return {Object} rpc client
|
[
"Generate",
"rpc",
"client"
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/components/proxy.js#L160-L168
|
train
|
|
NetEase/pomelo
|
lib/connectors/siosocket.js
|
function(id, socket) {
EventEmitter.call(this);
this.id = id;
this.socket = socket;
this.remoteAddress = {
ip: socket.handshake.address.address,
port: socket.handshake.address.port
};
var self = this;
socket.on('disconnect', this.emit.bind(this, 'disconnect'));
socket.on('error', this.emit.bind(this, 'error'));
socket.on('message', function(msg) {
self.emit('message', msg);
});
this.state = ST_INITED;
// TODO: any other events?
}
|
javascript
|
function(id, socket) {
EventEmitter.call(this);
this.id = id;
this.socket = socket;
this.remoteAddress = {
ip: socket.handshake.address.address,
port: socket.handshake.address.port
};
var self = this;
socket.on('disconnect', this.emit.bind(this, 'disconnect'));
socket.on('error', this.emit.bind(this, 'error'));
socket.on('message', function(msg) {
self.emit('message', msg);
});
this.state = ST_INITED;
// TODO: any other events?
}
|
[
"function",
"(",
"id",
",",
"socket",
")",
"{",
"EventEmitter",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"id",
"=",
"id",
";",
"this",
".",
"socket",
"=",
"socket",
";",
"this",
".",
"remoteAddress",
"=",
"{",
"ip",
":",
"socket",
".",
"handshake",
".",
"address",
".",
"address",
",",
"port",
":",
"socket",
".",
"handshake",
".",
"address",
".",
"port",
"}",
";",
"var",
"self",
"=",
"this",
";",
"socket",
".",
"on",
"(",
"'disconnect'",
",",
"this",
".",
"emit",
".",
"bind",
"(",
"this",
",",
"'disconnect'",
")",
")",
";",
"socket",
".",
"on",
"(",
"'error'",
",",
"this",
".",
"emit",
".",
"bind",
"(",
"this",
",",
"'error'",
")",
")",
";",
"socket",
".",
"on",
"(",
"'message'",
",",
"function",
"(",
"msg",
")",
"{",
"self",
".",
"emit",
"(",
"'message'",
",",
"msg",
")",
";",
"}",
")",
";",
"this",
".",
"state",
"=",
"ST_INITED",
";",
"}"
] |
Socket class that wraps socket.io socket to provide unified interface for up level.
|
[
"Socket",
"class",
"that",
"wraps",
"socket",
".",
"io",
"socket",
"to",
"provide",
"unified",
"interface",
"for",
"up",
"level",
"."
] |
defcf019631ed399cc4dad932d3b028a04a039a4
|
https://github.com/NetEase/pomelo/blob/defcf019631ed399cc4dad932d3b028a04a039a4/lib/connectors/siosocket.js#L10-L32
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.