repo stringlengths 5 67 | path stringlengths 4 116 | func_name stringlengths 0 58 | original_string stringlengths 52 373k | language stringclasses 1
value | code stringlengths 52 373k | code_tokens list | docstring stringlengths 4 11.8k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 86 226 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
jonschlinkert/github-base | lib/utils.js | interpolate | function interpolate(str, context) {
const opts = { ...context.options };
let val = opts.apiurl + str.replace(/:([\w_]+)/g, (m, key) => {
opts.params = union(opts.params, key);
let val = get(opts, key);
if (val !== void 0) {
return val;
}
return key;
});
if (opts.method.toLowerCase()... | javascript | function interpolate(str, context) {
const opts = { ...context.options };
let val = opts.apiurl + str.replace(/:([\w_]+)/g, (m, key) => {
opts.params = union(opts.params, key);
let val = get(opts, key);
if (val !== void 0) {
return val;
}
return key;
});
if (opts.method.toLowerCase()... | [
"function",
"interpolate",
"(",
"str",
",",
"context",
")",
"{",
"const",
"opts",
"=",
"{",
"...",
"context",
".",
"options",
"}",
";",
"let",
"val",
"=",
"opts",
".",
"apiurl",
"+",
"str",
".",
"replace",
"(",
"/",
":([\\w_]+)",
"/",
"g",
",",
"("... | Create request URL by replacing params with actual values. | [
"Create",
"request",
"URL",
"by",
"replacing",
"params",
"with",
"actual",
"values",
"."
] | 2fd664e3f9a3ad24758401bf98743d553875d2cf | https://github.com/jonschlinkert/github-base/blob/2fd664e3f9a3ad24758401bf98743d553875d2cf/lib/utils.js#L140-L163 | train |
jonschlinkert/github-base | lib/utils.js | sanitize | function sanitize(options, blacklist) {
const opts = Object.assign({}, options);
const defaults = ['apiurl', 'token', 'username', 'password', 'placeholders', 'bearer'];
const keys = union([], defaults, blacklist);
return omit(opts, keys);
} | javascript | function sanitize(options, blacklist) {
const opts = Object.assign({}, options);
const defaults = ['apiurl', 'token', 'username', 'password', 'placeholders', 'bearer'];
const keys = union([], defaults, blacklist);
return omit(opts, keys);
} | [
"function",
"sanitize",
"(",
"options",
",",
"blacklist",
")",
"{",
"const",
"opts",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"options",
")",
";",
"const",
"defaults",
"=",
"[",
"'apiurl'",
",",
"'token'",
",",
"'username'",
",",
"'password'",
... | Cleanup request options object | [
"Cleanup",
"request",
"options",
"object"
] | 2fd664e3f9a3ad24758401bf98743d553875d2cf | https://github.com/jonschlinkert/github-base/blob/2fd664e3f9a3ad24758401bf98743d553875d2cf/lib/utils.js#L189-L194 | train |
syntax-tree/unist-util-is | index.js | is | function is(test, node, index, parent, context) {
var hasParent = parent !== null && parent !== undefined
var hasIndex = index !== null && index !== undefined
var check = convert(test)
if (
hasIndex &&
(typeof index !== 'number' || index < 0 || index === Infinity)
) {
throw new Error('Expected po... | javascript | function is(test, node, index, parent, context) {
var hasParent = parent !== null && parent !== undefined
var hasIndex = index !== null && index !== undefined
var check = convert(test)
if (
hasIndex &&
(typeof index !== 'number' || index < 0 || index === Infinity)
) {
throw new Error('Expected po... | [
"function",
"is",
"(",
"test",
",",
"node",
",",
"index",
",",
"parent",
",",
"context",
")",
"{",
"var",
"hasParent",
"=",
"parent",
"!==",
"null",
"&&",
"parent",
"!==",
"undefined",
"var",
"hasIndex",
"=",
"index",
"!==",
"null",
"&&",
"index",
"!==... | Assert if `test` passes for `node`. When a `parent` node is known the `index` of node. | [
"Assert",
"if",
"test",
"passes",
"for",
"node",
".",
"When",
"a",
"parent",
"node",
"is",
"known",
"the",
"index",
"of",
"node",
"."
] | 35b280ee14ad215280fe6da89a33275c813265ae | https://github.com/syntax-tree/unist-util-is/blob/35b280ee14ad215280fe6da89a33275c813265ae/index.js#L9-L34 | train |
syntax-tree/unist-util-is | index.js | matchesFactory | function matchesFactory(test) {
return matches
function matches(node) {
var key
for (key in test) {
if (node[key] !== test[key]) {
return false
}
}
return true
}
} | javascript | function matchesFactory(test) {
return matches
function matches(node) {
var key
for (key in test) {
if (node[key] !== test[key]) {
return false
}
}
return true
}
} | [
"function",
"matchesFactory",
"(",
"test",
")",
"{",
"return",
"matches",
"function",
"matches",
"(",
"node",
")",
"{",
"var",
"key",
"for",
"(",
"key",
"in",
"test",
")",
"{",
"if",
"(",
"node",
"[",
"key",
"]",
"!==",
"test",
"[",
"key",
"]",
")"... | Utility assert each property in `test` is represented in `node`, and each values are strictly equal. | [
"Utility",
"assert",
"each",
"property",
"in",
"test",
"is",
"represented",
"in",
"node",
"and",
"each",
"values",
"are",
"strictly",
"equal",
"."
] | 35b280ee14ad215280fe6da89a33275c813265ae | https://github.com/syntax-tree/unist-util-is/blob/35b280ee14ad215280fe6da89a33275c813265ae/index.js#L70-L84 | train |
virtyaluk/paper-ripple | dist/paperRipple.jquery.js | ElementRect | function ElementRect(element) {
_classCallCheck(this, ElementRect);
this._element = element;
/**
* Returns the width of the current element.
*
* @type {Number}
*/
this.width = this.boundingRect.width;
/**
* Returns the height of the current element.
*
* @type {N... | javascript | function ElementRect(element) {
_classCallCheck(this, ElementRect);
this._element = element;
/**
* Returns the width of the current element.
*
* @type {Number}
*/
this.width = this.boundingRect.width;
/**
* Returns the height of the current element.
*
* @type {N... | [
"function",
"ElementRect",
"(",
"element",
")",
"{",
"_classCallCheck",
"(",
"this",
",",
"ElementRect",
")",
";",
"this",
".",
"_element",
"=",
"element",
";",
"/**\n * Returns the width of the current element.\n *\n * @type {Number}\n */",
"this",
".",
"... | Initializes a new instance of the `ElementRect` class with the specified `element`.
@constructs ElementRect
@param {HTMLElement} element - The DOM element to get metrics from
@returns {ElementRect} The new instance of a class. | [
"Initializes",
"a",
"new",
"instance",
"of",
"the",
"ElementRect",
"class",
"with",
"the",
"specified",
"element",
"."
] | 4e8507eb1ff3d69328e54ce7ea3fa7f7ad6d67da | https://github.com/virtyaluk/paper-ripple/blob/4e8507eb1ff3d69328e54ce7ea3fa7f7ad6d67da/dist/paperRipple.jquery.js#L46-L73 | train |
cmrd-senya/markdown-it-html5-embed | lib/index.js | translate | function translate(messageObj) {
// Default to English if we don't have this message, or don't support this
// language at all
var language = messageObj.language && this[messageObj.language] &&
this[messageObj.language][messageObj.messageKey] ?
messageObj.language :
'en';
var rv = this[language][mes... | javascript | function translate(messageObj) {
// Default to English if we don't have this message, or don't support this
// language at all
var language = messageObj.language && this[messageObj.language] &&
this[messageObj.language][messageObj.messageKey] ?
messageObj.language :
'en';
var rv = this[language][mes... | [
"function",
"translate",
"(",
"messageObj",
")",
"{",
"// Default to English if we don't have this message, or don't support this",
"// language at all",
"var",
"language",
"=",
"messageObj",
".",
"language",
"&&",
"this",
"[",
"messageObj",
".",
"language",
"]",
"&&",
"t... | Very basic translation function. To translate or customize the UI messages,
set options.messages. To also customize the translation function itself, set
option.translateFn to a function that handles the same message object format.
@param {Object} messageObj
the message object
@param {String} messageObj.messageKey
an i... | [
"Very",
"basic",
"translation",
"function",
".",
"To",
"translate",
"or",
"customize",
"the",
"UI",
"messages",
"set",
"options",
".",
"messages",
".",
"To",
"also",
"customize",
"the",
"translation",
"function",
"itself",
"set",
"option",
".",
"translateFn",
... | 9f9b729bdf7629b415fa46aface73c905db37aad | https://github.com/cmrd-senya/markdown-it-html5-embed/blob/9f9b729bdf7629b415fa46aface73c905db37aad/lib/index.js#L191-L204 | train |
jonschlinkert/parse-csv | lib/renderer.js | Renderer | function Renderer(options) {
var defaults = {
headers: {
included: true,
downcase: true,
upcase: true
},
delimiter: 'tab',
decimalSign: 'comma',
outputDataType: 'json',
columnDelimiter: "\t",
rowDelimiter: '\n',
inputHeader: {},
outputHeader: {},
dataSelect:... | javascript | function Renderer(options) {
var defaults = {
headers: {
included: true,
downcase: true,
upcase: true
},
delimiter: 'tab',
decimalSign: 'comma',
outputDataType: 'json',
columnDelimiter: "\t",
rowDelimiter: '\n',
inputHeader: {},
outputHeader: {},
dataSelect:... | [
"function",
"Renderer",
"(",
"options",
")",
"{",
"var",
"defaults",
"=",
"{",
"headers",
":",
"{",
"included",
":",
"true",
",",
"downcase",
":",
"true",
",",
"upcase",
":",
"true",
"}",
",",
"delimiter",
":",
"'tab'",
",",
"decimalSign",
":",
"'comma... | Create a new `Renderer` with the given `options`.
```js
var csv = require('parse-csv');
var renderer = new csv.Renderer();
```
@param {Object} `options`
@api public | [
"Create",
"a",
"new",
"Renderer",
"with",
"the",
"given",
"options",
"."
] | fc492d63e6ae80539689b3a0d663ca78aea819a3 | https://github.com/jonschlinkert/parse-csv/blob/fc492d63e6ae80539689b3a0d663ca78aea819a3/lib/renderer.js#L22-L61 | train |
jonschlinkert/parse-csv | lib/parser.js | Parser | function Parser(options) {
this.options = merge({}, {
headers: {
included: false,
downcase: true,
upcase: true
},
delimiter: 'tab',
decimalSign: 'comma'
}, options);
} | javascript | function Parser(options) {
this.options = merge({}, {
headers: {
included: false,
downcase: true,
upcase: true
},
delimiter: 'tab',
decimalSign: 'comma'
}, options);
} | [
"function",
"Parser",
"(",
"options",
")",
"{",
"this",
".",
"options",
"=",
"merge",
"(",
"{",
"}",
",",
"{",
"headers",
":",
"{",
"included",
":",
"false",
",",
"downcase",
":",
"true",
",",
"upcase",
":",
"true",
"}",
",",
"delimiter",
":",
"'ta... | Create a new `Parser` with the given `options`.
```js
var csv = require('parse-csv');
var parser = new csv.Parser();
```
@param {Options} `options`
@api public | [
"Create",
"a",
"new",
"Parser",
"with",
"the",
"given",
"options",
"."
] | fc492d63e6ae80539689b3a0d663ca78aea819a3 | https://github.com/jonschlinkert/parse-csv/blob/fc492d63e6ae80539689b3a0d663ca78aea819a3/lib/parser.js#L30-L40 | train |
jonschlinkert/parse-csv | lib/parser.js | toArray | function toArray(str, options) {
var opts = extend({delim: ','}, options);
// Create a regular expression to parse the CSV values.
var re = new RegExp(
// Delimiters.
'(\\' + opts.delim + '|\\n|^)' +
// Quoted fields.
'(?:"([^"]*(?:""[^"]*)*)"|' +
// Standard fields.
'([^"\\' + opts.del... | javascript | function toArray(str, options) {
var opts = extend({delim: ','}, options);
// Create a regular expression to parse the CSV values.
var re = new RegExp(
// Delimiters.
'(\\' + opts.delim + '|\\n|^)' +
// Quoted fields.
'(?:"([^"]*(?:""[^"]*)*)"|' +
// Standard fields.
'([^"\\' + opts.del... | [
"function",
"toArray",
"(",
"str",
",",
"options",
")",
"{",
"var",
"opts",
"=",
"extend",
"(",
"{",
"delim",
":",
"','",
"}",
",",
"options",
")",
";",
"// Create a regular expression to parse the CSV values.",
"var",
"re",
"=",
"new",
"RegExp",
"(",
"// De... | Parse a delimited string into an array of arrays.
The default delimiter is `comma`, this can be
overriden by passed a different delimiter on
the `delim` option as a second argument.
This Function is from [Ben Nadel] by way of [Mr Data Converer]
@param {String} `str`
@param {Object} `options`
@return {Array} | [
"Parse",
"a",
"delimited",
"string",
"into",
"an",
"array",
"of",
"arrays",
"."
] | fc492d63e6ae80539689b3a0d663ca78aea819a3 | https://github.com/jonschlinkert/parse-csv/blob/fc492d63e6ae80539689b3a0d663ca78aea819a3/lib/parser.js#L205-L266 | train |
canalplus/canal-js-utils | rx-lite.js | Subject | function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
} | javascript | function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
} | [
"function",
"Subject",
"(",
")",
"{",
"__super__",
".",
"call",
"(",
"this",
",",
"subscribe",
")",
";",
"this",
".",
"isDisposed",
"=",
"false",
",",
"this",
".",
"isStopped",
"=",
"false",
",",
"this",
".",
"observers",
"=",
"[",
"]",
";",
"this",
... | Creates a subject. | [
"Creates",
"a",
"subject",
"."
] | 671b1229230083148c11177aabd909fa7d275b2b | https://github.com/canalplus/canal-js-utils/blob/671b1229230083148c11177aabd909fa7d275b2b/rx-lite.js#L5204-L5210 | train |
canalplus/canal-js-utils | rx-lite.js | BehaviorSubject | function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.hasError = false;
} | javascript | function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.hasError = false;
} | [
"function",
"BehaviorSubject",
"(",
"value",
")",
"{",
"__super__",
".",
"call",
"(",
"this",
",",
"subscribe",
")",
";",
"this",
".",
"value",
"=",
"value",
",",
"this",
".",
"observers",
"=",
"[",
"]",
",",
"this",
".",
"isDisposed",
"=",
"false",
... | Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
@param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. | [
"Initializes",
"a",
"new",
"instance",
"of",
"the",
"BehaviorSubject",
"class",
"which",
"creates",
"a",
"subject",
"that",
"caches",
"its",
"last",
"value",
"and",
"starts",
"with",
"the",
"specified",
"value",
"."
] | 671b1229230083148c11177aabd909fa7d275b2b | https://github.com/canalplus/canal-js-utils/blob/671b1229230083148c11177aabd909fa7d275b2b/rx-lite.js#L5455-L5462 | train |
canalplus/canal-js-utils | rx-lite.js | ReplaySubject | function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopp... | javascript | function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopp... | [
"function",
"ReplaySubject",
"(",
"bufferSize",
",",
"windowSize",
",",
"scheduler",
")",
"{",
"this",
".",
"bufferSize",
"=",
"bufferSize",
"==",
"null",
"?",
"maxSafeInteger",
":",
"bufferSize",
";",
"this",
".",
"windowSize",
"=",
"windowSize",
"==",
"null"... | Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
@param {Number} [bufferSize] Maximum element count of the replay buffer.
@param {Number} [windowSize] Maximum time length of the replay buffer.
@param {Scheduler} [scheduler] Scheduler the observers are invo... | [
"Initializes",
"a",
"new",
"instance",
"of",
"the",
"ReplaySubject",
"class",
"with",
"the",
"specified",
"buffer",
"size",
"window",
"size",
"and",
"scheduler",
"."
] | 671b1229230083148c11177aabd909fa7d275b2b | https://github.com/canalplus/canal-js-utils/blob/671b1229230083148c11177aabd909fa7d275b2b/rx-lite.js#L5584-L5595 | train |
stackgl/gl-toy | index.js | toy | function toy(frag, cb) {
const canvas = document.body.appendChild(document.createElement('canvas'))
const gl = context(canvas, render)
const shader = Shader(gl, vert, frag)
const fitter = fit(canvas)
render.update = update
render.resize = fitter
render.shader = shader
render.canvas = canvas
rende... | javascript | function toy(frag, cb) {
const canvas = document.body.appendChild(document.createElement('canvas'))
const gl = context(canvas, render)
const shader = Shader(gl, vert, frag)
const fitter = fit(canvas)
render.update = update
render.resize = fitter
render.shader = shader
render.canvas = canvas
rende... | [
"function",
"toy",
"(",
"frag",
",",
"cb",
")",
"{",
"const",
"canvas",
"=",
"document",
".",
"body",
".",
"appendChild",
"(",
"document",
".",
"createElement",
"(",
"'canvas'",
")",
")",
"const",
"gl",
"=",
"context",
"(",
"canvas",
",",
"render",
")"... | String -> WebGLRenderingContext, Shader | [
"String",
"-",
">",
"WebGLRenderingContext",
"Shader"
] | 152e2f59e15fda14217a87d7f6ec953ccb127323 | https://github.com/stackgl/gl-toy/blob/152e2f59e15fda14217a87d7f6ec953ccb127323/index.js#L19-L47 | train |
DeMille/dnssd.js | lib/hash.js | stringify | function stringify(val) {
if (typeof val === 'string') return JSON.stringify(val.toLowerCase());
if (Array.isArray(val)) return '[' + val.map(stringify) + ']';
if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' && '' + val === '[object Object]') {
var str = Object.keys(val).sort().ma... | javascript | function stringify(val) {
if (typeof val === 'string') return JSON.stringify(val.toLowerCase());
if (Array.isArray(val)) return '[' + val.map(stringify) + ']';
if ((typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' && '' + val === '[object Object]') {
var str = Object.keys(val).sort().ma... | [
"function",
"stringify",
"(",
"val",
")",
"{",
"if",
"(",
"typeof",
"val",
"===",
"'string'",
")",
"return",
"JSON",
".",
"stringify",
"(",
"val",
".",
"toLowerCase",
"(",
")",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"val",
")",
")",
"re... | Deterministic JSON.stringify for resource record stuff
Object keys are sorted so strings are always the same independent of
what order properties were added in. Strings are lowercased because
record names, TXT keys, SRV target names, etc. need to be compared
case-insensitively.
@param {*} val
@return {string} | [
"Deterministic",
"JSON",
".",
"stringify",
"for",
"resource",
"record",
"stuff"
] | d66f0dd6c62300f3a2df38186c23c6ffacc02afc | https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/lib/hash.js#L16-L30 | train |
DeMille/dnssd.js | src/Browser.js | Browser | function Browser(type, options = {}) {
if (!(this instanceof Browser)) return new Browser(type, options);
EventEmitter.call(this);
// convert argument ServiceType to validate it (might throw)
const serviceType = (type instanceof ServiceType) ? type : new ServiceType(type);
// can't search for multiple subty... | javascript | function Browser(type, options = {}) {
if (!(this instanceof Browser)) return new Browser(type, options);
EventEmitter.call(this);
// convert argument ServiceType to validate it (might throw)
const serviceType = (type instanceof ServiceType) ? type : new ServiceType(type);
// can't search for multiple subty... | [
"function",
"Browser",
"(",
"type",
",",
"options",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Browser",
")",
")",
"return",
"new",
"Browser",
"(",
"type",
",",
"options",
")",
";",
"EventEmitter",
".",
"call",
"(",
"this",
... | Creates a new Browser
@emits 'serviceUp'
@emits 'serviceChanged'
@emits 'serviceDown'
@emits 'error'
@param {ServiceType|Object|String|Array} type - the service to browse
@param {Object} [options] | [
"Creates",
"a",
"new",
"Browser"
] | d66f0dd6c62300f3a2df38186c23c6ffacc02afc | https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/src/Browser.js#L27-L57 | train |
DeMille/dnssd.js | lib/misc.js | visualPad | function visualPad(str, num) {
var needed = num - str.replace(remove_colors_re, '').length;
return needed > 0 ? str + ' '.repeat(needed) : str;
} | javascript | function visualPad(str, num) {
var needed = num - str.replace(remove_colors_re, '').length;
return needed > 0 ? str + ' '.repeat(needed) : str;
} | [
"function",
"visualPad",
"(",
"str",
",",
"num",
")",
"{",
"var",
"needed",
"=",
"num",
"-",
"str",
".",
"replace",
"(",
"remove_colors_re",
",",
"''",
")",
".",
"length",
";",
"return",
"needed",
">",
"0",
"?",
"str",
"+",
"' '",
".",
"repeat",
"(... | Visually padEnd. Adding colors to strings adds escape sequences that
make it a color but also adds characters to str.length that aren't
displayed.
@param {string} str
@param {number} num
@return {string} | [
"Visually",
"padEnd",
".",
"Adding",
"colors",
"to",
"strings",
"adds",
"escape",
"sequences",
"that",
"make",
"it",
"a",
"color",
"but",
"also",
"adds",
"characters",
"to",
"str",
".",
"length",
"that",
"aren",
"t",
"displayed",
"."
] | d66f0dd6c62300f3a2df38186c23c6ffacc02afc | https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/lib/misc.js#L107-L111 | train |
DeMille/dnssd.js | lib/misc.js | alignRecords | function alignRecords() {
var colWidths = [];
var result = void 0;
// Get max size for each column (have to look at all records)
for (var _len2 = arguments.length, groups = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
groups[_key2] = arguments[_key2];
}
result = groups.map(function (records) {
... | javascript | function alignRecords() {
var colWidths = [];
var result = void 0;
// Get max size for each column (have to look at all records)
for (var _len2 = arguments.length, groups = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
groups[_key2] = arguments[_key2];
}
result = groups.map(function (records) {
... | [
"function",
"alignRecords",
"(",
")",
"{",
"var",
"colWidths",
"=",
"[",
"]",
";",
"var",
"result",
"=",
"void",
"0",
";",
"// Get max size for each column (have to look at all records)",
"for",
"(",
"var",
"_len2",
"=",
"arguments",
".",
"length",
",",
"groups"... | Make a table of records strings that have equal column lengths.
Ex, turn groups of records:
[
[
Host.local. * QU,
]
[
Host.local. A 10 169.254.132.42,
Host.local. AAAA 10 fe80::c17c:ec1c:530d:842a,
]
]
into a more readable form that can be printed:
[
[
'Host.local. * QU'
]
[
'Host.local. A 10 169.254.132.42'
'H... | [
"Make",
"a",
"table",
"of",
"records",
"strings",
"that",
"have",
"equal",
"column",
"lengths",
"."
] | d66f0dd6c62300f3a2df38186c23c6ffacc02afc | https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/lib/misc.js#L141-L177 | train |
DeMille/dnssd.js | src/Advertisement.js | Advertisement | function Advertisement(type, port, options = {}) {
if (!(this instanceof Advertisement)) {
return new Advertisement(type, port, options);
}
EventEmitter.call(this);
// convert argument ServiceType to validate it (might throw)
const serviceType = (!(type instanceof ServiceType))
? new ServiceType(typ... | javascript | function Advertisement(type, port, options = {}) {
if (!(this instanceof Advertisement)) {
return new Advertisement(type, port, options);
}
EventEmitter.call(this);
// convert argument ServiceType to validate it (might throw)
const serviceType = (!(type instanceof ServiceType))
? new ServiceType(typ... | [
"function",
"Advertisement",
"(",
"type",
",",
"port",
",",
"options",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"Advertisement",
")",
")",
"{",
"return",
"new",
"Advertisement",
"(",
"type",
",",
"port",
",",
"options",
")",
... | Creates a new Advertisement
@emits 'error'
@emits 'stopped' when the advertisement is stopped
@emits 'instanceRenamed' when the service instance is renamed
@emits 'hostRenamed' when the hostname has to be renamed
@param {ServiceType|Object|String|Array} type - type of service to advertise
@param {Number} ... | [
"Creates",
"a",
"new",
"Advertisement"
] | d66f0dd6c62300f3a2df38186c23c6ffacc02afc | https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/src/Advertisement.js#L40-L81 | train |
DeMille/dnssd.js | lib/Response.js | legacyify | function legacyify(record) {
var clone = record.clone();
clone.isUnique = false;
clone.ttl = 10;
return clone;
} | javascript | function legacyify(record) {
var clone = record.clone();
clone.isUnique = false;
clone.ttl = 10;
return clone;
} | [
"function",
"legacyify",
"(",
"record",
")",
"{",
"var",
"clone",
"=",
"record",
".",
"clone",
"(",
")",
";",
"clone",
".",
"isUnique",
"=",
"false",
";",
"clone",
".",
"ttl",
"=",
"10",
";",
"return",
"clone",
";",
"}"
] | Set TTL=10 on records for legacy responses. Use clones to prevent altering the original record set. | [
"Set",
"TTL",
"=",
"10",
"on",
"records",
"for",
"legacy",
"responses",
".",
"Use",
"clones",
"to",
"prevent",
"altering",
"the",
"original",
"record",
"set",
"."
] | d66f0dd6c62300f3a2df38186c23c6ffacc02afc | https://github.com/DeMille/dnssd.js/blob/d66f0dd6c62300f3a2df38186c23c6ffacc02afc/lib/Response.js#L452-L457 | train |
cheng-kang/wildfire | src/auto.js | loadJSSequentially | function loadJSSequentially (aList, finished) {
if (aList.length === 0) {
console.log('Finished loadJSSequentially.')
if (finished) {
finished()
}
return
}
let item = aList.shift()
let newScript = document.createElement('script')
let url = null
let shouldSkip = ... | javascript | function loadJSSequentially (aList, finished) {
if (aList.length === 0) {
console.log('Finished loadJSSequentially.')
if (finished) {
finished()
}
return
}
let item = aList.shift()
let newScript = document.createElement('script')
let url = null
let shouldSkip = ... | [
"function",
"loadJSSequentially",
"(",
"aList",
",",
"finished",
")",
"{",
"if",
"(",
"aList",
".",
"length",
"===",
"0",
")",
"{",
"console",
".",
"log",
"(",
"'Finished loadJSSequentially.'",
")",
"if",
"(",
"finished",
")",
"{",
"finished",
"(",
")",
... | Dynamically load a list JS files sequentially.
@param {(string|Object)[]} aList The list of JS files to load
@param {string} aList[].url The url of the JS file to load
@param {function} aList[].loaded Callback when the file is loaded
@param {function} aList[].shouldSkip Check before loading the file.
Note: if `loaded`... | [
"Dynamically",
"load",
"a",
"list",
"JS",
"files",
"sequentially",
"."
] | 85639018887ca657b94ef7edf30a7ef73eb247f8 | https://github.com/cheng-kang/wildfire/blob/85639018887ca657b94ef7edf30a7ef73eb247f8/src/auto.js#L57-L103 | train |
cheng-kang/wildfire | src/auto.js | WfI18n | function WfI18n (translation = {}, fallback = null, locale = 'en') {
this.translation = translation
this.locale = locale
this.fallback = fallback
this.t = (key) => {
let result = this.translation[this.locale]
if (!result) { result = this.translation[this.fallback] }
if (!result) { thr... | javascript | function WfI18n (translation = {}, fallback = null, locale = 'en') {
this.translation = translation
this.locale = locale
this.fallback = fallback
this.t = (key) => {
let result = this.translation[this.locale]
if (!result) { result = this.translation[this.fallback] }
if (!result) { thr... | [
"function",
"WfI18n",
"(",
"translation",
"=",
"{",
"}",
",",
"fallback",
"=",
"null",
",",
"locale",
"=",
"'en'",
")",
"{",
"this",
".",
"translation",
"=",
"translation",
"this",
".",
"locale",
"=",
"locale",
"this",
".",
"fallback",
"=",
"fallback",
... | Custom translator to replace `i18next` | [
"Custom",
"translator",
"to",
"replace",
"i18next"
] | 85639018887ca657b94ef7edf30a7ef73eb247f8 | https://github.com/cheng-kang/wildfire/blob/85639018887ca657b94ef7edf30a7ef73eb247f8/src/auto.js#L114-L139 | train |
depoio/node-telegram-bot | lib/Bot.js | Bot | function Bot(options) {
this.base_url = 'https://api.telegram.org/';
this.id = '';
this.first_name = '';
this.username = '';
this.token = options.token;
this.offset = options.offset ? options.offset : 0;
this.interval = options.interval ? options.interval : 500;
this.webhook = options.webhook ? options.... | javascript | function Bot(options) {
this.base_url = 'https://api.telegram.org/';
this.id = '';
this.first_name = '';
this.username = '';
this.token = options.token;
this.offset = options.offset ? options.offset : 0;
this.interval = options.interval ? options.interval : 500;
this.webhook = options.webhook ? options.... | [
"function",
"Bot",
"(",
"options",
")",
"{",
"this",
".",
"base_url",
"=",
"'https://api.telegram.org/'",
";",
"this",
".",
"id",
"=",
"''",
";",
"this",
".",
"first_name",
"=",
"''",
";",
"this",
".",
"username",
"=",
"''",
";",
"this",
".",
"token",
... | Constructor for Telegram Bot API Client.
@class Bot
@constructor
@param {Object} options Configurations for the client
@param {String} options.token Bot token
@see https://core.telegram.org/bots/api | [
"Constructor",
"for",
"Telegram",
"Bot",
"API",
"Client",
"."
] | 0abe096364b34469de304c1cc5ec28d8599233ca | https://github.com/depoio/node-telegram-bot/blob/0abe096364b34469de304c1cc5ec28d8599233ca/lib/Bot.js#L24-L42 | train |
Callidon/sparql-engine | src/engine/property-paths.js | transformPath | function transformPath (bgp, group, options) {
let i = 0
var queryChange = false
var ret = [bgp, null, []]
while (i < bgp.length && !queryChange) {
var curr = bgp[i]
if (typeof curr.predicate !== 'string' && curr.predicate.type === 'path') {
switch (curr.predicate.pathType) {
case '/':
... | javascript | function transformPath (bgp, group, options) {
let i = 0
var queryChange = false
var ret = [bgp, null, []]
while (i < bgp.length && !queryChange) {
var curr = bgp[i]
if (typeof curr.predicate !== 'string' && curr.predicate.type === 'path') {
switch (curr.predicate.pathType) {
case '/':
... | [
"function",
"transformPath",
"(",
"bgp",
",",
"group",
",",
"options",
")",
"{",
"let",
"i",
"=",
"0",
"var",
"queryChange",
"=",
"false",
"var",
"ret",
"=",
"[",
"bgp",
",",
"null",
",",
"[",
"]",
"]",
"while",
"(",
"i",
"<",
"bgp",
".",
"length... | rewriting rules for property paths | [
"rewriting",
"rules",
"for",
"property",
"paths"
] | bf4c602df3dd5ac190f99e8593aa134eba5cc084 | https://github.com/Callidon/sparql-engine/blob/bf4c602df3dd5ac190f99e8593aa134eba5cc084/src/engine/property-paths.js#L31-L66 | train |
101100/xbee-rx | examples/temp-upload.js | xivelyPost | function xivelyPost(feedId, streamId, apiKey, currentValue) {
var dataPoint =
{
"version":"1.0.0",
"datastreams" :
[
{
"id" : streamId,
"current_value" : currentValue
},
]
};
var requestUrl = "https://api.xively.com... | javascript | function xivelyPost(feedId, streamId, apiKey, currentValue) {
var dataPoint =
{
"version":"1.0.0",
"datastreams" :
[
{
"id" : streamId,
"current_value" : currentValue
},
]
};
var requestUrl = "https://api.xively.com... | [
"function",
"xivelyPost",
"(",
"feedId",
",",
"streamId",
",",
"apiKey",
",",
"currentValue",
")",
"{",
"var",
"dataPoint",
"=",
"{",
"\"version\"",
":",
"\"1.0.0\"",
",",
"\"datastreams\"",
":",
"[",
"{",
"\"id\"",
":",
"streamId",
",",
"\"current_value\"",
... | Creates a new observable that will make a HTTP or HTTPS POST request to the given url and will give the results as a single event in the stream. | [
"Creates",
"a",
"new",
"observable",
"that",
"will",
"make",
"a",
"HTTP",
"or",
"HTTPS",
"POST",
"request",
"to",
"the",
"given",
"url",
"and",
"will",
"give",
"the",
"results",
"as",
"a",
"single",
"event",
"in",
"the",
"stream",
"."
] | 248edb7e82dba41c0e352feffa952581d7967253 | https://github.com/101100/xbee-rx/blob/248edb7e82dba41c0e352feffa952581d7967253/examples/temp-upload.js#L33-L60 | train |
101100/xbee-rx | lib/xbee-rx.js | _lookupByNodeIdentifier | function _lookupByNodeIdentifier(nodeIdentifier, timeoutMs) {
// if the address is cached, return that
if (cachedNodes[nodeIdentifier]) {
return rx.of({ destination64: cachedNodes[nodeIdentifier]});
}
if (debug) {
console.log("Looking up", nodeIdentifier);
... | javascript | function _lookupByNodeIdentifier(nodeIdentifier, timeoutMs) {
// if the address is cached, return that
if (cachedNodes[nodeIdentifier]) {
return rx.of({ destination64: cachedNodes[nodeIdentifier]});
}
if (debug) {
console.log("Looking up", nodeIdentifier);
... | [
"function",
"_lookupByNodeIdentifier",
"(",
"nodeIdentifier",
",",
"timeoutMs",
")",
"{",
"// if the address is cached, return that",
"if",
"(",
"cachedNodes",
"[",
"nodeIdentifier",
"]",
")",
"{",
"return",
"rx",
".",
"of",
"(",
"{",
"destination64",
":",
"cachedNo... | Returns a stream that will emit the 64 bit address of the node with the given node identifier. | [
"Returns",
"a",
"stream",
"that",
"will",
"emit",
"the",
"64",
"bit",
"address",
"of",
"the",
"node",
"with",
"the",
"given",
"node",
"identifier",
"."
] | 248edb7e82dba41c0e352feffa952581d7967253 | https://github.com/101100/xbee-rx/blob/248edb7e82dba41c0e352feffa952581d7967253/lib/xbee-rx.js#L172-L194 | train |
101100/xbee-rx | lib/xbee-rx.js | _remoteCommand | function _remoteCommand(command, destination64, destination16, timeoutMs, commandParameter, broadcast) {
var frame = {
type: xbee_api.constants.FRAME_TYPE.REMOTE_AT_COMMAND_REQUEST,
command: command,
commandParameter: commandParameter,
destination6... | javascript | function _remoteCommand(command, destination64, destination16, timeoutMs, commandParameter, broadcast) {
var frame = {
type: xbee_api.constants.FRAME_TYPE.REMOTE_AT_COMMAND_REQUEST,
command: command,
commandParameter: commandParameter,
destination6... | [
"function",
"_remoteCommand",
"(",
"command",
",",
"destination64",
",",
"destination16",
",",
"timeoutMs",
",",
"commandParameter",
",",
"broadcast",
")",
"{",
"var",
"frame",
"=",
"{",
"type",
":",
"xbee_api",
".",
"constants",
".",
"FRAME_TYPE",
".",
"REMOT... | Sends a the given command and parameter to the given destination. A stream is returned that will emit to the resulting command data on success or end in an Error with the failed status as the text. Only one of destination64 or destination16 should be given; the other should be undefined. | [
"Sends",
"a",
"the",
"given",
"command",
"and",
"parameter",
"to",
"the",
"given",
"destination",
".",
"A",
"stream",
"is",
"returned",
"that",
"will",
"emit",
"to",
"the",
"resulting",
"command",
"data",
"on",
"success",
"or",
"end",
"in",
"an",
"Error",
... | 248edb7e82dba41c0e352feffa952581d7967253 | https://github.com/101100/xbee-rx/blob/248edb7e82dba41c0e352feffa952581d7967253/lib/xbee-rx.js#L283-L314 | train |
101100/xbee-rx | lib/xbee-rx.js | _remoteTransmit | function _remoteTransmit(destination64, destination16, data, timeoutMs) {
var frame = {
data: data,
type: xbee_api.constants.FRAME_TYPE.ZIGBEE_TRANSMIT_REQUEST,
destination64: destination64,
destination16: destination16
},
r... | javascript | function _remoteTransmit(destination64, destination16, data, timeoutMs) {
var frame = {
data: data,
type: xbee_api.constants.FRAME_TYPE.ZIGBEE_TRANSMIT_REQUEST,
destination64: destination64,
destination16: destination16
},
r... | [
"function",
"_remoteTransmit",
"(",
"destination64",
",",
"destination16",
",",
"data",
",",
"timeoutMs",
")",
"{",
"var",
"frame",
"=",
"{",
"data",
":",
"data",
",",
"type",
":",
"xbee_api",
".",
"constants",
".",
"FRAME_TYPE",
".",
"ZIGBEE_TRANSMIT_REQUEST"... | Sends a the given data to the given destination. A stream is returned that will complete on success or end in an Error with the failed status as the text. Only one of destination64 or destination16 should be given; the other should be undefined. | [
"Sends",
"a",
"the",
"given",
"data",
"to",
"the",
"given",
"destination",
".",
"A",
"stream",
"is",
"returned",
"that",
"will",
"complete",
"on",
"success",
"or",
"end",
"in",
"an",
"Error",
"with",
"the",
"failed",
"status",
"as",
"the",
"text",
".",
... | 248edb7e82dba41c0e352feffa952581d7967253 | https://github.com/101100/xbee-rx/blob/248edb7e82dba41c0e352feffa952581d7967253/lib/xbee-rx.js#L321-L351 | train |
glennjones/microformat-node | static/javascript/parse.js | getResults | function getResults( form, url, callback ){
var formData = new FormData( form );
var request = new XMLHttpRequest();
request.open("POST", url);
request.send(formData);
request.onload = function(e) {
if (request.status == 200) {
callback(null, JSON.parse(request.responseText));
... | javascript | function getResults( form, url, callback ){
var formData = new FormData( form );
var request = new XMLHttpRequest();
request.open("POST", url);
request.send(formData);
request.onload = function(e) {
if (request.status == 200) {
callback(null, JSON.parse(request.responseText));
... | [
"function",
"getResults",
"(",
"form",
",",
"url",
",",
"callback",
")",
"{",
"var",
"formData",
"=",
"new",
"FormData",
"(",
"form",
")",
";",
"var",
"request",
"=",
"new",
"XMLHttpRequest",
"(",
")",
";",
"request",
".",
"open",
"(",
"\"POST\"",
",",... | post form and returns JSON | [
"post",
"form",
"and",
"returns",
"JSON"
] | d817ebf484dedb1d042e635eccc0707afd46d7f7 | https://github.com/glennjones/microformat-node/blob/d817ebf484dedb1d042e635eccc0707afd46d7f7/static/javascript/parse.js#L64-L77 | train |
glennjones/microformat-node | app.js | buildOptions | function buildOptions(request, callback) {
let options = {};
let err = null;
if (request.payload.html !== undefined) {
options.html = request.payload.html.trim();
}
if (request.payload.baseUrl !== undefined) {
options.baseUrl = request.payload.baseUrl.trim();
}
if (reque... | javascript | function buildOptions(request, callback) {
let options = {};
let err = null;
if (request.payload.html !== undefined) {
options.html = request.payload.html.trim();
}
if (request.payload.baseUrl !== undefined) {
options.baseUrl = request.payload.baseUrl.trim();
}
if (reque... | [
"function",
"buildOptions",
"(",
"request",
",",
"callback",
")",
"{",
"let",
"options",
"=",
"{",
"}",
";",
"let",
"err",
"=",
"null",
";",
"if",
"(",
"request",
".",
"payload",
".",
"html",
"!==",
"undefined",
")",
"{",
"options",
".",
"html",
"=",... | create options from form input | [
"create",
"options",
"from",
"form",
"input"
] | d817ebf484dedb1d042e635eccc0707afd46d7f7 | https://github.com/glennjones/microformat-node/blob/d817ebf484dedb1d042e635eccc0707afd46d7f7/app.js#L73-L134 | train |
not-an-aardvark/eslint-rule-composer | lib/rule-composer.js | normalizeMessagePlaceholders | function normalizeMessagePlaceholders(descriptor, messageIds) {
const message = typeof descriptor.messageId === 'string' ? messageIds[descriptor.messageId] : descriptor.message;
if (!descriptor.data) {
return {
message,
data: typeof descriptor.messageId === 'string' ? {} : null,
};
}
const ... | javascript | function normalizeMessagePlaceholders(descriptor, messageIds) {
const message = typeof descriptor.messageId === 'string' ? messageIds[descriptor.messageId] : descriptor.message;
if (!descriptor.data) {
return {
message,
data: typeof descriptor.messageId === 'string' ? {} : null,
};
}
const ... | [
"function",
"normalizeMessagePlaceholders",
"(",
"descriptor",
",",
"messageIds",
")",
"{",
"const",
"message",
"=",
"typeof",
"descriptor",
".",
"messageId",
"===",
"'string'",
"?",
"messageIds",
"[",
"descriptor",
".",
"messageId",
"]",
":",
"descriptor",
".",
... | Interpolates data placeholders in report messages
@param {MessageDescriptor} descriptor The report message descriptor.
@param {Object} messageIds Message IDs from rule metadata
@returns {{message: string, data: Object}} The interpolated message and data for the descriptor | [
"Interpolates",
"data",
"placeholders",
"in",
"report",
"messages"
] | 7e8ec43d3e62d9766e87b09c1958ce2863b421f4 | https://github.com/not-an-aardvark/eslint-rule-composer/blob/7e8ec43d3e62d9766e87b09c1958ce2863b421f4/lib/rule-composer.js#L57-L80 | train |
smallalso/v-verify | src/utils.js | classOf | function classOf (obj) {
const class2type = {}
'Boolean Number String Function Array Date RegExp Object tips'.split(' ')
.forEach((e, i) => {
class2type['[object ' + e + ']'] = e.toLowerCase()
})
if (obj == null) {
return String(obj)
}
return typeof obj === 'object' || typeof obj === 'function'
... | javascript | function classOf (obj) {
const class2type = {}
'Boolean Number String Function Array Date RegExp Object tips'.split(' ')
.forEach((e, i) => {
class2type['[object ' + e + ']'] = e.toLowerCase()
})
if (obj == null) {
return String(obj)
}
return typeof obj === 'object' || typeof obj === 'function'
... | [
"function",
"classOf",
"(",
"obj",
")",
"{",
"const",
"class2type",
"=",
"{",
"}",
"'Boolean Number String Function Array Date RegExp Object tips'",
".",
"split",
"(",
"' '",
")",
".",
"forEach",
"(",
"(",
"e",
",",
"i",
")",
"=>",
"{",
"class2type",
"[",
"'... | javscript data type judgment
@param {*} obj | [
"javscript",
"data",
"type",
"judgment"
] | 36b389f560b6060e26c7a475902d4add1a644e1a | https://github.com/smallalso/v-verify/blob/36b389f560b6060e26c7a475902d4add1a644e1a/src/utils.js#L7-L19 | train |
smallalso/v-verify | src/index.js | install | function install (Vue, options = {}) {
options.lang = options.lang || 'zh_cn'
Object.assign(validator, options.validators)
Object.assign(lang[options.lang], options.messages)
try {
const directive = new Directive(Vue, {
mode: options.mode,
errorIcon: options.errorIcon,
errorClass: options.... | javascript | function install (Vue, options = {}) {
options.lang = options.lang || 'zh_cn'
Object.assign(validator, options.validators)
Object.assign(lang[options.lang], options.messages)
try {
const directive = new Directive(Vue, {
mode: options.mode,
errorIcon: options.errorIcon,
errorClass: options.... | [
"function",
"install",
"(",
"Vue",
",",
"options",
"=",
"{",
"}",
")",
"{",
"options",
".",
"lang",
"=",
"options",
".",
"lang",
"||",
"'zh_cn'",
"Object",
".",
"assign",
"(",
"validator",
",",
"options",
".",
"validators",
")",
"Object",
".",
"assign"... | VUE plugin registed function
@param {Object} Vue object
@param {Object} plugin config object | [
"VUE",
"plugin",
"registed",
"function"
] | 36b389f560b6060e26c7a475902d4add1a644e1a | https://github.com/smallalso/v-verify/blob/36b389f560b6060e26c7a475902d4add1a644e1a/src/index.js#L11-L28 | train |
trooba/trooba | index.js | add | function add(message) {
if (!message.order || // no keep order needed
message.inProcess) {// or already in process
return false; // should continue
}
var queue = this.getQueue(message.context);
queue.unshift(message); // FIFO
message.pointId = this.pi... | javascript | function add(message) {
if (!message.order || // no keep order needed
message.inProcess) {// or already in process
return false; // should continue
}
var queue = this.getQueue(message.context);
queue.unshift(message); // FIFO
message.pointId = this.pi... | [
"function",
"add",
"(",
"message",
")",
"{",
"if",
"(",
"!",
"message",
".",
"order",
"||",
"// no keep order needed",
"message",
".",
"inProcess",
")",
"{",
"// or already in process",
"return",
"false",
";",
"// should continue",
"}",
"var",
"queue",
"=",
"t... | return true, if message prcessing should be paused | [
"return",
"true",
"if",
"message",
"prcessing",
"should",
"be",
"paused"
] | fdfd1e0d329d419cff581835c8f7aaf213ea9f1f | https://github.com/trooba/trooba/blob/fdfd1e0d329d419cff581835c8f7aaf213ea9f1f/index.js#L700-L713 | train |
Pagawa/PgwSlider | pgwslider.js | function(elementId, apiController, direction) {
if (elementId == pgwSlider.currentSlide) {
return false;
}
var element = pgwSlider.data[elementId - 1];
if (typeof element == 'undefined') {
throw new Error('PgwSlider - The element ' + ele... | javascript | function(elementId, apiController, direction) {
if (elementId == pgwSlider.currentSlide) {
return false;
}
var element = pgwSlider.data[elementId - 1];
if (typeof element == 'undefined') {
throw new Error('PgwSlider - The element ' + ele... | [
"function",
"(",
"elementId",
",",
"apiController",
",",
"direction",
")",
"{",
"if",
"(",
"elementId",
"==",
"pgwSlider",
".",
"currentSlide",
")",
"{",
"return",
"false",
";",
"}",
"var",
"element",
"=",
"pgwSlider",
".",
"data",
"[",
"elementId",
"-",
... | Display the current element | [
"Display",
"the",
"current",
"element"
] | f180a3378d7446216cc927f21fff1714579e769f | https://github.com/Pagawa/PgwSlider/blob/f180a3378d7446216cc927f21fff1714579e769f/pgwslider.js#L580-L621 | train | |
kuzzleio/koncorde | lib/storage/removeOperands.js | destroy | function destroy(foPairs, index, collection, operand) {
if (foPairs[index][collection].size === 1) {
if (containsOne(foPairs[index])) {
delete foPairs[index];
} else {
delete foPairs[index][collection];
}
}else {
foPairs[index][collection].delete(operand);
}
} | javascript | function destroy(foPairs, index, collection, operand) {
if (foPairs[index][collection].size === 1) {
if (containsOne(foPairs[index])) {
delete foPairs[index];
} else {
delete foPairs[index][collection];
}
}else {
foPairs[index][collection].delete(operand);
}
} | [
"function",
"destroy",
"(",
"foPairs",
",",
"index",
",",
"collection",
",",
"operand",
")",
"{",
"if",
"(",
"foPairs",
"[",
"index",
"]",
"[",
"collection",
"]",
".",
"size",
"===",
"1",
")",
"{",
"if",
"(",
"containsOne",
"(",
"foPairs",
"[",
"inde... | Performs a cascading removal of a field-operand pair
@param foPairs
@param index
@param collection
@param operand | [
"Performs",
"a",
"cascading",
"removal",
"of",
"a",
"field",
"-",
"operand",
"pair"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/storage/removeOperands.js#L336-L346 | train |
kuzzleio/koncorde | lib/transform/canonical.js | evalFilter | function evalFilter(filters, results, pos = {value: 0}) {
const key = Object.keys(filters)[0];
if (['and', 'or', 'not'].indexOf(key) === -1 || filters._isLeaf) {
pos.value++;
return results[pos.value - 1];
}
if (key === 'not') {
return !evalFilter(filters[key], results, pos);
}
return filters... | javascript | function evalFilter(filters, results, pos = {value: 0}) {
const key = Object.keys(filters)[0];
if (['and', 'or', 'not'].indexOf(key) === -1 || filters._isLeaf) {
pos.value++;
return results[pos.value - 1];
}
if (key === 'not') {
return !evalFilter(filters[key], results, pos);
}
return filters... | [
"function",
"evalFilter",
"(",
"filters",
",",
"results",
",",
"pos",
"=",
"{",
"value",
":",
"0",
"}",
")",
"{",
"const",
"key",
"=",
"Object",
".",
"keys",
"(",
"filters",
")",
"[",
"0",
"]",
";",
"if",
"(",
"[",
"'and'",
",",
"'or'",
",",
"'... | Given a boolean array containing the conditions results, returns
a boolean indicating the whole filter result
@param {object} filters
@param {Array} results - condition results, contains booleans
@param {object} [pos] - current condition position
@returns {boolean} | [
"Given",
"a",
"boolean",
"array",
"containing",
"the",
"conditions",
"results",
"returns",
"a",
"boolean",
"indicating",
"the",
"whole",
"filter",
"result"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/canonical.js#L403-L424 | train |
kuzzleio/koncorde | lib/transform/standardize.js | onlyOneFieldAttribute | function onlyOneFieldAttribute(fieldsList, keyword) {
if (fieldsList.length > 1) {
return Bluebird.reject(new BadRequestError(`"${keyword}" can contain only one attribute`));
}
return Bluebird.resolve(fieldsList);
} | javascript | function onlyOneFieldAttribute(fieldsList, keyword) {
if (fieldsList.length > 1) {
return Bluebird.reject(new BadRequestError(`"${keyword}" can contain only one attribute`));
}
return Bluebird.resolve(fieldsList);
} | [
"function",
"onlyOneFieldAttribute",
"(",
"fieldsList",
",",
"keyword",
")",
"{",
"if",
"(",
"fieldsList",
".",
"length",
">",
"1",
")",
"{",
"return",
"Bluebird",
".",
"reject",
"(",
"new",
"BadRequestError",
"(",
"`",
"${",
"keyword",
"}",
"`",
")",
")... | Verifies that "filter" contains only 1 field
@param {Array} fieldsList
@param {string} keyword
@returns {Promise} Promise resolving to the provided fields list | [
"Verifies",
"that",
"filter",
"contains",
"only",
"1",
"field"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L691-L697 | train |
kuzzleio/koncorde | lib/transform/standardize.js | requireAttribute | function requireAttribute(filter, keyword, attribute) {
if (!filter[attribute]) {
return Bluebird.reject(new BadRequestError(`"${keyword}" requires the following attribute: ${attribute}`));
}
return Bluebird.resolve();
} | javascript | function requireAttribute(filter, keyword, attribute) {
if (!filter[attribute]) {
return Bluebird.reject(new BadRequestError(`"${keyword}" requires the following attribute: ${attribute}`));
}
return Bluebird.resolve();
} | [
"function",
"requireAttribute",
"(",
"filter",
",",
"keyword",
",",
"attribute",
")",
"{",
"if",
"(",
"!",
"filter",
"[",
"attribute",
"]",
")",
"{",
"return",
"Bluebird",
".",
"reject",
"(",
"new",
"BadRequestError",
"(",
"`",
"${",
"keyword",
"}",
"${"... | Verifies that "filter.attribute' exists
@param filter
@param keyword
@param attribute
@returns {Promise} | [
"Verifies",
"that",
"filter",
".",
"attribute",
"exists"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L706-L712 | train |
kuzzleio/koncorde | lib/transform/standardize.js | mustBeNonEmptyObject | function mustBeNonEmptyObject(filter, keyword) {
if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
return Bluebird.reject(new BadRequestError(`"${keyword}" must be a non-empty object`));
}
const fields = Object.keys(filter);
if (fields.length === 0) {
return Bluebird.reject(new Bad... | javascript | function mustBeNonEmptyObject(filter, keyword) {
if (!filter || typeof filter !== 'object' || Array.isArray(filter)) {
return Bluebird.reject(new BadRequestError(`"${keyword}" must be a non-empty object`));
}
const fields = Object.keys(filter);
if (fields.length === 0) {
return Bluebird.reject(new Bad... | [
"function",
"mustBeNonEmptyObject",
"(",
"filter",
",",
"keyword",
")",
"{",
"if",
"(",
"!",
"filter",
"||",
"typeof",
"filter",
"!==",
"'object'",
"||",
"Array",
".",
"isArray",
"(",
"filter",
")",
")",
"{",
"return",
"Bluebird",
".",
"reject",
"(",
"ne... | Tests if "filter" is a non-object
@param {object} filter
@param {string} keyword
@returns {Promise} Promise resolving to the object's keys | [
"Tests",
"if",
"filter",
"is",
"a",
"non",
"-",
"object"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L720-L732 | train |
kuzzleio/koncorde | lib/transform/standardize.js | mustBeScalar | function mustBeScalar(filter, keyword, field) {
if (filter[field] instanceof Object || filter[field] === undefined) {
return Bluebird.reject(new BadRequestError(`"${field}" in "${keyword}" must be either a string, a number, a boolean or null`));
}
return Bluebird.resolve();
} | javascript | function mustBeScalar(filter, keyword, field) {
if (filter[field] instanceof Object || filter[field] === undefined) {
return Bluebird.reject(new BadRequestError(`"${field}" in "${keyword}" must be either a string, a number, a boolean or null`));
}
return Bluebird.resolve();
} | [
"function",
"mustBeScalar",
"(",
"filter",
",",
"keyword",
",",
"field",
")",
"{",
"if",
"(",
"filter",
"[",
"field",
"]",
"instanceof",
"Object",
"||",
"filter",
"[",
"field",
"]",
"===",
"undefined",
")",
"{",
"return",
"Bluebird",
".",
"reject",
"(",
... | Checks that filter.field is a scalar value
@param filter
@param keyword
@param field
@returns {*} | [
"Checks",
"that",
"filter",
".",
"field",
"is",
"a",
"scalar",
"value"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L741-L747 | train |
kuzzleio/koncorde | lib/transform/standardize.js | mustBeString | function mustBeString(filter, keyword, field) {
if (typeof filter[field] !== 'string') {
return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" must be a string`));
}
return Bluebird.resolve();
} | javascript | function mustBeString(filter, keyword, field) {
if (typeof filter[field] !== 'string') {
return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" must be a string`));
}
return Bluebird.resolve();
} | [
"function",
"mustBeString",
"(",
"filter",
",",
"keyword",
",",
"field",
")",
"{",
"if",
"(",
"typeof",
"filter",
"[",
"field",
"]",
"!==",
"'string'",
")",
"{",
"return",
"Bluebird",
".",
"reject",
"(",
"new",
"BadRequestError",
"(",
"`",
"${",
"field",... | Verifies that filter.field is a string
@param filter
@param keyword
@param field
@returns {Promise} | [
"Verifies",
"that",
"filter",
".",
"field",
"is",
"a",
"string"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L756-L762 | train |
kuzzleio/koncorde | lib/transform/standardize.js | mustBeNonEmptyArray | function mustBeNonEmptyArray(filter, keyword, field) {
if (!Array.isArray(filter[field])) {
return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" must be an array`));
}
if (filter[field].length === 0) {
return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${key... | javascript | function mustBeNonEmptyArray(filter, keyword, field) {
if (!Array.isArray(filter[field])) {
return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${keyword}" must be an array`));
}
if (filter[field].length === 0) {
return Bluebird.reject(new BadRequestError(`Attribute "${field}" in "${key... | [
"function",
"mustBeNonEmptyArray",
"(",
"filter",
",",
"keyword",
",",
"field",
")",
"{",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"filter",
"[",
"field",
"]",
")",
")",
"{",
"return",
"Bluebird",
".",
"reject",
"(",
"new",
"BadRequestError",
"(",
... | Verifies that filter.field is an array
@param filter
@param keyword
@param field
@returns {Promise} | [
"Verifies",
"that",
"filter",
".",
"field",
"is",
"an",
"array"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/transform/standardize.js#L771-L781 | train |
kuzzleio/koncorde | lib/storage/storeOperands.js | storeGeoshape | function storeGeoshape(index, type, id, shape) {
switch (type) {
case 'geoBoundingBox':
index.addBoundingBox(id,
shape.bottom,
shape.left,
shape.top,
shape.right
);
break;
case 'geoDistance':
index.addCircle(id, shape.lat, shape.lon, shape.distance);
... | javascript | function storeGeoshape(index, type, id, shape) {
switch (type) {
case 'geoBoundingBox':
index.addBoundingBox(id,
shape.bottom,
shape.left,
shape.top,
shape.right
);
break;
case 'geoDistance':
index.addCircle(id, shape.lat, shape.lon, shape.distance);
... | [
"function",
"storeGeoshape",
"(",
"index",
",",
"type",
",",
"id",
",",
"shape",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"'geoBoundingBox'",
":",
"index",
".",
"addBoundingBox",
"(",
"id",
",",
"shape",
".",
"bottom",
",",
"shape",
".",
"lef... | Stores a geospatial shape in the provided index object.
@param {object} index
@param {string} type
@param {string} id
@param {Object|Array} shape | [
"Stores",
"a",
"geospatial",
"shape",
"in",
"the",
"provided",
"index",
"object",
"."
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/storage/storeOperands.js#L299-L321 | train |
kuzzleio/koncorde | lib/util/convertGeopoint.js | convertGeopoint | function convertGeopoint (point) {
const t = typeof point;
if (!point || (t !== 'string' && t !== 'object')) {
return null;
}
// Format: "lat, lon" or "geohash"
if (t === 'string') {
return fromString(point);
}
// Format: [lat, lon]
if (Array.isArray(point)) {
if (point.length === 2) {
... | javascript | function convertGeopoint (point) {
const t = typeof point;
if (!point || (t !== 'string' && t !== 'object')) {
return null;
}
// Format: "lat, lon" or "geohash"
if (t === 'string') {
return fromString(point);
}
// Format: [lat, lon]
if (Array.isArray(point)) {
if (point.length === 2) {
... | [
"function",
"convertGeopoint",
"(",
"point",
")",
"{",
"const",
"t",
"=",
"typeof",
"point",
";",
"if",
"(",
"!",
"point",
"||",
"(",
"t",
"!==",
"'string'",
"&&",
"t",
"!==",
"'object'",
")",
")",
"{",
"return",
"null",
";",
"}",
"// Format: \"lat, lo... | Converts one of the accepted geopoint format into
a standardized version
@param {*} point - geopoint field to convert
@returns {Coordinate} or null if no accepted format is found | [
"Converts",
"one",
"of",
"the",
"accepted",
"geopoint",
"format",
"into",
"a",
"standardized",
"version"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/util/convertGeopoint.js#L40-L89 | train |
kuzzleio/koncorde | lib/util/convertGeopoint.js | fromString | function fromString(str) {
let
tmp = str.match(regexLatLon),
converted = null;
// Format: "latitude, longitude"
if (tmp !== null) {
converted = toCoordinate(tmp[1], tmp[2]);
}
// Format: "<geohash>"
else if (regexGeohash.test(str)) {
tmp = geohash.decode(str);
converted = toCoordinate(... | javascript | function fromString(str) {
let
tmp = str.match(regexLatLon),
converted = null;
// Format: "latitude, longitude"
if (tmp !== null) {
converted = toCoordinate(tmp[1], tmp[2]);
}
// Format: "<geohash>"
else if (regexGeohash.test(str)) {
tmp = geohash.decode(str);
converted = toCoordinate(... | [
"function",
"fromString",
"(",
"str",
")",
"{",
"let",
"tmp",
"=",
"str",
".",
"match",
"(",
"regexLatLon",
")",
",",
"converted",
"=",
"null",
";",
"// Format: \"latitude, longitude\"",
"if",
"(",
"tmp",
"!==",
"null",
")",
"{",
"converted",
"=",
"toCoord... | Converts a geopoint from a string description
@param {string} str
@return {Coordinate} | [
"Converts",
"a",
"geopoint",
"from",
"a",
"string",
"description"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/util/convertGeopoint.js#L97-L113 | train |
kuzzleio/koncorde | lib/util/geoLocationToCamelCase.js | geoLocationToCamelCase | function geoLocationToCamelCase (obj) {
const
converted = {},
keys = Object.keys(obj);
let i; // NOSONAR
for(i = 0; i < keys.length; i++) {
const
k = keys[i],
idx = ['lat_lon', 'top_left', 'bottom_right'].indexOf(k);
if (idx === -1) {
converted[k] = obj[k];
}
else {
... | javascript | function geoLocationToCamelCase (obj) {
const
converted = {},
keys = Object.keys(obj);
let i; // NOSONAR
for(i = 0; i < keys.length; i++) {
const
k = keys[i],
idx = ['lat_lon', 'top_left', 'bottom_right'].indexOf(k);
if (idx === -1) {
converted[k] = obj[k];
}
else {
... | [
"function",
"geoLocationToCamelCase",
"(",
"obj",
")",
"{",
"const",
"converted",
"=",
"{",
"}",
",",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
";",
"let",
"i",
";",
"// NOSONAR",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
... | Converts known geolocation fields from snake_case to camelCase
Other fields are copied without change
@param {object} obj - object containing geolocation fields
@returns {object} new object with converted fields | [
"Converts",
"known",
"geolocation",
"fields",
"from",
"snake_case",
"to",
"camelCase",
"Other",
"fields",
"are",
"copied",
"without",
"change"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/util/geoLocationToCamelCase.js#L31-L54 | train |
kuzzleio/koncorde | lib/util/convertDistance.js | convertDistance | function convertDistance (distance) {
let cleaned, converted;
// clean up to ensure node-units will be able to convert it
// for instance: "3 258,55 Ft" => "3258.55 ft"
cleaned = distance
.replace(/[-\s]/g, '')
.replace(/,/g, '.')
.toLowerCase()
.replace(/([0-9])([a-z])/, '$1 $2');
try {
... | javascript | function convertDistance (distance) {
let cleaned, converted;
// clean up to ensure node-units will be able to convert it
// for instance: "3 258,55 Ft" => "3258.55 ft"
cleaned = distance
.replace(/[-\s]/g, '')
.replace(/,/g, '.')
.toLowerCase()
.replace(/([0-9])([a-z])/, '$1 $2');
try {
... | [
"function",
"convertDistance",
"(",
"distance",
")",
"{",
"let",
"cleaned",
",",
"converted",
";",
"// clean up to ensure node-units will be able to convert it",
"// for instance: \"3 258,55 Ft\" => \"3258.55 ft\"",
"cleaned",
"=",
"distance",
".",
"replace",
"(",
"/",
"[-\\s... | Converts a distance string value to a number of meters
@param {string} distance - client-provided distance
@returns {number} resolves to converted distance | [
"Converts",
"a",
"distance",
"string",
"value",
"to",
"a",
"number",
"of",
"meters"
] | e23403920517494f86b7a566acf89d527065c4a2 | https://github.com/kuzzleio/koncorde/blob/e23403920517494f86b7a566acf89d527065c4a2/lib/util/convertDistance.js#L33-L52 | train |
tiaanduplessis/react-native-modest-cache | index.js | dateAdd | function dateAdd (date, interval, units) {
let result = new Date(date)
switch (interval.toLowerCase()) {
case 'year':
result.setFullYear(result.getFullYear() + units)
break
case 'quarter':
result.setMonth(result.getMonth() + 3 * units)
break
case 'month':
result.setMonth(r... | javascript | function dateAdd (date, interval, units) {
let result = new Date(date)
switch (interval.toLowerCase()) {
case 'year':
result.setFullYear(result.getFullYear() + units)
break
case 'quarter':
result.setMonth(result.getMonth() + 3 * units)
break
case 'month':
result.setMonth(r... | [
"function",
"dateAdd",
"(",
"date",
",",
"interval",
",",
"units",
")",
"{",
"let",
"result",
"=",
"new",
"Date",
"(",
"date",
")",
"switch",
"(",
"interval",
".",
"toLowerCase",
"(",
")",
")",
"{",
"case",
"'year'",
":",
"result",
".",
"setFullYear",
... | Utility function to add units to date based on interval
@param {Date} date
@param {String} interval
@param {Number} units | [
"Utility",
"function",
"to",
"add",
"units",
"to",
"date",
"based",
"on",
"interval"
] | 308de78c66c894b83da169ff43d7cbd356b88c76 | https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L12-L45 | train |
tiaanduplessis/react-native-modest-cache | index.js | set | function set (key, value, time = 60) {
let expireTime
const cacheKey = `${prefix}${key}`
const expireKey = `${expire}${key}`
if (typeof time === 'number') {
expireTime = dateAdd(Date.now(), 'minute', time)
} else if (time !== null && typeof time === 'object' && time.interval && time.units) {
expireTi... | javascript | function set (key, value, time = 60) {
let expireTime
const cacheKey = `${prefix}${key}`
const expireKey = `${expire}${key}`
if (typeof time === 'number') {
expireTime = dateAdd(Date.now(), 'minute', time)
} else if (time !== null && typeof time === 'object' && time.interval && time.units) {
expireTi... | [
"function",
"set",
"(",
"key",
",",
"value",
",",
"time",
"=",
"60",
")",
"{",
"let",
"expireTime",
"const",
"cacheKey",
"=",
"`",
"${",
"prefix",
"}",
"${",
"key",
"}",
"`",
"const",
"expireKey",
"=",
"`",
"${",
"expire",
"}",
"${",
"key",
"}",
... | Persist value and expire date of cache.
@param {string} key
@param {Any} value Value to persist
@param {Number or Object} [time=60] Time in minutes
@returns {Promise} | [
"Persist",
"value",
"and",
"expire",
"date",
"of",
"cache",
"."
] | 308de78c66c894b83da169ff43d7cbd356b88c76 | https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L55-L69 | train |
tiaanduplessis/react-native-modest-cache | index.js | remove | function remove (key) {
if (typeof key !== 'string') {
throw new Error('Invalid key provided for remove')
}
const keys = [`${prefix}${key}`, `${expire}${key}`]
return storage.remove(keys)
} | javascript | function remove (key) {
if (typeof key !== 'string') {
throw new Error('Invalid key provided for remove')
}
const keys = [`${prefix}${key}`, `${expire}${key}`]
return storage.remove(keys)
} | [
"function",
"remove",
"(",
"key",
")",
"{",
"if",
"(",
"typeof",
"key",
"!==",
"'string'",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid key provided for remove'",
")",
"}",
"const",
"keys",
"=",
"[",
"`",
"${",
"prefix",
"}",
"${",
"key",
"}",
"`"... | Remove cached value from storage
@param {String} key | [
"Remove",
"cached",
"value",
"from",
"storage"
] | 308de78c66c894b83da169ff43d7cbd356b88c76 | https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L75-L82 | train |
tiaanduplessis/react-native-modest-cache | index.js | isExpired | function isExpired (key) {
const expireKey = `${expire}${key}`
return storage
.get(expireKey)
.then(time => Promise.resolve(Date.now() >= new Date(time).getTime(), time))
} | javascript | function isExpired (key) {
const expireKey = `${expire}${key}`
return storage
.get(expireKey)
.then(time => Promise.resolve(Date.now() >= new Date(time).getTime(), time))
} | [
"function",
"isExpired",
"(",
"key",
")",
"{",
"const",
"expireKey",
"=",
"`",
"${",
"expire",
"}",
"${",
"key",
"}",
"`",
"return",
"storage",
".",
"get",
"(",
"expireKey",
")",
".",
"then",
"(",
"time",
"=>",
"Promise",
".",
"resolve",
"(",
"Date",... | Determine if cache has expired
@param {String} key | [
"Determine",
"if",
"cache",
"has",
"expired"
] | 308de78c66c894b83da169ff43d7cbd356b88c76 | https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L88-L93 | train |
tiaanduplessis/react-native-modest-cache | index.js | get | function get (key) {
return isExpired(key).then(hasExpired => {
if (hasExpired) {
return remove(key).then(() => Promise.resolve(undefined))
} else {
return storage.get(`${prefix}${key}`)
}
})
} | javascript | function get (key) {
return isExpired(key).then(hasExpired => {
if (hasExpired) {
return remove(key).then(() => Promise.resolve(undefined))
} else {
return storage.get(`${prefix}${key}`)
}
})
} | [
"function",
"get",
"(",
"key",
")",
"{",
"return",
"isExpired",
"(",
"key",
")",
".",
"then",
"(",
"hasExpired",
"=>",
"{",
"if",
"(",
"hasExpired",
")",
"{",
"return",
"remove",
"(",
"key",
")",
".",
"then",
"(",
"(",
")",
"=>",
"Promise",
".",
... | Retrieve value from cache. Remove if expired.
@param {String} key | [
"Retrieve",
"value",
"from",
"cache",
".",
"Remove",
"if",
"expired",
"."
] | 308de78c66c894b83da169ff43d7cbd356b88c76 | https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L99-L107 | train |
tiaanduplessis/react-native-modest-cache | index.js | flush | function flush () {
return storage.keys().then(keys => {
return storage.remove(
keys.filter(key => key.indexOf(prefix) === 0 || key.indexOf(expire) === 0)
)
})
} | javascript | function flush () {
return storage.keys().then(keys => {
return storage.remove(
keys.filter(key => key.indexOf(prefix) === 0 || key.indexOf(expire) === 0)
)
})
} | [
"function",
"flush",
"(",
")",
"{",
"return",
"storage",
".",
"keys",
"(",
")",
".",
"then",
"(",
"keys",
"=>",
"{",
"return",
"storage",
".",
"remove",
"(",
"keys",
".",
"filter",
"(",
"key",
"=>",
"key",
".",
"indexOf",
"(",
"prefix",
")",
"===",... | Remove all cached values from storage | [
"Remove",
"all",
"cached",
"values",
"from",
"storage"
] | 308de78c66c894b83da169ff43d7cbd356b88c76 | https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L112-L118 | train |
tiaanduplessis/react-native-modest-cache | index.js | flushExpired | function flushExpired () {
return storage.keys().then(keys => {
const cacheKeys = keys.filter(key => key.indexOf(expire) === 0)
return Promise.all(cacheKeys.map(key => get(key.slice(prefix.length))))
})
} | javascript | function flushExpired () {
return storage.keys().then(keys => {
const cacheKeys = keys.filter(key => key.indexOf(expire) === 0)
return Promise.all(cacheKeys.map(key => get(key.slice(prefix.length))))
})
} | [
"function",
"flushExpired",
"(",
")",
"{",
"return",
"storage",
".",
"keys",
"(",
")",
".",
"then",
"(",
"keys",
"=>",
"{",
"const",
"cacheKeys",
"=",
"keys",
".",
"filter",
"(",
"key",
"=>",
"key",
".",
"indexOf",
"(",
"expire",
")",
"===",
"0",
"... | Remove all expired values from storage | [
"Remove",
"all",
"expired",
"values",
"from",
"storage"
] | 308de78c66c894b83da169ff43d7cbd356b88c76 | https://github.com/tiaanduplessis/react-native-modest-cache/blob/308de78c66c894b83da169ff43d7cbd356b88c76/index.js#L123-L128 | train |
fb55/readabilitySAX | readabilitySAX.js | function(tagName, parent){
this.name = tagName;
this.parent = parent;
this.attributes = {};
this.children = [];
this.tagScore = 0;
this.attributeScore = 0;
this.totalScore = 0;
this.elementData = "";
this.info = {
textLength: 0,
linkLength: 0,
commas: 0,
density: 0,
tagCount: {}
};
this.isCandidat... | javascript | function(tagName, parent){
this.name = tagName;
this.parent = parent;
this.attributes = {};
this.children = [];
this.tagScore = 0;
this.attributeScore = 0;
this.totalScore = 0;
this.elementData = "";
this.info = {
textLength: 0,
linkLength: 0,
commas: 0,
density: 0,
tagCount: {}
};
this.isCandidat... | [
"function",
"(",
"tagName",
",",
"parent",
")",
"{",
"this",
".",
"name",
"=",
"tagName",
";",
"this",
".",
"parent",
"=",
"parent",
";",
"this",
".",
"attributes",
"=",
"{",
"}",
";",
"this",
".",
"children",
"=",
"[",
"]",
";",
"this",
".",
"ta... | 1. the tree element | [
"1",
".",
"the",
"tree",
"element"
] | ed3566bcc0e841f596612e295b69376ec359938c | https://github.com/fb55/readabilitySAX/blob/ed3566bcc0e841f596612e295b69376ec359938c/readabilitySAX.js#L14-L31 | train | |
fb55/readabilitySAX | readabilitySAX.js | function(settings){
//the root node
this._currentElement = new Element("document");
this._topCandidate = null;
this._origTitle = this._headerTitle = "";
this._scannedLinks = {};
if(settings) this._processSettings(settings);
} | javascript | function(settings){
//the root node
this._currentElement = new Element("document");
this._topCandidate = null;
this._origTitle = this._headerTitle = "";
this._scannedLinks = {};
if(settings) this._processSettings(settings);
} | [
"function",
"(",
"settings",
")",
"{",
"//the root node",
"this",
".",
"_currentElement",
"=",
"new",
"Element",
"(",
"\"document\"",
")",
";",
"this",
".",
"_topCandidate",
"=",
"null",
";",
"this",
".",
"_origTitle",
"=",
"this",
".",
"_headerTitle",
"=",
... | 3. the readability class | [
"3",
".",
"the",
"readability",
"class"
] | ed3566bcc0e841f596612e295b69376ec359938c | https://github.com/fb55/readabilitySAX/blob/ed3566bcc0e841f596612e295b69376ec359938c/readabilitySAX.js#L190-L197 | train | |
silverwind/rrdir | index.js | canInclude | function canInclude(entry, opts) {
if (!opts.include || !opts.include.length) return true;
return !entry.isDirectory();
} | javascript | function canInclude(entry, opts) {
if (!opts.include || !opts.include.length) return true;
return !entry.isDirectory();
} | [
"function",
"canInclude",
"(",
"entry",
",",
"opts",
")",
"{",
"if",
"(",
"!",
"opts",
".",
"include",
"||",
"!",
"opts",
".",
"include",
".",
"length",
")",
"return",
"true",
";",
"return",
"!",
"entry",
".",
"isDirectory",
"(",
")",
";",
"}"
] | when a include pattern is specified, stop yielding directories | [
"when",
"a",
"include",
"pattern",
"is",
"specified",
"stop",
"yielding",
"directories"
] | 340889bb8e84ab81fa212e539266f06fb0778c48 | https://github.com/silverwind/rrdir/blob/340889bb8e84ab81fa212e539266f06fb0778c48/index.js#L35-L38 | train |
vasturiano/canvas-color-tracker | example/circle-generator.js | genCircles | function genCircles(width, height, N = 500) {
const minR = 1;
const maxR = Math.sqrt(width * height / N) * 0.5;
return [...Array(N)].map((_, idx) => ({
id: idx,
x: Math.round(Math.random() * width),
y: Math.round(Math.random() * height),
r: Math.max(minR, Math.round(Math.random() * maxR))
}));
... | javascript | function genCircles(width, height, N = 500) {
const minR = 1;
const maxR = Math.sqrt(width * height / N) * 0.5;
return [...Array(N)].map((_, idx) => ({
id: idx,
x: Math.round(Math.random() * width),
y: Math.round(Math.random() * height),
r: Math.max(minR, Math.round(Math.random() * maxR))
}));
... | [
"function",
"genCircles",
"(",
"width",
",",
"height",
",",
"N",
"=",
"500",
")",
"{",
"const",
"minR",
"=",
"1",
";",
"const",
"maxR",
"=",
"Math",
".",
"sqrt",
"(",
"width",
"*",
"height",
"/",
"N",
")",
"*",
"0.5",
";",
"return",
"[",
"...",
... | Generate random circles | [
"Generate",
"random",
"circles"
] | 90ac081b236a5d034ae0529f222ca2b0840ec483 | https://github.com/vasturiano/canvas-color-tracker/blob/90ac081b236a5d034ae0529f222ca2b0840ec483/example/circle-generator.js#L2-L12 | train |
cloudfour/core-hbs-helpers | lib/toFraction.js | toFraction | function toFraction (value) {
var integer = Math.floor(value);
var decimal = value - integer;
var key = n2f(decimal);
var result = value;
if (vulgarities.hasOwnProperty(key)) {
result = integer + vulgarities[key];
}
return result;
} | javascript | function toFraction (value) {
var integer = Math.floor(value);
var decimal = value - integer;
var key = n2f(decimal);
var result = value;
if (vulgarities.hasOwnProperty(key)) {
result = integer + vulgarities[key];
}
return result;
} | [
"function",
"toFraction",
"(",
"value",
")",
"{",
"var",
"integer",
"=",
"Math",
".",
"floor",
"(",
"value",
")",
";",
"var",
"decimal",
"=",
"value",
"-",
"integer",
";",
"var",
"key",
"=",
"n2f",
"(",
"decimal",
")",
";",
"var",
"result",
"=",
"v... | Format a decimal as a fractional HTML entity if possible.
@since v0.0.1
@param {Number} value
@return {String|Number}
@example
{{toFraction 1.25}} //=> "1¼"
{{toFraction 3.1666}} //=> "3⅙"
{{toFraction 2.7}} //=> 2.7 | [
"Format",
"a",
"decimal",
"as",
"a",
"fractional",
"HTML",
"entity",
"if",
"possible",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/toFraction.js#L35-L46 | train |
cloudfour/core-hbs-helpers | lib/dummyImgSrc.js | dummyImgSrc | function dummyImgSrc (width, height, options) {
if (!R.is(Number, width) || !R.is(Number, height)) {
throw new Error('The "dummyImgSrc" helper must be passed two numeric dimensions.');
}
var result = encode(create(width, height, options.hash));
return new Handlebars.SafeString(result);
} | javascript | function dummyImgSrc (width, height, options) {
if (!R.is(Number, width) || !R.is(Number, height)) {
throw new Error('The "dummyImgSrc" helper must be passed two numeric dimensions.');
}
var result = encode(create(width, height, options.hash));
return new Handlebars.SafeString(result);
} | [
"function",
"dummyImgSrc",
"(",
"width",
",",
"height",
",",
"options",
")",
"{",
"if",
"(",
"!",
"R",
".",
"is",
"(",
"Number",
",",
"width",
")",
"||",
"!",
"R",
".",
"is",
"(",
"Number",
",",
"height",
")",
")",
"{",
"throw",
"new",
"Error",
... | Returns an escaped data URI for a placeholder image that can be used as the
src attribute of an img element.
@since v0.3.0
@param {Number} width
@param {Number} height
@param {Object} options
@return {String}
@example
<img src="{{dummyImgSrc 150 50}}">
<img src="{{dummyImgSrc 150 50 text="foo"}}">
<img src="{{dummyI... | [
"Returns",
"an",
"escaped",
"data",
"URI",
"for",
"a",
"placeholder",
"image",
"that",
"can",
"be",
"used",
"as",
"the",
"src",
"attribute",
"of",
"an",
"img",
"element",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/dummyImgSrc.js#L70-L78 | train |
cloudfour/core-hbs-helpers | lib/randomItem.js | randomItem | function randomItem () {
var items = R.dropLast(1, arguments);
if (!items.length) {
throw new Error('The helper "randomItem" must be passed at least one argument.');
}
if (items.length === 1) {
items = R.is(Array, items[0]) ? items[0] : [items[0]];
}
return items[Math.floor(Math.random() * items.... | javascript | function randomItem () {
var items = R.dropLast(1, arguments);
if (!items.length) {
throw new Error('The helper "randomItem" must be passed at least one argument.');
}
if (items.length === 1) {
items = R.is(Array, items[0]) ? items[0] : [items[0]];
}
return items[Math.floor(Math.random() * items.... | [
"function",
"randomItem",
"(",
")",
"{",
"var",
"items",
"=",
"R",
".",
"dropLast",
"(",
"1",
",",
"arguments",
")",
";",
"if",
"(",
"!",
"items",
".",
"length",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The helper \"randomItem\" must be passed at least one ... | Return only one random item. If only one argument is provided and it is an
array, it will return a random item from that array. Otherwise it will return
one of the arguments.
@since v0.0.1
@param {...*} items
@return One random item.
@example
var beatles = ["John", "Paul", "George", "Ringo"];
{{randomItem beatles}} //... | [
"Return",
"only",
"one",
"random",
"item",
".",
"If",
"only",
"one",
"argument",
"is",
"provided",
"and",
"it",
"is",
"an",
"array",
"it",
"will",
"return",
"a",
"random",
"item",
"from",
"that",
"array",
".",
"Otherwise",
"it",
"will",
"return",
"one",
... | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/randomItem.js#L20-L32 | train |
cloudfour/core-hbs-helpers | lib/compare.js | compare | function compare (left, operator, right, options) {
var result;
if (arguments.length < 3) {
throw new Error('The "compare" helper needs two arguments.');
}
if (options === undefined) {
options = right;
right = operator;
operator = '===';
}
if (operators[operator] === undefined) {
th... | javascript | function compare (left, operator, right, options) {
var result;
if (arguments.length < 3) {
throw new Error('The "compare" helper needs two arguments.');
}
if (options === undefined) {
options = right;
right = operator;
operator = '===';
}
if (operators[operator] === undefined) {
th... | [
"function",
"compare",
"(",
"left",
",",
"operator",
",",
"right",
",",
"options",
")",
"{",
"var",
"result",
";",
"if",
"(",
"arguments",
".",
"length",
"<",
"3",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The \"compare\" helper needs two arguments.'",
")",
... | Compare two values using logical operators.
@credit: github.com/assemble
@param {*} left
@param {String} operator
@param {*} right
@param {Object} options
@return {(String|Boolean)} formatted html if block, true/false if inline
@example:
{{#compare 1 "<" 2}}
This is true.
{{else}}
This is false.
{{/compare}}
{{#if (c... | [
"Compare",
"two",
"values",
"using",
"logical",
"operators",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/compare.js#L38-L62 | train |
cloudfour/core-hbs-helpers | lib/capitalizeWords.js | capitalizeWords | function capitalizeWords (str) {
if (R.isNil(str)) {
throw new Error('The "capitalizeWords" helper requires one argument.')
}
if (!R.is(String, str)) {
str = str.toString();
}
return Capitalize.words(str);
} | javascript | function capitalizeWords (str) {
if (R.isNil(str)) {
throw new Error('The "capitalizeWords" helper requires one argument.')
}
if (!R.is(String, str)) {
str = str.toString();
}
return Capitalize.words(str);
} | [
"function",
"capitalizeWords",
"(",
"str",
")",
"{",
"if",
"(",
"R",
".",
"isNil",
"(",
"str",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The \"capitalizeWords\" helper requires one argument.'",
")",
"}",
"if",
"(",
"!",
"R",
".",
"is",
"(",
"String",
... | Capitalize each word in a String. Works with punctuation and international
characters.
@since 0.4.0
@param {String|*} str - String to capitalize. Other types will be converted.
@return {String}
@example:
{{capitalizeWords "hello world"}} //=> "Hello World"
{{capitalizeWords "hello-cañapolísas"}} //=> "Hello-Cañapolísa... | [
"Capitalize",
"each",
"word",
"in",
"a",
"String",
".",
"Works",
"with",
"punctuation",
"and",
"international",
"characters",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/capitalizeWords.js#L19-L29 | train |
cloudfour/core-hbs-helpers | lib/replaceAll.js | replaceAll | function replaceAll (input, find, replace) {
let regex = new RegExp(find, 'g');
return input.toString().replace(regex, replace);
} | javascript | function replaceAll (input, find, replace) {
let regex = new RegExp(find, 'g');
return input.toString().replace(regex, replace);
} | [
"function",
"replaceAll",
"(",
"input",
",",
"find",
",",
"replace",
")",
"{",
"let",
"regex",
"=",
"new",
"RegExp",
"(",
"find",
",",
"'g'",
")",
";",
"return",
"input",
".",
"toString",
"(",
")",
".",
"replace",
"(",
"regex",
",",
"replace",
")",
... | Replace all occurrences of a string in another string
Can also be used on numbers, though they'll be treated as strings.
Case sensitive
@since 0.6.1
@return {String}
@param {Number|String} input
@param {Number|String} find
@param {Number|String} replace
@example
{{replaceAll "9:00" ":00" ""}} //=> "9"
{{replaceAll "ex... | [
"Replace",
"all",
"occurrences",
"of",
"a",
"string",
"in",
"another",
"string",
"Can",
"also",
"be",
"used",
"on",
"numbers",
"though",
"they",
"ll",
"be",
"treated",
"as",
"strings",
".",
"Case",
"sensitive"
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/replaceAll.js#L20-L23 | train |
cloudfour/core-hbs-helpers | lib/around.js | around | function around (items, center, padding, block) {
var result = '';
var options = (block && block.hash) ? R.merge(defaults, block.hash) : R.clone(defaults);
var max, start, end;
center = parseFloat(center) + options.offset;
padding = parseFloat(padding);
max = padding * 2 + 1;
if (items.length > max) {
... | javascript | function around (items, center, padding, block) {
var result = '';
var options = (block && block.hash) ? R.merge(defaults, block.hash) : R.clone(defaults);
var max, start, end;
center = parseFloat(center) + options.offset;
padding = parseFloat(padding);
max = padding * 2 + 1;
if (items.length > max) {
... | [
"function",
"around",
"(",
"items",
",",
"center",
",",
"padding",
",",
"block",
")",
"{",
"var",
"result",
"=",
"''",
";",
"var",
"options",
"=",
"(",
"block",
"&&",
"block",
".",
"hash",
")",
"?",
"R",
".",
"merge",
"(",
"defaults",
",",
"block",... | Slices a list based on a center-point and a maximum amount of "padding"
before and after. Useful for pagination.
Supports an optional <code>offset</code> hash option in case your center
value isn't matching up with your array indexes.
@since v0.0.1
@param {Array} items - Collection to iterate over.
@param {Number} ce... | [
"Slices",
"a",
"list",
"based",
"on",
"a",
"center",
"-",
"point",
"and",
"a",
"maximum",
"amount",
"of",
"padding",
"before",
"and",
"after",
".",
"Useful",
"for",
"pagination",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/around.js#L39-L70 | train |
cloudfour/core-hbs-helpers | lib/average.js | average | function average (arr, options) {
var isArray = Array.isArray(arr);
var key = options.hash.key;
var sum;
if (!isArray) {
throw new Error('The helper "average" must be passed an Array.');
}
if (key) {
arr = arr.map(function (item) {
return item[key];
});
}
sum = arr.reduce(function (pr... | javascript | function average (arr, options) {
var isArray = Array.isArray(arr);
var key = options.hash.key;
var sum;
if (!isArray) {
throw new Error('The helper "average" must be passed an Array.');
}
if (key) {
arr = arr.map(function (item) {
return item[key];
});
}
sum = arr.reduce(function (pr... | [
"function",
"average",
"(",
"arr",
",",
"options",
")",
"{",
"var",
"isArray",
"=",
"Array",
".",
"isArray",
"(",
"arr",
")",
";",
"var",
"key",
"=",
"options",
".",
"hash",
".",
"key",
";",
"var",
"sum",
";",
"if",
"(",
"!",
"isArray",
")",
"{",... | Average an array of numeric values.
@since v0.0.1
@param {Array} arr
@return {Number} Returns the average of all values.
@example
var numbers = [1, 2, 3];
var products = [{rating: 1}, {rating: 2}, {rating: 3}];
{{average ratings}} //=> 2
{{average products key="rating"}} //=> 2 | [
"Average",
"an",
"array",
"of",
"numeric",
"values",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/average.js#L17-L34 | train |
cloudfour/core-hbs-helpers | lib/toSlug.js | toSlug | function toSlug (str) {
return str
.toString()
.toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '-') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
... | javascript | function toSlug (str) {
return str
.toString()
.toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '-') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
... | [
"function",
"toSlug",
"(",
"str",
")",
"{",
"return",
"str",
".",
"toString",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"replace",
"(",
"/",
"\\s+",
"/",
"g",
",",
"'-'",
")",
"// Replace spaces with -",
".",
"replace",
"(",
"/",
"[^\\w\\-]+",
"/",
... | Format a string as a lowercase, URL-friendly value.
@since v0.0.1
@param {String} str
@return {String}
@example
{{toSlug "Well, hello there!"}} //=> "well-hello-there" | [
"Format",
"a",
"string",
"as",
"a",
"lowercase",
"URL",
"-",
"friendly",
"value",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/toSlug.js#L13-L22 | train |
cloudfour/core-hbs-helpers | lib/concat.js | concat | function concat () {
var items = R.dropLast(1, arguments);
if (!items.length) {
throw new Error('The helper "concat" must be passed at least one argument.');
}
return items.join('');
} | javascript | function concat () {
var items = R.dropLast(1, arguments);
if (!items.length) {
throw new Error('The helper "concat" must be passed at least one argument.');
}
return items.join('');
} | [
"function",
"concat",
"(",
")",
"{",
"var",
"items",
"=",
"R",
".",
"dropLast",
"(",
"1",
",",
"arguments",
")",
";",
"if",
"(",
"!",
"items",
".",
"length",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The helper \"concat\" must be passed at least one argument... | Concatenate items into a single string.
@since v0.8.0
@param {...*} items
@return string
@example
{{concat "foo" "bar"}} //=> "foobar" | [
"Concatenate",
"items",
"into",
"a",
"single",
"string",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/concat.js#L14-L22 | train |
cloudfour/core-hbs-helpers | lib/iterate.js | iterate | function iterate (num, block) {
return R.times(function (i) {
var data = block.data ? R.merge(
Handlebars.createFrame(block.data),
{ index: i, count: i + 1}
) : null;
return block.fn(i, {data: data});
}, num).join('');
} | javascript | function iterate (num, block) {
return R.times(function (i) {
var data = block.data ? R.merge(
Handlebars.createFrame(block.data),
{ index: i, count: i + 1}
) : null;
return block.fn(i, {data: data});
}, num).join('');
} | [
"function",
"iterate",
"(",
"num",
",",
"block",
")",
"{",
"return",
"R",
".",
"times",
"(",
"function",
"(",
"i",
")",
"{",
"var",
"data",
"=",
"block",
".",
"data",
"?",
"R",
".",
"merge",
"(",
"Handlebars",
".",
"createFrame",
"(",
"block",
".",... | Repeat a block a given amount of times.
@credit https://github.com/fbrctr/fabricator-assemble
@since v0.0.2
@example
{{#iterate 10}}
<li>Index: {{@index}} Count: {{@count}}</li>
{{/iterate}} | [
"Repeat",
"a",
"block",
"a",
"given",
"amount",
"of",
"times",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/iterate.js#L17-L26 | train |
cloudfour/core-hbs-helpers | lib/toJSON.js | toJSON | function toJSON (str) {
str = str.toString();
try {
return JSON.parse(str);
} catch (e) {
throw new Error(
'The "toJSON" helper must be passed a valid JSON string.'
);
}
} | javascript | function toJSON (str) {
str = str.toString();
try {
return JSON.parse(str);
} catch (e) {
throw new Error(
'The "toJSON" helper must be passed a valid JSON string.'
);
}
} | [
"function",
"toJSON",
"(",
"str",
")",
"{",
"str",
"=",
"str",
".",
"toString",
"(",
")",
";",
"try",
"{",
"return",
"JSON",
".",
"parse",
"(",
"str",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The \"toJSON\" helper... | Converts a string to JSON; useful when used in helper sub-expressions.
@since v0.0.1
@param {String} str
@return {Array|Object}
@example
{{#each (toJSON '[1,2,3]')}}{{this}}{{/each}} //=> '123' | [
"Converts",
"a",
"string",
"to",
"JSON",
";",
"useful",
"when",
"used",
"in",
"helper",
"sub",
"-",
"expressions",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/toJSON.js#L13-L22 | train |
cloudfour/core-hbs-helpers | lib/capitalize.js | capitalize | function capitalize (str) {
if (R.isNil(str)) {
throw new Error('The "capitalize" helper requires one argument.')
}
if (!R.is(String, str)) {
str = str.toString();
}
return Capitalize(str);
} | javascript | function capitalize (str) {
if (R.isNil(str)) {
throw new Error('The "capitalize" helper requires one argument.')
}
if (!R.is(String, str)) {
str = str.toString();
}
return Capitalize(str);
} | [
"function",
"capitalize",
"(",
"str",
")",
"{",
"if",
"(",
"R",
".",
"isNil",
"(",
"str",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The \"capitalize\" helper requires one argument.'",
")",
"}",
"if",
"(",
"!",
"R",
".",
"is",
"(",
"String",
",",
"... | Capitalize the first letter of a String.
@since 0.4.0
@param {String|*} str - String to capitalize. Other types will be converted.
@return {String}
@example:
{{capitalize "hello world"}} //=> "Hello world" | [
"Capitalize",
"the",
"first",
"letter",
"of",
"a",
"String",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/capitalize.js#L16-L26 | train |
cloudfour/core-hbs-helpers | lib/math.js | math | function math (left, operator, right, options) {
if (arguments.length < 3) {
throw new Error('The "math" helper needs at least two arguments.');
}
if (options === undefined) {
options = right;
right = undefined;
}
left = parseFloat(left);
right = parseFloat(right);
if (operators[operator] =... | javascript | function math (left, operator, right, options) {
if (arguments.length < 3) {
throw new Error('The "math" helper needs at least two arguments.');
}
if (options === undefined) {
options = right;
right = undefined;
}
left = parseFloat(left);
right = parseFloat(right);
if (operators[operator] =... | [
"function",
"math",
"(",
"left",
",",
"operator",
",",
"right",
",",
"options",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"<",
"3",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The \"math\" helper needs at least two arguments.'",
")",
";",
"}",
"if",
"... | Perform mathematical operations on one or two values.
@param {*} left
@param {String} operator
@param {*} right
@param {Object} options
@return {Number}
@example:
{{math 1 "+" 2}} //=> 3
{{math 2 "-" 1}} //=> 1
{{math 2 "*" 3}} //=> 6
{{math 9 "/" 3}} //=> 3
{{math 17 "%" 3}} //=> 2
{{math 2 "**" 3}} //=> 8
{{math 1 "... | [
"Perform",
"mathematical",
"operations",
"on",
"one",
"or",
"two",
"values",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/math.js#L35-L53 | train |
cloudfour/core-hbs-helpers | lib/defaultTo.js | defaultTo | function defaultTo () {
var values = R.append('', R.dropLast(1, arguments));
return R.head(R.reject(R.isNil, values));
} | javascript | function defaultTo () {
var values = R.append('', R.dropLast(1, arguments));
return R.head(R.reject(R.isNil, values));
} | [
"function",
"defaultTo",
"(",
")",
"{",
"var",
"values",
"=",
"R",
".",
"append",
"(",
"''",
",",
"R",
".",
"dropLast",
"(",
"1",
",",
"arguments",
")",
")",
";",
"return",
"R",
".",
"head",
"(",
"R",
".",
"reject",
"(",
"R",
".",
"isNil",
",",... | Output the first provided value that exists, or fallback to a default if
none do.
@since v0.0.1
@param {...*} value
@return {String}
@example
var doesExist = 'Hello';
{{defaultTo doesExist "Goodbye"}} // => "Hello"
{{defaultTo doesNotExist "Goodbye"}} // => "Goodbye"
{{defaultTo doesNotExist}} // => ""
{{defaultTo do... | [
"Output",
"the",
"first",
"provided",
"value",
"that",
"exists",
"or",
"fallback",
"to",
"a",
"default",
"if",
"none",
"do",
"."
] | 26ca9d12b08b83f2c379ea1de4bb27cd85f416f7 | https://github.com/cloudfour/core-hbs-helpers/blob/26ca9d12b08b83f2c379ea1de4bb27cd85f416f7/lib/defaultTo.js#L21-L24 | train |
ostdotcom/base | lib/ost_web3/ost-web3-providers-ws.js | function(iOstWSProvider) {
const oThis = this;
oThis.iOstWSProvider = iOstWSProvider;
oThis.endPointUrl = iOstWSProvider.endPointUrl;
oThis.notificationCallbacks = iOstWSProvider.notificationCallbacks;
const options = iOstWSProvider.options;
Object.assign(oThis, options);
oThis.reconnect();
} | javascript | function(iOstWSProvider) {
const oThis = this;
oThis.iOstWSProvider = iOstWSProvider;
oThis.endPointUrl = iOstWSProvider.endPointUrl;
oThis.notificationCallbacks = iOstWSProvider.notificationCallbacks;
const options = iOstWSProvider.options;
Object.assign(oThis, options);
oThis.reconnect();
} | [
"function",
"(",
"iOstWSProvider",
")",
"{",
"const",
"oThis",
"=",
"this",
";",
"oThis",
".",
"iOstWSProvider",
"=",
"iOstWSProvider",
";",
"oThis",
".",
"endPointUrl",
"=",
"iOstWSProvider",
".",
"endPointUrl",
";",
"oThis",
".",
"notificationCallbacks",
"=",
... | Reconnector Class. | [
"Reconnector",
"Class",
"."
] | 0f799337ae59e09abeddc4afc8e4a739397533c4 | https://github.com/ostdotcom/base/blob/0f799337ae59e09abeddc4afc8e4a739397533c4/lib/ost_web3/ost-web3-providers-ws.js#L253-L264 | train | |
ostdotcom/base | lib/logger/custom_console_logger.js | function(moduleName, logLevel) {
var oThis = this;
if (moduleName) {
oThis.moduleNamePrefix = '[' + moduleName + ']';
}
oThis.setLogLevel(logLevel);
} | javascript | function(moduleName, logLevel) {
var oThis = this;
if (moduleName) {
oThis.moduleNamePrefix = '[' + moduleName + ']';
}
oThis.setLogLevel(logLevel);
} | [
"function",
"(",
"moduleName",
",",
"logLevel",
")",
"{",
"var",
"oThis",
"=",
"this",
";",
"if",
"(",
"moduleName",
")",
"{",
"oThis",
".",
"moduleNamePrefix",
"=",
"'['",
"+",
"moduleName",
"+",
"']'",
";",
"}",
"oThis",
".",
"setLogLevel",
"(",
"log... | Custom Console Logger
@constructor | [
"Custom",
"Console",
"Logger"
] | 0f799337ae59e09abeddc4afc8e4a739397533c4 | https://github.com/ostdotcom/base/blob/0f799337ae59e09abeddc4afc8e4a739397533c4/lib/logger/custom_console_logger.js#L91-L99 | train | |
ostdotcom/base | lib/logger/custom_console_logger.js | function(requestUrl, requestType) {
const oThis = this,
d = new Date(),
dateTime =
d.getFullYear() +
'-' +
(d.getMonth() + 1) +
'-' +
d.getDate() +
' ' +
d.getHours() +
':' +
d.getMinutes() +
':' +
d.getSeconds() +
... | javascript | function(requestUrl, requestType) {
const oThis = this,
d = new Date(),
dateTime =
d.getFullYear() +
'-' +
(d.getMonth() + 1) +
'-' +
d.getDate() +
' ' +
d.getHours() +
':' +
d.getMinutes() +
':' +
d.getSeconds() +
... | [
"function",
"(",
"requestUrl",
",",
"requestType",
")",
"{",
"const",
"oThis",
"=",
"this",
",",
"d",
"=",
"new",
"Date",
"(",
")",
",",
"dateTime",
"=",
"d",
".",
"getFullYear",
"(",
")",
"+",
"'-'",
"+",
"(",
"d",
".",
"getMonth",
"(",
")",
"+"... | Method to Log Request Started. | [
"Method",
"to",
"Log",
"Request",
"Started",
"."
] | 0f799337ae59e09abeddc4afc8e4a739397533c4 | https://github.com/ostdotcom/base/blob/0f799337ae59e09abeddc4afc8e4a739397533c4/lib/logger/custom_console_logger.js#L238-L258 | train | |
ostdotcom/base | lib/logger/custom_console_logger.js | function() {
var oThis = this;
var argsPassed = oThis._filterArgs(arguments);
var args = [oThis.getPrefix(this.ERR_PRE)];
args = args.concat(Array.prototype.slice.call(argsPassed));
args.push(this.CONSOLE_RESET);
console.log.apply(console, args);
} | javascript | function() {
var oThis = this;
var argsPassed = oThis._filterArgs(arguments);
var args = [oThis.getPrefix(this.ERR_PRE)];
args = args.concat(Array.prototype.slice.call(argsPassed));
args.push(this.CONSOLE_RESET);
console.log.apply(console, args);
} | [
"function",
"(",
")",
"{",
"var",
"oThis",
"=",
"this",
";",
"var",
"argsPassed",
"=",
"oThis",
".",
"_filterArgs",
"(",
"arguments",
")",
";",
"var",
"args",
"=",
"[",
"oThis",
".",
"getPrefix",
"(",
"this",
".",
"ERR_PRE",
")",
"]",
";",
"args",
... | Log level error methods | [
"Log",
"level",
"error",
"methods"
] | 0f799337ae59e09abeddc4afc8e4a739397533c4 | https://github.com/ostdotcom/base/blob/0f799337ae59e09abeddc4afc8e4a739397533c4/lib/logger/custom_console_logger.js#L291-L300 | train | |
ostdotcom/base | lib/InstanceComposer.js | checkAvailability | function checkAvailability(fullGetterName) {
if (composerMap.hasOwnProperty(fullGetterName) || shadowMap.hasOwnProperty(fullGetterName)) {
console.trace('Duplicate Getter Method name', fullGetterName);
throw 'Duplicate Getter Method Name ';
}
} | javascript | function checkAvailability(fullGetterName) {
if (composerMap.hasOwnProperty(fullGetterName) || shadowMap.hasOwnProperty(fullGetterName)) {
console.trace('Duplicate Getter Method name', fullGetterName);
throw 'Duplicate Getter Method Name ';
}
} | [
"function",
"checkAvailability",
"(",
"fullGetterName",
")",
"{",
"if",
"(",
"composerMap",
".",
"hasOwnProperty",
"(",
"fullGetterName",
")",
"||",
"shadowMap",
".",
"hasOwnProperty",
"(",
"fullGetterName",
")",
")",
"{",
"console",
".",
"trace",
"(",
"'Duplica... | Check if full getter name is available
@param fullGetterName {string} - full getter name
Throws error if fullGetterName is not available, i.e. already taken. | [
"Check",
"if",
"full",
"getter",
"name",
"is",
"available"
] | 0f799337ae59e09abeddc4afc8e4a739397533c4 | https://github.com/ostdotcom/base/blob/0f799337ae59e09abeddc4afc8e4a739397533c4/lib/InstanceComposer.js#L30-L35 | train |
sapegin/mrm | src/index.js | promiseSeries | function promiseSeries(items, iterator) {
return items.reduce((iterable, name) => {
return iterable.then(() => iterator(name));
}, Promise.resolve());
} | javascript | function promiseSeries(items, iterator) {
return items.reduce((iterable, name) => {
return iterable.then(() => iterator(name));
}, Promise.resolve());
} | [
"function",
"promiseSeries",
"(",
"items",
",",
"iterator",
")",
"{",
"return",
"items",
".",
"reduce",
"(",
"(",
"iterable",
",",
"name",
")",
"=>",
"{",
"return",
"iterable",
".",
"then",
"(",
"(",
")",
"=>",
"iterator",
"(",
"name",
")",
")",
";",... | Runs an array of promises in series
@method promiseSeries
@param {Array} items
@param {Function} iterator
@return {Promise} | [
"Runs",
"an",
"array",
"of",
"promises",
"in",
"series"
] | f4892d3eee6bc52b3805181f2b813e8ea9eaba7f | https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L53-L57 | train |
sapegin/mrm | src/index.js | getConfigGetter | function getConfigGetter(options) {
/**
* Return a config value.
*
* @param {string} prop
* @param {any} [defaultValue]
* @return {any}
*/
function config(prop, defaultValue) {
console.warn(
'Warning: calling config as a function is deprecated. Use config.values() instead'
);
return get(options, ... | javascript | function getConfigGetter(options) {
/**
* Return a config value.
*
* @param {string} prop
* @param {any} [defaultValue]
* @return {any}
*/
function config(prop, defaultValue) {
console.warn(
'Warning: calling config as a function is deprecated. Use config.values() instead'
);
return get(options, ... | [
"function",
"getConfigGetter",
"(",
"options",
")",
"{",
"/**\n\t * Return a config value.\n\t *\n\t * @param {string} prop\n\t * @param {any} [defaultValue]\n\t * @return {any}\n\t */",
"function",
"config",
"(",
"prop",
",",
"defaultValue",
")",
"{",
"console",
".",
"warn",
"("... | Return a config getter.
@param {Object} options
@return {any} | [
"Return",
"a",
"config",
"getter",
"."
] | f4892d3eee6bc52b3805181f2b813e8ea9eaba7f | https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L150-L205 | train |
sapegin/mrm | src/index.js | require | function require(...names) {
const unknown = names.filter(name => !options[name]);
if (unknown.length > 0) {
throw new MrmUndefinedOption(`Required config options are missed: ${unknown.join(', ')}.`, {
unknown,
});
}
return config;
} | javascript | function require(...names) {
const unknown = names.filter(name => !options[name]);
if (unknown.length > 0) {
throw new MrmUndefinedOption(`Required config options are missed: ${unknown.join(', ')}.`, {
unknown,
});
}
return config;
} | [
"function",
"require",
"(",
"...",
"names",
")",
"{",
"const",
"unknown",
"=",
"names",
".",
"filter",
"(",
"name",
"=>",
"!",
"options",
"[",
"name",
"]",
")",
";",
"if",
"(",
"unknown",
".",
"length",
">",
"0",
")",
"{",
"throw",
"new",
"MrmUndef... | Mark config options as required.
@param {string[]} names...
@return {Object} this | [
"Mark",
"config",
"options",
"as",
"required",
"."
] | f4892d3eee6bc52b3805181f2b813e8ea9eaba7f | https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L180-L188 | train |
sapegin/mrm | src/index.js | getConfigFromFile | function getConfigFromFile(directories, filename) {
const filepath = tryFile(directories, filename);
if (!filepath) {
return {};
}
return require(filepath);
} | javascript | function getConfigFromFile(directories, filename) {
const filepath = tryFile(directories, filename);
if (!filepath) {
return {};
}
return require(filepath);
} | [
"function",
"getConfigFromFile",
"(",
"directories",
",",
"filename",
")",
"{",
"const",
"filepath",
"=",
"tryFile",
"(",
"directories",
",",
"filename",
")",
";",
"if",
"(",
"!",
"filepath",
")",
"{",
"return",
"{",
"}",
";",
"}",
"return",
"require",
"... | Find and load config file.
@param {string[]} directories
@param {string} filename
@return {Object} | [
"Find",
"and",
"load",
"config",
"file",
"."
] | f4892d3eee6bc52b3805181f2b813e8ea9eaba7f | https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L229-L236 | train |
sapegin/mrm | src/index.js | tryFile | function tryFile(directories, filename) {
return firstResult(directories, dir => {
const filepath = path.resolve(dir, filename);
return fs.existsSync(filepath) ? filepath : undefined;
});
} | javascript | function tryFile(directories, filename) {
return firstResult(directories, dir => {
const filepath = path.resolve(dir, filename);
return fs.existsSync(filepath) ? filepath : undefined;
});
} | [
"function",
"tryFile",
"(",
"directories",
",",
"filename",
")",
"{",
"return",
"firstResult",
"(",
"directories",
",",
"dir",
"=>",
"{",
"const",
"filepath",
"=",
"path",
".",
"resolve",
"(",
"dir",
",",
"filename",
")",
";",
"return",
"fs",
".",
"exist... | Try to load a file from a list of folders.
@param {string[]} directories
@param {string} filename
@return {string|undefined} Absolute path or undefined | [
"Try",
"to",
"load",
"a",
"file",
"from",
"a",
"list",
"of",
"folders",
"."
] | f4892d3eee6bc52b3805181f2b813e8ea9eaba7f | https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L261-L266 | train |
sapegin/mrm | src/index.js | firstResult | function firstResult(items, fn) {
for (const item of items) {
if (!item) {
continue;
}
const result = fn(item);
if (result) {
return result;
}
}
return undefined;
} | javascript | function firstResult(items, fn) {
for (const item of items) {
if (!item) {
continue;
}
const result = fn(item);
if (result) {
return result;
}
}
return undefined;
} | [
"function",
"firstResult",
"(",
"items",
",",
"fn",
")",
"{",
"for",
"(",
"const",
"item",
"of",
"items",
")",
"{",
"if",
"(",
"!",
"item",
")",
"{",
"continue",
";",
"}",
"const",
"result",
"=",
"fn",
"(",
"item",
")",
";",
"if",
"(",
"result",
... | Return the first truthy result of a callback.
@param {any[]} items
@param {Function} fn
@return {any} | [
"Return",
"the",
"first",
"truthy",
"result",
"of",
"a",
"callback",
"."
] | f4892d3eee6bc52b3805181f2b813e8ea9eaba7f | https://github.com/sapegin/mrm/blob/f4892d3eee6bc52b3805181f2b813e8ea9eaba7f/src/index.js#L285-L297 | train |
zenozeng/color-hash | lib/color-hash.js | function(RGBArray) {
var hex = '#';
RGBArray.forEach(function(value) {
if (value < 16) {
hex += 0;
}
hex += value.toString(16);
});
return hex;
} | javascript | function(RGBArray) {
var hex = '#';
RGBArray.forEach(function(value) {
if (value < 16) {
hex += 0;
}
hex += value.toString(16);
});
return hex;
} | [
"function",
"(",
"RGBArray",
")",
"{",
"var",
"hex",
"=",
"'#'",
";",
"RGBArray",
".",
"forEach",
"(",
"function",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"<",
"16",
")",
"{",
"hex",
"+=",
"0",
";",
"}",
"hex",
"+=",
"value",
".",
"toString",... | Convert RGB Array to HEX
@param {Array} RGBArray - [R, G, B]
@returns {String} 6 digits hex starting with # | [
"Convert",
"RGB",
"Array",
"to",
"HEX"
] | ca0228156c0e0223268274376bbc94850cebe80c | https://github.com/zenozeng/color-hash/blob/ca0228156c0e0223268274376bbc94850cebe80c/lib/color-hash.js#L9-L18 | train | |
zenozeng/color-hash | lib/color-hash.js | function(H, S, L) {
H /= 360;
var q = L < 0.5 ? L * (1 + S) : L + S - L * S;
var p = 2 * L - q;
return [H + 1/3, H, H - 1/3].map(function(color) {
if(color < 0) {
color++;
}
if(color > 1) {
color--;
}
if(color < 1/6) {
color =... | javascript | function(H, S, L) {
H /= 360;
var q = L < 0.5 ? L * (1 + S) : L + S - L * S;
var p = 2 * L - q;
return [H + 1/3, H, H - 1/3].map(function(color) {
if(color < 0) {
color++;
}
if(color > 1) {
color--;
}
if(color < 1/6) {
color =... | [
"function",
"(",
"H",
",",
"S",
",",
"L",
")",
"{",
"H",
"/=",
"360",
";",
"var",
"q",
"=",
"L",
"<",
"0.5",
"?",
"L",
"*",
"(",
"1",
"+",
"S",
")",
":",
"L",
"+",
"S",
"-",
"L",
"*",
"S",
";",
"var",
"p",
"=",
"2",
"*",
"L",
"-",
... | Convert HSL to RGB
@see {@link http://zh.wikipedia.org/wiki/HSL和HSV色彩空间} for further information.
@param {Number} H Hue ∈ [0, 360)
@param {Number} S Saturation ∈ [0, 1]
@param {Number} L Lightness ∈ [0, 1]
@returns {Array} R, G, B ∈ [0, 255] | [
"Convert",
"HSL",
"to",
"RGB"
] | ca0228156c0e0223268274376bbc94850cebe80c | https://github.com/zenozeng/color-hash/blob/ca0228156c0e0223268274376bbc94850cebe80c/lib/color-hash.js#L29-L53 | train | |
zenozeng/color-hash | lib/color-hash.js | function(options) {
options = options || {};
var LS = [options.lightness, options.saturation].map(function(param) {
param = param || [0.35, 0.5, 0.65]; // note that 3 is a prime
return isArray(param) ? param.concat() : [param];
});
this.L = LS[0];
this.S = LS[1];
if (typeof op... | javascript | function(options) {
options = options || {};
var LS = [options.lightness, options.saturation].map(function(param) {
param = param || [0.35, 0.5, 0.65]; // note that 3 is a prime
return isArray(param) ? param.concat() : [param];
});
this.L = LS[0];
this.S = LS[1];
if (typeof op... | [
"function",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"LS",
"=",
"[",
"options",
".",
"lightness",
",",
"options",
".",
"saturation",
"]",
".",
"map",
"(",
"function",
"(",
"param",
")",
"{",
"param",
"=",
"pa... | Color Hash Class
@class | [
"Color",
"Hash",
"Class"
] | ca0228156c0e0223268274376bbc94850cebe80c | https://github.com/zenozeng/color-hash/blob/ca0228156c0e0223268274376bbc94850cebe80c/lib/color-hash.js#L64-L92 | train | |
functional-jslib/fjl | dist/amd/function/compose.js | compose | function compose() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return function (arg0) {
return (0, _array.reduceRight)(function (value, fn) {
return fn(value);
}, arg0, args);
};
} | javascript | function compose() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return function (arg0) {
return (0, _array.reduceRight)(function (value, fn) {
return fn(value);
}, arg0, args);
};
} | [
"function",
"compose",
"(",
")",
"{",
"for",
"(",
"var",
"_len",
"=",
"arguments",
".",
"length",
",",
"args",
"=",
"new",
"Array",
"(",
"_len",
")",
",",
"_key",
"=",
"0",
";",
"_key",
"<",
"_len",
";",
"_key",
"++",
")",
"{",
"args",
"[",
"_k... | Composes all functions passed in from right to left passing each functions return value to
the function on the left of itself.
@function module:function.compose
@type {Function}
@param args {...{Function}}
@returns {Function} | [
"Composes",
"all",
"functions",
"passed",
"in",
"from",
"right",
"to",
"left",
"passing",
"each",
"functions",
"return",
"value",
"to",
"the",
"function",
"on",
"the",
"left",
"of",
"itself",
"."
] | 5dd1faaf7d86a20e03e54df3044a8cb82f0cde43 | https://github.com/functional-jslib/fjl/blob/5dd1faaf7d86a20e03e54df3044a8cb82f0cde43/dist/amd/function/compose.js#L17-L27 | train |
zachowj/node-red-contrib-home-assistant-websocket | lib/mustache-context.js | NodeContext | function NodeContext(msg, parent, nodeContext, serverName) {
this.msgContext = new mustache.Context(msg, parent);
this.nodeContext = nodeContext;
this.serverName = serverName;
} | javascript | function NodeContext(msg, parent, nodeContext, serverName) {
this.msgContext = new mustache.Context(msg, parent);
this.nodeContext = nodeContext;
this.serverName = serverName;
} | [
"function",
"NodeContext",
"(",
"msg",
",",
"parent",
",",
"nodeContext",
",",
"serverName",
")",
"{",
"this",
".",
"msgContext",
"=",
"new",
"mustache",
".",
"Context",
"(",
"msg",
",",
"parent",
")",
";",
"this",
".",
"nodeContext",
"=",
"nodeContext",
... | Custom Mustache Context capable to collect message property and node
flow and global context | [
"Custom",
"Mustache",
"Context",
"capable",
"to",
"collect",
"message",
"property",
"and",
"node",
"flow",
"and",
"global",
"context"
] | aad4ab10e6307701eae8e3c558428082640f8ace | https://github.com/zachowj/node-red-contrib-home-assistant-websocket/blob/aad4ab10e6307701eae8e3c558428082640f8ace/lib/mustache-context.js#L25-L29 | train |
openshift/origin-web-common | dist/origin-web-common-services.js | function() {
window.OPENSHIFT_CONFIG.api.k8s.resources = api.k8s;
window.OPENSHIFT_CONFIG.api.openshift.resources = api.openshift;
window.OPENSHIFT_CONFIG.apis.groups = apis;
if (API_DISCOVERY_ERRORS.length) {
window.OPENSHIFT_CONFIG.apis.API_DISCOVERY_ERRORS = API_DISCOVERY_ERRORS;
}
next... | javascript | function() {
window.OPENSHIFT_CONFIG.api.k8s.resources = api.k8s;
window.OPENSHIFT_CONFIG.api.openshift.resources = api.openshift;
window.OPENSHIFT_CONFIG.apis.groups = apis;
if (API_DISCOVERY_ERRORS.length) {
window.OPENSHIFT_CONFIG.apis.API_DISCOVERY_ERRORS = API_DISCOVERY_ERRORS;
}
next... | [
"function",
"(",
")",
"{",
"window",
".",
"OPENSHIFT_CONFIG",
".",
"api",
".",
"k8s",
".",
"resources",
"=",
"api",
".",
"k8s",
";",
"window",
".",
"OPENSHIFT_CONFIG",
".",
"api",
".",
"openshift",
".",
"resources",
"=",
"api",
".",
"openshift",
";",
"... | Will be called on success or failure | [
"Will",
"be",
"called",
"on",
"success",
"or",
"failure"
] | a56152ba5a42b95bd91c0e65531f6104b9a4dc8f | https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L566-L574 | train | |
openshift/origin-web-common | dist/origin-web-common-services.js | ResourceGroupVersion | function ResourceGroupVersion(resource, group, version) {
this.resource = resource;
this.group = group;
this.version = version;
return this;
} | javascript | function ResourceGroupVersion(resource, group, version) {
this.resource = resource;
this.group = group;
this.version = version;
return this;
} | [
"function",
"ResourceGroupVersion",
"(",
"resource",
",",
"group",
",",
"version",
")",
"{",
"this",
".",
"resource",
"=",
"resource",
";",
"this",
".",
"group",
"=",
"group",
";",
"this",
".",
"version",
"=",
"version",
";",
"return",
"this",
";",
"}"
] | ResourceGroupVersion represents a fully qualified resource | [
"ResourceGroupVersion",
"represents",
"a",
"fully",
"qualified",
"resource"
] | a56152ba5a42b95bd91c0e65531f6104b9a4dc8f | https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L611-L616 | train |
openshift/origin-web-common | dist/origin-web-common-services.js | normalizeResource | function normalizeResource(resource) {
if (!resource) {
return resource;
}
var i = resource.indexOf('/');
if (i === -1) {
return resource.toLowerCase();
}
return resource.substring(0, i).toLowerCase() + resource.substring(i);
} | javascript | function normalizeResource(resource) {
if (!resource) {
return resource;
}
var i = resource.indexOf('/');
if (i === -1) {
return resource.toLowerCase();
}
return resource.substring(0, i).toLowerCase() + resource.substring(i);
} | [
"function",
"normalizeResource",
"(",
"resource",
")",
"{",
"if",
"(",
"!",
"resource",
")",
"{",
"return",
"resource",
";",
"}",
"var",
"i",
"=",
"resource",
".",
"indexOf",
"(",
"'/'",
")",
";",
"if",
"(",
"i",
"===",
"-",
"1",
")",
"{",
"return"... | normalizeResource lowercases the first segment of the given resource. subresources can be case-sensitive. | [
"normalizeResource",
"lowercases",
"the",
"first",
"segment",
"of",
"the",
"given",
"resource",
".",
"subresources",
"can",
"be",
"case",
"-",
"sensitive",
"."
] | a56152ba5a42b95bd91c0e65531f6104b9a4dc8f | https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L702-L711 | train |
openshift/origin-web-common | dist/origin-web-common-services.js | function(includeClusterScoped) {
var kinds = [];
var rejectedKinds = _.map(Constants.AVAILABLE_KINDS_BLACKLIST, function(kind) {
return _.isString(kind) ?
{ kind: kind, group: '' } :
kind;
});
// ignore the legacy openshift kinds, these have been migrated to api groups... | javascript | function(includeClusterScoped) {
var kinds = [];
var rejectedKinds = _.map(Constants.AVAILABLE_KINDS_BLACKLIST, function(kind) {
return _.isString(kind) ?
{ kind: kind, group: '' } :
kind;
});
// ignore the legacy openshift kinds, these have been migrated to api groups... | [
"function",
"(",
"includeClusterScoped",
")",
"{",
"var",
"kinds",
"=",
"[",
"]",
";",
"var",
"rejectedKinds",
"=",
"_",
".",
"map",
"(",
"Constants",
".",
"AVAILABLE_KINDS_BLACKLIST",
",",
"function",
"(",
"kind",
")",
"{",
"return",
"_",
".",
"isString",... | Returns an array of available kinds, including their group | [
"Returns",
"an",
"array",
"of",
"available",
"kinds",
"including",
"their",
"group"
] | a56152ba5a42b95bd91c0e65531f6104b9a4dc8f | https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L918-L973 | train | |
openshift/origin-web-common | dist/origin-web-common-services.js | function() {
var user = userStore.getUser();
if (user) {
$rootScope.user = user;
authLogger.log('AuthService.withUser()', user);
return $q.when(user);
} else {
authLogger.log('AuthService.withUser(), calling startLogin()');
return this.startLogin... | javascript | function() {
var user = userStore.getUser();
if (user) {
$rootScope.user = user;
authLogger.log('AuthService.withUser()', user);
return $q.when(user);
} else {
authLogger.log('AuthService.withUser(), calling startLogin()');
return this.startLogin... | [
"function",
"(",
")",
"{",
"var",
"user",
"=",
"userStore",
".",
"getUser",
"(",
")",
";",
"if",
"(",
"user",
")",
"{",
"$rootScope",
".",
"user",
"=",
"user",
";",
"authLogger",
".",
"log",
"(",
"'AuthService.withUser()'",
",",
"user",
")",
";",
"re... | Returns a promise of a user, which is resolved with a logged in user. Triggers a login if needed. | [
"Returns",
"a",
"promise",
"of",
"a",
"user",
"which",
"is",
"resolved",
"with",
"a",
"logged",
"in",
"user",
".",
"Triggers",
"a",
"login",
"if",
"needed",
"."
] | a56152ba5a42b95bd91c0e65531f6104b9a4dc8f | https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L1188-L1198 | train | |
openshift/origin-web-common | dist/origin-web-common-services.js | function(config) {
// Requests that don't require auth can continue
if (!AuthService.requestRequiresAuth(config)) {
// console.log("No auth required", config.url);
return config;
}
// If we could add auth info, we can continue
if (AuthService.addAuthToRequest(config)) {
... | javascript | function(config) {
// Requests that don't require auth can continue
if (!AuthService.requestRequiresAuth(config)) {
// console.log("No auth required", config.url);
return config;
}
// If we could add auth info, we can continue
if (AuthService.addAuthToRequest(config)) {
... | [
"function",
"(",
"config",
")",
"{",
"// Requests that don't require auth can continue",
"if",
"(",
"!",
"AuthService",
".",
"requestRequiresAuth",
"(",
"config",
")",
")",
"{",
"// console.log(\"No auth required\", config.url);",
"return",
"config",
";",
"}",
"// If we c... | If auth is not needed, or is already present, returns a config If auth is needed and not present, starts a login flow and returns a promise of a config | [
"If",
"auth",
"is",
"not",
"needed",
"or",
"is",
"already",
"present",
"returns",
"a",
"config",
"If",
"auth",
"is",
"needed",
"and",
"not",
"present",
"starts",
"a",
"login",
"flow",
"and",
"returns",
"a",
"promise",
"of",
"a",
"config"
] | a56152ba5a42b95bd91c0e65531f6104b9a4dc8f | https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L1330-L1357 | train | |
openshift/origin-web-common | dist/origin-web-common-services.js | function(projectName, forceRefresh) {
var deferred = $q.defer();
currentProject = projectName;
var projectRules = cachedRulesByProject.get(projectName);
var rulesResource = "selfsubjectrulesreviews";
if (!projectRules || projectRules.forceRefresh || forceRefresh) {
// Check if APIs... | javascript | function(projectName, forceRefresh) {
var deferred = $q.defer();
currentProject = projectName;
var projectRules = cachedRulesByProject.get(projectName);
var rulesResource = "selfsubjectrulesreviews";
if (!projectRules || projectRules.forceRefresh || forceRefresh) {
// Check if APIs... | [
"function",
"(",
"projectName",
",",
"forceRefresh",
")",
"{",
"var",
"deferred",
"=",
"$q",
".",
"defer",
"(",
")",
";",
"currentProject",
"=",
"projectName",
";",
"var",
"projectRules",
"=",
"cachedRulesByProject",
".",
"get",
"(",
"projectName",
")",
";",... | forceRefresh is a boolean to bust the cache & request new perms | [
"forceRefresh",
"is",
"a",
"boolean",
"to",
"bust",
"the",
"cache",
"&",
"request",
"new",
"perms"
] | a56152ba5a42b95bd91c0e65531f6104b9a4dc8f | https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L1461-L1510 | train | |
openshift/origin-web-common | dist/origin-web-common-services.js | function(serviceInstance, application, serviceClass, parameters) {
var parametersSecretName;
if (!_.isEmpty(parameters)) {
parametersSecretName = generateSecretName(serviceInstance.metadata.name + '-bind-parameters-');
}
var newBinding = makeBinding(serviceInstance, applicatio... | javascript | function(serviceInstance, application, serviceClass, parameters) {
var parametersSecretName;
if (!_.isEmpty(parameters)) {
parametersSecretName = generateSecretName(serviceInstance.metadata.name + '-bind-parameters-');
}
var newBinding = makeBinding(serviceInstance, applicatio... | [
"function",
"(",
"serviceInstance",
",",
"application",
",",
"serviceClass",
",",
"parameters",
")",
"{",
"var",
"parametersSecretName",
";",
"if",
"(",
"!",
"_",
".",
"isEmpty",
"(",
"parameters",
")",
")",
"{",
"parametersSecretName",
"=",
"generateSecretName"... | Create a binding for `serviceInstance`. If an `application` API object is specified, also create a pod preset for that application using its `spec.selector`. `serviceClass` is required to determine if any parameters need to be set when creating the binding. | [
"Create",
"a",
"binding",
"for",
"serviceInstance",
".",
"If",
"an",
"application",
"API",
"object",
"is",
"specified",
"also",
"create",
"a",
"pod",
"preset",
"for",
"that",
"application",
"using",
"its",
"spec",
".",
"selector",
".",
"serviceClass",
"is",
... | a56152ba5a42b95bd91c0e65531f6104b9a4dc8f | https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L1796-L1819 | train | |
openshift/origin-web-common | dist/origin-web-common-services.js | function(id) {
if (openQueue[id]) { delete openQueue[id]; }
if (messageQueue[id]) { delete messageQueue[id]; }
if (closeQueue[id]) { delete closeQueue[id]; }
if (errorQueue[id]) { delete errorQueue[id]; }
} | javascript | function(id) {
if (openQueue[id]) { delete openQueue[id]; }
if (messageQueue[id]) { delete messageQueue[id]; }
if (closeQueue[id]) { delete closeQueue[id]; }
if (errorQueue[id]) { delete errorQueue[id]; }
} | [
"function",
"(",
"id",
")",
"{",
"if",
"(",
"openQueue",
"[",
"id",
"]",
")",
"{",
"delete",
"openQueue",
"[",
"id",
"]",
";",
"}",
"if",
"(",
"messageQueue",
"[",
"id",
"]",
")",
"{",
"delete",
"messageQueue",
"[",
"id",
"]",
";",
"}",
"if",
"... | can remove any callback from open, message, close or error | [
"can",
"remove",
"any",
"callback",
"from",
"open",
"message",
"close",
"or",
"error"
] | a56152ba5a42b95bd91c0e65531f6104b9a4dc8f | https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L2451-L2456 | train | |
openshift/origin-web-common | dist/origin-web-common-services.js | function(params) {
var keys = _.keysIn(
_.pick(
params,
['fieldSelector', 'labelSelector'])
).sort();
return _.reduce(
keys,
function(result, key, i) {
return result + key + '=' + encodeURIComponent(p... | javascript | function(params) {
var keys = _.keysIn(
_.pick(
params,
['fieldSelector', 'labelSelector'])
).sort();
return _.reduce(
keys,
function(result, key, i) {
return result + key + '=' + encodeURIComponent(p... | [
"function",
"(",
"params",
")",
"{",
"var",
"keys",
"=",
"_",
".",
"keysIn",
"(",
"_",
".",
"pick",
"(",
"params",
",",
"[",
"'fieldSelector'",
",",
"'labelSelector'",
"]",
")",
")",
".",
"sort",
"(",
")",
";",
"return",
"_",
".",
"reduce",
"(",
... | will take an object, filter & sort it for consistent unique key generation uses encodeURIComponent internally because keys can have special characters, such as '=' | [
"will",
"take",
"an",
"object",
"filter",
"&",
"sort",
"it",
"for",
"consistent",
"unique",
"key",
"generation",
"uses",
"encodeURIComponent",
"internally",
"because",
"keys",
"can",
"have",
"special",
"characters",
"such",
"as",
"="
] | a56152ba5a42b95bd91c0e65531f6104b9a4dc8f | https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L2819-L2832 | train | |
openshift/origin-web-common | dist/origin-web-common-services.js | function(objects, filterFields, keywords) {
if (_.isEmpty(keywords)) {
return [];
}
var results = [];
_.each(objects, function(object) {
// Keep a score for matches, weighted by field.
var score = 0;
_.each(keywords, function(regex) {
var matchesKeyword... | javascript | function(objects, filterFields, keywords) {
if (_.isEmpty(keywords)) {
return [];
}
var results = [];
_.each(objects, function(object) {
// Keep a score for matches, weighted by field.
var score = 0;
_.each(keywords, function(regex) {
var matchesKeyword... | [
"function",
"(",
"objects",
",",
"filterFields",
",",
"keywords",
")",
"{",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"keywords",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"var",
"results",
"=",
"[",
"]",
";",
"_",
".",
"each",
"(",
"objects",
",",... | Perform a simple weighted search. weightedSearch is like filterForKeywords, except each field has a weight and the result is a sorted array of matches. filterFields is an array of objects with keys `path` and `weight`. | [
"Perform",
"a",
"simple",
"weighted",
"search",
".",
"weightedSearch",
"is",
"like",
"filterForKeywords",
"except",
"each",
"field",
"has",
"a",
"weight",
"and",
"the",
"result",
"is",
"a",
"sorted",
"array",
"of",
"matches",
".",
"filterFields",
"is",
"an",
... | a56152ba5a42b95bd91c0e65531f6104b9a4dc8f | https://github.com/openshift/origin-web-common/blob/a56152ba5a42b95bd91c0e65531f6104b9a4dc8f/dist/origin-web-common-services.js#L3418-L3460 | train |
Subsets and Splits
SQL Console for semeru/code-text-javascript
Retrieves 20,000 non-null code samples labeled as JavaScript, providing a basic overview of the dataset.