id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
6,200 | prebid/Prebid.js | modules/ixBidAdapter.js | bidToBannerImp | function bidToBannerImp(bid) {
const imp = {};
imp.id = bid.bidId;
imp.banner = {};
imp.banner.w = bid.params.size[0];
imp.banner.h = bid.params.size[1];
imp.banner.topframe = utils.inIframe() ? 0 : 1;
imp.ext = {};
imp.ext.siteID = bid.params.siteId;
if (bid.params.hasOwnProperty('id') &&
(typeof bid.params.id === 'string' || typeof bid.params.id === 'number')) {
imp.ext.sid = String(bid.params.id);
} else {
imp.ext.sid = `${bid.params.size[0]}x${bid.params.size[1]}`;
}
if (bid.params.hasOwnProperty('bidFloor') && bid.params.hasOwnProperty('bidFloorCur')) {
imp.bidfloor = bid.params.bidFloor;
imp.bidfloorcur = bid.params.bidFloorCur;
}
return imp;
} | javascript | function bidToBannerImp(bid) {
const imp = {};
imp.id = bid.bidId;
imp.banner = {};
imp.banner.w = bid.params.size[0];
imp.banner.h = bid.params.size[1];
imp.banner.topframe = utils.inIframe() ? 0 : 1;
imp.ext = {};
imp.ext.siteID = bid.params.siteId;
if (bid.params.hasOwnProperty('id') &&
(typeof bid.params.id === 'string' || typeof bid.params.id === 'number')) {
imp.ext.sid = String(bid.params.id);
} else {
imp.ext.sid = `${bid.params.size[0]}x${bid.params.size[1]}`;
}
if (bid.params.hasOwnProperty('bidFloor') && bid.params.hasOwnProperty('bidFloorCur')) {
imp.bidfloor = bid.params.bidFloor;
imp.bidfloorcur = bid.params.bidFloorCur;
}
return imp;
} | [
"function",
"bidToBannerImp",
"(",
"bid",
")",
"{",
"const",
"imp",
"=",
"{",
"}",
";",
"imp",
".",
"id",
"=",
"bid",
".",
"bidId",
";",
"imp",
".",
"banner",
"=",
"{",
"}",
";",
"imp",
".",
"banner",
".",
"w",
"=",
"bid",
".",
"params",
".",
"size",
"[",
"0",
"]",
";",
"imp",
".",
"banner",
".",
"h",
"=",
"bid",
".",
"params",
".",
"size",
"[",
"1",
"]",
";",
"imp",
".",
"banner",
".",
"topframe",
"=",
"utils",
".",
"inIframe",
"(",
")",
"?",
"0",
":",
"1",
";",
"imp",
".",
"ext",
"=",
"{",
"}",
";",
"imp",
".",
"ext",
".",
"siteID",
"=",
"bid",
".",
"params",
".",
"siteId",
";",
"if",
"(",
"bid",
".",
"params",
".",
"hasOwnProperty",
"(",
"'id'",
")",
"&&",
"(",
"typeof",
"bid",
".",
"params",
".",
"id",
"===",
"'string'",
"||",
"typeof",
"bid",
".",
"params",
".",
"id",
"===",
"'number'",
")",
")",
"{",
"imp",
".",
"ext",
".",
"sid",
"=",
"String",
"(",
"bid",
".",
"params",
".",
"id",
")",
";",
"}",
"else",
"{",
"imp",
".",
"ext",
".",
"sid",
"=",
"`",
"${",
"bid",
".",
"params",
".",
"size",
"[",
"0",
"]",
"}",
"${",
"bid",
".",
"params",
".",
"size",
"[",
"1",
"]",
"}",
"`",
";",
"}",
"if",
"(",
"bid",
".",
"params",
".",
"hasOwnProperty",
"(",
"'bidFloor'",
")",
"&&",
"bid",
".",
"params",
".",
"hasOwnProperty",
"(",
"'bidFloorCur'",
")",
")",
"{",
"imp",
".",
"bidfloor",
"=",
"bid",
".",
"params",
".",
"bidFloor",
";",
"imp",
".",
"bidfloorcur",
"=",
"bid",
".",
"params",
".",
"bidFloorCur",
";",
"}",
"return",
"imp",
";",
"}"
] | Transform valid bid request config object to impression object that will be sent to ad server.
@param {object} bid A valid bid request config object.
@return {object} A impression object that will be sent to ad server. | [
"Transform",
"valid",
"bid",
"request",
"config",
"object",
"to",
"impression",
"object",
"that",
"will",
"be",
"sent",
"to",
"ad",
"server",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/ixBidAdapter.js#L26-L52 |
6,201 | prebid/Prebid.js | modules/ixBidAdapter.js | parseBid | function parseBid(rawBid, currency) {
const bid = {};
if (PRICE_TO_DOLLAR_FACTOR.hasOwnProperty(currency)) {
bid.cpm = rawBid.price / PRICE_TO_DOLLAR_FACTOR[currency];
} else {
bid.cpm = rawBid.price / CENT_TO_DOLLAR_FACTOR;
}
bid.requestId = rawBid.impid;
bid.width = rawBid.w;
bid.height = rawBid.h;
bid.ad = rawBid.adm;
bid.dealId = utils.deepAccess(rawBid, 'ext.dealid');
bid.ttl = TIME_TO_LIVE;
bid.netRevenue = NET_REVENUE;
bid.currency = currency;
bid.creativeId = rawBid.hasOwnProperty('crid') ? rawBid.crid : '-';
bid.meta = {};
bid.meta.networkId = utils.deepAccess(rawBid, 'ext.dspid');
bid.meta.brandId = utils.deepAccess(rawBid, 'ext.advbrandid');
bid.meta.brandName = utils.deepAccess(rawBid, 'ext.advbrand');
return bid;
} | javascript | function parseBid(rawBid, currency) {
const bid = {};
if (PRICE_TO_DOLLAR_FACTOR.hasOwnProperty(currency)) {
bid.cpm = rawBid.price / PRICE_TO_DOLLAR_FACTOR[currency];
} else {
bid.cpm = rawBid.price / CENT_TO_DOLLAR_FACTOR;
}
bid.requestId = rawBid.impid;
bid.width = rawBid.w;
bid.height = rawBid.h;
bid.ad = rawBid.adm;
bid.dealId = utils.deepAccess(rawBid, 'ext.dealid');
bid.ttl = TIME_TO_LIVE;
bid.netRevenue = NET_REVENUE;
bid.currency = currency;
bid.creativeId = rawBid.hasOwnProperty('crid') ? rawBid.crid : '-';
bid.meta = {};
bid.meta.networkId = utils.deepAccess(rawBid, 'ext.dspid');
bid.meta.brandId = utils.deepAccess(rawBid, 'ext.advbrandid');
bid.meta.brandName = utils.deepAccess(rawBid, 'ext.advbrand');
return bid;
} | [
"function",
"parseBid",
"(",
"rawBid",
",",
"currency",
")",
"{",
"const",
"bid",
"=",
"{",
"}",
";",
"if",
"(",
"PRICE_TO_DOLLAR_FACTOR",
".",
"hasOwnProperty",
"(",
"currency",
")",
")",
"{",
"bid",
".",
"cpm",
"=",
"rawBid",
".",
"price",
"/",
"PRICE_TO_DOLLAR_FACTOR",
"[",
"currency",
"]",
";",
"}",
"else",
"{",
"bid",
".",
"cpm",
"=",
"rawBid",
".",
"price",
"/",
"CENT_TO_DOLLAR_FACTOR",
";",
"}",
"bid",
".",
"requestId",
"=",
"rawBid",
".",
"impid",
";",
"bid",
".",
"width",
"=",
"rawBid",
".",
"w",
";",
"bid",
".",
"height",
"=",
"rawBid",
".",
"h",
";",
"bid",
".",
"ad",
"=",
"rawBid",
".",
"adm",
";",
"bid",
".",
"dealId",
"=",
"utils",
".",
"deepAccess",
"(",
"rawBid",
",",
"'ext.dealid'",
")",
";",
"bid",
".",
"ttl",
"=",
"TIME_TO_LIVE",
";",
"bid",
".",
"netRevenue",
"=",
"NET_REVENUE",
";",
"bid",
".",
"currency",
"=",
"currency",
";",
"bid",
".",
"creativeId",
"=",
"rawBid",
".",
"hasOwnProperty",
"(",
"'crid'",
")",
"?",
"rawBid",
".",
"crid",
":",
"'-'",
";",
"bid",
".",
"meta",
"=",
"{",
"}",
";",
"bid",
".",
"meta",
".",
"networkId",
"=",
"utils",
".",
"deepAccess",
"(",
"rawBid",
",",
"'ext.dspid'",
")",
";",
"bid",
".",
"meta",
".",
"brandId",
"=",
"utils",
".",
"deepAccess",
"(",
"rawBid",
",",
"'ext.advbrandid'",
")",
";",
"bid",
".",
"meta",
".",
"brandName",
"=",
"utils",
".",
"deepAccess",
"(",
"rawBid",
",",
"'ext.advbrand'",
")",
";",
"return",
"bid",
";",
"}"
] | Parses a raw bid for the relevant information.
@param {object} rawBid The bid to be parsed.
@param {string} currency Global currency in bid response.
@return {object} bid The parsed bid. | [
"Parses",
"a",
"raw",
"bid",
"for",
"the",
"relevant",
"information",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/ixBidAdapter.js#L61-L86 |
6,202 | prebid/Prebid.js | modules/ixBidAdapter.js | isValidSize | function isValidSize(size) {
return isArray(size) && size.length === 2 && isInteger(size[0]) && isInteger(size[1]);
} | javascript | function isValidSize(size) {
return isArray(size) && size.length === 2 && isInteger(size[0]) && isInteger(size[1]);
} | [
"function",
"isValidSize",
"(",
"size",
")",
"{",
"return",
"isArray",
"(",
"size",
")",
"&&",
"size",
".",
"length",
"===",
"2",
"&&",
"isInteger",
"(",
"size",
"[",
"0",
"]",
")",
"&&",
"isInteger",
"(",
"size",
"[",
"1",
"]",
")",
";",
"}"
] | Determines whether or not the given object is valid size format.
@param {*} size The object to be validated.
@return {boolean} True if this is a valid size format, and false otherwise. | [
"Determines",
"whether",
"or",
"not",
"the",
"given",
"object",
"is",
"valid",
"size",
"format",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/ixBidAdapter.js#L94-L96 |
6,203 | prebid/Prebid.js | modules/ixBidAdapter.js | includesSize | function includesSize(sizeArray, size) {
if (isValidSize(sizeArray)) {
return sizeArray[0] === size[0] && sizeArray[1] === size[1];
}
for (let i = 0; i < sizeArray.length; i++) {
if (sizeArray[i][0] === size[0] && sizeArray[i][1] === size[1]) {
return true;
}
}
return false;
} | javascript | function includesSize(sizeArray, size) {
if (isValidSize(sizeArray)) {
return sizeArray[0] === size[0] && sizeArray[1] === size[1];
}
for (let i = 0; i < sizeArray.length; i++) {
if (sizeArray[i][0] === size[0] && sizeArray[i][1] === size[1]) {
return true;
}
}
return false;
} | [
"function",
"includesSize",
"(",
"sizeArray",
",",
"size",
")",
"{",
"if",
"(",
"isValidSize",
"(",
"sizeArray",
")",
")",
"{",
"return",
"sizeArray",
"[",
"0",
"]",
"===",
"size",
"[",
"0",
"]",
"&&",
"sizeArray",
"[",
"1",
"]",
"===",
"size",
"[",
"1",
"]",
";",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"sizeArray",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"sizeArray",
"[",
"i",
"]",
"[",
"0",
"]",
"===",
"size",
"[",
"0",
"]",
"&&",
"sizeArray",
"[",
"i",
"]",
"[",
"1",
"]",
"===",
"size",
"[",
"1",
"]",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Determines whether or not the given size object is an element of the size
array.
@param {array} sizeArray The size array.
@param {object} size The size object.
@return {boolean} True if the size object is an element of the size array, and false
otherwise. | [
"Determines",
"whether",
"or",
"not",
"the",
"given",
"size",
"object",
"is",
"an",
"element",
"of",
"the",
"size",
"array",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/ixBidAdapter.js#L107-L119 |
6,204 | prebid/Prebid.js | modules/ixBidAdapter.js | isValidBidFloorParams | function isValidBidFloorParams(bidFloor, bidFloorCur) {
const curRegex = /^[A-Z]{3}$/;
return Boolean(typeof bidFloor === 'number' && typeof bidFloorCur === 'string' &&
bidFloorCur.match(curRegex));
} | javascript | function isValidBidFloorParams(bidFloor, bidFloorCur) {
const curRegex = /^[A-Z]{3}$/;
return Boolean(typeof bidFloor === 'number' && typeof bidFloorCur === 'string' &&
bidFloorCur.match(curRegex));
} | [
"function",
"isValidBidFloorParams",
"(",
"bidFloor",
",",
"bidFloorCur",
")",
"{",
"const",
"curRegex",
"=",
"/",
"^[A-Z]{3}$",
"/",
";",
"return",
"Boolean",
"(",
"typeof",
"bidFloor",
"===",
"'number'",
"&&",
"typeof",
"bidFloorCur",
"===",
"'string'",
"&&",
"bidFloorCur",
".",
"match",
"(",
"curRegex",
")",
")",
";",
"}"
] | Determines whether or not the given bidFloor parameters are valid.
@param {*} bidFloor The bidFloor parameter inside bid request config.
@param {*} bidFloorCur The bidFloorCur parameter inside bid request config.
@return {boolean} True if this is a valid biFfloor parameters format, and false
otherwise. | [
"Determines",
"whether",
"or",
"not",
"the",
"given",
"bidFloor",
"parameters",
"are",
"valid",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/ixBidAdapter.js#L129-L134 |
6,205 | prebid/Prebid.js | modules/rubiconBidAdapter.js | bidType | function bidType(bid, log = false) {
// Is it considered video ad unit by rubicon
if (hasVideoMediaType(bid)) {
// Removed legacy mediaType support. new way using mediaTypes.video object is now required
// We require either context as instream or outstream
if (['outstream', 'instream'].indexOf(utils.deepAccess(bid, `mediaTypes.${VIDEO}.context`)) === -1) {
if (log) {
utils.logError('Rubicon bid adapter requires mediaTypes.video.context to be one of outstream or instream');
}
return;
}
// we require playerWidth and playerHeight to come from one of params.playerWidth/playerHeight or mediaTypes.video.playerSize or adUnit.sizes
if (parseSizes(bid, 'video').length < 2) {
if (log) {
utils.logError('Rubicon bid adapter could not determine the playerSize of the video\nplayerWidth and playerHeight are inferred from one of params.playerWidth/playerHeight or mediaTypes.video.playerSize or adUnit.sizes, in that order');
}
return;
}
if (log) {
utils.logMessage('Rubicon bid adapter making video request for adUnit', bid.adUnitCode);
}
return 'video';
} else {
// we require banner sizes to come from one of params.sizes or mediaTypes.banner.sizes or adUnit.sizes, in that order
// if we cannot determine them, we reject it!
if (parseSizes(bid, 'banner').length === 0) {
if (log) {
utils.logError('Rubicon bid adapter could not determine the sizes for a banner request\nThey are inferred from one of params.sizes or mediaTypes.banner.sizes or adUnit.sizes, in that order');
}
return;
}
// everything looks good for banner so lets do it
if (log) {
utils.logMessage('Rubicon bid adapter making banner request for adUnit', bid.adUnitCode);
}
return 'banner';
}
} | javascript | function bidType(bid, log = false) {
// Is it considered video ad unit by rubicon
if (hasVideoMediaType(bid)) {
// Removed legacy mediaType support. new way using mediaTypes.video object is now required
// We require either context as instream or outstream
if (['outstream', 'instream'].indexOf(utils.deepAccess(bid, `mediaTypes.${VIDEO}.context`)) === -1) {
if (log) {
utils.logError('Rubicon bid adapter requires mediaTypes.video.context to be one of outstream or instream');
}
return;
}
// we require playerWidth and playerHeight to come from one of params.playerWidth/playerHeight or mediaTypes.video.playerSize or adUnit.sizes
if (parseSizes(bid, 'video').length < 2) {
if (log) {
utils.logError('Rubicon bid adapter could not determine the playerSize of the video\nplayerWidth and playerHeight are inferred from one of params.playerWidth/playerHeight or mediaTypes.video.playerSize or adUnit.sizes, in that order');
}
return;
}
if (log) {
utils.logMessage('Rubicon bid adapter making video request for adUnit', bid.adUnitCode);
}
return 'video';
} else {
// we require banner sizes to come from one of params.sizes or mediaTypes.banner.sizes or adUnit.sizes, in that order
// if we cannot determine them, we reject it!
if (parseSizes(bid, 'banner').length === 0) {
if (log) {
utils.logError('Rubicon bid adapter could not determine the sizes for a banner request\nThey are inferred from one of params.sizes or mediaTypes.banner.sizes or adUnit.sizes, in that order');
}
return;
}
// everything looks good for banner so lets do it
if (log) {
utils.logMessage('Rubicon bid adapter making banner request for adUnit', bid.adUnitCode);
}
return 'banner';
}
} | [
"function",
"bidType",
"(",
"bid",
",",
"log",
"=",
"false",
")",
"{",
"// Is it considered video ad unit by rubicon",
"if",
"(",
"hasVideoMediaType",
"(",
"bid",
")",
")",
"{",
"// Removed legacy mediaType support. new way using mediaTypes.video object is now required",
"// We require either context as instream or outstream",
"if",
"(",
"[",
"'outstream'",
",",
"'instream'",
"]",
".",
"indexOf",
"(",
"utils",
".",
"deepAccess",
"(",
"bid",
",",
"`",
"${",
"VIDEO",
"}",
"`",
")",
")",
"===",
"-",
"1",
")",
"{",
"if",
"(",
"log",
")",
"{",
"utils",
".",
"logError",
"(",
"'Rubicon bid adapter requires mediaTypes.video.context to be one of outstream or instream'",
")",
";",
"}",
"return",
";",
"}",
"// we require playerWidth and playerHeight to come from one of params.playerWidth/playerHeight or mediaTypes.video.playerSize or adUnit.sizes",
"if",
"(",
"parseSizes",
"(",
"bid",
",",
"'video'",
")",
".",
"length",
"<",
"2",
")",
"{",
"if",
"(",
"log",
")",
"{",
"utils",
".",
"logError",
"(",
"'Rubicon bid adapter could not determine the playerSize of the video\\nplayerWidth and playerHeight are inferred from one of params.playerWidth/playerHeight or mediaTypes.video.playerSize or adUnit.sizes, in that order'",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"log",
")",
"{",
"utils",
".",
"logMessage",
"(",
"'Rubicon bid adapter making video request for adUnit'",
",",
"bid",
".",
"adUnitCode",
")",
";",
"}",
"return",
"'video'",
";",
"}",
"else",
"{",
"// we require banner sizes to come from one of params.sizes or mediaTypes.banner.sizes or adUnit.sizes, in that order",
"// if we cannot determine them, we reject it!",
"if",
"(",
"parseSizes",
"(",
"bid",
",",
"'banner'",
")",
".",
"length",
"===",
"0",
")",
"{",
"if",
"(",
"log",
")",
"{",
"utils",
".",
"logError",
"(",
"'Rubicon bid adapter could not determine the sizes for a banner request\\nThey are inferred from one of params.sizes or mediaTypes.banner.sizes or adUnit.sizes, in that order'",
")",
";",
"}",
"return",
";",
"}",
"// everything looks good for banner so lets do it",
"if",
"(",
"log",
")",
"{",
"utils",
".",
"logMessage",
"(",
"'Rubicon bid adapter making banner request for adUnit'",
",",
"bid",
".",
"adUnitCode",
")",
";",
"}",
"return",
"'banner'",
";",
"}",
"}"
] | Determine bidRequest mediaType
@param bid the bid to test
@param log whether we should log errors/warnings for invalid bids
@returns {string|undefined} Returns 'video' or 'banner' if resolves to a type, or undefined otherwise (invalid). | [
"Determine",
"bidRequest",
"mediaType"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/rubiconBidAdapter.js#L775-L815 |
6,206 | prebid/Prebid.js | modules/rubiconBidAdapter.js | partitionArray | function partitionArray(array, size) {
return array.map((e, i) => (i % size === 0) ? array.slice(i, i + size) : null).filter((e) => e)
} | javascript | function partitionArray(array, size) {
return array.map((e, i) => (i % size === 0) ? array.slice(i, i + size) : null).filter((e) => e)
} | [
"function",
"partitionArray",
"(",
"array",
",",
"size",
")",
"{",
"return",
"array",
".",
"map",
"(",
"(",
"e",
",",
"i",
")",
"=>",
"(",
"i",
"%",
"size",
"===",
"0",
")",
"?",
"array",
".",
"slice",
"(",
"i",
",",
"i",
"+",
"size",
")",
":",
"null",
")",
".",
"filter",
"(",
"(",
"e",
")",
"=>",
"e",
")",
"}"
] | split array into multiple arrays of defined size
@param {Array} array
@param {number} size
@returns {Array} | [
"split",
"array",
"into",
"multiple",
"arrays",
"of",
"defined",
"size"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/rubiconBidAdapter.js#L906-L908 |
6,207 | prebid/Prebid.js | modules/googleAnalyticsAdapter.js | checkAnalytics | function checkAnalytics() {
if (_enableCheck && typeof window[_gaGlobal] === 'function') {
for (var i = 0; i < _analyticsQueue.length; i++) {
_analyticsQueue[i].call();
}
// override push to execute the command immediately from now on
_analyticsQueue.push = function (fn) {
fn.call();
};
// turn check into NOOP
_enableCheck = false;
}
utils.logMessage('event count sent to GA: ' + _eventCount);
} | javascript | function checkAnalytics() {
if (_enableCheck && typeof window[_gaGlobal] === 'function') {
for (var i = 0; i < _analyticsQueue.length; i++) {
_analyticsQueue[i].call();
}
// override push to execute the command immediately from now on
_analyticsQueue.push = function (fn) {
fn.call();
};
// turn check into NOOP
_enableCheck = false;
}
utils.logMessage('event count sent to GA: ' + _eventCount);
} | [
"function",
"checkAnalytics",
"(",
")",
"{",
"if",
"(",
"_enableCheck",
"&&",
"typeof",
"window",
"[",
"_gaGlobal",
"]",
"===",
"'function'",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"_analyticsQueue",
".",
"length",
";",
"i",
"++",
")",
"{",
"_analyticsQueue",
"[",
"i",
"]",
".",
"call",
"(",
")",
";",
"}",
"// override push to execute the command immediately from now on",
"_analyticsQueue",
".",
"push",
"=",
"function",
"(",
"fn",
")",
"{",
"fn",
".",
"call",
"(",
")",
";",
"}",
";",
"// turn check into NOOP",
"_enableCheck",
"=",
"false",
";",
"}",
"utils",
".",
"logMessage",
"(",
"'event count sent to GA: '",
"+",
"_eventCount",
")",
";",
"}"
] | Check if gaGlobal or window.ga is defined on page. If defined execute all the GA commands | [
"Check",
"if",
"gaGlobal",
"or",
"window",
".",
"ga",
"is",
"defined",
"on",
"page",
".",
"If",
"defined",
"execute",
"all",
"the",
"GA",
"commands"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/googleAnalyticsAdapter.js#L113-L129 |
6,208 | prebid/Prebid.js | src/native.js | typeIsSupported | function typeIsSupported(type) {
if (!(type && includes(Object.keys(SUPPORTED_TYPES), type))) {
logError(`${type} nativeParam is not supported`);
return false;
}
return true;
} | javascript | function typeIsSupported(type) {
if (!(type && includes(Object.keys(SUPPORTED_TYPES), type))) {
logError(`${type} nativeParam is not supported`);
return false;
}
return true;
} | [
"function",
"typeIsSupported",
"(",
"type",
")",
"{",
"if",
"(",
"!",
"(",
"type",
"&&",
"includes",
"(",
"Object",
".",
"keys",
"(",
"SUPPORTED_TYPES",
")",
",",
"type",
")",
")",
")",
"{",
"logError",
"(",
"`",
"${",
"type",
"}",
"`",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Check if the native type specified in the adUnit is supported by Prebid. | [
"Check",
"if",
"the",
"native",
"type",
"specified",
"in",
"the",
"adUnit",
"is",
"supported",
"by",
"Prebid",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/src/native.js#L41-L48 |
6,209 | prebid/Prebid.js | src/videoCache.js | toStorageRequest | function toStorageRequest(bid) {
const vastValue = bid.vastXml ? bid.vastXml : wrapURI(bid.vastUrl, bid.vastImpUrl);
let payload = {
type: 'xml',
value: vastValue,
ttlseconds: Number(bid.ttl)
};
if (typeof bid.customCacheKey === 'string' && bid.customCacheKey !== '') {
payload.key = bid.customCacheKey;
}
return payload;
} | javascript | function toStorageRequest(bid) {
const vastValue = bid.vastXml ? bid.vastXml : wrapURI(bid.vastUrl, bid.vastImpUrl);
let payload = {
type: 'xml',
value: vastValue,
ttlseconds: Number(bid.ttl)
};
if (typeof bid.customCacheKey === 'string' && bid.customCacheKey !== '') {
payload.key = bid.customCacheKey;
}
return payload;
} | [
"function",
"toStorageRequest",
"(",
"bid",
")",
"{",
"const",
"vastValue",
"=",
"bid",
".",
"vastXml",
"?",
"bid",
".",
"vastXml",
":",
"wrapURI",
"(",
"bid",
".",
"vastUrl",
",",
"bid",
".",
"vastImpUrl",
")",
";",
"let",
"payload",
"=",
"{",
"type",
":",
"'xml'",
",",
"value",
":",
"vastValue",
",",
"ttlseconds",
":",
"Number",
"(",
"bid",
".",
"ttl",
")",
"}",
";",
"if",
"(",
"typeof",
"bid",
".",
"customCacheKey",
"===",
"'string'",
"&&",
"bid",
".",
"customCacheKey",
"!==",
"''",
")",
"{",
"payload",
".",
"key",
"=",
"bid",
".",
"customCacheKey",
";",
"}",
"return",
"payload",
";",
"}"
] | Wraps a bid in the format expected by the prebid-server endpoints, or returns null if
the bid can't be converted cleanly.
@param {CacheableBid} bid | [
"Wraps",
"a",
"bid",
"in",
"the",
"format",
"expected",
"by",
"the",
"prebid",
"-",
"server",
"endpoints",
"or",
"returns",
"null",
"if",
"the",
"bid",
"can",
"t",
"be",
"converted",
"cleanly",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/src/videoCache.js#L61-L74 |
6,210 | prebid/Prebid.js | src/videoCache.js | shimStorageCallback | function shimStorageCallback(done) {
return {
success: function(responseBody) {
let ids;
try {
ids = JSON.parse(responseBody).responses
} catch (e) {
done(e, []);
return;
}
if (ids) {
done(null, ids);
} else {
done(new Error("The cache server didn't respond with a responses property."), []);
}
},
error: function(statusText, responseBody) {
done(new Error(`Error storing video ad in the cache: ${statusText}: ${JSON.stringify(responseBody)}`), []);
}
}
} | javascript | function shimStorageCallback(done) {
return {
success: function(responseBody) {
let ids;
try {
ids = JSON.parse(responseBody).responses
} catch (e) {
done(e, []);
return;
}
if (ids) {
done(null, ids);
} else {
done(new Error("The cache server didn't respond with a responses property."), []);
}
},
error: function(statusText, responseBody) {
done(new Error(`Error storing video ad in the cache: ${statusText}: ${JSON.stringify(responseBody)}`), []);
}
}
} | [
"function",
"shimStorageCallback",
"(",
"done",
")",
"{",
"return",
"{",
"success",
":",
"function",
"(",
"responseBody",
")",
"{",
"let",
"ids",
";",
"try",
"{",
"ids",
"=",
"JSON",
".",
"parse",
"(",
"responseBody",
")",
".",
"responses",
"}",
"catch",
"(",
"e",
")",
"{",
"done",
"(",
"e",
",",
"[",
"]",
")",
";",
"return",
";",
"}",
"if",
"(",
"ids",
")",
"{",
"done",
"(",
"null",
",",
"ids",
")",
";",
"}",
"else",
"{",
"done",
"(",
"new",
"Error",
"(",
"\"The cache server didn't respond with a responses property.\"",
")",
",",
"[",
"]",
")",
";",
"}",
"}",
",",
"error",
":",
"function",
"(",
"statusText",
",",
"responseBody",
")",
"{",
"done",
"(",
"new",
"Error",
"(",
"`",
"${",
"statusText",
"}",
"${",
"JSON",
".",
"stringify",
"(",
"responseBody",
")",
"}",
"`",
")",
",",
"[",
"]",
")",
";",
"}",
"}",
"}"
] | A function which should be called with the results of the storage operation.
@callback videoCacheStoreCallback
@param {Error} [error] The error, if one occurred.
@param {?string[]} uuids An array of unique IDs. The array will have one element for each bid we were asked
to store. It may include null elements if some of the bids were malformed, or an error occurred.
Each non-null element in this array is a valid input into the retrieve function, which will fetch
some VAST XML which can be used to render this bid's ad.
A function which bridges the APIs between the videoCacheStoreCallback and our ajax function's API.
@param {videoCacheStoreCallback} done A callback to the "store" function.
@return {Function} A callback which interprets the cache server's responses, and makes up the right
arguments for our callback. | [
"A",
"function",
"which",
"should",
"be",
"called",
"with",
"the",
"results",
"of",
"the",
"storage",
"operation",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/src/videoCache.js#L95-L116 |
6,211 | prebid/Prebid.js | modules/medianetBidAdapter.js | getOverlapArea | function getOverlapArea(topLeft1, bottomRight1, topLeft2, bottomRight2) {
// If no overlap, return 0
if ((topLeft1.x > bottomRight2.x || bottomRight1.x < topLeft2.x) || (topLeft1.y > bottomRight2.y || bottomRight1.y < topLeft2.y)) {
return 0;
}
// return overlapping area : [ min of rightmost/bottommost co-ordinates ] - [ max of leftmost/topmost co-ordinates ]
return ((Math.min(bottomRight1.x, bottomRight2.x) - Math.max(topLeft1.x, topLeft2.x)) * (Math.min(bottomRight1.y, bottomRight2.y) - Math.max(topLeft1.y, topLeft2.y)));
} | javascript | function getOverlapArea(topLeft1, bottomRight1, topLeft2, bottomRight2) {
// If no overlap, return 0
if ((topLeft1.x > bottomRight2.x || bottomRight1.x < topLeft2.x) || (topLeft1.y > bottomRight2.y || bottomRight1.y < topLeft2.y)) {
return 0;
}
// return overlapping area : [ min of rightmost/bottommost co-ordinates ] - [ max of leftmost/topmost co-ordinates ]
return ((Math.min(bottomRight1.x, bottomRight2.x) - Math.max(topLeft1.x, topLeft2.x)) * (Math.min(bottomRight1.y, bottomRight2.y) - Math.max(topLeft1.y, topLeft2.y)));
} | [
"function",
"getOverlapArea",
"(",
"topLeft1",
",",
"bottomRight1",
",",
"topLeft2",
",",
"bottomRight2",
")",
"{",
"// If no overlap, return 0",
"if",
"(",
"(",
"topLeft1",
".",
"x",
">",
"bottomRight2",
".",
"x",
"||",
"bottomRight1",
".",
"x",
"<",
"topLeft2",
".",
"x",
")",
"||",
"(",
"topLeft1",
".",
"y",
">",
"bottomRight2",
".",
"y",
"||",
"bottomRight1",
".",
"y",
"<",
"topLeft2",
".",
"y",
")",
")",
"{",
"return",
"0",
";",
"}",
"// return overlapping area : [ min of rightmost/bottommost co-ordinates ] - [ max of leftmost/topmost co-ordinates ]",
"return",
"(",
"(",
"Math",
".",
"min",
"(",
"bottomRight1",
".",
"x",
",",
"bottomRight2",
".",
"x",
")",
"-",
"Math",
".",
"max",
"(",
"topLeft1",
".",
"x",
",",
"topLeft2",
".",
"x",
")",
")",
"*",
"(",
"Math",
".",
"min",
"(",
"bottomRight1",
".",
"y",
",",
"bottomRight2",
".",
"y",
")",
"-",
"Math",
".",
"max",
"(",
"topLeft1",
".",
"y",
",",
"topLeft2",
".",
"y",
")",
")",
")",
";",
"}"
] | find the overlapping area between two rectangles | [
"find",
"the",
"overlapping",
"area",
"between",
"two",
"rectangles"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/medianetBidAdapter.js#L199-L206 |
6,212 | prebid/Prebid.js | modules/ucfunnelBidAdapter.js | function(bid) {
const isVideoMediaType = utils.deepAccess(bid, 'mediaTypes.video');
const videoContext = utils.deepAccess(bid, 'mediaTypes.video.context');
if (typeof bid.params !== 'object' || typeof bid.params.adid != 'string') {
return false;
}
if (isVideoMediaType && videoContext === 'outstream') {
utils.logWarn('Warning: outstream video is not supported yet');
return false;
}
return true;
} | javascript | function(bid) {
const isVideoMediaType = utils.deepAccess(bid, 'mediaTypes.video');
const videoContext = utils.deepAccess(bid, 'mediaTypes.video.context');
if (typeof bid.params !== 'object' || typeof bid.params.adid != 'string') {
return false;
}
if (isVideoMediaType && videoContext === 'outstream') {
utils.logWarn('Warning: outstream video is not supported yet');
return false;
}
return true;
} | [
"function",
"(",
"bid",
")",
"{",
"const",
"isVideoMediaType",
"=",
"utils",
".",
"deepAccess",
"(",
"bid",
",",
"'mediaTypes.video'",
")",
";",
"const",
"videoContext",
"=",
"utils",
".",
"deepAccess",
"(",
"bid",
",",
"'mediaTypes.video.context'",
")",
";",
"if",
"(",
"typeof",
"bid",
".",
"params",
"!==",
"'object'",
"||",
"typeof",
"bid",
".",
"params",
".",
"adid",
"!=",
"'string'",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"isVideoMediaType",
"&&",
"videoContext",
"===",
"'outstream'",
")",
"{",
"utils",
".",
"logWarn",
"(",
"'Warning: outstream video is not supported yet'",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Check if the bid is a valid zone ID in either number or string form
@param {object} bid the ucfunnel bid to validate
@return boolean for whether or not a bid is valid | [
"Check",
"if",
"the",
"bid",
"is",
"a",
"valid",
"zone",
"ID",
"in",
"either",
"number",
"or",
"string",
"form"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/ucfunnelBidAdapter.js#L22-L36 |
|
6,213 | prebid/Prebid.js | modules/ucfunnelBidAdapter.js | function (ucfunnelResponseObj, request) {
const bidRequest = request.bidRequest;
const ad = ucfunnelResponseObj ? ucfunnelResponseObj.body : {};
const videoPlayerSize = parseSizes(bidRequest);
let bid = {
requestId: bidRequest.bidId,
cpm: ad.cpm || 0,
creativeId: ad.ad_id,
dealId: ad.deal || null,
currency: 'USD',
netRevenue: true,
ttl: 1800
};
if (ad.creative_type) {
bid.mediaType = ad.creative_type;
}
switch (ad.creative_type) {
case NATIVE:
let nativeAd = ad.native;
Object.assign(bid, {
width: 1,
height: 1,
native: {
title: nativeAd.title,
body: nativeAd.desc,
cta: nativeAd.ctatext,
sponsoredBy: nativeAd.sponsored,
image: nativeAd.image || nativeAd.image.url,
icon: nativeAd.icon || nativeAd.icon.url,
clickUrl: nativeAd.clickUrl,
impressionTrackers: nativeAd.impressionTrackers,
}
});
break;
case VIDEO:
Object.assign(bid, {
vastUrl: ad.vastUrl,
vastXml: ad.vastXml
});
if (videoPlayerSize && videoPlayerSize.length === 2) {
Object.assign(bid, {
width: videoPlayerSize[0],
height: videoPlayerSize[1]
});
}
break;
case BANNER:
default:
Object.assign(bid, {
width: ad.width,
height: ad.height,
ad: ad.adm
});
}
return [bid];
} | javascript | function (ucfunnelResponseObj, request) {
const bidRequest = request.bidRequest;
const ad = ucfunnelResponseObj ? ucfunnelResponseObj.body : {};
const videoPlayerSize = parseSizes(bidRequest);
let bid = {
requestId: bidRequest.bidId,
cpm: ad.cpm || 0,
creativeId: ad.ad_id,
dealId: ad.deal || null,
currency: 'USD',
netRevenue: true,
ttl: 1800
};
if (ad.creative_type) {
bid.mediaType = ad.creative_type;
}
switch (ad.creative_type) {
case NATIVE:
let nativeAd = ad.native;
Object.assign(bid, {
width: 1,
height: 1,
native: {
title: nativeAd.title,
body: nativeAd.desc,
cta: nativeAd.ctatext,
sponsoredBy: nativeAd.sponsored,
image: nativeAd.image || nativeAd.image.url,
icon: nativeAd.icon || nativeAd.icon.url,
clickUrl: nativeAd.clickUrl,
impressionTrackers: nativeAd.impressionTrackers,
}
});
break;
case VIDEO:
Object.assign(bid, {
vastUrl: ad.vastUrl,
vastXml: ad.vastXml
});
if (videoPlayerSize && videoPlayerSize.length === 2) {
Object.assign(bid, {
width: videoPlayerSize[0],
height: videoPlayerSize[1]
});
}
break;
case BANNER:
default:
Object.assign(bid, {
width: ad.width,
height: ad.height,
ad: ad.adm
});
}
return [bid];
} | [
"function",
"(",
"ucfunnelResponseObj",
",",
"request",
")",
"{",
"const",
"bidRequest",
"=",
"request",
".",
"bidRequest",
";",
"const",
"ad",
"=",
"ucfunnelResponseObj",
"?",
"ucfunnelResponseObj",
".",
"body",
":",
"{",
"}",
";",
"const",
"videoPlayerSize",
"=",
"parseSizes",
"(",
"bidRequest",
")",
";",
"let",
"bid",
"=",
"{",
"requestId",
":",
"bidRequest",
".",
"bidId",
",",
"cpm",
":",
"ad",
".",
"cpm",
"||",
"0",
",",
"creativeId",
":",
"ad",
".",
"ad_id",
",",
"dealId",
":",
"ad",
".",
"deal",
"||",
"null",
",",
"currency",
":",
"'USD'",
",",
"netRevenue",
":",
"true",
",",
"ttl",
":",
"1800",
"}",
";",
"if",
"(",
"ad",
".",
"creative_type",
")",
"{",
"bid",
".",
"mediaType",
"=",
"ad",
".",
"creative_type",
";",
"}",
"switch",
"(",
"ad",
".",
"creative_type",
")",
"{",
"case",
"NATIVE",
":",
"let",
"nativeAd",
"=",
"ad",
".",
"native",
";",
"Object",
".",
"assign",
"(",
"bid",
",",
"{",
"width",
":",
"1",
",",
"height",
":",
"1",
",",
"native",
":",
"{",
"title",
":",
"nativeAd",
".",
"title",
",",
"body",
":",
"nativeAd",
".",
"desc",
",",
"cta",
":",
"nativeAd",
".",
"ctatext",
",",
"sponsoredBy",
":",
"nativeAd",
".",
"sponsored",
",",
"image",
":",
"nativeAd",
".",
"image",
"||",
"nativeAd",
".",
"image",
".",
"url",
",",
"icon",
":",
"nativeAd",
".",
"icon",
"||",
"nativeAd",
".",
"icon",
".",
"url",
",",
"clickUrl",
":",
"nativeAd",
".",
"clickUrl",
",",
"impressionTrackers",
":",
"nativeAd",
".",
"impressionTrackers",
",",
"}",
"}",
")",
";",
"break",
";",
"case",
"VIDEO",
":",
"Object",
".",
"assign",
"(",
"bid",
",",
"{",
"vastUrl",
":",
"ad",
".",
"vastUrl",
",",
"vastXml",
":",
"ad",
".",
"vastXml",
"}",
")",
";",
"if",
"(",
"videoPlayerSize",
"&&",
"videoPlayerSize",
".",
"length",
"===",
"2",
")",
"{",
"Object",
".",
"assign",
"(",
"bid",
",",
"{",
"width",
":",
"videoPlayerSize",
"[",
"0",
"]",
",",
"height",
":",
"videoPlayerSize",
"[",
"1",
"]",
"}",
")",
";",
"}",
"break",
";",
"case",
"BANNER",
":",
"default",
":",
"Object",
".",
"assign",
"(",
"bid",
",",
"{",
"width",
":",
"ad",
".",
"width",
",",
"height",
":",
"ad",
".",
"height",
",",
"ad",
":",
"ad",
".",
"adm",
"}",
")",
";",
"}",
"return",
"[",
"bid",
"]",
";",
"}"
] | Format ucfunnel responses as Prebid bid responses
@param {ucfunnelResponseObj} ucfunnelResponse A successful response from ucfunnel.
@return {Bid[]} An array of formatted bids. | [
"Format",
"ucfunnel",
"responses",
"as",
"Prebid",
"bid",
"responses"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/ucfunnelBidAdapter.js#L59-L119 |
|
6,214 | prebid/Prebid.js | modules/conversantBidAdapter.js | getDevice | function getDevice() {
const language = navigator.language ? 'language' : 'userLanguage';
return {
h: screen.height,
w: screen.width,
dnt: getDNT() ? 1 : 0,
language: navigator[language].split('-')[0],
make: navigator.vendor ? navigator.vendor : '',
ua: navigator.userAgent
};
} | javascript | function getDevice() {
const language = navigator.language ? 'language' : 'userLanguage';
return {
h: screen.height,
w: screen.width,
dnt: getDNT() ? 1 : 0,
language: navigator[language].split('-')[0],
make: navigator.vendor ? navigator.vendor : '',
ua: navigator.userAgent
};
} | [
"function",
"getDevice",
"(",
")",
"{",
"const",
"language",
"=",
"navigator",
".",
"language",
"?",
"'language'",
":",
"'userLanguage'",
";",
"return",
"{",
"h",
":",
"screen",
".",
"height",
",",
"w",
":",
"screen",
".",
"width",
",",
"dnt",
":",
"getDNT",
"(",
")",
"?",
"1",
":",
"0",
",",
"language",
":",
"navigator",
"[",
"language",
"]",
".",
"split",
"(",
"'-'",
")",
"[",
"0",
"]",
",",
"make",
":",
"navigator",
".",
"vendor",
"?",
"navigator",
".",
"vendor",
":",
"''",
",",
"ua",
":",
"navigator",
".",
"userAgent",
"}",
";",
"}"
] | Return openrtb device object that includes ua, width, and height.
@returns {Device} Openrtb device object | [
"Return",
"openrtb",
"device",
"object",
"that",
"includes",
"ua",
"width",
"and",
"height",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/conversantBidAdapter.js#L236-L246 |
6,215 | prebid/Prebid.js | modules/conversantBidAdapter.js | convertSizes | function convertSizes(bidSizes) {
let format;
if (Array.isArray(bidSizes)) {
if (bidSizes.length === 2 && typeof bidSizes[0] === 'number' && typeof bidSizes[1] === 'number') {
format = [{w: bidSizes[0], h: bidSizes[1]}];
} else {
format = utils._map(bidSizes, d => { return {w: d[0], h: d[1]}; });
}
}
return format;
} | javascript | function convertSizes(bidSizes) {
let format;
if (Array.isArray(bidSizes)) {
if (bidSizes.length === 2 && typeof bidSizes[0] === 'number' && typeof bidSizes[1] === 'number') {
format = [{w: bidSizes[0], h: bidSizes[1]}];
} else {
format = utils._map(bidSizes, d => { return {w: d[0], h: d[1]}; });
}
}
return format;
} | [
"function",
"convertSizes",
"(",
"bidSizes",
")",
"{",
"let",
"format",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"bidSizes",
")",
")",
"{",
"if",
"(",
"bidSizes",
".",
"length",
"===",
"2",
"&&",
"typeof",
"bidSizes",
"[",
"0",
"]",
"===",
"'number'",
"&&",
"typeof",
"bidSizes",
"[",
"1",
"]",
"===",
"'number'",
")",
"{",
"format",
"=",
"[",
"{",
"w",
":",
"bidSizes",
"[",
"0",
"]",
",",
"h",
":",
"bidSizes",
"[",
"1",
"]",
"}",
"]",
";",
"}",
"else",
"{",
"format",
"=",
"utils",
".",
"_map",
"(",
"bidSizes",
",",
"d",
"=>",
"{",
"return",
"{",
"w",
":",
"d",
"[",
"0",
"]",
",",
"h",
":",
"d",
"[",
"1",
"]",
"}",
";",
"}",
")",
";",
"}",
"}",
"return",
"format",
";",
"}"
] | Convert arrays of widths and heights to an array of objects with w and h properties.
[[300, 250], [300, 600]] => [{w: 300, h: 250}, {w: 300, h: 600}]
@param {number[2][]|number[2]} bidSizes - arrays of widths and heights
@returns {object[]} Array of objects with w and h | [
"Convert",
"arrays",
"of",
"widths",
"and",
"heights",
"to",
"an",
"array",
"of",
"objects",
"with",
"w",
"and",
"h",
"properties",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/conversantBidAdapter.js#L256-L267 |
6,216 | prebid/Prebid.js | src/adapters/bidderFactory.js | validBidSize | function validBidSize(adUnitCode, bid, bidRequests) {
if ((bid.width || parseInt(bid.width, 10) === 0) && (bid.height || parseInt(bid.height, 10) === 0)) {
bid.width = parseInt(bid.width, 10);
bid.height = parseInt(bid.height, 10);
return true;
}
const adUnit = getBidderRequest(bidRequests, bid.bidderCode, adUnitCode);
const sizes = adUnit && adUnit.bids && adUnit.bids[0] && adUnit.bids[0].sizes;
const parsedSizes = parseSizesInput(sizes);
// if a banner impression has one valid size, we assign that size to any bid
// response that does not explicitly set width or height
if (parsedSizes.length === 1) {
const [ width, height ] = parsedSizes[0].split('x');
bid.width = parseInt(width, 10);
bid.height = parseInt(height, 10);
return true;
}
return false;
} | javascript | function validBidSize(adUnitCode, bid, bidRequests) {
if ((bid.width || parseInt(bid.width, 10) === 0) && (bid.height || parseInt(bid.height, 10) === 0)) {
bid.width = parseInt(bid.width, 10);
bid.height = parseInt(bid.height, 10);
return true;
}
const adUnit = getBidderRequest(bidRequests, bid.bidderCode, adUnitCode);
const sizes = adUnit && adUnit.bids && adUnit.bids[0] && adUnit.bids[0].sizes;
const parsedSizes = parseSizesInput(sizes);
// if a banner impression has one valid size, we assign that size to any bid
// response that does not explicitly set width or height
if (parsedSizes.length === 1) {
const [ width, height ] = parsedSizes[0].split('x');
bid.width = parseInt(width, 10);
bid.height = parseInt(height, 10);
return true;
}
return false;
} | [
"function",
"validBidSize",
"(",
"adUnitCode",
",",
"bid",
",",
"bidRequests",
")",
"{",
"if",
"(",
"(",
"bid",
".",
"width",
"||",
"parseInt",
"(",
"bid",
".",
"width",
",",
"10",
")",
"===",
"0",
")",
"&&",
"(",
"bid",
".",
"height",
"||",
"parseInt",
"(",
"bid",
".",
"height",
",",
"10",
")",
"===",
"0",
")",
")",
"{",
"bid",
".",
"width",
"=",
"parseInt",
"(",
"bid",
".",
"width",
",",
"10",
")",
";",
"bid",
".",
"height",
"=",
"parseInt",
"(",
"bid",
".",
"height",
",",
"10",
")",
";",
"return",
"true",
";",
"}",
"const",
"adUnit",
"=",
"getBidderRequest",
"(",
"bidRequests",
",",
"bid",
".",
"bidderCode",
",",
"adUnitCode",
")",
";",
"const",
"sizes",
"=",
"adUnit",
"&&",
"adUnit",
".",
"bids",
"&&",
"adUnit",
".",
"bids",
"[",
"0",
"]",
"&&",
"adUnit",
".",
"bids",
"[",
"0",
"]",
".",
"sizes",
";",
"const",
"parsedSizes",
"=",
"parseSizesInput",
"(",
"sizes",
")",
";",
"// if a banner impression has one valid size, we assign that size to any bid",
"// response that does not explicitly set width or height",
"if",
"(",
"parsedSizes",
".",
"length",
"===",
"1",
")",
"{",
"const",
"[",
"width",
",",
"height",
"]",
"=",
"parsedSizes",
"[",
"0",
"]",
".",
"split",
"(",
"'x'",
")",
";",
"bid",
".",
"width",
"=",
"parseInt",
"(",
"width",
",",
"10",
")",
";",
"bid",
".",
"height",
"=",
"parseInt",
"(",
"height",
",",
"10",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | check that the bid has a width and height set | [
"check",
"that",
"the",
"bid",
"has",
"a",
"width",
"and",
"height",
"set"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/src/adapters/bidderFactory.js#L425-L447 |
6,217 | prebid/Prebid.js | modules/prebidServerBidAdapter/index.js | setS2sConfig | function setS2sConfig(options) {
if (options.defaultVendor) {
let vendor = options.defaultVendor;
let optionKeys = Object.keys(options);
if (S2S_VENDORS[vendor]) {
// vendor keys will be set if either: the key was not specified by user
// or if the user did not set their own distinct value (ie using the system default) to override the vendor
Object.keys(S2S_VENDORS[vendor]).forEach((vendorKey) => {
if (s2sDefaultConfig[vendorKey] === options[vendorKey] || !includes(optionKeys, vendorKey)) {
options[vendorKey] = S2S_VENDORS[vendor][vendorKey];
}
});
} else {
utils.logError('Incorrect or unavailable prebid server default vendor option: ' + vendor);
return false;
}
}
let keys = Object.keys(options);
if (['accountId', 'bidders', 'endpoint'].filter(key => {
if (!includes(keys, key)) {
utils.logError(key + ' missing in server to server config');
return true;
}
return false;
}).length > 0) {
return;
}
_s2sConfig = options;
} | javascript | function setS2sConfig(options) {
if (options.defaultVendor) {
let vendor = options.defaultVendor;
let optionKeys = Object.keys(options);
if (S2S_VENDORS[vendor]) {
// vendor keys will be set if either: the key was not specified by user
// or if the user did not set their own distinct value (ie using the system default) to override the vendor
Object.keys(S2S_VENDORS[vendor]).forEach((vendorKey) => {
if (s2sDefaultConfig[vendorKey] === options[vendorKey] || !includes(optionKeys, vendorKey)) {
options[vendorKey] = S2S_VENDORS[vendor][vendorKey];
}
});
} else {
utils.logError('Incorrect or unavailable prebid server default vendor option: ' + vendor);
return false;
}
}
let keys = Object.keys(options);
if (['accountId', 'bidders', 'endpoint'].filter(key => {
if (!includes(keys, key)) {
utils.logError(key + ' missing in server to server config');
return true;
}
return false;
}).length > 0) {
return;
}
_s2sConfig = options;
} | [
"function",
"setS2sConfig",
"(",
"options",
")",
"{",
"if",
"(",
"options",
".",
"defaultVendor",
")",
"{",
"let",
"vendor",
"=",
"options",
".",
"defaultVendor",
";",
"let",
"optionKeys",
"=",
"Object",
".",
"keys",
"(",
"options",
")",
";",
"if",
"(",
"S2S_VENDORS",
"[",
"vendor",
"]",
")",
"{",
"// vendor keys will be set if either: the key was not specified by user",
"// or if the user did not set their own distinct value (ie using the system default) to override the vendor",
"Object",
".",
"keys",
"(",
"S2S_VENDORS",
"[",
"vendor",
"]",
")",
".",
"forEach",
"(",
"(",
"vendorKey",
")",
"=>",
"{",
"if",
"(",
"s2sDefaultConfig",
"[",
"vendorKey",
"]",
"===",
"options",
"[",
"vendorKey",
"]",
"||",
"!",
"includes",
"(",
"optionKeys",
",",
"vendorKey",
")",
")",
"{",
"options",
"[",
"vendorKey",
"]",
"=",
"S2S_VENDORS",
"[",
"vendor",
"]",
"[",
"vendorKey",
"]",
";",
"}",
"}",
")",
";",
"}",
"else",
"{",
"utils",
".",
"logError",
"(",
"'Incorrect or unavailable prebid server default vendor option: '",
"+",
"vendor",
")",
";",
"return",
"false",
";",
"}",
"}",
"let",
"keys",
"=",
"Object",
".",
"keys",
"(",
"options",
")",
";",
"if",
"(",
"[",
"'accountId'",
",",
"'bidders'",
",",
"'endpoint'",
"]",
".",
"filter",
"(",
"key",
"=>",
"{",
"if",
"(",
"!",
"includes",
"(",
"keys",
",",
"key",
")",
")",
"{",
"utils",
".",
"logError",
"(",
"key",
"+",
"' missing in server to server config'",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
")",
".",
"length",
">",
"0",
")",
"{",
"return",
";",
"}",
"_s2sConfig",
"=",
"options",
";",
"}"
] | Set config for server to server header bidding
@typedef {Object} options - required
@property {boolean} enabled enables S2S bidding
@property {string[]} bidders bidders to request S2S
@property {string} endpoint endpoint to contact
=== optional params below ===
@property {number} [timeout] timeout for S2S bidders - should be lower than `pbjs.requestBids({timeout})`
@property {boolean} [cacheMarkup] whether to cache the adm result
@property {string} [adapter] adapter code to use for S2S
@property {string} [syncEndpoint] endpoint URL for syncing cookies
@property {Object} [extPrebid] properties will be merged into request.ext.prebid
@property {AdapterOptions} [adapterOptions] adds arguments to resulting OpenRTB payload to Prebid Server | [
"Set",
"config",
"for",
"server",
"to",
"server",
"header",
"bidding"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/prebidServerBidAdapter/index.js#L78-L109 |
6,218 | prebid/Prebid.js | modules/prebidServerBidAdapter/index.js | doPreBidderSync | function doPreBidderSync(type, url, bidder, done) {
if (_s2sConfig.syncUrlModifier && typeof _s2sConfig.syncUrlModifier[bidder] === 'function') {
const newSyncUrl = _s2sConfig.syncUrlModifier[bidder](type, url, bidder);
doBidderSync(type, newSyncUrl, bidder, done)
} else {
doBidderSync(type, url, bidder, done)
}
} | javascript | function doPreBidderSync(type, url, bidder, done) {
if (_s2sConfig.syncUrlModifier && typeof _s2sConfig.syncUrlModifier[bidder] === 'function') {
const newSyncUrl = _s2sConfig.syncUrlModifier[bidder](type, url, bidder);
doBidderSync(type, newSyncUrl, bidder, done)
} else {
doBidderSync(type, url, bidder, done)
}
} | [
"function",
"doPreBidderSync",
"(",
"type",
",",
"url",
",",
"bidder",
",",
"done",
")",
"{",
"if",
"(",
"_s2sConfig",
".",
"syncUrlModifier",
"&&",
"typeof",
"_s2sConfig",
".",
"syncUrlModifier",
"[",
"bidder",
"]",
"===",
"'function'",
")",
"{",
"const",
"newSyncUrl",
"=",
"_s2sConfig",
".",
"syncUrlModifier",
"[",
"bidder",
"]",
"(",
"type",
",",
"url",
",",
"bidder",
")",
";",
"doBidderSync",
"(",
"type",
",",
"newSyncUrl",
",",
"bidder",
",",
"done",
")",
"}",
"else",
"{",
"doBidderSync",
"(",
"type",
",",
"url",
",",
"bidder",
",",
"done",
")",
"}",
"}"
] | Modify the cookie sync url from prebid server to add new params.
@param {string} type the type of sync, "image", "redirect", "iframe"
@param {string} url the url to sync
@param {string} bidder name of bidder doing sync for
@param {function} done an exit callback; to signify this pixel has either: finished rendering or something went wrong | [
"Modify",
"the",
"cookie",
"sync",
"url",
"from",
"prebid",
"server",
"to",
"add",
"new",
"params",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/prebidServerBidAdapter/index.js#L188-L195 |
6,219 | prebid/Prebid.js | modules/prebidServerBidAdapter/index.js | doBidderSync | function doBidderSync(type, url, bidder, done) {
if (!url) {
utils.logError(`No sync url for bidder "${bidder}": ${url}`);
done();
} else if (type === 'image' || type === 'redirect') {
utils.logMessage(`Invoking image pixel user sync for bidder: "${bidder}"`);
utils.triggerPixel(url, done);
} else if (type == 'iframe') {
utils.logMessage(`Invoking iframe user sync for bidder: "${bidder}"`);
utils.insertUserSyncIframe(url, done);
} else {
utils.logError(`User sync type "${type}" not supported for bidder: "${bidder}"`);
done();
}
} | javascript | function doBidderSync(type, url, bidder, done) {
if (!url) {
utils.logError(`No sync url for bidder "${bidder}": ${url}`);
done();
} else if (type === 'image' || type === 'redirect') {
utils.logMessage(`Invoking image pixel user sync for bidder: "${bidder}"`);
utils.triggerPixel(url, done);
} else if (type == 'iframe') {
utils.logMessage(`Invoking iframe user sync for bidder: "${bidder}"`);
utils.insertUserSyncIframe(url, done);
} else {
utils.logError(`User sync type "${type}" not supported for bidder: "${bidder}"`);
done();
}
} | [
"function",
"doBidderSync",
"(",
"type",
",",
"url",
",",
"bidder",
",",
"done",
")",
"{",
"if",
"(",
"!",
"url",
")",
"{",
"utils",
".",
"logError",
"(",
"`",
"${",
"bidder",
"}",
"${",
"url",
"}",
"`",
")",
";",
"done",
"(",
")",
";",
"}",
"else",
"if",
"(",
"type",
"===",
"'image'",
"||",
"type",
"===",
"'redirect'",
")",
"{",
"utils",
".",
"logMessage",
"(",
"`",
"${",
"bidder",
"}",
"`",
")",
";",
"utils",
".",
"triggerPixel",
"(",
"url",
",",
"done",
")",
";",
"}",
"else",
"if",
"(",
"type",
"==",
"'iframe'",
")",
"{",
"utils",
".",
"logMessage",
"(",
"`",
"${",
"bidder",
"}",
"`",
")",
";",
"utils",
".",
"insertUserSyncIframe",
"(",
"url",
",",
"done",
")",
";",
"}",
"else",
"{",
"utils",
".",
"logError",
"(",
"`",
"${",
"type",
"}",
"${",
"bidder",
"}",
"`",
")",
";",
"done",
"(",
")",
";",
"}",
"}"
] | Run a cookie sync for the given type, url, and bidder
@param {string} type the type of sync, "image", "redirect", "iframe"
@param {string} url the url to sync
@param {string} bidder name of bidder doing sync for
@param {function} done an exit callback; to signify this pixel has either: finished rendering or something went wrong | [
"Run",
"a",
"cookie",
"sync",
"for",
"the",
"given",
"type",
"url",
"and",
"bidder"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/prebidServerBidAdapter/index.js#L205-L219 |
6,220 | prebid/Prebid.js | modules/prebidServerBidAdapter/index.js | doClientSideSyncs | function doClientSideSyncs(bidders) {
bidders.forEach(bidder => {
let clientAdapter = adapterManager.getBidAdapter(bidder);
if (clientAdapter && clientAdapter.registerSyncs) {
clientAdapter.registerSyncs([]);
}
});
} | javascript | function doClientSideSyncs(bidders) {
bidders.forEach(bidder => {
let clientAdapter = adapterManager.getBidAdapter(bidder);
if (clientAdapter && clientAdapter.registerSyncs) {
clientAdapter.registerSyncs([]);
}
});
} | [
"function",
"doClientSideSyncs",
"(",
"bidders",
")",
"{",
"bidders",
".",
"forEach",
"(",
"bidder",
"=>",
"{",
"let",
"clientAdapter",
"=",
"adapterManager",
".",
"getBidAdapter",
"(",
"bidder",
")",
";",
"if",
"(",
"clientAdapter",
"&&",
"clientAdapter",
".",
"registerSyncs",
")",
"{",
"clientAdapter",
".",
"registerSyncs",
"(",
"[",
"]",
")",
";",
"}",
"}",
")",
";",
"}"
] | Do client-side syncs for bidders.
@param {Array} bidders a list of bidder names | [
"Do",
"client",
"-",
"side",
"syncs",
"for",
"bidders",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/prebidServerBidAdapter/index.js#L226-L233 |
6,221 | prebid/Prebid.js | gulpHelpers.js | isModuleDirectory | function isModuleDirectory(filePath) {
try {
const manifestPath = path.join(filePath, MANIFEST);
if (fs.statSync(manifestPath).isFile()) {
const module = require(manifestPath);
return module && module.main;
}
} catch (error) {}
} | javascript | function isModuleDirectory(filePath) {
try {
const manifestPath = path.join(filePath, MANIFEST);
if (fs.statSync(manifestPath).isFile()) {
const module = require(manifestPath);
return module && module.main;
}
} catch (error) {}
} | [
"function",
"isModuleDirectory",
"(",
"filePath",
")",
"{",
"try",
"{",
"const",
"manifestPath",
"=",
"path",
".",
"join",
"(",
"filePath",
",",
"MANIFEST",
")",
";",
"if",
"(",
"fs",
".",
"statSync",
"(",
"manifestPath",
")",
".",
"isFile",
"(",
")",
")",
"{",
"const",
"module",
"=",
"require",
"(",
"manifestPath",
")",
";",
"return",
"module",
"&&",
"module",
".",
"main",
";",
"}",
"}",
"catch",
"(",
"error",
")",
"{",
"}",
"}"
] | get only subdirectories that contain package.json with 'main' property | [
"get",
"only",
"subdirectories",
"that",
"contain",
"package",
".",
"json",
"with",
"main",
"property"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/gulpHelpers.js#L16-L24 |
6,222 | prebid/Prebid.js | modules/dfpAdServerVideo.js | buildUrlFromAdserverUrlComponents | function buildUrlFromAdserverUrlComponents(components, bid, options) {
const descriptionUrl = getDescriptionUrl(bid, components, 'search');
if (descriptionUrl) { components.search.description_url = descriptionUrl; }
const encodedCustomParams = getCustParams(bid, options);
components.search.cust_params = (components.search.cust_params) ? components.search.cust_params + '%26' + encodedCustomParams : encodedCustomParams;
return buildUrl(components);
} | javascript | function buildUrlFromAdserverUrlComponents(components, bid, options) {
const descriptionUrl = getDescriptionUrl(bid, components, 'search');
if (descriptionUrl) { components.search.description_url = descriptionUrl; }
const encodedCustomParams = getCustParams(bid, options);
components.search.cust_params = (components.search.cust_params) ? components.search.cust_params + '%26' + encodedCustomParams : encodedCustomParams;
return buildUrl(components);
} | [
"function",
"buildUrlFromAdserverUrlComponents",
"(",
"components",
",",
"bid",
",",
"options",
")",
"{",
"const",
"descriptionUrl",
"=",
"getDescriptionUrl",
"(",
"bid",
",",
"components",
",",
"'search'",
")",
";",
"if",
"(",
"descriptionUrl",
")",
"{",
"components",
".",
"search",
".",
"description_url",
"=",
"descriptionUrl",
";",
"}",
"const",
"encodedCustomParams",
"=",
"getCustParams",
"(",
"bid",
",",
"options",
")",
";",
"components",
".",
"search",
".",
"cust_params",
"=",
"(",
"components",
".",
"search",
".",
"cust_params",
")",
"?",
"components",
".",
"search",
".",
"cust_params",
"+",
"'%26'",
"+",
"encodedCustomParams",
":",
"encodedCustomParams",
";",
"return",
"buildUrl",
"(",
"components",
")",
";",
"}"
] | Builds a video url from a base dfp video url and a winning bid, appending
Prebid-specific key-values.
@param {Object} components base video adserver url parsed into components object
@param {AdapterBidResponse} bid winning bid object to append parameters from
@param {Object} options Options which should be used to construct the URL (used for custom params).
@return {string} video url | [
"Builds",
"a",
"video",
"url",
"from",
"a",
"base",
"dfp",
"video",
"url",
"and",
"a",
"winning",
"bid",
"appending",
"Prebid",
"-",
"specific",
"key",
"-",
"values",
"."
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/dfpAdServerVideo.js#L114-L122 |
6,223 | prebid/Prebid.js | modules/dfpAdServerVideo.js | getDescriptionUrl | function getDescriptionUrl(bid, components, prop) {
if (config.getConfig('cache.url')) { return; }
if (!deepAccess(components, `${prop}.description_url`)) {
const vastUrl = bid && bid.vastUrl;
if (vastUrl) { return encodeURIComponent(vastUrl); }
} else {
logError(`input cannnot contain description_url`);
}
} | javascript | function getDescriptionUrl(bid, components, prop) {
if (config.getConfig('cache.url')) { return; }
if (!deepAccess(components, `${prop}.description_url`)) {
const vastUrl = bid && bid.vastUrl;
if (vastUrl) { return encodeURIComponent(vastUrl); }
} else {
logError(`input cannnot contain description_url`);
}
} | [
"function",
"getDescriptionUrl",
"(",
"bid",
",",
"components",
",",
"prop",
")",
"{",
"if",
"(",
"config",
".",
"getConfig",
"(",
"'cache.url'",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"deepAccess",
"(",
"components",
",",
"`",
"${",
"prop",
"}",
"`",
")",
")",
"{",
"const",
"vastUrl",
"=",
"bid",
"&&",
"bid",
".",
"vastUrl",
";",
"if",
"(",
"vastUrl",
")",
"{",
"return",
"encodeURIComponent",
"(",
"vastUrl",
")",
";",
"}",
"}",
"else",
"{",
"logError",
"(",
"`",
"`",
")",
";",
"}",
"}"
] | Returns the encoded vast url if it exists on a bid object, only if prebid-cache
is disabled, and description_url is not already set on a given input
@param {AdapterBidResponse} bid object to check for vast url
@param {Object} components the object to check that description_url is NOT set on
@param {string} prop the property of components that would contain description_url
@return {string | undefined} The encoded vast url if it exists, or undefined | [
"Returns",
"the",
"encoded",
"vast",
"url",
"if",
"it",
"exists",
"on",
"a",
"bid",
"object",
"only",
"if",
"prebid",
"-",
"cache",
"is",
"disabled",
"and",
"description_url",
"is",
"not",
"already",
"set",
"on",
"a",
"given",
"input"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/dfpAdServerVideo.js#L132-L141 |
6,224 | prebid/Prebid.js | modules/dfpAdServerVideo.js | getCustParams | function getCustParams(bid, options) {
const adserverTargeting = (bid && bid.adserverTargeting) || {};
let allTargetingData = {};
const adUnit = options && options.adUnit;
if (adUnit) {
let allTargeting = targeting.getAllTargeting(adUnit.code);
allTargetingData = (allTargeting) ? allTargeting[adUnit.code] : {};
}
const optCustParams = deepAccess(options, 'params.cust_params');
let customParams = Object.assign({},
// Why are we adding standard keys here ? Refer https://github.com/prebid/Prebid.js/issues/3664
{ hb_uuid: bid && bid.videoCacheKey },
// hb_uuid will be deprecated and replaced by hb_cache_id
{ hb_cache_id: bid && bid.videoCacheKey },
allTargetingData,
adserverTargeting,
optCustParams,
);
return encodeURIComponent(formatQS(customParams));
} | javascript | function getCustParams(bid, options) {
const adserverTargeting = (bid && bid.adserverTargeting) || {};
let allTargetingData = {};
const adUnit = options && options.adUnit;
if (adUnit) {
let allTargeting = targeting.getAllTargeting(adUnit.code);
allTargetingData = (allTargeting) ? allTargeting[adUnit.code] : {};
}
const optCustParams = deepAccess(options, 'params.cust_params');
let customParams = Object.assign({},
// Why are we adding standard keys here ? Refer https://github.com/prebid/Prebid.js/issues/3664
{ hb_uuid: bid && bid.videoCacheKey },
// hb_uuid will be deprecated and replaced by hb_cache_id
{ hb_cache_id: bid && bid.videoCacheKey },
allTargetingData,
adserverTargeting,
optCustParams,
);
return encodeURIComponent(formatQS(customParams));
} | [
"function",
"getCustParams",
"(",
"bid",
",",
"options",
")",
"{",
"const",
"adserverTargeting",
"=",
"(",
"bid",
"&&",
"bid",
".",
"adserverTargeting",
")",
"||",
"{",
"}",
";",
"let",
"allTargetingData",
"=",
"{",
"}",
";",
"const",
"adUnit",
"=",
"options",
"&&",
"options",
".",
"adUnit",
";",
"if",
"(",
"adUnit",
")",
"{",
"let",
"allTargeting",
"=",
"targeting",
".",
"getAllTargeting",
"(",
"adUnit",
".",
"code",
")",
";",
"allTargetingData",
"=",
"(",
"allTargeting",
")",
"?",
"allTargeting",
"[",
"adUnit",
".",
"code",
"]",
":",
"{",
"}",
";",
"}",
"const",
"optCustParams",
"=",
"deepAccess",
"(",
"options",
",",
"'params.cust_params'",
")",
";",
"let",
"customParams",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"// Why are we adding standard keys here ? Refer https://github.com/prebid/Prebid.js/issues/3664",
"{",
"hb_uuid",
":",
"bid",
"&&",
"bid",
".",
"videoCacheKey",
"}",
",",
"// hb_uuid will be deprecated and replaced by hb_cache_id",
"{",
"hb_cache_id",
":",
"bid",
"&&",
"bid",
".",
"videoCacheKey",
"}",
",",
"allTargetingData",
",",
"adserverTargeting",
",",
"optCustParams",
",",
")",
";",
"return",
"encodeURIComponent",
"(",
"formatQS",
"(",
"customParams",
")",
")",
";",
"}"
] | Returns the encoded `cust_params` from the bid.adserverTargeting and adds the `hb_uuid`, and `hb_cache_id`. Optionally the options.params.cust_params
@param {AdapterBidResponse} bid
@param {Object} options this is the options passed in from the `buildDfpVideoUrl` function
@return {Object} Encoded key value pairs for cust_params | [
"Returns",
"the",
"encoded",
"cust_params",
"from",
"the",
"bid",
".",
"adserverTargeting",
"and",
"adds",
"the",
"hb_uuid",
"and",
"hb_cache_id",
".",
"Optionally",
"the",
"options",
".",
"params",
".",
"cust_params"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/dfpAdServerVideo.js#L149-L170 |
6,225 | prebid/Prebid.js | modules/pubCommonId.js | readValue | function readValue(name) {
let value;
if (pubcidConfig.typeEnabled === COOKIE) {
value = getCookie(name);
} else if (pubcidConfig.typeEnabled === LOCAL_STORAGE) {
value = getStorageItem(name);
if (!value) {
value = getCookie(name);
}
}
if (value === 'undefined' || value === 'null') { return null; }
return value;
} | javascript | function readValue(name) {
let value;
if (pubcidConfig.typeEnabled === COOKIE) {
value = getCookie(name);
} else if (pubcidConfig.typeEnabled === LOCAL_STORAGE) {
value = getStorageItem(name);
if (!value) {
value = getCookie(name);
}
}
if (value === 'undefined' || value === 'null') { return null; }
return value;
} | [
"function",
"readValue",
"(",
"name",
")",
"{",
"let",
"value",
";",
"if",
"(",
"pubcidConfig",
".",
"typeEnabled",
"===",
"COOKIE",
")",
"{",
"value",
"=",
"getCookie",
"(",
"name",
")",
";",
"}",
"else",
"if",
"(",
"pubcidConfig",
".",
"typeEnabled",
"===",
"LOCAL_STORAGE",
")",
"{",
"value",
"=",
"getStorageItem",
"(",
"name",
")",
";",
"if",
"(",
"!",
"value",
")",
"{",
"value",
"=",
"getCookie",
"(",
"name",
")",
";",
"}",
"}",
"if",
"(",
"value",
"===",
"'undefined'",
"||",
"value",
"===",
"'null'",
")",
"{",
"return",
"null",
";",
"}",
"return",
"value",
";",
"}"
] | Read a value either from cookie or local storage
@param {string} name Name of the item
@returns {string|null} a string if item exists | [
"Read",
"a",
"value",
"either",
"from",
"cookie",
"or",
"local",
"storage"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/pubCommonId.js#L94-L108 |
6,226 | prebid/Prebid.js | modules/pubCommonId.js | writeValue | function writeValue(name, value, expInterval) {
if (name && value) {
if (pubcidConfig.typeEnabled === COOKIE) {
setCookie(name, value, expInterval);
} else if (pubcidConfig.typeEnabled === LOCAL_STORAGE) {
setStorageItem(name, value, expInterval);
}
}
} | javascript | function writeValue(name, value, expInterval) {
if (name && value) {
if (pubcidConfig.typeEnabled === COOKIE) {
setCookie(name, value, expInterval);
} else if (pubcidConfig.typeEnabled === LOCAL_STORAGE) {
setStorageItem(name, value, expInterval);
}
}
} | [
"function",
"writeValue",
"(",
"name",
",",
"value",
",",
"expInterval",
")",
"{",
"if",
"(",
"name",
"&&",
"value",
")",
"{",
"if",
"(",
"pubcidConfig",
".",
"typeEnabled",
"===",
"COOKIE",
")",
"{",
"setCookie",
"(",
"name",
",",
"value",
",",
"expInterval",
")",
";",
"}",
"else",
"if",
"(",
"pubcidConfig",
".",
"typeEnabled",
"===",
"LOCAL_STORAGE",
")",
"{",
"setStorageItem",
"(",
"name",
",",
"value",
",",
"expInterval",
")",
";",
"}",
"}",
"}"
] | Write a value to either cookies or local storage
@param {string} name Name of the item
@param {string} value Value to be stored
@param {number} expInterval Expiry time in minutes | [
"Write",
"a",
"value",
"to",
"either",
"cookies",
"or",
"local",
"storage"
] | bd1636ada243f30c309bd8212e4446d39d86659b | https://github.com/prebid/Prebid.js/blob/bd1636ada243f30c309bd8212e4446d39d86659b/modules/pubCommonId.js#L116-L124 |
6,227 | Codeception/CodeceptJS | lib/pause.js | function () {
next = false;
// add listener to all next steps to provide next() functionality
event.dispatcher.on(event.step.after, () => {
recorder.add('Start next pause session', () => {
if (!next) return;
return pauseSession();
});
});
recorder.add('Start new session', pauseSession);
} | javascript | function () {
next = false;
// add listener to all next steps to provide next() functionality
event.dispatcher.on(event.step.after, () => {
recorder.add('Start next pause session', () => {
if (!next) return;
return pauseSession();
});
});
recorder.add('Start new session', pauseSession);
} | [
"function",
"(",
")",
"{",
"next",
"=",
"false",
";",
"// add listener to all next steps to provide next() functionality",
"event",
".",
"dispatcher",
".",
"on",
"(",
"event",
".",
"step",
".",
"after",
",",
"(",
")",
"=>",
"{",
"recorder",
".",
"add",
"(",
"'Start next pause session'",
",",
"(",
")",
"=>",
"{",
"if",
"(",
"!",
"next",
")",
"return",
";",
"return",
"pauseSession",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"recorder",
".",
"add",
"(",
"'Start new session'",
",",
"pauseSession",
")",
";",
"}"
] | Pauses test execution and starts interactive shell | [
"Pauses",
"test",
"execution",
"and",
"starts",
"interactive",
"shell"
] | 314fcc13ed4ddbe80f8af3b6fb44712ff3aee12d | https://github.com/Codeception/CodeceptJS/blob/314fcc13ed4ddbe80f8af3b6fb44712ff3aee12d/lib/pause.js#L19-L29 |
|
6,228 | Codeception/CodeceptJS | lib/colorUtils.js | convertColorToRGBA | function convertColorToRGBA(color) {
const cstr = `${color}`.toLowerCase().trim() || '';
if (!/^rgba?\(.+?\)$/.test(cstr)) {
// Convert both color names and hex colors to rgba
const hexColor = convertColorNameToHex(color);
return convertHexColorToRgba(hexColor);
}
// Convert rgb to rgba
const channels = cstr.match(/([\-0-9.]+)/g) || [];
switch (channels.length) {
case 3:
// Convert rgb to rgba
return `rgba(${channels.join(', ')}, 1)`;
case 4:
// Format rgba
return `rgba(${channels.join(', ')})`;
default:
// Unexpected color format. Leave it untouched (let the user handle it)
return color;
}
} | javascript | function convertColorToRGBA(color) {
const cstr = `${color}`.toLowerCase().trim() || '';
if (!/^rgba?\(.+?\)$/.test(cstr)) {
// Convert both color names and hex colors to rgba
const hexColor = convertColorNameToHex(color);
return convertHexColorToRgba(hexColor);
}
// Convert rgb to rgba
const channels = cstr.match(/([\-0-9.]+)/g) || [];
switch (channels.length) {
case 3:
// Convert rgb to rgba
return `rgba(${channels.join(', ')}, 1)`;
case 4:
// Format rgba
return `rgba(${channels.join(', ')})`;
default:
// Unexpected color format. Leave it untouched (let the user handle it)
return color;
}
} | [
"function",
"convertColorToRGBA",
"(",
"color",
")",
"{",
"const",
"cstr",
"=",
"`",
"${",
"color",
"}",
"`",
".",
"toLowerCase",
"(",
")",
".",
"trim",
"(",
")",
"||",
"''",
";",
"if",
"(",
"!",
"/",
"^rgba?\\(.+?\\)$",
"/",
".",
"test",
"(",
"cstr",
")",
")",
"{",
"// Convert both color names and hex colors to rgba",
"const",
"hexColor",
"=",
"convertColorNameToHex",
"(",
"color",
")",
";",
"return",
"convertHexColorToRgba",
"(",
"hexColor",
")",
";",
"}",
"// Convert rgb to rgba",
"const",
"channels",
"=",
"cstr",
".",
"match",
"(",
"/",
"([\\-0-9.]+)",
"/",
"g",
")",
"||",
"[",
"]",
";",
"switch",
"(",
"channels",
".",
"length",
")",
"{",
"case",
"3",
":",
"// Convert rgb to rgba",
"return",
"`",
"${",
"channels",
".",
"join",
"(",
"', '",
")",
"}",
"`",
";",
"case",
"4",
":",
"// Format rgba",
"return",
"`",
"${",
"channels",
".",
"join",
"(",
"', '",
")",
"}",
"`",
";",
"default",
":",
"// Unexpected color format. Leave it untouched (let the user handle it)",
"return",
"color",
";",
"}",
"}"
] | Convert a colour to a normalised RGBA format
Required due to the different color formats
returned by different web drivers.
Examples:
rgb(85,0,0) => rgba(85, 0, 0, 1)
@param {string} color Color as a string, i.e. rgb(85,0,0) | [
"Convert",
"a",
"colour",
"to",
"a",
"normalised",
"RGBA",
"format",
"Required",
"due",
"to",
"the",
"different",
"color",
"formats",
"returned",
"by",
"different",
"web",
"drivers",
"."
] | 314fcc13ed4ddbe80f8af3b6fb44712ff3aee12d | https://github.com/Codeception/CodeceptJS/blob/314fcc13ed4ddbe80f8af3b6fb44712ff3aee12d/lib/colorUtils.js#L194-L219 |
6,229 | Codeception/CodeceptJS | lib/command/run-multiple.js | replaceValue | function replaceValue(obj, key, value) {
if (!obj) return;
if (obj instanceof Array) {
for (const i in obj) {
replaceValue(obj[i], key, value);
}
}
if (obj[key]) obj[key] = value;
if (typeof obj === 'object' && obj !== null) {
const children = Object.keys(obj);
for (let childIndex = 0; childIndex < children.length; childIndex++) {
replaceValue(obj[children[childIndex]], key, value);
}
}
return obj;
} | javascript | function replaceValue(obj, key, value) {
if (!obj) return;
if (obj instanceof Array) {
for (const i in obj) {
replaceValue(obj[i], key, value);
}
}
if (obj[key]) obj[key] = value;
if (typeof obj === 'object' && obj !== null) {
const children = Object.keys(obj);
for (let childIndex = 0; childIndex < children.length; childIndex++) {
replaceValue(obj[children[childIndex]], key, value);
}
}
return obj;
} | [
"function",
"replaceValue",
"(",
"obj",
",",
"key",
",",
"value",
")",
"{",
"if",
"(",
"!",
"obj",
")",
"return",
";",
"if",
"(",
"obj",
"instanceof",
"Array",
")",
"{",
"for",
"(",
"const",
"i",
"in",
"obj",
")",
"{",
"replaceValue",
"(",
"obj",
"[",
"i",
"]",
",",
"key",
",",
"value",
")",
";",
"}",
"}",
"if",
"(",
"obj",
"[",
"key",
"]",
")",
"obj",
"[",
"key",
"]",
"=",
"value",
";",
"if",
"(",
"typeof",
"obj",
"===",
"'object'",
"&&",
"obj",
"!==",
"null",
")",
"{",
"const",
"children",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"for",
"(",
"let",
"childIndex",
"=",
"0",
";",
"childIndex",
"<",
"children",
".",
"length",
";",
"childIndex",
"++",
")",
"{",
"replaceValue",
"(",
"obj",
"[",
"children",
"[",
"childIndex",
"]",
"]",
",",
"key",
",",
"value",
")",
";",
"}",
"}",
"return",
"obj",
";",
"}"
] | search key in object recursive and replace value in it | [
"search",
"key",
"in",
"object",
"recursive",
"and",
"replace",
"value",
"in",
"it"
] | 314fcc13ed4ddbe80f8af3b6fb44712ff3aee12d | https://github.com/Codeception/CodeceptJS/blob/314fcc13ed4ddbe80f8af3b6fb44712ff3aee12d/lib/command/run-multiple.js#L186-L201 |
6,230 | Codeception/CodeceptJS | lib/assert/error.js | AssertionFailedError | function AssertionFailedError(params, template) {
this.params = params;
this.template = template;
// this.message = "AssertionFailedError";
let stack = new Error().stack;
// this.showDiff = true;
stack = stack ? stack.split('\n').filter(line =>
// @todo cut assert things nicer
line.indexOf('lib/assert') < 0).join('\n') : '';
this.showDiff = true;
this.actual = this.params.actual;
this.expected = this.params.expected;
this.inspect = () => {
const params = this.params || {};
const msg = params.customMessage || '';
return msg + subs(this.template, params);
};
this.cliMessage = () => this.inspect();
} | javascript | function AssertionFailedError(params, template) {
this.params = params;
this.template = template;
// this.message = "AssertionFailedError";
let stack = new Error().stack;
// this.showDiff = true;
stack = stack ? stack.split('\n').filter(line =>
// @todo cut assert things nicer
line.indexOf('lib/assert') < 0).join('\n') : '';
this.showDiff = true;
this.actual = this.params.actual;
this.expected = this.params.expected;
this.inspect = () => {
const params = this.params || {};
const msg = params.customMessage || '';
return msg + subs(this.template, params);
};
this.cliMessage = () => this.inspect();
} | [
"function",
"AssertionFailedError",
"(",
"params",
",",
"template",
")",
"{",
"this",
".",
"params",
"=",
"params",
";",
"this",
".",
"template",
"=",
"template",
";",
"// this.message = \"AssertionFailedError\";",
"let",
"stack",
"=",
"new",
"Error",
"(",
")",
".",
"stack",
";",
"// this.showDiff = true;",
"stack",
"=",
"stack",
"?",
"stack",
".",
"split",
"(",
"'\\n'",
")",
".",
"filter",
"(",
"line",
"=>",
"// @todo cut assert things nicer",
"line",
".",
"indexOf",
"(",
"'lib/assert'",
")",
"<",
"0",
")",
".",
"join",
"(",
"'\\n'",
")",
":",
"''",
";",
"this",
".",
"showDiff",
"=",
"true",
";",
"this",
".",
"actual",
"=",
"this",
".",
"params",
".",
"actual",
";",
"this",
".",
"expected",
"=",
"this",
".",
"params",
".",
"expected",
";",
"this",
".",
"inspect",
"=",
"(",
")",
"=>",
"{",
"const",
"params",
"=",
"this",
".",
"params",
"||",
"{",
"}",
";",
"const",
"msg",
"=",
"params",
".",
"customMessage",
"||",
"''",
";",
"return",
"msg",
"+",
"subs",
"(",
"this",
".",
"template",
",",
"params",
")",
";",
"}",
";",
"this",
".",
"cliMessage",
"=",
"(",
")",
"=>",
"this",
".",
"inspect",
"(",
")",
";",
"}"
] | Assertion errors, can provide a detailed error messages.
inspect() and cliMessage() added to display errors with params. | [
"Assertion",
"errors",
"can",
"provide",
"a",
"detailed",
"error",
"messages",
"."
] | 314fcc13ed4ddbe80f8af3b6fb44712ff3aee12d | https://github.com/Codeception/CodeceptJS/blob/314fcc13ed4ddbe80f8af3b6fb44712ff3aee12d/lib/assert/error.js#L8-L29 |
6,231 | Codeception/CodeceptJS | lib/helper/Appium.js | onlyForApps | function onlyForApps(expectedPlatform) {
const stack = new Error().stack || '';
const re = /Appium.(\w+)/g;
const caller = stack.split('\n')[2].trim();
const m = re.exec(caller);
if (!m) {
throw new Error(`Invalid caller ${caller}`);
}
const callerName = m[1] || m[2];
if (!expectedPlatform) {
if (!this.platform) {
throw new Error(`${callerName} method can be used only with apps`);
}
} else if (this.platform !== expectedPlatform.toLowerCase()) {
throw new Error(`${callerName} method can be used only with ${expectedPlatform} apps`);
}
} | javascript | function onlyForApps(expectedPlatform) {
const stack = new Error().stack || '';
const re = /Appium.(\w+)/g;
const caller = stack.split('\n')[2].trim();
const m = re.exec(caller);
if (!m) {
throw new Error(`Invalid caller ${caller}`);
}
const callerName = m[1] || m[2];
if (!expectedPlatform) {
if (!this.platform) {
throw new Error(`${callerName} method can be used only with apps`);
}
} else if (this.platform !== expectedPlatform.toLowerCase()) {
throw new Error(`${callerName} method can be used only with ${expectedPlatform} apps`);
}
} | [
"function",
"onlyForApps",
"(",
"expectedPlatform",
")",
"{",
"const",
"stack",
"=",
"new",
"Error",
"(",
")",
".",
"stack",
"||",
"''",
";",
"const",
"re",
"=",
"/",
"Appium.(\\w+)",
"/",
"g",
";",
"const",
"caller",
"=",
"stack",
".",
"split",
"(",
"'\\n'",
")",
"[",
"2",
"]",
".",
"trim",
"(",
")",
";",
"const",
"m",
"=",
"re",
".",
"exec",
"(",
"caller",
")",
";",
"if",
"(",
"!",
"m",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"caller",
"}",
"`",
")",
";",
"}",
"const",
"callerName",
"=",
"m",
"[",
"1",
"]",
"||",
"m",
"[",
"2",
"]",
";",
"if",
"(",
"!",
"expectedPlatform",
")",
"{",
"if",
"(",
"!",
"this",
".",
"platform",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"callerName",
"}",
"`",
")",
";",
"}",
"}",
"else",
"if",
"(",
"this",
".",
"platform",
"!==",
"expectedPlatform",
".",
"toLowerCase",
"(",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"callerName",
"}",
"${",
"expectedPlatform",
"}",
"`",
")",
";",
"}",
"}"
] | in the end of a file | [
"in",
"the",
"end",
"of",
"a",
"file"
] | 314fcc13ed4ddbe80f8af3b6fb44712ff3aee12d | https://github.com/Codeception/CodeceptJS/blob/314fcc13ed4ddbe80f8af3b6fb44712ff3aee12d/lib/helper/Appium.js#L1433-L1451 |
6,232 | kangax/html-minifier | benchmark.js | function(done) {
gzip(info.filePath, info.gzFilePath, function() {
info.gzTime = Date.now();
// Open and read the size of the minified+gzip output
readSize(info.gzFilePath, function(size) {
info.gzSize = size;
done();
});
});
} | javascript | function(done) {
gzip(info.filePath, info.gzFilePath, function() {
info.gzTime = Date.now();
// Open and read the size of the minified+gzip output
readSize(info.gzFilePath, function(size) {
info.gzSize = size;
done();
});
});
} | [
"function",
"(",
"done",
")",
"{",
"gzip",
"(",
"info",
".",
"filePath",
",",
"info",
".",
"gzFilePath",
",",
"function",
"(",
")",
"{",
"info",
".",
"gzTime",
"=",
"Date",
".",
"now",
"(",
")",
";",
"// Open and read the size of the minified+gzip output",
"readSize",
"(",
"info",
".",
"gzFilePath",
",",
"function",
"(",
"size",
")",
"{",
"info",
".",
"gzSize",
"=",
"size",
";",
"done",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Apply Gzip on minified output | [
"Apply",
"Gzip",
"on",
"minified",
"output"
] | 51ce10f4daedb1de483ffbcccecc41be1c873da2 | https://github.com/kangax/html-minifier/blob/51ce10f4daedb1de483ffbcccecc41be1c873da2/benchmark.js#L226-L235 |
|
6,233 | kangax/html-minifier | benchmark.js | function(done) {
readBuffer(info.filePath, function(data) {
lzma.compress(data, 1, function(result, error) {
if (error) {
throw error;
}
writeBuffer(info.lzFilePath, new Buffer(result), function() {
info.lzTime = Date.now();
// Open and read the size of the minified+lzma output
readSize(info.lzFilePath, function(size) {
info.lzSize = size;
done();
});
});
});
});
} | javascript | function(done) {
readBuffer(info.filePath, function(data) {
lzma.compress(data, 1, function(result, error) {
if (error) {
throw error;
}
writeBuffer(info.lzFilePath, new Buffer(result), function() {
info.lzTime = Date.now();
// Open and read the size of the minified+lzma output
readSize(info.lzFilePath, function(size) {
info.lzSize = size;
done();
});
});
});
});
} | [
"function",
"(",
"done",
")",
"{",
"readBuffer",
"(",
"info",
".",
"filePath",
",",
"function",
"(",
"data",
")",
"{",
"lzma",
".",
"compress",
"(",
"data",
",",
"1",
",",
"function",
"(",
"result",
",",
"error",
")",
"{",
"if",
"(",
"error",
")",
"{",
"throw",
"error",
";",
"}",
"writeBuffer",
"(",
"info",
".",
"lzFilePath",
",",
"new",
"Buffer",
"(",
"result",
")",
",",
"function",
"(",
")",
"{",
"info",
".",
"lzTime",
"=",
"Date",
".",
"now",
"(",
")",
";",
"// Open and read the size of the minified+lzma output",
"readSize",
"(",
"info",
".",
"lzFilePath",
",",
"function",
"(",
"size",
")",
"{",
"info",
".",
"lzSize",
"=",
"size",
";",
"done",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] | Apply LZMA on minified output | [
"Apply",
"LZMA",
"on",
"minified",
"output"
] | 51ce10f4daedb1de483ffbcccecc41be1c873da2 | https://github.com/kangax/html-minifier/blob/51ce10f4daedb1de483ffbcccecc41be1c873da2/benchmark.js#L237-L253 |
|
6,234 | kangax/html-minifier | src/htmlminifier.js | trimTrailingWhitespace | function trimTrailingWhitespace(index, nextTag) {
for (var endTag = null; index >= 0 && _canTrimWhitespace(endTag); index--) {
var str = buffer[index];
var match = str.match(/^<\/([\w:-]+)>$/);
if (match) {
endTag = match[1];
}
else if (/>$/.test(str) || (buffer[index] = collapseWhitespaceSmart(str, null, nextTag, options))) {
break;
}
}
} | javascript | function trimTrailingWhitespace(index, nextTag) {
for (var endTag = null; index >= 0 && _canTrimWhitespace(endTag); index--) {
var str = buffer[index];
var match = str.match(/^<\/([\w:-]+)>$/);
if (match) {
endTag = match[1];
}
else if (/>$/.test(str) || (buffer[index] = collapseWhitespaceSmart(str, null, nextTag, options))) {
break;
}
}
} | [
"function",
"trimTrailingWhitespace",
"(",
"index",
",",
"nextTag",
")",
"{",
"for",
"(",
"var",
"endTag",
"=",
"null",
";",
"index",
">=",
"0",
"&&",
"_canTrimWhitespace",
"(",
"endTag",
")",
";",
"index",
"--",
")",
"{",
"var",
"str",
"=",
"buffer",
"[",
"index",
"]",
";",
"var",
"match",
"=",
"str",
".",
"match",
"(",
"/",
"^<\\/([\\w:-]+)>$",
"/",
")",
";",
"if",
"(",
"match",
")",
"{",
"endTag",
"=",
"match",
"[",
"1",
"]",
";",
"}",
"else",
"if",
"(",
"/",
">$",
"/",
".",
"test",
"(",
"str",
")",
"||",
"(",
"buffer",
"[",
"index",
"]",
"=",
"collapseWhitespaceSmart",
"(",
"str",
",",
"null",
",",
"nextTag",
",",
"options",
")",
")",
")",
"{",
"break",
";",
"}",
"}",
"}"
] | look for trailing whitespaces, bypass any inline tags | [
"look",
"for",
"trailing",
"whitespaces",
"bypass",
"any",
"inline",
"tags"
] | 51ce10f4daedb1de483ffbcccecc41be1c873da2 | https://github.com/kangax/html-minifier/blob/51ce10f4daedb1de483ffbcccecc41be1c873da2/src/htmlminifier.js#L953-L964 |
6,235 | kangax/html-minifier | src/htmlminifier.js | squashTrailingWhitespace | function squashTrailingWhitespace(nextTag) {
var charsIndex = buffer.length - 1;
if (buffer.length > 1) {
var item = buffer[buffer.length - 1];
if (/^(?:<!|$)/.test(item) && item.indexOf(uidIgnore) === -1) {
charsIndex--;
}
}
trimTrailingWhitespace(charsIndex, nextTag);
} | javascript | function squashTrailingWhitespace(nextTag) {
var charsIndex = buffer.length - 1;
if (buffer.length > 1) {
var item = buffer[buffer.length - 1];
if (/^(?:<!|$)/.test(item) && item.indexOf(uidIgnore) === -1) {
charsIndex--;
}
}
trimTrailingWhitespace(charsIndex, nextTag);
} | [
"function",
"squashTrailingWhitespace",
"(",
"nextTag",
")",
"{",
"var",
"charsIndex",
"=",
"buffer",
".",
"length",
"-",
"1",
";",
"if",
"(",
"buffer",
".",
"length",
">",
"1",
")",
"{",
"var",
"item",
"=",
"buffer",
"[",
"buffer",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"/",
"^(?:<!|$)",
"/",
".",
"test",
"(",
"item",
")",
"&&",
"item",
".",
"indexOf",
"(",
"uidIgnore",
")",
"===",
"-",
"1",
")",
"{",
"charsIndex",
"--",
";",
"}",
"}",
"trimTrailingWhitespace",
"(",
"charsIndex",
",",
"nextTag",
")",
";",
"}"
] | look for trailing whitespaces from previously processed text which may not be trimmed due to a following comment or an empty element which has now been removed | [
"look",
"for",
"trailing",
"whitespaces",
"from",
"previously",
"processed",
"text",
"which",
"may",
"not",
"be",
"trimmed",
"due",
"to",
"a",
"following",
"comment",
"or",
"an",
"empty",
"element",
"which",
"has",
"now",
"been",
"removed"
] | 51ce10f4daedb1de483ffbcccecc41be1c873da2 | https://github.com/kangax/html-minifier/blob/51ce10f4daedb1de483ffbcccecc41be1c873da2/src/htmlminifier.js#L969-L978 |
6,236 | developit/preact-cli | packages/cli/lib/lib/webpack/run-webpack.js | stripLoaderPrefix | function stripLoaderPrefix(str) {
if (typeof str === 'string') {
str = str.replace(
/(?:(\()|(^|\b|@))(\.\/~|\.{0,2}\/(?:[^\s]+\/)?node_modules)\/\w+-loader(\/[^?!]+)?(\?\?[\w_.-]+|\?({[\s\S]*?})?)?!/g,
'$1'
);
str = str.replace(/(\.?\.?(?:\/[^/ ]+)+)\s+\(\1\)/g, '$1');
str = replaceAll(str, process.cwd(), '.');
return str;
}
return str;
} | javascript | function stripLoaderPrefix(str) {
if (typeof str === 'string') {
str = str.replace(
/(?:(\()|(^|\b|@))(\.\/~|\.{0,2}\/(?:[^\s]+\/)?node_modules)\/\w+-loader(\/[^?!]+)?(\?\?[\w_.-]+|\?({[\s\S]*?})?)?!/g,
'$1'
);
str = str.replace(/(\.?\.?(?:\/[^/ ]+)+)\s+\(\1\)/g, '$1');
str = replaceAll(str, process.cwd(), '.');
return str;
}
return str;
} | [
"function",
"stripLoaderPrefix",
"(",
"str",
")",
"{",
"if",
"(",
"typeof",
"str",
"===",
"'string'",
")",
"{",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"(?:(\\()|(^|\\b|@))(\\.\\/~|\\.{0,2}\\/(?:[^\\s]+\\/)?node_modules)\\/\\w+-loader(\\/[^?!]+)?(\\?\\?[\\w_.-]+|\\?({[\\s\\S]*?})?)?!",
"/",
"g",
",",
"'$1'",
")",
";",
"str",
"=",
"str",
".",
"replace",
"(",
"/",
"(\\.?\\.?(?:\\/[^/ ]+)+)\\s+\\(\\1\\)",
"/",
"g",
",",
"'$1'",
")",
";",
"str",
"=",
"replaceAll",
"(",
"str",
",",
"process",
".",
"cwd",
"(",
")",
",",
"'.'",
")",
";",
"return",
"str",
";",
"}",
"return",
"str",
";",
"}"
] | Removes all loaders from any resource identifiers found in a string | [
"Removes",
"all",
"loaders",
"from",
"any",
"resource",
"identifiers",
"found",
"in",
"a",
"string"
] | a5968ebab794c363883ca71a053d6ce7d75abe06 | https://github.com/developit/preact-cli/blob/a5968ebab794c363883ca71a053d6ce7d75abe06/packages/cli/lib/lib/webpack/run-webpack.js#L199-L210 |
6,237 | cssnano/cssnano | packages/postcss-merge-rules/src/index.js | intersect | function intersect(a, b, not) {
return a.filter((c) => {
const index = ~indexOfDeclaration(b, c);
return not ? !index : index;
});
} | javascript | function intersect(a, b, not) {
return a.filter((c) => {
const index = ~indexOfDeclaration(b, c);
return not ? !index : index;
});
} | [
"function",
"intersect",
"(",
"a",
",",
"b",
",",
"not",
")",
"{",
"return",
"a",
".",
"filter",
"(",
"(",
"c",
")",
"=>",
"{",
"const",
"index",
"=",
"~",
"indexOfDeclaration",
"(",
"b",
",",
"c",
")",
";",
"return",
"not",
"?",
"!",
"index",
":",
"index",
";",
"}",
")",
";",
"}"
] | Returns filtered array of matched or unmatched declarations
@param {postcss.Declaration[]} a
@param {postcss.Declaration[]} b
@param {boolean} [not=false]
@return {postcss.Declaration[]} | [
"Returns",
"filtered",
"array",
"of",
"matched",
"or",
"unmatched",
"declarations"
] | 29bf15a0d83b8e4b799dd07de70e1ef16dcfce74 | https://github.com/cssnano/cssnano/blob/29bf15a0d83b8e4b799dd07de70e1ef16dcfce74/packages/postcss-merge-rules/src/index.js#L37-L42 |
6,238 | cssnano/cssnano | packages/postcss-merge-rules/src/lib/ensureCompatibility.js | isSupportedCached | function isSupportedCached(feature, browsers) {
const key = JSON.stringify({ feature, browsers });
let result = isSupportedCache[key];
if (!result) {
result = isSupported(feature, browsers);
isSupportedCache[key] = result;
}
return result;
} | javascript | function isSupportedCached(feature, browsers) {
const key = JSON.stringify({ feature, browsers });
let result = isSupportedCache[key];
if (!result) {
result = isSupported(feature, browsers);
isSupportedCache[key] = result;
}
return result;
} | [
"function",
"isSupportedCached",
"(",
"feature",
",",
"browsers",
")",
"{",
"const",
"key",
"=",
"JSON",
".",
"stringify",
"(",
"{",
"feature",
",",
"browsers",
"}",
")",
";",
"let",
"result",
"=",
"isSupportedCache",
"[",
"key",
"]",
";",
"if",
"(",
"!",
"result",
")",
"{",
"result",
"=",
"isSupported",
"(",
"feature",
",",
"browsers",
")",
";",
"isSupportedCache",
"[",
"key",
"]",
"=",
"result",
";",
"}",
"return",
"result",
";",
"}"
] | Move to util in future | [
"Move",
"to",
"util",
"in",
"future"
] | 29bf15a0d83b8e4b799dd07de70e1ef16dcfce74 | https://github.com/cssnano/cssnano/blob/29bf15a0d83b8e4b799dd07de70e1ef16dcfce74/packages/postcss-merge-rules/src/lib/ensureCompatibility.js#L66-L76 |
6,239 | cssnano/cssnano | packages/postcss-merge-longhand/src/lib/decl/columns.js | normalize | function normalize(values) {
if (values[0].toLowerCase() === auto) {
return values[1];
}
if (values[1].toLowerCase() === auto) {
return values[0];
}
if (
values[0].toLowerCase() === inherit &&
values[1].toLowerCase() === inherit
) {
return inherit;
}
return values.join(' ');
} | javascript | function normalize(values) {
if (values[0].toLowerCase() === auto) {
return values[1];
}
if (values[1].toLowerCase() === auto) {
return values[0];
}
if (
values[0].toLowerCase() === inherit &&
values[1].toLowerCase() === inherit
) {
return inherit;
}
return values.join(' ');
} | [
"function",
"normalize",
"(",
"values",
")",
"{",
"if",
"(",
"values",
"[",
"0",
"]",
".",
"toLowerCase",
"(",
")",
"===",
"auto",
")",
"{",
"return",
"values",
"[",
"1",
"]",
";",
"}",
"if",
"(",
"values",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
"===",
"auto",
")",
"{",
"return",
"values",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"values",
"[",
"0",
"]",
".",
"toLowerCase",
"(",
")",
"===",
"inherit",
"&&",
"values",
"[",
"1",
"]",
".",
"toLowerCase",
"(",
")",
"===",
"inherit",
")",
"{",
"return",
"inherit",
";",
"}",
"return",
"values",
".",
"join",
"(",
"' '",
")",
";",
"}"
] | Normalize a columns shorthand definition. Both of the longhand
properties' initial values are 'auto', and as per the spec,
omitted values are set to their initial values. Thus, we can
remove any 'auto' definition when there are two values.
Specification link: https://www.w3.org/TR/css3-multicol/ | [
"Normalize",
"a",
"columns",
"shorthand",
"definition",
".",
"Both",
"of",
"the",
"longhand",
"properties",
"initial",
"values",
"are",
"auto",
"and",
"as",
"per",
"the",
"spec",
"omitted",
"values",
"are",
"set",
"to",
"their",
"initial",
"values",
".",
"Thus",
"we",
"can",
"remove",
"any",
"auto",
"definition",
"when",
"there",
"are",
"two",
"values",
"."
] | 29bf15a0d83b8e4b799dd07de70e1ef16dcfce74 | https://github.com/cssnano/cssnano/blob/29bf15a0d83b8e4b799dd07de70e1ef16dcfce74/packages/postcss-merge-longhand/src/lib/decl/columns.js#L26-L43 |
6,240 | cssnano/cssnano | packages/postcss-discard-unused/src/index.js | filterFont | function filterFont({ atRules, values }) {
values = uniqs(values);
atRules.forEach((r) => {
const families = r.nodes.filter(({ prop }) => prop === 'font-family');
// Discard the @font-face if it has no font-family
if (!families.length) {
return r.remove();
}
families.forEach((family) => {
if (!hasFont(family.value.toLowerCase(), values)) {
r.remove();
}
});
});
} | javascript | function filterFont({ atRules, values }) {
values = uniqs(values);
atRules.forEach((r) => {
const families = r.nodes.filter(({ prop }) => prop === 'font-family');
// Discard the @font-face if it has no font-family
if (!families.length) {
return r.remove();
}
families.forEach((family) => {
if (!hasFont(family.value.toLowerCase(), values)) {
r.remove();
}
});
});
} | [
"function",
"filterFont",
"(",
"{",
"atRules",
",",
"values",
"}",
")",
"{",
"values",
"=",
"uniqs",
"(",
"values",
")",
";",
"atRules",
".",
"forEach",
"(",
"(",
"r",
")",
"=>",
"{",
"const",
"families",
"=",
"r",
".",
"nodes",
".",
"filter",
"(",
"(",
"{",
"prop",
"}",
")",
"=>",
"prop",
"===",
"'font-family'",
")",
";",
"// Discard the @font-face if it has no font-family",
"if",
"(",
"!",
"families",
".",
"length",
")",
"{",
"return",
"r",
".",
"remove",
"(",
")",
";",
"}",
"families",
".",
"forEach",
"(",
"(",
"family",
")",
"=>",
"{",
"if",
"(",
"!",
"hasFont",
"(",
"family",
".",
"value",
".",
"toLowerCase",
"(",
")",
",",
"values",
")",
")",
"{",
"r",
".",
"remove",
"(",
")",
";",
"}",
"}",
")",
";",
"}",
")",
";",
"}"
] | fonts have slightly different logic | [
"fonts",
"have",
"slightly",
"different",
"logic"
] | 29bf15a0d83b8e4b799dd07de70e1ef16dcfce74 | https://github.com/cssnano/cssnano/blob/29bf15a0d83b8e4b799dd07de70e1ef16dcfce74/packages/postcss-discard-unused/src/index.js#L48-L64 |
6,241 | jaredhanson/passport | lib/strategies/session.js | SessionStrategy | function SessionStrategy(options, deserializeUser) {
if (typeof options == 'function') {
deserializeUser = options;
options = undefined;
}
options = options || {};
Strategy.call(this);
this.name = 'session';
this._deserializeUser = deserializeUser;
} | javascript | function SessionStrategy(options, deserializeUser) {
if (typeof options == 'function') {
deserializeUser = options;
options = undefined;
}
options = options || {};
Strategy.call(this);
this.name = 'session';
this._deserializeUser = deserializeUser;
} | [
"function",
"SessionStrategy",
"(",
"options",
",",
"deserializeUser",
")",
"{",
"if",
"(",
"typeof",
"options",
"==",
"'function'",
")",
"{",
"deserializeUser",
"=",
"options",
";",
"options",
"=",
"undefined",
";",
"}",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"Strategy",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"name",
"=",
"'session'",
";",
"this",
".",
"_deserializeUser",
"=",
"deserializeUser",
";",
"}"
] | `SessionStrategy` constructor.
@api public | [
"SessionStrategy",
"constructor",
"."
] | 882d65e69d5b56c6b88dd0248891af9e0d80244b | https://github.com/jaredhanson/passport/blob/882d65e69d5b56c6b88dd0248891af9e0d80244b/lib/strategies/session.js#L14-L24 |
6,242 | jaredhanson/passport | lib/authenticator.js | Authenticator | function Authenticator() {
this._key = 'passport';
this._strategies = {};
this._serializers = [];
this._deserializers = [];
this._infoTransformers = [];
this._framework = null;
this._userProperty = 'user';
this.init();
} | javascript | function Authenticator() {
this._key = 'passport';
this._strategies = {};
this._serializers = [];
this._deserializers = [];
this._infoTransformers = [];
this._framework = null;
this._userProperty = 'user';
this.init();
} | [
"function",
"Authenticator",
"(",
")",
"{",
"this",
".",
"_key",
"=",
"'passport'",
";",
"this",
".",
"_strategies",
"=",
"{",
"}",
";",
"this",
".",
"_serializers",
"=",
"[",
"]",
";",
"this",
".",
"_deserializers",
"=",
"[",
"]",
";",
"this",
".",
"_infoTransformers",
"=",
"[",
"]",
";",
"this",
".",
"_framework",
"=",
"null",
";",
"this",
".",
"_userProperty",
"=",
"'user'",
";",
"this",
".",
"init",
"(",
")",
";",
"}"
] | `Authenticator` constructor.
@api public | [
"Authenticator",
"constructor",
"."
] | 882d65e69d5b56c6b88dd0248891af9e0d80244b | https://github.com/jaredhanson/passport/blob/882d65e69d5b56c6b88dd0248891af9e0d80244b/lib/authenticator.js#L13-L23 |
6,243 | Microsoft/botbuilder-tools | packages/LUIS/bin/help.js | getHelpContents | async function getHelpContents(args, output) {
if ('!' in args) {
return getAllCommands(process.stdout);
}
if (args._.length == 0) {
return getGeneralHelpContents(output);
}
else if (args._.length == 1) {
return getVerbHelp(args._[0], output);
} else if (args._.length >= 2) {
const operation = getOperation(args._[0], args._[1]);
if (operation) {
output.write(`${operation.description}\n\n`);
output.write(`Usage:\n${chalk.cyan.bold(operation.command)}\n\n`);
return getHelpContentsForOperation(operation, output);
} else {
return getVerbHelp(args._[0], output);
}
}
return getGeneralHelpContents(output);
} | javascript | async function getHelpContents(args, output) {
if ('!' in args) {
return getAllCommands(process.stdout);
}
if (args._.length == 0) {
return getGeneralHelpContents(output);
}
else if (args._.length == 1) {
return getVerbHelp(args._[0], output);
} else if (args._.length >= 2) {
const operation = getOperation(args._[0], args._[1]);
if (operation) {
output.write(`${operation.description}\n\n`);
output.write(`Usage:\n${chalk.cyan.bold(operation.command)}\n\n`);
return getHelpContentsForOperation(operation, output);
} else {
return getVerbHelp(args._[0], output);
}
}
return getGeneralHelpContents(output);
} | [
"async",
"function",
"getHelpContents",
"(",
"args",
",",
"output",
")",
"{",
"if",
"(",
"'!'",
"in",
"args",
")",
"{",
"return",
"getAllCommands",
"(",
"process",
".",
"stdout",
")",
";",
"}",
"if",
"(",
"args",
".",
"_",
".",
"length",
"==",
"0",
")",
"{",
"return",
"getGeneralHelpContents",
"(",
"output",
")",
";",
"}",
"else",
"if",
"(",
"args",
".",
"_",
".",
"length",
"==",
"1",
")",
"{",
"return",
"getVerbHelp",
"(",
"args",
".",
"_",
"[",
"0",
"]",
",",
"output",
")",
";",
"}",
"else",
"if",
"(",
"args",
".",
"_",
".",
"length",
">=",
"2",
")",
"{",
"const",
"operation",
"=",
"getOperation",
"(",
"args",
".",
"_",
"[",
"0",
"]",
",",
"args",
".",
"_",
"[",
"1",
"]",
")",
";",
"if",
"(",
"operation",
")",
"{",
"output",
".",
"write",
"(",
"`",
"${",
"operation",
".",
"description",
"}",
"\\n",
"\\n",
"`",
")",
";",
"output",
".",
"write",
"(",
"`",
"\\n",
"${",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"operation",
".",
"command",
")",
"}",
"\\n",
"\\n",
"`",
")",
";",
"return",
"getHelpContentsForOperation",
"(",
"operation",
",",
"output",
")",
";",
"}",
"else",
"{",
"return",
"getVerbHelp",
"(",
"args",
".",
"_",
"[",
"0",
"]",
",",
"output",
")",
";",
"}",
"}",
"return",
"getGeneralHelpContents",
"(",
"output",
")",
";",
"}"
] | Retrieves help content vie the luis.json from
the arguments input by the user.
@param args The arguments input by the user
@returns {Promise<*>}1] | [
"Retrieves",
"help",
"content",
"vie",
"the",
"luis",
".",
"json",
"from",
"the",
"arguments",
"input",
"by",
"the",
"user",
"."
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/LUIS/bin/help.js#L78-L100 |
6,244 | Microsoft/botbuilder-tools | packages/LUIS/bin/help.js | getGeneralHelpContents | function getGeneralHelpContents() {
let options = {
head: chalk.bold(`Available actions are:`),
table: [
[chalk.cyan.bold("add"), "add a resource"],
[chalk.cyan.bold("clone"), "clone a resource"],
[chalk.cyan.bold("delete"), "delete a resource"],
[chalk.cyan.bold("export"), "export resources"],
[chalk.cyan.bold("package"), "package resources"],
[chalk.cyan.bold("get"), "get a resource"],
[chalk.cyan.bold("import"), "import resources"],
[chalk.cyan.bold('init'), 'Initializes the .luisrc file with settings specific to your LUIS instance'],
[chalk.cyan.bold("list"), "list resources"],
[chalk.cyan.bold("publish"), "publish resource"],
[chalk.cyan.bold("query"), "query model for prediction"],
[chalk.cyan.bold("rename"), "change the name of a resource"],
[chalk.cyan.bold("set"), "change the .luisrc settings"],
[chalk.cyan.bold("suggest"), "suggest resources"],
[chalk.cyan.bold("train"), "train resource"],
[chalk.cyan.bold("update"), "update resources"]
]
};
let sections = [];
sections.push(options);
sections.push(configSection);
sections.push(globalArgs);
return sections;
} | javascript | function getGeneralHelpContents() {
let options = {
head: chalk.bold(`Available actions are:`),
table: [
[chalk.cyan.bold("add"), "add a resource"],
[chalk.cyan.bold("clone"), "clone a resource"],
[chalk.cyan.bold("delete"), "delete a resource"],
[chalk.cyan.bold("export"), "export resources"],
[chalk.cyan.bold("package"), "package resources"],
[chalk.cyan.bold("get"), "get a resource"],
[chalk.cyan.bold("import"), "import resources"],
[chalk.cyan.bold('init'), 'Initializes the .luisrc file with settings specific to your LUIS instance'],
[chalk.cyan.bold("list"), "list resources"],
[chalk.cyan.bold("publish"), "publish resource"],
[chalk.cyan.bold("query"), "query model for prediction"],
[chalk.cyan.bold("rename"), "change the name of a resource"],
[chalk.cyan.bold("set"), "change the .luisrc settings"],
[chalk.cyan.bold("suggest"), "suggest resources"],
[chalk.cyan.bold("train"), "train resource"],
[chalk.cyan.bold("update"), "update resources"]
]
};
let sections = [];
sections.push(options);
sections.push(configSection);
sections.push(globalArgs);
return sections;
} | [
"function",
"getGeneralHelpContents",
"(",
")",
"{",
"let",
"options",
"=",
"{",
"head",
":",
"chalk",
".",
"bold",
"(",
"`",
"`",
")",
",",
"table",
":",
"[",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"add\"",
")",
",",
"\"add a resource\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"clone\"",
")",
",",
"\"clone a resource\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"delete\"",
")",
",",
"\"delete a resource\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"export\"",
")",
",",
"\"export resources\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"package\"",
")",
",",
"\"package resources\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"get\"",
")",
",",
"\"get a resource\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"import\"",
")",
",",
"\"import resources\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"'init'",
")",
",",
"'Initializes the .luisrc file with settings specific to your LUIS instance'",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"list\"",
")",
",",
"\"list resources\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"publish\"",
")",
",",
"\"publish resource\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"query\"",
")",
",",
"\"query model for prediction\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"rename\"",
")",
",",
"\"change the name of a resource\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"set\"",
")",
",",
"\"change the .luisrc settings\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"suggest\"",
")",
",",
"\"suggest resources\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"train\"",
")",
",",
"\"train resource\"",
"]",
",",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"\"update\"",
")",
",",
"\"update resources\"",
"]",
"]",
"}",
";",
"let",
"sections",
"=",
"[",
"]",
";",
"sections",
".",
"push",
"(",
"options",
")",
";",
"sections",
".",
"push",
"(",
"configSection",
")",
";",
"sections",
".",
"push",
"(",
"globalArgs",
")",
";",
"return",
"sections",
";",
"}"
] | General help contents
@returns {*[]} | [
"General",
"help",
"contents"
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/LUIS/bin/help.js#L133-L161 |
6,245 | Microsoft/botbuilder-tools | packages/LUIS/bin/help.js | getAllCommands | function getAllCommands() {
let resourceTypes = [];
let tables = {};
operations.forEach((operation) => {
let opCategory = operation.target[0];
if (resourceTypes.indexOf(opCategory) < 0) {
resourceTypes.push(opCategory);
tables[opCategory] = [];
}
tables[opCategory].push([chalk.cyan.bold(operation.command), operation.description]);
});
resourceTypes.sort();
let sections = [];
for (let resourceType of resourceTypes) {
tables[resourceType].sort((a, b) => a[0].localeCompare(b[0]));
sections.push({
head: chalk.white.bold(resourceType),
table: tables[resourceType]
});
}
return sections;
} | javascript | function getAllCommands() {
let resourceTypes = [];
let tables = {};
operations.forEach((operation) => {
let opCategory = operation.target[0];
if (resourceTypes.indexOf(opCategory) < 0) {
resourceTypes.push(opCategory);
tables[opCategory] = [];
}
tables[opCategory].push([chalk.cyan.bold(operation.command), operation.description]);
});
resourceTypes.sort();
let sections = [];
for (let resourceType of resourceTypes) {
tables[resourceType].sort((a, b) => a[0].localeCompare(b[0]));
sections.push({
head: chalk.white.bold(resourceType),
table: tables[resourceType]
});
}
return sections;
} | [
"function",
"getAllCommands",
"(",
")",
"{",
"let",
"resourceTypes",
"=",
"[",
"]",
";",
"let",
"tables",
"=",
"{",
"}",
";",
"operations",
".",
"forEach",
"(",
"(",
"operation",
")",
"=>",
"{",
"let",
"opCategory",
"=",
"operation",
".",
"target",
"[",
"0",
"]",
";",
"if",
"(",
"resourceTypes",
".",
"indexOf",
"(",
"opCategory",
")",
"<",
"0",
")",
"{",
"resourceTypes",
".",
"push",
"(",
"opCategory",
")",
";",
"tables",
"[",
"opCategory",
"]",
"=",
"[",
"]",
";",
"}",
"tables",
"[",
"opCategory",
"]",
".",
"push",
"(",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"operation",
".",
"command",
")",
",",
"operation",
".",
"description",
"]",
")",
";",
"}",
")",
";",
"resourceTypes",
".",
"sort",
"(",
")",
";",
"let",
"sections",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"resourceType",
"of",
"resourceTypes",
")",
"{",
"tables",
"[",
"resourceType",
"]",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"a",
"[",
"0",
"]",
".",
"localeCompare",
"(",
"b",
"[",
"0",
"]",
")",
")",
";",
"sections",
".",
"push",
"(",
"{",
"head",
":",
"chalk",
".",
"white",
".",
"bold",
"(",
"resourceType",
")",
",",
"table",
":",
"tables",
"[",
"resourceType",
"]",
"}",
")",
";",
"}",
"return",
"sections",
";",
"}"
] | Walks the luis.json and pulls out all
commands that are supported.
@returns {*[]} | [
"Walks",
"the",
"luis",
".",
"json",
"and",
"pulls",
"out",
"all",
"commands",
"that",
"are",
"supported",
"."
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/LUIS/bin/help.js#L239-L263 |
6,246 | Microsoft/botbuilder-tools | packages/LUIS/bin/luis.js | getFileInput | async function getFileInput(args) {
if (typeof args.in !== 'string') {
return null;
}
// Let any errors fall through to the runProgram() promise
return JSON.parse(await txtfile.read(path.resolve(args.in)));
} | javascript | async function getFileInput(args) {
if (typeof args.in !== 'string') {
return null;
}
// Let any errors fall through to the runProgram() promise
return JSON.parse(await txtfile.read(path.resolve(args.in)));
} | [
"async",
"function",
"getFileInput",
"(",
"args",
")",
"{",
"if",
"(",
"typeof",
"args",
".",
"in",
"!==",
"'string'",
")",
"{",
"return",
"null",
";",
"}",
"// Let any errors fall through to the runProgram() promise",
"return",
"JSON",
".",
"parse",
"(",
"await",
"txtfile",
".",
"read",
"(",
"path",
".",
"resolve",
"(",
"args",
".",
"in",
")",
")",
")",
";",
"}"
] | Retrieves the input file to send as
the body of the request.
@param args
@returns {Promise<*>} | [
"Retrieves",
"the",
"input",
"file",
"to",
"send",
"as",
"the",
"body",
"of",
"the",
"request",
"."
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/LUIS/bin/luis.js#L898-L904 |
6,247 | Microsoft/botbuilder-tools | packages/LUIS/bin/luis.js | composeConfig | async function composeConfig() {
const { LUIS_APP_ID, LUIS_AUTHORING_KEY, LUIS_VERSION_ID, LUIS_REGION } = process.env;
const {
appId: args_appId,
authoringKey: args_authoringKey,
versionId: args_versionId,
region: args_region
} = args;
let luisrcJson = {};
let config;
try {
await fs.access(path.join(process.cwd(), '.luisrc'), fs.R_OK);
luisrcJson = JSON.parse(await txtfile.read(path.join(process.cwd(), '.luisrc')));
} catch (e) {
// Do nothing
} finally {
config = {
appId: (args_appId || luisrcJson.appId || LUIS_APP_ID),
authoringKey: (args_authoringKey || luisrcJson.authoringKey || LUIS_AUTHORING_KEY),
versionId: (args_versionId || luisrcJson.versionId || LUIS_VERSION_ID),
region: (args_region || luisrcJson.region || LUIS_REGION)
};
}
return config;
} | javascript | async function composeConfig() {
const { LUIS_APP_ID, LUIS_AUTHORING_KEY, LUIS_VERSION_ID, LUIS_REGION } = process.env;
const {
appId: args_appId,
authoringKey: args_authoringKey,
versionId: args_versionId,
region: args_region
} = args;
let luisrcJson = {};
let config;
try {
await fs.access(path.join(process.cwd(), '.luisrc'), fs.R_OK);
luisrcJson = JSON.parse(await txtfile.read(path.join(process.cwd(), '.luisrc')));
} catch (e) {
// Do nothing
} finally {
config = {
appId: (args_appId || luisrcJson.appId || LUIS_APP_ID),
authoringKey: (args_authoringKey || luisrcJson.authoringKey || LUIS_AUTHORING_KEY),
versionId: (args_versionId || luisrcJson.versionId || LUIS_VERSION_ID),
region: (args_region || luisrcJson.region || LUIS_REGION)
};
}
return config;
} | [
"async",
"function",
"composeConfig",
"(",
")",
"{",
"const",
"{",
"LUIS_APP_ID",
",",
"LUIS_AUTHORING_KEY",
",",
"LUIS_VERSION_ID",
",",
"LUIS_REGION",
"}",
"=",
"process",
".",
"env",
";",
"const",
"{",
"appId",
":",
"args_appId",
",",
"authoringKey",
":",
"args_authoringKey",
",",
"versionId",
":",
"args_versionId",
",",
"region",
":",
"args_region",
"}",
"=",
"args",
";",
"let",
"luisrcJson",
"=",
"{",
"}",
";",
"let",
"config",
";",
"try",
"{",
"await",
"fs",
".",
"access",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'.luisrc'",
")",
",",
"fs",
".",
"R_OK",
")",
";",
"luisrcJson",
"=",
"JSON",
".",
"parse",
"(",
"await",
"txtfile",
".",
"read",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'.luisrc'",
")",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// Do nothing",
"}",
"finally",
"{",
"config",
"=",
"{",
"appId",
":",
"(",
"args_appId",
"||",
"luisrcJson",
".",
"appId",
"||",
"LUIS_APP_ID",
")",
",",
"authoringKey",
":",
"(",
"args_authoringKey",
"||",
"luisrcJson",
".",
"authoringKey",
"||",
"LUIS_AUTHORING_KEY",
")",
",",
"versionId",
":",
"(",
"args_versionId",
"||",
"luisrcJson",
".",
"versionId",
"||",
"LUIS_VERSION_ID",
")",
",",
"region",
":",
"(",
"args_region",
"||",
"luisrcJson",
".",
"region",
"||",
"LUIS_REGION",
")",
"}",
";",
"}",
"return",
"config",
";",
"}"
] | Composes the config from the 3 sources that it may reside.
Precedence is 1. Arguments, 2. luisrc and 3. env variables
@returns {Promise<*>} | [
"Composes",
"the",
"config",
"from",
"the",
"3",
"sources",
"that",
"it",
"may",
"reside",
".",
"Precedence",
"is",
"1",
".",
"Arguments",
"2",
".",
"luisrc",
"and",
"3",
".",
"env",
"variables"
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/LUIS/bin/luis.js#L912-L938 |
6,248 | Microsoft/botbuilder-tools | packages/QnAMaker/bin/qnamaker.js | composeConfig | async function composeConfig() {
const {QNAMAKER_SUBSCRIPTION_KEY, QNAMAKER_HOSTNAME, QNAMAKER_ENDPOINTKEY, QNAMAKER_KBID} = process.env;
const {subscriptionKey, hostname, endpointKey, kbId} = args;
let qnamakerrcJson = {};
let config;
try {
await fs.access(path.join(process.cwd(), '.qnamakerrc'), fs.R_OK);
qnamakerrcJson = JSON.parse(await txtfile.read(path.join(process.cwd(), '.qnamakerrc')));
} catch (e) {
// Do nothing
} finally {
config = {
subscriptionKey: (subscriptionKey || qnamakerrcJson.subscriptionKey || QNAMAKER_SUBSCRIPTION_KEY),
hostname: (hostname || qnamakerrcJson.hostname || QNAMAKER_HOSTNAME),
endpointKey: (endpointKey || qnamakerrcJson.endpointKey || QNAMAKER_ENDPOINTKEY),
kbId: (kbId || qnamakerrcJson.kbId || QNAMAKER_KBID)
};
}
return config;
} | javascript | async function composeConfig() {
const {QNAMAKER_SUBSCRIPTION_KEY, QNAMAKER_HOSTNAME, QNAMAKER_ENDPOINTKEY, QNAMAKER_KBID} = process.env;
const {subscriptionKey, hostname, endpointKey, kbId} = args;
let qnamakerrcJson = {};
let config;
try {
await fs.access(path.join(process.cwd(), '.qnamakerrc'), fs.R_OK);
qnamakerrcJson = JSON.parse(await txtfile.read(path.join(process.cwd(), '.qnamakerrc')));
} catch (e) {
// Do nothing
} finally {
config = {
subscriptionKey: (subscriptionKey || qnamakerrcJson.subscriptionKey || QNAMAKER_SUBSCRIPTION_KEY),
hostname: (hostname || qnamakerrcJson.hostname || QNAMAKER_HOSTNAME),
endpointKey: (endpointKey || qnamakerrcJson.endpointKey || QNAMAKER_ENDPOINTKEY),
kbId: (kbId || qnamakerrcJson.kbId || QNAMAKER_KBID)
};
}
return config;
} | [
"async",
"function",
"composeConfig",
"(",
")",
"{",
"const",
"{",
"QNAMAKER_SUBSCRIPTION_KEY",
",",
"QNAMAKER_HOSTNAME",
",",
"QNAMAKER_ENDPOINTKEY",
",",
"QNAMAKER_KBID",
"}",
"=",
"process",
".",
"env",
";",
"const",
"{",
"subscriptionKey",
",",
"hostname",
",",
"endpointKey",
",",
"kbId",
"}",
"=",
"args",
";",
"let",
"qnamakerrcJson",
"=",
"{",
"}",
";",
"let",
"config",
";",
"try",
"{",
"await",
"fs",
".",
"access",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'.qnamakerrc'",
")",
",",
"fs",
".",
"R_OK",
")",
";",
"qnamakerrcJson",
"=",
"JSON",
".",
"parse",
"(",
"await",
"txtfile",
".",
"read",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'.qnamakerrc'",
")",
")",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"// Do nothing",
"}",
"finally",
"{",
"config",
"=",
"{",
"subscriptionKey",
":",
"(",
"subscriptionKey",
"||",
"qnamakerrcJson",
".",
"subscriptionKey",
"||",
"QNAMAKER_SUBSCRIPTION_KEY",
")",
",",
"hostname",
":",
"(",
"hostname",
"||",
"qnamakerrcJson",
".",
"hostname",
"||",
"QNAMAKER_HOSTNAME",
")",
",",
"endpointKey",
":",
"(",
"endpointKey",
"||",
"qnamakerrcJson",
".",
"endpointKey",
"||",
"QNAMAKER_ENDPOINTKEY",
")",
",",
"kbId",
":",
"(",
"kbId",
"||",
"qnamakerrcJson",
".",
"kbId",
"||",
"QNAMAKER_KBID",
")",
"}",
";",
"}",
"return",
"config",
";",
"}"
] | Composes the config from the 3 sources that it may reside.
Precedence is 1. Arguments, 2. qnamakerrc and 3. env variables
@returns {Promise<*>} | [
"Composes",
"the",
"config",
"from",
"the",
"3",
"sources",
"that",
"it",
"may",
"reside",
".",
"Precedence",
"is",
"1",
".",
"Arguments",
"2",
".",
"qnamakerrc",
"and",
"3",
".",
"env",
"variables"
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/QnAMaker/bin/qnamaker.js#L345-L365 |
6,249 | Microsoft/botbuilder-tools | packages/QnAMaker/bin/qnamaker.js | handleError | async function handleError(error) {
process.stderr.write('\n' + chalk.red.bold(error + '\n\n'));
await help(args);
return 1;
} | javascript | async function handleError(error) {
process.stderr.write('\n' + chalk.red.bold(error + '\n\n'));
await help(args);
return 1;
} | [
"async",
"function",
"handleError",
"(",
"error",
")",
"{",
"process",
".",
"stderr",
".",
"write",
"(",
"'\\n'",
"+",
"chalk",
".",
"red",
".",
"bold",
"(",
"error",
"+",
"'\\n\\n'",
")",
")",
";",
"await",
"help",
"(",
"args",
")",
";",
"return",
"1",
";",
"}"
] | Exits with a non-zero status and prints
the error if present or displays the help
@param error | [
"Exits",
"with",
"a",
"non",
"-",
"zero",
"status",
"and",
"prints",
"the",
"error",
"if",
"present",
"or",
"displays",
"the",
"help"
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/QnAMaker/bin/qnamaker.js#L454-L458 |
6,250 | Microsoft/botbuilder-tools | packages/Chatdown/bin/chatdown.js | processFiles | async function processFiles(inputDir, outputDir) {
return new Promise(async (resolve, reject) => {
let files = glob.sync(inputDir, { "ignore": ["**/node_modules/**"] });
for (let i = 0; i < files.length; i++) {
try {
let fileName = files[i];
if (files[i].lastIndexOf("/") != -1) {
fileName = files[i].substr(files[i].lastIndexOf("/"))
}
fileName = fileName.split(".")[0];
let activities = await chatdown(txtfile.readSync(files[i]));
let writeFile = `${outputDir}/${fileName}.transcript`;
await fs.ensureFile(writeFile);
await fs.writeJson(writeFile, activities, { spaces: 2 });
}
catch (e) {
reject(e);
}
}
resolve(files.length);
});
} | javascript | async function processFiles(inputDir, outputDir) {
return new Promise(async (resolve, reject) => {
let files = glob.sync(inputDir, { "ignore": ["**/node_modules/**"] });
for (let i = 0; i < files.length; i++) {
try {
let fileName = files[i];
if (files[i].lastIndexOf("/") != -1) {
fileName = files[i].substr(files[i].lastIndexOf("/"))
}
fileName = fileName.split(".")[0];
let activities = await chatdown(txtfile.readSync(files[i]));
let writeFile = `${outputDir}/${fileName}.transcript`;
await fs.ensureFile(writeFile);
await fs.writeJson(writeFile, activities, { spaces: 2 });
}
catch (e) {
reject(e);
}
}
resolve(files.length);
});
} | [
"async",
"function",
"processFiles",
"(",
"inputDir",
",",
"outputDir",
")",
"{",
"return",
"new",
"Promise",
"(",
"async",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"let",
"files",
"=",
"glob",
".",
"sync",
"(",
"inputDir",
",",
"{",
"\"ignore\"",
":",
"[",
"\"**/node_modules/**\"",
"]",
"}",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"try",
"{",
"let",
"fileName",
"=",
"files",
"[",
"i",
"]",
";",
"if",
"(",
"files",
"[",
"i",
"]",
".",
"lastIndexOf",
"(",
"\"/\"",
")",
"!=",
"-",
"1",
")",
"{",
"fileName",
"=",
"files",
"[",
"i",
"]",
".",
"substr",
"(",
"files",
"[",
"i",
"]",
".",
"lastIndexOf",
"(",
"\"/\"",
")",
")",
"}",
"fileName",
"=",
"fileName",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
";",
"let",
"activities",
"=",
"await",
"chatdown",
"(",
"txtfile",
".",
"readSync",
"(",
"files",
"[",
"i",
"]",
")",
")",
";",
"let",
"writeFile",
"=",
"`",
"${",
"outputDir",
"}",
"${",
"fileName",
"}",
"`",
";",
"await",
"fs",
".",
"ensureFile",
"(",
"writeFile",
")",
";",
"await",
"fs",
".",
"writeJson",
"(",
"writeFile",
",",
"activities",
",",
"{",
"spaces",
":",
"2",
"}",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"reject",
"(",
"e",
")",
";",
"}",
"}",
"resolve",
"(",
"files",
".",
"length",
")",
";",
"}",
")",
";",
"}"
] | Processes multiple files, and writes them to the output directory.
@param {string} inputDir String representing a glob that specifies the input directory
@param {string} outputDir String representing the output directory for the processesd files
@returns {Promise<string>|boolean} The length of the files array that was processes | [
"Processes",
"multiple",
"files",
"and",
"writes",
"them",
"to",
"the",
"output",
"directory",
"."
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/Chatdown/bin/chatdown.js#L86-L107 |
6,251 | Microsoft/botbuilder-tools | packages/Chatdown/bin/chatdown.js | runProgram | async function runProgram() {
const args = minimist(process.argv.slice(2));
if (args.prefix) {
intercept(function(txt) {
return `[${pkg.name}]\n${txt}`;
});
}
let latest = await latestVersion(pkg.name, { version: `>${pkg.version}` })
.catch(error => pkg.version);
if (semver.gt(latest, pkg.version)) {
process.stderr.write(chalk.default.white(`\n Update available `));
process.stderr.write(chalk.default.grey(`${pkg.version}`));
process.stderr.write(chalk.default.white(` -> `));
process.stderr.write(chalk.default.greenBright(`${latest}\n`));
process.stderr.write(chalk.default.white(` Run `));
process.stderr.write(chalk.default.blueBright(`npm i -g ${pkg.name} `));
process.stderr.write(chalk.default.white(`to update.\n`));
}
if (args.version || args.v) {
process.stdout.write(pkg.version);
return 0;
}
if (args.h || args.help) {
help(process.stdout);
return 0;
}
if (args.f || args.folder) {
let inputDir = args.f.trim();
let outputDir = (args.o || args.out_folder) ? args.o.trim() : "./";
if (outputDir.substr(0, 2) === "./") {
outputDir = path.resolve(process.cwd(), outputDir.substr(2))
}
const len = await processFiles(inputDir, outputDir);
process.stdout.write(chalk`{green Successfully wrote ${len} files}\n`);
return len;
}
else {
const fileContents = await getInput(args);
if (fileContents) {
const activities = await chatdown(fileContents, args);
const writeConfirmation = await writeOut(activities, args);
if (typeof writeConfirmation === 'string') {
process.stdout.write(chalk`{green Successfully wrote file:} {blue ${writeConfirmation}}\n`);
}
return 0;
}
else {
help();
return -1;
}
}
} | javascript | async function runProgram() {
const args = minimist(process.argv.slice(2));
if (args.prefix) {
intercept(function(txt) {
return `[${pkg.name}]\n${txt}`;
});
}
let latest = await latestVersion(pkg.name, { version: `>${pkg.version}` })
.catch(error => pkg.version);
if (semver.gt(latest, pkg.version)) {
process.stderr.write(chalk.default.white(`\n Update available `));
process.stderr.write(chalk.default.grey(`${pkg.version}`));
process.stderr.write(chalk.default.white(` -> `));
process.stderr.write(chalk.default.greenBright(`${latest}\n`));
process.stderr.write(chalk.default.white(` Run `));
process.stderr.write(chalk.default.blueBright(`npm i -g ${pkg.name} `));
process.stderr.write(chalk.default.white(`to update.\n`));
}
if (args.version || args.v) {
process.stdout.write(pkg.version);
return 0;
}
if (args.h || args.help) {
help(process.stdout);
return 0;
}
if (args.f || args.folder) {
let inputDir = args.f.trim();
let outputDir = (args.o || args.out_folder) ? args.o.trim() : "./";
if (outputDir.substr(0, 2) === "./") {
outputDir = path.resolve(process.cwd(), outputDir.substr(2))
}
const len = await processFiles(inputDir, outputDir);
process.stdout.write(chalk`{green Successfully wrote ${len} files}\n`);
return len;
}
else {
const fileContents = await getInput(args);
if (fileContents) {
const activities = await chatdown(fileContents, args);
const writeConfirmation = await writeOut(activities, args);
if (typeof writeConfirmation === 'string') {
process.stdout.write(chalk`{green Successfully wrote file:} {blue ${writeConfirmation}}\n`);
}
return 0;
}
else {
help();
return -1;
}
}
} | [
"async",
"function",
"runProgram",
"(",
")",
"{",
"const",
"args",
"=",
"minimist",
"(",
"process",
".",
"argv",
".",
"slice",
"(",
"2",
")",
")",
";",
"if",
"(",
"args",
".",
"prefix",
")",
"{",
"intercept",
"(",
"function",
"(",
"txt",
")",
"{",
"return",
"`",
"${",
"pkg",
".",
"name",
"}",
"\\n",
"${",
"txt",
"}",
"`",
";",
"}",
")",
";",
"}",
"let",
"latest",
"=",
"await",
"latestVersion",
"(",
"pkg",
".",
"name",
",",
"{",
"version",
":",
"`",
"${",
"pkg",
".",
"version",
"}",
"`",
"}",
")",
".",
"catch",
"(",
"error",
"=>",
"pkg",
".",
"version",
")",
";",
"if",
"(",
"semver",
".",
"gt",
"(",
"latest",
",",
"pkg",
".",
"version",
")",
")",
"{",
"process",
".",
"stderr",
".",
"write",
"(",
"chalk",
".",
"default",
".",
"white",
"(",
"`",
"\\n",
"`",
")",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"chalk",
".",
"default",
".",
"grey",
"(",
"`",
"${",
"pkg",
".",
"version",
"}",
"`",
")",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"chalk",
".",
"default",
".",
"white",
"(",
"`",
"`",
")",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"chalk",
".",
"default",
".",
"greenBright",
"(",
"`",
"${",
"latest",
"}",
"\\n",
"`",
")",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"chalk",
".",
"default",
".",
"white",
"(",
"`",
"`",
")",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"chalk",
".",
"default",
".",
"blueBright",
"(",
"`",
"${",
"pkg",
".",
"name",
"}",
"`",
")",
")",
";",
"process",
".",
"stderr",
".",
"write",
"(",
"chalk",
".",
"default",
".",
"white",
"(",
"`",
"\\n",
"`",
")",
")",
";",
"}",
"if",
"(",
"args",
".",
"version",
"||",
"args",
".",
"v",
")",
"{",
"process",
".",
"stdout",
".",
"write",
"(",
"pkg",
".",
"version",
")",
";",
"return",
"0",
";",
"}",
"if",
"(",
"args",
".",
"h",
"||",
"args",
".",
"help",
")",
"{",
"help",
"(",
"process",
".",
"stdout",
")",
";",
"return",
"0",
";",
"}",
"if",
"(",
"args",
".",
"f",
"||",
"args",
".",
"folder",
")",
"{",
"let",
"inputDir",
"=",
"args",
".",
"f",
".",
"trim",
"(",
")",
";",
"let",
"outputDir",
"=",
"(",
"args",
".",
"o",
"||",
"args",
".",
"out_folder",
")",
"?",
"args",
".",
"o",
".",
"trim",
"(",
")",
":",
"\"./\"",
";",
"if",
"(",
"outputDir",
".",
"substr",
"(",
"0",
",",
"2",
")",
"===",
"\"./\"",
")",
"{",
"outputDir",
"=",
"path",
".",
"resolve",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"outputDir",
".",
"substr",
"(",
"2",
")",
")",
"}",
"const",
"len",
"=",
"await",
"processFiles",
"(",
"inputDir",
",",
"outputDir",
")",
";",
"process",
".",
"stdout",
".",
"write",
"(",
"chalk",
"`",
"${",
"len",
"}",
"\\n",
"`",
")",
";",
"return",
"len",
";",
"}",
"else",
"{",
"const",
"fileContents",
"=",
"await",
"getInput",
"(",
"args",
")",
";",
"if",
"(",
"fileContents",
")",
"{",
"const",
"activities",
"=",
"await",
"chatdown",
"(",
"fileContents",
",",
"args",
")",
";",
"const",
"writeConfirmation",
"=",
"await",
"writeOut",
"(",
"activities",
",",
"args",
")",
";",
"if",
"(",
"typeof",
"writeConfirmation",
"===",
"'string'",
")",
"{",
"process",
".",
"stdout",
".",
"write",
"(",
"chalk",
"`",
"${",
"writeConfirmation",
"}",
"\\n",
"`",
")",
";",
"}",
"return",
"0",
";",
"}",
"else",
"{",
"help",
"(",
")",
";",
"return",
"-",
"1",
";",
"}",
"}",
"}"
] | Runs the program
@returns {Promise<void>} | [
"Runs",
"the",
"program"
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/Chatdown/bin/chatdown.js#L113-L170 |
6,252 | Microsoft/botbuilder-tools | packages/Chatdown/bin/chatdown.js | exitWithError | function exitWithError(error) {
if (error instanceof Error) {
process.stderr.write(chalk.red(error));
} else {
help();
}
process.exit(1);
} | javascript | function exitWithError(error) {
if (error instanceof Error) {
process.stderr.write(chalk.red(error));
} else {
help();
}
process.exit(1);
} | [
"function",
"exitWithError",
"(",
"error",
")",
"{",
"if",
"(",
"error",
"instanceof",
"Error",
")",
"{",
"process",
".",
"stderr",
".",
"write",
"(",
"chalk",
".",
"red",
"(",
"error",
")",
")",
";",
"}",
"else",
"{",
"help",
"(",
")",
";",
"}",
"process",
".",
"exit",
"(",
"1",
")",
";",
"}"
] | Utility function that exist the process with an
optional error. If an Error is received, the error
message is written to stdout, otherwise, the help
content are displayed.
@param {*} error Either an instance of Error or null | [
"Utility",
"function",
"that",
"exist",
"the",
"process",
"with",
"an",
"optional",
"error",
".",
"If",
"an",
"Error",
"is",
"received",
"the",
"error",
"message",
"is",
"written",
"to",
"stdout",
"otherwise",
"the",
"help",
"content",
"are",
"displayed",
"."
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/Chatdown/bin/chatdown.js#L180-L187 |
6,253 | Microsoft/botbuilder-tools | packages/QnAMaker/lib/help.js | getHelpContents | async function getHelpContents(args, output) {
if ('!' in args) {
return getAllCommands(output);
}
if (args._.length == 0) {
return getGeneralHelpContents(output);
}
else if (args._.length == 1) {
return getVerbHelp(args._[0], output);
} else if (args._.length >= 2) {
const serviceManifest = getServiceManifest(args);
if (serviceManifest) {
const { operation } = serviceManifest;
output.write(`${operation.description}\n\n`);
output.write(`Usage:\n${chalk.cyan.bold(operation.command)}\n\n`);
} else {
return getVerbHelp(args._[0], output);
}
}
const serviceManifest = getServiceManifest(args);
if (serviceManifest) {
return getHelpContentsForService(serviceManifest, output);
}
return getGeneralHelpContents(output);
} | javascript | async function getHelpContents(args, output) {
if ('!' in args) {
return getAllCommands(output);
}
if (args._.length == 0) {
return getGeneralHelpContents(output);
}
else if (args._.length == 1) {
return getVerbHelp(args._[0], output);
} else if (args._.length >= 2) {
const serviceManifest = getServiceManifest(args);
if (serviceManifest) {
const { operation } = serviceManifest;
output.write(`${operation.description}\n\n`);
output.write(`Usage:\n${chalk.cyan.bold(operation.command)}\n\n`);
} else {
return getVerbHelp(args._[0], output);
}
}
const serviceManifest = getServiceManifest(args);
if (serviceManifest) {
return getHelpContentsForService(serviceManifest, output);
}
return getGeneralHelpContents(output);
} | [
"async",
"function",
"getHelpContents",
"(",
"args",
",",
"output",
")",
"{",
"if",
"(",
"'!'",
"in",
"args",
")",
"{",
"return",
"getAllCommands",
"(",
"output",
")",
";",
"}",
"if",
"(",
"args",
".",
"_",
".",
"length",
"==",
"0",
")",
"{",
"return",
"getGeneralHelpContents",
"(",
"output",
")",
";",
"}",
"else",
"if",
"(",
"args",
".",
"_",
".",
"length",
"==",
"1",
")",
"{",
"return",
"getVerbHelp",
"(",
"args",
".",
"_",
"[",
"0",
"]",
",",
"output",
")",
";",
"}",
"else",
"if",
"(",
"args",
".",
"_",
".",
"length",
">=",
"2",
")",
"{",
"const",
"serviceManifest",
"=",
"getServiceManifest",
"(",
"args",
")",
";",
"if",
"(",
"serviceManifest",
")",
"{",
"const",
"{",
"operation",
"}",
"=",
"serviceManifest",
";",
"output",
".",
"write",
"(",
"`",
"${",
"operation",
".",
"description",
"}",
"\\n",
"\\n",
"`",
")",
";",
"output",
".",
"write",
"(",
"`",
"\\n",
"${",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"operation",
".",
"command",
")",
"}",
"\\n",
"\\n",
"`",
")",
";",
"}",
"else",
"{",
"return",
"getVerbHelp",
"(",
"args",
".",
"_",
"[",
"0",
"]",
",",
"output",
")",
";",
"}",
"}",
"const",
"serviceManifest",
"=",
"getServiceManifest",
"(",
"args",
")",
";",
"if",
"(",
"serviceManifest",
")",
"{",
"return",
"getHelpContentsForService",
"(",
"serviceManifest",
",",
"output",
")",
";",
"}",
"return",
"getGeneralHelpContents",
"(",
"output",
")",
";",
"}"
] | Retrieves help content vie the qnamaker.json from
the arguments input by the user.
@param args The arguments input by the user
@returns {Promise<*>} | [
"Retrieves",
"help",
"content",
"vie",
"the",
"qnamaker",
".",
"json",
"from",
"the",
"arguments",
"input",
"by",
"the",
"user",
"."
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/QnAMaker/lib/help.js#L78-L106 |
6,254 | Microsoft/botbuilder-tools | packages/QnAMaker/lib/help.js | getAllCommands | function getAllCommands() {
let resourceTypes = [];
let tables = {};
Object.keys(manifest).forEach(key => {
const { [key]: category } = manifest;
Object.keys(category.operations).forEach((operationKey) => {
let operation = category.operations[operationKey];
let opCategory = operation.target[0] || operation.methodAlias;
if (resourceTypes.indexOf(opCategory) < 0) {
resourceTypes.push(opCategory);
tables[opCategory] = [];
}
tables[opCategory].push([chalk.cyan.bold(operation.command), operation.description]);
});
});
resourceTypes.sort();
let sections = [];
for (let resourceType of resourceTypes) {
tables[resourceType].sort((a, b) => a[0].localeCompare(b[0]));
sections.push({
head: chalk.white.bold(resourceType),
table: tables[resourceType]
});
}
return sections;
} | javascript | function getAllCommands() {
let resourceTypes = [];
let tables = {};
Object.keys(manifest).forEach(key => {
const { [key]: category } = manifest;
Object.keys(category.operations).forEach((operationKey) => {
let operation = category.operations[operationKey];
let opCategory = operation.target[0] || operation.methodAlias;
if (resourceTypes.indexOf(opCategory) < 0) {
resourceTypes.push(opCategory);
tables[opCategory] = [];
}
tables[opCategory].push([chalk.cyan.bold(operation.command), operation.description]);
});
});
resourceTypes.sort();
let sections = [];
for (let resourceType of resourceTypes) {
tables[resourceType].sort((a, b) => a[0].localeCompare(b[0]));
sections.push({
head: chalk.white.bold(resourceType),
table: tables[resourceType]
});
}
return sections;
} | [
"function",
"getAllCommands",
"(",
")",
"{",
"let",
"resourceTypes",
"=",
"[",
"]",
";",
"let",
"tables",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"manifest",
")",
".",
"forEach",
"(",
"key",
"=>",
"{",
"const",
"{",
"[",
"key",
"]",
":",
"category",
"}",
"=",
"manifest",
";",
"Object",
".",
"keys",
"(",
"category",
".",
"operations",
")",
".",
"forEach",
"(",
"(",
"operationKey",
")",
"=>",
"{",
"let",
"operation",
"=",
"category",
".",
"operations",
"[",
"operationKey",
"]",
";",
"let",
"opCategory",
"=",
"operation",
".",
"target",
"[",
"0",
"]",
"||",
"operation",
".",
"methodAlias",
";",
"if",
"(",
"resourceTypes",
".",
"indexOf",
"(",
"opCategory",
")",
"<",
"0",
")",
"{",
"resourceTypes",
".",
"push",
"(",
"opCategory",
")",
";",
"tables",
"[",
"opCategory",
"]",
"=",
"[",
"]",
";",
"}",
"tables",
"[",
"opCategory",
"]",
".",
"push",
"(",
"[",
"chalk",
".",
"cyan",
".",
"bold",
"(",
"operation",
".",
"command",
")",
",",
"operation",
".",
"description",
"]",
")",
";",
"}",
")",
";",
"}",
")",
";",
"resourceTypes",
".",
"sort",
"(",
")",
";",
"let",
"sections",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"resourceType",
"of",
"resourceTypes",
")",
"{",
"tables",
"[",
"resourceType",
"]",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"a",
"[",
"0",
"]",
".",
"localeCompare",
"(",
"b",
"[",
"0",
"]",
")",
")",
";",
"sections",
".",
"push",
"(",
"{",
"head",
":",
"chalk",
".",
"white",
".",
"bold",
"(",
"resourceType",
")",
",",
"table",
":",
"tables",
"[",
"resourceType",
"]",
"}",
")",
";",
"}",
"return",
"sections",
";",
"}"
] | Walks the qnamaker.json and pulls out all
commands that are supported.
@returns {*[]} | [
"Walks",
"the",
"qnamaker",
".",
"json",
"and",
"pulls",
"out",
"all",
"commands",
"that",
"are",
"supported",
"."
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/QnAMaker/lib/help.js#L230-L258 |
6,255 | Microsoft/botbuilder-tools | packages/Chatdown/lib/index.js | createConversationUpdate | function createConversationUpdate(args, membersAdded, membersRemoved) {
let conversationUpdateActivity = createActivity({
type: activitytypes.conversationupdate,
recipient: args[args.botId],
conversationId: args.conversation.id
});
conversationUpdateActivity.membersAdded = membersAdded || [];
conversationUpdateActivity.membersRemoved = membersRemoved || [];
conversationUpdateActivity.timestamp = getIncrementedDate(100);
return conversationUpdateActivity;
} | javascript | function createConversationUpdate(args, membersAdded, membersRemoved) {
let conversationUpdateActivity = createActivity({
type: activitytypes.conversationupdate,
recipient: args[args.botId],
conversationId: args.conversation.id
});
conversationUpdateActivity.membersAdded = membersAdded || [];
conversationUpdateActivity.membersRemoved = membersRemoved || [];
conversationUpdateActivity.timestamp = getIncrementedDate(100);
return conversationUpdateActivity;
} | [
"function",
"createConversationUpdate",
"(",
"args",
",",
"membersAdded",
",",
"membersRemoved",
")",
"{",
"let",
"conversationUpdateActivity",
"=",
"createActivity",
"(",
"{",
"type",
":",
"activitytypes",
".",
"conversationupdate",
",",
"recipient",
":",
"args",
"[",
"args",
".",
"botId",
"]",
",",
"conversationId",
":",
"args",
".",
"conversation",
".",
"id",
"}",
")",
";",
"conversationUpdateActivity",
".",
"membersAdded",
"=",
"membersAdded",
"||",
"[",
"]",
";",
"conversationUpdateActivity",
".",
"membersRemoved",
"=",
"membersRemoved",
"||",
"[",
"]",
";",
"conversationUpdateActivity",
".",
"timestamp",
"=",
"getIncrementedDate",
"(",
"100",
")",
";",
"return",
"conversationUpdateActivity",
";",
"}"
] | create ConversationUpdate Activity
@param {*} args
@param {ChannelAccount} from
@param {ChannelAccount[]} membersAdded
@param {ChannelAccount[]} membersRemoved | [
"create",
"ConversationUpdate",
"Activity"
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/Chatdown/lib/index.js#L177-L187 |
6,256 | Microsoft/botbuilder-tools | packages/Chatdown/lib/index.js | addAttachment | async function addAttachment(activity, arg) {
let parts = arg.trim().split(' ');
let contentUrl = parts[0].trim();
let contentType = (parts.length > 1) ? parts[1].trim() : undefined;
if (contentType) {
contentType = contentType.toLowerCase();
if (cardContentTypes[contentType])
contentType = cardContentTypes[contentType];
}
else {
contentType = mime.lookup(contentUrl) || cardContentTypes[path.extname(contentUrl)];
if (!contentType && contentUrl && contentUrl.indexOf('http') == 0) {
let options = { method: 'HEAD', uri: contentUrl };
let response = await request(options);
contentType = response['content-type'].split(';')[0];
}
}
const charset = mime.charset(contentType);
// if not a url
if (contentUrl.indexOf('http') != 0) {
// read the file
let content = await readAttachmentFile(contentUrl, contentType);
// if it is not a card
if (!isCard(contentType) && charset !== 'UTF-8') {
// send as base64
contentUrl = `data:${contentType};base64,${new Buffer(content).toString('base64')}`;
content = undefined;
} else {
contentUrl = undefined;
}
return (activity.attachments || (activity.attachments = [])).push(new Attachment({ contentType, contentUrl, content }));
}
// send as contentUrl
return (activity.attachments || (activity.attachments = [])).push(new Attachment({ contentType, contentUrl }));
} | javascript | async function addAttachment(activity, arg) {
let parts = arg.trim().split(' ');
let contentUrl = parts[0].trim();
let contentType = (parts.length > 1) ? parts[1].trim() : undefined;
if (contentType) {
contentType = contentType.toLowerCase();
if (cardContentTypes[contentType])
contentType = cardContentTypes[contentType];
}
else {
contentType = mime.lookup(contentUrl) || cardContentTypes[path.extname(contentUrl)];
if (!contentType && contentUrl && contentUrl.indexOf('http') == 0) {
let options = { method: 'HEAD', uri: contentUrl };
let response = await request(options);
contentType = response['content-type'].split(';')[0];
}
}
const charset = mime.charset(contentType);
// if not a url
if (contentUrl.indexOf('http') != 0) {
// read the file
let content = await readAttachmentFile(contentUrl, contentType);
// if it is not a card
if (!isCard(contentType) && charset !== 'UTF-8') {
// send as base64
contentUrl = `data:${contentType};base64,${new Buffer(content).toString('base64')}`;
content = undefined;
} else {
contentUrl = undefined;
}
return (activity.attachments || (activity.attachments = [])).push(new Attachment({ contentType, contentUrl, content }));
}
// send as contentUrl
return (activity.attachments || (activity.attachments = [])).push(new Attachment({ contentType, contentUrl }));
} | [
"async",
"function",
"addAttachment",
"(",
"activity",
",",
"arg",
")",
"{",
"let",
"parts",
"=",
"arg",
".",
"trim",
"(",
")",
".",
"split",
"(",
"' '",
")",
";",
"let",
"contentUrl",
"=",
"parts",
"[",
"0",
"]",
".",
"trim",
"(",
")",
";",
"let",
"contentType",
"=",
"(",
"parts",
".",
"length",
">",
"1",
")",
"?",
"parts",
"[",
"1",
"]",
".",
"trim",
"(",
")",
":",
"undefined",
";",
"if",
"(",
"contentType",
")",
"{",
"contentType",
"=",
"contentType",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"cardContentTypes",
"[",
"contentType",
"]",
")",
"contentType",
"=",
"cardContentTypes",
"[",
"contentType",
"]",
";",
"}",
"else",
"{",
"contentType",
"=",
"mime",
".",
"lookup",
"(",
"contentUrl",
")",
"||",
"cardContentTypes",
"[",
"path",
".",
"extname",
"(",
"contentUrl",
")",
"]",
";",
"if",
"(",
"!",
"contentType",
"&&",
"contentUrl",
"&&",
"contentUrl",
".",
"indexOf",
"(",
"'http'",
")",
"==",
"0",
")",
"{",
"let",
"options",
"=",
"{",
"method",
":",
"'HEAD'",
",",
"uri",
":",
"contentUrl",
"}",
";",
"let",
"response",
"=",
"await",
"request",
"(",
"options",
")",
";",
"contentType",
"=",
"response",
"[",
"'content-type'",
"]",
".",
"split",
"(",
"';'",
")",
"[",
"0",
"]",
";",
"}",
"}",
"const",
"charset",
"=",
"mime",
".",
"charset",
"(",
"contentType",
")",
";",
"// if not a url",
"if",
"(",
"contentUrl",
".",
"indexOf",
"(",
"'http'",
")",
"!=",
"0",
")",
"{",
"// read the file",
"let",
"content",
"=",
"await",
"readAttachmentFile",
"(",
"contentUrl",
",",
"contentType",
")",
";",
"// if it is not a card",
"if",
"(",
"!",
"isCard",
"(",
"contentType",
")",
"&&",
"charset",
"!==",
"'UTF-8'",
")",
"{",
"// send as base64",
"contentUrl",
"=",
"`",
"${",
"contentType",
"}",
"${",
"new",
"Buffer",
"(",
"content",
")",
".",
"toString",
"(",
"'base64'",
")",
"}",
"`",
";",
"content",
"=",
"undefined",
";",
"}",
"else",
"{",
"contentUrl",
"=",
"undefined",
";",
"}",
"return",
"(",
"activity",
".",
"attachments",
"||",
"(",
"activity",
".",
"attachments",
"=",
"[",
"]",
")",
")",
".",
"push",
"(",
"new",
"Attachment",
"(",
"{",
"contentType",
",",
"contentUrl",
",",
"content",
"}",
")",
")",
";",
"}",
"// send as contentUrl",
"return",
"(",
"activity",
".",
"attachments",
"||",
"(",
"activity",
".",
"attachments",
"=",
"[",
"]",
")",
")",
".",
"push",
"(",
"new",
"Attachment",
"(",
"{",
"contentType",
",",
"contentUrl",
"}",
")",
")",
";",
"}"
] | Adds an attachment to the activity. If a mimetype is
specified, it is used as is. Otherwise, it is derived
from the file extension.
@param {Activity} activity The activity to add the attachment to
@param {*} contentUrl contenturl
@param {*} contentType contentType
@returns {Promise<number>} The new number of attachments for the activity | [
"Adds",
"an",
"attachment",
"to",
"the",
"activity",
".",
"If",
"a",
"mimetype",
"is",
"specified",
"it",
"is",
"used",
"as",
"is",
".",
"Otherwise",
"it",
"is",
"derived",
"from",
"the",
"file",
"extension",
"."
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/Chatdown/lib/index.js#L468-L505 |
6,257 | Microsoft/botbuilder-tools | packages/Chatdown/lib/index.js | readAttachmentFile | async function readAttachmentFile(fileLocation, contentType) {
let resolvedFileLocation = path.join(workingDirectory, fileLocation);
let exists = fs.pathExistsSync(resolvedFileLocation);
// fallback to cwd
if (!exists) {
resolvedFileLocation = path.resolve(fileLocation);
}
// Throws if the fallback does not exist.
if (contentType.includes('json') || isCard(contentType)) {
return fs.readJsonSync(resolvedFileLocation);
} else {
return fs.readFileSync(resolvedFileLocation);
}
} | javascript | async function readAttachmentFile(fileLocation, contentType) {
let resolvedFileLocation = path.join(workingDirectory, fileLocation);
let exists = fs.pathExistsSync(resolvedFileLocation);
// fallback to cwd
if (!exists) {
resolvedFileLocation = path.resolve(fileLocation);
}
// Throws if the fallback does not exist.
if (contentType.includes('json') || isCard(contentType)) {
return fs.readJsonSync(resolvedFileLocation);
} else {
return fs.readFileSync(resolvedFileLocation);
}
} | [
"async",
"function",
"readAttachmentFile",
"(",
"fileLocation",
",",
"contentType",
")",
"{",
"let",
"resolvedFileLocation",
"=",
"path",
".",
"join",
"(",
"workingDirectory",
",",
"fileLocation",
")",
";",
"let",
"exists",
"=",
"fs",
".",
"pathExistsSync",
"(",
"resolvedFileLocation",
")",
";",
"// fallback to cwd",
"if",
"(",
"!",
"exists",
")",
"{",
"resolvedFileLocation",
"=",
"path",
".",
"resolve",
"(",
"fileLocation",
")",
";",
"}",
"// Throws if the fallback does not exist.",
"if",
"(",
"contentType",
".",
"includes",
"(",
"'json'",
")",
"||",
"isCard",
"(",
"contentType",
")",
")",
"{",
"return",
"fs",
".",
"readJsonSync",
"(",
"resolvedFileLocation",
")",
";",
"}",
"else",
"{",
"return",
"fs",
".",
"readFileSync",
"(",
"resolvedFileLocation",
")",
";",
"}",
"}"
] | Utility function for reading the attachment
@param fileLocation
@param contentType
@returns {*} | [
"Utility",
"function",
"for",
"reading",
"the",
"attachment"
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/Chatdown/lib/index.js#L514-L528 |
6,258 | Microsoft/botbuilder-tools | packages/Chatdown/lib/index.js | createActivity | function createActivity({ type = ActivityTypes.Message, recipient, from, conversationId }) {
const activity = new Activity({ from, recipient, type, id: '' + activityId++ });
activity.conversation = new ConversationAccount({ id: conversationId });
return activity;
} | javascript | function createActivity({ type = ActivityTypes.Message, recipient, from, conversationId }) {
const activity = new Activity({ from, recipient, type, id: '' + activityId++ });
activity.conversation = new ConversationAccount({ id: conversationId });
return activity;
} | [
"function",
"createActivity",
"(",
"{",
"type",
"=",
"ActivityTypes",
".",
"Message",
",",
"recipient",
",",
"from",
",",
"conversationId",
"}",
")",
"{",
"const",
"activity",
"=",
"new",
"Activity",
"(",
"{",
"from",
",",
"recipient",
",",
"type",
",",
"id",
":",
"''",
"+",
"activityId",
"++",
"}",
")",
";",
"activity",
".",
"conversation",
"=",
"new",
"ConversationAccount",
"(",
"{",
"id",
":",
"conversationId",
"}",
")",
";",
"return",
"activity",
";",
"}"
] | Utility for creating a new serializable Activity.
@param {ActivityTypes} type The Activity type
@param {string} to The recipient of the Activity
@param {string} from The sender of the Activity
@param {string} conversationId The id of the conversation
@returns {Activity} The newly created activity | [
"Utility",
"for",
"creating",
"a",
"new",
"serializable",
"Activity",
"."
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/Chatdown/lib/index.js#L539-L543 |
6,259 | Microsoft/botbuilder-tools | packages/QnAMaker/lib/utils/insertParametersFromObject.js | insertParametersFromObject | function insertParametersFromObject(parameterizedString, sourceObj) {
let result;
let payload = parameterizedString;
while ((result = tokenRegExp.exec(parameterizedString))) {
const token = result[1];
const propertyName = token.replace(/[{}]/g, '');
if (!(propertyName in sourceObj)) {
continue;
}
payload = payload.replace(token, '' + sourceObj[propertyName]);
}
return payload;
} | javascript | function insertParametersFromObject(parameterizedString, sourceObj) {
let result;
let payload = parameterizedString;
while ((result = tokenRegExp.exec(parameterizedString))) {
const token = result[1];
const propertyName = token.replace(/[{}]/g, '');
if (!(propertyName in sourceObj)) {
continue;
}
payload = payload.replace(token, '' + sourceObj[propertyName]);
}
return payload;
} | [
"function",
"insertParametersFromObject",
"(",
"parameterizedString",
",",
"sourceObj",
")",
"{",
"let",
"result",
";",
"let",
"payload",
"=",
"parameterizedString",
";",
"while",
"(",
"(",
"result",
"=",
"tokenRegExp",
".",
"exec",
"(",
"parameterizedString",
")",
")",
")",
"{",
"const",
"token",
"=",
"result",
"[",
"1",
"]",
";",
"const",
"propertyName",
"=",
"token",
".",
"replace",
"(",
"/",
"[{}]",
"/",
"g",
",",
"''",
")",
";",
"if",
"(",
"!",
"(",
"propertyName",
"in",
"sourceObj",
")",
")",
"{",
"continue",
";",
"}",
"payload",
"=",
"payload",
".",
"replace",
"(",
"token",
",",
"''",
"+",
"sourceObj",
"[",
"propertyName",
"]",
")",
";",
"}",
"return",
"payload",
";",
"}"
] | Replaces parameterized strings with the value from the
corresponding source object's property.
@param parameterizedString {string} The String containing parameters represented by braces
@param sourceObj {*} The object containing the properties to transfer.
@returns {string} The string containing the replaced parameters from the source object. | [
"Replaces",
"parameterized",
"strings",
"with",
"the",
"value",
"from",
"the",
"corresponding",
"source",
"object",
"s",
"property",
"."
] | 917d4271f624f10bb3a9e6bcc26fb5de587e37e6 | https://github.com/Microsoft/botbuilder-tools/blob/917d4271f624f10bb3a9e6bcc26fb5de587e37e6/packages/QnAMaker/lib/utils/insertParametersFromObject.js#L15-L27 |
6,260 | chimurai/http-proxy-middleware | dist/path-rewriter.js | createPathRewriter | function createPathRewriter(rewriteConfig) {
let rulesCache;
if (!isValidRewriteConfig(rewriteConfig)) {
return;
}
if (_.isFunction(rewriteConfig)) {
const customRewriteFn = rewriteConfig;
return customRewriteFn;
}
else {
rulesCache = parsePathRewriteRules(rewriteConfig);
return rewritePath;
}
function rewritePath(path) {
let result = path;
_.forEach(rulesCache, rule => {
if (rule.regex.test(path)) {
result = result.replace(rule.regex, rule.value);
logger.debug('[HPM] Rewriting path from "%s" to "%s"', path, result);
return false;
}
});
return result;
}
} | javascript | function createPathRewriter(rewriteConfig) {
let rulesCache;
if (!isValidRewriteConfig(rewriteConfig)) {
return;
}
if (_.isFunction(rewriteConfig)) {
const customRewriteFn = rewriteConfig;
return customRewriteFn;
}
else {
rulesCache = parsePathRewriteRules(rewriteConfig);
return rewritePath;
}
function rewritePath(path) {
let result = path;
_.forEach(rulesCache, rule => {
if (rule.regex.test(path)) {
result = result.replace(rule.regex, rule.value);
logger.debug('[HPM] Rewriting path from "%s" to "%s"', path, result);
return false;
}
});
return result;
}
} | [
"function",
"createPathRewriter",
"(",
"rewriteConfig",
")",
"{",
"let",
"rulesCache",
";",
"if",
"(",
"!",
"isValidRewriteConfig",
"(",
"rewriteConfig",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"_",
".",
"isFunction",
"(",
"rewriteConfig",
")",
")",
"{",
"const",
"customRewriteFn",
"=",
"rewriteConfig",
";",
"return",
"customRewriteFn",
";",
"}",
"else",
"{",
"rulesCache",
"=",
"parsePathRewriteRules",
"(",
"rewriteConfig",
")",
";",
"return",
"rewritePath",
";",
"}",
"function",
"rewritePath",
"(",
"path",
")",
"{",
"let",
"result",
"=",
"path",
";",
"_",
".",
"forEach",
"(",
"rulesCache",
",",
"rule",
"=>",
"{",
"if",
"(",
"rule",
".",
"regex",
".",
"test",
"(",
"path",
")",
")",
"{",
"result",
"=",
"result",
".",
"replace",
"(",
"rule",
".",
"regex",
",",
"rule",
".",
"value",
")",
";",
"logger",
".",
"debug",
"(",
"'[HPM] Rewriting path from \"%s\" to \"%s\"'",
",",
"path",
",",
"result",
")",
";",
"return",
"false",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}",
"}"
] | Create rewrite function, to cache parsed rewrite rules.
@param {Object} rewriteConfig
@return {Function} Function to rewrite paths; This function should accept `path` (request.url) as parameter | [
"Create",
"rewrite",
"function",
"to",
"cache",
"parsed",
"rewrite",
"rules",
"."
] | b13302c87a04bf7adc4c2547affaaeeb7ecb0c42 | https://github.com/chimurai/http-proxy-middleware/blob/b13302c87a04bf7adc4c2547affaaeeb7ecb0c42/dist/path-rewriter.js#L13-L37 |
6,261 | peterbraden/node-opencv | examples/write-video.js | function () {
vid2.read(function (err, m2) {
if (writer2 === null)
writer2 = new cv.VideoWriter(filename2, 'DIVX', vid2.getFPS(), m2.size(), true);
x++;
writer2.write(m2, function(err){
if (x < 100) {
iter();
} else {
vid2.release();
writer2.release();
}
});
m2.release();
delete m2;
});
} | javascript | function () {
vid2.read(function (err, m2) {
if (writer2 === null)
writer2 = new cv.VideoWriter(filename2, 'DIVX', vid2.getFPS(), m2.size(), true);
x++;
writer2.write(m2, function(err){
if (x < 100) {
iter();
} else {
vid2.release();
writer2.release();
}
});
m2.release();
delete m2;
});
} | [
"function",
"(",
")",
"{",
"vid2",
".",
"read",
"(",
"function",
"(",
"err",
",",
"m2",
")",
"{",
"if",
"(",
"writer2",
"===",
"null",
")",
"writer2",
"=",
"new",
"cv",
".",
"VideoWriter",
"(",
"filename2",
",",
"'DIVX'",
",",
"vid2",
".",
"getFPS",
"(",
")",
",",
"m2",
".",
"size",
"(",
")",
",",
"true",
")",
";",
"x",
"++",
";",
"writer2",
".",
"write",
"(",
"m2",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"x",
"<",
"100",
")",
"{",
"iter",
"(",
")",
";",
"}",
"else",
"{",
"vid2",
".",
"release",
"(",
")",
";",
"writer2",
".",
"release",
"(",
")",
";",
"}",
"}",
")",
";",
"m2",
".",
"release",
"(",
")",
";",
"delete",
"m2",
";",
"}",
")",
";",
"}"
] | do the same write async | [
"do",
"the",
"same",
"write",
"async"
] | db093cb2ec422e507a61e79dd490126060a7e7d0 | https://github.com/peterbraden/node-opencv/blob/db093cb2ec422e507a61e79dd490126060a7e7d0/examples/write-video.js#L39-L56 |
|
6,262 | cornerstonejs/cornerstone | src/falseColorMapping.js | getPixelValues | function getPixelValues (pixelData) {
let minPixelValue = Number.MAX_VALUE;
let maxPixelValue = Number.MIN_VALUE;
const len = pixelData.length;
let pixel;
for (let i = 0; i < len; i++) {
pixel = pixelData[i];
minPixelValue = minPixelValue < pixel ? minPixelValue : pixel;
maxPixelValue = maxPixelValue > pixel ? maxPixelValue : pixel;
}
return {
minPixelValue,
maxPixelValue
};
} | javascript | function getPixelValues (pixelData) {
let minPixelValue = Number.MAX_VALUE;
let maxPixelValue = Number.MIN_VALUE;
const len = pixelData.length;
let pixel;
for (let i = 0; i < len; i++) {
pixel = pixelData[i];
minPixelValue = minPixelValue < pixel ? minPixelValue : pixel;
maxPixelValue = maxPixelValue > pixel ? maxPixelValue : pixel;
}
return {
minPixelValue,
maxPixelValue
};
} | [
"function",
"getPixelValues",
"(",
"pixelData",
")",
"{",
"let",
"minPixelValue",
"=",
"Number",
".",
"MAX_VALUE",
";",
"let",
"maxPixelValue",
"=",
"Number",
".",
"MIN_VALUE",
";",
"const",
"len",
"=",
"pixelData",
".",
"length",
";",
"let",
"pixel",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"pixel",
"=",
"pixelData",
"[",
"i",
"]",
";",
"minPixelValue",
"=",
"minPixelValue",
"<",
"pixel",
"?",
"minPixelValue",
":",
"pixel",
";",
"maxPixelValue",
"=",
"maxPixelValue",
">",
"pixel",
"?",
"maxPixelValue",
":",
"pixel",
";",
"}",
"return",
"{",
"minPixelValue",
",",
"maxPixelValue",
"}",
";",
"}"
] | Retrieves the minimum and maximum pixel values from an Array of pixel data
@param {Array} pixelData The input pixel data array
@returns {{minPixelValue: Number, maxPixelValue: Number}} The minimum and maximum pixel values in the input Array | [
"Retrieves",
"the",
"minimum",
"and",
"maximum",
"pixel",
"values",
"from",
"an",
"Array",
"of",
"pixel",
"data"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/falseColorMapping.js#L12-L28 |
6,263 | cornerstonejs/cornerstone | src/falseColorMapping.js | getRestoreImageMethod | function getRestoreImageMethod (image) {
if (image.restore) {
return image.restore;
}
const color = image.color;
const rgba = image.rgba;
const cachedLut = image.cachedLut;
const slope = image.slope;
const windowWidth = image.windowWidth;
const windowCenter = image.windowCenter;
const minPixelValue = image.minPixelValue;
const maxPixelValue = image.maxPixelValue;
return function () {
image.color = color;
image.rgba = rgba;
image.cachedLut = cachedLut;
image.slope = slope;
image.windowWidth = windowWidth;
image.windowCenter = windowCenter;
image.minPixelValue = minPixelValue;
image.maxPixelValue = maxPixelValue;
if (image.origPixelData) {
const pixelData = image.origPixelData;
image.getPixelData = () => pixelData;
}
// Remove some attributes added by false color mapping
image.origPixelData = undefined;
image.colormapId = undefined;
image.falseColor = undefined;
};
} | javascript | function getRestoreImageMethod (image) {
if (image.restore) {
return image.restore;
}
const color = image.color;
const rgba = image.rgba;
const cachedLut = image.cachedLut;
const slope = image.slope;
const windowWidth = image.windowWidth;
const windowCenter = image.windowCenter;
const minPixelValue = image.minPixelValue;
const maxPixelValue = image.maxPixelValue;
return function () {
image.color = color;
image.rgba = rgba;
image.cachedLut = cachedLut;
image.slope = slope;
image.windowWidth = windowWidth;
image.windowCenter = windowCenter;
image.minPixelValue = minPixelValue;
image.maxPixelValue = maxPixelValue;
if (image.origPixelData) {
const pixelData = image.origPixelData;
image.getPixelData = () => pixelData;
}
// Remove some attributes added by false color mapping
image.origPixelData = undefined;
image.colormapId = undefined;
image.falseColor = undefined;
};
} | [
"function",
"getRestoreImageMethod",
"(",
"image",
")",
"{",
"if",
"(",
"image",
".",
"restore",
")",
"{",
"return",
"image",
".",
"restore",
";",
"}",
"const",
"color",
"=",
"image",
".",
"color",
";",
"const",
"rgba",
"=",
"image",
".",
"rgba",
";",
"const",
"cachedLut",
"=",
"image",
".",
"cachedLut",
";",
"const",
"slope",
"=",
"image",
".",
"slope",
";",
"const",
"windowWidth",
"=",
"image",
".",
"windowWidth",
";",
"const",
"windowCenter",
"=",
"image",
".",
"windowCenter",
";",
"const",
"minPixelValue",
"=",
"image",
".",
"minPixelValue",
";",
"const",
"maxPixelValue",
"=",
"image",
".",
"maxPixelValue",
";",
"return",
"function",
"(",
")",
"{",
"image",
".",
"color",
"=",
"color",
";",
"image",
".",
"rgba",
"=",
"rgba",
";",
"image",
".",
"cachedLut",
"=",
"cachedLut",
";",
"image",
".",
"slope",
"=",
"slope",
";",
"image",
".",
"windowWidth",
"=",
"windowWidth",
";",
"image",
".",
"windowCenter",
"=",
"windowCenter",
";",
"image",
".",
"minPixelValue",
"=",
"minPixelValue",
";",
"image",
".",
"maxPixelValue",
"=",
"maxPixelValue",
";",
"if",
"(",
"image",
".",
"origPixelData",
")",
"{",
"const",
"pixelData",
"=",
"image",
".",
"origPixelData",
";",
"image",
".",
"getPixelData",
"=",
"(",
")",
"=>",
"pixelData",
";",
"}",
"// Remove some attributes added by false color mapping",
"image",
".",
"origPixelData",
"=",
"undefined",
";",
"image",
".",
"colormapId",
"=",
"undefined",
";",
"image",
".",
"falseColor",
"=",
"undefined",
";",
"}",
";",
"}"
] | Retrieve a function that will allow an image object to be reset to its original form
after a false color mapping transformation
@param {Image} image A Cornerstone Image Object
@return {Function} A function for resetting an Image Object to its original form | [
"Retrieve",
"a",
"function",
"that",
"will",
"allow",
"an",
"image",
"object",
"to",
"be",
"reset",
"to",
"its",
"original",
"form",
"after",
"a",
"false",
"color",
"mapping",
"transformation"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/falseColorMapping.js#L38-L73 |
6,264 | cornerstonejs/cornerstone | src/falseColorMapping.js | restoreImage | function restoreImage (image) {
if (image.restore && (typeof image.restore === 'function')) {
image.restore();
return true;
}
return false;
} | javascript | function restoreImage (image) {
if (image.restore && (typeof image.restore === 'function')) {
image.restore();
return true;
}
return false;
} | [
"function",
"restoreImage",
"(",
"image",
")",
"{",
"if",
"(",
"image",
".",
"restore",
"&&",
"(",
"typeof",
"image",
".",
"restore",
"===",
"'function'",
")",
")",
"{",
"image",
".",
"restore",
"(",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Restores a false color image to its original version
@param {Image} image A Cornerstone Image Object
@returns {Boolean} True if the image object had a valid restore function, which was run. Otherwise, false. | [
"Restores",
"a",
"false",
"color",
"image",
"to",
"its",
"original",
"version"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/falseColorMapping.js#L99-L107 |
6,265 | cornerstonejs/cornerstone | src/falseColorMapping.js | convertImageToFalseColorImage | function convertImageToFalseColorImage (image, colormap) {
if (image.color && !image.falseColor) {
throw new Error('Color transforms are not implemented yet');
}
// User can pass a colormap id or a colormap object
colormap = ensuresColormap(colormap);
const colormapId = colormap.getId();
// Doesn't do anything if colormapId hasn't changed
if (image.colormapId === colormapId) {
// It has already being converted into a false color image
// Using the colormapId passed as parameter
return false;
}
// Restore the image attributes updated when converting to a false color image
restoreImage(image);
// Convert the image to a false color image
if (colormapId) {
const minPixelValue = image.minPixelValue || 0;
const maxPixelValue = image.maxPixelValue || 255;
image.restore = getRestoreImageMethod(image);
const lookupTable = colormap.createLookupTable();
lookupTable.setTableRange(minPixelValue, maxPixelValue);
// Update the pixel data and render the new image
pixelDataToFalseColorData(image, lookupTable);
// Update min and max pixel values
const pixelValues = getPixelValues(image.getPixelData());
image.minPixelValue = pixelValues.minPixelValue;
image.maxPixelValue = pixelValues.maxPixelValue;
image.windowWidth = 255;
image.windowCenter = 128;
// Cache the last colormapId used for performance
// Then it doesn't need to be re-rendered on next
// Time if the user hasn't updated it
image.colormapId = colormapId;
}
// Return `true` to tell the caller that the image has got updated
return true;
} | javascript | function convertImageToFalseColorImage (image, colormap) {
if (image.color && !image.falseColor) {
throw new Error('Color transforms are not implemented yet');
}
// User can pass a colormap id or a colormap object
colormap = ensuresColormap(colormap);
const colormapId = colormap.getId();
// Doesn't do anything if colormapId hasn't changed
if (image.colormapId === colormapId) {
// It has already being converted into a false color image
// Using the colormapId passed as parameter
return false;
}
// Restore the image attributes updated when converting to a false color image
restoreImage(image);
// Convert the image to a false color image
if (colormapId) {
const minPixelValue = image.minPixelValue || 0;
const maxPixelValue = image.maxPixelValue || 255;
image.restore = getRestoreImageMethod(image);
const lookupTable = colormap.createLookupTable();
lookupTable.setTableRange(minPixelValue, maxPixelValue);
// Update the pixel data and render the new image
pixelDataToFalseColorData(image, lookupTable);
// Update min and max pixel values
const pixelValues = getPixelValues(image.getPixelData());
image.minPixelValue = pixelValues.minPixelValue;
image.maxPixelValue = pixelValues.maxPixelValue;
image.windowWidth = 255;
image.windowCenter = 128;
// Cache the last colormapId used for performance
// Then it doesn't need to be re-rendered on next
// Time if the user hasn't updated it
image.colormapId = colormapId;
}
// Return `true` to tell the caller that the image has got updated
return true;
} | [
"function",
"convertImageToFalseColorImage",
"(",
"image",
",",
"colormap",
")",
"{",
"if",
"(",
"image",
".",
"color",
"&&",
"!",
"image",
".",
"falseColor",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Color transforms are not implemented yet'",
")",
";",
"}",
"// User can pass a colormap id or a colormap object",
"colormap",
"=",
"ensuresColormap",
"(",
"colormap",
")",
";",
"const",
"colormapId",
"=",
"colormap",
".",
"getId",
"(",
")",
";",
"// Doesn't do anything if colormapId hasn't changed",
"if",
"(",
"image",
".",
"colormapId",
"===",
"colormapId",
")",
"{",
"// It has already being converted into a false color image",
"// Using the colormapId passed as parameter",
"return",
"false",
";",
"}",
"// Restore the image attributes updated when converting to a false color image",
"restoreImage",
"(",
"image",
")",
";",
"// Convert the image to a false color image",
"if",
"(",
"colormapId",
")",
"{",
"const",
"minPixelValue",
"=",
"image",
".",
"minPixelValue",
"||",
"0",
";",
"const",
"maxPixelValue",
"=",
"image",
".",
"maxPixelValue",
"||",
"255",
";",
"image",
".",
"restore",
"=",
"getRestoreImageMethod",
"(",
"image",
")",
";",
"const",
"lookupTable",
"=",
"colormap",
".",
"createLookupTable",
"(",
")",
";",
"lookupTable",
".",
"setTableRange",
"(",
"minPixelValue",
",",
"maxPixelValue",
")",
";",
"// Update the pixel data and render the new image",
"pixelDataToFalseColorData",
"(",
"image",
",",
"lookupTable",
")",
";",
"// Update min and max pixel values",
"const",
"pixelValues",
"=",
"getPixelValues",
"(",
"image",
".",
"getPixelData",
"(",
")",
")",
";",
"image",
".",
"minPixelValue",
"=",
"pixelValues",
".",
"minPixelValue",
";",
"image",
".",
"maxPixelValue",
"=",
"pixelValues",
".",
"maxPixelValue",
";",
"image",
".",
"windowWidth",
"=",
"255",
";",
"image",
".",
"windowCenter",
"=",
"128",
";",
"// Cache the last colormapId used for performance",
"// Then it doesn't need to be re-rendered on next",
"// Time if the user hasn't updated it",
"image",
".",
"colormapId",
"=",
"colormapId",
";",
"}",
"// Return `true` to tell the caller that the image has got updated",
"return",
"true",
";",
"}"
] | Convert an image to a false color image
@param {Image} image A Cornerstone Image Object
@param {String|Object} colormap - it can be a colormap object or a colormap id (string)
@returns {Boolean} - Whether or not the image has been converted to a false color image | [
"Convert",
"an",
"image",
"to",
"a",
"false",
"color",
"image"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/falseColorMapping.js#L117-L168 |
6,266 | cornerstonejs/cornerstone | src/falseColorMapping.js | convertToFalseColorImage | function convertToFalseColorImage (element, colormap) {
const enabledElement = getEnabledElement(element);
return convertImageToFalseColorImage(enabledElement.image, colormap);
} | javascript | function convertToFalseColorImage (element, colormap) {
const enabledElement = getEnabledElement(element);
return convertImageToFalseColorImage(enabledElement.image, colormap);
} | [
"function",
"convertToFalseColorImage",
"(",
"element",
",",
"colormap",
")",
"{",
"const",
"enabledElement",
"=",
"getEnabledElement",
"(",
"element",
")",
";",
"return",
"convertImageToFalseColorImage",
"(",
"enabledElement",
".",
"image",
",",
"colormap",
")",
";",
"}"
] | Convert the image of a element to a false color image
@param {HTMLElement} element The Cornerstone element
@param {*} colormap - it can be a colormap object or a colormap id (string)
@returns {void} | [
"Convert",
"the",
"image",
"of",
"a",
"element",
"to",
"a",
"false",
"color",
"image"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/falseColorMapping.js#L178-L183 |
6,267 | cornerstonejs/cornerstone | src/webgl/createProgramFromString.js | compileShader | function compileShader (gl, shaderSource, shaderType) {
// Create the shader object
const shader = gl.createShader(shaderType);
// Set the shader source code.
gl.shaderSource(shader, shaderSource);
// Compile the shader
gl.compileShader(shader);
// Check if it compiled
const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!success && !gl.isContextLost()) {
// Something went wrong during compilation; get the error
const infoLog = gl.getShaderInfoLog(shader);
console.error(`Could not compile shader:\n${infoLog}`);
}
return shader;
} | javascript | function compileShader (gl, shaderSource, shaderType) {
// Create the shader object
const shader = gl.createShader(shaderType);
// Set the shader source code.
gl.shaderSource(shader, shaderSource);
// Compile the shader
gl.compileShader(shader);
// Check if it compiled
const success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!success && !gl.isContextLost()) {
// Something went wrong during compilation; get the error
const infoLog = gl.getShaderInfoLog(shader);
console.error(`Could not compile shader:\n${infoLog}`);
}
return shader;
} | [
"function",
"compileShader",
"(",
"gl",
",",
"shaderSource",
",",
"shaderType",
")",
"{",
"// Create the shader object",
"const",
"shader",
"=",
"gl",
".",
"createShader",
"(",
"shaderType",
")",
";",
"// Set the shader source code.",
"gl",
".",
"shaderSource",
"(",
"shader",
",",
"shaderSource",
")",
";",
"// Compile the shader",
"gl",
".",
"compileShader",
"(",
"shader",
")",
";",
"// Check if it compiled",
"const",
"success",
"=",
"gl",
".",
"getShaderParameter",
"(",
"shader",
",",
"gl",
".",
"COMPILE_STATUS",
")",
";",
"if",
"(",
"!",
"success",
"&&",
"!",
"gl",
".",
"isContextLost",
"(",
")",
")",
"{",
"// Something went wrong during compilation; get the error",
"const",
"infoLog",
"=",
"gl",
".",
"getShaderInfoLog",
"(",
"shader",
")",
";",
"console",
".",
"error",
"(",
"`",
"\\n",
"${",
"infoLog",
"}",
"`",
")",
";",
"}",
"return",
"shader",
";",
"}"
] | Creates and compiles a shader.
@param {!WebGLRenderingContext} gl The WebGL Context.
@param {string} shaderSource The GLSL source code for the shader.
@param {number} shaderType The type of shader, VERTEX_SHADER or FRAGMENT_SHADER.
@return {!WebGLShader} The shader.
@memberof WebGLRendering | [
"Creates",
"and",
"compiles",
"a",
"shader",
"."
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/webgl/createProgramFromString.js#L11-L33 |
6,268 | cornerstonejs/cornerstone | src/webgl/createProgramFromString.js | createProgram | function createProgram (gl, vertexShader, fragmentShader) {
// Create a program.
const program = gl.createProgram();
// Attach the shaders.
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
// Link the program.
gl.linkProgram(program);
// Check if it linked.
const success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!success && !gl.isContextLost()) {
// Something went wrong with the link
const infoLog = gl.getProgramInfoLog(program);
console.error(`WebGL program filed to link:\n${infoLog}`);
}
return program;
} | javascript | function createProgram (gl, vertexShader, fragmentShader) {
// Create a program.
const program = gl.createProgram();
// Attach the shaders.
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
// Link the program.
gl.linkProgram(program);
// Check if it linked.
const success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!success && !gl.isContextLost()) {
// Something went wrong with the link
const infoLog = gl.getProgramInfoLog(program);
console.error(`WebGL program filed to link:\n${infoLog}`);
}
return program;
} | [
"function",
"createProgram",
"(",
"gl",
",",
"vertexShader",
",",
"fragmentShader",
")",
"{",
"// Create a program.",
"const",
"program",
"=",
"gl",
".",
"createProgram",
"(",
")",
";",
"// Attach the shaders.",
"gl",
".",
"attachShader",
"(",
"program",
",",
"vertexShader",
")",
";",
"gl",
".",
"attachShader",
"(",
"program",
",",
"fragmentShader",
")",
";",
"// Link the program.",
"gl",
".",
"linkProgram",
"(",
"program",
")",
";",
"// Check if it linked.",
"const",
"success",
"=",
"gl",
".",
"getProgramParameter",
"(",
"program",
",",
"gl",
".",
"LINK_STATUS",
")",
";",
"if",
"(",
"!",
"success",
"&&",
"!",
"gl",
".",
"isContextLost",
"(",
")",
")",
"{",
"// Something went wrong with the link",
"const",
"infoLog",
"=",
"gl",
".",
"getProgramInfoLog",
"(",
"program",
")",
";",
"console",
".",
"error",
"(",
"`",
"\\n",
"${",
"infoLog",
"}",
"`",
")",
";",
"}",
"return",
"program",
";",
"}"
] | Creates a program from 2 shaders.
@param {!WebGLRenderingContext} gl The WebGL context.
@param {!WebGLShader} vertexShader A vertex shader.
@param {!WebGLShader} fragmentShader A fragment shader.
@return {!WebGLProgram} A program.
@memberof WebGLRendering | [
"Creates",
"a",
"program",
"from",
"2",
"shaders",
"."
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/webgl/createProgramFromString.js#L44-L67 |
6,269 | cornerstonejs/cornerstone | src/internal/getDefaultViewport.js | createViewport | function createViewport () {
const displayedArea = createDefaultDisplayedArea();
return {
scale: 1,
translation: {
x: 0,
y: 0
},
voi: {
windowWidth: undefined,
windowCenter: undefined
},
invert: false,
pixelReplication: false,
rotation: 0,
hflip: false,
vflip: false,
modalityLUT: undefined,
voiLUT: undefined,
colormap: undefined,
labelmap: false,
displayedArea
};
} | javascript | function createViewport () {
const displayedArea = createDefaultDisplayedArea();
return {
scale: 1,
translation: {
x: 0,
y: 0
},
voi: {
windowWidth: undefined,
windowCenter: undefined
},
invert: false,
pixelReplication: false,
rotation: 0,
hflip: false,
vflip: false,
modalityLUT: undefined,
voiLUT: undefined,
colormap: undefined,
labelmap: false,
displayedArea
};
} | [
"function",
"createViewport",
"(",
")",
"{",
"const",
"displayedArea",
"=",
"createDefaultDisplayedArea",
"(",
")",
";",
"return",
"{",
"scale",
":",
"1",
",",
"translation",
":",
"{",
"x",
":",
"0",
",",
"y",
":",
"0",
"}",
",",
"voi",
":",
"{",
"windowWidth",
":",
"undefined",
",",
"windowCenter",
":",
"undefined",
"}",
",",
"invert",
":",
"false",
",",
"pixelReplication",
":",
"false",
",",
"rotation",
":",
"0",
",",
"hflip",
":",
"false",
",",
"vflip",
":",
"false",
",",
"modalityLUT",
":",
"undefined",
",",
"voiLUT",
":",
"undefined",
",",
"colormap",
":",
"undefined",
",",
"labelmap",
":",
"false",
",",
"displayedArea",
"}",
";",
"}"
] | Creates a new viewport object containing default values
@returns {Viewport} viewport object
@memberof Internal | [
"Creates",
"a",
"new",
"viewport",
"object",
"containing",
"default",
"values"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/internal/getDefaultViewport.js#L10-L34 |
6,270 | cornerstonejs/cornerstone | src/colors/lookupTable.js | linearIndexLookupMain | function linearIndexLookupMain (v, p) {
let dIndex;
// NOTE: Added Math.floor since values were not integers? Check VTK source
if (v < p.Range[0]) {
dIndex = p.MaxIndex + BELOW_RANGE_COLOR_INDEX + 1.5;
} else if (v > p.Range[1]) {
dIndex = p.MaxIndex + ABOVE_RANGE_COLOR_INDEX + 1.5;
} else {
dIndex = (v + p.Shift) * p.Scale;
}
return Math.floor(dIndex);
} | javascript | function linearIndexLookupMain (v, p) {
let dIndex;
// NOTE: Added Math.floor since values were not integers? Check VTK source
if (v < p.Range[0]) {
dIndex = p.MaxIndex + BELOW_RANGE_COLOR_INDEX + 1.5;
} else if (v > p.Range[1]) {
dIndex = p.MaxIndex + ABOVE_RANGE_COLOR_INDEX + 1.5;
} else {
dIndex = (v + p.Shift) * p.Scale;
}
return Math.floor(dIndex);
} | [
"function",
"linearIndexLookupMain",
"(",
"v",
",",
"p",
")",
"{",
"let",
"dIndex",
";",
"// NOTE: Added Math.floor since values were not integers? Check VTK source",
"if",
"(",
"v",
"<",
"p",
".",
"Range",
"[",
"0",
"]",
")",
"{",
"dIndex",
"=",
"p",
".",
"MaxIndex",
"+",
"BELOW_RANGE_COLOR_INDEX",
"+",
"1.5",
";",
"}",
"else",
"if",
"(",
"v",
">",
"p",
".",
"Range",
"[",
"1",
"]",
")",
"{",
"dIndex",
"=",
"p",
".",
"MaxIndex",
"+",
"ABOVE_RANGE_COLOR_INDEX",
"+",
"1.5",
";",
"}",
"else",
"{",
"dIndex",
"=",
"(",
"v",
"+",
"p",
".",
"Shift",
")",
"*",
"p",
".",
"Scale",
";",
"}",
"return",
"Math",
".",
"floor",
"(",
"dIndex",
")",
";",
"}"
] | Maps a value to an index in the table
@param {Number} v A double value which table index will be returned.
@param {any} p An object that contains the Table "Range", the table "MaxIndex",
A "Shift" from first value in the table and the table "Scale" value
@returns {Number} The mapped index in the table
@memberof Colors | [
"Maps",
"a",
"value",
"to",
"an",
"index",
"in",
"the",
"table"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/colors/lookupTable.js#L93-L106 |
6,271 | cornerstonejs/cornerstone | src/internal/computeAutoVoi.js | hasVoi | function hasVoi (viewport) {
const hasLut = viewport.voiLUT && viewport.voiLUT.lut && viewport.voiLUT.lut.length > 0;
return hasLut || (viewport.voi.windowWidth !== undefined && viewport.voi.windowCenter !== undefined);
} | javascript | function hasVoi (viewport) {
const hasLut = viewport.voiLUT && viewport.voiLUT.lut && viewport.voiLUT.lut.length > 0;
return hasLut || (viewport.voi.windowWidth !== undefined && viewport.voi.windowCenter !== undefined);
} | [
"function",
"hasVoi",
"(",
"viewport",
")",
"{",
"const",
"hasLut",
"=",
"viewport",
".",
"voiLUT",
"&&",
"viewport",
".",
"voiLUT",
".",
"lut",
"&&",
"viewport",
".",
"voiLUT",
".",
"lut",
".",
"length",
">",
"0",
";",
"return",
"hasLut",
"||",
"(",
"viewport",
".",
"voi",
".",
"windowWidth",
"!==",
"undefined",
"&&",
"viewport",
".",
"voi",
".",
"windowCenter",
"!==",
"undefined",
")",
";",
"}"
] | Check if viewport has voi LUT data
@param {any} viewport The viewport to check for voi LUT data
@returns {Boolean} true viewport has LUT data (Window Width/Window Center or voiLUT). Otherwise, false.
@memberof Internal | [
"Check",
"if",
"viewport",
"has",
"voi",
"LUT",
"data"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/internal/computeAutoVoi.js#L36-L40 |
6,272 | cornerstonejs/cornerstone | src/webgl/textureCache.js | compare | function compare (a, b) {
if (a.timeStamp > b.timeStamp) {
return -1;
}
if (a.timeStamp < b.timeStamp) {
return 1;
}
return 0;
} | javascript | function compare (a, b) {
if (a.timeStamp > b.timeStamp) {
return -1;
}
if (a.timeStamp < b.timeStamp) {
return 1;
}
return 0;
} | [
"function",
"compare",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
".",
"timeStamp",
">",
"b",
".",
"timeStamp",
")",
"{",
"return",
"-",
"1",
";",
"}",
"if",
"(",
"a",
".",
"timeStamp",
"<",
"b",
".",
"timeStamp",
")",
"{",
"return",
"1",
";",
"}",
"return",
"0",
";",
"}"
] | Cache size has been exceeded, create list of images sorted by timeStamp So we can purge the least recently used image | [
"Cache",
"size",
"has",
"been",
"exceeded",
"create",
"list",
"of",
"images",
"sorted",
"by",
"timeStamp",
"So",
"we",
"can",
"purge",
"the",
"least",
"recently",
"used",
"image"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/webgl/textureCache.js#L32-L41 |
6,273 | cornerstonejs/cornerstone | src/webgl/renderer.js | getImageDataType | function getImageDataType (image) {
if (image.color) {
return 'rgb';
}
const pixelData = image.getPixelData();
if (pixelData instanceof Int16Array) {
return 'int16';
}
if (pixelData instanceof Uint16Array) {
return 'uint16';
}
if (pixelData instanceof Int8Array) {
return 'int8';
}
return 'uint8';
} | javascript | function getImageDataType (image) {
if (image.color) {
return 'rgb';
}
const pixelData = image.getPixelData();
if (pixelData instanceof Int16Array) {
return 'int16';
}
if (pixelData instanceof Uint16Array) {
return 'uint16';
}
if (pixelData instanceof Int8Array) {
return 'int8';
}
return 'uint8';
} | [
"function",
"getImageDataType",
"(",
"image",
")",
"{",
"if",
"(",
"image",
".",
"color",
")",
"{",
"return",
"'rgb'",
";",
"}",
"const",
"pixelData",
"=",
"image",
".",
"getPixelData",
"(",
")",
";",
"if",
"(",
"pixelData",
"instanceof",
"Int16Array",
")",
"{",
"return",
"'int16'",
";",
"}",
"if",
"(",
"pixelData",
"instanceof",
"Uint16Array",
")",
"{",
"return",
"'uint16'",
";",
"}",
"if",
"(",
"pixelData",
"instanceof",
"Int8Array",
")",
"{",
"return",
"'int8'",
";",
"}",
"return",
"'uint8'",
";",
"}"
] | Returns the image data type as a string representation.
@param {any} image The cornerstone image object
@returns {string} image data type (rgb, iint16, uint16, int8 and uint8)
@memberof WebGLRendering | [
"Returns",
"the",
"image",
"data",
"type",
"as",
"a",
"string",
"representation",
"."
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/webgl/renderer.js#L119-L139 |
6,274 | cornerstonejs/cornerstone | src/imageCache.js | purgeCacheIfNecessary | function purgeCacheIfNecessary () {
// If max cache size has not been exceeded, do nothing
if (cacheSizeInBytes <= maximumSizeInBytes) {
return;
}
// Cache size has been exceeded, create list of images sorted by timeStamp
// So we can purge the least recently used image
function compare (a, b) {
if (a.timeStamp > b.timeStamp) {
return -1;
}
if (a.timeStamp < b.timeStamp) {
return 1;
}
return 0;
}
cachedImages.sort(compare);
// Remove images as necessary)
while (cacheSizeInBytes > maximumSizeInBytes) {
const lastCachedImage = cachedImages[cachedImages.length - 1];
const imageId = lastCachedImage.imageId;
removeImageLoadObject(imageId);
triggerEvent(events, EVENTS.IMAGE_CACHE_PROMISE_REMOVED, { imageId });
}
const cacheInfo = getCacheInfo();
triggerEvent(events, EVENTS.IMAGE_CACHE_FULL, cacheInfo);
} | javascript | function purgeCacheIfNecessary () {
// If max cache size has not been exceeded, do nothing
if (cacheSizeInBytes <= maximumSizeInBytes) {
return;
}
// Cache size has been exceeded, create list of images sorted by timeStamp
// So we can purge the least recently used image
function compare (a, b) {
if (a.timeStamp > b.timeStamp) {
return -1;
}
if (a.timeStamp < b.timeStamp) {
return 1;
}
return 0;
}
cachedImages.sort(compare);
// Remove images as necessary)
while (cacheSizeInBytes > maximumSizeInBytes) {
const lastCachedImage = cachedImages[cachedImages.length - 1];
const imageId = lastCachedImage.imageId;
removeImageLoadObject(imageId);
triggerEvent(events, EVENTS.IMAGE_CACHE_PROMISE_REMOVED, { imageId });
}
const cacheInfo = getCacheInfo();
triggerEvent(events, EVENTS.IMAGE_CACHE_FULL, cacheInfo);
} | [
"function",
"purgeCacheIfNecessary",
"(",
")",
"{",
"// If max cache size has not been exceeded, do nothing",
"if",
"(",
"cacheSizeInBytes",
"<=",
"maximumSizeInBytes",
")",
"{",
"return",
";",
"}",
"// Cache size has been exceeded, create list of images sorted by timeStamp",
"// So we can purge the least recently used image",
"function",
"compare",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
".",
"timeStamp",
">",
"b",
".",
"timeStamp",
")",
"{",
"return",
"-",
"1",
";",
"}",
"if",
"(",
"a",
".",
"timeStamp",
"<",
"b",
".",
"timeStamp",
")",
"{",
"return",
"1",
";",
"}",
"return",
"0",
";",
"}",
"cachedImages",
".",
"sort",
"(",
"compare",
")",
";",
"// Remove images as necessary)",
"while",
"(",
"cacheSizeInBytes",
">",
"maximumSizeInBytes",
")",
"{",
"const",
"lastCachedImage",
"=",
"cachedImages",
"[",
"cachedImages",
".",
"length",
"-",
"1",
"]",
";",
"const",
"imageId",
"=",
"lastCachedImage",
".",
"imageId",
";",
"removeImageLoadObject",
"(",
"imageId",
")",
";",
"triggerEvent",
"(",
"events",
",",
"EVENTS",
".",
"IMAGE_CACHE_PROMISE_REMOVED",
",",
"{",
"imageId",
"}",
")",
";",
"}",
"const",
"cacheInfo",
"=",
"getCacheInfo",
"(",
")",
";",
"triggerEvent",
"(",
"events",
",",
"EVENTS",
".",
"IMAGE_CACHE_FULL",
",",
"cacheInfo",
")",
";",
"}"
] | Purges the cache if size exceeds maximum
@returns {void} | [
"Purges",
"the",
"cache",
"if",
"size",
"exceeds",
"maximum"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/imageCache.js#L42-L75 |
6,275 | cornerstonejs/cornerstone | src/internal/getCanvas.js | createCanvas | function createCanvas (element) {
const canvas = document.createElement('canvas');
canvas.style.display = 'block';
canvas.classList.add(CANVAS_CSS_CLASS);
element.appendChild(canvas);
return canvas;
} | javascript | function createCanvas (element) {
const canvas = document.createElement('canvas');
canvas.style.display = 'block';
canvas.classList.add(CANVAS_CSS_CLASS);
element.appendChild(canvas);
return canvas;
} | [
"function",
"createCanvas",
"(",
"element",
")",
"{",
"const",
"canvas",
"=",
"document",
".",
"createElement",
"(",
"'canvas'",
")",
";",
"canvas",
".",
"style",
".",
"display",
"=",
"'block'",
";",
"canvas",
".",
"classList",
".",
"add",
"(",
"CANVAS_CSS_CLASS",
")",
";",
"element",
".",
"appendChild",
"(",
"canvas",
")",
";",
"return",
"canvas",
";",
"}"
] | Create a canvas and append it to the element
@param {HTMLElement} element An HTML Element
@return {HTMLElement} canvas A Canvas DOM element | [
"Create",
"a",
"canvas",
"and",
"append",
"it",
"to",
"the",
"element"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/internal/getCanvas.js#L9-L17 |
6,276 | cornerstonejs/cornerstone | src/internal/getVOILut.js | generateNonLinearVOILUT | function generateNonLinearVOILUT (voiLUT) {
// We don't trust the voiLUT.numBitsPerEntry, mainly thanks to Agfa!
const bitsPerEntry = Math.max(...voiLUT.lut).toString(2).length;
const shift = bitsPerEntry - 8;
const minValue = voiLUT.lut[0] >> shift;
const maxValue = voiLUT.lut[voiLUT.lut.length - 1] >> shift;
const maxValueMapped = voiLUT.firstValueMapped + voiLUT.lut.length - 1;
return function (modalityLutValue) {
if (modalityLutValue < voiLUT.firstValueMapped) {
return minValue;
} else if (modalityLutValue >= maxValueMapped) {
return maxValue;
}
return voiLUT.lut[modalityLutValue - voiLUT.firstValueMapped] >> shift;
};
} | javascript | function generateNonLinearVOILUT (voiLUT) {
// We don't trust the voiLUT.numBitsPerEntry, mainly thanks to Agfa!
const bitsPerEntry = Math.max(...voiLUT.lut).toString(2).length;
const shift = bitsPerEntry - 8;
const minValue = voiLUT.lut[0] >> shift;
const maxValue = voiLUT.lut[voiLUT.lut.length - 1] >> shift;
const maxValueMapped = voiLUT.firstValueMapped + voiLUT.lut.length - 1;
return function (modalityLutValue) {
if (modalityLutValue < voiLUT.firstValueMapped) {
return minValue;
} else if (modalityLutValue >= maxValueMapped) {
return maxValue;
}
return voiLUT.lut[modalityLutValue - voiLUT.firstValueMapped] >> shift;
};
} | [
"function",
"generateNonLinearVOILUT",
"(",
"voiLUT",
")",
"{",
"// We don't trust the voiLUT.numBitsPerEntry, mainly thanks to Agfa!",
"const",
"bitsPerEntry",
"=",
"Math",
".",
"max",
"(",
"...",
"voiLUT",
".",
"lut",
")",
".",
"toString",
"(",
"2",
")",
".",
"length",
";",
"const",
"shift",
"=",
"bitsPerEntry",
"-",
"8",
";",
"const",
"minValue",
"=",
"voiLUT",
".",
"lut",
"[",
"0",
"]",
">>",
"shift",
";",
"const",
"maxValue",
"=",
"voiLUT",
".",
"lut",
"[",
"voiLUT",
".",
"lut",
".",
"length",
"-",
"1",
"]",
">>",
"shift",
";",
"const",
"maxValueMapped",
"=",
"voiLUT",
".",
"firstValueMapped",
"+",
"voiLUT",
".",
"lut",
".",
"length",
"-",
"1",
";",
"return",
"function",
"(",
"modalityLutValue",
")",
"{",
"if",
"(",
"modalityLutValue",
"<",
"voiLUT",
".",
"firstValueMapped",
")",
"{",
"return",
"minValue",
";",
"}",
"else",
"if",
"(",
"modalityLutValue",
">=",
"maxValueMapped",
")",
"{",
"return",
"maxValue",
";",
"}",
"return",
"voiLUT",
".",
"lut",
"[",
"modalityLutValue",
"-",
"voiLUT",
".",
"firstValueMapped",
"]",
">>",
"shift",
";",
"}",
";",
"}"
] | Generate a non-linear volume of interest lookup table
@param {LUT} voiLUT Volume of Interest Lookup Table Object
@returns {VOILUTFunction} VOI LUT mapping function
@memberof VOILUT | [
"Generate",
"a",
"non",
"-",
"linear",
"volume",
"of",
"interest",
"lookup",
"table"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/internal/getVOILut.js#L38-L55 |
6,277 | cornerstonejs/cornerstone | src/internal/drawCompositeImage.js | syncViewports | function syncViewports (layers, activeLayer) {
// If we intend to keep the viewport's scale, translation and rotation in sync,
// loop through the layers
layers.forEach((layer) => {
// Don't do anything to the active layer
// Don't do anything if this layer has no viewport
if (layer === activeLayer ||
!layer.viewport ||
!activeLayer.viewport) {
return;
}
if (!layer.syncProps) {
updateLayerSyncProps(layer);
}
const viewportRatio = getViewportRatio(activeLayer, layer);
// Update the layer's translation and scale to keep them in sync with the first image
// based on the ratios between the images
layer.viewport.scale = activeLayer.viewport.scale * viewportRatio;
layer.viewport.rotation = activeLayer.viewport.rotation;
layer.viewport.translation = {
x: (activeLayer.viewport.translation.x / viewportRatio),
y: (activeLayer.viewport.translation.y / viewportRatio)
};
layer.viewport.hflip = activeLayer.viewport.hflip;
layer.viewport.vflip = activeLayer.viewport.vflip;
});
} | javascript | function syncViewports (layers, activeLayer) {
// If we intend to keep the viewport's scale, translation and rotation in sync,
// loop through the layers
layers.forEach((layer) => {
// Don't do anything to the active layer
// Don't do anything if this layer has no viewport
if (layer === activeLayer ||
!layer.viewport ||
!activeLayer.viewport) {
return;
}
if (!layer.syncProps) {
updateLayerSyncProps(layer);
}
const viewportRatio = getViewportRatio(activeLayer, layer);
// Update the layer's translation and scale to keep them in sync with the first image
// based on the ratios between the images
layer.viewport.scale = activeLayer.viewport.scale * viewportRatio;
layer.viewport.rotation = activeLayer.viewport.rotation;
layer.viewport.translation = {
x: (activeLayer.viewport.translation.x / viewportRatio),
y: (activeLayer.viewport.translation.y / viewportRatio)
};
layer.viewport.hflip = activeLayer.viewport.hflip;
layer.viewport.vflip = activeLayer.viewport.vflip;
});
} | [
"function",
"syncViewports",
"(",
"layers",
",",
"activeLayer",
")",
"{",
"// If we intend to keep the viewport's scale, translation and rotation in sync,",
"// loop through the layers",
"layers",
".",
"forEach",
"(",
"(",
"layer",
")",
"=>",
"{",
"// Don't do anything to the active layer",
"// Don't do anything if this layer has no viewport",
"if",
"(",
"layer",
"===",
"activeLayer",
"||",
"!",
"layer",
".",
"viewport",
"||",
"!",
"activeLayer",
".",
"viewport",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"layer",
".",
"syncProps",
")",
"{",
"updateLayerSyncProps",
"(",
"layer",
")",
";",
"}",
"const",
"viewportRatio",
"=",
"getViewportRatio",
"(",
"activeLayer",
",",
"layer",
")",
";",
"// Update the layer's translation and scale to keep them in sync with the first image",
"// based on the ratios between the images",
"layer",
".",
"viewport",
".",
"scale",
"=",
"activeLayer",
".",
"viewport",
".",
"scale",
"*",
"viewportRatio",
";",
"layer",
".",
"viewport",
".",
"rotation",
"=",
"activeLayer",
".",
"viewport",
".",
"rotation",
";",
"layer",
".",
"viewport",
".",
"translation",
"=",
"{",
"x",
":",
"(",
"activeLayer",
".",
"viewport",
".",
"translation",
".",
"x",
"/",
"viewportRatio",
")",
",",
"y",
":",
"(",
"activeLayer",
".",
"viewport",
".",
"translation",
".",
"y",
"/",
"viewportRatio",
")",
"}",
";",
"layer",
".",
"viewport",
".",
"hflip",
"=",
"activeLayer",
".",
"viewport",
".",
"hflip",
";",
"layer",
".",
"viewport",
".",
"vflip",
"=",
"activeLayer",
".",
"viewport",
".",
"vflip",
";",
"}",
")",
";",
"}"
] | Sync all viewports based on active layer's viewport | [
"Sync",
"all",
"viewports",
"based",
"on",
"active",
"layer",
"s",
"viewport"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/internal/drawCompositeImage.js#L30-L59 |
6,278 | cornerstonejs/cornerstone | src/internal/drawCompositeImage.js | renderLayers | function renderLayers (context, layers, invalidated) {
// Loop through each layer and draw it to the canvas
layers.forEach((layer, index) => {
if (!layer.image) {
return;
}
context.save();
// Set the layer's canvas to the pixel coordinate system
layer.canvas = context.canvas;
setToPixelCoordinateSystem(layer, context);
// Render into the layer's canvas
const colormap = layer.viewport.colormap || layer.options.colormap;
const labelmap = layer.viewport.labelmap;
const isInvalid = layer.invalid || invalidated;
if (colormap && colormap !== '' && labelmap === true) {
addLabelMapLayer(layer, isInvalid);
} else if (colormap && colormap !== '') {
addPseudoColorLayer(layer, isInvalid);
} else if (layer.image.color === true) {
addColorLayer(layer, isInvalid);
} else {
// If this is the base layer, use the alpha channel for rendering of the grayscale image
const useAlphaChannel = (index === 0);
addGrayscaleLayer(layer, isInvalid, useAlphaChannel);
}
// Apply any global opacity settings that have been defined for this layer
if (layer.options && layer.options.opacity) {
context.globalAlpha = layer.options.opacity;
} else {
context.globalAlpha = 1;
}
if (layer.options && layer.options.fillStyle) {
context.fillStyle = layer.options.fillStyle;
}
// Set the pixelReplication property before drawing from the layer into the
// composite canvas
context.imageSmoothingEnabled = !layer.viewport.pixelReplication;
context.mozImageSmoothingEnabled = context.imageSmoothingEnabled;
// Draw from the current layer's canvas onto the enabled element's canvas
const sx = layer.viewport.displayedArea.tlhc.x - 1;
const sy = layer.viewport.displayedArea.tlhc.y - 1;
const width = layer.viewport.displayedArea.brhc.x - sx;
const height = layer.viewport.displayedArea.brhc.y - sy;
context.drawImage(layer.canvas, sx, sy, width, height, 0, 0, width, height);
context.restore();
layer.invalid = false;
});
} | javascript | function renderLayers (context, layers, invalidated) {
// Loop through each layer and draw it to the canvas
layers.forEach((layer, index) => {
if (!layer.image) {
return;
}
context.save();
// Set the layer's canvas to the pixel coordinate system
layer.canvas = context.canvas;
setToPixelCoordinateSystem(layer, context);
// Render into the layer's canvas
const colormap = layer.viewport.colormap || layer.options.colormap;
const labelmap = layer.viewport.labelmap;
const isInvalid = layer.invalid || invalidated;
if (colormap && colormap !== '' && labelmap === true) {
addLabelMapLayer(layer, isInvalid);
} else if (colormap && colormap !== '') {
addPseudoColorLayer(layer, isInvalid);
} else if (layer.image.color === true) {
addColorLayer(layer, isInvalid);
} else {
// If this is the base layer, use the alpha channel for rendering of the grayscale image
const useAlphaChannel = (index === 0);
addGrayscaleLayer(layer, isInvalid, useAlphaChannel);
}
// Apply any global opacity settings that have been defined for this layer
if (layer.options && layer.options.opacity) {
context.globalAlpha = layer.options.opacity;
} else {
context.globalAlpha = 1;
}
if (layer.options && layer.options.fillStyle) {
context.fillStyle = layer.options.fillStyle;
}
// Set the pixelReplication property before drawing from the layer into the
// composite canvas
context.imageSmoothingEnabled = !layer.viewport.pixelReplication;
context.mozImageSmoothingEnabled = context.imageSmoothingEnabled;
// Draw from the current layer's canvas onto the enabled element's canvas
const sx = layer.viewport.displayedArea.tlhc.x - 1;
const sy = layer.viewport.displayedArea.tlhc.y - 1;
const width = layer.viewport.displayedArea.brhc.x - sx;
const height = layer.viewport.displayedArea.brhc.y - sy;
context.drawImage(layer.canvas, sx, sy, width, height, 0, 0, width, height);
context.restore();
layer.invalid = false;
});
} | [
"function",
"renderLayers",
"(",
"context",
",",
"layers",
",",
"invalidated",
")",
"{",
"// Loop through each layer and draw it to the canvas",
"layers",
".",
"forEach",
"(",
"(",
"layer",
",",
"index",
")",
"=>",
"{",
"if",
"(",
"!",
"layer",
".",
"image",
")",
"{",
"return",
";",
"}",
"context",
".",
"save",
"(",
")",
";",
"// Set the layer's canvas to the pixel coordinate system",
"layer",
".",
"canvas",
"=",
"context",
".",
"canvas",
";",
"setToPixelCoordinateSystem",
"(",
"layer",
",",
"context",
")",
";",
"// Render into the layer's canvas",
"const",
"colormap",
"=",
"layer",
".",
"viewport",
".",
"colormap",
"||",
"layer",
".",
"options",
".",
"colormap",
";",
"const",
"labelmap",
"=",
"layer",
".",
"viewport",
".",
"labelmap",
";",
"const",
"isInvalid",
"=",
"layer",
".",
"invalid",
"||",
"invalidated",
";",
"if",
"(",
"colormap",
"&&",
"colormap",
"!==",
"''",
"&&",
"labelmap",
"===",
"true",
")",
"{",
"addLabelMapLayer",
"(",
"layer",
",",
"isInvalid",
")",
";",
"}",
"else",
"if",
"(",
"colormap",
"&&",
"colormap",
"!==",
"''",
")",
"{",
"addPseudoColorLayer",
"(",
"layer",
",",
"isInvalid",
")",
";",
"}",
"else",
"if",
"(",
"layer",
".",
"image",
".",
"color",
"===",
"true",
")",
"{",
"addColorLayer",
"(",
"layer",
",",
"isInvalid",
")",
";",
"}",
"else",
"{",
"// If this is the base layer, use the alpha channel for rendering of the grayscale image",
"const",
"useAlphaChannel",
"=",
"(",
"index",
"===",
"0",
")",
";",
"addGrayscaleLayer",
"(",
"layer",
",",
"isInvalid",
",",
"useAlphaChannel",
")",
";",
"}",
"// Apply any global opacity settings that have been defined for this layer",
"if",
"(",
"layer",
".",
"options",
"&&",
"layer",
".",
"options",
".",
"opacity",
")",
"{",
"context",
".",
"globalAlpha",
"=",
"layer",
".",
"options",
".",
"opacity",
";",
"}",
"else",
"{",
"context",
".",
"globalAlpha",
"=",
"1",
";",
"}",
"if",
"(",
"layer",
".",
"options",
"&&",
"layer",
".",
"options",
".",
"fillStyle",
")",
"{",
"context",
".",
"fillStyle",
"=",
"layer",
".",
"options",
".",
"fillStyle",
";",
"}",
"// Set the pixelReplication property before drawing from the layer into the",
"// composite canvas",
"context",
".",
"imageSmoothingEnabled",
"=",
"!",
"layer",
".",
"viewport",
".",
"pixelReplication",
";",
"context",
".",
"mozImageSmoothingEnabled",
"=",
"context",
".",
"imageSmoothingEnabled",
";",
"// Draw from the current layer's canvas onto the enabled element's canvas",
"const",
"sx",
"=",
"layer",
".",
"viewport",
".",
"displayedArea",
".",
"tlhc",
".",
"x",
"-",
"1",
";",
"const",
"sy",
"=",
"layer",
".",
"viewport",
".",
"displayedArea",
".",
"tlhc",
".",
"y",
"-",
"1",
";",
"const",
"width",
"=",
"layer",
".",
"viewport",
".",
"displayedArea",
".",
"brhc",
".",
"x",
"-",
"sx",
";",
"const",
"height",
"=",
"layer",
".",
"viewport",
".",
"displayedArea",
".",
"brhc",
".",
"y",
"-",
"sy",
";",
"context",
".",
"drawImage",
"(",
"layer",
".",
"canvas",
",",
"sx",
",",
"sy",
",",
"width",
",",
"height",
",",
"0",
",",
"0",
",",
"width",
",",
"height",
")",
";",
"context",
".",
"restore",
"(",
")",
";",
"layer",
".",
"invalid",
"=",
"false",
";",
"}",
")",
";",
"}"
] | Internal function to render all layers for a Cornerstone enabled element
@param {CanvasRenderingContext2D} context Canvas context to draw upon
@param {EnabledElementLayer[]} layers The array of all layers for this enabled element
@param {Boolean} invalidated A boolean whether or not this image has been invalidated and must be redrawn
@returns {void}
@memberof Internal | [
"Internal",
"function",
"to",
"render",
"all",
"layers",
"for",
"a",
"Cornerstone",
"enabled",
"element"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/internal/drawCompositeImage.js#L70-L128 |
6,279 | cornerstonejs/cornerstone | src/colors/colormap.js | createLinearSegmentedColormap | function createLinearSegmentedColormap (segmentedData, N, gamma) {
let i;
const lut = [];
N = N === null ? 256 : N;
gamma = gamma === null ? 1 : gamma;
const redLut = makeMappingArray(N, segmentedData.red, gamma);
const greenLut = makeMappingArray(N, segmentedData.green, gamma);
const blueLut = makeMappingArray(N, segmentedData.blue, gamma);
for (i = 0; i < N; i++) {
const red = Math.round(redLut[i] * 255);
const green = Math.round(greenLut[i] * 255);
const blue = Math.round(blueLut[i] * 255);
const rgba = [red, green, blue, 255];
lut.push(rgba);
}
return lut;
} | javascript | function createLinearSegmentedColormap (segmentedData, N, gamma) {
let i;
const lut = [];
N = N === null ? 256 : N;
gamma = gamma === null ? 1 : gamma;
const redLut = makeMappingArray(N, segmentedData.red, gamma);
const greenLut = makeMappingArray(N, segmentedData.green, gamma);
const blueLut = makeMappingArray(N, segmentedData.blue, gamma);
for (i = 0; i < N; i++) {
const red = Math.round(redLut[i] * 255);
const green = Math.round(greenLut[i] * 255);
const blue = Math.round(blueLut[i] * 255);
const rgba = [red, green, blue, 255];
lut.push(rgba);
}
return lut;
} | [
"function",
"createLinearSegmentedColormap",
"(",
"segmentedData",
",",
"N",
",",
"gamma",
")",
"{",
"let",
"i",
";",
"const",
"lut",
"=",
"[",
"]",
";",
"N",
"=",
"N",
"===",
"null",
"?",
"256",
":",
"N",
";",
"gamma",
"=",
"gamma",
"===",
"null",
"?",
"1",
":",
"gamma",
";",
"const",
"redLut",
"=",
"makeMappingArray",
"(",
"N",
",",
"segmentedData",
".",
"red",
",",
"gamma",
")",
";",
"const",
"greenLut",
"=",
"makeMappingArray",
"(",
"N",
",",
"segmentedData",
".",
"green",
",",
"gamma",
")",
";",
"const",
"blueLut",
"=",
"makeMappingArray",
"(",
"N",
",",
"segmentedData",
".",
"blue",
",",
"gamma",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"N",
";",
"i",
"++",
")",
"{",
"const",
"red",
"=",
"Math",
".",
"round",
"(",
"redLut",
"[",
"i",
"]",
"*",
"255",
")",
";",
"const",
"green",
"=",
"Math",
".",
"round",
"(",
"greenLut",
"[",
"i",
"]",
"*",
"255",
")",
";",
"const",
"blue",
"=",
"Math",
".",
"round",
"(",
"blueLut",
"[",
"i",
"]",
"*",
"255",
")",
";",
"const",
"rgba",
"=",
"[",
"red",
",",
"green",
",",
"blue",
",",
"255",
"]",
";",
"lut",
".",
"push",
"(",
"rgba",
")",
";",
"}",
"return",
"lut",
";",
"}"
] | Creates a Colormap based on lookup tables using linear segments.
@param {{red:Array, green:Array, blue:Array}} segmentedData An object with a red, green and blue entries.
Each entry should be a list of x, y0, y1 tuples, forming rows in a table.
@param {Number} N The number of elements in the result Colormap
@param {any} gamma value denotes a "gamma curve" value which adjusts the brightness
at the bottom and top of the Colormap.
@returns {Array} The created Colormap object
@description The lookup table is generated using linear interpolation for each
Primary color, with the 0-1 domain divided into any number of
Segments.
https://github.com/stefanv/matplotlib/blob/3f1a23755e86fef97d51e30e106195f34425c9e3/lib/matplotlib/colors.py#L663
@memberof Colors | [
"Creates",
"a",
"Colormap",
"based",
"on",
"lookup",
"tables",
"using",
"linear",
"segments",
"."
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/colors/colormap.js#L619-L640 |
6,280 | cornerstonejs/cornerstone | src/resize.js | setCanvasSize | function setCanvasSize (element, canvas) {
// The device pixel ratio is 1.0 for normal displays and > 1.0
// For high DPI displays like Retina
/*
This functionality is disabled due to buggy behavior on systems with mixed DPI's. If the canvas
is created on a display with high DPI (e.g. 2.0) and then the browser window is dragged to
a different display with a different DPI (e.g. 1.0), the canvas is not recreated so the pageToPixel
produces incorrect results. I couldn't find any way to determine when the DPI changed other than
by polling which is not very clean. If anyone has any ideas here, please let me know, but for now
we will disable this functionality. We may want
to add a mechanism to optionally enable this functionality if we can determine it is safe to do
so (e.g. iPad or iPhone or perhaps enumerate the displays on the system. I am choosing
to be cautious here since I would rather not have bug reports or safety issues related to this
scenario.
var devicePixelRatio = window.devicePixelRatio;
if(devicePixelRatio === undefined) {
devicePixelRatio = 1.0;
}
*/
// Avoid setting the same value because it flashes the canvas with IE and Edge
if (canvas.width !== element.clientWidth) {
canvas.width = element.clientWidth;
canvas.style.width = `${element.clientWidth}px`;
}
// Avoid setting the same value because it flashes the canvas with IE and Edge
if (canvas.height !== element.clientHeight) {
canvas.height = element.clientHeight;
canvas.style.height = `${element.clientHeight}px`;
}
} | javascript | function setCanvasSize (element, canvas) {
// The device pixel ratio is 1.0 for normal displays and > 1.0
// For high DPI displays like Retina
/*
This functionality is disabled due to buggy behavior on systems with mixed DPI's. If the canvas
is created on a display with high DPI (e.g. 2.0) and then the browser window is dragged to
a different display with a different DPI (e.g. 1.0), the canvas is not recreated so the pageToPixel
produces incorrect results. I couldn't find any way to determine when the DPI changed other than
by polling which is not very clean. If anyone has any ideas here, please let me know, but for now
we will disable this functionality. We may want
to add a mechanism to optionally enable this functionality if we can determine it is safe to do
so (e.g. iPad or iPhone or perhaps enumerate the displays on the system. I am choosing
to be cautious here since I would rather not have bug reports or safety issues related to this
scenario.
var devicePixelRatio = window.devicePixelRatio;
if(devicePixelRatio === undefined) {
devicePixelRatio = 1.0;
}
*/
// Avoid setting the same value because it flashes the canvas with IE and Edge
if (canvas.width !== element.clientWidth) {
canvas.width = element.clientWidth;
canvas.style.width = `${element.clientWidth}px`;
}
// Avoid setting the same value because it flashes the canvas with IE and Edge
if (canvas.height !== element.clientHeight) {
canvas.height = element.clientHeight;
canvas.style.height = `${element.clientHeight}px`;
}
} | [
"function",
"setCanvasSize",
"(",
"element",
",",
"canvas",
")",
"{",
"// The device pixel ratio is 1.0 for normal displays and > 1.0\r",
"// For high DPI displays like Retina\r",
"/*\r\n\r\n This functionality is disabled due to buggy behavior on systems with mixed DPI's. If the canvas\r\n is created on a display with high DPI (e.g. 2.0) and then the browser window is dragged to\r\n a different display with a different DPI (e.g. 1.0), the canvas is not recreated so the pageToPixel\r\n produces incorrect results. I couldn't find any way to determine when the DPI changed other than\r\n by polling which is not very clean. If anyone has any ideas here, please let me know, but for now\r\n we will disable this functionality. We may want\r\n to add a mechanism to optionally enable this functionality if we can determine it is safe to do\r\n so (e.g. iPad or iPhone or perhaps enumerate the displays on the system. I am choosing\r\n to be cautious here since I would rather not have bug reports or safety issues related to this\r\n scenario.\r\n\r\n var devicePixelRatio = window.devicePixelRatio;\r\n if(devicePixelRatio === undefined) {\r\n devicePixelRatio = 1.0;\r\n }\r\n */",
"// Avoid setting the same value because it flashes the canvas with IE and Edge\r",
"if",
"(",
"canvas",
".",
"width",
"!==",
"element",
".",
"clientWidth",
")",
"{",
"canvas",
".",
"width",
"=",
"element",
".",
"clientWidth",
";",
"canvas",
".",
"style",
".",
"width",
"=",
"`",
"${",
"element",
".",
"clientWidth",
"}",
"`",
";",
"}",
"// Avoid setting the same value because it flashes the canvas with IE and Edge\r",
"if",
"(",
"canvas",
".",
"height",
"!==",
"element",
".",
"clientHeight",
")",
"{",
"canvas",
".",
"height",
"=",
"element",
".",
"clientHeight",
";",
"canvas",
".",
"style",
".",
"height",
"=",
"`",
"${",
"element",
".",
"clientHeight",
"}",
"`",
";",
"}",
"}"
] | This module is responsible for enabling an element to display images with cornerstone
@param {HTMLElement} element The DOM element enabled for Cornerstone
@param {HTMLElement} canvas The Canvas DOM element within the DOM element enabled for Cornerstone
@returns {void} | [
"This",
"module",
"is",
"responsible",
"for",
"enabling",
"an",
"element",
"to",
"display",
"images",
"with",
"cornerstone"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/resize.js#L15-L47 |
6,281 | cornerstonejs/cornerstone | src/resize.js | wasFitToWindow | function wasFitToWindow (enabledElement, oldCanvasWidth, oldCanvasHeight) {
const scale = enabledElement.viewport.scale;
const imageSize = getImageSize(enabledElement.image, enabledElement.viewport.rotation);
const imageWidth = Math.round(imageSize.width * scale);
const imageHeight = Math.round(imageSize.height * scale);
const x = enabledElement.viewport.translation.x;
const y = enabledElement.viewport.translation.y;
return (imageWidth === oldCanvasWidth && imageHeight <= oldCanvasHeight) ||
(imageWidth <= oldCanvasWidth && imageHeight === oldCanvasHeight) &&
(x === 0 && y === 0);
} | javascript | function wasFitToWindow (enabledElement, oldCanvasWidth, oldCanvasHeight) {
const scale = enabledElement.viewport.scale;
const imageSize = getImageSize(enabledElement.image, enabledElement.viewport.rotation);
const imageWidth = Math.round(imageSize.width * scale);
const imageHeight = Math.round(imageSize.height * scale);
const x = enabledElement.viewport.translation.x;
const y = enabledElement.viewport.translation.y;
return (imageWidth === oldCanvasWidth && imageHeight <= oldCanvasHeight) ||
(imageWidth <= oldCanvasWidth && imageHeight === oldCanvasHeight) &&
(x === 0 && y === 0);
} | [
"function",
"wasFitToWindow",
"(",
"enabledElement",
",",
"oldCanvasWidth",
",",
"oldCanvasHeight",
")",
"{",
"const",
"scale",
"=",
"enabledElement",
".",
"viewport",
".",
"scale",
";",
"const",
"imageSize",
"=",
"getImageSize",
"(",
"enabledElement",
".",
"image",
",",
"enabledElement",
".",
"viewport",
".",
"rotation",
")",
";",
"const",
"imageWidth",
"=",
"Math",
".",
"round",
"(",
"imageSize",
".",
"width",
"*",
"scale",
")",
";",
"const",
"imageHeight",
"=",
"Math",
".",
"round",
"(",
"imageSize",
".",
"height",
"*",
"scale",
")",
";",
"const",
"x",
"=",
"enabledElement",
".",
"viewport",
".",
"translation",
".",
"x",
";",
"const",
"y",
"=",
"enabledElement",
".",
"viewport",
".",
"translation",
".",
"y",
";",
"return",
"(",
"imageWidth",
"===",
"oldCanvasWidth",
"&&",
"imageHeight",
"<=",
"oldCanvasHeight",
")",
"||",
"(",
"imageWidth",
"<=",
"oldCanvasWidth",
"&&",
"imageHeight",
"===",
"oldCanvasHeight",
")",
"&&",
"(",
"x",
"===",
"0",
"&&",
"y",
"===",
"0",
")",
";",
"}"
] | Checks if the image of a given enabled element fitted the window
before the resize
@param {EnabledElement} enabledElement The Cornerstone Enabled Element
@param {number} oldCanvasWidth The width of the canvas before the resize
@param {number} oldCanvasHeight The height of the canvas before the resize
@return {Boolean} true if it fitted the windows, false otherwise | [
"Checks",
"if",
"the",
"image",
"of",
"a",
"given",
"enabled",
"element",
"fitted",
"the",
"window",
"before",
"the",
"resize"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/resize.js#L58-L69 |
6,282 | cornerstonejs/cornerstone | src/resize.js | relativeRescale | function relativeRescale (enabledElement, oldCanvasWidth, oldCanvasHeight) {
const scale = enabledElement.viewport.scale;
const canvasWidth = enabledElement.canvas.width;
const canvasHeight = enabledElement.canvas.height;
const relWidthChange = canvasWidth / oldCanvasWidth;
const relHeightChange = canvasHeight / oldCanvasHeight;
const relChange = Math.sqrt(relWidthChange * relHeightChange);
enabledElement.viewport.scale = relChange * scale;
} | javascript | function relativeRescale (enabledElement, oldCanvasWidth, oldCanvasHeight) {
const scale = enabledElement.viewport.scale;
const canvasWidth = enabledElement.canvas.width;
const canvasHeight = enabledElement.canvas.height;
const relWidthChange = canvasWidth / oldCanvasWidth;
const relHeightChange = canvasHeight / oldCanvasHeight;
const relChange = Math.sqrt(relWidthChange * relHeightChange);
enabledElement.viewport.scale = relChange * scale;
} | [
"function",
"relativeRescale",
"(",
"enabledElement",
",",
"oldCanvasWidth",
",",
"oldCanvasHeight",
")",
"{",
"const",
"scale",
"=",
"enabledElement",
".",
"viewport",
".",
"scale",
";",
"const",
"canvasWidth",
"=",
"enabledElement",
".",
"canvas",
".",
"width",
";",
"const",
"canvasHeight",
"=",
"enabledElement",
".",
"canvas",
".",
"height",
";",
"const",
"relWidthChange",
"=",
"canvasWidth",
"/",
"oldCanvasWidth",
";",
"const",
"relHeightChange",
"=",
"canvasHeight",
"/",
"oldCanvasHeight",
";",
"const",
"relChange",
"=",
"Math",
".",
"sqrt",
"(",
"relWidthChange",
"*",
"relHeightChange",
")",
";",
"enabledElement",
".",
"viewport",
".",
"scale",
"=",
"relChange",
"*",
"scale",
";",
"}"
] | Rescale the image relative to the changed size of the canvas
@param {EnabledElement} enabledElement The Cornerstone Enabled Element
@param {number} oldCanvasWidth The width of the canvas before the resize
@param {number} oldCanvasHeight The height of the canvas before the resize
@return {void} | [
"Rescale",
"the",
"image",
"relative",
"to",
"the",
"changed",
"size",
"of",
"the",
"canvas"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/resize.js#L79-L88 |
6,283 | cornerstonejs/cornerstone | src/imageLoader.js | loadImageFromImageLoader | function loadImageFromImageLoader (imageId, options) {
const colonIndex = imageId.indexOf(':');
const scheme = imageId.substring(0, colonIndex);
const loader = imageLoaders[scheme];
if (loader === undefined || loader === null) {
if (unknownImageLoader !== undefined) {
return unknownImageLoader(imageId);
}
throw new Error('loadImageFromImageLoader: no image loader for imageId');
}
const imageLoadObject = loader(imageId, options);
// Broadcast an image loaded event once the image is loaded
imageLoadObject.promise.then(function (image) {
triggerEvent(events, EVENTS.IMAGE_LOADED, { image });
}, function (error) {
const errorObject = {
imageId,
error
};
triggerEvent(events, EVENTS.IMAGE_LOAD_FAILED, errorObject);
});
return imageLoadObject;
} | javascript | function loadImageFromImageLoader (imageId, options) {
const colonIndex = imageId.indexOf(':');
const scheme = imageId.substring(0, colonIndex);
const loader = imageLoaders[scheme];
if (loader === undefined || loader === null) {
if (unknownImageLoader !== undefined) {
return unknownImageLoader(imageId);
}
throw new Error('loadImageFromImageLoader: no image loader for imageId');
}
const imageLoadObject = loader(imageId, options);
// Broadcast an image loaded event once the image is loaded
imageLoadObject.promise.then(function (image) {
triggerEvent(events, EVENTS.IMAGE_LOADED, { image });
}, function (error) {
const errorObject = {
imageId,
error
};
triggerEvent(events, EVENTS.IMAGE_LOAD_FAILED, errorObject);
});
return imageLoadObject;
} | [
"function",
"loadImageFromImageLoader",
"(",
"imageId",
",",
"options",
")",
"{",
"const",
"colonIndex",
"=",
"imageId",
".",
"indexOf",
"(",
"':'",
")",
";",
"const",
"scheme",
"=",
"imageId",
".",
"substring",
"(",
"0",
",",
"colonIndex",
")",
";",
"const",
"loader",
"=",
"imageLoaders",
"[",
"scheme",
"]",
";",
"if",
"(",
"loader",
"===",
"undefined",
"||",
"loader",
"===",
"null",
")",
"{",
"if",
"(",
"unknownImageLoader",
"!==",
"undefined",
")",
"{",
"return",
"unknownImageLoader",
"(",
"imageId",
")",
";",
"}",
"throw",
"new",
"Error",
"(",
"'loadImageFromImageLoader: no image loader for imageId'",
")",
";",
"}",
"const",
"imageLoadObject",
"=",
"loader",
"(",
"imageId",
",",
"options",
")",
";",
"// Broadcast an image loaded event once the image is loaded\r",
"imageLoadObject",
".",
"promise",
".",
"then",
"(",
"function",
"(",
"image",
")",
"{",
"triggerEvent",
"(",
"events",
",",
"EVENTS",
".",
"IMAGE_LOADED",
",",
"{",
"image",
"}",
")",
";",
"}",
",",
"function",
"(",
"error",
")",
"{",
"const",
"errorObject",
"=",
"{",
"imageId",
",",
"error",
"}",
";",
"triggerEvent",
"(",
"events",
",",
"EVENTS",
".",
"IMAGE_LOAD_FAILED",
",",
"errorObject",
")",
";",
"}",
")",
";",
"return",
"imageLoadObject",
";",
"}"
] | Load an image using a registered Cornerstone Image Loader.
The image loader that is used will be
determined by the image loader scheme matching against the imageId.
@param {String} imageId A Cornerstone Image Object's imageId
@param {Object} [options] Options to be passed to the Image Loader
@returns {ImageLoadObject} An Object which can be used to act after an image is loaded or loading fails
@memberof ImageLoader | [
"Load",
"an",
"image",
"using",
"a",
"registered",
"Cornerstone",
"Image",
"Loader",
"."
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/imageLoader.js#L27-L55 |
6,284 | cornerstonejs/cornerstone | src/metaData.js | getMetaData | function getMetaData (type, imageId) {
// Invoke each provider in priority order until one returns something
for (let i = 0; i < providers.length; i++) {
const result = providers[i].provider(type, imageId);
if (result !== undefined) {
return result;
}
}
} | javascript | function getMetaData (type, imageId) {
// Invoke each provider in priority order until one returns something
for (let i = 0; i < providers.length; i++) {
const result = providers[i].provider(type, imageId);
if (result !== undefined) {
return result;
}
}
} | [
"function",
"getMetaData",
"(",
"type",
",",
"imageId",
")",
"{",
"// Invoke each provider in priority order until one returns something",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"providers",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"result",
"=",
"providers",
"[",
"i",
"]",
".",
"provider",
"(",
"type",
",",
"imageId",
")",
";",
"if",
"(",
"result",
"!==",
"undefined",
")",
"{",
"return",
"result",
";",
"}",
"}",
"}"
] | Gets metadata from the registered metadata providers. Will call each one from highest priority to lowest
until one responds
@param {String} type The type of metadata requested from the metadata store
@param {String} imageId The Cornerstone Image Object's imageId
@returns {*} The metadata retrieved from the metadata store
@memberof Metadata | [
"Gets",
"metadata",
"from",
"the",
"registered",
"metadata",
"providers",
".",
"Will",
"call",
"each",
"one",
"from",
"highest",
"priority",
"to",
"lowest",
"until",
"one",
"responds"
] | f3b4accef3a700b0719e8373c08c414a1448b563 | https://github.com/cornerstonejs/cornerstone/blob/f3b4accef3a700b0719e8373c08c414a1448b563/src/metaData.js#L63-L72 |
6,285 | wenzhixin/multiple-select | tools/template.js | run | async function run () {
if (options.help || Object.keys(options).length === 1) {
showHelp()
return
}
if (!options.name) {
console.error('You need to input -n, --name argv')
return
}
if (!options.title) {
options.title = options.name.split('-').join(' ')
}
let content = (await fs.readFile(`${__dirname}/example.tpl`)).toString()
content = content.replace(/@title@/, options.title || '')
.replace(/@desc@/, options.desc || '')
await fs.writeFile(`${__dirname}/../docs/examples/${options.name}.html`, content)
console.info(`${options.name}.html`)
let list = (await fs.readFile(`${__dirname}/../docs/_includes/example-list.md`)).toString()
list += `<li><a href="../examples#${options.name}.html">${options.title}</a></li>\n`
await fs.writeFile(`${__dirname}/../docs/_includes/example-list.md`, list)
} | javascript | async function run () {
if (options.help || Object.keys(options).length === 1) {
showHelp()
return
}
if (!options.name) {
console.error('You need to input -n, --name argv')
return
}
if (!options.title) {
options.title = options.name.split('-').join(' ')
}
let content = (await fs.readFile(`${__dirname}/example.tpl`)).toString()
content = content.replace(/@title@/, options.title || '')
.replace(/@desc@/, options.desc || '')
await fs.writeFile(`${__dirname}/../docs/examples/${options.name}.html`, content)
console.info(`${options.name}.html`)
let list = (await fs.readFile(`${__dirname}/../docs/_includes/example-list.md`)).toString()
list += `<li><a href="../examples#${options.name}.html">${options.title}</a></li>\n`
await fs.writeFile(`${__dirname}/../docs/_includes/example-list.md`, list)
} | [
"async",
"function",
"run",
"(",
")",
"{",
"if",
"(",
"options",
".",
"help",
"||",
"Object",
".",
"keys",
"(",
"options",
")",
".",
"length",
"===",
"1",
")",
"{",
"showHelp",
"(",
")",
"return",
"}",
"if",
"(",
"!",
"options",
".",
"name",
")",
"{",
"console",
".",
"error",
"(",
"'You need to input -n, --name argv'",
")",
"return",
"}",
"if",
"(",
"!",
"options",
".",
"title",
")",
"{",
"options",
".",
"title",
"=",
"options",
".",
"name",
".",
"split",
"(",
"'-'",
")",
".",
"join",
"(",
"' '",
")",
"}",
"let",
"content",
"=",
"(",
"await",
"fs",
".",
"readFile",
"(",
"`",
"${",
"__dirname",
"}",
"`",
")",
")",
".",
"toString",
"(",
")",
"content",
"=",
"content",
".",
"replace",
"(",
"/",
"@title@",
"/",
",",
"options",
".",
"title",
"||",
"''",
")",
".",
"replace",
"(",
"/",
"@desc@",
"/",
",",
"options",
".",
"desc",
"||",
"''",
")",
"await",
"fs",
".",
"writeFile",
"(",
"`",
"${",
"__dirname",
"}",
"${",
"options",
".",
"name",
"}",
"`",
",",
"content",
")",
"console",
".",
"info",
"(",
"`",
"${",
"options",
".",
"name",
"}",
"`",
")",
"let",
"list",
"=",
"(",
"await",
"fs",
".",
"readFile",
"(",
"`",
"${",
"__dirname",
"}",
"`",
")",
")",
".",
"toString",
"(",
")",
"list",
"+=",
"`",
"${",
"options",
".",
"name",
"}",
"${",
"options",
".",
"title",
"}",
"\\n",
"`",
"await",
"fs",
".",
"writeFile",
"(",
"`",
"${",
"__dirname",
"}",
"`",
",",
"list",
")",
"}"
] | Perform document file writing.
@returns {void} | [
"Perform",
"document",
"file",
"writing",
"."
] | 063f343a88156979e5747088aa6364bc400c5a51 | https://github.com/wenzhixin/multiple-select/blob/063f343a88156979e5747088aa6364bc400c5a51/tools/template.js#L36-L59 |
6,286 | epoberezkin/ajv | lib/keyword.js | addKeyword | function addKeyword(keyword, definition) {
/* jshint validthis: true */
/* eslint no-shadow: 0 */
var RULES = this.RULES;
if (RULES.keywords[keyword])
throw new Error('Keyword ' + keyword + ' is already defined');
if (!IDENTIFIER.test(keyword))
throw new Error('Keyword ' + keyword + ' is not a valid identifier');
if (definition) {
this.validateKeyword(definition, true);
var dataType = definition.type;
if (Array.isArray(dataType)) {
for (var i=0; i<dataType.length; i++)
_addRule(keyword, dataType[i], definition);
} else {
_addRule(keyword, dataType, definition);
}
var metaSchema = definition.metaSchema;
if (metaSchema) {
if (definition.$data && this._opts.$data) {
metaSchema = {
anyOf: [
metaSchema,
{ '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
]
};
}
definition.validateSchema = this.compile(metaSchema, true);
}
}
RULES.keywords[keyword] = RULES.all[keyword] = true;
function _addRule(keyword, dataType, definition) {
var ruleGroup;
for (var i=0; i<RULES.length; i++) {
var rg = RULES[i];
if (rg.type == dataType) {
ruleGroup = rg;
break;
}
}
if (!ruleGroup) {
ruleGroup = { type: dataType, rules: [] };
RULES.push(ruleGroup);
}
var rule = {
keyword: keyword,
definition: definition,
custom: true,
code: customRuleCode,
implements: definition.implements
};
ruleGroup.rules.push(rule);
RULES.custom[keyword] = rule;
}
return this;
} | javascript | function addKeyword(keyword, definition) {
/* jshint validthis: true */
/* eslint no-shadow: 0 */
var RULES = this.RULES;
if (RULES.keywords[keyword])
throw new Error('Keyword ' + keyword + ' is already defined');
if (!IDENTIFIER.test(keyword))
throw new Error('Keyword ' + keyword + ' is not a valid identifier');
if (definition) {
this.validateKeyword(definition, true);
var dataType = definition.type;
if (Array.isArray(dataType)) {
for (var i=0; i<dataType.length; i++)
_addRule(keyword, dataType[i], definition);
} else {
_addRule(keyword, dataType, definition);
}
var metaSchema = definition.metaSchema;
if (metaSchema) {
if (definition.$data && this._opts.$data) {
metaSchema = {
anyOf: [
metaSchema,
{ '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
]
};
}
definition.validateSchema = this.compile(metaSchema, true);
}
}
RULES.keywords[keyword] = RULES.all[keyword] = true;
function _addRule(keyword, dataType, definition) {
var ruleGroup;
for (var i=0; i<RULES.length; i++) {
var rg = RULES[i];
if (rg.type == dataType) {
ruleGroup = rg;
break;
}
}
if (!ruleGroup) {
ruleGroup = { type: dataType, rules: [] };
RULES.push(ruleGroup);
}
var rule = {
keyword: keyword,
definition: definition,
custom: true,
code: customRuleCode,
implements: definition.implements
};
ruleGroup.rules.push(rule);
RULES.custom[keyword] = rule;
}
return this;
} | [
"function",
"addKeyword",
"(",
"keyword",
",",
"definition",
")",
"{",
"/* jshint validthis: true */",
"/* eslint no-shadow: 0 */",
"var",
"RULES",
"=",
"this",
".",
"RULES",
";",
"if",
"(",
"RULES",
".",
"keywords",
"[",
"keyword",
"]",
")",
"throw",
"new",
"Error",
"(",
"'Keyword '",
"+",
"keyword",
"+",
"' is already defined'",
")",
";",
"if",
"(",
"!",
"IDENTIFIER",
".",
"test",
"(",
"keyword",
")",
")",
"throw",
"new",
"Error",
"(",
"'Keyword '",
"+",
"keyword",
"+",
"' is not a valid identifier'",
")",
";",
"if",
"(",
"definition",
")",
"{",
"this",
".",
"validateKeyword",
"(",
"definition",
",",
"true",
")",
";",
"var",
"dataType",
"=",
"definition",
".",
"type",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"dataType",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"dataType",
".",
"length",
";",
"i",
"++",
")",
"_addRule",
"(",
"keyword",
",",
"dataType",
"[",
"i",
"]",
",",
"definition",
")",
";",
"}",
"else",
"{",
"_addRule",
"(",
"keyword",
",",
"dataType",
",",
"definition",
")",
";",
"}",
"var",
"metaSchema",
"=",
"definition",
".",
"metaSchema",
";",
"if",
"(",
"metaSchema",
")",
"{",
"if",
"(",
"definition",
".",
"$data",
"&&",
"this",
".",
"_opts",
".",
"$data",
")",
"{",
"metaSchema",
"=",
"{",
"anyOf",
":",
"[",
"metaSchema",
",",
"{",
"'$ref'",
":",
"'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#'",
"}",
"]",
"}",
";",
"}",
"definition",
".",
"validateSchema",
"=",
"this",
".",
"compile",
"(",
"metaSchema",
",",
"true",
")",
";",
"}",
"}",
"RULES",
".",
"keywords",
"[",
"keyword",
"]",
"=",
"RULES",
".",
"all",
"[",
"keyword",
"]",
"=",
"true",
";",
"function",
"_addRule",
"(",
"keyword",
",",
"dataType",
",",
"definition",
")",
"{",
"var",
"ruleGroup",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"RULES",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"rg",
"=",
"RULES",
"[",
"i",
"]",
";",
"if",
"(",
"rg",
".",
"type",
"==",
"dataType",
")",
"{",
"ruleGroup",
"=",
"rg",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"ruleGroup",
")",
"{",
"ruleGroup",
"=",
"{",
"type",
":",
"dataType",
",",
"rules",
":",
"[",
"]",
"}",
";",
"RULES",
".",
"push",
"(",
"ruleGroup",
")",
";",
"}",
"var",
"rule",
"=",
"{",
"keyword",
":",
"keyword",
",",
"definition",
":",
"definition",
",",
"custom",
":",
"true",
",",
"code",
":",
"customRuleCode",
",",
"implements",
":",
"definition",
".",
"implements",
"}",
";",
"ruleGroup",
".",
"rules",
".",
"push",
"(",
"rule",
")",
";",
"RULES",
".",
"custom",
"[",
"keyword",
"]",
"=",
"rule",
";",
"}",
"return",
"this",
";",
"}"
] | Define custom keyword
@this Ajv
@param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
@param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
@return {Ajv} this for method chaining | [
"Define",
"custom",
"keyword"
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/keyword.js#L22-L87 |
6,287 | epoberezkin/ajv | lib/keyword.js | validateKeyword | function validateKeyword(definition, throwError) {
validateKeyword.errors = null;
var v = this._validateKeyword = this._validateKeyword
|| this.compile(definitionSchema, true);
if (v(definition)) return true;
validateKeyword.errors = v.errors;
if (throwError)
throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors));
else
return false;
} | javascript | function validateKeyword(definition, throwError) {
validateKeyword.errors = null;
var v = this._validateKeyword = this._validateKeyword
|| this.compile(definitionSchema, true);
if (v(definition)) return true;
validateKeyword.errors = v.errors;
if (throwError)
throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors));
else
return false;
} | [
"function",
"validateKeyword",
"(",
"definition",
",",
"throwError",
")",
"{",
"validateKeyword",
".",
"errors",
"=",
"null",
";",
"var",
"v",
"=",
"this",
".",
"_validateKeyword",
"=",
"this",
".",
"_validateKeyword",
"||",
"this",
".",
"compile",
"(",
"definitionSchema",
",",
"true",
")",
";",
"if",
"(",
"v",
"(",
"definition",
")",
")",
"return",
"true",
";",
"validateKeyword",
".",
"errors",
"=",
"v",
".",
"errors",
";",
"if",
"(",
"throwError",
")",
"throw",
"new",
"Error",
"(",
"'custom keyword definition is invalid: '",
"+",
"this",
".",
"errorsText",
"(",
"v",
".",
"errors",
")",
")",
";",
"else",
"return",
"false",
";",
"}"
] | Validate keyword definition
@this Ajv
@param {Object} definition keyword definition object.
@param {Boolean} throwError true to throw exception if definition is invalid
@return {boolean} validation result | [
"Validate",
"keyword",
"definition"
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/keyword.js#L135-L146 |
6,288 | epoberezkin/ajv | lib/compile/resolve.js | resolveSchema | function resolveSchema(root, ref) {
/* jshint validthis: true */
var p = URI.parse(ref)
, refPath = _getFullPath(p)
, baseId = getFullPath(this._getId(root.schema));
if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
var id = normalizeId(refPath);
var refVal = this._refs[id];
if (typeof refVal == 'string') {
return resolveRecursive.call(this, root, refVal, p);
} else if (refVal instanceof SchemaObject) {
if (!refVal.validate) this._compile(refVal);
root = refVal;
} else {
refVal = this._schemas[id];
if (refVal instanceof SchemaObject) {
if (!refVal.validate) this._compile(refVal);
if (id == normalizeId(ref))
return { schema: refVal, root: root, baseId: baseId };
root = refVal;
} else {
return;
}
}
if (!root.schema) return;
baseId = getFullPath(this._getId(root.schema));
}
return getJsonPointer.call(this, p, baseId, root.schema, root);
} | javascript | function resolveSchema(root, ref) {
/* jshint validthis: true */
var p = URI.parse(ref)
, refPath = _getFullPath(p)
, baseId = getFullPath(this._getId(root.schema));
if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
var id = normalizeId(refPath);
var refVal = this._refs[id];
if (typeof refVal == 'string') {
return resolveRecursive.call(this, root, refVal, p);
} else if (refVal instanceof SchemaObject) {
if (!refVal.validate) this._compile(refVal);
root = refVal;
} else {
refVal = this._schemas[id];
if (refVal instanceof SchemaObject) {
if (!refVal.validate) this._compile(refVal);
if (id == normalizeId(ref))
return { schema: refVal, root: root, baseId: baseId };
root = refVal;
} else {
return;
}
}
if (!root.schema) return;
baseId = getFullPath(this._getId(root.schema));
}
return getJsonPointer.call(this, p, baseId, root.schema, root);
} | [
"function",
"resolveSchema",
"(",
"root",
",",
"ref",
")",
"{",
"/* jshint validthis: true */",
"var",
"p",
"=",
"URI",
".",
"parse",
"(",
"ref",
")",
",",
"refPath",
"=",
"_getFullPath",
"(",
"p",
")",
",",
"baseId",
"=",
"getFullPath",
"(",
"this",
".",
"_getId",
"(",
"root",
".",
"schema",
")",
")",
";",
"if",
"(",
"Object",
".",
"keys",
"(",
"root",
".",
"schema",
")",
".",
"length",
"===",
"0",
"||",
"refPath",
"!==",
"baseId",
")",
"{",
"var",
"id",
"=",
"normalizeId",
"(",
"refPath",
")",
";",
"var",
"refVal",
"=",
"this",
".",
"_refs",
"[",
"id",
"]",
";",
"if",
"(",
"typeof",
"refVal",
"==",
"'string'",
")",
"{",
"return",
"resolveRecursive",
".",
"call",
"(",
"this",
",",
"root",
",",
"refVal",
",",
"p",
")",
";",
"}",
"else",
"if",
"(",
"refVal",
"instanceof",
"SchemaObject",
")",
"{",
"if",
"(",
"!",
"refVal",
".",
"validate",
")",
"this",
".",
"_compile",
"(",
"refVal",
")",
";",
"root",
"=",
"refVal",
";",
"}",
"else",
"{",
"refVal",
"=",
"this",
".",
"_schemas",
"[",
"id",
"]",
";",
"if",
"(",
"refVal",
"instanceof",
"SchemaObject",
")",
"{",
"if",
"(",
"!",
"refVal",
".",
"validate",
")",
"this",
".",
"_compile",
"(",
"refVal",
")",
";",
"if",
"(",
"id",
"==",
"normalizeId",
"(",
"ref",
")",
")",
"return",
"{",
"schema",
":",
"refVal",
",",
"root",
":",
"root",
",",
"baseId",
":",
"baseId",
"}",
";",
"root",
"=",
"refVal",
";",
"}",
"else",
"{",
"return",
";",
"}",
"}",
"if",
"(",
"!",
"root",
".",
"schema",
")",
"return",
";",
"baseId",
"=",
"getFullPath",
"(",
"this",
".",
"_getId",
"(",
"root",
".",
"schema",
")",
")",
";",
"}",
"return",
"getJsonPointer",
".",
"call",
"(",
"this",
",",
"p",
",",
"baseId",
",",
"root",
".",
"schema",
",",
"root",
")",
";",
"}"
] | Resolve schema, its root and baseId
@this Ajv
@param {Object} root root object with properties schema, refVal, refs
@param {String} ref reference to resolve
@return {Object} object with properties schema, root, baseId | [
"Resolve",
"schema",
"its",
"root",
"and",
"baseId"
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/compile/resolve.js#L68-L96 |
6,289 | epoberezkin/ajv | lib/ajv.js | compile | function compile(schema, _meta) {
var schemaObj = this._addSchema(schema, undefined, _meta);
return schemaObj.validate || this._compile(schemaObj);
} | javascript | function compile(schema, _meta) {
var schemaObj = this._addSchema(schema, undefined, _meta);
return schemaObj.validate || this._compile(schemaObj);
} | [
"function",
"compile",
"(",
"schema",
",",
"_meta",
")",
"{",
"var",
"schemaObj",
"=",
"this",
".",
"_addSchema",
"(",
"schema",
",",
"undefined",
",",
"_meta",
")",
";",
"return",
"schemaObj",
".",
"validate",
"||",
"this",
".",
"_compile",
"(",
"schemaObj",
")",
";",
"}"
] | Create validating function for passed schema.
@this Ajv
@param {Object} schema schema object
@param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
@return {Function} validating function | [
"Create",
"validating",
"function",
"for",
"passed",
"schema",
"."
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/ajv.js#L111-L114 |
6,290 | epoberezkin/ajv | lib/ajv.js | addSchema | function addSchema(schema, key, _skipValidation, _meta) {
if (Array.isArray(schema)){
for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
return this;
}
var id = this._getId(schema);
if (id !== undefined && typeof id != 'string')
throw new Error('schema id must be string');
key = resolve.normalizeId(key || id);
checkUnique(this, key);
this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
return this;
} | javascript | function addSchema(schema, key, _skipValidation, _meta) {
if (Array.isArray(schema)){
for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
return this;
}
var id = this._getId(schema);
if (id !== undefined && typeof id != 'string')
throw new Error('schema id must be string');
key = resolve.normalizeId(key || id);
checkUnique(this, key);
this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
return this;
} | [
"function",
"addSchema",
"(",
"schema",
",",
"key",
",",
"_skipValidation",
",",
"_meta",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"schema",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"schema",
".",
"length",
";",
"i",
"++",
")",
"this",
".",
"addSchema",
"(",
"schema",
"[",
"i",
"]",
",",
"undefined",
",",
"_skipValidation",
",",
"_meta",
")",
";",
"return",
"this",
";",
"}",
"var",
"id",
"=",
"this",
".",
"_getId",
"(",
"schema",
")",
";",
"if",
"(",
"id",
"!==",
"undefined",
"&&",
"typeof",
"id",
"!=",
"'string'",
")",
"throw",
"new",
"Error",
"(",
"'schema id must be string'",
")",
";",
"key",
"=",
"resolve",
".",
"normalizeId",
"(",
"key",
"||",
"id",
")",
";",
"checkUnique",
"(",
"this",
",",
"key",
")",
";",
"this",
".",
"_schemas",
"[",
"key",
"]",
"=",
"this",
".",
"_addSchema",
"(",
"schema",
",",
"_skipValidation",
",",
"_meta",
",",
"true",
")",
";",
"return",
"this",
";",
"}"
] | Adds schema to the instance.
@this Ajv
@param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
@param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
@param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
@param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
@return {Ajv} this for method chaining | [
"Adds",
"schema",
"to",
"the",
"instance",
"."
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/ajv.js#L126-L138 |
6,291 | epoberezkin/ajv | lib/ajv.js | getSchema | function getSchema(keyRef) {
var schemaObj = _getSchemaObj(this, keyRef);
switch (typeof schemaObj) {
case 'object': return schemaObj.validate || this._compile(schemaObj);
case 'string': return this.getSchema(schemaObj);
case 'undefined': return _getSchemaFragment(this, keyRef);
}
} | javascript | function getSchema(keyRef) {
var schemaObj = _getSchemaObj(this, keyRef);
switch (typeof schemaObj) {
case 'object': return schemaObj.validate || this._compile(schemaObj);
case 'string': return this.getSchema(schemaObj);
case 'undefined': return _getSchemaFragment(this, keyRef);
}
} | [
"function",
"getSchema",
"(",
"keyRef",
")",
"{",
"var",
"schemaObj",
"=",
"_getSchemaObj",
"(",
"this",
",",
"keyRef",
")",
";",
"switch",
"(",
"typeof",
"schemaObj",
")",
"{",
"case",
"'object'",
":",
"return",
"schemaObj",
".",
"validate",
"||",
"this",
".",
"_compile",
"(",
"schemaObj",
")",
";",
"case",
"'string'",
":",
"return",
"this",
".",
"getSchema",
"(",
"schemaObj",
")",
";",
"case",
"'undefined'",
":",
"return",
"_getSchemaFragment",
"(",
"this",
",",
"keyRef",
")",
";",
"}",
"}"
] | Get compiled schema from the instance by `key` or `ref`.
@this Ajv
@param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
@return {Function} schema validating function (with property `schema`). | [
"Get",
"compiled",
"schema",
"from",
"the",
"instance",
"by",
"key",
"or",
"ref",
"."
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/ajv.js#L200-L207 |
6,292 | epoberezkin/ajv | lib/ajv.js | errorsText | function errorsText(errors, options) {
errors = errors || this.errors;
if (!errors) return 'No errors';
options = options || {};
var separator = options.separator === undefined ? ', ' : options.separator;
var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
var text = '';
for (var i=0; i<errors.length; i++) {
var e = errors[i];
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
}
return text.slice(0, -separator.length);
} | javascript | function errorsText(errors, options) {
errors = errors || this.errors;
if (!errors) return 'No errors';
options = options || {};
var separator = options.separator === undefined ? ', ' : options.separator;
var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
var text = '';
for (var i=0; i<errors.length; i++) {
var e = errors[i];
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
}
return text.slice(0, -separator.length);
} | [
"function",
"errorsText",
"(",
"errors",
",",
"options",
")",
"{",
"errors",
"=",
"errors",
"||",
"this",
".",
"errors",
";",
"if",
"(",
"!",
"errors",
")",
"return",
"'No errors'",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"separator",
"=",
"options",
".",
"separator",
"===",
"undefined",
"?",
"', '",
":",
"options",
".",
"separator",
";",
"var",
"dataVar",
"=",
"options",
".",
"dataVar",
"===",
"undefined",
"?",
"'data'",
":",
"options",
".",
"dataVar",
";",
"var",
"text",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"errors",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"e",
"=",
"errors",
"[",
"i",
"]",
";",
"if",
"(",
"e",
")",
"text",
"+=",
"dataVar",
"+",
"e",
".",
"dataPath",
"+",
"' '",
"+",
"e",
".",
"message",
"+",
"separator",
";",
"}",
"return",
"text",
".",
"slice",
"(",
"0",
",",
"-",
"separator",
".",
"length",
")",
";",
"}"
] | Convert array of error message objects to string
@this Ajv
@param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
@param {Object} options optional options with properties `separator` and `dataVar`.
@return {String} human readable string with all errors descriptions | [
"Convert",
"array",
"of",
"error",
"message",
"objects",
"to",
"string"
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/ajv.js#L410-L423 |
6,293 | epoberezkin/ajv | lib/ajv.js | addFormat | function addFormat(name, format) {
if (typeof format == 'string') format = new RegExp(format);
this._formats[name] = format;
return this;
} | javascript | function addFormat(name, format) {
if (typeof format == 'string') format = new RegExp(format);
this._formats[name] = format;
return this;
} | [
"function",
"addFormat",
"(",
"name",
",",
"format",
")",
"{",
"if",
"(",
"typeof",
"format",
"==",
"'string'",
")",
"format",
"=",
"new",
"RegExp",
"(",
"format",
")",
";",
"this",
".",
"_formats",
"[",
"name",
"]",
"=",
"format",
";",
"return",
"this",
";",
"}"
] | Add custom format
@this Ajv
@param {String} name format name
@param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
@return {Ajv} this for method chaining | [
"Add",
"custom",
"format"
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/ajv.js#L433-L437 |
6,294 | epoberezkin/ajv | lib/compile/index.js | checkCompiling | function checkCompiling(schema, root, baseId) {
/* jshint validthis: true */
var index = compIndex.call(this, schema, root, baseId);
if (index >= 0) return { index: index, compiling: true };
index = this._compilations.length;
this._compilations[index] = {
schema: schema,
root: root,
baseId: baseId
};
return { index: index, compiling: false };
} | javascript | function checkCompiling(schema, root, baseId) {
/* jshint validthis: true */
var index = compIndex.call(this, schema, root, baseId);
if (index >= 0) return { index: index, compiling: true };
index = this._compilations.length;
this._compilations[index] = {
schema: schema,
root: root,
baseId: baseId
};
return { index: index, compiling: false };
} | [
"function",
"checkCompiling",
"(",
"schema",
",",
"root",
",",
"baseId",
")",
"{",
"/* jshint validthis: true */",
"var",
"index",
"=",
"compIndex",
".",
"call",
"(",
"this",
",",
"schema",
",",
"root",
",",
"baseId",
")",
";",
"if",
"(",
"index",
">=",
"0",
")",
"return",
"{",
"index",
":",
"index",
",",
"compiling",
":",
"true",
"}",
";",
"index",
"=",
"this",
".",
"_compilations",
".",
"length",
";",
"this",
".",
"_compilations",
"[",
"index",
"]",
"=",
"{",
"schema",
":",
"schema",
",",
"root",
":",
"root",
",",
"baseId",
":",
"baseId",
"}",
";",
"return",
"{",
"index",
":",
"index",
",",
"compiling",
":",
"false",
"}",
";",
"}"
] | Checks if the schema is currently compiled
@this Ajv
@param {Object} schema schema to compile
@param {Object} root root object
@param {String} baseId base schema ID
@return {Object} object with properties "index" (compilation index) and "compiling" (boolean) | [
"Checks",
"if",
"the",
"schema",
"is",
"currently",
"compiled"
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/compile/index.js#L315-L326 |
6,295 | epoberezkin/ajv | lib/compile/index.js | endCompiling | function endCompiling(schema, root, baseId) {
/* jshint validthis: true */
var i = compIndex.call(this, schema, root, baseId);
if (i >= 0) this._compilations.splice(i, 1);
} | javascript | function endCompiling(schema, root, baseId) {
/* jshint validthis: true */
var i = compIndex.call(this, schema, root, baseId);
if (i >= 0) this._compilations.splice(i, 1);
} | [
"function",
"endCompiling",
"(",
"schema",
",",
"root",
",",
"baseId",
")",
"{",
"/* jshint validthis: true */",
"var",
"i",
"=",
"compIndex",
".",
"call",
"(",
"this",
",",
"schema",
",",
"root",
",",
"baseId",
")",
";",
"if",
"(",
"i",
">=",
"0",
")",
"this",
".",
"_compilations",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"}"
] | Removes the schema from the currently compiled list
@this Ajv
@param {Object} schema schema to compile
@param {Object} root root object
@param {String} baseId base schema ID | [
"Removes",
"the",
"schema",
"from",
"the",
"currently",
"compiled",
"list"
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/compile/index.js#L336-L340 |
6,296 | epoberezkin/ajv | lib/compile/index.js | compIndex | function compIndex(schema, root, baseId) {
/* jshint validthis: true */
for (var i=0; i<this._compilations.length; i++) {
var c = this._compilations[i];
if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
}
return -1;
} | javascript | function compIndex(schema, root, baseId) {
/* jshint validthis: true */
for (var i=0; i<this._compilations.length; i++) {
var c = this._compilations[i];
if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
}
return -1;
} | [
"function",
"compIndex",
"(",
"schema",
",",
"root",
",",
"baseId",
")",
"{",
"/* jshint validthis: true */",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"_compilations",
".",
"length",
";",
"i",
"++",
")",
"{",
"var",
"c",
"=",
"this",
".",
"_compilations",
"[",
"i",
"]",
";",
"if",
"(",
"c",
".",
"schema",
"==",
"schema",
"&&",
"c",
".",
"root",
"==",
"root",
"&&",
"c",
".",
"baseId",
"==",
"baseId",
")",
"return",
"i",
";",
"}",
"return",
"-",
"1",
";",
"}"
] | Index of schema compilation in the currently compiled list
@this Ajv
@param {Object} schema schema to compile
@param {Object} root root object
@param {String} baseId base schema ID
@return {Integer} compilation index | [
"Index",
"of",
"schema",
"compilation",
"in",
"the",
"currently",
"compiled",
"list"
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/compile/index.js#L351-L358 |
6,297 | epoberezkin/ajv | lib/compile/async.js | compileAsync | function compileAsync(schema, meta, callback) {
/* eslint no-shadow: 0 */
/* global Promise */
/* jshint validthis: true */
var self = this;
if (typeof this._opts.loadSchema != 'function')
throw new Error('options.loadSchema should be a function');
if (typeof meta == 'function') {
callback = meta;
meta = undefined;
}
var p = loadMetaSchemaOf(schema).then(function () {
var schemaObj = self._addSchema(schema, undefined, meta);
return schemaObj.validate || _compileAsync(schemaObj);
});
if (callback) {
p.then(
function(v) { callback(null, v); },
callback
);
}
return p;
function loadMetaSchemaOf(sch) {
var $schema = sch.$schema;
return $schema && !self.getSchema($schema)
? compileAsync.call(self, { $ref: $schema }, true)
: Promise.resolve();
}
function _compileAsync(schemaObj) {
try { return self._compile(schemaObj); }
catch(e) {
if (e instanceof MissingRefError) return loadMissingSchema(e);
throw e;
}
function loadMissingSchema(e) {
var ref = e.missingSchema;
if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
var schemaPromise = self._loadingSchemas[ref];
if (!schemaPromise) {
schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
schemaPromise.then(removePromise, removePromise);
}
return schemaPromise.then(function (sch) {
if (!added(ref)) {
return loadMetaSchemaOf(sch).then(function () {
if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
});
}
}).then(function() {
return _compileAsync(schemaObj);
});
function removePromise() {
delete self._loadingSchemas[ref];
}
function added(ref) {
return self._refs[ref] || self._schemas[ref];
}
}
}
} | javascript | function compileAsync(schema, meta, callback) {
/* eslint no-shadow: 0 */
/* global Promise */
/* jshint validthis: true */
var self = this;
if (typeof this._opts.loadSchema != 'function')
throw new Error('options.loadSchema should be a function');
if (typeof meta == 'function') {
callback = meta;
meta = undefined;
}
var p = loadMetaSchemaOf(schema).then(function () {
var schemaObj = self._addSchema(schema, undefined, meta);
return schemaObj.validate || _compileAsync(schemaObj);
});
if (callback) {
p.then(
function(v) { callback(null, v); },
callback
);
}
return p;
function loadMetaSchemaOf(sch) {
var $schema = sch.$schema;
return $schema && !self.getSchema($schema)
? compileAsync.call(self, { $ref: $schema }, true)
: Promise.resolve();
}
function _compileAsync(schemaObj) {
try { return self._compile(schemaObj); }
catch(e) {
if (e instanceof MissingRefError) return loadMissingSchema(e);
throw e;
}
function loadMissingSchema(e) {
var ref = e.missingSchema;
if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
var schemaPromise = self._loadingSchemas[ref];
if (!schemaPromise) {
schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
schemaPromise.then(removePromise, removePromise);
}
return schemaPromise.then(function (sch) {
if (!added(ref)) {
return loadMetaSchemaOf(sch).then(function () {
if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
});
}
}).then(function() {
return _compileAsync(schemaObj);
});
function removePromise() {
delete self._loadingSchemas[ref];
}
function added(ref) {
return self._refs[ref] || self._schemas[ref];
}
}
}
} | [
"function",
"compileAsync",
"(",
"schema",
",",
"meta",
",",
"callback",
")",
"{",
"/* eslint no-shadow: 0 */",
"/* global Promise */",
"/* jshint validthis: true */",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"typeof",
"this",
".",
"_opts",
".",
"loadSchema",
"!=",
"'function'",
")",
"throw",
"new",
"Error",
"(",
"'options.loadSchema should be a function'",
")",
";",
"if",
"(",
"typeof",
"meta",
"==",
"'function'",
")",
"{",
"callback",
"=",
"meta",
";",
"meta",
"=",
"undefined",
";",
"}",
"var",
"p",
"=",
"loadMetaSchemaOf",
"(",
"schema",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"schemaObj",
"=",
"self",
".",
"_addSchema",
"(",
"schema",
",",
"undefined",
",",
"meta",
")",
";",
"return",
"schemaObj",
".",
"validate",
"||",
"_compileAsync",
"(",
"schemaObj",
")",
";",
"}",
")",
";",
"if",
"(",
"callback",
")",
"{",
"p",
".",
"then",
"(",
"function",
"(",
"v",
")",
"{",
"callback",
"(",
"null",
",",
"v",
")",
";",
"}",
",",
"callback",
")",
";",
"}",
"return",
"p",
";",
"function",
"loadMetaSchemaOf",
"(",
"sch",
")",
"{",
"var",
"$schema",
"=",
"sch",
".",
"$schema",
";",
"return",
"$schema",
"&&",
"!",
"self",
".",
"getSchema",
"(",
"$schema",
")",
"?",
"compileAsync",
".",
"call",
"(",
"self",
",",
"{",
"$ref",
":",
"$schema",
"}",
",",
"true",
")",
":",
"Promise",
".",
"resolve",
"(",
")",
";",
"}",
"function",
"_compileAsync",
"(",
"schemaObj",
")",
"{",
"try",
"{",
"return",
"self",
".",
"_compile",
"(",
"schemaObj",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"MissingRefError",
")",
"return",
"loadMissingSchema",
"(",
"e",
")",
";",
"throw",
"e",
";",
"}",
"function",
"loadMissingSchema",
"(",
"e",
")",
"{",
"var",
"ref",
"=",
"e",
".",
"missingSchema",
";",
"if",
"(",
"added",
"(",
"ref",
")",
")",
"throw",
"new",
"Error",
"(",
"'Schema '",
"+",
"ref",
"+",
"' is loaded but '",
"+",
"e",
".",
"missingRef",
"+",
"' cannot be resolved'",
")",
";",
"var",
"schemaPromise",
"=",
"self",
".",
"_loadingSchemas",
"[",
"ref",
"]",
";",
"if",
"(",
"!",
"schemaPromise",
")",
"{",
"schemaPromise",
"=",
"self",
".",
"_loadingSchemas",
"[",
"ref",
"]",
"=",
"self",
".",
"_opts",
".",
"loadSchema",
"(",
"ref",
")",
";",
"schemaPromise",
".",
"then",
"(",
"removePromise",
",",
"removePromise",
")",
";",
"}",
"return",
"schemaPromise",
".",
"then",
"(",
"function",
"(",
"sch",
")",
"{",
"if",
"(",
"!",
"added",
"(",
"ref",
")",
")",
"{",
"return",
"loadMetaSchemaOf",
"(",
"sch",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"added",
"(",
"ref",
")",
")",
"self",
".",
"addSchema",
"(",
"sch",
",",
"ref",
",",
"undefined",
",",
"meta",
")",
";",
"}",
")",
";",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"_compileAsync",
"(",
"schemaObj",
")",
";",
"}",
")",
";",
"function",
"removePromise",
"(",
")",
"{",
"delete",
"self",
".",
"_loadingSchemas",
"[",
"ref",
"]",
";",
"}",
"function",
"added",
"(",
"ref",
")",
"{",
"return",
"self",
".",
"_refs",
"[",
"ref",
"]",
"||",
"self",
".",
"_schemas",
"[",
"ref",
"]",
";",
"}",
"}",
"}",
"}"
] | Creates validating function for passed schema with asynchronous loading of missing schemas.
`loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
@this Ajv
@param {Object} schema schema object
@param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
@param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
@return {Promise} promise that resolves with a validating function. | [
"Creates",
"validating",
"function",
"for",
"passed",
"schema",
"with",
"asynchronous",
"loading",
"of",
"missing",
"schemas",
".",
"loadSchema",
"option",
"should",
"be",
"a",
"function",
"that",
"accepts",
"schema",
"uri",
"and",
"returns",
"promise",
"that",
"resolves",
"with",
"the",
"schema",
"."
] | ab841b462ec4baff37d2a7319cef13820b53d963 | https://github.com/epoberezkin/ajv/blob/ab841b462ec4baff37d2a7319cef13820b53d963/lib/compile/async.js#L17-L90 |
6,298 | jdorn/json-editor | dist/jsoneditor.js | function() {
var self = this, vars, j;
// If this editor needs to be rendered by a macro template
if(this.template) {
vars = this.getWatchedFieldValues();
this.setValue(this.template(vars),false,true);
}
this._super();
} | javascript | function() {
var self = this, vars, j;
// If this editor needs to be rendered by a macro template
if(this.template) {
vars = this.getWatchedFieldValues();
this.setValue(this.template(vars),false,true);
}
this._super();
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
",",
"vars",
",",
"j",
";",
"// If this editor needs to be rendered by a macro template",
"if",
"(",
"this",
".",
"template",
")",
"{",
"vars",
"=",
"this",
".",
"getWatchedFieldValues",
"(",
")",
";",
"this",
".",
"setValue",
"(",
"this",
".",
"template",
"(",
"vars",
")",
",",
"false",
",",
"true",
")",
";",
"}",
"this",
".",
"_super",
"(",
")",
";",
"}"
] | Re-calculates the value if needed | [
"Re",
"-",
"calculates",
"the",
"value",
"if",
"needed"
] | 682120870a9c7df36bd79969c5b883e0a189d92d | https://github.com/jdorn/json-editor/blob/682120870a9c7df36bd79969c5b883e0a189d92d/dist/jsoneditor.js#L2285-L2295 |
|
6,299 | maptalks/maptalks.js | src/geometry/ext/Geometry.Events.js | function (event, type) {
if (!this.getMap()) {
return;
}
const eventType = type || this._getEventTypeToFire(event);
if (eventType === 'contextmenu' && this.listens('contextmenu')) {
stopPropagation(event);
preventDefault(event);
}
const params = this._getEventParams(event);
this._fireEvent(eventType, params);
} | javascript | function (event, type) {
if (!this.getMap()) {
return;
}
const eventType = type || this._getEventTypeToFire(event);
if (eventType === 'contextmenu' && this.listens('contextmenu')) {
stopPropagation(event);
preventDefault(event);
}
const params = this._getEventParams(event);
this._fireEvent(eventType, params);
} | [
"function",
"(",
"event",
",",
"type",
")",
"{",
"if",
"(",
"!",
"this",
".",
"getMap",
"(",
")",
")",
"{",
"return",
";",
"}",
"const",
"eventType",
"=",
"type",
"||",
"this",
".",
"_getEventTypeToFire",
"(",
"event",
")",
";",
"if",
"(",
"eventType",
"===",
"'contextmenu'",
"&&",
"this",
".",
"listens",
"(",
"'contextmenu'",
")",
")",
"{",
"stopPropagation",
"(",
"event",
")",
";",
"preventDefault",
"(",
"event",
")",
";",
"}",
"const",
"params",
"=",
"this",
".",
"_getEventParams",
"(",
"event",
")",
";",
"this",
".",
"_fireEvent",
"(",
"eventType",
",",
"params",
")",
";",
"}"
] | The event handler for all the events.
@param {Event} event - dom event
@private | [
"The",
"event",
"handler",
"for",
"all",
"the",
"events",
"."
] | 8ee32cb20c5ea79dd687e1076c1310a288955792 | https://github.com/maptalks/maptalks.js/blob/8ee32cb20c5ea79dd687e1076c1310a288955792/src/geometry/ext/Geometry.Events.js#L10-L21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.