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 |
---|---|---|---|---|---|---|---|---|---|---|---|
armed/gulp-flatten
|
lib/flatten-path.js
|
flattenPath
|
function flattenPath(file, opts) {
var fileName = path.basename(file.path);
var dirs;
if (!opts.includeParents && !opts.subPath) {
return fileName;
}
dirs = path.dirname(file.relative).split(path.sep);
if (opts.includeParents) {
dirs = includeParents(dirs, opts.includeParents);
}
if (opts.subPath) {
dirs = subPath(dirs, opts.subPath);
}
dirs.push(fileName);
return path.join.apply(path, dirs);
}
|
javascript
|
function flattenPath(file, opts) {
var fileName = path.basename(file.path);
var dirs;
if (!opts.includeParents && !opts.subPath) {
return fileName;
}
dirs = path.dirname(file.relative).split(path.sep);
if (opts.includeParents) {
dirs = includeParents(dirs, opts.includeParents);
}
if (opts.subPath) {
dirs = subPath(dirs, opts.subPath);
}
dirs.push(fileName);
return path.join.apply(path, dirs);
}
|
[
"function",
"flattenPath",
"(",
"file",
",",
"opts",
")",
"{",
"var",
"fileName",
"=",
"path",
".",
"basename",
"(",
"file",
".",
"path",
")",
";",
"var",
"dirs",
";",
"if",
"(",
"!",
"opts",
".",
"includeParents",
"&&",
"!",
"opts",
".",
"subPath",
")",
"{",
"return",
"fileName",
";",
"}",
"dirs",
"=",
"path",
".",
"dirname",
"(",
"file",
".",
"relative",
")",
".",
"split",
"(",
"path",
".",
"sep",
")",
";",
"if",
"(",
"opts",
".",
"includeParents",
")",
"{",
"dirs",
"=",
"includeParents",
"(",
"dirs",
",",
"opts",
".",
"includeParents",
")",
";",
"}",
"if",
"(",
"opts",
".",
"subPath",
")",
"{",
"dirs",
"=",
"subPath",
"(",
"dirs",
",",
"opts",
".",
"subPath",
")",
";",
"}",
"dirs",
".",
"push",
"(",
"fileName",
")",
";",
"return",
"path",
".",
"join",
".",
"apply",
"(",
"path",
",",
"dirs",
")",
";",
"}"
] |
Flatten the path to the desired depth
@param {File} file - vinyl file
@param {Object} options
@return {String}
|
[
"Flatten",
"the",
"path",
"to",
"the",
"desired",
"depth"
] |
aa164976236a44a7f7f31de58d57c71384ae2c26
|
https://github.com/armed/gulp-flatten/blob/aa164976236a44a7f7f31de58d57c71384ae2c26/lib/flatten-path.js#L49-L67
|
train
|
giseburt/TinyG-node
|
tinyg.js
|
function(r) {
if (!seenConnectionBanner) {
self.emit('connected', r);
seenConnectionBanner = true;
deferredSetup.resolve(r);
return;
}
if (r.hasOwnProperty("rx") && self.serialPortData === null) {
self.ignoredResponses--;
if (!self.timedSendsOnly) {
self.linesRequested = r.rx - 1;
}
// -1 is okay, that just means wait until we've sent two lines to send again
} else if (self.ignoredResponses > 0) {
self.ignoredResponses--;
return;
} else {
if (!self.timedSendsOnly) {
self.linesRequested++;
}
}
self._sendLines();
}
|
javascript
|
function(r) {
if (!seenConnectionBanner) {
self.emit('connected', r);
seenConnectionBanner = true;
deferredSetup.resolve(r);
return;
}
if (r.hasOwnProperty("rx") && self.serialPortData === null) {
self.ignoredResponses--;
if (!self.timedSendsOnly) {
self.linesRequested = r.rx - 1;
}
// -1 is okay, that just means wait until we've sent two lines to send again
} else if (self.ignoredResponses > 0) {
self.ignoredResponses--;
return;
} else {
if (!self.timedSendsOnly) {
self.linesRequested++;
}
}
self._sendLines();
}
|
[
"function",
"(",
"r",
")",
"{",
"if",
"(",
"!",
"seenConnectionBanner",
")",
"{",
"self",
".",
"emit",
"(",
"'connected'",
",",
"r",
")",
";",
"seenConnectionBanner",
"=",
"true",
";",
"deferredSetup",
".",
"resolve",
"(",
"r",
")",
";",
"return",
";",
"}",
"if",
"(",
"r",
".",
"hasOwnProperty",
"(",
"\"rx\"",
")",
"&&",
"self",
".",
"serialPortData",
"===",
"null",
")",
"{",
"self",
".",
"ignoredResponses",
"--",
";",
"if",
"(",
"!",
"self",
".",
"timedSendsOnly",
")",
"{",
"self",
".",
"linesRequested",
"=",
"r",
".",
"rx",
"-",
"1",
";",
"}",
"}",
"else",
"if",
"(",
"self",
".",
"ignoredResponses",
">",
"0",
")",
"{",
"self",
".",
"ignoredResponses",
"--",
";",
"return",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"self",
".",
"timedSendsOnly",
")",
"{",
"self",
".",
"linesRequested",
"++",
";",
"}",
"}",
"self",
".",
"_sendLines",
"(",
")",
";",
"}"
] |
Prepare the event listeners
|
[
"Prepare",
"the",
"event",
"listeners"
] |
1bf51558e4e6b8165fdc7ed09f80782ab81834f1
|
https://github.com/giseburt/TinyG-node/blob/1bf51558e4e6b8165fdc7ed09f80782ab81834f1/tinyg.js#L252-L276
|
train
|
|
giseburt/TinyG-node
|
tinyg.js
|
function (k, v) {
promiseChain = promiseChain.then(function() {
return self.set(k, v);
}).catch(function (e) {
// console.log("Caught error setting {", k, ":", v, "}: ", e);
self.emit('error', e);
return Q.fcall(function () {});
});
}
|
javascript
|
function (k, v) {
promiseChain = promiseChain.then(function() {
return self.set(k, v);
}).catch(function (e) {
// console.log("Caught error setting {", k, ":", v, "}: ", e);
self.emit('error', e);
return Q.fcall(function () {});
});
}
|
[
"function",
"(",
"k",
",",
"v",
")",
"{",
"promiseChain",
"=",
"promiseChain",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"self",
".",
"set",
"(",
"k",
",",
"v",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"e",
")",
"{",
"self",
".",
"emit",
"(",
"'error'",
",",
"e",
")",
";",
"return",
"Q",
".",
"fcall",
"(",
"function",
"(",
")",
"{",
"}",
")",
";",
"}",
")",
";",
"}"
] |
We have to artificially create a function context to hold the values so we make a closure function, assign the variables, and immediately call it.
|
[
"We",
"have",
"to",
"artificially",
"create",
"a",
"function",
"context",
"to",
"hold",
"the",
"values",
"so",
"we",
"make",
"a",
"closure",
"function",
"assign",
"the",
"variables",
"and",
"immediately",
"call",
"it",
"."
] |
1bf51558e4e6b8165fdc7ed09f80782ab81834f1
|
https://github.com/giseburt/TinyG-node/blob/1bf51558e4e6b8165fdc7ed09f80782ab81834f1/tinyg.js#L866-L874
|
train
|
|
audiojs/pcm-util
|
index.js
|
getFormat
|
function getFormat (obj) {
//undefined format - no format-related props, for sure
if (!obj) return {}
//if is string - parse format
if (typeof obj === 'string' || obj.id) {
return parse(obj.id || obj)
}
//if audio buffer - we know it’s format
else if (isAudioBuffer(obj)) {
var arrayFormat = fromTypedArray(obj.getChannelData(0))
return {
sampleRate: obj.sampleRate,
channels: obj.numberOfChannels,
samplesPerFrame: obj.length,
float: true,
signed: true,
bitDepth: arrayFormat.bitDepth
}
}
//if is array - detect format
else if (ArrayBuffer.isView(obj)) {
return fromTypedArray(obj)
}
//FIXME: add AudioNode, stream detection
//else detect from obhect
return fromObject(obj)
}
|
javascript
|
function getFormat (obj) {
//undefined format - no format-related props, for sure
if (!obj) return {}
//if is string - parse format
if (typeof obj === 'string' || obj.id) {
return parse(obj.id || obj)
}
//if audio buffer - we know it’s format
else if (isAudioBuffer(obj)) {
var arrayFormat = fromTypedArray(obj.getChannelData(0))
return {
sampleRate: obj.sampleRate,
channels: obj.numberOfChannels,
samplesPerFrame: obj.length,
float: true,
signed: true,
bitDepth: arrayFormat.bitDepth
}
}
//if is array - detect format
else if (ArrayBuffer.isView(obj)) {
return fromTypedArray(obj)
}
//FIXME: add AudioNode, stream detection
//else detect from obhect
return fromObject(obj)
}
|
[
"function",
"getFormat",
"(",
"obj",
")",
"{",
"if",
"(",
"!",
"obj",
")",
"return",
"{",
"}",
"if",
"(",
"typeof",
"obj",
"===",
"'string'",
"||",
"obj",
".",
"id",
")",
"{",
"return",
"parse",
"(",
"obj",
".",
"id",
"||",
"obj",
")",
"}",
"else",
"if",
"(",
"isAudioBuffer",
"(",
"obj",
")",
")",
"{",
"var",
"arrayFormat",
"=",
"fromTypedArray",
"(",
"obj",
".",
"getChannelData",
"(",
"0",
")",
")",
"return",
"{",
"sampleRate",
":",
"obj",
".",
"sampleRate",
",",
"channels",
":",
"obj",
".",
"numberOfChannels",
",",
"samplesPerFrame",
":",
"obj",
".",
"length",
",",
"float",
":",
"true",
",",
"signed",
":",
"true",
",",
"bitDepth",
":",
"arrayFormat",
".",
"bitDepth",
"}",
"}",
"else",
"if",
"(",
"ArrayBuffer",
".",
"isView",
"(",
"obj",
")",
")",
"{",
"return",
"fromTypedArray",
"(",
"obj",
")",
"}",
"return",
"fromObject",
"(",
"obj",
")",
"}"
] |
Get format info from any object, unnormalized.
|
[
"Get",
"format",
"info",
"from",
"any",
"object",
"unnormalized",
"."
] |
d4e949178e61a2c297d7d38df6da0ee325524e2f
|
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L43-L74
|
train
|
audiojs/pcm-util
|
index.js
|
equal
|
function equal (a, b) {
return (a.id || stringify(a)) === (b.id || stringify(b))
}
|
javascript
|
function equal (a, b) {
return (a.id || stringify(a)) === (b.id || stringify(b))
}
|
[
"function",
"equal",
"(",
"a",
",",
"b",
")",
"{",
"return",
"(",
"a",
".",
"id",
"||",
"stringify",
"(",
"a",
")",
")",
"===",
"(",
"b",
".",
"id",
"||",
"stringify",
"(",
"b",
")",
")",
"}"
] |
Whether one format is equal to another
|
[
"Whether",
"one",
"format",
"is",
"equal",
"to",
"another"
] |
d4e949178e61a2c297d7d38df6da0ee325524e2f
|
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L119-L121
|
train
|
audiojs/pcm-util
|
index.js
|
toArrayBuffer
|
function toArrayBuffer (audioBuffer, format) {
if (!isNormalized(format)) format = normalize(format)
var data
//convert to arraybuffer
if (audioBuffer._data) data = audioBuffer._data.buffer;
else {
var floatArray = audioBuffer.getChannelData(0).constructor;
data = new floatArray(audioBuffer.length * audioBuffer.numberOfChannels);
for (var channel = 0; channel < audioBuffer.numberOfChannels; channel++) {
data.set(audioBuffer.getChannelData(channel), channel * audioBuffer.length);
}
}
var arrayFormat = fromTypedArray(audioBuffer.getChannelData(0))
var buffer = convert(data, {
float: true,
channels: audioBuffer.numberOfChannels,
sampleRate: audioBuffer.sampleRate,
interleaved: false,
bitDepth: arrayFormat.bitDepth
}, format)
return buffer
}
|
javascript
|
function toArrayBuffer (audioBuffer, format) {
if (!isNormalized(format)) format = normalize(format)
var data
//convert to arraybuffer
if (audioBuffer._data) data = audioBuffer._data.buffer;
else {
var floatArray = audioBuffer.getChannelData(0).constructor;
data = new floatArray(audioBuffer.length * audioBuffer.numberOfChannels);
for (var channel = 0; channel < audioBuffer.numberOfChannels; channel++) {
data.set(audioBuffer.getChannelData(channel), channel * audioBuffer.length);
}
}
var arrayFormat = fromTypedArray(audioBuffer.getChannelData(0))
var buffer = convert(data, {
float: true,
channels: audioBuffer.numberOfChannels,
sampleRate: audioBuffer.sampleRate,
interleaved: false,
bitDepth: arrayFormat.bitDepth
}, format)
return buffer
}
|
[
"function",
"toArrayBuffer",
"(",
"audioBuffer",
",",
"format",
")",
"{",
"if",
"(",
"!",
"isNormalized",
"(",
"format",
")",
")",
"format",
"=",
"normalize",
"(",
"format",
")",
"var",
"data",
"if",
"(",
"audioBuffer",
".",
"_data",
")",
"data",
"=",
"audioBuffer",
".",
"_data",
".",
"buffer",
";",
"else",
"{",
"var",
"floatArray",
"=",
"audioBuffer",
".",
"getChannelData",
"(",
"0",
")",
".",
"constructor",
";",
"data",
"=",
"new",
"floatArray",
"(",
"audioBuffer",
".",
"length",
"*",
"audioBuffer",
".",
"numberOfChannels",
")",
";",
"for",
"(",
"var",
"channel",
"=",
"0",
";",
"channel",
"<",
"audioBuffer",
".",
"numberOfChannels",
";",
"channel",
"++",
")",
"{",
"data",
".",
"set",
"(",
"audioBuffer",
".",
"getChannelData",
"(",
"channel",
")",
",",
"channel",
"*",
"audioBuffer",
".",
"length",
")",
";",
"}",
"}",
"var",
"arrayFormat",
"=",
"fromTypedArray",
"(",
"audioBuffer",
".",
"getChannelData",
"(",
"0",
")",
")",
"var",
"buffer",
"=",
"convert",
"(",
"data",
",",
"{",
"float",
":",
"true",
",",
"channels",
":",
"audioBuffer",
".",
"numberOfChannels",
",",
"sampleRate",
":",
"audioBuffer",
".",
"sampleRate",
",",
"interleaved",
":",
"false",
",",
"bitDepth",
":",
"arrayFormat",
".",
"bitDepth",
"}",
",",
"format",
")",
"return",
"buffer",
"}"
] |
Convert AudioBuffer to Buffer with specified format
|
[
"Convert",
"AudioBuffer",
"to",
"Buffer",
"with",
"specified",
"format"
] |
d4e949178e61a2c297d7d38df6da0ee325524e2f
|
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L170-L198
|
train
|
audiojs/pcm-util
|
index.js
|
toAudioBuffer
|
function toAudioBuffer (buffer, format) {
if (!isNormalized(format)) format = normalize(format)
buffer = convert(buffer, format, {
channels: format.channels,
sampleRate: format.sampleRate,
interleaved: false,
float: true
})
var len = Math.floor(buffer.byteLength * .25 / format.channels)
var audioBuffer = new AudioBuffer(null, {
length: len,
numberOfChannels: format.channels,
sampleRate: format.sampleRate
})
var step = len * 4
for (var channel = 0; channel < format.channels; channel++) {
var offset = channel * step
var data = new Float32Array(buffer.slice(offset, offset + step))
audioBuffer.getChannelData(channel).set(data)
}
return audioBuffer
}
|
javascript
|
function toAudioBuffer (buffer, format) {
if (!isNormalized(format)) format = normalize(format)
buffer = convert(buffer, format, {
channels: format.channels,
sampleRate: format.sampleRate,
interleaved: false,
float: true
})
var len = Math.floor(buffer.byteLength * .25 / format.channels)
var audioBuffer = new AudioBuffer(null, {
length: len,
numberOfChannels: format.channels,
sampleRate: format.sampleRate
})
var step = len * 4
for (var channel = 0; channel < format.channels; channel++) {
var offset = channel * step
var data = new Float32Array(buffer.slice(offset, offset + step))
audioBuffer.getChannelData(channel).set(data)
}
return audioBuffer
}
|
[
"function",
"toAudioBuffer",
"(",
"buffer",
",",
"format",
")",
"{",
"if",
"(",
"!",
"isNormalized",
"(",
"format",
")",
")",
"format",
"=",
"normalize",
"(",
"format",
")",
"buffer",
"=",
"convert",
"(",
"buffer",
",",
"format",
",",
"{",
"channels",
":",
"format",
".",
"channels",
",",
"sampleRate",
":",
"format",
".",
"sampleRate",
",",
"interleaved",
":",
"false",
",",
"float",
":",
"true",
"}",
")",
"var",
"len",
"=",
"Math",
".",
"floor",
"(",
"buffer",
".",
"byteLength",
"*",
".25",
"/",
"format",
".",
"channels",
")",
"var",
"audioBuffer",
"=",
"new",
"AudioBuffer",
"(",
"null",
",",
"{",
"length",
":",
"len",
",",
"numberOfChannels",
":",
"format",
".",
"channels",
",",
"sampleRate",
":",
"format",
".",
"sampleRate",
"}",
")",
"var",
"step",
"=",
"len",
"*",
"4",
"for",
"(",
"var",
"channel",
"=",
"0",
";",
"channel",
"<",
"format",
".",
"channels",
";",
"channel",
"++",
")",
"{",
"var",
"offset",
"=",
"channel",
"*",
"step",
"var",
"data",
"=",
"new",
"Float32Array",
"(",
"buffer",
".",
"slice",
"(",
"offset",
",",
"offset",
"+",
"step",
")",
")",
"audioBuffer",
".",
"getChannelData",
"(",
"channel",
")",
".",
"set",
"(",
"data",
")",
"}",
"return",
"audioBuffer",
"}"
] |
Convert Buffer to AudioBuffer with specified format
|
[
"Convert",
"Buffer",
"to",
"AudioBuffer",
"with",
"specified",
"format"
] |
d4e949178e61a2c297d7d38df6da0ee325524e2f
|
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L202-L228
|
train
|
audiojs/pcm-util
|
index.js
|
convert
|
function convert (buffer, from, to) {
//ensure formats are full
if (!isNormalized(from)) from = normalize(from)
if (!isNormalized(to)) to = normalize(to)
//convert buffer/alike to arrayBuffer
var data
if (buffer instanceof ArrayBuffer) {
data = buffer
}
else if (ArrayBuffer.isView(buffer)) {
if (buffer.byteOffset != null) data = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
else data = buffer.buffer;
}
else {
data = (new Uint8Array(buffer.length != null ? buffer : [buffer])).buffer
}
//ignore needless conversion
if (equal(from ,to)) {
return data
}
//create containers for conversion
var fromArray = new (arrayClass(from))(data)
//toArray is automatically filled with mapped values
//but in some cases mapped badly, e. g. float → int(round + rotate)
var toArray = new (arrayClass(to))(fromArray)
//if range differ, we should apply more thoughtful mapping
if (from.max !== to.max) {
fromArray.forEach(function (value, idx) {
//ignore not changed range
//bring to 0..1
var normalValue = (value - from.min) / (from.max - from.min)
//bring to new format ranges
value = normalValue * (to.max - to.min) + to.min
//clamp (buffers does not like values outside of bounds)
toArray[idx] = Math.max(to.min, Math.min(to.max, value))
})
}
//reinterleave, if required
if (from.interleaved != to.interleaved) {
var channels = from.channels
var len = Math.floor(fromArray.length / channels)
//deinterleave
if (from.interleaved && !to.interleaved) {
toArray = toArray.map(function (value, idx, data) {
var targetOffset = idx % len
var targetChannel = ~~(idx / len)
return data[targetOffset * channels + targetChannel]
})
}
//interleave
else if (!from.interleaved && to.interleaved) {
toArray = toArray.map(function (value, idx, data) {
var targetOffset = ~~(idx / channels)
var targetChannel = idx % channels
return data[targetChannel * len + targetOffset]
})
}
}
//ensure endianness
if (!to.float && from.byteOrder !== to.byteOrder) {
var le = to.byteOrder === 'LE'
var view = new DataView(toArray.buffer)
var step = to.bitDepth / 8
var methodName = 'set' + getDataViewSuffix(to)
for (var i = 0, l = toArray.length; i < l; i++) {
view[methodName](i*step, toArray[i], le)
}
}
return toArray.buffer
}
|
javascript
|
function convert (buffer, from, to) {
//ensure formats are full
if (!isNormalized(from)) from = normalize(from)
if (!isNormalized(to)) to = normalize(to)
//convert buffer/alike to arrayBuffer
var data
if (buffer instanceof ArrayBuffer) {
data = buffer
}
else if (ArrayBuffer.isView(buffer)) {
if (buffer.byteOffset != null) data = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
else data = buffer.buffer;
}
else {
data = (new Uint8Array(buffer.length != null ? buffer : [buffer])).buffer
}
//ignore needless conversion
if (equal(from ,to)) {
return data
}
//create containers for conversion
var fromArray = new (arrayClass(from))(data)
//toArray is automatically filled with mapped values
//but in some cases mapped badly, e. g. float → int(round + rotate)
var toArray = new (arrayClass(to))(fromArray)
//if range differ, we should apply more thoughtful mapping
if (from.max !== to.max) {
fromArray.forEach(function (value, idx) {
//ignore not changed range
//bring to 0..1
var normalValue = (value - from.min) / (from.max - from.min)
//bring to new format ranges
value = normalValue * (to.max - to.min) + to.min
//clamp (buffers does not like values outside of bounds)
toArray[idx] = Math.max(to.min, Math.min(to.max, value))
})
}
//reinterleave, if required
if (from.interleaved != to.interleaved) {
var channels = from.channels
var len = Math.floor(fromArray.length / channels)
//deinterleave
if (from.interleaved && !to.interleaved) {
toArray = toArray.map(function (value, idx, data) {
var targetOffset = idx % len
var targetChannel = ~~(idx / len)
return data[targetOffset * channels + targetChannel]
})
}
//interleave
else if (!from.interleaved && to.interleaved) {
toArray = toArray.map(function (value, idx, data) {
var targetOffset = ~~(idx / channels)
var targetChannel = idx % channels
return data[targetChannel * len + targetOffset]
})
}
}
//ensure endianness
if (!to.float && from.byteOrder !== to.byteOrder) {
var le = to.byteOrder === 'LE'
var view = new DataView(toArray.buffer)
var step = to.bitDepth / 8
var methodName = 'set' + getDataViewSuffix(to)
for (var i = 0, l = toArray.length; i < l; i++) {
view[methodName](i*step, toArray[i], le)
}
}
return toArray.buffer
}
|
[
"function",
"convert",
"(",
"buffer",
",",
"from",
",",
"to",
")",
"{",
"if",
"(",
"!",
"isNormalized",
"(",
"from",
")",
")",
"from",
"=",
"normalize",
"(",
"from",
")",
"if",
"(",
"!",
"isNormalized",
"(",
"to",
")",
")",
"to",
"=",
"normalize",
"(",
"to",
")",
"var",
"data",
"if",
"(",
"buffer",
"instanceof",
"ArrayBuffer",
")",
"{",
"data",
"=",
"buffer",
"}",
"else",
"if",
"(",
"ArrayBuffer",
".",
"isView",
"(",
"buffer",
")",
")",
"{",
"if",
"(",
"buffer",
".",
"byteOffset",
"!=",
"null",
")",
"data",
"=",
"buffer",
".",
"buffer",
".",
"slice",
"(",
"buffer",
".",
"byteOffset",
",",
"buffer",
".",
"byteOffset",
"+",
"buffer",
".",
"byteLength",
")",
";",
"else",
"data",
"=",
"buffer",
".",
"buffer",
";",
"}",
"else",
"{",
"data",
"=",
"(",
"new",
"Uint8Array",
"(",
"buffer",
".",
"length",
"!=",
"null",
"?",
"buffer",
":",
"[",
"buffer",
"]",
")",
")",
".",
"buffer",
"}",
"if",
"(",
"equal",
"(",
"from",
",",
"to",
")",
")",
"{",
"return",
"data",
"}",
"var",
"fromArray",
"=",
"new",
"(",
"arrayClass",
"(",
"from",
")",
")",
"(",
"data",
")",
"var",
"toArray",
"=",
"new",
"(",
"arrayClass",
"(",
"to",
")",
")",
"(",
"fromArray",
")",
"if",
"(",
"from",
".",
"max",
"!==",
"to",
".",
"max",
")",
"{",
"fromArray",
".",
"forEach",
"(",
"function",
"(",
"value",
",",
"idx",
")",
"{",
"var",
"normalValue",
"=",
"(",
"value",
"-",
"from",
".",
"min",
")",
"/",
"(",
"from",
".",
"max",
"-",
"from",
".",
"min",
")",
"value",
"=",
"normalValue",
"*",
"(",
"to",
".",
"max",
"-",
"to",
".",
"min",
")",
"+",
"to",
".",
"min",
"toArray",
"[",
"idx",
"]",
"=",
"Math",
".",
"max",
"(",
"to",
".",
"min",
",",
"Math",
".",
"min",
"(",
"to",
".",
"max",
",",
"value",
")",
")",
"}",
")",
"}",
"if",
"(",
"from",
".",
"interleaved",
"!=",
"to",
".",
"interleaved",
")",
"{",
"var",
"channels",
"=",
"from",
".",
"channels",
"var",
"len",
"=",
"Math",
".",
"floor",
"(",
"fromArray",
".",
"length",
"/",
"channels",
")",
"if",
"(",
"from",
".",
"interleaved",
"&&",
"!",
"to",
".",
"interleaved",
")",
"{",
"toArray",
"=",
"toArray",
".",
"map",
"(",
"function",
"(",
"value",
",",
"idx",
",",
"data",
")",
"{",
"var",
"targetOffset",
"=",
"idx",
"%",
"len",
"var",
"targetChannel",
"=",
"~",
"~",
"(",
"idx",
"/",
"len",
")",
"return",
"data",
"[",
"targetOffset",
"*",
"channels",
"+",
"targetChannel",
"]",
"}",
")",
"}",
"else",
"if",
"(",
"!",
"from",
".",
"interleaved",
"&&",
"to",
".",
"interleaved",
")",
"{",
"toArray",
"=",
"toArray",
".",
"map",
"(",
"function",
"(",
"value",
",",
"idx",
",",
"data",
")",
"{",
"var",
"targetOffset",
"=",
"~",
"~",
"(",
"idx",
"/",
"channels",
")",
"var",
"targetChannel",
"=",
"idx",
"%",
"channels",
"return",
"data",
"[",
"targetChannel",
"*",
"len",
"+",
"targetOffset",
"]",
"}",
")",
"}",
"}",
"if",
"(",
"!",
"to",
".",
"float",
"&&",
"from",
".",
"byteOrder",
"!==",
"to",
".",
"byteOrder",
")",
"{",
"var",
"le",
"=",
"to",
".",
"byteOrder",
"===",
"'LE'",
"var",
"view",
"=",
"new",
"DataView",
"(",
"toArray",
".",
"buffer",
")",
"var",
"step",
"=",
"to",
".",
"bitDepth",
"/",
"8",
"var",
"methodName",
"=",
"'set'",
"+",
"getDataViewSuffix",
"(",
"to",
")",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"toArray",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"view",
"[",
"methodName",
"]",
"(",
"i",
"*",
"step",
",",
"toArray",
"[",
"i",
"]",
",",
"le",
")",
"}",
"}",
"return",
"toArray",
".",
"buffer",
"}"
] |
Convert buffer from format A to format B.
|
[
"Convert",
"buffer",
"from",
"format",
"A",
"to",
"format",
"B",
"."
] |
d4e949178e61a2c297d7d38df6da0ee325524e2f
|
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L234-L316
|
train
|
audiojs/pcm-util
|
index.js
|
fromTypedArray
|
function fromTypedArray (array) {
if (array instanceof Int8Array) {
return {
float: false,
signed: true,
bitDepth: 8
}
}
if ((array instanceof Uint8Array) || (array instanceof Uint8ClampedArray)) {
return {
float: false,
signed: false,
bitDepth: 8
}
}
if (array instanceof Int16Array) {
return {
float: false,
signed: true,
bitDepth: 16
}
}
if (array instanceof Uint16Array) {
return {
float: false,
signed: false,
bitDepth: 16
}
}
if (array instanceof Int32Array) {
return {
float: false,
signed: true,
bitDepth: 32
}
}
if (array instanceof Uint32Array) {
return {
float: false,
signed: false,
bitDepth: 32
}
}
if (array instanceof Float32Array) {
return {
float: true,
signed: false,
bitDepth: 32
}
}
if (array instanceof Float64Array) {
return {
float: true,
signed: false,
bitDepth: 64
}
}
//other dataview types are Uint8Arrays
return {
float: false,
signed: false,
bitDepth: 8
}
}
|
javascript
|
function fromTypedArray (array) {
if (array instanceof Int8Array) {
return {
float: false,
signed: true,
bitDepth: 8
}
}
if ((array instanceof Uint8Array) || (array instanceof Uint8ClampedArray)) {
return {
float: false,
signed: false,
bitDepth: 8
}
}
if (array instanceof Int16Array) {
return {
float: false,
signed: true,
bitDepth: 16
}
}
if (array instanceof Uint16Array) {
return {
float: false,
signed: false,
bitDepth: 16
}
}
if (array instanceof Int32Array) {
return {
float: false,
signed: true,
bitDepth: 32
}
}
if (array instanceof Uint32Array) {
return {
float: false,
signed: false,
bitDepth: 32
}
}
if (array instanceof Float32Array) {
return {
float: true,
signed: false,
bitDepth: 32
}
}
if (array instanceof Float64Array) {
return {
float: true,
signed: false,
bitDepth: 64
}
}
//other dataview types are Uint8Arrays
return {
float: false,
signed: false,
bitDepth: 8
}
}
|
[
"function",
"fromTypedArray",
"(",
"array",
")",
"{",
"if",
"(",
"array",
"instanceof",
"Int8Array",
")",
"{",
"return",
"{",
"float",
":",
"false",
",",
"signed",
":",
"true",
",",
"bitDepth",
":",
"8",
"}",
"}",
"if",
"(",
"(",
"array",
"instanceof",
"Uint8Array",
")",
"||",
"(",
"array",
"instanceof",
"Uint8ClampedArray",
")",
")",
"{",
"return",
"{",
"float",
":",
"false",
",",
"signed",
":",
"false",
",",
"bitDepth",
":",
"8",
"}",
"}",
"if",
"(",
"array",
"instanceof",
"Int16Array",
")",
"{",
"return",
"{",
"float",
":",
"false",
",",
"signed",
":",
"true",
",",
"bitDepth",
":",
"16",
"}",
"}",
"if",
"(",
"array",
"instanceof",
"Uint16Array",
")",
"{",
"return",
"{",
"float",
":",
"false",
",",
"signed",
":",
"false",
",",
"bitDepth",
":",
"16",
"}",
"}",
"if",
"(",
"array",
"instanceof",
"Int32Array",
")",
"{",
"return",
"{",
"float",
":",
"false",
",",
"signed",
":",
"true",
",",
"bitDepth",
":",
"32",
"}",
"}",
"if",
"(",
"array",
"instanceof",
"Uint32Array",
")",
"{",
"return",
"{",
"float",
":",
"false",
",",
"signed",
":",
"false",
",",
"bitDepth",
":",
"32",
"}",
"}",
"if",
"(",
"array",
"instanceof",
"Float32Array",
")",
"{",
"return",
"{",
"float",
":",
"true",
",",
"signed",
":",
"false",
",",
"bitDepth",
":",
"32",
"}",
"}",
"if",
"(",
"array",
"instanceof",
"Float64Array",
")",
"{",
"return",
"{",
"float",
":",
"true",
",",
"signed",
":",
"false",
",",
"bitDepth",
":",
"64",
"}",
"}",
"return",
"{",
"float",
":",
"false",
",",
"signed",
":",
"false",
",",
"bitDepth",
":",
"8",
"}",
"}"
] |
Get format info from the array type
|
[
"Get",
"format",
"info",
"from",
"the",
"array",
"type"
] |
d4e949178e61a2c297d7d38df6da0ee325524e2f
|
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L359-L423
|
train
|
audiojs/pcm-util
|
index.js
|
fromObject
|
function fromObject (obj) {
//else retrieve format properties from object
var format = {}
formatProperties.forEach(function (key) {
if (obj[key] != null) format[key] = obj[key]
})
//some AudioNode/etc-specific options
if (!format.channels && (obj.channelCount || obj.numberOfChannels)) {
format.channels = obj.channelCount || obj.numberOfChannels
}
if (!format.sampleRate && obj.rate) {
format.sampleRate = obj.rate
}
return format
}
|
javascript
|
function fromObject (obj) {
//else retrieve format properties from object
var format = {}
formatProperties.forEach(function (key) {
if (obj[key] != null) format[key] = obj[key]
})
//some AudioNode/etc-specific options
if (!format.channels && (obj.channelCount || obj.numberOfChannels)) {
format.channels = obj.channelCount || obj.numberOfChannels
}
if (!format.sampleRate && obj.rate) {
format.sampleRate = obj.rate
}
return format
}
|
[
"function",
"fromObject",
"(",
"obj",
")",
"{",
"var",
"format",
"=",
"{",
"}",
"formatProperties",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"obj",
"[",
"key",
"]",
"!=",
"null",
")",
"format",
"[",
"key",
"]",
"=",
"obj",
"[",
"key",
"]",
"}",
")",
"if",
"(",
"!",
"format",
".",
"channels",
"&&",
"(",
"obj",
".",
"channelCount",
"||",
"obj",
".",
"numberOfChannels",
")",
")",
"{",
"format",
".",
"channels",
"=",
"obj",
".",
"channelCount",
"||",
"obj",
".",
"numberOfChannels",
"}",
"if",
"(",
"!",
"format",
".",
"sampleRate",
"&&",
"obj",
".",
"rate",
")",
"{",
"format",
".",
"sampleRate",
"=",
"obj",
".",
"rate",
"}",
"return",
"format",
"}"
] |
Retrieve format info from object
|
[
"Retrieve",
"format",
"info",
"from",
"object"
] |
d4e949178e61a2c297d7d38df6da0ee325524e2f
|
https://github.com/audiojs/pcm-util/blob/d4e949178e61a2c297d7d38df6da0ee325524e2f/index.js#L429-L446
|
train
|
mesaugat/chai-exclude
|
chai-exclude.js
|
isObject
|
function isObject (arg) {
return arg === Object(arg) && Object.prototype.toString.call(arg) !== '[object Array]'
}
|
javascript
|
function isObject (arg) {
return arg === Object(arg) && Object.prototype.toString.call(arg) !== '[object Array]'
}
|
[
"function",
"isObject",
"(",
"arg",
")",
"{",
"return",
"arg",
"===",
"Object",
"(",
"arg",
")",
"&&",
"Object",
".",
"prototype",
".",
"toString",
".",
"call",
"(",
"arg",
")",
"!==",
"'[object Array]'",
"}"
] |
Check if the argument is an object.
@param {any} arg
@returns {Boolean}
|
[
"Check",
"if",
"the",
"argument",
"is",
"an",
"object",
"."
] |
ef4e8e6ec597a1308fa2bb89d97c59a31c8f1cae
|
https://github.com/mesaugat/chai-exclude/blob/ef4e8e6ec597a1308fa2bb89d97c59a31c8f1cae/chai-exclude.js#L23-L25
|
train
|
mesaugat/chai-exclude
|
chai-exclude.js
|
removeKeysFrom
|
function removeKeysFrom (val, props, recursive = false) {
// Replace circular values with '[Circular]'
const obj = fclone(val)
if (isObject(obj)) {
return removeKeysFromObject(obj, props, recursive)
}
return removeKeysFromArray(obj, props, recursive)
}
|
javascript
|
function removeKeysFrom (val, props, recursive = false) {
// Replace circular values with '[Circular]'
const obj = fclone(val)
if (isObject(obj)) {
return removeKeysFromObject(obj, props, recursive)
}
return removeKeysFromArray(obj, props, recursive)
}
|
[
"function",
"removeKeysFrom",
"(",
"val",
",",
"props",
",",
"recursive",
"=",
"false",
")",
"{",
"const",
"obj",
"=",
"fclone",
"(",
"val",
")",
"if",
"(",
"isObject",
"(",
"obj",
")",
")",
"{",
"return",
"removeKeysFromObject",
"(",
"obj",
",",
"props",
",",
"recursive",
")",
"}",
"return",
"removeKeysFromArray",
"(",
"obj",
",",
"props",
",",
"recursive",
")",
"}"
] |
Remove keys from an object or an array.
@param {Object|Array} val object or array to remove keys
@param {Array} props array of keys to remove
@param {Boolean} recursive true if property needs to be removed recursively
@returns {Object}
|
[
"Remove",
"keys",
"from",
"an",
"object",
"or",
"an",
"array",
"."
] |
ef4e8e6ec597a1308fa2bb89d97c59a31c8f1cae
|
https://github.com/mesaugat/chai-exclude/blob/ef4e8e6ec597a1308fa2bb89d97c59a31c8f1cae/chai-exclude.js#L35-L44
|
train
|
mesaugat/chai-exclude
|
chai-exclude.js
|
removeKeysFromObject
|
function removeKeysFromObject (obj, props, recursive = false) {
const res = {}
const keys = Object.keys(obj)
const isRecursive = !!recursive
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const val = obj[key]
const hasKey = props.indexOf(key) === -1
if (isRecursive && hasKey && isObject(val)) {
res[key] = removeKeysFromObject(val, props, true)
} else if (isRecursive && hasKey && isArray(val)) {
res[key] = removeKeysFromArray(val, props, true)
} else if (hasKey) {
res[key] = val
}
}
return res
}
|
javascript
|
function removeKeysFromObject (obj, props, recursive = false) {
const res = {}
const keys = Object.keys(obj)
const isRecursive = !!recursive
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const val = obj[key]
const hasKey = props.indexOf(key) === -1
if (isRecursive && hasKey && isObject(val)) {
res[key] = removeKeysFromObject(val, props, true)
} else if (isRecursive && hasKey && isArray(val)) {
res[key] = removeKeysFromArray(val, props, true)
} else if (hasKey) {
res[key] = val
}
}
return res
}
|
[
"function",
"removeKeysFromObject",
"(",
"obj",
",",
"props",
",",
"recursive",
"=",
"false",
")",
"{",
"const",
"res",
"=",
"{",
"}",
"const",
"keys",
"=",
"Object",
".",
"keys",
"(",
"obj",
")",
"const",
"isRecursive",
"=",
"!",
"!",
"recursive",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"keys",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"key",
"=",
"keys",
"[",
"i",
"]",
"const",
"val",
"=",
"obj",
"[",
"key",
"]",
"const",
"hasKey",
"=",
"props",
".",
"indexOf",
"(",
"key",
")",
"===",
"-",
"1",
"if",
"(",
"isRecursive",
"&&",
"hasKey",
"&&",
"isObject",
"(",
"val",
")",
")",
"{",
"res",
"[",
"key",
"]",
"=",
"removeKeysFromObject",
"(",
"val",
",",
"props",
",",
"true",
")",
"}",
"else",
"if",
"(",
"isRecursive",
"&&",
"hasKey",
"&&",
"isArray",
"(",
"val",
")",
")",
"{",
"res",
"[",
"key",
"]",
"=",
"removeKeysFromArray",
"(",
"val",
",",
"props",
",",
"true",
")",
"}",
"else",
"if",
"(",
"hasKey",
")",
"{",
"res",
"[",
"key",
"]",
"=",
"val",
"}",
"}",
"return",
"res",
"}"
] |
Remove keys from an object and return a new object.
@param {Object} obj object to remove keys
@param {Array} props array of keys to remove
@param {Boolean} recursive true if property needs to be removed recursively
@returns {Object}
|
[
"Remove",
"keys",
"from",
"an",
"object",
"and",
"return",
"a",
"new",
"object",
"."
] |
ef4e8e6ec597a1308fa2bb89d97c59a31c8f1cae
|
https://github.com/mesaugat/chai-exclude/blob/ef4e8e6ec597a1308fa2bb89d97c59a31c8f1cae/chai-exclude.js#L54-L75
|
train
|
mesaugat/chai-exclude
|
chai-exclude.js
|
removeKeysFromArray
|
function removeKeysFromArray (array, props, recursive = false) {
const res = []
let val = {}
if (!array.length) {
return res
}
for (let i = 0; i < array.length; i++) {
if (isObject(array[i])) {
val = removeKeysFromObject(array[i], props, recursive)
} else if (isArray(array[i])) {
val = removeKeysFromArray(array[i], props, recursive)
} else {
val = array[i]
}
res.push(val)
}
return res
}
|
javascript
|
function removeKeysFromArray (array, props, recursive = false) {
const res = []
let val = {}
if (!array.length) {
return res
}
for (let i = 0; i < array.length; i++) {
if (isObject(array[i])) {
val = removeKeysFromObject(array[i], props, recursive)
} else if (isArray(array[i])) {
val = removeKeysFromArray(array[i], props, recursive)
} else {
val = array[i]
}
res.push(val)
}
return res
}
|
[
"function",
"removeKeysFromArray",
"(",
"array",
",",
"props",
",",
"recursive",
"=",
"false",
")",
"{",
"const",
"res",
"=",
"[",
"]",
"let",
"val",
"=",
"{",
"}",
"if",
"(",
"!",
"array",
".",
"length",
")",
"{",
"return",
"res",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"array",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"isObject",
"(",
"array",
"[",
"i",
"]",
")",
")",
"{",
"val",
"=",
"removeKeysFromObject",
"(",
"array",
"[",
"i",
"]",
",",
"props",
",",
"recursive",
")",
"}",
"else",
"if",
"(",
"isArray",
"(",
"array",
"[",
"i",
"]",
")",
")",
"{",
"val",
"=",
"removeKeysFromArray",
"(",
"array",
"[",
"i",
"]",
",",
"props",
",",
"recursive",
")",
"}",
"else",
"{",
"val",
"=",
"array",
"[",
"i",
"]",
"}",
"res",
".",
"push",
"(",
"val",
")",
"}",
"return",
"res",
"}"
] |
Remove keys from an object inside an array and return a new array.
@param {Array} array array with objects
@param {Array} props array of keys to remove
@param {Boolean} recursive true if property needs to be removed recursively
@returns {Array}
|
[
"Remove",
"keys",
"from",
"an",
"object",
"inside",
"an",
"array",
"and",
"return",
"a",
"new",
"array",
"."
] |
ef4e8e6ec597a1308fa2bb89d97c59a31c8f1cae
|
https://github.com/mesaugat/chai-exclude/blob/ef4e8e6ec597a1308fa2bb89d97c59a31c8f1cae/chai-exclude.js#L85-L106
|
train
|
mesaugat/chai-exclude
|
chai-exclude.js
|
assertEqual
|
function assertEqual (_super) {
return function (val) {
const props = utils.flag(this, 'excludingProps')
if (utils.flag(this, 'excluding')) {
val = removeKeysFrom(val, props)
} else if (utils.flag(this, 'excludingEvery')) {
val = removeKeysFrom(val, props, true)
}
// In case of 'use strict' and babelified code
arguments[0] = val
_super.apply(this, arguments)
}
}
|
javascript
|
function assertEqual (_super) {
return function (val) {
const props = utils.flag(this, 'excludingProps')
if (utils.flag(this, 'excluding')) {
val = removeKeysFrom(val, props)
} else if (utils.flag(this, 'excludingEvery')) {
val = removeKeysFrom(val, props, true)
}
// In case of 'use strict' and babelified code
arguments[0] = val
_super.apply(this, arguments)
}
}
|
[
"function",
"assertEqual",
"(",
"_super",
")",
"{",
"return",
"function",
"(",
"val",
")",
"{",
"const",
"props",
"=",
"utils",
".",
"flag",
"(",
"this",
",",
"'excludingProps'",
")",
"if",
"(",
"utils",
".",
"flag",
"(",
"this",
",",
"'excluding'",
")",
")",
"{",
"val",
"=",
"removeKeysFrom",
"(",
"val",
",",
"props",
")",
"}",
"else",
"if",
"(",
"utils",
".",
"flag",
"(",
"this",
",",
"'excludingEvery'",
")",
")",
"{",
"val",
"=",
"removeKeysFrom",
"(",
"val",
",",
"props",
",",
"true",
")",
"}",
"arguments",
"[",
"0",
"]",
"=",
"val",
"_super",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
"}",
"}"
] |
Override standard assertEqual method to remove the keys from other part of the equation.
@param {Object} _super
@returns {Function}
|
[
"Override",
"standard",
"assertEqual",
"method",
"to",
"remove",
"the",
"keys",
"from",
"other",
"part",
"of",
"the",
"equation",
"."
] |
ef4e8e6ec597a1308fa2bb89d97c59a31c8f1cae
|
https://github.com/mesaugat/chai-exclude/blob/ef4e8e6ec597a1308fa2bb89d97c59a31c8f1cae/chai-exclude.js#L114-L129
|
train
|
howdyai/botkit-storage-redis
|
src/index.js
|
getStorageObj
|
function getStorageObj(client, namespace) {
return {
get: function(id, cb) {
client.hget(namespace, id, function(err, res) {
cb(err, res ? JSON.parse(res) : null);
});
},
save: function(object, cb) {
if (!object.id) {
return cb(new Error('The given object must have an id property'), {});
}
client.hset(namespace, object.id, JSON.stringify(object), cb);
},
remove: function(id, cb) {
client.hdel(namespace, [id], cb);
},
all: function(cb, options) {
client.hgetall(namespace, function(err, res) {
if (err) {
return cb(err);
}
var parsed,
array = [];
for (var i in res) {
parsed = JSON.parse(res[i]);
res[i] = parsed;
array.push(parsed);
}
cb(null, options && options.type === 'object' ? res : array);
});
}
};
}
|
javascript
|
function getStorageObj(client, namespace) {
return {
get: function(id, cb) {
client.hget(namespace, id, function(err, res) {
cb(err, res ? JSON.parse(res) : null);
});
},
save: function(object, cb) {
if (!object.id) {
return cb(new Error('The given object must have an id property'), {});
}
client.hset(namespace, object.id, JSON.stringify(object), cb);
},
remove: function(id, cb) {
client.hdel(namespace, [id], cb);
},
all: function(cb, options) {
client.hgetall(namespace, function(err, res) {
if (err) {
return cb(err);
}
var parsed,
array = [];
for (var i in res) {
parsed = JSON.parse(res[i]);
res[i] = parsed;
array.push(parsed);
}
cb(null, options && options.type === 'object' ? res : array);
});
}
};
}
|
[
"function",
"getStorageObj",
"(",
"client",
",",
"namespace",
")",
"{",
"return",
"{",
"get",
":",
"function",
"(",
"id",
",",
"cb",
")",
"{",
"client",
".",
"hget",
"(",
"namespace",
",",
"id",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"cb",
"(",
"err",
",",
"res",
"?",
"JSON",
".",
"parse",
"(",
"res",
")",
":",
"null",
")",
";",
"}",
")",
";",
"}",
",",
"save",
":",
"function",
"(",
"object",
",",
"cb",
")",
"{",
"if",
"(",
"!",
"object",
".",
"id",
")",
"{",
"return",
"cb",
"(",
"new",
"Error",
"(",
"'The given object must have an id property'",
")",
",",
"{",
"}",
")",
";",
"}",
"client",
".",
"hset",
"(",
"namespace",
",",
"object",
".",
"id",
",",
"JSON",
".",
"stringify",
"(",
"object",
")",
",",
"cb",
")",
";",
"}",
",",
"remove",
":",
"function",
"(",
"id",
",",
"cb",
")",
"{",
"client",
".",
"hdel",
"(",
"namespace",
",",
"[",
"id",
"]",
",",
"cb",
")",
";",
"}",
",",
"all",
":",
"function",
"(",
"cb",
",",
"options",
")",
"{",
"client",
".",
"hgetall",
"(",
"namespace",
",",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
")",
";",
"}",
"var",
"parsed",
",",
"array",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"in",
"res",
")",
"{",
"parsed",
"=",
"JSON",
".",
"parse",
"(",
"res",
"[",
"i",
"]",
")",
";",
"res",
"[",
"i",
"]",
"=",
"parsed",
";",
"array",
".",
"push",
"(",
"parsed",
")",
";",
"}",
"cb",
"(",
"null",
",",
"options",
"&&",
"options",
".",
"type",
"===",
"'object'",
"?",
"res",
":",
"array",
")",
";",
"}",
")",
";",
"}",
"}",
";",
"}"
] |
Function to generate a storage object for a given namespace
@param {Object} client The redis client
@param {String} namespace The namespace to use for storing in Redis
@returns {{get: get, save: save, all: all, allById: allById}}
|
[
"Function",
"to",
"generate",
"a",
"storage",
"object",
"for",
"a",
"given",
"namespace"
] |
66d41fd796ae400195f3b491fa5743d36184164b
|
https://github.com/howdyai/botkit-storage-redis/blob/66d41fd796ae400195f3b491fa5743d36184164b/src/index.js#L37-L73
|
train
|
yyssc/ssc-grid
|
docs/assets/javascript.js
|
inTag
|
function inTag(stream, state) {
var ch = stream.next();
if (ch == ">" || (ch == "/" && stream.eat(">"))) {
state.jsxTag.depth -= 1;
state.tokenize = tokenBase;
return ret(ch == ">" ? "endTag" : "selfcloseTag", "tag bracket");
} else if (ch == "=") {
type = "equals";
return null;
} else if (ch == "<") {
state.tokenize = tokenBase;
var next = state.tokenize(stream, state);
return next ? next + " tag error" : "tag error";
} else if (ch == "{") {
state.jsxTag.brackets[state.jsxTag.depth] = 1; // counter for brackets
state.tokenize = tokenBase;
return null;
} else if (ch == "}") {
return null;
} else if (/[\'\"]/.test(ch)) {
state.tokenize = inAttribute(ch);
return state.tokenize(stream, state);
} else {
stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
return "word";
}
}
|
javascript
|
function inTag(stream, state) {
var ch = stream.next();
if (ch == ">" || (ch == "/" && stream.eat(">"))) {
state.jsxTag.depth -= 1;
state.tokenize = tokenBase;
return ret(ch == ">" ? "endTag" : "selfcloseTag", "tag bracket");
} else if (ch == "=") {
type = "equals";
return null;
} else if (ch == "<") {
state.tokenize = tokenBase;
var next = state.tokenize(stream, state);
return next ? next + " tag error" : "tag error";
} else if (ch == "{") {
state.jsxTag.brackets[state.jsxTag.depth] = 1; // counter for brackets
state.tokenize = tokenBase;
return null;
} else if (ch == "}") {
return null;
} else if (/[\'\"]/.test(ch)) {
state.tokenize = inAttribute(ch);
return state.tokenize(stream, state);
} else {
stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
return "word";
}
}
|
[
"function",
"inTag",
"(",
"stream",
",",
"state",
")",
"{",
"var",
"ch",
"=",
"stream",
".",
"next",
"(",
")",
";",
"if",
"(",
"ch",
"==",
"\">\"",
"||",
"(",
"ch",
"==",
"\"/\"",
"&&",
"stream",
".",
"eat",
"(",
"\">\"",
")",
")",
")",
"{",
"state",
".",
"jsxTag",
".",
"depth",
"-=",
"1",
";",
"state",
".",
"tokenize",
"=",
"tokenBase",
";",
"return",
"ret",
"(",
"ch",
"==",
"\">\"",
"?",
"\"endTag\"",
":",
"\"selfcloseTag\"",
",",
"\"tag bracket\"",
")",
";",
"}",
"else",
"if",
"(",
"ch",
"==",
"\"=\"",
")",
"{",
"type",
"=",
"\"equals\"",
";",
"return",
"null",
";",
"}",
"else",
"if",
"(",
"ch",
"==",
"\"<\"",
")",
"{",
"state",
".",
"tokenize",
"=",
"tokenBase",
";",
"var",
"next",
"=",
"state",
".",
"tokenize",
"(",
"stream",
",",
"state",
")",
";",
"return",
"next",
"?",
"next",
"+",
"\" tag error\"",
":",
"\"tag error\"",
";",
"}",
"else",
"if",
"(",
"ch",
"==",
"\"{\"",
")",
"{",
"state",
".",
"jsxTag",
".",
"brackets",
"[",
"state",
".",
"jsxTag",
".",
"depth",
"]",
"=",
"1",
";",
"state",
".",
"tokenize",
"=",
"tokenBase",
";",
"return",
"null",
";",
"}",
"else",
"if",
"(",
"ch",
"==",
"\"}\"",
")",
"{",
"return",
"null",
";",
"}",
"else",
"if",
"(",
"/",
"[\\'\\\"]",
"/",
".",
"test",
"(",
"ch",
")",
")",
"{",
"state",
".",
"tokenize",
"=",
"inAttribute",
"(",
"ch",
")",
";",
"return",
"state",
".",
"tokenize",
"(",
"stream",
",",
"state",
")",
";",
"}",
"else",
"{",
"stream",
".",
"match",
"(",
"/",
"^[^\\s\\u00a0=<>\\\"\\']*[^\\s\\u00a0=<>\\\"\\'\\/]",
"/",
")",
";",
"return",
"\"word\"",
";",
"}",
"}"
] |
for JSX mode
|
[
"for",
"JSX",
"mode"
] |
6687a483c83e02c97504ff1fba99a14dbe3e0390
|
https://github.com/yyssc/ssc-grid/blob/6687a483c83e02c97504ff1fba99a14dbe3e0390/docs/assets/javascript.js#L156-L182
|
train
|
yyssc/ssc-grid
|
docs/generate-metadata.js
|
applyPropDoclets
|
function applyPropDoclets(props, propName) {
let prop = props[propName];
let doclets = prop.doclets;
let value;
// the @type doclet to provide a prop type
// Also allows enums (oneOf) if string literals are provided
// ex: @type {("optionA"|"optionB")}
if (doclets.type) {
value = cleanDocletValue(doclets.type);
prop.type.name = value;
if (value[0] === '(') {
value = value.substring(1, value.length - 1).split('|');
prop.type.value = value;
prop.type.name = value.every(isLiteral) ? 'enum' : 'union';
}
}
// Use @required to mark a prop as required
// useful for custom propTypes where there isn't a `.isRequired` addon
if (doclets.required) {
prop.required = true;
}
// Use @defaultValue to provide a prop's default value
if (doclets.defaultValue) {
prop.defaultValue = cleanDocletValue(doclets.defaultValue);
}
}
|
javascript
|
function applyPropDoclets(props, propName) {
let prop = props[propName];
let doclets = prop.doclets;
let value;
// the @type doclet to provide a prop type
// Also allows enums (oneOf) if string literals are provided
// ex: @type {("optionA"|"optionB")}
if (doclets.type) {
value = cleanDocletValue(doclets.type);
prop.type.name = value;
if (value[0] === '(') {
value = value.substring(1, value.length - 1).split('|');
prop.type.value = value;
prop.type.name = value.every(isLiteral) ? 'enum' : 'union';
}
}
// Use @required to mark a prop as required
// useful for custom propTypes where there isn't a `.isRequired` addon
if (doclets.required) {
prop.required = true;
}
// Use @defaultValue to provide a prop's default value
if (doclets.defaultValue) {
prop.defaultValue = cleanDocletValue(doclets.defaultValue);
}
}
|
[
"function",
"applyPropDoclets",
"(",
"props",
",",
"propName",
")",
"{",
"let",
"prop",
"=",
"props",
"[",
"propName",
"]",
";",
"let",
"doclets",
"=",
"prop",
".",
"doclets",
";",
"let",
"value",
";",
"if",
"(",
"doclets",
".",
"type",
")",
"{",
"value",
"=",
"cleanDocletValue",
"(",
"doclets",
".",
"type",
")",
";",
"prop",
".",
"type",
".",
"name",
"=",
"value",
";",
"if",
"(",
"value",
"[",
"0",
"]",
"===",
"'('",
")",
"{",
"value",
"=",
"value",
".",
"substring",
"(",
"1",
",",
"value",
".",
"length",
"-",
"1",
")",
".",
"split",
"(",
"'|'",
")",
";",
"prop",
".",
"type",
".",
"value",
"=",
"value",
";",
"prop",
".",
"type",
".",
"name",
"=",
"value",
".",
"every",
"(",
"isLiteral",
")",
"?",
"'enum'",
":",
"'union'",
";",
"}",
"}",
"if",
"(",
"doclets",
".",
"required",
")",
"{",
"prop",
".",
"required",
"=",
"true",
";",
"}",
"if",
"(",
"doclets",
".",
"defaultValue",
")",
"{",
"prop",
".",
"defaultValue",
"=",
"cleanDocletValue",
"(",
"doclets",
".",
"defaultValue",
")",
";",
"}",
"}"
] |
Reads the JSDoc "doclets" and applies certain ones to the prop type data
This allows us to "fix" parsing errors, or unparsable data with JSDoc style comments
@param {Object} props Object Hash of the prop metadata
@param {String} propName
|
[
"Reads",
"the",
"JSDoc",
"doclets",
"and",
"applies",
"certain",
"ones",
"to",
"the",
"prop",
"type",
"data",
"This",
"allows",
"us",
"to",
"fix",
"parsing",
"errors",
"or",
"unparsable",
"data",
"with",
"JSDoc",
"style",
"comments"
] |
6687a483c83e02c97504ff1fba99a14dbe3e0390
|
https://github.com/yyssc/ssc-grid/blob/6687a483c83e02c97504ff1fba99a14dbe3e0390/docs/generate-metadata.js#L49-L79
|
train
|
yyssc/ssc-grid
|
docs/build.js
|
generateHTML
|
function generateHTML(fileName) {
return new Promise( resolve => {
const location = fileName === 'index.html' ? '/' : `/${fileName}`;
match({routes, location}, (error, redirectLocation, renderProps) => {
let html = ReactDOMServer.renderToString(
<RouterContext {...renderProps} />
);
html = '<!doctype html>' + html;
let write = fsp.writeFile(path.join(docsBuilt, fileName), html);
resolve(write);
});
});
}
|
javascript
|
function generateHTML(fileName) {
return new Promise( resolve => {
const location = fileName === 'index.html' ? '/' : `/${fileName}`;
match({routes, location}, (error, redirectLocation, renderProps) => {
let html = ReactDOMServer.renderToString(
<RouterContext {...renderProps} />
);
html = '<!doctype html>' + html;
let write = fsp.writeFile(path.join(docsBuilt, fileName), html);
resolve(write);
});
});
}
|
[
"function",
"generateHTML",
"(",
"fileName",
")",
"{",
"return",
"new",
"Promise",
"(",
"resolve",
"=>",
"{",
"const",
"location",
"=",
"fileName",
"===",
"'index.html'",
"?",
"'/'",
":",
"`",
"${",
"fileName",
"}",
"`",
";",
"match",
"(",
"{",
"routes",
",",
"location",
"}",
",",
"(",
"error",
",",
"redirectLocation",
",",
"renderProps",
")",
"=>",
"{",
"let",
"html",
"=",
"ReactDOMServer",
".",
"renderToString",
"(",
"<",
"RouterContext",
"{",
"...",
"renderProps",
"}",
"/",
">",
")",
";",
"html",
"=",
"'<!doctype html>'",
"+",
"html",
";",
"let",
"write",
"=",
"fsp",
".",
"writeFile",
"(",
"path",
".",
"join",
"(",
"docsBuilt",
",",
"fileName",
")",
",",
"html",
")",
";",
"resolve",
"(",
"write",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
] |
Generates HTML code for `fileName` page.
@param {string} fileName Path for Router.Route
@return {Promise} promise
@internal
|
[
"Generates",
"HTML",
"code",
"for",
"fileName",
"page",
"."
] |
6687a483c83e02c97504ff1fba99a14dbe3e0390
|
https://github.com/yyssc/ssc-grid/blob/6687a483c83e02c97504ff1fba99a14dbe3e0390/docs/build.js#L31-L43
|
train
|
Mozu/mozu-node-sdk
|
security/auth-ticket.js
|
AuthTicket
|
function AuthTicket(json) {
var self = this;
if (!(this instanceof AuthTicket)) return new AuthTicket(json);
for (var p in json) {
if (json.hasOwnProperty(p)) {
self[p] = p.indexOf('Expiration') !== -1 ? new Date(json[p]) : json[p]; // dateify the dates, this'll break if the prop name changes
}
}
}
|
javascript
|
function AuthTicket(json) {
var self = this;
if (!(this instanceof AuthTicket)) return new AuthTicket(json);
for (var p in json) {
if (json.hasOwnProperty(p)) {
self[p] = p.indexOf('Expiration') !== -1 ? new Date(json[p]) : json[p]; // dateify the dates, this'll break if the prop name changes
}
}
}
|
[
"function",
"AuthTicket",
"(",
"json",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"(",
"this",
"instanceof",
"AuthTicket",
")",
")",
"return",
"new",
"AuthTicket",
"(",
"json",
")",
";",
"for",
"(",
"var",
"p",
"in",
"json",
")",
"{",
"if",
"(",
"json",
".",
"hasOwnProperty",
"(",
"p",
")",
")",
"{",
"self",
"[",
"p",
"]",
"=",
"p",
".",
"indexOf",
"(",
"'Expiration'",
")",
"!==",
"-",
"1",
"?",
"new",
"Date",
"(",
"json",
"[",
"p",
"]",
")",
":",
"json",
"[",
"p",
"]",
";",
"}",
"}",
"}"
] |
The authentication ticket used to authenticate anything.
@class AuthTicket
@property {string} accessToken The token that stores an encrypted list of the application's configured behaviors and authenticates the application.
@property {Date} accessTokenExpiration Date and time the access token expires. After the access token expires, refresh the authentication ticket using the refresh token.
@property {string} refreshToken The token that refreshes the application's authentication ticket.
@property {Date} refreshTokenExpiration Date and time the refresh token expires. After the refresh token expires, generate a new authentication ticket.
|
[
"The",
"authentication",
"ticket",
"used",
"to",
"authenticate",
"anything",
"."
] |
ff976fa97c5b4cca5135e47d616ba1bae47d20ee
|
https://github.com/Mozu/mozu-node-sdk/blob/ff976fa97c5b4cca5135e47d616ba1bae47d20ee/security/auth-ticket.js#L12-L20
|
train
|
Financial-Times/ftdomdelegate
|
lib/delegate.js
|
Delegate
|
function Delegate(root) {
/**
* Maintain a map of listener
* lists, keyed by event name.
*
* @type Object
*/
this.listenerMap = [{}, {}];
if (root) {
this.root(root);
}
/** @type function() */
this.handle = Delegate.prototype.handle.bind(this);
}
|
javascript
|
function Delegate(root) {
/**
* Maintain a map of listener
* lists, keyed by event name.
*
* @type Object
*/
this.listenerMap = [{}, {}];
if (root) {
this.root(root);
}
/** @type function() */
this.handle = Delegate.prototype.handle.bind(this);
}
|
[
"function",
"Delegate",
"(",
"root",
")",
"{",
"this",
".",
"listenerMap",
"=",
"[",
"{",
"}",
",",
"{",
"}",
"]",
";",
"if",
"(",
"root",
")",
"{",
"this",
".",
"root",
"(",
"root",
")",
";",
"}",
"this",
".",
"handle",
"=",
"Delegate",
".",
"prototype",
".",
"handle",
".",
"bind",
"(",
"this",
")",
";",
"}"
] |
DOM event delegator
The delegator will listen
for events that bubble up
to the root node.
@constructor
@param {Node|string} [root] The root node or a selector string matching the root node
|
[
"DOM",
"event",
"delegator"
] |
d95d92da2da7d66ae9f7284339f0e953d15919ce
|
https://github.com/Financial-Times/ftdomdelegate/blob/d95d92da2da7d66ae9f7284339f0e953d15919ce/lib/delegate.js#L17-L32
|
train
|
rogeriopvl/gulp-mustache
|
index.js
|
loadPartials
|
function loadPartials(template, templatePath) {
var templateDir = path.dirname(templatePath)
var partialRegexp = new RegExp(
escapeRegex(mustache.tags[0]) +
'>\\s*(\\S+)\\s*' +
escapeRegex(mustache.tags[1]),
'g'
)
var partialMatch
while ((partialMatch = partialRegexp.exec(template))) {
var partialName = partialMatch[1]
if (!partials[partialName]) {
try {
var partialPath = null
var partial = null
// ignore `partial` with file extension.
// e.g.
// 1, `{{> ./path/to/partial.html }}`
// 2, `{{> ./path/to/partial. }}`
if (path.extname(partialName) !== '') {
partialPath = path.resolve(templateDir, partialName)
partial = fs.readFileSync(partialPath, 'utf8')
} else {
// ignore `partial` file is exists without file extension.
// e.g.
// 1, `{{> ./path/to/partial }}` is exists.
// 2, `{{> ./path/to/.partial }}` is exists.
partialPath = path.resolve(templateDir, partialName)
if (fs.existsSync(partialPath)) {
partial = fs.readFileSync(partialPath, 'utf8')
} else {
// or check if `partial + options.extension` is exists.
// e.g.
// if `options.extension` equals ".html":
// the `{{> ./path/to/partial }}` will load
// `./path/to/partial.html`.
if (typeof options.extension === 'string') {
partialPath = path.resolve(
templateDir,
partialName + options.extension
)
if (fs.existsSync(partialPath)) {
partial = fs.readFileSync(partialPath, 'utf8')
}
}
// when `options.extension` is not a string or
// `partialName + options.extension` does not exists.
// try use `.mustache` extension to load `partial` file.
if (partial === null) {
partialPath = path.resolve(
templateDir,
partialName + '.mustache'
)
partial = fs.readFileSync(partialPath, 'utf8')
}
}
}
partials[partialName] = partial
loadPartials.call(this, partial, partialPath)
} catch (ex) {
this.emit(
'error',
new PluginError(
'gulp-mustache',
// use `ex.message` property instead of `partialPath`,
// because `this.emit()` seems not a sync method.
// also the `ex.message` property provide more details
// about error information.
'Unable to load partial file: ' + ex.message
)
)
}
}
}
}
|
javascript
|
function loadPartials(template, templatePath) {
var templateDir = path.dirname(templatePath)
var partialRegexp = new RegExp(
escapeRegex(mustache.tags[0]) +
'>\\s*(\\S+)\\s*' +
escapeRegex(mustache.tags[1]),
'g'
)
var partialMatch
while ((partialMatch = partialRegexp.exec(template))) {
var partialName = partialMatch[1]
if (!partials[partialName]) {
try {
var partialPath = null
var partial = null
// ignore `partial` with file extension.
// e.g.
// 1, `{{> ./path/to/partial.html }}`
// 2, `{{> ./path/to/partial. }}`
if (path.extname(partialName) !== '') {
partialPath = path.resolve(templateDir, partialName)
partial = fs.readFileSync(partialPath, 'utf8')
} else {
// ignore `partial` file is exists without file extension.
// e.g.
// 1, `{{> ./path/to/partial }}` is exists.
// 2, `{{> ./path/to/.partial }}` is exists.
partialPath = path.resolve(templateDir, partialName)
if (fs.existsSync(partialPath)) {
partial = fs.readFileSync(partialPath, 'utf8')
} else {
// or check if `partial + options.extension` is exists.
// e.g.
// if `options.extension` equals ".html":
// the `{{> ./path/to/partial }}` will load
// `./path/to/partial.html`.
if (typeof options.extension === 'string') {
partialPath = path.resolve(
templateDir,
partialName + options.extension
)
if (fs.existsSync(partialPath)) {
partial = fs.readFileSync(partialPath, 'utf8')
}
}
// when `options.extension` is not a string or
// `partialName + options.extension` does not exists.
// try use `.mustache` extension to load `partial` file.
if (partial === null) {
partialPath = path.resolve(
templateDir,
partialName + '.mustache'
)
partial = fs.readFileSync(partialPath, 'utf8')
}
}
}
partials[partialName] = partial
loadPartials.call(this, partial, partialPath)
} catch (ex) {
this.emit(
'error',
new PluginError(
'gulp-mustache',
// use `ex.message` property instead of `partialPath`,
// because `this.emit()` seems not a sync method.
// also the `ex.message` property provide more details
// about error information.
'Unable to load partial file: ' + ex.message
)
)
}
}
}
}
|
[
"function",
"loadPartials",
"(",
"template",
",",
"templatePath",
")",
"{",
"var",
"templateDir",
"=",
"path",
".",
"dirname",
"(",
"templatePath",
")",
"var",
"partialRegexp",
"=",
"new",
"RegExp",
"(",
"escapeRegex",
"(",
"mustache",
".",
"tags",
"[",
"0",
"]",
")",
"+",
"'>\\\\s*(\\\\S+)\\\\s*'",
"+",
"\\\\",
",",
"\\\\",
")",
"\\\\",
"escapeRegex",
"(",
"mustache",
".",
"tags",
"[",
"1",
"]",
")",
"}"
] |
find and load partials not already in partials list from disk, recursively
|
[
"find",
"and",
"load",
"partials",
"not",
"already",
"in",
"partials",
"list",
"from",
"disk",
"recursively"
] |
c9c39e1a3e94a5a34181af44581c79a7673b5aea
|
https://github.com/rogeriopvl/gulp-mustache/blob/c9c39e1a3e94a5a34181af44581c79a7673b5aea/index.js#L70-L153
|
train
|
conveyal/mastarm
|
lib/logger.js
|
notifySlack
|
function notifySlack ({ channel, text, webhook }) {
return fetch(webhook, {
body: JSON.stringify({
channel,
text
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
})
.then(response => response.text())
.catch(err => {
logToErrorConsole('Error posting to Slack webhook')
logToErrorConsole(err)
return err
})
}
|
javascript
|
function notifySlack ({ channel, text, webhook }) {
return fetch(webhook, {
body: JSON.stringify({
channel,
text
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
})
.then(response => response.text())
.catch(err => {
logToErrorConsole('Error posting to Slack webhook')
logToErrorConsole(err)
return err
})
}
|
[
"function",
"notifySlack",
"(",
"{",
"channel",
",",
"text",
",",
"webhook",
"}",
")",
"{",
"return",
"fetch",
"(",
"webhook",
",",
"{",
"body",
":",
"JSON",
".",
"stringify",
"(",
"{",
"channel",
",",
"text",
"}",
")",
",",
"headers",
":",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
",",
"method",
":",
"'POST'",
"}",
")",
".",
"then",
"(",
"response",
"=>",
"response",
".",
"text",
"(",
")",
")",
".",
"catch",
"(",
"err",
"=>",
"{",
"logToErrorConsole",
"(",
"'Error posting to Slack webhook'",
")",
"logToErrorConsole",
"(",
"err",
")",
"return",
"err",
"}",
")",
"}"
] |
Send a message to slack by making a request to a webhook.
|
[
"Send",
"a",
"message",
"to",
"slack",
"by",
"making",
"a",
"request",
"to",
"a",
"webhook",
"."
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/logger.js#L33-L50
|
train
|
conveyal/mastarm
|
lib/load-config.js
|
findFile
|
function findFile (filename) {
const file = configDirectory + '/' + filename
if (fs.existsSync(file)) return file
const defaultFile = defaultDirectory + '/' + filename
if (fs.existsSync(defaultFile)) return defaultFile
return null
}
|
javascript
|
function findFile (filename) {
const file = configDirectory + '/' + filename
if (fs.existsSync(file)) return file
const defaultFile = defaultDirectory + '/' + filename
if (fs.existsSync(defaultFile)) return defaultFile
return null
}
|
[
"function",
"findFile",
"(",
"filename",
")",
"{",
"const",
"file",
"=",
"configDirectory",
"+",
"'/'",
"+",
"filename",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"file",
")",
")",
"return",
"file",
"const",
"defaultFile",
"=",
"defaultDirectory",
"+",
"'/'",
"+",
"filename",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"defaultFile",
")",
")",
"return",
"defaultFile",
"return",
"null",
"}"
] |
Try to find a config file.
Look first in the configDirectory and then fallback to the defaultDirectory.
If the file is still not found, return null.
|
[
"Try",
"to",
"find",
"a",
"config",
"file",
".",
"Look",
"first",
"in",
"the",
"configDirectory",
"and",
"then",
"fallback",
"to",
"the",
"defaultDirectory",
".",
"If",
"the",
"file",
"is",
"still",
"not",
"found",
"return",
"null",
"."
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/load-config.js#L31-L37
|
train
|
conveyal/mastarm
|
lib/load-config.js
|
loadYaml
|
function loadYaml (filename) {
const file = findFile(`${filename}.yml`)
return file ? YAML.parse(fs.readFileSync(file, 'utf8')) : {}
}
|
javascript
|
function loadYaml (filename) {
const file = findFile(`${filename}.yml`)
return file ? YAML.parse(fs.readFileSync(file, 'utf8')) : {}
}
|
[
"function",
"loadYaml",
"(",
"filename",
")",
"{",
"const",
"file",
"=",
"findFile",
"(",
"`",
"${",
"filename",
"}",
"`",
")",
"return",
"file",
"?",
"YAML",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"file",
",",
"'utf8'",
")",
")",
":",
"{",
"}",
"}"
] |
Return the JSON of a YAML file if it found, otherwise return an empty object.
|
[
"Return",
"the",
"JSON",
"of",
"a",
"YAML",
"file",
"if",
"it",
"found",
"otherwise",
"return",
"an",
"empty",
"object",
"."
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/load-config.js#L42-L45
|
train
|
conveyal/mastarm
|
lib/load-config.js
|
overrideWithEnvironment
|
function overrideWithEnvironment (object, environment) {
if (object.environments && object.environments[environment]) {
const newObject = Object.assign(
{},
object,
object.environments[environment]
)
delete newObject.environments
return newObject
}
return object
}
|
javascript
|
function overrideWithEnvironment (object, environment) {
if (object.environments && object.environments[environment]) {
const newObject = Object.assign(
{},
object,
object.environments[environment]
)
delete newObject.environments
return newObject
}
return object
}
|
[
"function",
"overrideWithEnvironment",
"(",
"object",
",",
"environment",
")",
"{",
"if",
"(",
"object",
".",
"environments",
"&&",
"object",
".",
"environments",
"[",
"environment",
"]",
")",
"{",
"const",
"newObject",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"object",
",",
"object",
".",
"environments",
"[",
"environment",
"]",
")",
"delete",
"newObject",
".",
"environments",
"return",
"newObject",
"}",
"return",
"object",
"}"
] |
If an environments key exists within a config object, use that data instead.
|
[
"If",
"an",
"environments",
"key",
"exists",
"within",
"a",
"config",
"object",
"use",
"that",
"data",
"instead",
"."
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/load-config.js#L51-L63
|
train
|
conveyal/mastarm
|
lib/lint-messages.js
|
parseImportLine
|
function parseImportLine (line) {
if (IS_IMPORT.test(line)) {
// could be either depending on whether default import was before or after named imports
const [, default0, named, default1] = IMPORT.exec(line)
const defaultImport = default0 || default1
const namedImports = []
if (named) {
let next
while ((next = NAMED_IMPORTS.exec(named)) != null) {
const [, src, importedAs] = next
namedImports.push([src, importedAs || src]) // if no alternate name, use default name
}
}
return [defaultImport, namedImports]
} else {
return null
}
}
|
javascript
|
function parseImportLine (line) {
if (IS_IMPORT.test(line)) {
// could be either depending on whether default import was before or after named imports
const [, default0, named, default1] = IMPORT.exec(line)
const defaultImport = default0 || default1
const namedImports = []
if (named) {
let next
while ((next = NAMED_IMPORTS.exec(named)) != null) {
const [, src, importedAs] = next
namedImports.push([src, importedAs || src]) // if no alternate name, use default name
}
}
return [defaultImport, namedImports]
} else {
return null
}
}
|
[
"function",
"parseImportLine",
"(",
"line",
")",
"{",
"if",
"(",
"IS_IMPORT",
".",
"test",
"(",
"line",
")",
")",
"{",
"const",
"[",
",",
"default0",
",",
"named",
",",
"default1",
"]",
"=",
"IMPORT",
".",
"exec",
"(",
"line",
")",
"const",
"defaultImport",
"=",
"default0",
"||",
"default1",
"const",
"namedImports",
"=",
"[",
"]",
"if",
"(",
"named",
")",
"{",
"let",
"next",
"while",
"(",
"(",
"next",
"=",
"NAMED_IMPORTS",
".",
"exec",
"(",
"named",
")",
")",
"!=",
"null",
")",
"{",
"const",
"[",
",",
"src",
",",
"importedAs",
"]",
"=",
"next",
"namedImports",
".",
"push",
"(",
"[",
"src",
",",
"importedAs",
"||",
"src",
"]",
")",
"}",
"}",
"return",
"[",
"defaultImport",
",",
"namedImports",
"]",
"}",
"else",
"{",
"return",
"null",
"}",
"}"
] |
parse a line to determine if it is an import of messages
|
[
"parse",
"a",
"line",
"to",
"determine",
"if",
"it",
"is",
"an",
"import",
"of",
"messages"
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/lint-messages.js#L23-L41
|
train
|
conveyal/mastarm
|
lib/lint-messages.js
|
lintFileContents
|
function lintFileContents (messages, js) {
// what was messages imported as
let importedAtRootAs = false
let importedMembersAs
const importedMembersLookup = new Map()
let namedMatcher, rootMatcher
// TODO handle importing members, e.g. import { analysis } from messages
const foundMessages = []
let lineNumber = 0 // first increment lands at 0
for (const line of js.split('\n')) {
lineNumber++
const parsedImport = parseImportLine(line)
if (parsedImport) {
;[importedAtRootAs, importedMembersAs] = parsedImport
// make sure we don't catch things like display_messages by making sure there's a diff char before
rootMatcher = new RegExp(
`[^a-zA-Z0-9_$]${importedAtRootAs}\\.([^ ,\\(\\)\\[}]+)`,
'g'
)
namedMatcher = new RegExp(
`[^a-zA-Z0-9_$](${importedMembersAs
.map(a => a[1])
.join('|')})\\.([^ ,\\(\\)\\[}]+)`,
'g'
)
importedMembersAs.forEach(([member, importedAs]) =>
importedMembersLookup.set(importedAs, member)
)
} else if (importedAtRootAs || importedMembersAs) {
let result
// each subsequent call gets next match
if (importedAtRootAs) {
while ((result = rootMatcher.exec(line)) != null) {
foundMessages.push([result[1], lineNumber])
}
}
// do the same for imported members
if (importedMembersAs.length > 0) {
while ((result = namedMatcher.exec(line)) != null) {
// map back to the names in the messages file
foundMessages.push([
`${importedMembersLookup.get(result[1])}.${result[2]}`,
lineNumber
])
}
}
}
}
// filter to only the missing ones
return foundMessages.filter(([message, lineNumber]) => {
let current = messages
for (const sub of message.split('.')) {
current = current[sub]
if (current == null) {
return true // something in the chain is undefined
}
}
return false
})
}
|
javascript
|
function lintFileContents (messages, js) {
// what was messages imported as
let importedAtRootAs = false
let importedMembersAs
const importedMembersLookup = new Map()
let namedMatcher, rootMatcher
// TODO handle importing members, e.g. import { analysis } from messages
const foundMessages = []
let lineNumber = 0 // first increment lands at 0
for (const line of js.split('\n')) {
lineNumber++
const parsedImport = parseImportLine(line)
if (parsedImport) {
;[importedAtRootAs, importedMembersAs] = parsedImport
// make sure we don't catch things like display_messages by making sure there's a diff char before
rootMatcher = new RegExp(
`[^a-zA-Z0-9_$]${importedAtRootAs}\\.([^ ,\\(\\)\\[}]+)`,
'g'
)
namedMatcher = new RegExp(
`[^a-zA-Z0-9_$](${importedMembersAs
.map(a => a[1])
.join('|')})\\.([^ ,\\(\\)\\[}]+)`,
'g'
)
importedMembersAs.forEach(([member, importedAs]) =>
importedMembersLookup.set(importedAs, member)
)
} else if (importedAtRootAs || importedMembersAs) {
let result
// each subsequent call gets next match
if (importedAtRootAs) {
while ((result = rootMatcher.exec(line)) != null) {
foundMessages.push([result[1], lineNumber])
}
}
// do the same for imported members
if (importedMembersAs.length > 0) {
while ((result = namedMatcher.exec(line)) != null) {
// map back to the names in the messages file
foundMessages.push([
`${importedMembersLookup.get(result[1])}.${result[2]}`,
lineNumber
])
}
}
}
}
// filter to only the missing ones
return foundMessages.filter(([message, lineNumber]) => {
let current = messages
for (const sub of message.split('.')) {
current = current[sub]
if (current == null) {
return true // something in the chain is undefined
}
}
return false
})
}
|
[
"function",
"lintFileContents",
"(",
"messages",
",",
"js",
")",
"{",
"let",
"importedAtRootAs",
"=",
"false",
"let",
"importedMembersAs",
"const",
"importedMembersLookup",
"=",
"new",
"Map",
"(",
")",
"let",
"namedMatcher",
",",
"rootMatcher",
"const",
"foundMessages",
"=",
"[",
"]",
"let",
"lineNumber",
"=",
"0",
"for",
"(",
"const",
"line",
"of",
"js",
".",
"split",
"(",
"'\\n'",
")",
")",
"\\n",
"{",
"lineNumber",
"++",
"const",
"parsedImport",
"=",
"parseImportLine",
"(",
"line",
")",
"if",
"(",
"parsedImport",
")",
"{",
";",
"[",
"importedAtRootAs",
",",
"importedMembersAs",
"]",
"=",
"parsedImport",
"rootMatcher",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"importedAtRootAs",
"}",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"`",
",",
"'g'",
")",
"namedMatcher",
"=",
"new",
"RegExp",
"(",
"`",
"${",
"importedMembersAs",
".",
"map",
"(",
"a",
"=>",
"a",
"[",
"1",
"]",
")",
".",
"join",
"(",
"'|'",
")",
"}",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"`",
",",
"'g'",
")",
"importedMembersAs",
".",
"forEach",
"(",
"(",
"[",
"member",
",",
"importedAs",
"]",
")",
"=>",
"importedMembersLookup",
".",
"set",
"(",
"importedAs",
",",
"member",
")",
")",
"}",
"else",
"if",
"(",
"importedAtRootAs",
"||",
"importedMembersAs",
")",
"{",
"let",
"result",
"if",
"(",
"importedAtRootAs",
")",
"{",
"while",
"(",
"(",
"result",
"=",
"rootMatcher",
".",
"exec",
"(",
"line",
")",
")",
"!=",
"null",
")",
"{",
"foundMessages",
".",
"push",
"(",
"[",
"result",
"[",
"1",
"]",
",",
"lineNumber",
"]",
")",
"}",
"}",
"if",
"(",
"importedMembersAs",
".",
"length",
">",
"0",
")",
"{",
"while",
"(",
"(",
"result",
"=",
"namedMatcher",
".",
"exec",
"(",
"line",
")",
")",
"!=",
"null",
")",
"{",
"foundMessages",
".",
"push",
"(",
"[",
"`",
"${",
"importedMembersLookup",
".",
"get",
"(",
"result",
"[",
"1",
"]",
")",
"}",
"${",
"result",
"[",
"2",
"]",
"}",
"`",
",",
"lineNumber",
"]",
")",
"}",
"}",
"}",
"}",
"}"
] |
Lint a file against messages. Exported for testing
|
[
"Lint",
"a",
"file",
"against",
"messages",
".",
"Exported",
"for",
"testing"
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/lint-messages.js#L44-L111
|
train
|
conveyal/mastarm
|
lib/js-transform.js
|
svgToString
|
function svgToString (filename) {
if (!/\.svg$/i.test(filename)) {
return through()
}
return through(function (buf, enc, next) {
this.push('module.exports=' + JSON.stringify(buf.toString('utf8')))
next()
})
}
|
javascript
|
function svgToString (filename) {
if (!/\.svg$/i.test(filename)) {
return through()
}
return through(function (buf, enc, next) {
this.push('module.exports=' + JSON.stringify(buf.toString('utf8')))
next()
})
}
|
[
"function",
"svgToString",
"(",
"filename",
")",
"{",
"if",
"(",
"!",
"/",
"\\.svg$",
"/",
"i",
".",
"test",
"(",
"filename",
")",
")",
"{",
"return",
"through",
"(",
")",
"}",
"return",
"through",
"(",
"function",
"(",
"buf",
",",
"enc",
",",
"next",
")",
"{",
"this",
".",
"push",
"(",
"'module.exports='",
"+",
"JSON",
".",
"stringify",
"(",
"buf",
".",
"toString",
"(",
"'utf8'",
")",
")",
")",
"next",
"(",
")",
"}",
")",
"}"
] |
Transform a svg file to a module containing a JSON string
|
[
"Transform",
"a",
"svg",
"file",
"to",
"a",
"module",
"containing",
"a",
"JSON",
"string"
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/js-transform.js#L43-L52
|
train
|
conveyal/mastarm
|
lib/js-transform.js
|
yamlTransform
|
function yamlTransform (filename) {
if (!/\.yml|\.yaml$/i.test(filename)) {
return through()
}
return through(function (buf, enc, next) {
this.push(
'module.exports=' + JSON.stringify(YAML.parse(buf.toString('utf8')))
)
next()
})
}
|
javascript
|
function yamlTransform (filename) {
if (!/\.yml|\.yaml$/i.test(filename)) {
return through()
}
return through(function (buf, enc, next) {
this.push(
'module.exports=' + JSON.stringify(YAML.parse(buf.toString('utf8')))
)
next()
})
}
|
[
"function",
"yamlTransform",
"(",
"filename",
")",
"{",
"if",
"(",
"!",
"/",
"\\.yml|\\.yaml$",
"/",
"i",
".",
"test",
"(",
"filename",
")",
")",
"{",
"return",
"through",
"(",
")",
"}",
"return",
"through",
"(",
"function",
"(",
"buf",
",",
"enc",
",",
"next",
")",
"{",
"this",
".",
"push",
"(",
"'module.exports='",
"+",
"JSON",
".",
"stringify",
"(",
"YAML",
".",
"parse",
"(",
"buf",
".",
"toString",
"(",
"'utf8'",
")",
")",
")",
")",
"next",
"(",
")",
"}",
")",
"}"
] |
Transform an YAML file to a module containing a JSON string
|
[
"Transform",
"an",
"YAML",
"file",
"to",
"a",
"module",
"containing",
"a",
"JSON",
"string"
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/js-transform.js#L85-L96
|
train
|
conveyal/mastarm
|
lib/flyle.js
|
logAndSend
|
function logAndSend ({ err, res }) {
logger.error('flyle >> sending default image: ', err.message)
sendImg({
path: DEFAULT_PNG,
res
})
}
|
javascript
|
function logAndSend ({ err, res }) {
logger.error('flyle >> sending default image: ', err.message)
sendImg({
path: DEFAULT_PNG,
res
})
}
|
[
"function",
"logAndSend",
"(",
"{",
"err",
",",
"res",
"}",
")",
"{",
"logger",
".",
"error",
"(",
"'flyle >> sending default image: '",
",",
"err",
".",
"message",
")",
"sendImg",
"(",
"{",
"path",
":",
"DEFAULT_PNG",
",",
"res",
"}",
")",
"}"
] |
Send the default image and log an error
|
[
"Send",
"the",
"default",
"image",
"and",
"log",
"an",
"error"
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/flyle.js#L53-L59
|
train
|
conveyal/mastarm
|
lib/flyle.js
|
sendImg
|
function sendImg ({ path, res }) {
res.writeHead(STATUS_OK, {
'Content-Type': 'image/png'
})
fs.createReadStream(path).pipe(res)
}
|
javascript
|
function sendImg ({ path, res }) {
res.writeHead(STATUS_OK, {
'Content-Type': 'image/png'
})
fs.createReadStream(path).pipe(res)
}
|
[
"function",
"sendImg",
"(",
"{",
"path",
",",
"res",
"}",
")",
"{",
"res",
".",
"writeHead",
"(",
"STATUS_OK",
",",
"{",
"'Content-Type'",
":",
"'image/png'",
"}",
")",
"fs",
".",
"createReadStream",
"(",
"path",
")",
".",
"pipe",
"(",
"res",
")",
"}"
] |
Respond with an image
|
[
"Respond",
"with",
"an",
"image"
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/flyle.js#L66-L71
|
train
|
conveyal/mastarm
|
lib/util.js
|
classifyFile
|
function classifyFile (file) {
return stat(file).then(({ err, stats }) => {
if (err) {
if (err.code === 'ENOENT') {
missingFiles.push(file)
} else {
throw err
}
} else {
foundFiles.push(file)
}
})
}
|
javascript
|
function classifyFile (file) {
return stat(file).then(({ err, stats }) => {
if (err) {
if (err.code === 'ENOENT') {
missingFiles.push(file)
} else {
throw err
}
} else {
foundFiles.push(file)
}
})
}
|
[
"function",
"classifyFile",
"(",
"file",
")",
"{",
"return",
"stat",
"(",
"file",
")",
".",
"then",
"(",
"(",
"{",
"err",
",",
"stats",
"}",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"code",
"===",
"'ENOENT'",
")",
"{",
"missingFiles",
".",
"push",
"(",
"file",
")",
"}",
"else",
"{",
"throw",
"err",
"}",
"}",
"else",
"{",
"foundFiles",
".",
"push",
"(",
"file",
")",
"}",
"}",
")",
"}"
] |
Add the file to the foundFiles or missingFiles arrays based on their existance.
|
[
"Add",
"the",
"file",
"to",
"the",
"foundFiles",
"or",
"missingFiles",
"arrays",
"based",
"on",
"their",
"existance",
"."
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/util.js#L32-L44
|
train
|
conveyal/mastarm
|
lib/util.js
|
globPromise
|
function globPromise (file) {
return new Promise((resolve, reject) => {
glob(file, (err, files) => {
if (err) {
reject(err)
} else {
resolve(files)
}
})
})
}
|
javascript
|
function globPromise (file) {
return new Promise((resolve, reject) => {
glob(file, (err, files) => {
if (err) {
reject(err)
} else {
resolve(files)
}
})
})
}
|
[
"function",
"globPromise",
"(",
"file",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"glob",
"(",
"file",
",",
"(",
"err",
",",
"files",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
"}",
"else",
"{",
"resolve",
"(",
"files",
")",
"}",
"}",
")",
"}",
")",
"}"
] |
Use the `glob` function on a file, but return a promise
|
[
"Use",
"the",
"glob",
"function",
"on",
"a",
"file",
"but",
"return",
"a",
"promise"
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/util.js#L49-L59
|
train
|
conveyal/mastarm
|
lib/util.js
|
globFile
|
function globFile (file) {
return stat(file).then(({ err, stats }) => {
if (err) throw err
if (stats.isDirectory()) {
// TODO what if file is already slash-terminated?
switch (file) {
case './':
return globPromise('./*.js')
case 'bin':
return globPromise('bin/*')
default:
return globPromise(`${file}/**/*.js`)
}
} else {
return Promise.resolve(file)
}
})
}
|
javascript
|
function globFile (file) {
return stat(file).then(({ err, stats }) => {
if (err) throw err
if (stats.isDirectory()) {
// TODO what if file is already slash-terminated?
switch (file) {
case './':
return globPromise('./*.js')
case 'bin':
return globPromise('bin/*')
default:
return globPromise(`${file}/**/*.js`)
}
} else {
return Promise.resolve(file)
}
})
}
|
[
"function",
"globFile",
"(",
"file",
")",
"{",
"return",
"stat",
"(",
"file",
")",
".",
"then",
"(",
"(",
"{",
"err",
",",
"stats",
"}",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"throw",
"err",
"if",
"(",
"stats",
".",
"isDirectory",
"(",
")",
")",
"{",
"switch",
"(",
"file",
")",
"{",
"case",
"'./'",
":",
"return",
"globPromise",
"(",
"'./*.js'",
")",
"case",
"'bin'",
":",
"return",
"globPromise",
"(",
"'bin/*'",
")",
"default",
":",
"return",
"globPromise",
"(",
"`",
"${",
"file",
"}",
"`",
")",
"}",
"}",
"else",
"{",
"return",
"Promise",
".",
"resolve",
"(",
"file",
")",
"}",
"}",
")",
"}"
] |
Glob a path.
If the path is a file, return the path
If the path is a directory, return the promisified glob of the directory
Throw an error if the path does no exist
|
[
"Glob",
"a",
"path",
".",
"If",
"the",
"path",
"is",
"a",
"file",
"return",
"the",
"path",
"If",
"the",
"path",
"is",
"a",
"directory",
"return",
"the",
"promisified",
"glob",
"of",
"the",
"directory",
"Throw",
"an",
"error",
"if",
"the",
"path",
"does",
"no",
"exist"
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/util.js#L67-L84
|
train
|
nodules/asker
|
lib/asker.js
|
clearTimeouts
|
function clearTimeouts() {
// stop tracking time for network operations
self._networkTime = contimer.stop(self._timerCtx, self.buildTimerId('network'));
if (socketTimeout) {
clearTimeout(socketTimeout);
socketTimeout = null;
}
if (queueTimeout) {
clearTimeout(queueTimeout);
queueTimeout = null;
}
}
|
javascript
|
function clearTimeouts() {
// stop tracking time for network operations
self._networkTime = contimer.stop(self._timerCtx, self.buildTimerId('network'));
if (socketTimeout) {
clearTimeout(socketTimeout);
socketTimeout = null;
}
if (queueTimeout) {
clearTimeout(queueTimeout);
queueTimeout = null;
}
}
|
[
"function",
"clearTimeouts",
"(",
")",
"{",
"self",
".",
"_networkTime",
"=",
"contimer",
".",
"stop",
"(",
"self",
".",
"_timerCtx",
",",
"self",
".",
"buildTimerId",
"(",
"'network'",
")",
")",
";",
"if",
"(",
"socketTimeout",
")",
"{",
"clearTimeout",
"(",
"socketTimeout",
")",
";",
"socketTimeout",
"=",
"null",
";",
"}",
"if",
"(",
"queueTimeout",
")",
"{",
"clearTimeout",
"(",
"queueTimeout",
")",
";",
"queueTimeout",
"=",
"null",
";",
"}",
"}"
] |
Clears queue and socket timeouts if any
|
[
"Clears",
"queue",
"and",
"socket",
"timeouts",
"if",
"any"
] |
edf5f733806a044634a37c704e01077b9afa064f
|
https://github.com/nodules/asker/blob/edf5f733806a044634a37c704e01077b9afa064f/lib/asker.js#L586-L599
|
train
|
nodules/asker
|
lib/asker.js
|
breakRequest
|
function breakRequest(retryReason) {
clearTimeouts();
// mark this request as rejected, response must not be built in this case
httpRequest.rejected = true;
// force agent "freeness" (e.g. release) in Node.js<0.12 and dump response object internally
httpRequest.abort();
if (retryReason) {
// call for retry if retryReason provided
self._retryHttpRequest(retryReason);
}
}
|
javascript
|
function breakRequest(retryReason) {
clearTimeouts();
// mark this request as rejected, response must not be built in this case
httpRequest.rejected = true;
// force agent "freeness" (e.g. release) in Node.js<0.12 and dump response object internally
httpRequest.abort();
if (retryReason) {
// call for retry if retryReason provided
self._retryHttpRequest(retryReason);
}
}
|
[
"function",
"breakRequest",
"(",
"retryReason",
")",
"{",
"clearTimeouts",
"(",
")",
";",
"httpRequest",
".",
"rejected",
"=",
"true",
";",
"httpRequest",
".",
"abort",
"(",
")",
";",
"if",
"(",
"retryReason",
")",
"{",
"self",
".",
"_retryHttpRequest",
"(",
"retryReason",
")",
";",
"}",
"}"
] |
Breaks request execution and retry request if retryReason is provided
@param {AskerError} [retryReason]
|
[
"Breaks",
"request",
"execution",
"and",
"retry",
"request",
"if",
"retryReason",
"is",
"provided"
] |
edf5f733806a044634a37c704e01077b9afa064f
|
https://github.com/nodules/asker/blob/edf5f733806a044634a37c704e01077b9afa064f/lib/asker.js#L605-L617
|
train
|
conveyal/mastarm
|
lib/push-to-s3.js
|
upload
|
function upload ({ body, s3bucket, cloudfront, outfile }) {
const bucketUrl = `https://s3.amazonaws.com/${s3bucket}`
return new Promise((resolve, reject) => {
const s3object = new AWS.S3({
params: {
ACL: 'public-read',
Body: body,
Bucket: s3bucket,
ContentType: mime.getType(outfile),
Key: outfile
}
})
const bytes = bytesToSize(body.byteLength || body.length)
const bucketLink = `<${bucketUrl}/${outfile}|${s3bucket}/${outfile}>`
s3object.upload().send(function (err) {
if (err) {
return reject(
new Error(
`s3 upload to ${bucketLink} rejected with ${err.code} ${
err.message
}`
)
)
}
if (cloudfront) {
const cf = new AWS.CloudFront()
logger
.log(`:lightning: *cloudfront:* invalidating path ${outfile}`)
.then(() => {
cf.createInvalidation(
{
DistributionId: cloudfront,
InvalidationBatch: {
CallerReference: uuid.v4(),
Paths: {
Items: ['/' + outfile],
Quantity: 1
}
}
},
function (err) {
if (err) {
return reject(
new Error(`cf invalidation rejected with ${err.message}`)
)
}
done()
}
)
})
} else {
done()
}
})
/**
* Helper function to log a successful upload to s3.
*/
function done () {
logger
.log(`:checkered_flag: *uploaded:* ${bucketLink} (${bytes})`)
.then(resolve)
}
})
}
|
javascript
|
function upload ({ body, s3bucket, cloudfront, outfile }) {
const bucketUrl = `https://s3.amazonaws.com/${s3bucket}`
return new Promise((resolve, reject) => {
const s3object = new AWS.S3({
params: {
ACL: 'public-read',
Body: body,
Bucket: s3bucket,
ContentType: mime.getType(outfile),
Key: outfile
}
})
const bytes = bytesToSize(body.byteLength || body.length)
const bucketLink = `<${bucketUrl}/${outfile}|${s3bucket}/${outfile}>`
s3object.upload().send(function (err) {
if (err) {
return reject(
new Error(
`s3 upload to ${bucketLink} rejected with ${err.code} ${
err.message
}`
)
)
}
if (cloudfront) {
const cf = new AWS.CloudFront()
logger
.log(`:lightning: *cloudfront:* invalidating path ${outfile}`)
.then(() => {
cf.createInvalidation(
{
DistributionId: cloudfront,
InvalidationBatch: {
CallerReference: uuid.v4(),
Paths: {
Items: ['/' + outfile],
Quantity: 1
}
}
},
function (err) {
if (err) {
return reject(
new Error(`cf invalidation rejected with ${err.message}`)
)
}
done()
}
)
})
} else {
done()
}
})
/**
* Helper function to log a successful upload to s3.
*/
function done () {
logger
.log(`:checkered_flag: *uploaded:* ${bucketLink} (${bytes})`)
.then(resolve)
}
})
}
|
[
"function",
"upload",
"(",
"{",
"body",
",",
"s3bucket",
",",
"cloudfront",
",",
"outfile",
"}",
")",
"{",
"const",
"bucketUrl",
"=",
"`",
"${",
"s3bucket",
"}",
"`",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"const",
"s3object",
"=",
"new",
"AWS",
".",
"S3",
"(",
"{",
"params",
":",
"{",
"ACL",
":",
"'public-read'",
",",
"Body",
":",
"body",
",",
"Bucket",
":",
"s3bucket",
",",
"ContentType",
":",
"mime",
".",
"getType",
"(",
"outfile",
")",
",",
"Key",
":",
"outfile",
"}",
"}",
")",
"const",
"bytes",
"=",
"bytesToSize",
"(",
"body",
".",
"byteLength",
"||",
"body",
".",
"length",
")",
"const",
"bucketLink",
"=",
"`",
"${",
"bucketUrl",
"}",
"${",
"outfile",
"}",
"${",
"s3bucket",
"}",
"${",
"outfile",
"}",
"`",
"s3object",
".",
"upload",
"(",
")",
".",
"send",
"(",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"bucketLink",
"}",
"${",
"err",
".",
"code",
"}",
"${",
"err",
".",
"message",
"}",
"`",
")",
")",
"}",
"if",
"(",
"cloudfront",
")",
"{",
"const",
"cf",
"=",
"new",
"AWS",
".",
"CloudFront",
"(",
")",
"logger",
".",
"log",
"(",
"`",
"${",
"outfile",
"}",
"`",
")",
".",
"then",
"(",
"(",
")",
"=>",
"{",
"cf",
".",
"createInvalidation",
"(",
"{",
"DistributionId",
":",
"cloudfront",
",",
"InvalidationBatch",
":",
"{",
"CallerReference",
":",
"uuid",
".",
"v4",
"(",
")",
",",
"Paths",
":",
"{",
"Items",
":",
"[",
"'/'",
"+",
"outfile",
"]",
",",
"Quantity",
":",
"1",
"}",
"}",
"}",
",",
"function",
"(",
"err",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"reject",
"(",
"new",
"Error",
"(",
"`",
"${",
"err",
".",
"message",
"}",
"`",
")",
")",
"}",
"done",
"(",
")",
"}",
")",
"}",
")",
"}",
"else",
"{",
"done",
"(",
")",
"}",
"}",
")",
"function",
"done",
"(",
")",
"{",
"logger",
".",
"log",
"(",
"`",
"${",
"bucketLink",
"}",
"${",
"bytes",
"}",
"`",
")",
".",
"then",
"(",
"resolve",
")",
"}",
"}",
")",
"}"
] |
Upload the contents of a file to s3.
Also, invalidate the respective cloudfront path if instructed to do so.
|
[
"Upload",
"the",
"contents",
"of",
"a",
"file",
"to",
"s3",
".",
"Also",
"invalidate",
"the",
"respective",
"cloudfront",
"path",
"if",
"instructed",
"to",
"do",
"so",
"."
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/push-to-s3.js#L14-L79
|
train
|
conveyal/mastarm
|
lib/push-to-s3.js
|
bytesToSize
|
function bytesToSize (bytes) {
const sizes = ['bytes', 'kb', 'mb', 'gb', 'tb']
if (bytes === 0) return '0 byte'
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(BYTES)))
return (bytes / Math.pow(BYTES, i)).toFixed(DISPLAY_DECIMALS) + sizes[i]
}
|
javascript
|
function bytesToSize (bytes) {
const sizes = ['bytes', 'kb', 'mb', 'gb', 'tb']
if (bytes === 0) return '0 byte'
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(BYTES)))
return (bytes / Math.pow(BYTES, i)).toFixed(DISPLAY_DECIMALS) + sizes[i]
}
|
[
"function",
"bytesToSize",
"(",
"bytes",
")",
"{",
"const",
"sizes",
"=",
"[",
"'bytes'",
",",
"'kb'",
",",
"'mb'",
",",
"'gb'",
",",
"'tb'",
"]",
"if",
"(",
"bytes",
"===",
"0",
")",
"return",
"'0 byte'",
"const",
"i",
"=",
"parseInt",
"(",
"Math",
".",
"floor",
"(",
"Math",
".",
"log",
"(",
"bytes",
")",
"/",
"Math",
".",
"log",
"(",
"BYTES",
")",
")",
")",
"return",
"(",
"bytes",
"/",
"Math",
".",
"pow",
"(",
"BYTES",
",",
"i",
")",
")",
".",
"toFixed",
"(",
"DISPLAY_DECIMALS",
")",
"+",
"sizes",
"[",
"i",
"]",
"}"
] |
Pretty print the size of the number of bytes.
|
[
"Pretty",
"print",
"the",
"size",
"of",
"the",
"number",
"of",
"bytes",
"."
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/push-to-s3.js#L87-L92
|
train
|
conveyal/mastarm
|
lib/css-transform.js
|
getUrl
|
function getUrl (value) {
const reg = /url\((\s*)(['"]?)(.+?)\2(\s*)\)/g
const match = reg.exec(value)
const url = match[URL_POSITION]
return url
}
|
javascript
|
function getUrl (value) {
const reg = /url\((\s*)(['"]?)(.+?)\2(\s*)\)/g
const match = reg.exec(value)
const url = match[URL_POSITION]
return url
}
|
[
"function",
"getUrl",
"(",
"value",
")",
"{",
"const",
"reg",
"=",
"/",
"url\\((\\s*)(['\"]?)(.+?)\\2(\\s*)\\)",
"/",
"g",
"const",
"match",
"=",
"reg",
".",
"exec",
"(",
"value",
")",
"const",
"url",
"=",
"match",
"[",
"URL_POSITION",
"]",
"return",
"url",
"}"
] |
Extract the contents of a css url
@param {string} value raw css
@return {string} the contents of the url
|
[
"Extract",
"the",
"contents",
"of",
"a",
"css",
"url"
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/css-transform.js#L119-L124
|
train
|
conveyal/mastarm
|
lib/browserify.js
|
browserifyIt
|
function browserifyIt ({ config, entry, env, instrument }) {
return browserify(entry, {
basedir: process.cwd(),
cache: {},
debug: true,
fullPaths: env === 'development',
packageCache: {},
paths: [
path.join(__dirname, '/../node_modules'),
path.join(process.cwd(), '/node_modules')
],
transform: transform({ config, env, instrument })
})
}
|
javascript
|
function browserifyIt ({ config, entry, env, instrument }) {
return browserify(entry, {
basedir: process.cwd(),
cache: {},
debug: true,
fullPaths: env === 'development',
packageCache: {},
paths: [
path.join(__dirname, '/../node_modules'),
path.join(process.cwd(), '/node_modules')
],
transform: transform({ config, env, instrument })
})
}
|
[
"function",
"browserifyIt",
"(",
"{",
"config",
",",
"entry",
",",
"env",
",",
"instrument",
"}",
")",
"{",
"return",
"browserify",
"(",
"entry",
",",
"{",
"basedir",
":",
"process",
".",
"cwd",
"(",
")",
",",
"cache",
":",
"{",
"}",
",",
"debug",
":",
"true",
",",
"fullPaths",
":",
"env",
"===",
"'development'",
",",
"packageCache",
":",
"{",
"}",
",",
"paths",
":",
"[",
"path",
".",
"join",
"(",
"__dirname",
",",
"'/../node_modules'",
")",
",",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"'/node_modules'",
")",
"]",
",",
"transform",
":",
"transform",
"(",
"{",
"config",
",",
"env",
",",
"instrument",
"}",
")",
"}",
")",
"}"
] |
Bundle some js together with browserify
|
[
"Bundle",
"some",
"js",
"together",
"with",
"browserify"
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/browserify.js#L13-L26
|
train
|
conveyal/mastarm
|
lib/prepublish.js
|
transformDir
|
function transformDir ({ config, entry, outdir }) {
return glob.sync(`${entry[0]}/**/*.js`).map(filename =>
transformFile({
config,
entry: [filename, filename.replace(entry[0], entry[1] || outdir)]
})
)
}
|
javascript
|
function transformDir ({ config, entry, outdir }) {
return glob.sync(`${entry[0]}/**/*.js`).map(filename =>
transformFile({
config,
entry: [filename, filename.replace(entry[0], entry[1] || outdir)]
})
)
}
|
[
"function",
"transformDir",
"(",
"{",
"config",
",",
"entry",
",",
"outdir",
"}",
")",
"{",
"return",
"glob",
".",
"sync",
"(",
"`",
"${",
"entry",
"[",
"0",
"]",
"}",
"`",
")",
".",
"map",
"(",
"filename",
"=>",
"transformFile",
"(",
"{",
"config",
",",
"entry",
":",
"[",
"filename",
",",
"filename",
".",
"replace",
"(",
"entry",
"[",
"0",
"]",
",",
"entry",
"[",
"1",
"]",
"||",
"outdir",
")",
"]",
"}",
")",
")",
"}"
] |
Transform all of the files in a directory recursively.
|
[
"Transform",
"all",
"of",
"the",
"files",
"in",
"a",
"directory",
"recursively",
"."
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/prepublish.js#L29-L36
|
train
|
conveyal/mastarm
|
lib/prepublish.js
|
transformFile
|
function transformFile ({ config, entry, outdir }) {
const filename = entry[0]
const filepath = entry[1] || `${outdir}/${filename}`
const results = babel.transform(
fs.readFileSync(filename, 'utf8'),
Object.assign({}, config, { filename, sourceMaps: true })
)
mkdirp.sync(path.dirname(filepath))
fs.writeFileSync(
filepath,
results.code + '\n\n//# sourceMappingURL=' + path.basename(filepath)
)
fs.writeFileSync(`${filepath}.map`, JSON.stringify(results.map))
return results
}
|
javascript
|
function transformFile ({ config, entry, outdir }) {
const filename = entry[0]
const filepath = entry[1] || `${outdir}/${filename}`
const results = babel.transform(
fs.readFileSync(filename, 'utf8'),
Object.assign({}, config, { filename, sourceMaps: true })
)
mkdirp.sync(path.dirname(filepath))
fs.writeFileSync(
filepath,
results.code + '\n\n//# sourceMappingURL=' + path.basename(filepath)
)
fs.writeFileSync(`${filepath}.map`, JSON.stringify(results.map))
return results
}
|
[
"function",
"transformFile",
"(",
"{",
"config",
",",
"entry",
",",
"outdir",
"}",
")",
"{",
"const",
"filename",
"=",
"entry",
"[",
"0",
"]",
"const",
"filepath",
"=",
"entry",
"[",
"1",
"]",
"||",
"`",
"${",
"outdir",
"}",
"${",
"filename",
"}",
"`",
"const",
"results",
"=",
"babel",
".",
"transform",
"(",
"fs",
".",
"readFileSync",
"(",
"filename",
",",
"'utf8'",
")",
",",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"config",
",",
"{",
"filename",
",",
"sourceMaps",
":",
"true",
"}",
")",
")",
"mkdirp",
".",
"sync",
"(",
"path",
".",
"dirname",
"(",
"filepath",
")",
")",
"fs",
".",
"writeFileSync",
"(",
"filepath",
",",
"results",
".",
"code",
"+",
"'\\n\\n//# sourceMappingURL='",
"+",
"\\n",
")",
"\\n",
"path",
".",
"basename",
"(",
"filepath",
")",
"}"
] |
Transform a file with babel and also write the sourcemap for the file.
|
[
"Transform",
"a",
"file",
"with",
"babel",
"and",
"also",
"write",
"the",
"sourcemap",
"for",
"the",
"file",
"."
] |
bf525af25c6b6a14e383bc009cd92753b520e50b
|
https://github.com/conveyal/mastarm/blob/bf525af25c6b6a14e383bc009cd92753b520e50b/lib/prepublish.js#L41-L56
|
train
|
thrashr888/grunt-sftp-deploy
|
tasks/sftp-deploy.js
|
dirParseSync
|
function dirParseSync(startDir, result) {
var files;
var i;
var tmpPath;
var currFile;
// initialize the `result` object if it is the first iteration
if (result === undefined) {
result = {};
result[localSep] = [];
}
// check if `startDir` is a valid location
if (!fs.existsSync(startDir)) {
grunt.warn(startDir + ' is not an existing location');
}
// iterate throught the contents of the `startDir` location of the current iteration
files = fs.readdirSync(startDir);
for (i = 0; i < files.length; i++) {
currFile = startDir + localSep + files[i];
if (!file.isMatch({matchBase: true}, exclusions, currFile)) {
if (file.isDir(currFile)) {
tmpPath = path.relative(localRoot, startDir + localSep + files[i]);
if (!_.has(result, tmpPath)) {
result[tmpPath] = [];
}
dirParseSync(currFile, result);
} else {
tmpPath = path.relative(localRoot, startDir);
if (!tmpPath.length) {
tmpPath = localSep;
}
result[tmpPath].push(files[i]);
}
}
}
return result;
}
|
javascript
|
function dirParseSync(startDir, result) {
var files;
var i;
var tmpPath;
var currFile;
// initialize the `result` object if it is the first iteration
if (result === undefined) {
result = {};
result[localSep] = [];
}
// check if `startDir` is a valid location
if (!fs.existsSync(startDir)) {
grunt.warn(startDir + ' is not an existing location');
}
// iterate throught the contents of the `startDir` location of the current iteration
files = fs.readdirSync(startDir);
for (i = 0; i < files.length; i++) {
currFile = startDir + localSep + files[i];
if (!file.isMatch({matchBase: true}, exclusions, currFile)) {
if (file.isDir(currFile)) {
tmpPath = path.relative(localRoot, startDir + localSep + files[i]);
if (!_.has(result, tmpPath)) {
result[tmpPath] = [];
}
dirParseSync(currFile, result);
} else {
tmpPath = path.relative(localRoot, startDir);
if (!tmpPath.length) {
tmpPath = localSep;
}
result[tmpPath].push(files[i]);
}
}
}
return result;
}
|
[
"function",
"dirParseSync",
"(",
"startDir",
",",
"result",
")",
"{",
"var",
"files",
";",
"var",
"i",
";",
"var",
"tmpPath",
";",
"var",
"currFile",
";",
"if",
"(",
"result",
"===",
"undefined",
")",
"{",
"result",
"=",
"{",
"}",
";",
"result",
"[",
"localSep",
"]",
"=",
"[",
"]",
";",
"}",
"if",
"(",
"!",
"fs",
".",
"existsSync",
"(",
"startDir",
")",
")",
"{",
"grunt",
".",
"warn",
"(",
"startDir",
"+",
"' is not an existing location'",
")",
";",
"}",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"startDir",
")",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"currFile",
"=",
"startDir",
"+",
"localSep",
"+",
"files",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"file",
".",
"isMatch",
"(",
"{",
"matchBase",
":",
"true",
"}",
",",
"exclusions",
",",
"currFile",
")",
")",
"{",
"if",
"(",
"file",
".",
"isDir",
"(",
"currFile",
")",
")",
"{",
"tmpPath",
"=",
"path",
".",
"relative",
"(",
"localRoot",
",",
"startDir",
"+",
"localSep",
"+",
"files",
"[",
"i",
"]",
")",
";",
"if",
"(",
"!",
"_",
".",
"has",
"(",
"result",
",",
"tmpPath",
")",
")",
"{",
"result",
"[",
"tmpPath",
"]",
"=",
"[",
"]",
";",
"}",
"dirParseSync",
"(",
"currFile",
",",
"result",
")",
";",
"}",
"else",
"{",
"tmpPath",
"=",
"path",
".",
"relative",
"(",
"localRoot",
",",
"startDir",
")",
";",
"if",
"(",
"!",
"tmpPath",
".",
"length",
")",
"{",
"tmpPath",
"=",
"localSep",
";",
"}",
"result",
"[",
"tmpPath",
"]",
".",
"push",
"(",
"files",
"[",
"i",
"]",
")",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] |
A method for parsing the source location and storing the information into a suitably formated object
|
[
"A",
"method",
"for",
"parsing",
"the",
"source",
"location",
"and",
"storing",
"the",
"information",
"into",
"a",
"suitably",
"formated",
"object"
] |
71aeb29e90f4d1fd9589bf43a7c39654eb08a657
|
https://github.com/thrashr888/grunt-sftp-deploy/blob/71aeb29e90f4d1fd9589bf43a7c39654eb08a657/tasks/sftp-deploy.js#L42-L81
|
train
|
CPatchane/create-cozy-app
|
packages/cozy-scripts/config/webpack.config.hash.js
|
function() {
this.plugin('done', stats => {
fs.writeFileSync(
path.join(targetConfig.output.path, paths.appBuildAssetsJson()),
`{"hash":"${stats.hash}"}`
)
})
}
|
javascript
|
function() {
this.plugin('done', stats => {
fs.writeFileSync(
path.join(targetConfig.output.path, paths.appBuildAssetsJson()),
`{"hash":"${stats.hash}"}`
)
})
}
|
[
"function",
"(",
")",
"{",
"this",
".",
"plugin",
"(",
"'done'",
",",
"stats",
"=>",
"{",
"fs",
".",
"writeFileSync",
"(",
"path",
".",
"join",
"(",
"targetConfig",
".",
"output",
".",
"path",
",",
"paths",
".",
"appBuildAssetsJson",
"(",
")",
")",
",",
"`",
"${",
"stats",
".",
"hash",
"}",
"`",
")",
"}",
")",
"}"
] |
Extracts Hash in external file for reference
|
[
"Extracts",
"Hash",
"in",
"external",
"file",
"for",
"reference"
] |
14ff6733e51a2c50a472ecebd895ed557c62fc37
|
https://github.com/CPatchane/create-cozy-app/blob/14ff6733e51a2c50a472ecebd895ed557c62fc37/packages/cozy-scripts/config/webpack.config.hash.js#L13-L20
|
train
|
|
ssbc/patchcore
|
backlinks/obs-cache.js
|
createCache
|
function createCache (cacheForMilliSeconds) {
var cache = {}
var newRemove = new Set()
var oldRemove = new Set()
function use (id) {
newRemove.delete(id)
oldRemove.delete(id)
}
function release (id) {
newRemove.add(id)
}
var timer = setInterval(() => {
oldRemove.forEach(id => {
if (cache[id]) {
cache[id].destroy()
delete cache[id]
}
})
oldRemove.clear()
// cycle
var hold = oldRemove
oldRemove = newRemove
newRemove = hold
}, cacheForMilliSeconds || 5e3)
if (timer.unref) timer.unref()
/**
* Takes a thread ID (for the cache ID) and a pull stream to populate the
* backlinks observable with. After the backlinks obserable is unsubscribed
* from it is cached for the configured amount of time before the pull stream
* is aborted unless there is a new incoming listener
*/
function cachedBacklinks (id, backlinksPullStream) {
if (!cache[id]) {
var sync = Value(false)
var aborter = Abortable()
var collection = Value([])
// try not to saturate the thread
onceIdle(() => {
pull(
backlinksPullStream,
aborter,
pull.drain((msg) => {
if (msg.sync) {
sync.set(true)
} else {
var value = resolve(collection)
value.push(msg)
collection.set(value)
}
})
)
})
cache[id] = computed([collection], x => x, {
onListen: () => use(id),
onUnlisten: () => release(id)
})
cache[id].destroy = aborter.abort
cache[id].sync = sync
}
return cache[id]
}
return {
cachedBacklinks: cachedBacklinks
}
}
|
javascript
|
function createCache (cacheForMilliSeconds) {
var cache = {}
var newRemove = new Set()
var oldRemove = new Set()
function use (id) {
newRemove.delete(id)
oldRemove.delete(id)
}
function release (id) {
newRemove.add(id)
}
var timer = setInterval(() => {
oldRemove.forEach(id => {
if (cache[id]) {
cache[id].destroy()
delete cache[id]
}
})
oldRemove.clear()
// cycle
var hold = oldRemove
oldRemove = newRemove
newRemove = hold
}, cacheForMilliSeconds || 5e3)
if (timer.unref) timer.unref()
/**
* Takes a thread ID (for the cache ID) and a pull stream to populate the
* backlinks observable with. After the backlinks obserable is unsubscribed
* from it is cached for the configured amount of time before the pull stream
* is aborted unless there is a new incoming listener
*/
function cachedBacklinks (id, backlinksPullStream) {
if (!cache[id]) {
var sync = Value(false)
var aborter = Abortable()
var collection = Value([])
// try not to saturate the thread
onceIdle(() => {
pull(
backlinksPullStream,
aborter,
pull.drain((msg) => {
if (msg.sync) {
sync.set(true)
} else {
var value = resolve(collection)
value.push(msg)
collection.set(value)
}
})
)
})
cache[id] = computed([collection], x => x, {
onListen: () => use(id),
onUnlisten: () => release(id)
})
cache[id].destroy = aborter.abort
cache[id].sync = sync
}
return cache[id]
}
return {
cachedBacklinks: cachedBacklinks
}
}
|
[
"function",
"createCache",
"(",
"cacheForMilliSeconds",
")",
"{",
"var",
"cache",
"=",
"{",
"}",
"var",
"newRemove",
"=",
"new",
"Set",
"(",
")",
"var",
"oldRemove",
"=",
"new",
"Set",
"(",
")",
"function",
"use",
"(",
"id",
")",
"{",
"newRemove",
".",
"delete",
"(",
"id",
")",
"oldRemove",
".",
"delete",
"(",
"id",
")",
"}",
"function",
"release",
"(",
"id",
")",
"{",
"newRemove",
".",
"add",
"(",
"id",
")",
"}",
"var",
"timer",
"=",
"setInterval",
"(",
"(",
")",
"=>",
"{",
"oldRemove",
".",
"forEach",
"(",
"id",
"=>",
"{",
"if",
"(",
"cache",
"[",
"id",
"]",
")",
"{",
"cache",
"[",
"id",
"]",
".",
"destroy",
"(",
")",
"delete",
"cache",
"[",
"id",
"]",
"}",
"}",
")",
"oldRemove",
".",
"clear",
"(",
")",
"var",
"hold",
"=",
"oldRemove",
"oldRemove",
"=",
"newRemove",
"newRemove",
"=",
"hold",
"}",
",",
"cacheForMilliSeconds",
"||",
"5e3",
")",
"if",
"(",
"timer",
".",
"unref",
")",
"timer",
".",
"unref",
"(",
")",
"function",
"cachedBacklinks",
"(",
"id",
",",
"backlinksPullStream",
")",
"{",
"if",
"(",
"!",
"cache",
"[",
"id",
"]",
")",
"{",
"var",
"sync",
"=",
"Value",
"(",
"false",
")",
"var",
"aborter",
"=",
"Abortable",
"(",
")",
"var",
"collection",
"=",
"Value",
"(",
"[",
"]",
")",
"onceIdle",
"(",
"(",
")",
"=>",
"{",
"pull",
"(",
"backlinksPullStream",
",",
"aborter",
",",
"pull",
".",
"drain",
"(",
"(",
"msg",
")",
"=>",
"{",
"if",
"(",
"msg",
".",
"sync",
")",
"{",
"sync",
".",
"set",
"(",
"true",
")",
"}",
"else",
"{",
"var",
"value",
"=",
"resolve",
"(",
"collection",
")",
"value",
".",
"push",
"(",
"msg",
")",
"collection",
".",
"set",
"(",
"value",
")",
"}",
"}",
")",
")",
"}",
")",
"cache",
"[",
"id",
"]",
"=",
"computed",
"(",
"[",
"collection",
"]",
",",
"x",
"=>",
"x",
",",
"{",
"onListen",
":",
"(",
")",
"=>",
"use",
"(",
"id",
")",
",",
"onUnlisten",
":",
"(",
")",
"=>",
"release",
"(",
"id",
")",
"}",
")",
"cache",
"[",
"id",
"]",
".",
"destroy",
"=",
"aborter",
".",
"abort",
"cache",
"[",
"id",
"]",
".",
"sync",
"=",
"sync",
"}",
"return",
"cache",
"[",
"id",
"]",
"}",
"return",
"{",
"cachedBacklinks",
":",
"cachedBacklinks",
"}",
"}"
] |
Creates a cache for backlinks observables by thread ID. The cache entry is an obserable
list of messages built from a backlinks stream. The cache is evicted if there are no
listeners for the given backlinks observable for the configured amount of time,
or a default of 5 seconds
|
[
"Creates",
"a",
"cache",
"for",
"backlinks",
"observables",
"by",
"thread",
"ID",
".",
"The",
"cache",
"entry",
"is",
"an",
"obserable",
"list",
"of",
"messages",
"built",
"from",
"a",
"backlinks",
"stream",
".",
"The",
"cache",
"is",
"evicted",
"if",
"there",
"are",
"no",
"listeners",
"for",
"the",
"given",
"backlinks",
"observable",
"for",
"the",
"configured",
"amount",
"of",
"time",
"or",
"a",
"default",
"of",
"5",
"seconds"
] |
d2f310a16a8a0b6fed80d8a4afa7cadb21610901
|
https://github.com/ssbc/patchcore/blob/d2f310a16a8a0b6fed80d8a4afa7cadb21610901/backlinks/obs-cache.js#L23-L98
|
train
|
scotthovestadt/schema-object
|
lib/schemaobject.js
|
getIndex
|
function getIndex(index) {
if (this[_privateKey]._options.keysIgnoreCase && typeof index === 'string') {
const indexLowerCase = index.toLowerCase();
for (const key in this[_privateKey]._schema) {
if (typeof key === 'string' && key.toLowerCase() === indexLowerCase) {
return key;
}
}
}
return index;
}
|
javascript
|
function getIndex(index) {
if (this[_privateKey]._options.keysIgnoreCase && typeof index === 'string') {
const indexLowerCase = index.toLowerCase();
for (const key in this[_privateKey]._schema) {
if (typeof key === 'string' && key.toLowerCase() === indexLowerCase) {
return key;
}
}
}
return index;
}
|
[
"function",
"getIndex",
"(",
"index",
")",
"{",
"if",
"(",
"this",
"[",
"_privateKey",
"]",
".",
"_options",
".",
"keysIgnoreCase",
"&&",
"typeof",
"index",
"===",
"'string'",
")",
"{",
"const",
"indexLowerCase",
"=",
"index",
".",
"toLowerCase",
"(",
")",
";",
"for",
"(",
"const",
"key",
"in",
"this",
"[",
"_privateKey",
"]",
".",
"_schema",
")",
"{",
"if",
"(",
"typeof",
"key",
"===",
"'string'",
"&&",
"key",
".",
"toLowerCase",
"(",
")",
"===",
"indexLowerCase",
")",
"{",
"return",
"key",
";",
"}",
"}",
"}",
"return",
"index",
";",
"}"
] |
Used to get real index name.
|
[
"Used",
"to",
"get",
"real",
"index",
"name",
"."
] |
4bc51c6dc7bd8082b2de28c609927dc1801733ca
|
https://github.com/scotthovestadt/schema-object/blob/4bc51c6dc7bd8082b2de28c609927dc1801733ca/lib/schemaobject.js#L38-L49
|
train
|
scotthovestadt/schema-object
|
lib/schemaobject.js
|
detectCustomErrorMessage
|
function detectCustomErrorMessage(key) {
if (typeof properties[key] === 'object' && properties[key].errorMessage && properties[key].value) {
return properties[key];
}
else if (_.isArray(properties[key])) {
return {
value: properties[key][0],
errorMessage: properties[key][1]
};
}
else {
return {
value: properties[key],
errorMessage: undefined
};
}
}
|
javascript
|
function detectCustomErrorMessage(key) {
if (typeof properties[key] === 'object' && properties[key].errorMessage && properties[key].value) {
return properties[key];
}
else if (_.isArray(properties[key])) {
return {
value: properties[key][0],
errorMessage: properties[key][1]
};
}
else {
return {
value: properties[key],
errorMessage: undefined
};
}
}
|
[
"function",
"detectCustomErrorMessage",
"(",
"key",
")",
"{",
"if",
"(",
"typeof",
"properties",
"[",
"key",
"]",
"===",
"'object'",
"&&",
"properties",
"[",
"key",
"]",
".",
"errorMessage",
"&&",
"properties",
"[",
"key",
"]",
".",
"value",
")",
"{",
"return",
"properties",
"[",
"key",
"]",
";",
"}",
"else",
"if",
"(",
"_",
".",
"isArray",
"(",
"properties",
"[",
"key",
"]",
")",
")",
"{",
"return",
"{",
"value",
":",
"properties",
"[",
"key",
"]",
"[",
"0",
"]",
",",
"errorMessage",
":",
"properties",
"[",
"key",
"]",
"[",
"1",
"]",
"}",
";",
"}",
"else",
"{",
"return",
"{",
"value",
":",
"properties",
"[",
"key",
"]",
",",
"errorMessage",
":",
"undefined",
"}",
";",
"}",
"}"
] |
Helper function designed to detect and handle usage of array-form custom error messages for validators
|
[
"Helper",
"function",
"designed",
"to",
"detect",
"and",
"handle",
"usage",
"of",
"array",
"-",
"form",
"custom",
"error",
"messages",
"for",
"validators"
] |
4bc51c6dc7bd8082b2de28c609927dc1801733ca
|
https://github.com/scotthovestadt/schema-object/blob/4bc51c6dc7bd8082b2de28c609927dc1801733ca/lib/schemaobject.js#L312-L328
|
train
|
scotthovestadt/schema-object
|
lib/schemaobject.js
|
addToSchema
|
function addToSchema(index, properties) {
this[_privateKey]._schema[index] = normalizeProperties.call(this, properties, index);
defineGetter.call(this[_privateKey]._getset, index, this[_privateKey]._schema[index]);
defineSetter.call(this[_privateKey]._getset, index, this[_privateKey]._schema[index]);
}
|
javascript
|
function addToSchema(index, properties) {
this[_privateKey]._schema[index] = normalizeProperties.call(this, properties, index);
defineGetter.call(this[_privateKey]._getset, index, this[_privateKey]._schema[index]);
defineSetter.call(this[_privateKey]._getset, index, this[_privateKey]._schema[index]);
}
|
[
"function",
"addToSchema",
"(",
"index",
",",
"properties",
")",
"{",
"this",
"[",
"_privateKey",
"]",
".",
"_schema",
"[",
"index",
"]",
"=",
"normalizeProperties",
".",
"call",
"(",
"this",
",",
"properties",
",",
"index",
")",
";",
"defineGetter",
".",
"call",
"(",
"this",
"[",
"_privateKey",
"]",
".",
"_getset",
",",
"index",
",",
"this",
"[",
"_privateKey",
"]",
".",
"_schema",
"[",
"index",
"]",
")",
";",
"defineSetter",
".",
"call",
"(",
"this",
"[",
"_privateKey",
"]",
".",
"_getset",
",",
"index",
",",
"this",
"[",
"_privateKey",
"]",
".",
"_schema",
"[",
"index",
"]",
")",
";",
"}"
] |
Add field to schema and initializes getter and setter for the field.
|
[
"Add",
"field",
"to",
"schema",
"and",
"initializes",
"getter",
"and",
"setter",
"for",
"the",
"field",
"."
] |
4bc51c6dc7bd8082b2de28c609927dc1801733ca
|
https://github.com/scotthovestadt/schema-object/blob/4bc51c6dc7bd8082b2de28c609927dc1801733ca/lib/schemaobject.js#L690-L695
|
train
|
scotthovestadt/schema-object
|
lib/schemaobject.js
|
defineGetter
|
function defineGetter(index, properties) {
// If the field type is an alias, we retrieve the value through the alias's index.
let indexOrAliasIndex = properties.type === 'alias' ? properties.index : index;
this.__defineGetter__(index, () => {
// If accessing object or array, lazy initialize if not set.
if (!this[_privateKey]._obj[indexOrAliasIndex] && (properties.type === 'object' || properties.type === 'array')) {
// Initialize object.
if (properties.type === 'object') {
if (properties.default !== undefined) {
writeValue.call(this[_privateKey]._this, _.isFunction(properties.default) ?
properties.default.call(this) :
properties.default, properties);
} else {
writeValue.call(this[_privateKey]._this,
properties.objectType ? new properties.objectType({}, this[_privateKey]._root) : {}, properties);
}
// Native arrays are not used so that Array class can be extended with custom behaviors.
} else if (properties.type === 'array') {
writeValue.call(this[_privateKey]._this, new SchemaArray(this, properties), properties);
}
}
try {
return getter.call(this, this[_privateKey]._obj[indexOrAliasIndex], properties);
} catch (error) {
// This typically happens when the default value isn't valid -- log error.
this[_privateKey]._errors.push(error);
}
});
}
|
javascript
|
function defineGetter(index, properties) {
// If the field type is an alias, we retrieve the value through the alias's index.
let indexOrAliasIndex = properties.type === 'alias' ? properties.index : index;
this.__defineGetter__(index, () => {
// If accessing object or array, lazy initialize if not set.
if (!this[_privateKey]._obj[indexOrAliasIndex] && (properties.type === 'object' || properties.type === 'array')) {
// Initialize object.
if (properties.type === 'object') {
if (properties.default !== undefined) {
writeValue.call(this[_privateKey]._this, _.isFunction(properties.default) ?
properties.default.call(this) :
properties.default, properties);
} else {
writeValue.call(this[_privateKey]._this,
properties.objectType ? new properties.objectType({}, this[_privateKey]._root) : {}, properties);
}
// Native arrays are not used so that Array class can be extended with custom behaviors.
} else if (properties.type === 'array') {
writeValue.call(this[_privateKey]._this, new SchemaArray(this, properties), properties);
}
}
try {
return getter.call(this, this[_privateKey]._obj[indexOrAliasIndex], properties);
} catch (error) {
// This typically happens when the default value isn't valid -- log error.
this[_privateKey]._errors.push(error);
}
});
}
|
[
"function",
"defineGetter",
"(",
"index",
",",
"properties",
")",
"{",
"let",
"indexOrAliasIndex",
"=",
"properties",
".",
"type",
"===",
"'alias'",
"?",
"properties",
".",
"index",
":",
"index",
";",
"this",
".",
"__defineGetter__",
"(",
"index",
",",
"(",
")",
"=>",
"{",
"if",
"(",
"!",
"this",
"[",
"_privateKey",
"]",
".",
"_obj",
"[",
"indexOrAliasIndex",
"]",
"&&",
"(",
"properties",
".",
"type",
"===",
"'object'",
"||",
"properties",
".",
"type",
"===",
"'array'",
")",
")",
"{",
"if",
"(",
"properties",
".",
"type",
"===",
"'object'",
")",
"{",
"if",
"(",
"properties",
".",
"default",
"!==",
"undefined",
")",
"{",
"writeValue",
".",
"call",
"(",
"this",
"[",
"_privateKey",
"]",
".",
"_this",
",",
"_",
".",
"isFunction",
"(",
"properties",
".",
"default",
")",
"?",
"properties",
".",
"default",
".",
"call",
"(",
"this",
")",
":",
"properties",
".",
"default",
",",
"properties",
")",
";",
"}",
"else",
"{",
"writeValue",
".",
"call",
"(",
"this",
"[",
"_privateKey",
"]",
".",
"_this",
",",
"properties",
".",
"objectType",
"?",
"new",
"properties",
".",
"objectType",
"(",
"{",
"}",
",",
"this",
"[",
"_privateKey",
"]",
".",
"_root",
")",
":",
"{",
"}",
",",
"properties",
")",
";",
"}",
"}",
"else",
"if",
"(",
"properties",
".",
"type",
"===",
"'array'",
")",
"{",
"writeValue",
".",
"call",
"(",
"this",
"[",
"_privateKey",
"]",
".",
"_this",
",",
"new",
"SchemaArray",
"(",
"this",
",",
"properties",
")",
",",
"properties",
")",
";",
"}",
"}",
"try",
"{",
"return",
"getter",
".",
"call",
"(",
"this",
",",
"this",
"[",
"_privateKey",
"]",
".",
"_obj",
"[",
"indexOrAliasIndex",
"]",
",",
"properties",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"this",
"[",
"_privateKey",
"]",
".",
"_errors",
".",
"push",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Defines getter for specific field.
|
[
"Defines",
"getter",
"for",
"specific",
"field",
"."
] |
4bc51c6dc7bd8082b2de28c609927dc1801733ca
|
https://github.com/scotthovestadt/schema-object/blob/4bc51c6dc7bd8082b2de28c609927dc1801733ca/lib/schemaobject.js#L698-L729
|
train
|
scotthovestadt/schema-object
|
lib/schemaobject.js
|
defineSetter
|
function defineSetter(index, properties) {
this.__defineSetter__(index, (value) => {
// Don't proceed if readOnly is true.
if (properties.readOnly) {
return;
}
try {
// this[_privateKey]._this[index] is used instead of this[_privateKey]._obj[index] to route through the public interface.
writeValue.call(this[_privateKey]._this,
typecast.call(this, value, this[_privateKey]._this[index], properties), properties);
} catch (error) {
// Setter failed to validate value -- log error.
this[_privateKey]._errors.push(error);
}
});
}
|
javascript
|
function defineSetter(index, properties) {
this.__defineSetter__(index, (value) => {
// Don't proceed if readOnly is true.
if (properties.readOnly) {
return;
}
try {
// this[_privateKey]._this[index] is used instead of this[_privateKey]._obj[index] to route through the public interface.
writeValue.call(this[_privateKey]._this,
typecast.call(this, value, this[_privateKey]._this[index], properties), properties);
} catch (error) {
// Setter failed to validate value -- log error.
this[_privateKey]._errors.push(error);
}
});
}
|
[
"function",
"defineSetter",
"(",
"index",
",",
"properties",
")",
"{",
"this",
".",
"__defineSetter__",
"(",
"index",
",",
"(",
"value",
")",
"=>",
"{",
"if",
"(",
"properties",
".",
"readOnly",
")",
"{",
"return",
";",
"}",
"try",
"{",
"writeValue",
".",
"call",
"(",
"this",
"[",
"_privateKey",
"]",
".",
"_this",
",",
"typecast",
".",
"call",
"(",
"this",
",",
"value",
",",
"this",
"[",
"_privateKey",
"]",
".",
"_this",
"[",
"index",
"]",
",",
"properties",
")",
",",
"properties",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"this",
"[",
"_privateKey",
"]",
".",
"_errors",
".",
"push",
"(",
"error",
")",
";",
"}",
"}",
")",
";",
"}"
] |
Defines setter for specific field.
|
[
"Defines",
"setter",
"for",
"specific",
"field",
"."
] |
4bc51c6dc7bd8082b2de28c609927dc1801733ca
|
https://github.com/scotthovestadt/schema-object/blob/4bc51c6dc7bd8082b2de28c609927dc1801733ca/lib/schemaobject.js#L732-L748
|
train
|
canjs/can-define
|
list/list.js
|
function(where, name) {
var orig = [][name];
DefineList.prototype[name] = function() {
if (!this._length) {
// For shift and pop, we just return undefined without
// triggering events.
return undefined;
}
var args = getArgs(arguments),
len = where && this._length ? this._length - 1 : 0,
oldLength = this._length ? this._length : 0,
res;
// Call the original method.
runningNative = true;
res = orig.apply(this, args);
runningNative = false;
// Create a change where the args are
// `len` - Where these items were removed.
// `remove` - Items removed.
// `undefined` - The new values (there are none).
// `res` - The old, removed values (should these be unbound).
queues.batch.start();
this._triggerChange("" + len, "remove", undefined, [ res ]);
this.dispatch('length', [ this._length, oldLength ]);
queues.batch.stop();
return res;
};
}
|
javascript
|
function(where, name) {
var orig = [][name];
DefineList.prototype[name] = function() {
if (!this._length) {
// For shift and pop, we just return undefined without
// triggering events.
return undefined;
}
var args = getArgs(arguments),
len = where && this._length ? this._length - 1 : 0,
oldLength = this._length ? this._length : 0,
res;
// Call the original method.
runningNative = true;
res = orig.apply(this, args);
runningNative = false;
// Create a change where the args are
// `len` - Where these items were removed.
// `remove` - Items removed.
// `undefined` - The new values (there are none).
// `res` - The old, removed values (should these be unbound).
queues.batch.start();
this._triggerChange("" + len, "remove", undefined, [ res ]);
this.dispatch('length', [ this._length, oldLength ]);
queues.batch.stop();
return res;
};
}
|
[
"function",
"(",
"where",
",",
"name",
")",
"{",
"var",
"orig",
"=",
"[",
"]",
"[",
"name",
"]",
";",
"DefineList",
".",
"prototype",
"[",
"name",
"]",
"=",
"function",
"(",
")",
"{",
"if",
"(",
"!",
"this",
".",
"_length",
")",
"{",
"return",
"undefined",
";",
"}",
"var",
"args",
"=",
"getArgs",
"(",
"arguments",
")",
",",
"len",
"=",
"where",
"&&",
"this",
".",
"_length",
"?",
"this",
".",
"_length",
"-",
"1",
":",
"0",
",",
"oldLength",
"=",
"this",
".",
"_length",
"?",
"this",
".",
"_length",
":",
"0",
",",
"res",
";",
"runningNative",
"=",
"true",
";",
"res",
"=",
"orig",
".",
"apply",
"(",
"this",
",",
"args",
")",
";",
"runningNative",
"=",
"false",
";",
"queues",
".",
"batch",
".",
"start",
"(",
")",
";",
"this",
".",
"_triggerChange",
"(",
"\"\"",
"+",
"len",
",",
"\"remove\"",
",",
"undefined",
",",
"[",
"res",
"]",
")",
";",
"this",
".",
"dispatch",
"(",
"'length'",
",",
"[",
"this",
".",
"_length",
",",
"oldLength",
"]",
")",
";",
"queues",
".",
"batch",
".",
"stop",
"(",
")",
";",
"return",
"res",
";",
"}",
";",
"}"
] |
Creates a `remove` type method
|
[
"Creates",
"a",
"remove",
"type",
"method"
] |
c3ea493a6a13587b679ac51077a8124c8c67280d
|
https://github.com/canjs/can-define/blob/c3ea493a6a13587b679ac51077a8124c8c67280d/list/list.js#L402-L433
|
train
|
|
canjs/can-define
|
list/list.js
|
function(key, handler, queue) {
var translationHandler;
if (isNaN(key)) {
return onKeyValue.apply(this, arguments);
}
else {
translationHandler = function() {
handler(this[key]);
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
Object.defineProperty(translationHandler, "name", {
value: "translationHandler(" + key + ")::" + canReflect.getName(this) + ".onKeyValue('length'," + canReflect.getName(handler) + ")",
});
}
//!steal-remove-end
singleReference.set(handler, this, translationHandler, key);
return onKeyValue.call(this, 'length', translationHandler, queue);
}
}
|
javascript
|
function(key, handler, queue) {
var translationHandler;
if (isNaN(key)) {
return onKeyValue.apply(this, arguments);
}
else {
translationHandler = function() {
handler(this[key]);
};
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
Object.defineProperty(translationHandler, "name", {
value: "translationHandler(" + key + ")::" + canReflect.getName(this) + ".onKeyValue('length'," + canReflect.getName(handler) + ")",
});
}
//!steal-remove-end
singleReference.set(handler, this, translationHandler, key);
return onKeyValue.call(this, 'length', translationHandler, queue);
}
}
|
[
"function",
"(",
"key",
",",
"handler",
",",
"queue",
")",
"{",
"var",
"translationHandler",
";",
"if",
"(",
"isNaN",
"(",
"key",
")",
")",
"{",
"return",
"onKeyValue",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"else",
"{",
"translationHandler",
"=",
"function",
"(",
")",
"{",
"handler",
"(",
"this",
"[",
"key",
"]",
")",
";",
"}",
";",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"translationHandler",
",",
"\"name\"",
",",
"{",
"value",
":",
"\"translationHandler(\"",
"+",
"key",
"+",
"\")::\"",
"+",
"canReflect",
".",
"getName",
"(",
"this",
")",
"+",
"\".onKeyValue('length',\"",
"+",
"canReflect",
".",
"getName",
"(",
"handler",
")",
"+",
"\")\"",
",",
"}",
")",
";",
"}",
"singleReference",
".",
"set",
"(",
"handler",
",",
"this",
",",
"translationHandler",
",",
"key",
")",
";",
"return",
"onKeyValue",
".",
"call",
"(",
"this",
",",
"'length'",
",",
"translationHandler",
",",
"queue",
")",
";",
"}",
"}"
] |
Called for every reference to a property in a template if a key is a numerical index then translate to length event
|
[
"Called",
"for",
"every",
"reference",
"to",
"a",
"property",
"in",
"a",
"template",
"if",
"a",
"key",
"is",
"a",
"numerical",
"index",
"then",
"translate",
"to",
"length",
"event"
] |
c3ea493a6a13587b679ac51077a8124c8c67280d
|
https://github.com/canjs/can-define/blob/c3ea493a6a13587b679ac51077a8124c8c67280d/list/list.js#L654-L673
|
train
|
|
canjs/can-define
|
list/list.js
|
function(key, handler, queue) {
var translationHandler;
if ( isNaN(key)) {
return offKeyValue.apply(this, arguments);
}
else {
translationHandler = singleReference.getAndDelete(handler, this, key);
return offKeyValue.call(this, 'length', translationHandler, queue);
}
}
|
javascript
|
function(key, handler, queue) {
var translationHandler;
if ( isNaN(key)) {
return offKeyValue.apply(this, arguments);
}
else {
translationHandler = singleReference.getAndDelete(handler, this, key);
return offKeyValue.call(this, 'length', translationHandler, queue);
}
}
|
[
"function",
"(",
"key",
",",
"handler",
",",
"queue",
")",
"{",
"var",
"translationHandler",
";",
"if",
"(",
"isNaN",
"(",
"key",
")",
")",
"{",
"return",
"offKeyValue",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
";",
"}",
"else",
"{",
"translationHandler",
"=",
"singleReference",
".",
"getAndDelete",
"(",
"handler",
",",
"this",
",",
"key",
")",
";",
"return",
"offKeyValue",
".",
"call",
"(",
"this",
",",
"'length'",
",",
"translationHandler",
",",
"queue",
")",
";",
"}",
"}"
] |
Called when a property reference is removed
|
[
"Called",
"when",
"a",
"property",
"reference",
"is",
"removed"
] |
c3ea493a6a13587b679ac51077a8124c8c67280d
|
https://github.com/canjs/can-define/blob/c3ea493a6a13587b679ac51077a8124c8c67280d/list/list.js#L675-L684
|
train
|
|
canjs/can-define
|
can-define.js
|
function(prop, get, defaultValueFn) {
return function() {
var map = this,
defaultValue = defaultValueFn && defaultValueFn.call(this),
observable, computeObj;
if(get.length === 0) {
observable = new Observation(get, map);
} else if(get.length === 1) {
observable = new SettableObservable(get, map, defaultValue);
} else {
observable = new AsyncObservable(get, map, defaultValue);
}
computeObj = make.computeObj(map, prop, observable);
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
Object.defineProperty(computeObj.handler, "name", {
value: canReflect.getName(get).replace('getter', 'event emitter')
});
}
//!steal-remove-end
return computeObj;
};
}
|
javascript
|
function(prop, get, defaultValueFn) {
return function() {
var map = this,
defaultValue = defaultValueFn && defaultValueFn.call(this),
observable, computeObj;
if(get.length === 0) {
observable = new Observation(get, map);
} else if(get.length === 1) {
observable = new SettableObservable(get, map, defaultValue);
} else {
observable = new AsyncObservable(get, map, defaultValue);
}
computeObj = make.computeObj(map, prop, observable);
//!steal-remove-start
if(process.env.NODE_ENV !== 'production') {
Object.defineProperty(computeObj.handler, "name", {
value: canReflect.getName(get).replace('getter', 'event emitter')
});
}
//!steal-remove-end
return computeObj;
};
}
|
[
"function",
"(",
"prop",
",",
"get",
",",
"defaultValueFn",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"map",
"=",
"this",
",",
"defaultValue",
"=",
"defaultValueFn",
"&&",
"defaultValueFn",
".",
"call",
"(",
"this",
")",
",",
"observable",
",",
"computeObj",
";",
"if",
"(",
"get",
".",
"length",
"===",
"0",
")",
"{",
"observable",
"=",
"new",
"Observation",
"(",
"get",
",",
"map",
")",
";",
"}",
"else",
"if",
"(",
"get",
".",
"length",
"===",
"1",
")",
"{",
"observable",
"=",
"new",
"SettableObservable",
"(",
"get",
",",
"map",
",",
"defaultValue",
")",
";",
"}",
"else",
"{",
"observable",
"=",
"new",
"AsyncObservable",
"(",
"get",
",",
"map",
",",
"defaultValue",
")",
";",
"}",
"computeObj",
"=",
"make",
".",
"computeObj",
"(",
"map",
",",
"prop",
",",
"observable",
")",
";",
"if",
"(",
"process",
".",
"env",
".",
"NODE_ENV",
"!==",
"'production'",
")",
"{",
"Object",
".",
"defineProperty",
"(",
"computeObj",
".",
"handler",
",",
"\"name\"",
",",
"{",
"value",
":",
"canReflect",
".",
"getName",
"(",
"get",
")",
".",
"replace",
"(",
"'getter'",
",",
"'event emitter'",
")",
"}",
")",
";",
"}",
"return",
"computeObj",
";",
"}",
";",
"}"
] |
Returns a function that creates the `_computed` prop.
|
[
"Returns",
"a",
"function",
"that",
"creates",
"the",
"_computed",
"prop",
"."
] |
c3ea493a6a13587b679ac51077a8124c8c67280d
|
https://github.com/canjs/can-define/blob/c3ea493a6a13587b679ac51077a8124c8c67280d/can-define.js#L467-L494
|
train
|
|
canjs/can-define
|
can-define.js
|
function(definition, behavior, value) {
if(behavior === "enumerable") {
// treat enumerable like serialize
definition.serialize = !!value;
}
else if(behavior === "type") {
var behaviorDef = value;
if(typeof behaviorDef === "string") {
behaviorDef = define.types[behaviorDef];
if(typeof behaviorDef === "object" && !isDefineType(behaviorDef)) {
assign(definition, behaviorDef);
behaviorDef = behaviorDef[behavior];
}
}
if (typeof behaviorDef !== 'undefined') {
definition[behavior] = behaviorDef;
}
}
else {
definition[behavior] = value;
}
}
|
javascript
|
function(definition, behavior, value) {
if(behavior === "enumerable") {
// treat enumerable like serialize
definition.serialize = !!value;
}
else if(behavior === "type") {
var behaviorDef = value;
if(typeof behaviorDef === "string") {
behaviorDef = define.types[behaviorDef];
if(typeof behaviorDef === "object" && !isDefineType(behaviorDef)) {
assign(definition, behaviorDef);
behaviorDef = behaviorDef[behavior];
}
}
if (typeof behaviorDef !== 'undefined') {
definition[behavior] = behaviorDef;
}
}
else {
definition[behavior] = value;
}
}
|
[
"function",
"(",
"definition",
",",
"behavior",
",",
"value",
")",
"{",
"if",
"(",
"behavior",
"===",
"\"enumerable\"",
")",
"{",
"definition",
".",
"serialize",
"=",
"!",
"!",
"value",
";",
"}",
"else",
"if",
"(",
"behavior",
"===",
"\"type\"",
")",
"{",
"var",
"behaviorDef",
"=",
"value",
";",
"if",
"(",
"typeof",
"behaviorDef",
"===",
"\"string\"",
")",
"{",
"behaviorDef",
"=",
"define",
".",
"types",
"[",
"behaviorDef",
"]",
";",
"if",
"(",
"typeof",
"behaviorDef",
"===",
"\"object\"",
"&&",
"!",
"isDefineType",
"(",
"behaviorDef",
")",
")",
"{",
"assign",
"(",
"definition",
",",
"behaviorDef",
")",
";",
"behaviorDef",
"=",
"behaviorDef",
"[",
"behavior",
"]",
";",
"}",
"}",
"if",
"(",
"typeof",
"behaviorDef",
"!==",
"'undefined'",
")",
"{",
"definition",
"[",
"behavior",
"]",
"=",
"behaviorDef",
";",
"}",
"}",
"else",
"{",
"definition",
"[",
"behavior",
"]",
"=",
"value",
";",
"}",
"}"
] |
This cleans up a particular behavior and adds it to the definition
|
[
"This",
"cleans",
"up",
"a",
"particular",
"behavior",
"and",
"adds",
"it",
"to",
"the",
"definition"
] |
c3ea493a6a13587b679ac51077a8124c8c67280d
|
https://github.com/canjs/can-define/blob/c3ea493a6a13587b679ac51077a8124c8c67280d/can-define.js#L790-L811
|
train
|
|
plugCubed/plugAPI
|
lib/bufferObject.js
|
BufferObject
|
function BufferObject(data, getUpdate, maxAge) {
if (!Object.is(typeof getUpdate, 'function')) {
throw new Error('BufferObject requires an update function');
}
maxAge = maxAge || 6e4;
return {
lastUpdate: data ? Date.now() : 0,
data: data || null,
set(setData) {
this.data = setData;
this.lastUpdate = Date.now();
},
get(callback) {
if (this.data != null) {
if (maxAge < 0 || this.lastUpdate >= Date.now() - maxAge) {
if (Object.is(typeof callback, 'function')) {
return callback(this.data);
}
return this.data;
}
}
const that = this;
getUpdate(function(err, updateData) {
if (err) {
that.get();
return;
}
that.set(updateData);
if (Object.is(typeof callback, 'function')) {
return callback(updateData);
}
return updateData;
});
},
push(pushData) {
// Be sure the data is loaded
this.get();
if (Array.isArray(this.data)) {
this.data.push(pushData);
}
},
remove(removeData) {
this.get();
for (const i in this.data) {
if (!this.data.hasOwnProperty(i)) continue;
if (Object.is(this.data[i], removeData)) {
this.data.splice(i, 1);
return;
}
}
},
removeAt(index) {
// Be sure the data is loaded
this.get();
if (Array.isArray(this.data) && index < this.data.length) {
this.data.splice(index, 1);
}
}
};
}
|
javascript
|
function BufferObject(data, getUpdate, maxAge) {
if (!Object.is(typeof getUpdate, 'function')) {
throw new Error('BufferObject requires an update function');
}
maxAge = maxAge || 6e4;
return {
lastUpdate: data ? Date.now() : 0,
data: data || null,
set(setData) {
this.data = setData;
this.lastUpdate = Date.now();
},
get(callback) {
if (this.data != null) {
if (maxAge < 0 || this.lastUpdate >= Date.now() - maxAge) {
if (Object.is(typeof callback, 'function')) {
return callback(this.data);
}
return this.data;
}
}
const that = this;
getUpdate(function(err, updateData) {
if (err) {
that.get();
return;
}
that.set(updateData);
if (Object.is(typeof callback, 'function')) {
return callback(updateData);
}
return updateData;
});
},
push(pushData) {
// Be sure the data is loaded
this.get();
if (Array.isArray(this.data)) {
this.data.push(pushData);
}
},
remove(removeData) {
this.get();
for (const i in this.data) {
if (!this.data.hasOwnProperty(i)) continue;
if (Object.is(this.data[i], removeData)) {
this.data.splice(i, 1);
return;
}
}
},
removeAt(index) {
// Be sure the data is loaded
this.get();
if (Array.isArray(this.data) && index < this.data.length) {
this.data.splice(index, 1);
}
}
};
}
|
[
"function",
"BufferObject",
"(",
"data",
",",
"getUpdate",
",",
"maxAge",
")",
"{",
"if",
"(",
"!",
"Object",
".",
"is",
"(",
"typeof",
"getUpdate",
",",
"'function'",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'BufferObject requires an update function'",
")",
";",
"}",
"maxAge",
"=",
"maxAge",
"||",
"6e4",
";",
"return",
"{",
"lastUpdate",
":",
"data",
"?",
"Date",
".",
"now",
"(",
")",
":",
"0",
",",
"data",
":",
"data",
"||",
"null",
",",
"set",
"(",
"setData",
")",
"{",
"this",
".",
"data",
"=",
"setData",
";",
"this",
".",
"lastUpdate",
"=",
"Date",
".",
"now",
"(",
")",
";",
"}",
",",
"get",
"(",
"callback",
")",
"{",
"if",
"(",
"this",
".",
"data",
"!=",
"null",
")",
"{",
"if",
"(",
"maxAge",
"<",
"0",
"||",
"this",
".",
"lastUpdate",
">=",
"Date",
".",
"now",
"(",
")",
"-",
"maxAge",
")",
"{",
"if",
"(",
"Object",
".",
"is",
"(",
"typeof",
"callback",
",",
"'function'",
")",
")",
"{",
"return",
"callback",
"(",
"this",
".",
"data",
")",
";",
"}",
"return",
"this",
".",
"data",
";",
"}",
"}",
"const",
"that",
"=",
"this",
";",
"getUpdate",
"(",
"function",
"(",
"err",
",",
"updateData",
")",
"{",
"if",
"(",
"err",
")",
"{",
"that",
".",
"get",
"(",
")",
";",
"return",
";",
"}",
"that",
".",
"set",
"(",
"updateData",
")",
";",
"if",
"(",
"Object",
".",
"is",
"(",
"typeof",
"callback",
",",
"'function'",
")",
")",
"{",
"return",
"callback",
"(",
"updateData",
")",
";",
"}",
"return",
"updateData",
";",
"}",
")",
";",
"}",
",",
"push",
"(",
"pushData",
")",
"{",
"this",
".",
"get",
"(",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"this",
".",
"data",
")",
")",
"{",
"this",
".",
"data",
".",
"push",
"(",
"pushData",
")",
";",
"}",
"}",
",",
"remove",
"(",
"removeData",
")",
"{",
"this",
".",
"get",
"(",
")",
";",
"for",
"(",
"const",
"i",
"in",
"this",
".",
"data",
")",
"{",
"if",
"(",
"!",
"this",
".",
"data",
".",
"hasOwnProperty",
"(",
"i",
")",
")",
"continue",
";",
"if",
"(",
"Object",
".",
"is",
"(",
"this",
".",
"data",
"[",
"i",
"]",
",",
"removeData",
")",
")",
"{",
"this",
".",
"data",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"return",
";",
"}",
"}",
"}",
",",
"removeAt",
"(",
"index",
")",
"{",
"this",
".",
"get",
"(",
")",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"this",
".",
"data",
")",
"&&",
"index",
"<",
"this",
".",
"data",
".",
"length",
")",
"{",
"this",
".",
"data",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"}",
"}",
";",
"}"
] |
A buffer to cache data
@method BufferObject
@param {Object} data The data to cache.
@param {Function} getUpdate Function that is called when data needs to be updated.
@param {Number} maxAge the maximum age that items will be stored for.
@returns {Object} Returns an object of functions and the data that is stored.
@private
|
[
"A",
"buffer",
"to",
"cache",
"data"
] |
8af3f673ee5526b4e0f4c03476d7e2207563cbda
|
https://github.com/plugCubed/plugAPI/blob/8af3f673ee5526b4e0f4c03476d7e2207563cbda/lib/bufferObject.js#L12-L84
|
train
|
infinispan/js-client
|
lib/infinispan.js
|
function() {
var ctx = u.context(SMALL);
logger.debugf('Invoke iterator.close(msgId=%d,iteratorId=%s) on %s', ctx.id, iterId, conn.toString());
return futurePinned(
ctx, 0x35, p.encodeIterId(iterId), p.complete(p.hasSuccess), conn);
}
|
javascript
|
function() {
var ctx = u.context(SMALL);
logger.debugf('Invoke iterator.close(msgId=%d,iteratorId=%s) on %s', ctx.id, iterId, conn.toString());
return futurePinned(
ctx, 0x35, p.encodeIterId(iterId), p.complete(p.hasSuccess), conn);
}
|
[
"function",
"(",
")",
"{",
"var",
"ctx",
"=",
"u",
".",
"context",
"(",
"SMALL",
")",
";",
"logger",
".",
"debugf",
"(",
"'Invoke iterator.close(msgId=%d,iteratorId=%s) on %s'",
",",
"ctx",
".",
"id",
",",
"iterId",
",",
"conn",
".",
"toString",
"(",
")",
")",
";",
"return",
"futurePinned",
"(",
"ctx",
",",
"0x35",
",",
"p",
".",
"encodeIterId",
"(",
"iterId",
")",
",",
"p",
".",
"complete",
"(",
"p",
".",
"hasSuccess",
")",
",",
"conn",
")",
";",
"}"
] |
Close the iteration.
@returns {module:promise.Promise}
A Promise which will be completed once the iteration has been closed.
@memberof Iterator#
@since 0.3
|
[
"Close",
"the",
"iteration",
"."
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/infinispan.js#L174-L179
|
train
|
|
infinispan/js-client
|
lib/infinispan.js
|
function(k) {
var ctx = u.context(SMALL);
logger.debugf('Invoke containsKey(msgId=%d,key=%s)', ctx.id, u.str(k));
return futureKey(ctx, 0x0F, k, p.encodeKey(k), p.complete(p.hasSuccess));
}
|
javascript
|
function(k) {
var ctx = u.context(SMALL);
logger.debugf('Invoke containsKey(msgId=%d,key=%s)', ctx.id, u.str(k));
return futureKey(ctx, 0x0F, k, p.encodeKey(k), p.complete(p.hasSuccess));
}
|
[
"function",
"(",
"k",
")",
"{",
"var",
"ctx",
"=",
"u",
".",
"context",
"(",
"SMALL",
")",
";",
"logger",
".",
"debugf",
"(",
"'Invoke containsKey(msgId=%d,key=%s)'",
",",
"ctx",
".",
"id",
",",
"u",
".",
"str",
"(",
"k",
")",
")",
";",
"return",
"futureKey",
"(",
"ctx",
",",
"0x0F",
",",
"k",
",",
"p",
".",
"encodeKey",
"(",
"k",
")",
",",
"p",
".",
"complete",
"(",
"p",
".",
"hasSuccess",
")",
")",
";",
"}"
] |
Check whether the given key is present.
@param k {(String|Object)} Key to check for presence.
@returns {module:promise.Promise.<boolean>}
A promise that will be completed with true if there is a value
associated with the key, or false otherwise.
@memberof Client#
@since 0.3
|
[
"Check",
"whether",
"the",
"given",
"key",
"is",
"present",
"."
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/infinispan.js#L271-L275
|
train
|
|
infinispan/js-client
|
lib/infinispan.js
|
function(k) {
var ctx = u.context(SMALL);
logger.debugf('Invoke getWithMetadata(msgId=%d,key=%s)', ctx.id, u.str(k));
var decoder = p.decodeWithMeta();
return futureKey(ctx, 0x1B, k, p.encodeKey(k), decoder);
}
|
javascript
|
function(k) {
var ctx = u.context(SMALL);
logger.debugf('Invoke getWithMetadata(msgId=%d,key=%s)', ctx.id, u.str(k));
var decoder = p.decodeWithMeta();
return futureKey(ctx, 0x1B, k, p.encodeKey(k), decoder);
}
|
[
"function",
"(",
"k",
")",
"{",
"var",
"ctx",
"=",
"u",
".",
"context",
"(",
"SMALL",
")",
";",
"logger",
".",
"debugf",
"(",
"'Invoke getWithMetadata(msgId=%d,key=%s)'",
",",
"ctx",
".",
"id",
",",
"u",
".",
"str",
"(",
"k",
")",
")",
";",
"var",
"decoder",
"=",
"p",
".",
"decodeWithMeta",
"(",
")",
";",
"return",
"futureKey",
"(",
"ctx",
",",
"0x1B",
",",
"k",
",",
"p",
".",
"encodeKey",
"(",
"k",
")",
",",
"decoder",
")",
";",
"}"
] |
Metadata value.
@typedef {Object} MetadataValue
@property {(String|Object)} value - Value associated with the key
@property {Buffer} version - Version of the value as a byte buffer.
@property {Number} lifespan - Lifespan of entry, defined in seconds.
If the entry is immortal, it would be -1.
@property {Number} maxIdle - Max idle time of entry, defined in seconds.
If the entry is no transient, it would be -1.
@since 0.3
Get the value and metadata associated with the given key parameter.
@param k {(String|Object)} Key to retrieve.
@returns {module:promise.Promise.<?MetadataValue>}
A promise that will be completed with the value and metadata
associated with the key, or undefined if the value is not present.
@memberof Client#
@since 0.3
|
[
"Metadata",
"value",
"."
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/infinispan.js#L298-L303
|
train
|
|
infinispan/js-client
|
lib/infinispan.js
|
function(k, opts) {
var ctx = u.context(SMALL);
logger.debugl(function() {return ['Invoke remove(msgId=%d,key=%s,opts=%s)',
ctx.id, u.str(k), JSON.stringify(opts)]; });
var decoder = p.decodePrevOrElse(opts, p.hasSuccess, p.complete(p.hasSuccess));
return futureKey(ctx, 0x0B, k, p.encodeKey(k), decoder, opts);
}
|
javascript
|
function(k, opts) {
var ctx = u.context(SMALL);
logger.debugl(function() {return ['Invoke remove(msgId=%d,key=%s,opts=%s)',
ctx.id, u.str(k), JSON.stringify(opts)]; });
var decoder = p.decodePrevOrElse(opts, p.hasSuccess, p.complete(p.hasSuccess));
return futureKey(ctx, 0x0B, k, p.encodeKey(k), decoder, opts);
}
|
[
"function",
"(",
"k",
",",
"opts",
")",
"{",
"var",
"ctx",
"=",
"u",
".",
"context",
"(",
"SMALL",
")",
";",
"logger",
".",
"debugl",
"(",
"function",
"(",
")",
"{",
"return",
"[",
"'Invoke remove(msgId=%d,key=%s,opts=%s)'",
",",
"ctx",
".",
"id",
",",
"u",
".",
"str",
"(",
"k",
")",
",",
"JSON",
".",
"stringify",
"(",
"opts",
")",
"]",
";",
"}",
")",
";",
"var",
"decoder",
"=",
"p",
".",
"decodePrevOrElse",
"(",
"opts",
",",
"p",
".",
"hasSuccess",
",",
"p",
".",
"complete",
"(",
"p",
".",
"hasSuccess",
")",
")",
";",
"return",
"futureKey",
"(",
"ctx",
",",
"0x0B",
",",
"k",
",",
"p",
".",
"encodeKey",
"(",
"k",
")",
",",
"decoder",
",",
"opts",
")",
";",
"}"
] |
Remove options defines a set of optional parameters that can be
passed when removing data.
@typedef {Object} RemoveOptions
@property {Boolean} previous - Indicates whether previous value
should be returned. If no previous value exists, it would return
undefined.
@since 0.3
Removes the mapping for a key if it is present.
@param k {(String|Object)} Key whose mapping is to be removed.
@param opts {?RemoveOptions} Optional remove options.
@returns {module:promise.Promise.<(Boolean|String|Object)>}
A promise that will be completed with true if the mapping was removed,
or false if the key did not exist.
If the 'previous' option is enabled, it returns the value
before removal or undefined if the key did not exist.
@memberof Client#
@since 0.3
|
[
"Remove",
"options",
"defines",
"a",
"set",
"of",
"optional",
"parameters",
"that",
"can",
"be",
"passed",
"when",
"removing",
"data",
"."
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/infinispan.js#L372-L378
|
train
|
|
infinispan/js-client
|
lib/infinispan.js
|
function(k, v, version, opts) {
var ctx = u.context(MEDIUM);
logger.debugl(function() { return ['Invoke replaceWithVersion(msgId=%d,key=%s,value=%s,version=0x%s,opts=%s)',
ctx.id, u.str(k), u.str(v), version.toString('hex'), JSON.stringify(opts)]; });
var decoder = p.decodePrevOrElse(opts, p.hasPrevious, p.complete(p.hasSuccess));
return futureKey(ctx, 0x09, k, p.encodeKeyValueVersion(k, v, version), decoder, opts);
}
|
javascript
|
function(k, v, version, opts) {
var ctx = u.context(MEDIUM);
logger.debugl(function() { return ['Invoke replaceWithVersion(msgId=%d,key=%s,value=%s,version=0x%s,opts=%s)',
ctx.id, u.str(k), u.str(v), version.toString('hex'), JSON.stringify(opts)]; });
var decoder = p.decodePrevOrElse(opts, p.hasPrevious, p.complete(p.hasSuccess));
return futureKey(ctx, 0x09, k, p.encodeKeyValueVersion(k, v, version), decoder, opts);
}
|
[
"function",
"(",
"k",
",",
"v",
",",
"version",
",",
"opts",
")",
"{",
"var",
"ctx",
"=",
"u",
".",
"context",
"(",
"MEDIUM",
")",
";",
"logger",
".",
"debugl",
"(",
"function",
"(",
")",
"{",
"return",
"[",
"'Invoke replaceWithVersion(msgId=%d,key=%s,value=%s,version=0x%s,opts=%s)'",
",",
"ctx",
".",
"id",
",",
"u",
".",
"str",
"(",
"k",
")",
",",
"u",
".",
"str",
"(",
"v",
")",
",",
"version",
".",
"toString",
"(",
"'hex'",
")",
",",
"JSON",
".",
"stringify",
"(",
"opts",
")",
"]",
";",
"}",
")",
";",
"var",
"decoder",
"=",
"p",
".",
"decodePrevOrElse",
"(",
"opts",
",",
"p",
".",
"hasPrevious",
",",
"p",
".",
"complete",
"(",
"p",
".",
"hasSuccess",
")",
")",
";",
"return",
"futureKey",
"(",
"ctx",
",",
"0x09",
",",
"k",
",",
"p",
".",
"encodeKeyValueVersion",
"(",
"k",
",",
"v",
",",
"version",
")",
",",
"decoder",
",",
"opts",
")",
";",
"}"
] |
Replaces the given value only if its version matches the supplied
version.
@param k {(String|Object)} Key with which the specified value is associated.
@param v {(String|Object)} Value expected to be associated with the specified key.
@param version {Buffer} binary buffer version that should match the
one in the server for the operation to succeed. Version information
can be retrieved with getWithMetadata method.
@param opts {?StoreOptions} Optional store options.
@returns {module:promise.Promise.<(Boolean|String|Object)>}
A promise that will be completed with true if the version matches
and the mapping was replaced, otherwise it returns false if not
replaced because key does not exist or version sent does not match
server-side version.
If the 'previous' option is enabled, it returns the value that was
replaced if the version matches. If the version does not match, the
current value is returned. Fianlly if the key did not exist it
returns undefined.
@memberof Client#
@since 0.3
|
[
"Replaces",
"the",
"given",
"value",
"only",
"if",
"its",
"version",
"matches",
"the",
"supplied",
"version",
"."
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/infinispan.js#L445-L451
|
train
|
|
infinispan/js-client
|
lib/infinispan.js
|
function(pairs, opts) {
var ctx = u.context(BIG);
logger.debugl(function() { return ['Invoke putAll(msgId=%d,pairs=%s,opts=%s)',
ctx.id, JSON.stringify(pairs), JSON.stringify(opts)]; });
return future(ctx, 0x2D, p.encodeMultiKeyValue(pairs), p.complete(_.constant(undefined)), opts);
}
|
javascript
|
function(pairs, opts) {
var ctx = u.context(BIG);
logger.debugl(function() { return ['Invoke putAll(msgId=%d,pairs=%s,opts=%s)',
ctx.id, JSON.stringify(pairs), JSON.stringify(opts)]; });
return future(ctx, 0x2D, p.encodeMultiKeyValue(pairs), p.complete(_.constant(undefined)), opts);
}
|
[
"function",
"(",
"pairs",
",",
"opts",
")",
"{",
"var",
"ctx",
"=",
"u",
".",
"context",
"(",
"BIG",
")",
";",
"logger",
".",
"debugl",
"(",
"function",
"(",
")",
"{",
"return",
"[",
"'Invoke putAll(msgId=%d,pairs=%s,opts=%s)'",
",",
"ctx",
".",
"id",
",",
"JSON",
".",
"stringify",
"(",
"pairs",
")",
",",
"JSON",
".",
"stringify",
"(",
"opts",
")",
"]",
";",
"}",
")",
";",
"return",
"future",
"(",
"ctx",
",",
"0x2D",
",",
"p",
".",
"encodeMultiKeyValue",
"(",
"pairs",
")",
",",
"p",
".",
"complete",
"(",
"_",
".",
"constant",
"(",
"undefined",
")",
")",
",",
"opts",
")",
";",
"}"
] |
Multi store options defines a set of optional parameters that can be
passed when storing multiple entries.
@typedef {Object} MultiStoreOptions
@property {DurationUnit} lifespan -
Lifespan for the stored entry.
@property {DurationUnit} maxIdle -
Max idle time for the stored entry.
@since 0.3
Stores all of the mappings from the specified entry array.
@param pairs {Entry[]} key/value pair mappings to be stored
@param opts {MultiStoreOptions}
Optional storage options to apply to all entries.
@returns {module:promise.Promise}
A promise that will be completed when all entries have been stored.
@memberof Client#
@since 0.3
|
[
"Multi",
"store",
"options",
"defines",
"a",
"set",
"of",
"optional",
"parameters",
"that",
"can",
"be",
"passed",
"when",
"storing",
"multiple",
"entries",
"."
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/infinispan.js#L527-L532
|
train
|
|
infinispan/js-client
|
lib/infinispan.js
|
function(batchSize, opts) {
var ctx = u.context(SMALL);
logger.debugf('Invoke iterator(msgId=%d,batchSize=%d,opts=%s)', ctx.id, batchSize, u.str(opts));
var remote = future(ctx, 0x31, p.encodeIterStart(batchSize, opts), p.decodeIterId);
return remote.then(function(result) {
return iterator(result.iterId, result.conn);
});
}
|
javascript
|
function(batchSize, opts) {
var ctx = u.context(SMALL);
logger.debugf('Invoke iterator(msgId=%d,batchSize=%d,opts=%s)', ctx.id, batchSize, u.str(opts));
var remote = future(ctx, 0x31, p.encodeIterStart(batchSize, opts), p.decodeIterId);
return remote.then(function(result) {
return iterator(result.iterId, result.conn);
});
}
|
[
"function",
"(",
"batchSize",
",",
"opts",
")",
"{",
"var",
"ctx",
"=",
"u",
".",
"context",
"(",
"SMALL",
")",
";",
"logger",
".",
"debugf",
"(",
"'Invoke iterator(msgId=%d,batchSize=%d,opts=%s)'",
",",
"ctx",
".",
"id",
",",
"batchSize",
",",
"u",
".",
"str",
"(",
"opts",
")",
")",
";",
"var",
"remote",
"=",
"future",
"(",
"ctx",
",",
"0x31",
",",
"p",
".",
"encodeIterStart",
"(",
"batchSize",
",",
"opts",
")",
",",
"p",
".",
"decodeIterId",
")",
";",
"return",
"remote",
".",
"then",
"(",
"function",
"(",
"result",
")",
"{",
"return",
"iterator",
"(",
"result",
".",
"iterId",
",",
"result",
".",
"conn",
")",
";",
"}",
")",
";",
"}"
] |
Iterator options defines a set of optional parameters that
control how iteration occurs and the data that's iterated over.
@typedef {Object} IteratorOptions
@property {Boolean} metadata - Indicates whether entries iterated
over also expose metadata information. This option is false by
default which means no metadata information is exposed on iteration.
@since 0.3
Iterate over the entries stored in server(s).
@param batchSize {Number}
The number of entries transferred from the server at a time.
@param opts {?IteratorOptions} Optional iteration settings.
@return {module:promise.Promise.<Iterator>}
A promise that will be completed with an iterator that can be used
to retrieve stored elements.
@memberof Client#
@since 0.3
|
[
"Iterator",
"options",
"defines",
"a",
"set",
"of",
"optional",
"parameters",
"that",
"control",
"how",
"iteration",
"occurs",
"and",
"the",
"data",
"that",
"s",
"iterated",
"over",
"."
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/infinispan.js#L555-L562
|
train
|
|
infinispan/js-client
|
lib/infinispan.js
|
function(event, listener, opts) {
var ctx = u.context(SMALL);
return _.has(opts, 'listenerId')
? addLocalListener(ctx, event, listener, opts)
: addRemoteListener(ctx, event, listener, opts);
}
|
javascript
|
function(event, listener, opts) {
var ctx = u.context(SMALL);
return _.has(opts, 'listenerId')
? addLocalListener(ctx, event, listener, opts)
: addRemoteListener(ctx, event, listener, opts);
}
|
[
"function",
"(",
"event",
",",
"listener",
",",
"opts",
")",
"{",
"var",
"ctx",
"=",
"u",
".",
"context",
"(",
"SMALL",
")",
";",
"return",
"_",
".",
"has",
"(",
"opts",
",",
"'listenerId'",
")",
"?",
"addLocalListener",
"(",
"ctx",
",",
"event",
",",
"listener",
",",
"opts",
")",
":",
"addRemoteListener",
"(",
"ctx",
",",
"event",
",",
"listener",
",",
"opts",
")",
";",
"}"
] |
Listener options.
@typedef {Object} ListenOptions
@property {String} listenerId - Listener identifier can be passed
in as parameter to register multiple event callback functions for
the same listener.
@since 0.3
Add an event listener.
@param {String} event
Event to add listener to. Possible values are:
'create', 'modify', 'remove' and 'expiry'.
@param {Function} listener
Function to invoke when the listener event is received.
'create' and 'modify' events callback the function with key,
entry version and listener id.
'remove' and 'expiry' events callback the function with key
and listener id.
@param opts {?ListenOptions} Options for adding listener.
@returns {module:promise.Promise<String>}
A promise that will be completed with the identifier of the listener.
This identifier can be used to register multiple callbacks with the
same listener, or to remove the listener.
@memberof Client#
@since 0.3
|
[
"Listener",
"options",
"."
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/infinispan.js#L657-L662
|
train
|
|
infinispan/js-client
|
lib/infinispan.js
|
function(listenerId) {
var ctx = u.context(SMALL);
logger.debugf('Invoke removeListener(msgId=%d,listenerId=%s) remotely', ctx.id, listenerId);
var conn = p.findConnectionListener(listenerId);
if (!f.existy(conn))
return Promise.reject(
new Error('No server connection for listener (listenerId=' + listenerId + ')'));
var remote = futurePinned(ctx, 0x27, p.encodeListenerId(listenerId), p.complete(p.hasSuccess), conn);
return remote.then(function (success) {
if (success) {
p.removeListeners(listenerId);
return true;
}
return false;
})
}
|
javascript
|
function(listenerId) {
var ctx = u.context(SMALL);
logger.debugf('Invoke removeListener(msgId=%d,listenerId=%s) remotely', ctx.id, listenerId);
var conn = p.findConnectionListener(listenerId);
if (!f.existy(conn))
return Promise.reject(
new Error('No server connection for listener (listenerId=' + listenerId + ')'));
var remote = futurePinned(ctx, 0x27, p.encodeListenerId(listenerId), p.complete(p.hasSuccess), conn);
return remote.then(function (success) {
if (success) {
p.removeListeners(listenerId);
return true;
}
return false;
})
}
|
[
"function",
"(",
"listenerId",
")",
"{",
"var",
"ctx",
"=",
"u",
".",
"context",
"(",
"SMALL",
")",
";",
"logger",
".",
"debugf",
"(",
"'Invoke removeListener(msgId=%d,listenerId=%s) remotely'",
",",
"ctx",
".",
"id",
",",
"listenerId",
")",
";",
"var",
"conn",
"=",
"p",
".",
"findConnectionListener",
"(",
"listenerId",
")",
";",
"if",
"(",
"!",
"f",
".",
"existy",
"(",
"conn",
")",
")",
"return",
"Promise",
".",
"reject",
"(",
"new",
"Error",
"(",
"'No server connection for listener (listenerId='",
"+",
"listenerId",
"+",
"')'",
")",
")",
";",
"var",
"remote",
"=",
"futurePinned",
"(",
"ctx",
",",
"0x27",
",",
"p",
".",
"encodeListenerId",
"(",
"listenerId",
")",
",",
"p",
".",
"complete",
"(",
"p",
".",
"hasSuccess",
")",
",",
"conn",
")",
";",
"return",
"remote",
".",
"then",
"(",
"function",
"(",
"success",
")",
"{",
"if",
"(",
"success",
")",
"{",
"p",
".",
"removeListeners",
"(",
"listenerId",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
")",
"}"
] |
Remove an event listener.
@param {String} listenerId
Listener identifier to identify listener to remove.
@return {module:promise.Promise}
A promise that will be completed when the listener has been removed.
@memberof Client#
@since 0.3
|
[
"Remove",
"an",
"event",
"listener",
"."
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/infinispan.js#L673-L689
|
train
|
|
infinispan/js-client
|
lib/infinispan.js
|
function(scriptName, params) {
var ctx = u.context(SMALL);
logger.debugf('Invoke execute(msgId=%d,scriptName=%s,params=%s)', ctx.id, scriptName, u.str(params));
// TODO update jsdoc, value does not need to be String, can be JSON too
return futureExec(ctx, 0x2B, p.encodeNameParams(scriptName, params), p.decodeValue());
}
|
javascript
|
function(scriptName, params) {
var ctx = u.context(SMALL);
logger.debugf('Invoke execute(msgId=%d,scriptName=%s,params=%s)', ctx.id, scriptName, u.str(params));
// TODO update jsdoc, value does not need to be String, can be JSON too
return futureExec(ctx, 0x2B, p.encodeNameParams(scriptName, params), p.decodeValue());
}
|
[
"function",
"(",
"scriptName",
",",
"params",
")",
"{",
"var",
"ctx",
"=",
"u",
".",
"context",
"(",
"SMALL",
")",
";",
"logger",
".",
"debugf",
"(",
"'Invoke execute(msgId=%d,scriptName=%s,params=%s)'",
",",
"ctx",
".",
"id",
",",
"scriptName",
",",
"u",
".",
"str",
"(",
"params",
")",
")",
";",
"return",
"futureExec",
"(",
"ctx",
",",
"0x2B",
",",
"p",
".",
"encodeNameParams",
"(",
"scriptName",
",",
"params",
")",
",",
"p",
".",
"decodeValue",
"(",
")",
")",
";",
"}"
] |
Script execution parameters.
@typedef {Object} ExecParams
@property {String} PARAM_NAME -
Name of the parameter.
@property {String} PARAM_VALUE -
Value of the parameter.
@since 0.3
Execute the named script passing in optional parameters.
@param {String} scriptName Name of the script to execute.
@param {?ExecParams[]} params
Optional array of named parameters to pass to script in server.
@returns {module:promise.Promise<String|String[]>}
A promise that will be completed with either the value returned by the
script after execution for local scripts, or an array of values
returned by the script when executed in multiple servers for
distributed scripts.
@memberof Client#
@since 0.3
|
[
"Script",
"execution",
"parameters",
"."
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/infinispan.js#L733-L738
|
train
|
|
infinispan/js-client
|
lib/infinispan.js
|
function(transport) {
return {
/**
* Get the server topology identifier.
*
* @returns {Number} Topology identifier.
* @memberof Topology#
* @since 0.3
*/
getTopologyId: function() {
return transport.getTopologyId();
},
/**
* Get the list of servers that the client is currently connected to.
*
* @return {ServerAddress[]} An array of server addresses.
* @memberof Topology#
* @since 0.3
*/
getMembers: function() {
return transport.getMembers();
},
/**
* Find the list of server addresses that are owners for a given key.
*
* @param {(String|Object)} k Key to find owners for.
* @return {ServerAddress[]}
* An array of server addresses that are owners for the given key.
* @memberof Topology#
* @since 0.3
*/
findOwners: function(k) {
return transport.findOwners(k);
},
/**
* Switch remote cache manager to a different cluster,
* previously declared via configuration.
*
* @param clusterName name of the cluster to which to switch to
* @return {module:promise.Promise<Boolean>}
* A promise encapsulating a Boolean that indicates {@code true} if the
* switch happened, or {@code false} otherwise.
* @memberof Topology#
* @since 0.4
*/
switchToCluster: function(clusterName) {
return transport.switchToCluster(clusterName);
},
/**
* Switch remote cache manager to the default cluster,
* previously declared via configuration.
*
* @return {module:promise.Promise<Boolean>}
* A promise encapsulating a Boolean that indicates {@code true} if the
* switch happened, or {@code false} otherwise.
* @memberof Topology#
* @since 0.4
*/
switchToDefaultCluster: function() {
return transport.switchToDefaultCluster();
}
}
}
|
javascript
|
function(transport) {
return {
/**
* Get the server topology identifier.
*
* @returns {Number} Topology identifier.
* @memberof Topology#
* @since 0.3
*/
getTopologyId: function() {
return transport.getTopologyId();
},
/**
* Get the list of servers that the client is currently connected to.
*
* @return {ServerAddress[]} An array of server addresses.
* @memberof Topology#
* @since 0.3
*/
getMembers: function() {
return transport.getMembers();
},
/**
* Find the list of server addresses that are owners for a given key.
*
* @param {(String|Object)} k Key to find owners for.
* @return {ServerAddress[]}
* An array of server addresses that are owners for the given key.
* @memberof Topology#
* @since 0.3
*/
findOwners: function(k) {
return transport.findOwners(k);
},
/**
* Switch remote cache manager to a different cluster,
* previously declared via configuration.
*
* @param clusterName name of the cluster to which to switch to
* @return {module:promise.Promise<Boolean>}
* A promise encapsulating a Boolean that indicates {@code true} if the
* switch happened, or {@code false} otherwise.
* @memberof Topology#
* @since 0.4
*/
switchToCluster: function(clusterName) {
return transport.switchToCluster(clusterName);
},
/**
* Switch remote cache manager to the default cluster,
* previously declared via configuration.
*
* @return {module:promise.Promise<Boolean>}
* A promise encapsulating a Boolean that indicates {@code true} if the
* switch happened, or {@code false} otherwise.
* @memberof Topology#
* @since 0.4
*/
switchToDefaultCluster: function() {
return transport.switchToDefaultCluster();
}
}
}
|
[
"function",
"(",
"transport",
")",
"{",
"return",
"{",
"getTopologyId",
":",
"function",
"(",
")",
"{",
"return",
"transport",
".",
"getTopologyId",
"(",
")",
";",
"}",
",",
"getMembers",
":",
"function",
"(",
")",
"{",
"return",
"transport",
".",
"getMembers",
"(",
")",
";",
"}",
",",
"findOwners",
":",
"function",
"(",
"k",
")",
"{",
"return",
"transport",
".",
"findOwners",
"(",
"k",
")",
";",
"}",
",",
"switchToCluster",
":",
"function",
"(",
"clusterName",
")",
"{",
"return",
"transport",
".",
"switchToCluster",
"(",
"clusterName",
")",
";",
"}",
",",
"switchToDefaultCluster",
":",
"function",
"(",
")",
"{",
"return",
"transport",
".",
"switchToDefaultCluster",
"(",
")",
";",
"}",
"}",
"}"
] |
Server topology information.
@constructs Topology
@since 0.3
|
[
"Server",
"topology",
"information",
"."
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/infinispan.js#L768-L830
|
train
|
|
infinispan/js-client
|
lib/protocols.js
|
function(values) {
if (values.length < 3) {
logger.tracef("Not enough to read (not array): %s", values);
return undefined;
}
return {listenerId: values[0], isCustom: values[1] == 1, isRetried: values[2] == 1}
}
|
javascript
|
function(values) {
if (values.length < 3) {
logger.tracef("Not enough to read (not array): %s", values);
return undefined;
}
return {listenerId: values[0], isCustom: values[1] == 1, isRetried: values[2] == 1}
}
|
[
"function",
"(",
"values",
")",
"{",
"if",
"(",
"values",
".",
"length",
"<",
"3",
")",
"{",
"logger",
".",
"tracef",
"(",
"\"Not enough to read (not array): %s\"",
",",
"values",
")",
";",
"return",
"undefined",
";",
"}",
"return",
"{",
"listenerId",
":",
"values",
"[",
"0",
"]",
",",
"isCustom",
":",
"values",
"[",
"1",
"]",
"==",
"1",
",",
"isRetried",
":",
"values",
"[",
"2",
"]",
"==",
"1",
"}",
"}"
] |
event is retried
|
[
"event",
"is",
"retried"
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/protocols.js#L489-L496
|
train
|
|
infinispan/js-client
|
lib/protocols.js
|
function(values) {
if (values.length < 2) {
logger.tracef("Not enough to read (not array): %s", values);
return undefined;
}
return {segments: values[0], count: values[1]}
}
|
javascript
|
function(values) {
if (values.length < 2) {
logger.tracef("Not enough to read (not array): %s", values);
return undefined;
}
return {segments: values[0], count: values[1]}
}
|
[
"function",
"(",
"values",
")",
"{",
"if",
"(",
"values",
".",
"length",
"<",
"2",
")",
"{",
"logger",
".",
"tracef",
"(",
"\"Not enough to read (not array): %s\"",
",",
"values",
")",
";",
"return",
"undefined",
";",
"}",
"return",
"{",
"segments",
":",
"values",
"[",
"0",
"]",
",",
"count",
":",
"values",
"[",
"1",
"]",
"}",
"}"
] |
number of entries
|
[
"number",
"of",
"entries"
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/protocols.js#L645-L652
|
train
|
|
infinispan/js-client
|
lib/utils.js
|
toHex
|
function toHex(bignum) {
var tmp0 = bignum[0] < 0 ? (bignum[0]>>>0) : bignum[0];
var tmp1 = bignum[1] < 0 ? (bignum[1]>>>0) : bignum[1];
return tmp0.toString(16) + tmp1.toString(16);
}
|
javascript
|
function toHex(bignum) {
var tmp0 = bignum[0] < 0 ? (bignum[0]>>>0) : bignum[0];
var tmp1 = bignum[1] < 0 ? (bignum[1]>>>0) : bignum[1];
return tmp0.toString(16) + tmp1.toString(16);
}
|
[
"function",
"toHex",
"(",
"bignum",
")",
"{",
"var",
"tmp0",
"=",
"bignum",
"[",
"0",
"]",
"<",
"0",
"?",
"(",
"bignum",
"[",
"0",
"]",
">>>",
"0",
")",
":",
"bignum",
"[",
"0",
"]",
";",
"var",
"tmp1",
"=",
"bignum",
"[",
"1",
"]",
"<",
"0",
"?",
"(",
"bignum",
"[",
"1",
"]",
">>>",
"0",
")",
":",
"bignum",
"[",
"1",
"]",
";",
"return",
"tmp0",
".",
"toString",
"(",
"16",
")",
"+",
"tmp1",
".",
"toString",
"(",
"16",
")",
";",
"}"
] |
Used for debugging hashing
|
[
"Used",
"for",
"debugging",
"hashing"
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/lib/utils.js#L276-L280
|
train
|
infinispan/js-client
|
spec/infinispan_expiry_spec.js
|
waitIdleTimeExpire
|
function waitIdleTimeExpire(key, timeout) {
return function(client) {
var contains = true;
t.sleepFor(200); // sleep required
waitsFor(function() {
client.containsKey(key).then(function(success) {
contains = success;
});
return !contains;
}, '`' + key + '` key should be expired', timeout);
return client;
}
}
|
javascript
|
function waitIdleTimeExpire(key, timeout) {
return function(client) {
var contains = true;
t.sleepFor(200); // sleep required
waitsFor(function() {
client.containsKey(key).then(function(success) {
contains = success;
});
return !contains;
}, '`' + key + '` key should be expired', timeout);
return client;
}
}
|
[
"function",
"waitIdleTimeExpire",
"(",
"key",
",",
"timeout",
")",
"{",
"return",
"function",
"(",
"client",
")",
"{",
"var",
"contains",
"=",
"true",
";",
"t",
".",
"sleepFor",
"(",
"200",
")",
";",
"waitsFor",
"(",
"function",
"(",
")",
"{",
"client",
".",
"containsKey",
"(",
"key",
")",
".",
"then",
"(",
"function",
"(",
"success",
")",
"{",
"contains",
"=",
"success",
";",
"}",
")",
";",
"return",
"!",
"contains",
";",
"}",
",",
"'`'",
"+",
"key",
"+",
"'` key should be expired'",
",",
"timeout",
")",
";",
"return",
"client",
";",
"}",
"}"
] |
timeout in ms
|
[
"timeout",
"in",
"ms"
] |
37ed47d11ccae680a6416dbae7739be7bfa2877b
|
https://github.com/infinispan/js-client/blob/37ed47d11ccae680a6416dbae7739be7bfa2877b/spec/infinispan_expiry_spec.js#L190-L204
|
train
|
cvisco/eslint-plugin-requirejs
|
makefile.js
|
validSemverTag
|
function validSemverTag(list, tag) {
if (semver.valid(tag)) {
list.push(tag);
}
return list;
}
|
javascript
|
function validSemverTag(list, tag) {
if (semver.valid(tag)) {
list.push(tag);
}
return list;
}
|
[
"function",
"validSemverTag",
"(",
"list",
",",
"tag",
")",
"{",
"if",
"(",
"semver",
".",
"valid",
"(",
"tag",
")",
")",
"{",
"list",
".",
"push",
"(",
"tag",
")",
";",
"}",
"return",
"list",
";",
"}"
] |
Push supplied `tag` to supplied `list` only if it is a valid semver. This is
a reducer function.
@private
@param {Array} list - array of valid semver tags
@param {String} tag - tag to push if valid
@returns {Array} modified `list`
|
[
"Push",
"supplied",
"tag",
"to",
"supplied",
"list",
"only",
"if",
"it",
"is",
"a",
"valid",
"semver",
".",
"This",
"is",
"a",
"reducer",
"function",
"."
] |
163abf4507ac2c282e1dd14a87f77707e79edb41
|
https://github.com/cvisco/eslint-plugin-requirejs/blob/163abf4507ac2c282e1dd14a87f77707e79edb41/makefile.js#L61-L67
|
train
|
cvisco/eslint-plugin-requirejs
|
makefile.js
|
release
|
function release(type) {
target.test();
echo("Generating new version");
const newVersion = execSilent("npm version " + type).trim();
target.changelog();
// add changelog to commit
exec("git add CHANGELOG.md");
exec("git commit --amend --no-edit");
// replace existing tag
exec("git tag -f " + newVersion);
// push all the things
echo("Publishing to git");
exec("git push origin master --tags");
echo("Publishing to npm");
exec("npm publish");
}
|
javascript
|
function release(type) {
target.test();
echo("Generating new version");
const newVersion = execSilent("npm version " + type).trim();
target.changelog();
// add changelog to commit
exec("git add CHANGELOG.md");
exec("git commit --amend --no-edit");
// replace existing tag
exec("git tag -f " + newVersion);
// push all the things
echo("Publishing to git");
exec("git push origin master --tags");
echo("Publishing to npm");
exec("npm publish");
}
|
[
"function",
"release",
"(",
"type",
")",
"{",
"target",
".",
"test",
"(",
")",
";",
"echo",
"(",
"\"Generating new version\"",
")",
";",
"const",
"newVersion",
"=",
"execSilent",
"(",
"\"npm version \"",
"+",
"type",
")",
".",
"trim",
"(",
")",
";",
"target",
".",
"changelog",
"(",
")",
";",
"exec",
"(",
"\"git add CHANGELOG.md\"",
")",
";",
"exec",
"(",
"\"git commit --amend --no-edit\"",
")",
";",
"exec",
"(",
"\"git tag -f \"",
"+",
"newVersion",
")",
";",
"echo",
"(",
"\"Publishing to git\"",
")",
";",
"exec",
"(",
"\"git push origin master --tags\"",
")",
";",
"echo",
"(",
"\"Publishing to npm\"",
")",
";",
"exec",
"(",
"\"npm publish\"",
")",
";",
"}"
] |
Create a release version, push tags and publish.
@private
@param {String} type - type of release to do (patch, minor, major)
@returns {void}
|
[
"Create",
"a",
"release",
"version",
"push",
"tags",
"and",
"publish",
"."
] |
163abf4507ac2c282e1dd14a87f77707e79edb41
|
https://github.com/cvisco/eslint-plugin-requirejs/blob/163abf4507ac2c282e1dd14a87f77707e79edb41/makefile.js#L90-L111
|
train
|
cvisco/eslint-plugin-requirejs
|
lib/rules/no-restricted-amd-modules.js
|
reportPath
|
function reportPath(node) {
const moduleName = node.value.trim();
const customMessage = restrictedPathMessages[moduleName];
const message = customMessage
? CUSTOM_MESSAGE_TEMPLATE
: DEFAULT_MESSAGE_TEMPLATE;
context.report({
node,
message,
data: {
moduleName,
customMessage
}
});
}
|
javascript
|
function reportPath(node) {
const moduleName = node.value.trim();
const customMessage = restrictedPathMessages[moduleName];
const message = customMessage
? CUSTOM_MESSAGE_TEMPLATE
: DEFAULT_MESSAGE_TEMPLATE;
context.report({
node,
message,
data: {
moduleName,
customMessage
}
});
}
|
[
"function",
"reportPath",
"(",
"node",
")",
"{",
"const",
"moduleName",
"=",
"node",
".",
"value",
".",
"trim",
"(",
")",
";",
"const",
"customMessage",
"=",
"restrictedPathMessages",
"[",
"moduleName",
"]",
";",
"const",
"message",
"=",
"customMessage",
"?",
"CUSTOM_MESSAGE_TEMPLATE",
":",
"DEFAULT_MESSAGE_TEMPLATE",
";",
"context",
".",
"report",
"(",
"{",
"node",
",",
"message",
",",
"data",
":",
"{",
"moduleName",
",",
"customMessage",
"}",
"}",
")",
";",
"}"
] |
Report a restricted path.
@param {node} node representing the restricted path reference
@returns {void}
@private
|
[
"Report",
"a",
"restricted",
"path",
"."
] |
163abf4507ac2c282e1dd14a87f77707e79edb41
|
https://github.com/cvisco/eslint-plugin-requirejs/blob/163abf4507ac2c282e1dd14a87f77707e79edb41/lib/rules/no-restricted-amd-modules.js#L122-L137
|
train
|
cvisco/eslint-plugin-requirejs
|
lib/utils/ast.js
|
isStringLiteralArray
|
function isStringLiteralArray(node) {
return isArrayExpr(node) &&
isArray(node.elements) &&
node.elements.every(isStringLiteral);
}
|
javascript
|
function isStringLiteralArray(node) {
return isArrayExpr(node) &&
isArray(node.elements) &&
node.elements.every(isStringLiteral);
}
|
[
"function",
"isStringLiteralArray",
"(",
"node",
")",
"{",
"return",
"isArrayExpr",
"(",
"node",
")",
"&&",
"isArray",
"(",
"node",
".",
"elements",
")",
"&&",
"node",
".",
"elements",
".",
"every",
"(",
"isStringLiteral",
")",
";",
"}"
] |
Test if supplied `node` represents an array of string literals. Empty
arrays are also valid here.
@param {ASTNode} node - ArrayExpression node to test
@returns {Boolean} true if node represents an array of string literals
|
[
"Test",
"if",
"supplied",
"node",
"represents",
"an",
"array",
"of",
"string",
"literals",
".",
"Empty",
"arrays",
"are",
"also",
"valid",
"here",
"."
] |
163abf4507ac2c282e1dd14a87f77707e79edb41
|
https://github.com/cvisco/eslint-plugin-requirejs/blob/163abf4507ac2c282e1dd14a87f77707e79edb41/lib/utils/ast.js#L101-L105
|
train
|
cvisco/eslint-plugin-requirejs
|
lib/utils/ast.js
|
hasParams
|
function hasParams(node) {
return isObject(node) &&
isArray(node.params) &&
node.params.length > 0;
}
|
javascript
|
function hasParams(node) {
return isObject(node) &&
isArray(node.params) &&
node.params.length > 0;
}
|
[
"function",
"hasParams",
"(",
"node",
")",
"{",
"return",
"isObject",
"(",
"node",
")",
"&&",
"isArray",
"(",
"node",
".",
"params",
")",
"&&",
"node",
".",
"params",
".",
"length",
">",
"0",
";",
"}"
] |
Test if supplied `node` has parameters.
@param {ASTNode} node - FunctionExpression node to test
@returns {Boolean} true if node has at least one parameter
|
[
"Test",
"if",
"supplied",
"node",
"has",
"parameters",
"."
] |
163abf4507ac2c282e1dd14a87f77707e79edb41
|
https://github.com/cvisco/eslint-plugin-requirejs/blob/163abf4507ac2c282e1dd14a87f77707e79edb41/lib/utils/ast.js#L112-L116
|
train
|
cvisco/eslint-plugin-requirejs
|
lib/utils/ast.js
|
hasCallback
|
function hasCallback(node) {
return isObject(node) &&
isArray(node.arguments) &&
node.arguments.some(isFunctionExpr);
}
|
javascript
|
function hasCallback(node) {
return isObject(node) &&
isArray(node.arguments) &&
node.arguments.some(isFunctionExpr);
}
|
[
"function",
"hasCallback",
"(",
"node",
")",
"{",
"return",
"isObject",
"(",
"node",
")",
"&&",
"isArray",
"(",
"node",
".",
"arguments",
")",
"&&",
"node",
".",
"arguments",
".",
"some",
"(",
"isFunctionExpr",
")",
";",
"}"
] |
Test if supplied `node` has at least one callback argument
@param {ASTNode} node - CallExpression node to test
@returns {Boolean} true if node has at least one callback
|
[
"Test",
"if",
"supplied",
"node",
"has",
"at",
"least",
"one",
"callback",
"argument"
] |
163abf4507ac2c282e1dd14a87f77707e79edb41
|
https://github.com/cvisco/eslint-plugin-requirejs/blob/163abf4507ac2c282e1dd14a87f77707e79edb41/lib/utils/ast.js#L123-L127
|
train
|
cvisco/eslint-plugin-requirejs
|
lib/utils/ast.js
|
ancestor
|
function ancestor(predicate, node) {
while ((node = node.parent)) {
if (predicate(node)) return true;
}
return false;
}
|
javascript
|
function ancestor(predicate, node) {
while ((node = node.parent)) {
if (predicate(node)) return true;
}
return false;
}
|
[
"function",
"ancestor",
"(",
"predicate",
",",
"node",
")",
"{",
"while",
"(",
"(",
"node",
"=",
"node",
".",
"parent",
")",
")",
"{",
"if",
"(",
"predicate",
"(",
"node",
")",
")",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] |
Determine if `node` has an ancestor satisfying `predicate`.
@param {Function} predicate - predicate to test each ancestor against
@param {ASTNode} node - child node to begin search at
@returns {Boolean} true if an ancestor satisfies `predicate`
|
[
"Determine",
"if",
"node",
"has",
"an",
"ancestor",
"satisfying",
"predicate",
"."
] |
163abf4507ac2c282e1dd14a87f77707e79edb41
|
https://github.com/cvisco/eslint-plugin-requirejs/blob/163abf4507ac2c282e1dd14a87f77707e79edb41/lib/utils/ast.js#L135-L141
|
train
|
cvisco/eslint-plugin-requirejs
|
lib/utils/ast.js
|
nearest
|
function nearest(predicate, node) {
while ((node = node.parent)) {
if (predicate(node)) return node;
}
return undefined;
}
|
javascript
|
function nearest(predicate, node) {
while ((node = node.parent)) {
if (predicate(node)) return node;
}
return undefined;
}
|
[
"function",
"nearest",
"(",
"predicate",
",",
"node",
")",
"{",
"while",
"(",
"(",
"node",
"=",
"node",
".",
"parent",
")",
")",
"{",
"if",
"(",
"predicate",
"(",
"node",
")",
")",
"return",
"node",
";",
"}",
"return",
"undefined",
";",
"}"
] |
Find the nearest ancestor satisfying `predicate`.
@param {Function} predicate - predicate to test each ancestor against
@param {ASTNode} node - child node to begin search at
@returns {ASTNode|undefined} nearest ancestor satisfying `predicate`, if any
|
[
"Find",
"the",
"nearest",
"ancestor",
"satisfying",
"predicate",
"."
] |
163abf4507ac2c282e1dd14a87f77707e79edb41
|
https://github.com/cvisco/eslint-plugin-requirejs/blob/163abf4507ac2c282e1dd14a87f77707e79edb41/lib/utils/ast.js#L149-L155
|
train
|
Brightspace/ifrau
|
src/plugins/user-activity-events/client.js
|
throttle
|
function throttle(fn) {
var called = false;
var throttled = false;
var timeout = 10000;
function unthrottled() {
throttled = false;
maybeCall();
}
function maybeCall() {
if (called && !throttled) {
called = false;
throttled = true;
setTimeout(unthrottled, timeout);
fn();
}
}
return function() {
called = true;
maybeCall();
};
}
|
javascript
|
function throttle(fn) {
var called = false;
var throttled = false;
var timeout = 10000;
function unthrottled() {
throttled = false;
maybeCall();
}
function maybeCall() {
if (called && !throttled) {
called = false;
throttled = true;
setTimeout(unthrottled, timeout);
fn();
}
}
return function() {
called = true;
maybeCall();
};
}
|
[
"function",
"throttle",
"(",
"fn",
")",
"{",
"var",
"called",
"=",
"false",
";",
"var",
"throttled",
"=",
"false",
";",
"var",
"timeout",
"=",
"10000",
";",
"function",
"unthrottled",
"(",
")",
"{",
"throttled",
"=",
"false",
";",
"maybeCall",
"(",
")",
";",
"}",
"function",
"maybeCall",
"(",
")",
"{",
"if",
"(",
"called",
"&&",
"!",
"throttled",
")",
"{",
"called",
"=",
"false",
";",
"throttled",
"=",
"true",
";",
"setTimeout",
"(",
"unthrottled",
",",
"timeout",
")",
";",
"fn",
"(",
")",
";",
"}",
"}",
"return",
"function",
"(",
")",
"{",
"called",
"=",
"true",
";",
"maybeCall",
"(",
")",
";",
"}",
";",
"}"
] |
Call fn immediately, and then don't call again until after timeout has passed If it is called one or more times within the timeout, fn is called at the trailing edge of the timeout as well, and then re-throttled
|
[
"Call",
"fn",
"immediately",
"and",
"then",
"don",
"t",
"call",
"again",
"until",
"after",
"timeout",
"has",
"passed",
"If",
"it",
"is",
"called",
"one",
"or",
"more",
"times",
"within",
"the",
"timeout",
"fn",
"is",
"called",
"at",
"the",
"trailing",
"edge",
"of",
"the",
"timeout",
"as",
"well",
"and",
"then",
"re",
"-",
"throttled"
] |
f7b4774451da2314808a0c704f6b789e3a321a71
|
https://github.com/Brightspace/ifrau/blob/f7b4774451da2314808a0c704f6b789e3a321a71/src/plugins/user-activity-events/client.js#L22-L45
|
train
|
willscott/ip2country
|
src/tree.js
|
function (node, key) {
'use strict';
var i, k;
if (node.key === key) {
return node;
} else {
for (i = 0; i < node.children.length; i += 1) {
k = slow_findKey(node.children[i], key);
if (k) {
return k;
}
}
}
}
|
javascript
|
function (node, key) {
'use strict';
var i, k;
if (node.key === key) {
return node;
} else {
for (i = 0; i < node.children.length; i += 1) {
k = slow_findKey(node.children[i], key);
if (k) {
return k;
}
}
}
}
|
[
"function",
"(",
"node",
",",
"key",
")",
"{",
"'use strict'",
";",
"var",
"i",
",",
"k",
";",
"if",
"(",
"node",
".",
"key",
"===",
"key",
")",
"{",
"return",
"node",
";",
"}",
"else",
"{",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"node",
".",
"children",
".",
"length",
";",
"i",
"+=",
"1",
")",
"{",
"k",
"=",
"slow_findKey",
"(",
"node",
".",
"children",
"[",
"i",
"]",
",",
"key",
")",
";",
"if",
"(",
"k",
")",
"{",
"return",
"k",
";",
"}",
"}",
"}",
"}"
] |
Slow implementation of findKey which checks every node. Useful to understand if the tree has been built incorrectly.
|
[
"Slow",
"implementation",
"of",
"findKey",
"which",
"checks",
"every",
"node",
".",
"Useful",
"to",
"understand",
"if",
"the",
"tree",
"has",
"been",
"built",
"incorrectly",
"."
] |
eb34608e50f324d5ffa81030bc88a1a8b2537fb1
|
https://github.com/willscott/ip2country/blob/eb34608e50f324d5ffa81030bc88a1a8b2537fb1/src/tree.js#L172-L186
|
train
|
|
thlorenz/irish-pub
|
index.js
|
irishPub
|
function irishPub(root) {
root = root || process.cwd();
var out = new PassThrough();
getMetadata(root, function(err, meta) {
if (err) return out.emit('error', err);
out.emit('metadata', meta);
listFiles(root, out);
});
return out;
}
|
javascript
|
function irishPub(root) {
root = root || process.cwd();
var out = new PassThrough();
getMetadata(root, function(err, meta) {
if (err) return out.emit('error', err);
out.emit('metadata', meta);
listFiles(root, out);
});
return out;
}
|
[
"function",
"irishPub",
"(",
"root",
")",
"{",
"root",
"=",
"root",
"||",
"process",
".",
"cwd",
"(",
")",
";",
"var",
"out",
"=",
"new",
"PassThrough",
"(",
")",
";",
"getMetadata",
"(",
"root",
",",
"function",
"(",
"err",
",",
"meta",
")",
"{",
"if",
"(",
"err",
")",
"return",
"out",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"out",
".",
"emit",
"(",
"'metadata'",
",",
"meta",
")",
";",
"listFiles",
"(",
"root",
",",
"out",
")",
";",
"}",
")",
";",
"return",
"out",
";",
"}"
] |
Invokes `npm pack` to determine what would be included during `npm publish`.
@name irishPub
@function
@param {string} root path to package to publish, defaults to `cwd`
@return {ReadableStream} stream that emits all files with paths relative to `root` that will be packed via the `data` event
|
[
"Invokes",
"npm",
"pack",
"to",
"determine",
"what",
"would",
"be",
"included",
"during",
"npm",
"publish",
"."
] |
8653292936c5f53069f23b187e6792fc5566b99d
|
https://github.com/thlorenz/irish-pub/blob/8653292936c5f53069f23b187e6792fc5566b99d/index.js#L20-L31
|
train
|
Pearson-Higher-Ed/coach-mark
|
src/js/component-owner.js
|
focusWithTimeout
|
function focusWithTimeout(props, el, timeout = 0) {
setTimeout(() => {
if (props.stopScroll) {
el.focus({ preventScroll: true });
} else {
const x = window.pageXOffset,
y = window.pageYOffset;
el.focus();
window.scrollTo(x, y);
}
}, timeout);
}
|
javascript
|
function focusWithTimeout(props, el, timeout = 0) {
setTimeout(() => {
if (props.stopScroll) {
el.focus({ preventScroll: true });
} else {
const x = window.pageXOffset,
y = window.pageYOffset;
el.focus();
window.scrollTo(x, y);
}
}, timeout);
}
|
[
"function",
"focusWithTimeout",
"(",
"props",
",",
"el",
",",
"timeout",
"=",
"0",
")",
"{",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"if",
"(",
"props",
".",
"stopScroll",
")",
"{",
"el",
".",
"focus",
"(",
"{",
"preventScroll",
":",
"true",
"}",
")",
";",
"}",
"else",
"{",
"const",
"x",
"=",
"window",
".",
"pageXOffset",
",",
"y",
"=",
"window",
".",
"pageYOffset",
";",
"el",
".",
"focus",
"(",
")",
";",
"window",
".",
"scrollTo",
"(",
"x",
",",
"y",
")",
";",
"}",
"}",
",",
"timeout",
")",
";",
"}"
] |
Focus on DOM node after a delay.
@param {HTMLElement} el Element that will receive focus.
@param {Number} [timeout = 0] Delay before focus occurs, in ms. Defaults to 0.
|
[
"Focus",
"on",
"DOM",
"node",
"after",
"a",
"delay",
"."
] |
4d007afeb1102ca747f88c25612f73ab70436017
|
https://github.com/Pearson-Higher-Ed/coach-mark/blob/4d007afeb1102ca747f88c25612f73ab70436017/src/js/component-owner.js#L14-L25
|
train
|
binary-com/binary-style
|
src/js/binary.more.js
|
function (target) {
var elem = $(target);
var maxValue = 0;
var position, value;
while (elem.length && elem[0] !== document) {
position = elem.css("position");
if (position === "absolute" || position === "relative" || position === "fixed") {
value = parseInt(elem.css("zIndex"), 10);
if (!isNaN(value) && value !== 0) {
if (value > maxValue) { maxValue = value; }
}
}
elem = elem.parent();
}
return maxValue;
}
|
javascript
|
function (target) {
var elem = $(target);
var maxValue = 0;
var position, value;
while (elem.length && elem[0] !== document) {
position = elem.css("position");
if (position === "absolute" || position === "relative" || position === "fixed") {
value = parseInt(elem.css("zIndex"), 10);
if (!isNaN(value) && value !== 0) {
if (value > maxValue) { maxValue = value; }
}
}
elem = elem.parent();
}
return maxValue;
}
|
[
"function",
"(",
"target",
")",
"{",
"var",
"elem",
"=",
"$",
"(",
"target",
")",
";",
"var",
"maxValue",
"=",
"0",
";",
"var",
"position",
",",
"value",
";",
"while",
"(",
"elem",
".",
"length",
"&&",
"elem",
"[",
"0",
"]",
"!==",
"document",
")",
"{",
"position",
"=",
"elem",
".",
"css",
"(",
"\"position\"",
")",
";",
"if",
"(",
"position",
"===",
"\"absolute\"",
"||",
"position",
"===",
"\"relative\"",
"||",
"position",
"===",
"\"fixed\"",
")",
"{",
"value",
"=",
"parseInt",
"(",
"elem",
".",
"css",
"(",
"\"zIndex\"",
")",
",",
"10",
")",
";",
"if",
"(",
"!",
"isNaN",
"(",
"value",
")",
"&&",
"value",
"!==",
"0",
")",
"{",
"if",
"(",
"value",
">",
"maxValue",
")",
"{",
"maxValue",
"=",
"value",
";",
"}",
"}",
"}",
"elem",
"=",
"elem",
".",
"parent",
"(",
")",
";",
"}",
"return",
"maxValue",
";",
"}"
] |
This is an enhanced copy of the zIndex function of UI core 1.8.?? For backward compatibility. Enhancement returns maximum zindex value discovered while traversing parent elements, rather than the first zindex value found. Ensures the timepicker popup will be in front, even in funky scenarios like non-jq dialog containers with large fixed zindex values and nested zindex-influenced elements of their own.
|
[
"This",
"is",
"an",
"enhanced",
"copy",
"of",
"the",
"zIndex",
"function",
"of",
"UI",
"core",
"1",
".",
"8",
".",
"??",
"For",
"backward",
"compatibility",
".",
"Enhancement",
"returns",
"maximum",
"zindex",
"value",
"discovered",
"while",
"traversing",
"parent",
"elements",
"rather",
"than",
"the",
"first",
"zindex",
"value",
"found",
".",
"Ensures",
"the",
"timepicker",
"popup",
"will",
"be",
"in",
"front",
"even",
"in",
"funky",
"scenarios",
"like",
"non",
"-",
"jq",
"dialog",
"containers",
"with",
"large",
"fixed",
"zindex",
"values",
"and",
"nested",
"zindex",
"-",
"influenced",
"elements",
"of",
"their",
"own",
"."
] |
9cebb6e5be2ade703c68e7d7aca3e59c83b674c2
|
https://github.com/binary-com/binary-style/blob/9cebb6e5be2ade703c68e7d7aca3e59c83b674c2/src/js/binary.more.js#L6429-L6445
|
train
|
|
henry-luo/mark
|
dev/mark.find.js
|
function(type, pattern, data) {
if (type == 'tag') { // case-insensitive match on tag name
return pattern && pattern.toLowerCase() == data.toLowerCase();
} else {
return pattern === data;
}
}
|
javascript
|
function(type, pattern, data) {
if (type == 'tag') { // case-insensitive match on tag name
return pattern && pattern.toLowerCase() == data.toLowerCase();
} else {
return pattern === data;
}
}
|
[
"function",
"(",
"type",
",",
"pattern",
",",
"data",
")",
"{",
"if",
"(",
"type",
"==",
"'tag'",
")",
"{",
"return",
"pattern",
"&&",
"pattern",
".",
"toLowerCase",
"(",
")",
"==",
"data",
".",
"toLowerCase",
"(",
")",
";",
"}",
"else",
"{",
"return",
"pattern",
"===",
"data",
";",
"}",
"}"
] |
matchComparison, default is caseSensitiveComparison
|
[
"matchComparison",
"default",
"is",
"caseSensitiveComparison"
] |
65953a233ccba62120700b6a625461fbb1158578
|
https://github.com/henry-luo/mark/blob/65953a233ccba62120700b6a625461fbb1158578/dev/mark.find.js#L13-L19
|
train
|
|
alexfernandez/prototypes
|
lib/string.js
|
convertBinaryToBase36
|
function convertBinaryToBase36(binary)
{
var result = '';
for (var i = 0; i < 25; i++)
{
var c;
if (typeof binary == 'string')
{
c = binary.charCodeAt(i) % 36;
}
else
{
c = binary[i] % 36;
}
if (c < 10)
{
result += String.fromCharCode(48 + c);
}
else
{
result += String.fromCharCode(87 + c);
}
}
return result;
}
|
javascript
|
function convertBinaryToBase36(binary)
{
var result = '';
for (var i = 0; i < 25; i++)
{
var c;
if (typeof binary == 'string')
{
c = binary.charCodeAt(i) % 36;
}
else
{
c = binary[i] % 36;
}
if (c < 10)
{
result += String.fromCharCode(48 + c);
}
else
{
result += String.fromCharCode(87 + c);
}
}
return result;
}
|
[
"function",
"convertBinaryToBase36",
"(",
"binary",
")",
"{",
"var",
"result",
"=",
"''",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"25",
";",
"i",
"++",
")",
"{",
"var",
"c",
";",
"if",
"(",
"typeof",
"binary",
"==",
"'string'",
")",
"{",
"c",
"=",
"binary",
".",
"charCodeAt",
"(",
"i",
")",
"%",
"36",
";",
"}",
"else",
"{",
"c",
"=",
"binary",
"[",
"i",
"]",
"%",
"36",
";",
"}",
"if",
"(",
"c",
"<",
"10",
")",
"{",
"result",
"+=",
"String",
".",
"fromCharCode",
"(",
"48",
"+",
"c",
")",
";",
"}",
"else",
"{",
"result",
"+=",
"String",
".",
"fromCharCode",
"(",
"87",
"+",
"c",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Convert binary to base 36.
|
[
"Convert",
"binary",
"to",
"base",
"36",
"."
] |
1e7cd8b9b824efc8bbcc7ac727dfd51f1dc61008
|
https://github.com/alexfernandez/prototypes/blob/1e7cd8b9b824efc8bbcc7ac727dfd51f1dc61008/lib/string.js#L286-L310
|
train
|
henry-luo/mark
|
mark.js
|
Mark
|
function Mark(typeName, props, contents) {
// handle special shorthand
if (arguments.length === 1 && (typeName[0] === '{' || typeName[0] === '[' || ws.indexOf(typeName[0]) >= 0)) {
return MARK.parse(typeName);
}
// 1. prepare the constructor
if (typeof typeName !== 'string') {
if (this instanceof Mark) { // called through new operator
this[$length] = 0;
// no need to do further construction
// props, contents are not supported at the moment
return;
}
throw "Type name should be a string";
}
let con = $ctrs[typeName];
if (!con) {
con = $ctrs[typeName] = function(){};
// con.prototype.constructor is set to con by JS
// sets the type name
Object.defineProperty(con, 'name', {value:typeName, configurable:true}); // non-writable, as we don't want the name to be changed
// con.prototype.__proto__ = Array.prototype; // Mark no longer extends Array; Mark is array like, but not array.
// con is set to extend Mark, instead of copying all the API functions
// for (let a in api) { Object.defineProperty(con.prototype, a, {value:api[a], writable:true, configurable:true}); } // make API functions non-enumerable
Object.setPrototypeOf(con.prototype, Mark.prototype);
}
// 2. create object
let obj = Object.create(con.prototype);
// 3. copy properties, numeric keys are not allowed
if (props) {
for (let p in props) {
// accept only non-numeric key; and we do no check key duplication here, last definition wins
if (isNaN(p*1)) { obj[p] = props[p]; }
}
}
// 4. copy contents if any
obj[$length] = 0;
if (contents) { push.call(obj, contents); }
return obj;
}
|
javascript
|
function Mark(typeName, props, contents) {
// handle special shorthand
if (arguments.length === 1 && (typeName[0] === '{' || typeName[0] === '[' || ws.indexOf(typeName[0]) >= 0)) {
return MARK.parse(typeName);
}
// 1. prepare the constructor
if (typeof typeName !== 'string') {
if (this instanceof Mark) { // called through new operator
this[$length] = 0;
// no need to do further construction
// props, contents are not supported at the moment
return;
}
throw "Type name should be a string";
}
let con = $ctrs[typeName];
if (!con) {
con = $ctrs[typeName] = function(){};
// con.prototype.constructor is set to con by JS
// sets the type name
Object.defineProperty(con, 'name', {value:typeName, configurable:true}); // non-writable, as we don't want the name to be changed
// con.prototype.__proto__ = Array.prototype; // Mark no longer extends Array; Mark is array like, but not array.
// con is set to extend Mark, instead of copying all the API functions
// for (let a in api) { Object.defineProperty(con.prototype, a, {value:api[a], writable:true, configurable:true}); } // make API functions non-enumerable
Object.setPrototypeOf(con.prototype, Mark.prototype);
}
// 2. create object
let obj = Object.create(con.prototype);
// 3. copy properties, numeric keys are not allowed
if (props) {
for (let p in props) {
// accept only non-numeric key; and we do no check key duplication here, last definition wins
if (isNaN(p*1)) { obj[p] = props[p]; }
}
}
// 4. copy contents if any
obj[$length] = 0;
if (contents) { push.call(obj, contents); }
return obj;
}
|
[
"function",
"Mark",
"(",
"typeName",
",",
"props",
",",
"contents",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"1",
"&&",
"(",
"typeName",
"[",
"0",
"]",
"===",
"'{'",
"||",
"typeName",
"[",
"0",
"]",
"===",
"'['",
"||",
"ws",
".",
"indexOf",
"(",
"typeName",
"[",
"0",
"]",
")",
">=",
"0",
")",
")",
"{",
"return",
"MARK",
".",
"parse",
"(",
"typeName",
")",
";",
"}",
"if",
"(",
"typeof",
"typeName",
"!==",
"'string'",
")",
"{",
"if",
"(",
"this",
"instanceof",
"Mark",
")",
"{",
"this",
"[",
"$length",
"]",
"=",
"0",
";",
"return",
";",
"}",
"throw",
"\"Type name should be a string\"",
";",
"}",
"let",
"con",
"=",
"$ctrs",
"[",
"typeName",
"]",
";",
"if",
"(",
"!",
"con",
")",
"{",
"con",
"=",
"$ctrs",
"[",
"typeName",
"]",
"=",
"function",
"(",
")",
"{",
"}",
";",
"Object",
".",
"defineProperty",
"(",
"con",
",",
"'name'",
",",
"{",
"value",
":",
"typeName",
",",
"configurable",
":",
"true",
"}",
")",
";",
"Object",
".",
"setPrototypeOf",
"(",
"con",
".",
"prototype",
",",
"Mark",
".",
"prototype",
")",
";",
"}",
"let",
"obj",
"=",
"Object",
".",
"create",
"(",
"con",
".",
"prototype",
")",
";",
"if",
"(",
"props",
")",
"{",
"for",
"(",
"let",
"p",
"in",
"props",
")",
"{",
"if",
"(",
"isNaN",
"(",
"p",
"*",
"1",
")",
")",
"{",
"obj",
"[",
"p",
"]",
"=",
"props",
"[",
"p",
"]",
";",
"}",
"}",
"}",
"obj",
"[",
"$length",
"]",
"=",
"0",
";",
"if",
"(",
"contents",
")",
"{",
"push",
".",
"call",
"(",
"obj",
",",
"contents",
")",
";",
"}",
"return",
"obj",
";",
"}"
] |
Mark.prototype and Mark object constructor
|
[
"Mark",
".",
"prototype",
"and",
"Mark",
"object",
"constructor"
] |
65953a233ccba62120700b6a625461fbb1158578
|
https://github.com/henry-luo/mark/blob/65953a233ccba62120700b6a625461fbb1158578/mark.js#L68-L112
|
train
|
henry-luo/mark
|
mark.js
|
isNameChar
|
function isNameChar(c) {
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
c === '_' || c === '$' || c === '.' || c === '-';
}
|
javascript
|
function isNameChar(c) {
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
c === '_' || c === '$' || c === '.' || c === '-';
}
|
[
"function",
"isNameChar",
"(",
"c",
")",
"{",
"return",
"(",
"'a'",
"<=",
"c",
"&&",
"c",
"<=",
"'z'",
")",
"||",
"(",
"'A'",
"<=",
"c",
"&&",
"c",
"<=",
"'Z'",
")",
"||",
"(",
"'0'",
"<=",
"c",
"&&",
"c",
"<=",
"'9'",
")",
"||",
"c",
"===",
"'_'",
"||",
"c",
"===",
"'$'",
"||",
"c",
"===",
"'.'",
"||",
"c",
"===",
"'-'",
";",
"}"
] |
check if a string is a Mark identifier, exported for convenience
|
[
"check",
"if",
"a",
"string",
"is",
"a",
"Mark",
"identifier",
"exported",
"for",
"convenience"
] |
65953a233ccba62120700b6a625461fbb1158578
|
https://github.com/henry-luo/mark/blob/65953a233ccba62120700b6a625461fbb1158578/mark.js#L226-L229
|
train
|
jamesplease/fetch-dedupe
|
src/index.js
|
resolveRequest
|
function resolveRequest({ requestKey, res, err }) {
const handlers = requests[requestKey] || [];
handlers.forEach(handler => {
if (res) {
handler.resolve(res);
} else {
handler.reject(err);
}
});
// This list of handlers has been, well, handled. So we
// clear the handlers for the next request.
requests[requestKey] = null;
}
|
javascript
|
function resolveRequest({ requestKey, res, err }) {
const handlers = requests[requestKey] || [];
handlers.forEach(handler => {
if (res) {
handler.resolve(res);
} else {
handler.reject(err);
}
});
// This list of handlers has been, well, handled. So we
// clear the handlers for the next request.
requests[requestKey] = null;
}
|
[
"function",
"resolveRequest",
"(",
"{",
"requestKey",
",",
"res",
",",
"err",
"}",
")",
"{",
"const",
"handlers",
"=",
"requests",
"[",
"requestKey",
"]",
"||",
"[",
"]",
";",
"handlers",
".",
"forEach",
"(",
"handler",
"=>",
"{",
"if",
"(",
"res",
")",
"{",
"handler",
".",
"resolve",
"(",
"res",
")",
";",
"}",
"else",
"{",
"handler",
".",
"reject",
"(",
"err",
")",
";",
"}",
"}",
")",
";",
"requests",
"[",
"requestKey",
"]",
"=",
"null",
";",
"}"
] |
This loops through all of the handlers for the request and either resolves or rejects them.
|
[
"This",
"loops",
"through",
"all",
"of",
"the",
"handlers",
"for",
"the",
"request",
"and",
"either",
"resolves",
"or",
"rejects",
"them",
"."
] |
a8d2b2409c0c135e50f8fef282f7ff4c2900504c
|
https://github.com/jamesplease/fetch-dedupe/blob/a8d2b2409c0c135e50f8fef282f7ff4c2900504c/src/index.js#L27-L41
|
train
|
phovea/phovea_ui
|
index.js
|
byName
|
function byName(a, b) {
if (a === INDEX_FILE) {
return a === b ? 0 : -1;
}
if (b === INDEX_FILE) {
return 1;
}
return a.toLowerCase().localeCompare(b.toLowerCase());
}
|
javascript
|
function byName(a, b) {
if (a === INDEX_FILE) {
return a === b ? 0 : -1;
}
if (b === INDEX_FILE) {
return 1;
}
return a.toLowerCase().localeCompare(b.toLowerCase());
}
|
[
"function",
"byName",
"(",
"a",
",",
"b",
")",
"{",
"if",
"(",
"a",
"===",
"INDEX_FILE",
")",
"{",
"return",
"a",
"===",
"b",
"?",
"0",
":",
"-",
"1",
";",
"}",
"if",
"(",
"b",
"===",
"INDEX_FILE",
")",
"{",
"return",
"1",
";",
"}",
"return",
"a",
".",
"toLowerCase",
"(",
")",
".",
"localeCompare",
"(",
"b",
".",
"toLowerCase",
"(",
")",
")",
";",
"}"
] |
sorts the given filename by name ensuring INDEX is the first one
@param a
@param b
@returns {number}
|
[
"sorts",
"the",
"given",
"filename",
"by",
"name",
"ensuring",
"INDEX",
"is",
"the",
"first",
"one"
] |
9c57e68c0b850cb7b0208157f8c5086ea86f8f28
|
https://github.com/phovea/phovea_ui/blob/9c57e68c0b850cb7b0208157f8c5086ea86f8f28/index.js#L22-L30
|
train
|
thlorenz/deoptigate
|
examples/simple/adders.js
|
log
|
function log() {
if (typeof print === 'function') {
print.apply(this, arguments)
} else {
console.log.apply(console, arguments)
}
}
|
javascript
|
function log() {
if (typeof print === 'function') {
print.apply(this, arguments)
} else {
console.log.apply(console, arguments)
}
}
|
[
"function",
"log",
"(",
")",
"{",
"if",
"(",
"typeof",
"print",
"===",
"'function'",
")",
"{",
"print",
".",
"apply",
"(",
"this",
",",
"arguments",
")",
"}",
"else",
"{",
"console",
".",
"log",
".",
"apply",
"(",
"console",
",",
"arguments",
")",
"}",
"}"
] |
make this work with d8 and Node.js
|
[
"make",
"this",
"work",
"with",
"d8",
"and",
"Node",
".",
"js"
] |
28531307800a17214740906419b5b1cd2d527788
|
https://github.com/thlorenz/deoptigate/blob/28531307800a17214740906419b5b1cd2d527788/examples/simple/adders.js#L151-L157
|
train
|
UCF/Athena-Framework
|
gulpfile.js
|
buildCSS
|
function buildCSS(src, filename, dest, applyHeader) {
dest = dest || config.dist.cssPath;
applyHeader = applyHeader || false;
return gulp.src(src)
.pipe(sass({
includePaths: [config.src.scssPath, config.packagesPath]
})
.on('error', sass.logError))
.pipe(cleanCSS())
.pipe(autoprefixer({
// Supported browsers added in package.json ("browserslist")
cascade: false
}))
.pipe(gulpif(applyHeader, header(config.prj.header, {
config: config
})))
// Remove charset rule (if present) and add to the first
// line of the stylesheet (@charset must be on the first line)
.pipe(replace('@charset "UTF-8";', ''))
.pipe(header('@charset "UTF-8";\n'))
.pipe(rename(filename))
.pipe(gulp.dest(dest));
}
|
javascript
|
function buildCSS(src, filename, dest, applyHeader) {
dest = dest || config.dist.cssPath;
applyHeader = applyHeader || false;
return gulp.src(src)
.pipe(sass({
includePaths: [config.src.scssPath, config.packagesPath]
})
.on('error', sass.logError))
.pipe(cleanCSS())
.pipe(autoprefixer({
// Supported browsers added in package.json ("browserslist")
cascade: false
}))
.pipe(gulpif(applyHeader, header(config.prj.header, {
config: config
})))
// Remove charset rule (if present) and add to the first
// line of the stylesheet (@charset must be on the first line)
.pipe(replace('@charset "UTF-8";', ''))
.pipe(header('@charset "UTF-8";\n'))
.pipe(rename(filename))
.pipe(gulp.dest(dest));
}
|
[
"function",
"buildCSS",
"(",
"src",
",",
"filename",
",",
"dest",
",",
"applyHeader",
")",
"{",
"dest",
"=",
"dest",
"||",
"config",
".",
"dist",
".",
"cssPath",
";",
"applyHeader",
"=",
"applyHeader",
"||",
"false",
";",
"return",
"gulp",
".",
"src",
"(",
"src",
")",
".",
"pipe",
"(",
"sass",
"(",
"{",
"includePaths",
":",
"[",
"config",
".",
"src",
".",
"scssPath",
",",
"config",
".",
"packagesPath",
"]",
"}",
")",
".",
"on",
"(",
"'error'",
",",
"sass",
".",
"logError",
")",
")",
".",
"pipe",
"(",
"cleanCSS",
"(",
")",
")",
".",
"pipe",
"(",
"autoprefixer",
"(",
"{",
"cascade",
":",
"false",
"}",
")",
")",
".",
"pipe",
"(",
"gulpif",
"(",
"applyHeader",
",",
"header",
"(",
"config",
".",
"prj",
".",
"header",
",",
"{",
"config",
":",
"config",
"}",
")",
")",
")",
".",
"pipe",
"(",
"replace",
"(",
"'@charset \"UTF-8\";'",
",",
"''",
")",
")",
".",
"pipe",
"(",
"header",
"(",
"'@charset \"UTF-8\";\\n'",
")",
")",
".",
"\\n",
"pipe",
".",
"(",
"rename",
"(",
"filename",
")",
")",
"pipe",
";",
"}"
] |
Compile scss files
|
[
"Compile",
"scss",
"files"
] |
12cca54de650b5782956486267d3de81f237c8d1
|
https://github.com/UCF/Athena-Framework/blob/12cca54de650b5782956486267d3de81f237c8d1/gulpfile.js#L96-L119
|
train
|
UCF/Athena-Framework
|
gulpfile.js
|
buildJS
|
function buildJS(src, filename, dest, applyHeader, forceIncludePaths) {
dest = dest || config.dist.jsPath;
applyHeader = applyHeader || false;
forceIncludePaths = forceIncludePaths || false;
return gulp.src(src)
.pipe(gulpif(
forceIncludePaths,
include({
includePaths: [
path.dirname(src),
__dirname,
config.packagesPath
]
}),
include()
))
.on('error', console.log) // eslint-disable-line no-console
.pipe(babel())
.pipe(uglify({
output: {
// try to preserve non-standard headers (e.g. from objectFitPolyfill)
comments: /^(!|---)/
}
}))
.pipe(gulpif(applyHeader, header(config.prj.header, {
config: config
})))
.pipe(rename(filename))
.pipe(gulp.dest(dest));
}
|
javascript
|
function buildJS(src, filename, dest, applyHeader, forceIncludePaths) {
dest = dest || config.dist.jsPath;
applyHeader = applyHeader || false;
forceIncludePaths = forceIncludePaths || false;
return gulp.src(src)
.pipe(gulpif(
forceIncludePaths,
include({
includePaths: [
path.dirname(src),
__dirname,
config.packagesPath
]
}),
include()
))
.on('error', console.log) // eslint-disable-line no-console
.pipe(babel())
.pipe(uglify({
output: {
// try to preserve non-standard headers (e.g. from objectFitPolyfill)
comments: /^(!|---)/
}
}))
.pipe(gulpif(applyHeader, header(config.prj.header, {
config: config
})))
.pipe(rename(filename))
.pipe(gulp.dest(dest));
}
|
[
"function",
"buildJS",
"(",
"src",
",",
"filename",
",",
"dest",
",",
"applyHeader",
",",
"forceIncludePaths",
")",
"{",
"dest",
"=",
"dest",
"||",
"config",
".",
"dist",
".",
"jsPath",
";",
"applyHeader",
"=",
"applyHeader",
"||",
"false",
";",
"forceIncludePaths",
"=",
"forceIncludePaths",
"||",
"false",
";",
"return",
"gulp",
".",
"src",
"(",
"src",
")",
".",
"pipe",
"(",
"gulpif",
"(",
"forceIncludePaths",
",",
"include",
"(",
"{",
"includePaths",
":",
"[",
"path",
".",
"dirname",
"(",
"src",
")",
",",
"__dirname",
",",
"config",
".",
"packagesPath",
"]",
"}",
")",
",",
"include",
"(",
")",
")",
")",
".",
"on",
"(",
"'error'",
",",
"console",
".",
"log",
")",
".",
"pipe",
"(",
"babel",
"(",
")",
")",
".",
"pipe",
"(",
"uglify",
"(",
"{",
"output",
":",
"{",
"comments",
":",
"/",
"^(!|---)",
"/",
"}",
"}",
")",
")",
".",
"pipe",
"(",
"gulpif",
"(",
"applyHeader",
",",
"header",
"(",
"config",
".",
"prj",
".",
"header",
",",
"{",
"config",
":",
"config",
"}",
")",
")",
")",
".",
"pipe",
"(",
"rename",
"(",
"filename",
")",
")",
".",
"pipe",
"(",
"gulp",
".",
"dest",
"(",
"dest",
")",
")",
";",
"}"
] |
Concat and uglify js files through babel
|
[
"Concat",
"and",
"uglify",
"js",
"files",
"through",
"babel"
] |
12cca54de650b5782956486267d3de81f237c8d1
|
https://github.com/UCF/Athena-Framework/blob/12cca54de650b5782956486267d3de81f237c8d1/gulpfile.js#L136-L166
|
train
|
UCF/Athena-Framework
|
gulpfile.js
|
buildDocsIndex
|
function buildDocsIndex(dataPath, indexPath, done) {
dataPath = dataPath || `${config.docsLocalPath}/search-data.json`;
indexPath = indexPath || `${config.docsLocalPath}/search-index.json`;
const documents = JSON.parse(fs.readFileSync(dataPath));
// Generate index
const idx = lunr(function () {
this.ref('id');
this.field('title');
documents.forEach(function (doc) {
this.add(doc);
}, this);
});
const searchIndex = JSON.stringify(idx);
// Save search index
fs.writeFileSync(indexPath, searchIndex);
done();
}
|
javascript
|
function buildDocsIndex(dataPath, indexPath, done) {
dataPath = dataPath || `${config.docsLocalPath}/search-data.json`;
indexPath = indexPath || `${config.docsLocalPath}/search-index.json`;
const documents = JSON.parse(fs.readFileSync(dataPath));
// Generate index
const idx = lunr(function () {
this.ref('id');
this.field('title');
documents.forEach(function (doc) {
this.add(doc);
}, this);
});
const searchIndex = JSON.stringify(idx);
// Save search index
fs.writeFileSync(indexPath, searchIndex);
done();
}
|
[
"function",
"buildDocsIndex",
"(",
"dataPath",
",",
"indexPath",
",",
"done",
")",
"{",
"dataPath",
"=",
"dataPath",
"||",
"`",
"${",
"config",
".",
"docsLocalPath",
"}",
"`",
";",
"indexPath",
"=",
"indexPath",
"||",
"`",
"${",
"config",
".",
"docsLocalPath",
"}",
"`",
";",
"const",
"documents",
"=",
"JSON",
".",
"parse",
"(",
"fs",
".",
"readFileSync",
"(",
"dataPath",
")",
")",
";",
"const",
"idx",
"=",
"lunr",
"(",
"function",
"(",
")",
"{",
"this",
".",
"ref",
"(",
"'id'",
")",
";",
"this",
".",
"field",
"(",
"'title'",
")",
";",
"documents",
".",
"forEach",
"(",
"function",
"(",
"doc",
")",
"{",
"this",
".",
"add",
"(",
"doc",
")",
";",
"}",
",",
"this",
")",
";",
"}",
")",
";",
"const",
"searchIndex",
"=",
"JSON",
".",
"stringify",
"(",
"idx",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"indexPath",
",",
"searchIndex",
")",
";",
"done",
"(",
")",
";",
"}"
] |
Generates a search index for the documentation.
|
[
"Generates",
"a",
"search",
"index",
"for",
"the",
"documentation",
"."
] |
12cca54de650b5782956486267d3de81f237c8d1
|
https://github.com/UCF/Athena-Framework/blob/12cca54de650b5782956486267d3de81f237c8d1/gulpfile.js#L185-L207
|
train
|
UCF/Athena-Framework
|
src/js/Stickyfill/stickyfill.js
|
fastCheck
|
function fastCheck() {
for (var i = watchArray.length - 1; i >= 0; i--) {
if (!watchArray[i].inited) continue;
var deltaTop = Math.abs(getDocOffsetTop(watchArray[i].clone) - watchArray[i].docOffsetTop),
deltaHeight = Math.abs(watchArray[i].parent.node.offsetHeight - watchArray[i].parent.height);
if (deltaTop >= 2 || deltaHeight >= 2) return false;
}
return true;
}
|
javascript
|
function fastCheck() {
for (var i = watchArray.length - 1; i >= 0; i--) {
if (!watchArray[i].inited) continue;
var deltaTop = Math.abs(getDocOffsetTop(watchArray[i].clone) - watchArray[i].docOffsetTop),
deltaHeight = Math.abs(watchArray[i].parent.node.offsetHeight - watchArray[i].parent.height);
if (deltaTop >= 2 || deltaHeight >= 2) return false;
}
return true;
}
|
[
"function",
"fastCheck",
"(",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"watchArray",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"if",
"(",
"!",
"watchArray",
"[",
"i",
"]",
".",
"inited",
")",
"continue",
";",
"var",
"deltaTop",
"=",
"Math",
".",
"abs",
"(",
"getDocOffsetTop",
"(",
"watchArray",
"[",
"i",
"]",
".",
"clone",
")",
"-",
"watchArray",
"[",
"i",
"]",
".",
"docOffsetTop",
")",
",",
"deltaHeight",
"=",
"Math",
".",
"abs",
"(",
"watchArray",
"[",
"i",
"]",
".",
"parent",
".",
"node",
".",
"offsetHeight",
"-",
"watchArray",
"[",
"i",
"]",
".",
"parent",
".",
"height",
")",
";",
"if",
"(",
"deltaTop",
">=",
"2",
"||",
"deltaHeight",
">=",
"2",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
checks whether stickies start or stop positions have changed
|
[
"checks",
"whether",
"stickies",
"start",
"or",
"stop",
"positions",
"have",
"changed"
] |
12cca54de650b5782956486267d3de81f237c8d1
|
https://github.com/UCF/Athena-Framework/blob/12cca54de650b5782956486267d3de81f237c8d1/src/js/Stickyfill/stickyfill.js#L111-L121
|
train
|
UCF/Athena-Framework
|
src/js/objectFitPolyfill/objectFitPolyfill.js
|
function($container) {
var styles = window.getComputedStyle($container, null);
var position = styles.getPropertyValue("position");
var overflow = styles.getPropertyValue("overflow");
var display = styles.getPropertyValue("display");
if (!position || position === "static") {
$container.style.position = "relative";
}
if (overflow !== "hidden") {
$container.style.overflow = "hidden";
}
// Guesstimating that people want the parent to act like full width/height wrapper here.
// Mostly attempts to target <picture> elements, which default to inline.
if (!display || display === "inline") {
$container.style.display = "block";
}
if ($container.clientHeight === 0) {
$container.style.height = "100%";
}
// Add a CSS class hook, in case people need to override styles for any reason.
if ($container.className.indexOf("object-fit-polyfill") === -1) {
$container.className = $container.className + " object-fit-polyfill";
}
}
|
javascript
|
function($container) {
var styles = window.getComputedStyle($container, null);
var position = styles.getPropertyValue("position");
var overflow = styles.getPropertyValue("overflow");
var display = styles.getPropertyValue("display");
if (!position || position === "static") {
$container.style.position = "relative";
}
if (overflow !== "hidden") {
$container.style.overflow = "hidden";
}
// Guesstimating that people want the parent to act like full width/height wrapper here.
// Mostly attempts to target <picture> elements, which default to inline.
if (!display || display === "inline") {
$container.style.display = "block";
}
if ($container.clientHeight === 0) {
$container.style.height = "100%";
}
// Add a CSS class hook, in case people need to override styles for any reason.
if ($container.className.indexOf("object-fit-polyfill") === -1) {
$container.className = $container.className + " object-fit-polyfill";
}
}
|
[
"function",
"(",
"$container",
")",
"{",
"var",
"styles",
"=",
"window",
".",
"getComputedStyle",
"(",
"$container",
",",
"null",
")",
";",
"var",
"position",
"=",
"styles",
".",
"getPropertyValue",
"(",
"\"position\"",
")",
";",
"var",
"overflow",
"=",
"styles",
".",
"getPropertyValue",
"(",
"\"overflow\"",
")",
";",
"var",
"display",
"=",
"styles",
".",
"getPropertyValue",
"(",
"\"display\"",
")",
";",
"if",
"(",
"!",
"position",
"||",
"position",
"===",
"\"static\"",
")",
"{",
"$container",
".",
"style",
".",
"position",
"=",
"\"relative\"",
";",
"}",
"if",
"(",
"overflow",
"!==",
"\"hidden\"",
")",
"{",
"$container",
".",
"style",
".",
"overflow",
"=",
"\"hidden\"",
";",
"}",
"if",
"(",
"!",
"display",
"||",
"display",
"===",
"\"inline\"",
")",
"{",
"$container",
".",
"style",
".",
"display",
"=",
"\"block\"",
";",
"}",
"if",
"(",
"$container",
".",
"clientHeight",
"===",
"0",
")",
"{",
"$container",
".",
"style",
".",
"height",
"=",
"\"100%\"",
";",
"}",
"if",
"(",
"$container",
".",
"className",
".",
"indexOf",
"(",
"\"object-fit-polyfill\"",
")",
"===",
"-",
"1",
")",
"{",
"$container",
".",
"className",
"=",
"$container",
".",
"className",
"+",
"\" object-fit-polyfill\"",
";",
"}",
"}"
] |
Check the container's parent element to make sure it will
correctly handle and clip absolutely positioned children
@param {node} $container - parent element
|
[
"Check",
"the",
"container",
"s",
"parent",
"element",
"to",
"make",
"sure",
"it",
"will",
"correctly",
"handle",
"and",
"clip",
"absolutely",
"positioned",
"children"
] |
12cca54de650b5782956486267d3de81f237c8d1
|
https://github.com/UCF/Athena-Framework/blob/12cca54de650b5782956486267d3de81f237c8d1/src/js/objectFitPolyfill/objectFitPolyfill.js#L35-L60
|
train
|
|
UCF/Athena-Framework
|
src/js/objectFitPolyfill/objectFitPolyfill.js
|
function(axis, $media, objectPosition) {
var position, other, start, end, side;
objectPosition = objectPosition.split(" ");
if (objectPosition.length < 2) {
objectPosition[1] = objectPosition[0];
}
if (axis === "x") {
position = objectPosition[0];
other = objectPosition[1];
start = "left";
end = "right";
side = $media.clientWidth;
}
else if (axis === "y") {
position = objectPosition[1];
other = objectPosition[0];
start = "top";
end = "bottom";
side = $media.clientHeight;
}
else {
return; // Neither x or y axis specified
}
if (position === start || other === start) {
$media.style[start] = "0";
return;
}
if (position === end || other === end) {
$media.style[end] = "0";
return;
}
if (position === "center" || position === "50%") {
$media.style[start] = "50%";
$media.style["margin-" + start] = (side / -2) + "px";
return;
}
// Percentage values (e.g., 30% 10%)
if (position.indexOf("%") >= 0) {
position = parseInt(position);
if (position < 50) {
$media.style[start] = position + "%";
$media.style["margin-" + start] = side * (position / -100) + "px";
}
else {
position = 100 - position;
$media.style[end] = position + "%";
$media.style["margin-" + end] = side * (position / -100) + "px";
}
return;
}
// Length-based values (e.g. 10px / 10em)
else {
$media.style[start] = position;
}
}
|
javascript
|
function(axis, $media, objectPosition) {
var position, other, start, end, side;
objectPosition = objectPosition.split(" ");
if (objectPosition.length < 2) {
objectPosition[1] = objectPosition[0];
}
if (axis === "x") {
position = objectPosition[0];
other = objectPosition[1];
start = "left";
end = "right";
side = $media.clientWidth;
}
else if (axis === "y") {
position = objectPosition[1];
other = objectPosition[0];
start = "top";
end = "bottom";
side = $media.clientHeight;
}
else {
return; // Neither x or y axis specified
}
if (position === start || other === start) {
$media.style[start] = "0";
return;
}
if (position === end || other === end) {
$media.style[end] = "0";
return;
}
if (position === "center" || position === "50%") {
$media.style[start] = "50%";
$media.style["margin-" + start] = (side / -2) + "px";
return;
}
// Percentage values (e.g., 30% 10%)
if (position.indexOf("%") >= 0) {
position = parseInt(position);
if (position < 50) {
$media.style[start] = position + "%";
$media.style["margin-" + start] = side * (position / -100) + "px";
}
else {
position = 100 - position;
$media.style[end] = position + "%";
$media.style["margin-" + end] = side * (position / -100) + "px";
}
return;
}
// Length-based values (e.g. 10px / 10em)
else {
$media.style[start] = position;
}
}
|
[
"function",
"(",
"axis",
",",
"$media",
",",
"objectPosition",
")",
"{",
"var",
"position",
",",
"other",
",",
"start",
",",
"end",
",",
"side",
";",
"objectPosition",
"=",
"objectPosition",
".",
"split",
"(",
"\" \"",
")",
";",
"if",
"(",
"objectPosition",
".",
"length",
"<",
"2",
")",
"{",
"objectPosition",
"[",
"1",
"]",
"=",
"objectPosition",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"axis",
"===",
"\"x\"",
")",
"{",
"position",
"=",
"objectPosition",
"[",
"0",
"]",
";",
"other",
"=",
"objectPosition",
"[",
"1",
"]",
";",
"start",
"=",
"\"left\"",
";",
"end",
"=",
"\"right\"",
";",
"side",
"=",
"$media",
".",
"clientWidth",
";",
"}",
"else",
"if",
"(",
"axis",
"===",
"\"y\"",
")",
"{",
"position",
"=",
"objectPosition",
"[",
"1",
"]",
";",
"other",
"=",
"objectPosition",
"[",
"0",
"]",
";",
"start",
"=",
"\"top\"",
";",
"end",
"=",
"\"bottom\"",
";",
"side",
"=",
"$media",
".",
"clientHeight",
";",
"}",
"else",
"{",
"return",
";",
"}",
"if",
"(",
"position",
"===",
"start",
"||",
"other",
"===",
"start",
")",
"{",
"$media",
".",
"style",
"[",
"start",
"]",
"=",
"\"0\"",
";",
"return",
";",
"}",
"if",
"(",
"position",
"===",
"end",
"||",
"other",
"===",
"end",
")",
"{",
"$media",
".",
"style",
"[",
"end",
"]",
"=",
"\"0\"",
";",
"return",
";",
"}",
"if",
"(",
"position",
"===",
"\"center\"",
"||",
"position",
"===",
"\"50%\"",
")",
"{",
"$media",
".",
"style",
"[",
"start",
"]",
"=",
"\"50%\"",
";",
"$media",
".",
"style",
"[",
"\"margin-\"",
"+",
"start",
"]",
"=",
"(",
"side",
"/",
"-",
"2",
")",
"+",
"\"px\"",
";",
"return",
";",
"}",
"if",
"(",
"position",
".",
"indexOf",
"(",
"\"%\"",
")",
">=",
"0",
")",
"{",
"position",
"=",
"parseInt",
"(",
"position",
")",
";",
"if",
"(",
"position",
"<",
"50",
")",
"{",
"$media",
".",
"style",
"[",
"start",
"]",
"=",
"position",
"+",
"\"%\"",
";",
"$media",
".",
"style",
"[",
"\"margin-\"",
"+",
"start",
"]",
"=",
"side",
"*",
"(",
"position",
"/",
"-",
"100",
")",
"+",
"\"px\"",
";",
"}",
"else",
"{",
"position",
"=",
"100",
"-",
"position",
";",
"$media",
".",
"style",
"[",
"end",
"]",
"=",
"position",
"+",
"\"%\"",
";",
"$media",
".",
"style",
"[",
"\"margin-\"",
"+",
"end",
"]",
"=",
"side",
"*",
"(",
"position",
"/",
"-",
"100",
")",
"+",
"\"px\"",
";",
"}",
"return",
";",
"}",
"else",
"{",
"$media",
".",
"style",
"[",
"start",
"]",
"=",
"position",
";",
"}",
"}"
] |
Calculate & set object-position
@param {string} axis - either "x" or "y"
@param {node} $media - img or video element
@param {string} objectPosition - e.g. "50% 50%", "top bottom"
|
[
"Calculate",
"&",
"set",
"object",
"-",
"position"
] |
12cca54de650b5782956486267d3de81f237c8d1
|
https://github.com/UCF/Athena-Framework/blob/12cca54de650b5782956486267d3de81f237c8d1/src/js/objectFitPolyfill/objectFitPolyfill.js#L101-L164
|
train
|
|
UCF/Athena-Framework
|
src/js/objectFitPolyfill/objectFitPolyfill.js
|
function($media) {
// Fallbacks, IE 10- data
var fit = ($media.dataset) ? $media.dataset.objectFit : $media.getAttribute("data-object-fit");
var position = ($media.dataset) ? $media.dataset.objectPosition : $media.getAttribute("data-object-position");
fit = fit || "cover";
position = position || "50% 50%";
// If necessary, make the parent container work with absolutely positioned elements
var $container = $media.parentNode;
checkParentContainer($container);
// Check for any pre-set CSS which could mess up image calculations
checkMediaProperties($media);
// Mathematically figure out which side needs covering, and add CSS positioning & centering
$media.style.position = "absolute";
$media.style.height = "100%";
$media.style.width = "auto";
if (fit === "scale-down") {
$media.style.height = "auto";
if (
$media.clientWidth < $container.clientWidth &&
$media.clientHeight < $container.clientHeight
) {
setPosition("x", $media, position);
setPosition("y", $media, position);
}
else {
fit = "contain";
$media.style.height = "100%";
}
}
if (fit === "none") {
$media.style.width = "auto";
$media.style.height = "auto";
setPosition("x", $media, position);
setPosition("y", $media, position);
}
else if (
fit === "cover" && $media.clientWidth > $container.clientWidth ||
fit === "contain" && $media.clientWidth < $container.clientWidth
) {
$media.style.top = "0";
$media.style.marginTop = "0";
setPosition("x", $media, position);
}
else if (fit !== "scale-down") {
$media.style.width = "100%";
$media.style.height = "auto";
$media.style.left = "0";
$media.style.marginLeft = "0";
setPosition("y", $media, position);
}
}
|
javascript
|
function($media) {
// Fallbacks, IE 10- data
var fit = ($media.dataset) ? $media.dataset.objectFit : $media.getAttribute("data-object-fit");
var position = ($media.dataset) ? $media.dataset.objectPosition : $media.getAttribute("data-object-position");
fit = fit || "cover";
position = position || "50% 50%";
// If necessary, make the parent container work with absolutely positioned elements
var $container = $media.parentNode;
checkParentContainer($container);
// Check for any pre-set CSS which could mess up image calculations
checkMediaProperties($media);
// Mathematically figure out which side needs covering, and add CSS positioning & centering
$media.style.position = "absolute";
$media.style.height = "100%";
$media.style.width = "auto";
if (fit === "scale-down") {
$media.style.height = "auto";
if (
$media.clientWidth < $container.clientWidth &&
$media.clientHeight < $container.clientHeight
) {
setPosition("x", $media, position);
setPosition("y", $media, position);
}
else {
fit = "contain";
$media.style.height = "100%";
}
}
if (fit === "none") {
$media.style.width = "auto";
$media.style.height = "auto";
setPosition("x", $media, position);
setPosition("y", $media, position);
}
else if (
fit === "cover" && $media.clientWidth > $container.clientWidth ||
fit === "contain" && $media.clientWidth < $container.clientWidth
) {
$media.style.top = "0";
$media.style.marginTop = "0";
setPosition("x", $media, position);
}
else if (fit !== "scale-down") {
$media.style.width = "100%";
$media.style.height = "auto";
$media.style.left = "0";
$media.style.marginLeft = "0";
setPosition("y", $media, position);
}
}
|
[
"function",
"(",
"$media",
")",
"{",
"var",
"fit",
"=",
"(",
"$media",
".",
"dataset",
")",
"?",
"$media",
".",
"dataset",
".",
"objectFit",
":",
"$media",
".",
"getAttribute",
"(",
"\"data-object-fit\"",
")",
";",
"var",
"position",
"=",
"(",
"$media",
".",
"dataset",
")",
"?",
"$media",
".",
"dataset",
".",
"objectPosition",
":",
"$media",
".",
"getAttribute",
"(",
"\"data-object-position\"",
")",
";",
"fit",
"=",
"fit",
"||",
"\"cover\"",
";",
"position",
"=",
"position",
"||",
"\"50% 50%\"",
";",
"var",
"$container",
"=",
"$media",
".",
"parentNode",
";",
"checkParentContainer",
"(",
"$container",
")",
";",
"checkMediaProperties",
"(",
"$media",
")",
";",
"$media",
".",
"style",
".",
"position",
"=",
"\"absolute\"",
";",
"$media",
".",
"style",
".",
"height",
"=",
"\"100%\"",
";",
"$media",
".",
"style",
".",
"width",
"=",
"\"auto\"",
";",
"if",
"(",
"fit",
"===",
"\"scale-down\"",
")",
"{",
"$media",
".",
"style",
".",
"height",
"=",
"\"auto\"",
";",
"if",
"(",
"$media",
".",
"clientWidth",
"<",
"$container",
".",
"clientWidth",
"&&",
"$media",
".",
"clientHeight",
"<",
"$container",
".",
"clientHeight",
")",
"{",
"setPosition",
"(",
"\"x\"",
",",
"$media",
",",
"position",
")",
";",
"setPosition",
"(",
"\"y\"",
",",
"$media",
",",
"position",
")",
";",
"}",
"else",
"{",
"fit",
"=",
"\"contain\"",
";",
"$media",
".",
"style",
".",
"height",
"=",
"\"100%\"",
";",
"}",
"}",
"if",
"(",
"fit",
"===",
"\"none\"",
")",
"{",
"$media",
".",
"style",
".",
"width",
"=",
"\"auto\"",
";",
"$media",
".",
"style",
".",
"height",
"=",
"\"auto\"",
";",
"setPosition",
"(",
"\"x\"",
",",
"$media",
",",
"position",
")",
";",
"setPosition",
"(",
"\"y\"",
",",
"$media",
",",
"position",
")",
";",
"}",
"else",
"if",
"(",
"fit",
"===",
"\"cover\"",
"&&",
"$media",
".",
"clientWidth",
">",
"$container",
".",
"clientWidth",
"||",
"fit",
"===",
"\"contain\"",
"&&",
"$media",
".",
"clientWidth",
"<",
"$container",
".",
"clientWidth",
")",
"{",
"$media",
".",
"style",
".",
"top",
"=",
"\"0\"",
";",
"$media",
".",
"style",
".",
"marginTop",
"=",
"\"0\"",
";",
"setPosition",
"(",
"\"x\"",
",",
"$media",
",",
"position",
")",
";",
"}",
"else",
"if",
"(",
"fit",
"!==",
"\"scale-down\"",
")",
"{",
"$media",
".",
"style",
".",
"width",
"=",
"\"100%\"",
";",
"$media",
".",
"style",
".",
"height",
"=",
"\"auto\"",
";",
"$media",
".",
"style",
".",
"left",
"=",
"\"0\"",
";",
"$media",
".",
"style",
".",
"marginLeft",
"=",
"\"0\"",
";",
"setPosition",
"(",
"\"y\"",
",",
"$media",
",",
"position",
")",
";",
"}",
"}"
] |
Calculate & set object-fit
@param {node} $media - img/video/picture element
|
[
"Calculate",
"&",
"set",
"object",
"-",
"fit"
] |
12cca54de650b5782956486267d3de81f237c8d1
|
https://github.com/UCF/Athena-Framework/blob/12cca54de650b5782956486267d3de81f237c8d1/src/js/objectFitPolyfill/objectFitPolyfill.js#L171-L227
|
train
|
|
remusao/tldts
|
bin/builders/hashes.js
|
fastHash
|
function fastHash(str) {
let hash = 5381;
for (let j = str.length - 1; j >= 0; j -= 1) {
hash = (hash * 33) ^ str.charCodeAt(j);
}
return hash >>> 0;
}
|
javascript
|
function fastHash(str) {
let hash = 5381;
for (let j = str.length - 1; j >= 0; j -= 1) {
hash = (hash * 33) ^ str.charCodeAt(j);
}
return hash >>> 0;
}
|
[
"function",
"fastHash",
"(",
"str",
")",
"{",
"let",
"hash",
"=",
"5381",
";",
"for",
"(",
"let",
"j",
"=",
"str",
".",
"length",
"-",
"1",
";",
"j",
">=",
"0",
";",
"j",
"-=",
"1",
")",
"{",
"hash",
"=",
"(",
"hash",
"*",
"33",
")",
"^",
"str",
".",
"charCodeAt",
"(",
"j",
")",
";",
"}",
"return",
"hash",
">>>",
"0",
";",
"}"
] |
Compute 32 bits hash of `str` backward.
|
[
"Compute",
"32",
"bits",
"hash",
"of",
"str",
"backward",
"."
] |
a1036a05fa0dbef44c89fa52ac8eec9af5706be1
|
https://github.com/remusao/tldts/blob/a1036a05fa0dbef44c89fa52ac8eec9af5706be1/bin/builders/hashes.js#L92-L98
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.