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
imbo/imboclient-js
gulpfile.js
browserSpecific
function browserSpecific() { var data = ''; return through( function(buf) { data += buf; }, function() { this.queue(data.replace(/\.\/node\//g, './browser/')); this.queue(null); } ); }
javascript
function browserSpecific() { var data = ''; return through( function(buf) { data += buf; }, function() { this.queue(data.replace(/\.\/node\//g, './browser/')); this.queue(null); } ); }
[ "function", "browserSpecific", "(", ")", "{", "var", "data", "=", "''", ";", "return", "through", "(", "function", "(", "buf", ")", "{", "data", "+=", "buf", ";", "}", ",", "function", "(", ")", "{", "this", ".", "queue", "(", "data", ".", "replace", "(", "/", "\\.\\/node\\/", "/", "g", ",", "'./browser/'", ")", ")", ";", "this", ".", "queue", "(", "null", ")", ";", "}", ")", ";", "}" ]
Replace node-specific components with browser-specific ones
[ "Replace", "node", "-", "specific", "components", "with", "browser", "-", "specific", "ones" ]
809dcc489528dca9d67f49b03b612a99704339d0
https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/gulpfile.js#L23-L34
train
getlackey/mongoose-ref-validator
lib/index.js
setMiddleware
function setMiddleware(Model, modelName, path) { var RefModel; // We only apply the middleware on the provided // paths in the plugin options. if (opts.onDeleteRestrict.indexOf(path) === -1) { return; } RefModel = models[modelName]; RefModel.schema.pre('remove', function (next) { var doc = this, q = {}; q[path] = doc._id; Model .findOne(q) .exec() .then(function (doc) { if (doc) { return next(new Error('Unable to delete as ref exist in ' + Model.modelName + ' id:' + doc._id)); } next(); }, next); }); }
javascript
function setMiddleware(Model, modelName, path) { var RefModel; // We only apply the middleware on the provided // paths in the plugin options. if (opts.onDeleteRestrict.indexOf(path) === -1) { return; } RefModel = models[modelName]; RefModel.schema.pre('remove', function (next) { var doc = this, q = {}; q[path] = doc._id; Model .findOne(q) .exec() .then(function (doc) { if (doc) { return next(new Error('Unable to delete as ref exist in ' + Model.modelName + ' id:' + doc._id)); } next(); }, next); }); }
[ "function", "setMiddleware", "(", "Model", ",", "modelName", ",", "path", ")", "{", "var", "RefModel", ";", "if", "(", "opts", ".", "onDeleteRestrict", ".", "indexOf", "(", "path", ")", "===", "-", "1", ")", "{", "return", ";", "}", "RefModel", "=", "models", "[", "modelName", "]", ";", "RefModel", ".", "schema", ".", "pre", "(", "'remove'", ",", "function", "(", "next", ")", "{", "var", "doc", "=", "this", ",", "q", "=", "{", "}", ";", "q", "[", "path", "]", "=", "doc", ".", "_id", ";", "Model", ".", "findOne", "(", "q", ")", ".", "exec", "(", ")", ".", "then", "(", "function", "(", "doc", ")", "{", "if", "(", "doc", ")", "{", "return", "next", "(", "new", "Error", "(", "'Unable to delete as ref exist in '", "+", "Model", ".", "modelName", "+", "' id:'", "+", "doc", ".", "_id", ")", ")", ";", "}", "next", "(", ")", ";", "}", ",", "next", ")", ";", "}", ")", ";", "}" ]
Sets middleware on the referenced models @param {object} Model - The current model, where this plugin is running @param {string} modelName - the model that is being referenced @param {string} path - the property with the reference
[ "Sets", "middleware", "on", "the", "referenced", "models" ]
e21ac9c19d07b908991de8c8a295ebe1ca176b08
https://github.com/getlackey/mongoose-ref-validator/blob/e21ac9c19d07b908991de8c8a295ebe1ca176b08/lib/index.js#L81-L107
train
seykron/json-index
lib/EntryIterator.js
function (start, end, force) { var bytesRead; if (end - start > config.bufferSize) { return reject(new Error("Range exceeds the max buffer size")); } if (force || start < currentRange.start || (start > currentRange.end)) { bytesRead = fs.readSync(fd, buffer, 0, config.bufferSize, start); currentRange.start = start; currentRange.end = start + bytesRead; debug("buffering new range: %s", JSON.stringify(currentRange)); } }
javascript
function (start, end, force) { var bytesRead; if (end - start > config.bufferSize) { return reject(new Error("Range exceeds the max buffer size")); } if (force || start < currentRange.start || (start > currentRange.end)) { bytesRead = fs.readSync(fd, buffer, 0, config.bufferSize, start); currentRange.start = start; currentRange.end = start + bytesRead; debug("buffering new range: %s", JSON.stringify(currentRange)); } }
[ "function", "(", "start", ",", "end", ",", "force", ")", "{", "var", "bytesRead", ";", "if", "(", "end", "-", "start", ">", "config", ".", "bufferSize", ")", "{", "return", "reject", "(", "new", "Error", "(", "\"Range exceeds the max buffer size\"", ")", ")", ";", "}", "if", "(", "force", "||", "start", "<", "currentRange", ".", "start", "||", "(", "start", ">", "currentRange", ".", "end", ")", ")", "{", "bytesRead", "=", "fs", ".", "readSync", "(", "fd", ",", "buffer", ",", "0", ",", "config", ".", "bufferSize", ",", "start", ")", ";", "currentRange", ".", "start", "=", "start", ";", "currentRange", ".", "end", "=", "start", "+", "bytesRead", ";", "debug", "(", "\"buffering new range: %s\"", ",", "JSON", ".", "stringify", "(", "currentRange", ")", ")", ";", "}", "}" ]
Synchrounously updates the cache with a new range of data if the required range is not within the current cache. @param {Number} start Start position of the required range. Cannot be null. @param {Number} end End position of the required range. Cannot be null. @param {Boolean} force Indicates whether to force the cache update.
[ "Synchrounously", "updates", "the", "cache", "with", "a", "new", "range", "of", "data", "if", "the", "required", "range", "is", "not", "within", "the", "current", "cache", "." ]
b7f354197fc7129749032695e244f58954aa921d
https://github.com/seykron/json-index/blob/b7f354197fc7129749032695e244f58954aa921d/lib/EntryIterator.js#L29-L41
train
seykron/json-index
lib/EntryIterator.js
function (start, end) { var offsetStart; var offsetEnd; loadBufferIfRequired(start, end); offsetStart = start - currentRange.start; offsetEnd = offsetStart + (end - start); return buffer.slice(offsetStart, offsetEnd); }
javascript
function (start, end) { var offsetStart; var offsetEnd; loadBufferIfRequired(start, end); offsetStart = start - currentRange.start; offsetEnd = offsetStart + (end - start); return buffer.slice(offsetStart, offsetEnd); }
[ "function", "(", "start", ",", "end", ")", "{", "var", "offsetStart", ";", "var", "offsetEnd", ";", "loadBufferIfRequired", "(", "start", ",", "end", ")", ";", "offsetStart", "=", "start", "-", "currentRange", ".", "start", ";", "offsetEnd", "=", "offsetStart", "+", "(", "end", "-", "start", ")", ";", "return", "buffer", ".", "slice", "(", "offsetStart", ",", "offsetEnd", ")", ";", "}" ]
Reads data range from the file into the buffer. @param {Number} start Absolute start position. Cannot be null. @param {Number} end Absolute end position. Cannot be null.
[ "Reads", "data", "range", "from", "the", "file", "into", "the", "buffer", "." ]
b7f354197fc7129749032695e244f58954aa921d
https://github.com/seykron/json-index/blob/b7f354197fc7129749032695e244f58954aa921d/lib/EntryIterator.js#L47-L57
train
seykron/json-index
lib/EntryIterator.js
function (index) { var rawItem; var position = positions[index]; try { rawItem = readEntry(position.start, position.end); return JSON.parse(rawItem); } catch (ex) { debug("ERROR reading item: %s -> %s", ex, rawItem); } }
javascript
function (index) { var rawItem; var position = positions[index]; try { rawItem = readEntry(position.start, position.end); return JSON.parse(rawItem); } catch (ex) { debug("ERROR reading item: %s -> %s", ex, rawItem); } }
[ "function", "(", "index", ")", "{", "var", "rawItem", ";", "var", "position", "=", "positions", "[", "index", "]", ";", "try", "{", "rawItem", "=", "readEntry", "(", "position", ".", "start", ",", "position", ".", "end", ")", ";", "return", "JSON", ".", "parse", "(", "rawItem", ")", ";", "}", "catch", "(", "ex", ")", "{", "debug", "(", "\"ERROR reading item: %s -> %s\"", ",", "ex", ",", "rawItem", ")", ";", "}", "}" ]
Lazily retrives an item with the specified index. @param {Number} index Required item index. Cannot be null.
[ "Lazily", "retrives", "an", "item", "with", "the", "specified", "index", "." ]
b7f354197fc7129749032695e244f58954aa921d
https://github.com/seykron/json-index/blob/b7f354197fc7129749032695e244f58954aa921d/lib/EntryIterator.js#L62-L72
train
rootsdev/gedcomx-js
src/atom/AtomContent.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomContent)){ return new AtomContent(json); } // If the given object is already an instance then just return it. DON'T copy it. if(AtomContent.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomContent)){ return new AtomContent(json); } // If the given object is already an instance then just return it. DON'T copy it. if(AtomContent.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AtomContent", ")", ")", "{", "return", "new", "AtomContent", "(", "json", ")", ";", "}", "if", "(", "AtomContent", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
The content of an entry. @see {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/atom-model-specification.md#atom-json-media-type|GEDCOM X Atom JSON Spec} @see {@link https://tools.ietf.org/html/rfc4287#section-4.1.3|RFC 4287} @class AtomContent @extends AtomCommon @param {Object} [json]
[ "The", "content", "of", "an", "entry", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/atom/AtomContent.js#L16-L29
train
oipwg/oip-index
src/util.js
isValidWIF
function isValidWIF (key, network) { try { let dec = wif.decode(key); if (network) { return dec.version === network.wif } else { return true } } catch (e) { console.error(e); return false } }
javascript
function isValidWIF (key, network) { try { let dec = wif.decode(key); if (network) { return dec.version === network.wif } else { return true } } catch (e) { console.error(e); return false } }
[ "function", "isValidWIF", "(", "key", ",", "network", ")", "{", "try", "{", "let", "dec", "=", "wif", ".", "decode", "(", "key", ")", ";", "if", "(", "network", ")", "{", "return", "dec", ".", "version", "===", "network", ".", "wif", "}", "else", "{", "return", "true", "}", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "e", ")", ";", "return", "false", "}", "}" ]
Check if a WIF is valid for a specific CoinNetwork @param {string} key - Base58 WIF Private Key @param {CoinNetwork} network @return {Boolean}
[ "Check", "if", "a", "WIF", "is", "valid", "for", "a", "specific", "CoinNetwork" ]
155d4883d8e2ac144f99c615ef476ae9f6cf288f
https://github.com/oipwg/oip-index/blob/155d4883d8e2ac144f99c615ef476ae9f6cf288f/src/util.js#L10-L23
train
KapIT/observe-shim
lib/observe-shim.js
_cleanObserver
function _cleanObserver(observer) { if (!attachedNotifierCountMap.get(observer) && !pendingChangesMap.has(observer)) { attachedNotifierCountMap.delete(observer); var index = observerCallbacks.indexOf(observer); if (index !== -1) { observerCallbacks.splice(index, 1); } } }
javascript
function _cleanObserver(observer) { if (!attachedNotifierCountMap.get(observer) && !pendingChangesMap.has(observer)) { attachedNotifierCountMap.delete(observer); var index = observerCallbacks.indexOf(observer); if (index !== -1) { observerCallbacks.splice(index, 1); } } }
[ "function", "_cleanObserver", "(", "observer", ")", "{", "if", "(", "!", "attachedNotifierCountMap", ".", "get", "(", "observer", ")", "&&", "!", "pendingChangesMap", ".", "has", "(", "observer", ")", ")", "{", "attachedNotifierCountMap", ".", "delete", "(", "observer", ")", ";", "var", "index", "=", "observerCallbacks", ".", "indexOf", "(", "observer", ")", ";", "if", "(", "index", "!==", "-", "1", ")", "{", "observerCallbacks", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "}", "}" ]
Remove reference all reference to an observer callback, if this one is not used anymore. In the proposal the ObserverCallBack has a weak reference over observers, Without this possibility we need to clean this list to avoid memory leak
[ "Remove", "reference", "all", "reference", "to", "an", "observer", "callback", "if", "this", "one", "is", "not", "used", "anymore", ".", "In", "the", "proposal", "the", "ObserverCallBack", "has", "a", "weak", "reference", "over", "observers", "Without", "this", "possibility", "we", "need", "to", "clean", "this", "list", "to", "avoid", "memory", "leak" ]
75e8ea887c38bd1540fe4989a17b6e3751d7c7e5
https://github.com/KapIT/observe-shim/blob/75e8ea887c38bd1540fe4989a17b6e3751d7c7e5/lib/observe-shim.js#L343-L351
train
rackerlabs/zk-ultralight
ultralight.js
function(callback) { if (self._cxnState !== self.cxnStates.CONNECTED) { callback(new Error("(2) Error occurred while attempting to lock "+ name)); return; } try { // client doesn't like paths ending in /, so chop it off if lockpath != '/' self._zk.mkdirp(lockpath.length <= 1 ? lockpath : lockpath.slice(0, -1), callback); } catch (err) { callback(err); } }
javascript
function(callback) { if (self._cxnState !== self.cxnStates.CONNECTED) { callback(new Error("(2) Error occurred while attempting to lock "+ name)); return; } try { // client doesn't like paths ending in /, so chop it off if lockpath != '/' self._zk.mkdirp(lockpath.length <= 1 ? lockpath : lockpath.slice(0, -1), callback); } catch (err) { callback(err); } }
[ "function", "(", "callback", ")", "{", "if", "(", "self", ".", "_cxnState", "!==", "self", ".", "cxnStates", ".", "CONNECTED", ")", "{", "callback", "(", "new", "Error", "(", "\"(2) Error occurred while attempting to lock \"", "+", "name", ")", ")", ";", "return", ";", "}", "try", "{", "self", ".", "_zk", ".", "mkdirp", "(", "lockpath", ".", "length", "<=", "1", "?", "lockpath", ":", "lockpath", ".", "slice", "(", "0", ",", "-", "1", ")", ",", "callback", ")", ";", "}", "catch", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "}" ]
ensure the parent path exists
[ "ensure", "the", "parent", "path", "exists" ]
5295f0a891df42e7fafab7442461c6fe9a8538d0
https://github.com/rackerlabs/zk-ultralight/blob/5295f0a891df42e7fafab7442461c6fe9a8538d0/ultralight.js#L267-L278
train
savjs/sav-flux
examples/flux-todo-riot/bundle.js
$$
function $$(selector, ctx) { return Array.prototype.slice.call((ctx || document).querySelectorAll(selector)) }
javascript
function $$(selector, ctx) { return Array.prototype.slice.call((ctx || document).querySelectorAll(selector)) }
[ "function", "$$", "(", "selector", ",", "ctx", ")", "{", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "(", "ctx", "||", "document", ")", ".", "querySelectorAll", "(", "selector", ")", ")", "}" ]
Shorter and fast way to select multiple nodes in the DOM @param { String } selector - DOM selector @param { Object } ctx - DOM node where the targets of our search will is located @returns { Object } dom nodes found
[ "Shorter", "and", "fast", "way", "to", "select", "multiple", "nodes", "in", "the", "DOM" ]
d8f547a04467c8e3e2524bde95db0b7218b98be2
https://github.com/savjs/sav-flux/blob/d8f547a04467c8e3e2524bde95db0b7218b98be2/examples/flux-todo-riot/bundle.js#L1416-L1418
train
savjs/sav-flux
examples/flux-todo-riot/bundle.js
toggleVisibility
function toggleVisibility(dom, show) { dom.style.display = show ? '' : 'none'; dom['hidden'] = show ? false : true; }
javascript
function toggleVisibility(dom, show) { dom.style.display = show ? '' : 'none'; dom['hidden'] = show ? false : true; }
[ "function", "toggleVisibility", "(", "dom", ",", "show", ")", "{", "dom", ".", "style", ".", "display", "=", "show", "?", "''", ":", "'none'", ";", "dom", "[", "'hidden'", "]", "=", "show", "?", "false", ":", "true", ";", "}" ]
Toggle the visibility of any DOM node @param { Object } dom - DOM node we want to hide @param { Boolean } show - do we want to show it?
[ "Toggle", "the", "visibility", "of", "any", "DOM", "node" ]
d8f547a04467c8e3e2524bde95db0b7218b98be2
https://github.com/savjs/sav-flux/blob/d8f547a04467c8e3e2524bde95db0b7218b98be2/examples/flux-todo-riot/bundle.js#L1488-L1491
train
savjs/sav-flux
examples/flux-todo-riot/bundle.js
setAttr
function setAttr(dom, name, val) { var xlink = XLINK_REGEX.exec(name); if (xlink && xlink[1]) { dom.setAttributeNS(XLINK_NS, xlink[1], val); } else { dom.setAttribute(name, val); } }
javascript
function setAttr(dom, name, val) { var xlink = XLINK_REGEX.exec(name); if (xlink && xlink[1]) { dom.setAttributeNS(XLINK_NS, xlink[1], val); } else { dom.setAttribute(name, val); } }
[ "function", "setAttr", "(", "dom", ",", "name", ",", "val", ")", "{", "var", "xlink", "=", "XLINK_REGEX", ".", "exec", "(", "name", ")", ";", "if", "(", "xlink", "&&", "xlink", "[", "1", "]", ")", "{", "dom", ".", "setAttributeNS", "(", "XLINK_NS", ",", "xlink", "[", "1", "]", ",", "val", ")", ";", "}", "else", "{", "dom", ".", "setAttribute", "(", "name", ",", "val", ")", ";", "}", "}" ]
Set any DOM attribute @param { Object } dom - DOM node we want to update @param { String } name - name of the property we want to set @param { String } val - value of the property we want to set
[ "Set", "any", "DOM", "attribute" ]
d8f547a04467c8e3e2524bde95db0b7218b98be2
https://github.com/savjs/sav-flux/blob/d8f547a04467c8e3e2524bde95db0b7218b98be2/examples/flux-todo-riot/bundle.js#L1531-L1537
train
savjs/sav-flux
examples/flux-todo-riot/bundle.js
defineProperty
function defineProperty(el, key, value, options) { Object.defineProperty(el, key, extend({ value: value, enumerable: false, writable: false, configurable: true }, options)); return el }
javascript
function defineProperty(el, key, value, options) { Object.defineProperty(el, key, extend({ value: value, enumerable: false, writable: false, configurable: true }, options)); return el }
[ "function", "defineProperty", "(", "el", ",", "key", ",", "value", ",", "options", ")", "{", "Object", ".", "defineProperty", "(", "el", ",", "key", ",", "extend", "(", "{", "value", ":", "value", ",", "enumerable", ":", "false", ",", "writable", ":", "false", ",", "configurable", ":", "true", "}", ",", "options", ")", ")", ";", "return", "el", "}" ]
Helper function to set an immutable property @param { Object } el - object where the new property will be set @param { String } key - object key where the new property will be stored @param { * } value - value of the new property @param { Object } options - set the propery overriding the default options @returns { Object } - the initial object
[ "Helper", "function", "to", "set", "an", "immutable", "property" ]
d8f547a04467c8e3e2524bde95db0b7218b98be2
https://github.com/savjs/sav-flux/blob/d8f547a04467c8e3e2524bde95db0b7218b98be2/examples/flux-todo-riot/bundle.js#L2377-L2385
train
savjs/sav-flux
examples/flux-todo-riot/bundle.js
handleEvent
function handleEvent(dom, handler, e) { var ptag = this.__.parent, item = this.__.item; if (!item) { while (ptag && !item) { item = ptag.__.item; ptag = ptag.__.parent; } } // override the event properties /* istanbul ignore next */ if (isWritable(e, 'currentTarget')) { e.currentTarget = dom; } /* istanbul ignore next */ if (isWritable(e, 'target')) { e.target = e.srcElement; } /* istanbul ignore next */ if (isWritable(e, 'which')) { e.which = e.charCode || e.keyCode; } e.item = item; handler.call(this, e); // avoid auto updates if (!settings$1.autoUpdate) { return } if (!e.preventUpdate) { var p = getImmediateCustomParentTag(this); // fixes #2083 if (p.isMounted) { p.update(); } } }
javascript
function handleEvent(dom, handler, e) { var ptag = this.__.parent, item = this.__.item; if (!item) { while (ptag && !item) { item = ptag.__.item; ptag = ptag.__.parent; } } // override the event properties /* istanbul ignore next */ if (isWritable(e, 'currentTarget')) { e.currentTarget = dom; } /* istanbul ignore next */ if (isWritable(e, 'target')) { e.target = e.srcElement; } /* istanbul ignore next */ if (isWritable(e, 'which')) { e.which = e.charCode || e.keyCode; } e.item = item; handler.call(this, e); // avoid auto updates if (!settings$1.autoUpdate) { return } if (!e.preventUpdate) { var p = getImmediateCustomParentTag(this); // fixes #2083 if (p.isMounted) { p.update(); } } }
[ "function", "handleEvent", "(", "dom", ",", "handler", ",", "e", ")", "{", "var", "ptag", "=", "this", ".", "__", ".", "parent", ",", "item", "=", "this", ".", "__", ".", "item", ";", "if", "(", "!", "item", ")", "{", "while", "(", "ptag", "&&", "!", "item", ")", "{", "item", "=", "ptag", ".", "__", ".", "item", ";", "ptag", "=", "ptag", ".", "__", ".", "parent", ";", "}", "}", "if", "(", "isWritable", "(", "e", ",", "'currentTarget'", ")", ")", "{", "e", ".", "currentTarget", "=", "dom", ";", "}", "if", "(", "isWritable", "(", "e", ",", "'target'", ")", ")", "{", "e", ".", "target", "=", "e", ".", "srcElement", ";", "}", "if", "(", "isWritable", "(", "e", ",", "'which'", ")", ")", "{", "e", ".", "which", "=", "e", ".", "charCode", "||", "e", ".", "keyCode", ";", "}", "e", ".", "item", "=", "item", ";", "handler", ".", "call", "(", "this", ",", "e", ")", ";", "if", "(", "!", "settings$1", ".", "autoUpdate", ")", "{", "return", "}", "if", "(", "!", "e", ".", "preventUpdate", ")", "{", "var", "p", "=", "getImmediateCustomParentTag", "(", "this", ")", ";", "if", "(", "p", ".", "isMounted", ")", "{", "p", ".", "update", "(", ")", ";", "}", "}", "}" ]
Trigger DOM events @param { HTMLElement } dom - dom element target of the event @param { Function } handler - user function @param { Object } e - event object
[ "Trigger", "DOM", "events" ]
d8f547a04467c8e3e2524bde95db0b7218b98be2
https://github.com/savjs/sav-flux/blob/d8f547a04467c8e3e2524bde95db0b7218b98be2/examples/flux-todo-riot/bundle.js#L2432-L2462
train
savjs/sav-flux
examples/flux-todo-riot/bundle.js
inheritFrom
function inheritFrom(target, propsInSyncWithParent) { var this$1 = this; each(Object.keys(target), function (k) { // some properties must be always in sync with the parent tag var mustSync = !isReservedName(k) && contains(propsInSyncWithParent, k); if (isUndefined(this$1[k]) || mustSync) { // track the property to keep in sync // so we can keep it updated if (!mustSync) { propsInSyncWithParent.push(k); } this$1[k] = target[k]; } }); }
javascript
function inheritFrom(target, propsInSyncWithParent) { var this$1 = this; each(Object.keys(target), function (k) { // some properties must be always in sync with the parent tag var mustSync = !isReservedName(k) && contains(propsInSyncWithParent, k); if (isUndefined(this$1[k]) || mustSync) { // track the property to keep in sync // so we can keep it updated if (!mustSync) { propsInSyncWithParent.push(k); } this$1[k] = target[k]; } }); }
[ "function", "inheritFrom", "(", "target", ",", "propsInSyncWithParent", ")", "{", "var", "this$1", "=", "this", ";", "each", "(", "Object", ".", "keys", "(", "target", ")", ",", "function", "(", "k", ")", "{", "var", "mustSync", "=", "!", "isReservedName", "(", "k", ")", "&&", "contains", "(", "propsInSyncWithParent", ",", "k", ")", ";", "if", "(", "isUndefined", "(", "this$1", "[", "k", "]", ")", "||", "mustSync", ")", "{", "if", "(", "!", "mustSync", ")", "{", "propsInSyncWithParent", ".", "push", "(", "k", ")", ";", "}", "this$1", "[", "k", "]", "=", "target", "[", "k", "]", ";", "}", "}", ")", ";", "}" ]
Inherit properties from a target tag instance @this Tag @param { Tag } target - tag where we will inherit properties @param { Array } propsInSyncWithParent - array of properties to sync with the target
[ "Inherit", "properties", "from", "a", "target", "tag", "instance" ]
d8f547a04467c8e3e2524bde95db0b7218b98be2
https://github.com/savjs/sav-flux/blob/d8f547a04467c8e3e2524bde95db0b7218b98be2/examples/flux-todo-riot/bundle.js#L3804-L3818
train
savjs/sav-flux
examples/flux-todo-riot/bundle.js
unmountAll
function unmountAll(expressions) { each(expressions, function(expr) { if (expr instanceof Tag$1) { expr.unmount(true); } else if (expr.tagName) { expr.tag.unmount(true); } else if (expr.unmount) { expr.unmount(); } }); }
javascript
function unmountAll(expressions) { each(expressions, function(expr) { if (expr instanceof Tag$1) { expr.unmount(true); } else if (expr.tagName) { expr.tag.unmount(true); } else if (expr.unmount) { expr.unmount(); } }); }
[ "function", "unmountAll", "(", "expressions", ")", "{", "each", "(", "expressions", ",", "function", "(", "expr", ")", "{", "if", "(", "expr", "instanceof", "Tag$1", ")", "{", "expr", ".", "unmount", "(", "true", ")", ";", "}", "else", "if", "(", "expr", ".", "tagName", ")", "{", "expr", ".", "tag", ".", "unmount", "(", "true", ")", ";", "}", "else", "if", "(", "expr", ".", "unmount", ")", "{", "expr", ".", "unmount", "(", ")", ";", "}", "}", ")", ";", "}" ]
Trigger the unmount method on all the expressions @param { Array } expressions - DOM expressions
[ "Trigger", "the", "unmount", "method", "on", "all", "the", "expressions" ]
d8f547a04467c8e3e2524bde95db0b7218b98be2
https://github.com/savjs/sav-flux/blob/d8f547a04467c8e3e2524bde95db0b7218b98be2/examples/flux-todo-riot/bundle.js#L3886-L3892
train
savjs/sav-flux
examples/flux-todo-riot/bundle.js
selectTags
function selectTags(tags) { // select all tags if (!tags) { var keys = Object.keys(__TAG_IMPL); return keys + selectTags(keys) } return tags .filter(function (t) { return !/[^-\w]/.test(t); }) .reduce(function (list, t) { var name = t.trim().toLowerCase(); return list + ",[" + IS_DIRECTIVE + "=\"" + name + "\"]" }, '') }
javascript
function selectTags(tags) { // select all tags if (!tags) { var keys = Object.keys(__TAG_IMPL); return keys + selectTags(keys) } return tags .filter(function (t) { return !/[^-\w]/.test(t); }) .reduce(function (list, t) { var name = t.trim().toLowerCase(); return list + ",[" + IS_DIRECTIVE + "=\"" + name + "\"]" }, '') }
[ "function", "selectTags", "(", "tags", ")", "{", "if", "(", "!", "tags", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "__TAG_IMPL", ")", ";", "return", "keys", "+", "selectTags", "(", "keys", ")", "}", "return", "tags", ".", "filter", "(", "function", "(", "t", ")", "{", "return", "!", "/", "[^-\\w]", "/", ".", "test", "(", "t", ")", ";", "}", ")", ".", "reduce", "(", "function", "(", "list", ",", "t", ")", "{", "var", "name", "=", "t", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", ";", "return", "list", "+", "\",[\"", "+", "IS_DIRECTIVE", "+", "\"=\\\"\"", "+", "\\\"", "+", "name", "}", ",", "\"\\\"]\"", ")", "}" ]
Get selectors for tags @param { Array } tags - tag names to select @returns { String } selector
[ "Get", "selectors", "for", "tags" ]
d8f547a04467c8e3e2524bde95db0b7218b98be2
https://github.com/savjs/sav-flux/blob/d8f547a04467c8e3e2524bde95db0b7218b98be2/examples/flux-todo-riot/bundle.js#L4082-L4095
train
savjs/sav-flux
examples/flux-todo-riot/bundle.js
safeRegex
function safeRegex (re) { var arguments$1 = arguments; var src = re.source; var opt = re.global ? 'g' : ''; if (re.ignoreCase) { opt += 'i'; } if (re.multiline) { opt += 'm'; } for (var i = 1; i < arguments.length; i++) { src = src.replace('@', '\\' + arguments$1[i]); } return new RegExp(src, opt) }
javascript
function safeRegex (re) { var arguments$1 = arguments; var src = re.source; var opt = re.global ? 'g' : ''; if (re.ignoreCase) { opt += 'i'; } if (re.multiline) { opt += 'm'; } for (var i = 1; i < arguments.length; i++) { src = src.replace('@', '\\' + arguments$1[i]); } return new RegExp(src, opt) }
[ "function", "safeRegex", "(", "re", ")", "{", "var", "arguments$1", "=", "arguments", ";", "var", "src", "=", "re", ".", "source", ";", "var", "opt", "=", "re", ".", "global", "?", "'g'", ":", "''", ";", "if", "(", "re", ".", "ignoreCase", ")", "{", "opt", "+=", "'i'", ";", "}", "if", "(", "re", ".", "multiline", ")", "{", "opt", "+=", "'m'", ";", "}", "for", "(", "var", "i", "=", "1", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "src", "=", "src", ".", "replace", "(", "'@'", ",", "'\\\\'", "+", "\\\\", ")", ";", "}", "arguments$1", "[", "i", "]", "}" ]
Compiler for riot custom tags @version v3.2.3 istanbul ignore next
[ "Compiler", "for", "riot", "custom", "tags" ]
d8f547a04467c8e3e2524bde95db0b7218b98be2
https://github.com/savjs/sav-flux/blob/d8f547a04467c8e3e2524bde95db0b7218b98be2/examples/flux-todo-riot/bundle.js#L4172-L4186
train
savjs/sav-flux
examples/flux-todo-riot/bundle.js
globalEval
function globalEval (js, url) { if (typeof js === T_STRING) { var node = mkEl('script'), root = document.documentElement; // make the source available in the "(no domain)" tab // of Chrome DevTools, with a .js extension if (url) { js += '\n//# sourceURL=' + url + '.js'; } node.text = js; root.appendChild(node); root.removeChild(node); } }
javascript
function globalEval (js, url) { if (typeof js === T_STRING) { var node = mkEl('script'), root = document.documentElement; // make the source available in the "(no domain)" tab // of Chrome DevTools, with a .js extension if (url) { js += '\n//# sourceURL=' + url + '.js'; } node.text = js; root.appendChild(node); root.removeChild(node); } }
[ "function", "globalEval", "(", "js", ",", "url", ")", "{", "if", "(", "typeof", "js", "===", "T_STRING", ")", "{", "var", "node", "=", "mkEl", "(", "'script'", ")", ",", "root", "=", "document", ".", "documentElement", ";", "if", "(", "url", ")", "{", "js", "+=", "'\\n//# sourceURL='", "+", "\\n", "+", "url", ";", "}", "'.js'", "node", ".", "text", "=", "js", ";", "root", ".", "appendChild", "(", "node", ")", ";", "}", "}" ]
evaluates a compiled tag within the global context
[ "evaluates", "a", "compiled", "tag", "within", "the", "global", "context" ]
d8f547a04467c8e3e2524bde95db0b7218b98be2
https://github.com/savjs/sav-flux/blob/d8f547a04467c8e3e2524bde95db0b7218b98be2/examples/flux-todo-riot/bundle.js#L4929-L4943
train
matthewtoast/runiq
parser/parse.js
parse
function parse(tokens) { var ast = []; var current = ast; var _line = 0; var _char = 0; var openCount = 0; var closeCount = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; switch (token.type) { case TYPES.open: // Every time we open a list, we drop into a sub-array var child = []; child.parent = current; current.push(child); current = child; openCount += 1; break; case TYPES.open_array: case TYPES.quote: var child = []; var quote = {"'": child }; child.parent = current; current.push(quote); current = child; openCount += 1; break; case TYPES.close_array: case TYPES.close: // If no current, we probably have too many closing parens if (!current) _tooManyClosingParensErr(closeCount, openCount); // If we close a list, jump back up to the parent list current = current.parent; closeCount += 1; break; case TYPES.identifier: case TYPES.suffixed_number: current.push(token.string); break; case TYPES.number: current.push(Number(token.string)); break; case TYPES.string: // We need to strip the quotes off the string entity var dequoted = token.string.slice(1).slice(0, token.string.length - 2); current.push(dequoted); break; case TYPES.json: try { var deticked = token.string.slice(1).slice(0, token.string.length - 2); current.push(JSON.parse(deticked)); } catch (e) { throw new Error([ 'Runiq: Couldn\'t parse inlined JSON!', '--- Error occurred at line ' + _line + ', char ' + _char ].join('\n')); } break; } // Capture line numbers and columns for future use var lines = token.string.split(NEWLINE); _line += lines.length - 1; if (lines.length > 1) _char = lines[lines.length - 1].length; else _char += token.string.length; } // Raise error if we have a parentheses mismatch if (openCount > closeCount) _tooManyOpenParensErr(closeCount, openCount); if (openCount < closeCount) _tooManyClosingParensErr(closeCount, openCount); // For both safety and to ensure we actually have a JSON-able AST return JSON.parse(JSONStableStringify(ast)); }
javascript
function parse(tokens) { var ast = []; var current = ast; var _line = 0; var _char = 0; var openCount = 0; var closeCount = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; switch (token.type) { case TYPES.open: // Every time we open a list, we drop into a sub-array var child = []; child.parent = current; current.push(child); current = child; openCount += 1; break; case TYPES.open_array: case TYPES.quote: var child = []; var quote = {"'": child }; child.parent = current; current.push(quote); current = child; openCount += 1; break; case TYPES.close_array: case TYPES.close: // If no current, we probably have too many closing parens if (!current) _tooManyClosingParensErr(closeCount, openCount); // If we close a list, jump back up to the parent list current = current.parent; closeCount += 1; break; case TYPES.identifier: case TYPES.suffixed_number: current.push(token.string); break; case TYPES.number: current.push(Number(token.string)); break; case TYPES.string: // We need to strip the quotes off the string entity var dequoted = token.string.slice(1).slice(0, token.string.length - 2); current.push(dequoted); break; case TYPES.json: try { var deticked = token.string.slice(1).slice(0, token.string.length - 2); current.push(JSON.parse(deticked)); } catch (e) { throw new Error([ 'Runiq: Couldn\'t parse inlined JSON!', '--- Error occurred at line ' + _line + ', char ' + _char ].join('\n')); } break; } // Capture line numbers and columns for future use var lines = token.string.split(NEWLINE); _line += lines.length - 1; if (lines.length > 1) _char = lines[lines.length - 1].length; else _char += token.string.length; } // Raise error if we have a parentheses mismatch if (openCount > closeCount) _tooManyOpenParensErr(closeCount, openCount); if (openCount < closeCount) _tooManyClosingParensErr(closeCount, openCount); // For both safety and to ensure we actually have a JSON-able AST return JSON.parse(JSONStableStringify(ast)); }
[ "function", "parse", "(", "tokens", ")", "{", "var", "ast", "=", "[", "]", ";", "var", "current", "=", "ast", ";", "var", "_line", "=", "0", ";", "var", "_char", "=", "0", ";", "var", "openCount", "=", "0", ";", "var", "closeCount", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "tokens", ".", "length", ";", "i", "++", ")", "{", "var", "token", "=", "tokens", "[", "i", "]", ";", "switch", "(", "token", ".", "type", ")", "{", "case", "TYPES", ".", "open", ":", "var", "child", "=", "[", "]", ";", "child", ".", "parent", "=", "current", ";", "current", ".", "push", "(", "child", ")", ";", "current", "=", "child", ";", "openCount", "+=", "1", ";", "break", ";", "case", "TYPES", ".", "open_array", ":", "case", "TYPES", ".", "quote", ":", "var", "child", "=", "[", "]", ";", "var", "quote", "=", "{", "\"'\"", ":", "child", "}", ";", "child", ".", "parent", "=", "current", ";", "current", ".", "push", "(", "quote", ")", ";", "current", "=", "child", ";", "openCount", "+=", "1", ";", "break", ";", "case", "TYPES", ".", "close_array", ":", "case", "TYPES", ".", "close", ":", "if", "(", "!", "current", ")", "_tooManyClosingParensErr", "(", "closeCount", ",", "openCount", ")", ";", "current", "=", "current", ".", "parent", ";", "closeCount", "+=", "1", ";", "break", ";", "case", "TYPES", ".", "identifier", ":", "case", "TYPES", ".", "suffixed_number", ":", "current", ".", "push", "(", "token", ".", "string", ")", ";", "break", ";", "case", "TYPES", ".", "number", ":", "current", ".", "push", "(", "Number", "(", "token", ".", "string", ")", ")", ";", "break", ";", "case", "TYPES", ".", "string", ":", "var", "dequoted", "=", "token", ".", "string", ".", "slice", "(", "1", ")", ".", "slice", "(", "0", ",", "token", ".", "string", ".", "length", "-", "2", ")", ";", "current", ".", "push", "(", "dequoted", ")", ";", "break", ";", "case", "TYPES", ".", "json", ":", "try", "{", "var", "deticked", "=", "token", ".", "string", ".", "slice", "(", "1", ")", ".", "slice", "(", "0", ",", "token", ".", "string", ".", "length", "-", "2", ")", ";", "current", ".", "push", "(", "JSON", ".", "parse", "(", "deticked", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "Error", "(", "[", "'Runiq: Couldn\\'t parse inlined JSON!'", ",", "\\'", "]", ".", "'--- Error occurred at line '", "+", "_line", "+", "', char '", "+", "_char", "join", ")", ";", "}", "(", "'\\n'", ")", "}", "\\n", "break", ";", "var", "lines", "=", "token", ".", "string", ".", "split", "(", "NEWLINE", ")", ";", "}", "_line", "+=", "lines", ".", "length", "-", "1", ";", "if", "(", "lines", ".", "length", ">", "1", ")", "_char", "=", "lines", "[", "lines", ".", "length", "-", "1", "]", ".", "length", ";", "else", "_char", "+=", "token", ".", "string", ".", "length", ";", "if", "(", "openCount", ">", "closeCount", ")", "_tooManyOpenParensErr", "(", "closeCount", ",", "openCount", ")", ";", "}" ]
Given an array of token objects, recursively build an AST
[ "Given", "an", "array", "of", "token", "objects", "recursively", "build", "an", "AST" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/parser/parse.js#L31-L116
train
rootsdev/gedcomx-js
src/core/NamePart.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof NamePart)){ return new NamePart(json); } // If the given object is already an instance then just return it. DON'T copy it. if(NamePart.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof NamePart)){ return new NamePart(json); } // If the given object is already an instance then just return it. DON'T copy it. if(NamePart.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "NamePart", ")", ")", "{", "return", "new", "NamePart", "(", "json", ")", ";", "}", "if", "(", "NamePart", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A part of a name. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#name-part|GEDCOM X JSON Spec} @class @extends ExtensibleData @param {Object} [json]
[ "A", "part", "of", "a", "name", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/NamePart.js#L13-L26
train
jeremyruppel/pathmap
index.js
pathmap
function pathmap(path, spec, callback) { return spec.replace(regexp, function(match, replace, count, token) { var pattern; if (pattern = pathmap.patterns[token]) { return pattern.call(path, replace, count, callback); } else { throw new Error( 'Unknown pathmap specifier ' + match + ' in "' + spec + '"'); } }); }
javascript
function pathmap(path, spec, callback) { return spec.replace(regexp, function(match, replace, count, token) { var pattern; if (pattern = pathmap.patterns[token]) { return pattern.call(path, replace, count, callback); } else { throw new Error( 'Unknown pathmap specifier ' + match + ' in "' + spec + '"'); } }); }
[ "function", "pathmap", "(", "path", ",", "spec", ",", "callback", ")", "{", "return", "spec", ".", "replace", "(", "regexp", ",", "function", "(", "match", ",", "replace", ",", "count", ",", "token", ")", "{", "var", "pattern", ";", "if", "(", "pattern", "=", "pathmap", ".", "patterns", "[", "token", "]", ")", "{", "return", "pattern", ".", "call", "(", "path", ",", "replace", ",", "count", ",", "callback", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Unknown pathmap specifier '", "+", "match", "+", "' in \"'", "+", "spec", "+", "'\"'", ")", ";", "}", "}", ")", ";", "}" ]
Maps a path to a path spec.
[ "Maps", "a", "path", "to", "a", "path", "spec", "." ]
3c5023225c308ca078163228eda3e86043412402
https://github.com/jeremyruppel/pathmap/blob/3c5023225c308ca078163228eda3e86043412402/index.js#L17-L27
train
jeremyruppel/pathmap
index.js
function(replace, count, callback) { return pathmap.replace( pathmap.basename(this, pathmap.extname(this)), replace, callback); }
javascript
function(replace, count, callback) { return pathmap.replace( pathmap.basename(this, pathmap.extname(this)), replace, callback); }
[ "function", "(", "replace", ",", "count", ",", "callback", ")", "{", "return", "pathmap", ".", "replace", "(", "pathmap", ".", "basename", "(", "this", ",", "pathmap", ".", "extname", "(", "this", ")", ")", ",", "replace", ",", "callback", ")", ";", "}" ]
The file name of the path without its file extension.
[ "The", "file", "name", "of", "the", "path", "without", "its", "file", "extension", "." ]
3c5023225c308ca078163228eda3e86043412402
https://github.com/jeremyruppel/pathmap/blob/3c5023225c308ca078163228eda3e86043412402/index.js#L145-L148
train
jeremyruppel/pathmap
index.js
function(replace, count, callback) { return pathmap.replace( pathmap.dirname(this, count), replace, callback); }
javascript
function(replace, count, callback) { return pathmap.replace( pathmap.dirname(this, count), replace, callback); }
[ "function", "(", "replace", ",", "count", ",", "callback", ")", "{", "return", "pathmap", ".", "replace", "(", "pathmap", ".", "dirname", "(", "this", ",", "count", ")", ",", "replace", ",", "callback", ")", ";", "}" ]
The directory list of the path.
[ "The", "directory", "list", "of", "the", "path", "." ]
3c5023225c308ca078163228eda3e86043412402
https://github.com/jeremyruppel/pathmap/blob/3c5023225c308ca078163228eda3e86043412402/index.js#L153-L156
train
jeremyruppel/pathmap
index.js
function(replace, count, callback) { return pathmap.replace( pathmap.chomp(this, pathmap.extname(this)), replace, callback); }
javascript
function(replace, count, callback) { return pathmap.replace( pathmap.chomp(this, pathmap.extname(this)), replace, callback); }
[ "function", "(", "replace", ",", "count", ",", "callback", ")", "{", "return", "pathmap", ".", "replace", "(", "pathmap", ".", "chomp", "(", "this", ",", "pathmap", ".", "extname", "(", "this", ")", ")", ",", "replace", ",", "callback", ")", ";", "}" ]
Everything but the file extension.
[ "Everything", "but", "the", "file", "extension", "." ]
3c5023225c308ca078163228eda3e86043412402
https://github.com/jeremyruppel/pathmap/blob/3c5023225c308ca078163228eda3e86043412402/index.js#L170-L173
train
rootsdev/gedcomx-js
src/core/SourceReference.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof SourceReference)){ return new SourceReference(json); } // If the given object is already an instance then just return it. DON'T copy it. if(SourceReference.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof SourceReference)){ return new SourceReference(json); } // If the given object is already an instance then just return it. DON'T copy it. if(SourceReference.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "SourceReference", ")", ")", "{", "return", "new", "SourceReference", "(", "json", ")", ";", "}", "if", "(", "SourceReference", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A reference to a discription of a source. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#source-reference|GEDCOM X JSON Spec} @class @extends ExtensibleData @param {Object} [json]
[ "A", "reference", "to", "a", "discription", "of", "a", "source", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/SourceReference.js#L13-L26
train
jonschlinkert/gulp-middleware
index.js
middleware
function middleware(fns) { return through.obj(function(file, enc, cb) { eachSeries(arrayify(fns), function(fn, next) { try { fn(file, next); } catch (err) { next(err); } }, function(err) { cb(err, file); }); }); }
javascript
function middleware(fns) { return through.obj(function(file, enc, cb) { eachSeries(arrayify(fns), function(fn, next) { try { fn(file, next); } catch (err) { next(err); } }, function(err) { cb(err, file); }); }); }
[ "function", "middleware", "(", "fns", ")", "{", "return", "through", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "cb", ")", "{", "eachSeries", "(", "arrayify", "(", "fns", ")", ",", "function", "(", "fn", ",", "next", ")", "{", "try", "{", "fn", "(", "file", ",", "next", ")", ";", "}", "catch", "(", "err", ")", "{", "next", "(", "err", ")", ";", "}", "}", ",", "function", "(", "err", ")", "{", "cb", "(", "err", ",", "file", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Run middleware in series. ```js var middleware = require('gulp-middleware'); gulp.task('middleware', function() { return gulp.src('*.js') .pipe(middleware(fn('bar'))) .pipe(middleware([ fn('foo'), fn('bar'), fn('baz') ])) }); function fn(name) { return function(file, next) { console.log(name); next(); }; } ``` @param {Array|Function} `fns` Function or array of middleware functions @api public
[ "Run", "middleware", "in", "series", "." ]
04983efd8b3ab4b1dc932553159ca82078b7a6a9
https://github.com/jonschlinkert/gulp-middleware/blob/04983efd8b3ab4b1dc932553159ca82078b7a6a9/index.js#L47-L59
train
majorleaguesoccer/neulion
lib/neulion.js
toXML
function toXML(obj) { var xml = '' for (var prop in obj) { xml += `<${prop}>${obj[prop]}</${prop}>` } return xml }
javascript
function toXML(obj) { var xml = '' for (var prop in obj) { xml += `<${prop}>${obj[prop]}</${prop}>` } return xml }
[ "function", "toXML", "(", "obj", ")", "{", "var", "xml", "=", "''", "for", "(", "var", "prop", "in", "obj", ")", "{", "xml", "+=", "`", "${", "prop", "}", "${", "obj", "[", "prop", "]", "}", "${", "prop", "}", "`", "}", "return", "xml", "}" ]
Convert an object into simple XML @param {Object} input @return {String} xml output
[ "Convert", "an", "object", "into", "simple", "XML" ]
c461421d7af9bd638e241ea4f88fd40ae9bb39f2
https://github.com/majorleaguesoccer/neulion/blob/c461421d7af9bd638e241ea4f88fd40ae9bb39f2/lib/neulion.js#L29-L35
train
majorleaguesoccer/neulion
lib/neulion.js
go
function go() { return new Promise(handler) // Check for invalid `authCode`, this seems to happen at random intervals // within the neulion API, so we will only know when a request fails .catch(Errors.AuthenticationError, function(err) { // Authenticate and then try one more time return self .auth() .then(function() { return new Promise(handler) }) }) }
javascript
function go() { return new Promise(handler) // Check for invalid `authCode`, this seems to happen at random intervals // within the neulion API, so we will only know when a request fails .catch(Errors.AuthenticationError, function(err) { // Authenticate and then try one more time return self .auth() .then(function() { return new Promise(handler) }) }) }
[ "function", "go", "(", ")", "{", "return", "new", "Promise", "(", "handler", ")", ".", "catch", "(", "Errors", ".", "AuthenticationError", ",", "function", "(", "err", ")", "{", "return", "self", ".", "auth", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "new", "Promise", "(", "handler", ")", "}", ")", "}", ")", "}" ]
Primary method runner
[ "Primary", "method", "runner" ]
c461421d7af9bd638e241ea4f88fd40ae9bb39f2
https://github.com/majorleaguesoccer/neulion/blob/c461421d7af9bd638e241ea4f88fd40ae9bb39f2/lib/neulion.js#L137-L150
train
matthewtoast/runiq
library/http.js
request
function request(meth, url, headers, query, data, cb) { var req = SA(meth, url); if (headers) req.set(headers); if (query) req.query(query); if (data) req.send(data); return req.end(function(err, res) { if (err) return cb(err); return cb(null, res.text); }); }
javascript
function request(meth, url, headers, query, data, cb) { var req = SA(meth, url); if (headers) req.set(headers); if (query) req.query(query); if (data) req.send(data); return req.end(function(err, res) { if (err) return cb(err); return cb(null, res.text); }); }
[ "function", "request", "(", "meth", ",", "url", ",", "headers", ",", "query", ",", "data", ",", "cb", ")", "{", "var", "req", "=", "SA", "(", "meth", ",", "url", ")", ";", "if", "(", "headers", ")", "req", ".", "set", "(", "headers", ")", ";", "if", "(", "query", ")", "req", ".", "query", "(", "query", ")", ";", "if", "(", "data", ")", "req", ".", "send", "(", "data", ")", ";", "return", "req", ".", "end", "(", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "return", "cb", "(", "null", ",", "res", ".", "text", ")", ";", "}", ")", ";", "}" ]
Execute a HTTP request @function http.request @example (http.request) @returns {Anything}
[ "Execute", "a", "HTTP", "request" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/library/http.js#L16-L25
train
rootsdev/gedcomx-js
src/core/Event.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Event)){ return new Event(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Event.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Event)){ return new Event(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Event.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Event", ")", ")", "{", "return", "new", "Event", "(", "json", ")", ";", "}", "if", "(", "Event", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
An event. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#event|GEDCOM X JSON Spec} @class @extends Subject @param {Object} [json]
[ "An", "event", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Event.js#L13-L26
train
ndreckshage/isomorphic
lib/isomorphize.js
loadNonCriticalCSS
function loadNonCriticalCSS (href) { var link = window.document.createElement('link'); link.rel = 'stylesheet'; link.href = href; window.document.getElementsByTagName('head')[0].appendChild(link); }
javascript
function loadNonCriticalCSS (href) { var link = window.document.createElement('link'); link.rel = 'stylesheet'; link.href = href; window.document.getElementsByTagName('head')[0].appendChild(link); }
[ "function", "loadNonCriticalCSS", "(", "href", ")", "{", "var", "link", "=", "window", ".", "document", ".", "createElement", "(", "'link'", ")", ";", "link", ".", "rel", "=", "'stylesheet'", ";", "link", ".", "href", "=", "href", ";", "window", ".", "document", ".", "getElementsByTagName", "(", "'head'", ")", "[", "0", "]", ".", "appendChild", "(", "link", ")", ";", "}" ]
load non critical css async
[ "load", "non", "critical", "css", "async" ]
dc2f8220ed172aa3be82079af06a74ac29cf9b87
https://github.com/ndreckshage/isomorphic/blob/dc2f8220ed172aa3be82079af06a74ac29cf9b87/lib/isomorphize.js#L4-L9
train
bredele/steroid
examples/example2.js
async
function async(value, bool) { var def = promise() setTimeout(function() { if(!bool) def.fulfill(value) else def.reject('error') }, 10) return def.promise }
javascript
function async(value, bool) { var def = promise() setTimeout(function() { if(!bool) def.fulfill(value) else def.reject('error') }, 10) return def.promise }
[ "function", "async", "(", "value", ",", "bool", ")", "{", "var", "def", "=", "promise", "(", ")", "setTimeout", "(", "function", "(", ")", "{", "if", "(", "!", "bool", ")", "def", ".", "fulfill", "(", "value", ")", "else", "def", ".", "reject", "(", "'error'", ")", "}", ",", "10", ")", "return", "def", ".", "promise", "}" ]
Return value after 500ms using promises. @param {Any} value @return {Promise} @api private
[ "Return", "value", "after", "500ms", "using", "promises", "." ]
a9d2a7ae334ffcb9917a2190b9035e0a30e1bacb
https://github.com/bredele/steroid/blob/a9d2a7ae334ffcb9917a2190b9035e0a30e1bacb/examples/example2.js#L77-L84
train
Schoonology/discovery
lib/registry.js
Registry
function Registry(options) { if (!(this instanceof Registry)) { return new Registry(options); } options = options || {}; debug('New Registry: %j', options); this.manager = options.manager || new UdpBroadcast(); this.services = {}; this._initProperties(options); this._initManager(); assert(this.manager instanceof Manager, 'Invalid Manager type.'); }
javascript
function Registry(options) { if (!(this instanceof Registry)) { return new Registry(options); } options = options || {}; debug('New Registry: %j', options); this.manager = options.manager || new UdpBroadcast(); this.services = {}; this._initProperties(options); this._initManager(); assert(this.manager instanceof Manager, 'Invalid Manager type.'); }
[ "function", "Registry", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Registry", ")", ")", "{", "return", "new", "Registry", "(", "options", ")", ";", "}", "options", "=", "options", "||", "{", "}", ";", "debug", "(", "'New Registry: %j'", ",", "options", ")", ";", "this", ".", "manager", "=", "options", ".", "manager", "||", "new", "UdpBroadcast", "(", ")", ";", "this", ".", "services", "=", "{", "}", ";", "this", ".", "_initProperties", "(", "options", ")", ";", "this", ".", "_initManager", "(", ")", ";", "assert", "(", "this", ".", "manager", "instanceof", "Manager", ",", "'Invalid Manager type.'", ")", ";", "}" ]
Creates a new instance of Registry with the provided `options`. The Registry is the cornerstone of Discovery. Each node in the cluster is expected to have at least one Registry, with that Registry being responsible for one or more local Services. Its Manager, in turn, synchronizes the Registry's understanding of the cluster and its remotely-available Services. For more information, see the README. @param {Object} options
[ "Creates", "a", "new", "instance", "of", "Registry", "with", "the", "provided", "options", "." ]
9d123d74c13f8c9b6904e409f8933b09ab22e175
https://github.com/Schoonology/discovery/blob/9d123d74c13f8c9b6904e409f8933b09ab22e175/lib/registry.js#L23-L39
train
Schoonology/discovery
lib/managers/broadcast.js
UdpBroadcastManager
function UdpBroadcastManager(options) { if (!(this instanceof UdpBroadcastManager)) { return new UdpBroadcastManager(options); } options = options || {}; Manager.call(this, options); debug('New UdpBroadcastManager: %j', options); this.dgramType = options.dgramType ? String(options.dgramType).toLowerCase() : Defaults.DGRAM_TYPE; this.port = options.port || Defaults.PORT; this.address = options.address || null; this.multicastAddress = options.multicastAddress || Defaults.MULTICAST_ADDRESS; this.interval = options.interval || Defaults.INTERVAL; this.timeout = options.timeout || this.interval * 2.5; this._timeoutTimerIds = {}; this._announceTimerId = null; this._initSocket(); this._startAnnouncements(); }
javascript
function UdpBroadcastManager(options) { if (!(this instanceof UdpBroadcastManager)) { return new UdpBroadcastManager(options); } options = options || {}; Manager.call(this, options); debug('New UdpBroadcastManager: %j', options); this.dgramType = options.dgramType ? String(options.dgramType).toLowerCase() : Defaults.DGRAM_TYPE; this.port = options.port || Defaults.PORT; this.address = options.address || null; this.multicastAddress = options.multicastAddress || Defaults.MULTICAST_ADDRESS; this.interval = options.interval || Defaults.INTERVAL; this.timeout = options.timeout || this.interval * 2.5; this._timeoutTimerIds = {}; this._announceTimerId = null; this._initSocket(); this._startAnnouncements(); }
[ "function", "UdpBroadcastManager", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "UdpBroadcastManager", ")", ")", "{", "return", "new", "UdpBroadcastManager", "(", "options", ")", ";", "}", "options", "=", "options", "||", "{", "}", ";", "Manager", ".", "call", "(", "this", ",", "options", ")", ";", "debug", "(", "'New UdpBroadcastManager: %j'", ",", "options", ")", ";", "this", ".", "dgramType", "=", "options", ".", "dgramType", "?", "String", "(", "options", ".", "dgramType", ")", ".", "toLowerCase", "(", ")", ":", "Defaults", ".", "DGRAM_TYPE", ";", "this", ".", "port", "=", "options", ".", "port", "||", "Defaults", ".", "PORT", ";", "this", ".", "address", "=", "options", ".", "address", "||", "null", ";", "this", ".", "multicastAddress", "=", "options", ".", "multicastAddress", "||", "Defaults", ".", "MULTICAST_ADDRESS", ";", "this", ".", "interval", "=", "options", ".", "interval", "||", "Defaults", ".", "INTERVAL", ";", "this", ".", "timeout", "=", "options", ".", "timeout", "||", "this", ".", "interval", "*", "2.5", ";", "this", ".", "_timeoutTimerIds", "=", "{", "}", ";", "this", ".", "_announceTimerId", "=", "null", ";", "this", ".", "_initSocket", "(", ")", ";", "this", ".", "_startAnnouncements", "(", ")", ";", "}" ]
Creates a new instance of UdpBroadcastManager with the provided `options`. The UdpBroadcastManager provides a client connection to the zero-configuration, UDP-based discovery system that is used by Discovery by default. Because it requires zero configuration to use, it's ideal for initial exploration and development. However, it's not expected to work at-scale, and should be replaced with the included HTTP-based version. For more information, see the README. @param {Object} options
[ "Creates", "a", "new", "instance", "of", "UdpBroadcastManager", "with", "the", "provided", "options", "." ]
9d123d74c13f8c9b6904e409f8933b09ab22e175
https://github.com/Schoonology/discovery/blob/9d123d74c13f8c9b6904e409f8933b09ab22e175/lib/managers/broadcast.js#L31-L55
train
BeLi4L/subz-hero
src/subz-hero.js
downloadSubtitles
async function downloadSubtitles (file) { const subtitles = await getSubtitles(file) const { dir, name } = path.parse(file) const subtitlesFile = path.format({ dir, name, ext: '.srt' }) await fs.writeFile(subtitlesFile, subtitles) return subtitlesFile }
javascript
async function downloadSubtitles (file) { const subtitles = await getSubtitles(file) const { dir, name } = path.parse(file) const subtitlesFile = path.format({ dir, name, ext: '.srt' }) await fs.writeFile(subtitlesFile, subtitles) return subtitlesFile }
[ "async", "function", "downloadSubtitles", "(", "file", ")", "{", "const", "subtitles", "=", "await", "getSubtitles", "(", "file", ")", "const", "{", "dir", ",", "name", "}", "=", "path", ".", "parse", "(", "file", ")", "const", "subtitlesFile", "=", "path", ".", "format", "(", "{", "dir", ",", "name", ",", "ext", ":", "'.srt'", "}", ")", "await", "fs", ".", "writeFile", "(", "subtitlesFile", ",", "subtitles", ")", "return", "subtitlesFile", "}" ]
Download subtitles for the given file and create a '.srt' file next to it, with the same name. @param {string} file - path to a file @returns {Promise<string>} path to the .srt file
[ "Download", "subtitles", "for", "the", "given", "file", "and", "create", "a", ".", "srt", "file", "next", "to", "it", "with", "the", "same", "name", "." ]
c22c6df7c2d80c00685a9326043e1ceae3cbf53d
https://github.com/BeLi4L/subz-hero/blob/c22c6df7c2d80c00685a9326043e1ceae3cbf53d/src/subz-hero.js#L39-L49
train
rootsdev/gedcomx-js
src/records/Field.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Field)){ return new Field(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Field.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Field)){ return new Field(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Field.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Field", ")", ")", "{", "return", "new", "Field", "(", "json", ")", ";", "}", "if", "(", "Field", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
Information about the fields of a record from which genealogical data is extracted. @see {@link https://github.com/FamilySearch/gedcomx-record/blob/master/specifications/record-specification.md#field|GEDCOM X Records Spec} @class Field @extends ExtensibleData @param {Object} [json]
[ "Information", "about", "the", "fields", "of", "a", "record", "from", "which", "genealogical", "data", "is", "extracted", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/records/Field.js#L14-L27
train
declandewet/pipep
index.js
_resolvePromises
function _resolvePromises (opts, val) { opts = opts || {} var duplicate = opts.duplicate if (is(Array, val)) { return Promise.all(duplicate ? concat([], val) : val) } else if (duplicate && is(Object, val) && !is(Function, val.then)) { return Object.assign({}, val) } return val }
javascript
function _resolvePromises (opts, val) { opts = opts || {} var duplicate = opts.duplicate if (is(Array, val)) { return Promise.all(duplicate ? concat([], val) : val) } else if (duplicate && is(Object, val) && !is(Function, val.then)) { return Object.assign({}, val) } return val }
[ "function", "_resolvePromises", "(", "opts", ",", "val", ")", "{", "opts", "=", "opts", "||", "{", "}", "var", "duplicate", "=", "opts", ".", "duplicate", "if", "(", "is", "(", "Array", ",", "val", ")", ")", "{", "return", "Promise", ".", "all", "(", "duplicate", "?", "concat", "(", "[", "]", ",", "val", ")", ":", "val", ")", "}", "else", "if", "(", "duplicate", "&&", "is", "(", "Object", ",", "val", ")", "&&", "!", "is", "(", "Function", ",", "val", ".", "then", ")", ")", "{", "return", "Object", ".", "assign", "(", "{", "}", ",", "val", ")", "}", "return", "val", "}" ]
Calls Promise.all on passed value if it is an array Duplicates value if required. @param {Object} opts - options @param {*} val - value to resolve @return {*} - if val is an array, a promise for all resolved elements, else the original value
[ "Calls", "Promise", ".", "all", "on", "passed", "value", "if", "it", "is", "an", "array", "Duplicates", "value", "if", "required", "." ]
799e168125770f950ba91266a948c381a348bd3a
https://github.com/declandewet/pipep/blob/799e168125770f950ba91266a948c381a348bd3a/index.js#L93-L102
train
declandewet/pipep
index.js
_curry
function _curry (n, fn, args) { args = args || [] return function partial () { var rest = arrayFrom(arguments) var allArgs = concat(args, rest) return n > length(allArgs) ? _curry(n, fn, allArgs) : _call(fn, allArgs.slice(0, n)) } }
javascript
function _curry (n, fn, args) { args = args || [] return function partial () { var rest = arrayFrom(arguments) var allArgs = concat(args, rest) return n > length(allArgs) ? _curry(n, fn, allArgs) : _call(fn, allArgs.slice(0, n)) } }
[ "function", "_curry", "(", "n", ",", "fn", ",", "args", ")", "{", "args", "=", "args", "||", "[", "]", "return", "function", "partial", "(", ")", "{", "var", "rest", "=", "arrayFrom", "(", "arguments", ")", "var", "allArgs", "=", "concat", "(", "args", ",", "rest", ")", "return", "n", ">", "length", "(", "allArgs", ")", "?", "_curry", "(", "n", ",", "fn", ",", "allArgs", ")", ":", "_call", "(", "fn", ",", "allArgs", ".", "slice", "(", "0", ",", "n", ")", ")", "}", "}" ]
Returns a function of n-arity partially applied with supplied arguments @param {Number} n - arity of function to partially apply @param {Function} fn - function to partially apply @param {Array} args = [] - arguments to apply to new function @return {Function} - partially-applied function
[ "Returns", "a", "function", "of", "n", "-", "arity", "partially", "applied", "with", "supplied", "arguments" ]
799e168125770f950ba91266a948c381a348bd3a
https://github.com/declandewet/pipep/blob/799e168125770f950ba91266a948c381a348bd3a/index.js#L187-L196
train
ndreckshage/isomorphic
lib/gulp/utils/error.js
handleError
function handleError (task) { return function (err) { console.log(chalk.red(err)); notify.onError(task + ' failed, check the logs..')(err); }; }
javascript
function handleError (task) { return function (err) { console.log(chalk.red(err)); notify.onError(task + ' failed, check the logs..')(err); }; }
[ "function", "handleError", "(", "task", ")", "{", "return", "function", "(", "err", ")", "{", "console", ".", "log", "(", "chalk", ".", "red", "(", "err", ")", ")", ";", "notify", ".", "onError", "(", "task", "+", "' failed, check the logs..'", ")", "(", "err", ")", ";", "}", ";", "}" ]
Log errors from Gulp @param {string} task
[ "Log", "errors", "from", "Gulp" ]
dc2f8220ed172aa3be82079af06a74ac29cf9b87
https://github.com/ndreckshage/isomorphic/blob/dc2f8220ed172aa3be82079af06a74ac29cf9b87/lib/gulp/utils/error.js#L8-L13
train
matthewtoast/runiq
interpreter/index.js
Interpreter
function Interpreter(library, options, storage) { // What lengths I've gone to to use only 7-letter properties... this.library = new Library(CloneDeep(library || {})); this.options = Assign({}, Interpreter.DEFAULT_OPTIONS, options); this.balance = this.options.balance; this.timeout = Date.now() + this.options.timeout; this.seednum = this.options.seed || Math.random(); this.counter = this.options.count || 0; this.storage = storage || new Storage(); var outputs = this.outputs = []; if (this.options.doCaptureConsole) { Console.capture(function(type, messages) { outputs.push({ type: type, messages: messages }); }); } }
javascript
function Interpreter(library, options, storage) { // What lengths I've gone to to use only 7-letter properties... this.library = new Library(CloneDeep(library || {})); this.options = Assign({}, Interpreter.DEFAULT_OPTIONS, options); this.balance = this.options.balance; this.timeout = Date.now() + this.options.timeout; this.seednum = this.options.seed || Math.random(); this.counter = this.options.count || 0; this.storage = storage || new Storage(); var outputs = this.outputs = []; if (this.options.doCaptureConsole) { Console.capture(function(type, messages) { outputs.push({ type: type, messages: messages }); }); } }
[ "function", "Interpreter", "(", "library", ",", "options", ",", "storage", ")", "{", "this", ".", "library", "=", "new", "Library", "(", "CloneDeep", "(", "library", "||", "{", "}", ")", ")", ";", "this", ".", "options", "=", "Assign", "(", "{", "}", ",", "Interpreter", ".", "DEFAULT_OPTIONS", ",", "options", ")", ";", "this", ".", "balance", "=", "this", ".", "options", ".", "balance", ";", "this", ".", "timeout", "=", "Date", ".", "now", "(", ")", "+", "this", ".", "options", ".", "timeout", ";", "this", ".", "seednum", "=", "this", ".", "options", ".", "seed", "||", "Math", ".", "random", "(", ")", ";", "this", ".", "counter", "=", "this", ".", "options", ".", "count", "||", "0", ";", "this", ".", "storage", "=", "storage", "||", "new", "Storage", "(", ")", ";", "var", "outputs", "=", "this", ".", "outputs", "=", "[", "]", ";", "if", "(", "this", ".", "options", ".", "doCaptureConsole", ")", "{", "Console", ".", "capture", "(", "function", "(", "type", ",", "messages", ")", "{", "outputs", ".", "push", "(", "{", "type", ":", "type", ",", "messages", ":", "messages", "}", ")", ";", "}", ")", ";", "}", "}" ]
An instance of Interpreter can execute a Runiq AST. At a high level, it performs instructions defined in the AST by mapping function names to function entries in the passed-in Library instance The interpreter also manages ordering operations in accordance with the three basic control patterns available in Runiq: - Asynchronous function composition, via nesting: ['last', ['third', ['second', ['first']]]] - asynchronous function sequencing [['first'],['second'],['third'],['last']] - quoting (witholding lists for later execution) ['quote', ['save', 'me', 'for', 'later']] @class Interpreter @constructor @param [library] {Object} - Library dictionary @param [options] {Object} - Options object
[ "An", "instance", "of", "Interpreter", "can", "execute", "a", "Runiq", "AST", ".", "At", "a", "high", "level", "it", "performs", "instructions", "defined", "in", "the", "AST", "by", "mapping", "function", "names", "to", "function", "entries", "in", "the", "passed", "-", "in", "Library", "instance" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L39-L55
train
matthewtoast/runiq
interpreter/index.js
exec
function exec(inst, raw, argv, event, fin) { var after = nextup(inst, raw, argv, event, fin); return step(inst, raw, argv, event, passthrough(after)); }
javascript
function exec(inst, raw, argv, event, fin) { var after = nextup(inst, raw, argv, event, fin); return step(inst, raw, argv, event, passthrough(after)); }
[ "function", "exec", "(", "inst", ",", "raw", ",", "argv", ",", "event", ",", "fin", ")", "{", "var", "after", "=", "nextup", "(", "inst", ",", "raw", ",", "argv", ",", "event", ",", "fin", ")", ";", "return", "step", "(", "inst", ",", "raw", ",", "argv", ",", "event", ",", "passthrough", "(", "after", ")", ")", ";", "}" ]
Recursively execute a list in the context of the passed-in instance.
[ "Recursively", "execute", "a", "list", "in", "the", "context", "of", "the", "passed", "-", "in", "instance", "." ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L151-L154
train
matthewtoast/runiq
interpreter/index.js
nextup
function nextup(inst, orig, argv, event, cb) { return function nextupCallback(err, data) { if (err) return cb(err, null); if (_isQuoted(data)) return cb(null, _unquote(data)); if (_isValue(data)) return cb(null, _entityToValue(data, inst.library)); // Remove any nulls or undefineds from the list var compact = _compactList(data); // Allow the programmer to opt out for _minor_ perf gains if (inst.options.doIrreducibleListCheck) { // If no change, we'll keep looping forever, so just return if (IsEqual(orig, compact)) { Console.printWarning(inst, 'Detected irreducible list; exiting...'); return cb(null, compact); } } return exec(inst, compact, argv, event, cb); }; }
javascript
function nextup(inst, orig, argv, event, cb) { return function nextupCallback(err, data) { if (err) return cb(err, null); if (_isQuoted(data)) return cb(null, _unquote(data)); if (_isValue(data)) return cb(null, _entityToValue(data, inst.library)); // Remove any nulls or undefineds from the list var compact = _compactList(data); // Allow the programmer to opt out for _minor_ perf gains if (inst.options.doIrreducibleListCheck) { // If no change, we'll keep looping forever, so just return if (IsEqual(orig, compact)) { Console.printWarning(inst, 'Detected irreducible list; exiting...'); return cb(null, compact); } } return exec(inst, compact, argv, event, cb); }; }
[ "function", "nextup", "(", "inst", ",", "orig", ",", "argv", ",", "event", ",", "cb", ")", "{", "return", "function", "nextupCallback", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ",", "null", ")", ";", "if", "(", "_isQuoted", "(", "data", ")", ")", "return", "cb", "(", "null", ",", "_unquote", "(", "data", ")", ")", ";", "if", "(", "_isValue", "(", "data", ")", ")", "return", "cb", "(", "null", ",", "_entityToValue", "(", "data", ",", "inst", ".", "library", ")", ")", ";", "var", "compact", "=", "_compactList", "(", "data", ")", ";", "if", "(", "inst", ".", "options", ".", "doIrreducibleListCheck", ")", "{", "if", "(", "IsEqual", "(", "orig", ",", "compact", ")", ")", "{", "Console", ".", "printWarning", "(", "inst", ",", "'Detected irreducible list; exiting...'", ")", ";", "return", "cb", "(", "null", ",", "compact", ")", ";", "}", "}", "return", "exec", "(", "inst", ",", "compact", ",", "argv", ",", "event", ",", "cb", ")", ";", "}", ";", "}" ]
Return callback to produce a usable value, or continue execution
[ "Return", "callback", "to", "produce", "a", "usable", "value", "or", "continue", "execution" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L157-L174
train
matthewtoast/runiq
interpreter/index.js
step
function step(inst, raw, argv, event, fin) { if (!_isPresent(raw)) return fin(_wrapError(_badInput(inst), inst, raw), null); var flat = _denestList(raw); preproc(inst, flat, argv, event, function postPreproc(err, data) { if (err) return fin(err); var list = _safeObject(data); return branch(inst, list, argv, event, fin); }); }
javascript
function step(inst, raw, argv, event, fin) { if (!_isPresent(raw)) return fin(_wrapError(_badInput(inst), inst, raw), null); var flat = _denestList(raw); preproc(inst, flat, argv, event, function postPreproc(err, data) { if (err) return fin(err); var list = _safeObject(data); return branch(inst, list, argv, event, fin); }); }
[ "function", "step", "(", "inst", ",", "raw", ",", "argv", ",", "event", ",", "fin", ")", "{", "if", "(", "!", "_isPresent", "(", "raw", ")", ")", "return", "fin", "(", "_wrapError", "(", "_badInput", "(", "inst", ")", ",", "inst", ",", "raw", ")", ",", "null", ")", ";", "var", "flat", "=", "_denestList", "(", "raw", ")", ";", "preproc", "(", "inst", ",", "flat", ",", "argv", ",", "event", ",", "function", "postPreproc", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "fin", "(", "err", ")", ";", "var", "list", "=", "_safeObject", "(", "data", ")", ";", "return", "branch", "(", "inst", ",", "list", ",", "argv", ",", "event", ",", "fin", ")", ";", "}", ")", ";", "}" ]
Perform one step of execution to the given list, and return the AST.
[ "Perform", "one", "step", "of", "execution", "to", "the", "given", "list", "and", "return", "the", "AST", "." ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L177-L185
train
matthewtoast/runiq
interpreter/index.js
preproc
function preproc(inst, prog, argv, event, fin) { var info = findPreprocs(inst, prog, [], []); function step(procs, parts, list) { if (!procs || procs.length < 1) { return fin(null, list); } var part = parts.shift(); var proc = procs.shift(); var ctx = { id: inst.counter, seed: inst.seednum, store: inst.storage, argv: argv, event: event }; return proc.call(ctx, part, list, function(err, _list) { if (err) return fin(err); return step(procs, parts, _list); }); } return step(info.procs, info.parts, info.list); }
javascript
function preproc(inst, prog, argv, event, fin) { var info = findPreprocs(inst, prog, [], []); function step(procs, parts, list) { if (!procs || procs.length < 1) { return fin(null, list); } var part = parts.shift(); var proc = procs.shift(); var ctx = { id: inst.counter, seed: inst.seednum, store: inst.storage, argv: argv, event: event }; return proc.call(ctx, part, list, function(err, _list) { if (err) return fin(err); return step(procs, parts, _list); }); } return step(info.procs, info.parts, info.list); }
[ "function", "preproc", "(", "inst", ",", "prog", ",", "argv", ",", "event", ",", "fin", ")", "{", "var", "info", "=", "findPreprocs", "(", "inst", ",", "prog", ",", "[", "]", ",", "[", "]", ")", ";", "function", "step", "(", "procs", ",", "parts", ",", "list", ")", "{", "if", "(", "!", "procs", "||", "procs", ".", "length", "<", "1", ")", "{", "return", "fin", "(", "null", ",", "list", ")", ";", "}", "var", "part", "=", "parts", ".", "shift", "(", ")", ";", "var", "proc", "=", "procs", ".", "shift", "(", ")", ";", "var", "ctx", "=", "{", "id", ":", "inst", ".", "counter", ",", "seed", ":", "inst", ".", "seednum", ",", "store", ":", "inst", ".", "storage", ",", "argv", ":", "argv", ",", "event", ":", "event", "}", ";", "return", "proc", ".", "call", "(", "ctx", ",", "part", ",", "list", ",", "function", "(", "err", ",", "_list", ")", "{", "if", "(", "err", ")", "return", "fin", "(", "err", ")", ";", "return", "step", "(", "procs", ",", "parts", ",", "_list", ")", ";", "}", ")", ";", "}", "return", "step", "(", "info", ".", "procs", ",", "info", ".", "parts", ",", "info", ".", "list", ")", ";", "}" ]
Run any preprocessors that are present in the program, please
[ "Run", "any", "preprocessors", "that", "are", "present", "in", "the", "program", "please" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L188-L209
train
matthewtoast/runiq
interpreter/index.js
findPreprocs
function findPreprocs(inst, list, procs, parts) { if (Array.isArray(list)) { while (list.length > 0) { var part = list.shift(); // Preprocessors must be the first elements in the list; // if we hit any non-preprocessors, immediately assume // we're done preprocessing and can move on with execution // This is as opposed to doing something like hoisting if (!_isFunc(part)) { list.unshift(part); break; } var name = _getFnName(part); var lookup = inst.library.lookupPreprocessor(name); if (!lookup) { list.unshift(part); break; } if (lookup) { parts.push(part); procs.push(lookup); } } } return { list: list, parts: parts, procs: procs }; }
javascript
function findPreprocs(inst, list, procs, parts) { if (Array.isArray(list)) { while (list.length > 0) { var part = list.shift(); // Preprocessors must be the first elements in the list; // if we hit any non-preprocessors, immediately assume // we're done preprocessing and can move on with execution // This is as opposed to doing something like hoisting if (!_isFunc(part)) { list.unshift(part); break; } var name = _getFnName(part); var lookup = inst.library.lookupPreprocessor(name); if (!lookup) { list.unshift(part); break; } if (lookup) { parts.push(part); procs.push(lookup); } } } return { list: list, parts: parts, procs: procs }; }
[ "function", "findPreprocs", "(", "inst", ",", "list", ",", "procs", ",", "parts", ")", "{", "if", "(", "Array", ".", "isArray", "(", "list", ")", ")", "{", "while", "(", "list", ".", "length", ">", "0", ")", "{", "var", "part", "=", "list", ".", "shift", "(", ")", ";", "if", "(", "!", "_isFunc", "(", "part", ")", ")", "{", "list", ".", "unshift", "(", "part", ")", ";", "break", ";", "}", "var", "name", "=", "_getFnName", "(", "part", ")", ";", "var", "lookup", "=", "inst", ".", "library", ".", "lookupPreprocessor", "(", "name", ")", ";", "if", "(", "!", "lookup", ")", "{", "list", ".", "unshift", "(", "part", ")", ";", "break", ";", "}", "if", "(", "lookup", ")", "{", "parts", ".", "push", "(", "part", ")", ";", "procs", ".", "push", "(", "lookup", ")", ";", "}", "}", "}", "return", "{", "list", ":", "list", ",", "parts", ":", "parts", ",", "procs", ":", "procs", "}", ";", "}" ]
Find all preprocessors in the given program
[ "Find", "all", "preprocessors", "in", "the", "given", "program" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L212-L242
train
matthewtoast/runiq
interpreter/index.js
branch
function branch(inst, list, argv, event, fin) { if (argv.length > 0) { // Append the argv for programs that return // a list that accepts them as parameters list = list.concat(argv.splice(0)); } // HACK HACK HACK. OK, so, when dealing with deeply recursive // functions in Runiq, we may hit an error where we exceed the // available call stack size. A setTimeout will get us a fresh // call stack, but at serious perf expense, since setTimeouts // end up triggered 4 ms later. So what I'm doing here is // trying to call unload, and if that gives an error, then // falling back to setTimeout method. This technique has an // incredible benefit, speeding up Runiq programs by 50X or so. // However, it could prove unworkable depending on browser support // for catching call-stack errors. try { return unload(inst, list, argv, event, fin); } catch (e) { return setTimeout(function branchCallback() { Console.printWarning(inst, "Caught call stack error: " + e); return unload(inst, list, argv, event, fin); }, 0); } }
javascript
function branch(inst, list, argv, event, fin) { if (argv.length > 0) { // Append the argv for programs that return // a list that accepts them as parameters list = list.concat(argv.splice(0)); } // HACK HACK HACK. OK, so, when dealing with deeply recursive // functions in Runiq, we may hit an error where we exceed the // available call stack size. A setTimeout will get us a fresh // call stack, but at serious perf expense, since setTimeouts // end up triggered 4 ms later. So what I'm doing here is // trying to call unload, and if that gives an error, then // falling back to setTimeout method. This technique has an // incredible benefit, speeding up Runiq programs by 50X or so. // However, it could prove unworkable depending on browser support // for catching call-stack errors. try { return unload(inst, list, argv, event, fin); } catch (e) { return setTimeout(function branchCallback() { Console.printWarning(inst, "Caught call stack error: " + e); return unload(inst, list, argv, event, fin); }, 0); } }
[ "function", "branch", "(", "inst", ",", "list", ",", "argv", ",", "event", ",", "fin", ")", "{", "if", "(", "argv", ".", "length", ">", "0", ")", "{", "list", "=", "list", ".", "concat", "(", "argv", ".", "splice", "(", "0", ")", ")", ";", "}", "try", "{", "return", "unload", "(", "inst", ",", "list", ",", "argv", ",", "event", ",", "fin", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "setTimeout", "(", "function", "branchCallback", "(", ")", "{", "Console", ".", "printWarning", "(", "inst", ",", "\"Caught call stack error: \"", "+", "e", ")", ";", "return", "unload", "(", "inst", ",", "list", ",", "argv", ",", "event", ",", "fin", ")", ";", "}", ",", "0", ")", ";", "}", "}" ]
Force flow through a set timeout prior to executing the given list
[ "Force", "flow", "through", "a", "set", "timeout", "prior", "to", "executing", "the", "given", "list" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L245-L270
train
matthewtoast/runiq
interpreter/index.js
quote
function quote(inst, list, argv, event, fin) { // Remember to charge for the 'quote' function as a transaction if (!ok(inst, inst.options.quoteTransaction)) return exit(inst, list, fin); var entity = list[list.length - 1]; if (_isValue(entity)) return fin(null, entity); var quotation = {}; quotation[RUNIQ_QUOTED_ENTITY_PROP_NAME] = entity; return fin(null, quotation); }
javascript
function quote(inst, list, argv, event, fin) { // Remember to charge for the 'quote' function as a transaction if (!ok(inst, inst.options.quoteTransaction)) return exit(inst, list, fin); var entity = list[list.length - 1]; if (_isValue(entity)) return fin(null, entity); var quotation = {}; quotation[RUNIQ_QUOTED_ENTITY_PROP_NAME] = entity; return fin(null, quotation); }
[ "function", "quote", "(", "inst", ",", "list", ",", "argv", ",", "event", ",", "fin", ")", "{", "if", "(", "!", "ok", "(", "inst", ",", "inst", ".", "options", ".", "quoteTransaction", ")", ")", "return", "exit", "(", "inst", ",", "list", ",", "fin", ")", ";", "var", "entity", "=", "list", "[", "list", ".", "length", "-", "1", "]", ";", "if", "(", "_isValue", "(", "entity", ")", ")", "return", "fin", "(", "null", ",", "entity", ")", ";", "var", "quotation", "=", "{", "}", ";", "quotation", "[", "RUNIQ_QUOTED_ENTITY_PROP_NAME", "]", "=", "entity", ";", "return", "fin", "(", "null", ",", "quotation", ")", ";", "}" ]
Given a quote list, return a quote object for later use
[ "Given", "a", "quote", "list", "return", "a", "quote", "object", "for", "later", "use" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L288-L296
train
matthewtoast/runiq
interpreter/index.js
sequence
function sequence(inst, elems, argv, event, fin) { if (elems.length < 1) return fin(null, elems); // Running a sequence also costs some amount per element to sequence if (!ok(inst, inst.options.sequenceTransaction * elems.length)) { return exit(inst, list, fin); } return parallel(inst, elems, argv, event, fin, postSequence); }
javascript
function sequence(inst, elems, argv, event, fin) { if (elems.length < 1) return fin(null, elems); // Running a sequence also costs some amount per element to sequence if (!ok(inst, inst.options.sequenceTransaction * elems.length)) { return exit(inst, list, fin); } return parallel(inst, elems, argv, event, fin, postSequence); }
[ "function", "sequence", "(", "inst", ",", "elems", ",", "argv", ",", "event", ",", "fin", ")", "{", "if", "(", "elems", ".", "length", "<", "1", ")", "return", "fin", "(", "null", ",", "elems", ")", ";", "if", "(", "!", "ok", "(", "inst", ",", "inst", ".", "options", ".", "sequenceTransaction", "*", "elems", ".", "length", ")", ")", "{", "return", "exit", "(", "inst", ",", "list", ",", "fin", ")", ";", "}", "return", "parallel", "(", "inst", ",", "elems", ",", "argv", ",", "event", ",", "fin", ",", "postSequence", ")", ";", "}" ]
Get values for each list element. Subproc any elements that are lists
[ "Get", "values", "for", "each", "list", "element", ".", "Subproc", "any", "elements", "that", "are", "lists" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L386-L393
train
matthewtoast/runiq
interpreter/index.js
parallel
function parallel(inst, elems, argv, event, fin, _postSequence) { var total = elems.length; var complete = 0; function check(err, list) { if (total === ++complete) { if (!_isFunc(list)) return _postSequence(list, fin); return fin(err, list); } } for (var i = 0; i < total; i++) { if (_isList(elems[i])) { var after = edit(inst, elems, i, argv, event, check); branch(inst, elems[i], argv, event, after); } else { check(null, elems); } } }
javascript
function parallel(inst, elems, argv, event, fin, _postSequence) { var total = elems.length; var complete = 0; function check(err, list) { if (total === ++complete) { if (!_isFunc(list)) return _postSequence(list, fin); return fin(err, list); } } for (var i = 0; i < total; i++) { if (_isList(elems[i])) { var after = edit(inst, elems, i, argv, event, check); branch(inst, elems[i], argv, event, after); } else { check(null, elems); } } }
[ "function", "parallel", "(", "inst", ",", "elems", ",", "argv", ",", "event", ",", "fin", ",", "_postSequence", ")", "{", "var", "total", "=", "elems", ".", "length", ";", "var", "complete", "=", "0", ";", "function", "check", "(", "err", ",", "list", ")", "{", "if", "(", "total", "===", "++", "complete", ")", "{", "if", "(", "!", "_isFunc", "(", "list", ")", ")", "return", "_postSequence", "(", "list", ",", "fin", ")", ";", "return", "fin", "(", "err", ",", "list", ")", ";", "}", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "total", ";", "i", "++", ")", "{", "if", "(", "_isList", "(", "elems", "[", "i", "]", ")", ")", "{", "var", "after", "=", "edit", "(", "inst", ",", "elems", ",", "i", ",", "argv", ",", "event", ",", "check", ")", ";", "branch", "(", "inst", ",", "elems", "[", "i", "]", ",", "argv", ",", "event", ",", "after", ")", ";", "}", "else", "{", "check", "(", "null", ",", "elems", ")", ";", "}", "}", "}" ]
Run the sequence in parallel
[ "Run", "the", "sequence", "in", "parallel" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L396-L414
train
matthewtoast/runiq
interpreter/index.js
postSequence
function postSequence(elems, fin) { // Treat the final value of a sequence as its return value var toReturn = elems[elems.length - 1]; return fin(null, toReturn); }
javascript
function postSequence(elems, fin) { // Treat the final value of a sequence as its return value var toReturn = elems[elems.length - 1]; return fin(null, toReturn); }
[ "function", "postSequence", "(", "elems", ",", "fin", ")", "{", "var", "toReturn", "=", "elems", "[", "elems", ".", "length", "-", "1", "]", ";", "return", "fin", "(", "null", ",", "toReturn", ")", ";", "}" ]
Fire this function after completing a sequence of lists
[ "Fire", "this", "function", "after", "completing", "a", "sequence", "of", "lists" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L417-L421
train
matthewtoast/runiq
interpreter/index.js
edit
function edit(inst, list, index, argv, event, fin) { return function editCallback(err, data) { if (err) return fin(err); list[index] = data; return fin(null, list); }; }
javascript
function edit(inst, list, index, argv, event, fin) { return function editCallback(err, data) { if (err) return fin(err); list[index] = data; return fin(null, list); }; }
[ "function", "edit", "(", "inst", ",", "list", ",", "index", ",", "argv", ",", "event", ",", "fin", ")", "{", "return", "function", "editCallback", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "fin", "(", "err", ")", ";", "list", "[", "index", "]", "=", "data", ";", "return", "fin", "(", "null", ",", "list", ")", ";", "}", ";", "}" ]
Return a function to patch a subroutine result into a parent list
[ "Return", "a", "function", "to", "patch", "a", "subroutine", "result", "into", "a", "parent", "list" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L424-L430
train
matthewtoast/runiq
interpreter/index.js
_valuefyArgs
function _valuefyArgs(args, lib) { for (var i = 0; i < args.length; i++) { args[i] = _entityToValue(args[i], lib); } }
javascript
function _valuefyArgs(args, lib) { for (var i = 0; i < args.length; i++) { args[i] = _entityToValue(args[i], lib); } }
[ "function", "_valuefyArgs", "(", "args", ",", "lib", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "args", "[", "i", "]", "=", "_entityToValue", "(", "args", "[", "i", "]", ",", "lib", ")", ";", "}", "}" ]
Convert 'const' args to their values when they are defined
[ "Convert", "const", "args", "to", "their", "values", "when", "they", "are", "defined" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L433-L437
train
matthewtoast/runiq
interpreter/index.js
_unquoteArgs
function _unquoteArgs(args) { for (var i = 0; i < args.length; i++) { if (_isQuoted(args[i])) args[i] = _unquote(args[i]); } }
javascript
function _unquoteArgs(args) { for (var i = 0; i < args.length; i++) { if (_isQuoted(args[i])) args[i] = _unquote(args[i]); } }
[ "function", "_unquoteArgs", "(", "args", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "if", "(", "_isQuoted", "(", "args", "[", "i", "]", ")", ")", "args", "[", "i", "]", "=", "_unquote", "(", "args", "[", "i", "]", ")", ";", "}", "}" ]
Unquote the arguments. This modifies the arguments in place
[ "Unquote", "the", "arguments", ".", "This", "modifies", "the", "arguments", "in", "place" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L440-L444
train
matthewtoast/runiq
interpreter/index.js
_entityToValue
function _entityToValue(item, lib) { if (typeof item === JS_STRING_TYPE) { // Only JSON-serializable entities may be put into a list var constant = lib.lookupConstant(item); if (constant !== undefined) return constant; } // Also unquote any item we got that also happens to be a quote if (item && item[RUNIQ_QUOTED_ENTITY_PROP_NAME]) { return item[RUNIQ_QUOTED_ENTITY_PROP_NAME]; } return item; }
javascript
function _entityToValue(item, lib) { if (typeof item === JS_STRING_TYPE) { // Only JSON-serializable entities may be put into a list var constant = lib.lookupConstant(item); if (constant !== undefined) return constant; } // Also unquote any item we got that also happens to be a quote if (item && item[RUNIQ_QUOTED_ENTITY_PROP_NAME]) { return item[RUNIQ_QUOTED_ENTITY_PROP_NAME]; } return item; }
[ "function", "_entityToValue", "(", "item", ",", "lib", ")", "{", "if", "(", "typeof", "item", "===", "JS_STRING_TYPE", ")", "{", "var", "constant", "=", "lib", ".", "lookupConstant", "(", "item", ")", ";", "if", "(", "constant", "!==", "undefined", ")", "return", "constant", ";", "}", "if", "(", "item", "&&", "item", "[", "RUNIQ_QUOTED_ENTITY_PROP_NAME", "]", ")", "{", "return", "item", "[", "RUNIQ_QUOTED_ENTITY_PROP_NAME", "]", ";", "}", "return", "item", ";", "}" ]
Convert a given entity to a value, if one is defined in the lib
[ "Convert", "a", "given", "entity", "to", "a", "value", "if", "one", "is", "defined", "in", "the", "lib" ]
897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d
https://github.com/matthewtoast/runiq/blob/897ce0c919a9eb6dd0ae1825f0ab1222c42f9d1d/interpreter/index.js#L447-L458
train
moshekarmel1/node-sql
index.js
exec
function exec(query, config, done) { if(!query || (typeof query != 'string')){ throw new Error('Node-SQL: query was not in the correct format.'); return; } if(!config || (typeof config != 'object')){ throw new Error('Node-SQL: config was not in the correct format.'); return; } if(!done || (typeof done != 'function')){ done = function(a, b){}; } var connection = new Connection(config); connection.on('connect', function(err) { if(err){ done(err, null); return; } var request = new Request(query, function(_err) { if (_err) { done(_err, null); return; } connection.close(); }); var result = []; request.on('row', function(columns) { var row = {}; columns.forEach(function(column) { row[column.metadata.colName] = column.value; }); result.push(row); }); request.on('doneProc', function(rowCount, more, returnStatus) { if(returnStatus == 0) done(null, result); }); connection.execSql(request); }); }
javascript
function exec(query, config, done) { if(!query || (typeof query != 'string')){ throw new Error('Node-SQL: query was not in the correct format.'); return; } if(!config || (typeof config != 'object')){ throw new Error('Node-SQL: config was not in the correct format.'); return; } if(!done || (typeof done != 'function')){ done = function(a, b){}; } var connection = new Connection(config); connection.on('connect', function(err) { if(err){ done(err, null); return; } var request = new Request(query, function(_err) { if (_err) { done(_err, null); return; } connection.close(); }); var result = []; request.on('row', function(columns) { var row = {}; columns.forEach(function(column) { row[column.metadata.colName] = column.value; }); result.push(row); }); request.on('doneProc', function(rowCount, more, returnStatus) { if(returnStatus == 0) done(null, result); }); connection.execSql(request); }); }
[ "function", "exec", "(", "query", ",", "config", ",", "done", ")", "{", "if", "(", "!", "query", "||", "(", "typeof", "query", "!=", "'string'", ")", ")", "{", "throw", "new", "Error", "(", "'Node-SQL: query was not in the correct format.'", ")", ";", "return", ";", "}", "if", "(", "!", "config", "||", "(", "typeof", "config", "!=", "'object'", ")", ")", "{", "throw", "new", "Error", "(", "'Node-SQL: config was not in the correct format.'", ")", ";", "return", ";", "}", "if", "(", "!", "done", "||", "(", "typeof", "done", "!=", "'function'", ")", ")", "{", "done", "=", "function", "(", "a", ",", "b", ")", "{", "}", ";", "}", "var", "connection", "=", "new", "Connection", "(", "config", ")", ";", "connection", ".", "on", "(", "'connect'", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "done", "(", "err", ",", "null", ")", ";", "return", ";", "}", "var", "request", "=", "new", "Request", "(", "query", ",", "function", "(", "_err", ")", "{", "if", "(", "_err", ")", "{", "done", "(", "_err", ",", "null", ")", ";", "return", ";", "}", "connection", ".", "close", "(", ")", ";", "}", ")", ";", "var", "result", "=", "[", "]", ";", "request", ".", "on", "(", "'row'", ",", "function", "(", "columns", ")", "{", "var", "row", "=", "{", "}", ";", "columns", ".", "forEach", "(", "function", "(", "column", ")", "{", "row", "[", "column", ".", "metadata", ".", "colName", "]", "=", "column", ".", "value", ";", "}", ")", ";", "result", ".", "push", "(", "row", ")", ";", "}", ")", ";", "request", ".", "on", "(", "'doneProc'", ",", "function", "(", "rowCount", ",", "more", ",", "returnStatus", ")", "{", "if", "(", "returnStatus", "==", "0", ")", "done", "(", "null", ",", "result", ")", ";", "}", ")", ";", "connection", ".", "execSql", "(", "request", ")", ";", "}", ")", ";", "}" ]
Executes a sql query @param {string} query -- good old query string @param {Object} config -- standard tedious config object @param {Function} done -- standard node callback
[ "Executes", "a", "sql", "query" ]
59cd089cbef4845baf777adfa5aaf332276e022d
https://github.com/moshekarmel1/node-sql/blob/59cd089cbef4845baf777adfa5aaf332276e022d/index.js#L20-L58
train
rootsdev/gedcomx-js
src/core/Person.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Person)){ return new Person(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Person.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Person)){ return new Person(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Person.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Person", ")", ")", "{", "return", "new", "Person", "(", "json", ")", ";", "}", "if", "(", "Person", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A person. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#person|GEDCOM X JSON Spec} @class @extends Subject @param {Object} [json]
[ "A", "person", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Person.js#L13-L26
train
dciccale/css2stylus.js
lib/css2stylus.js
function (str, n) { n = window.parseInt(n, 10); return new Array(n + 1).join(str); }
javascript
function (str, n) { n = window.parseInt(n, 10); return new Array(n + 1).join(str); }
[ "function", "(", "str", ",", "n", ")", "{", "n", "=", "window", ".", "parseInt", "(", "n", ",", "10", ")", ";", "return", "new", "Array", "(", "n", "+", "1", ")", ".", "join", "(", "str", ")", ";", "}" ]
_repeat same string n times
[ "_repeat", "same", "string", "n", "times" ]
86b3fa92bfe0d59eb3390ce41cc8d90bd751afac
https://github.com/dciccale/css2stylus.js/blob/86b3fa92bfe0d59eb3390ce41cc8d90bd751afac/lib/css2stylus.js#L261-L264
train
Ubudu/uBeacon-uart-lib
node/examples/eddystone-setter.js
function(callback){ ubeacon.setEddystoneURL( program.url , function(data, error){ console.log('Set URL to', data ); callback(error); }); }
javascript
function(callback){ ubeacon.setEddystoneURL( program.url , function(data, error){ console.log('Set URL to', data ); callback(error); }); }
[ "function", "(", "callback", ")", "{", "ubeacon", ".", "setEddystoneURL", "(", "program", ".", "url", ",", "function", "(", "data", ",", "error", ")", "{", "console", ".", "log", "(", "'Set URL to'", ",", "data", ")", ";", "callback", "(", "error", ")", ";", "}", ")", ";", "}" ]
Set new url
[ "Set", "new", "url" ]
a7436f3491f61ffabb34e2bc3b2441cc048f5dfa
https://github.com/Ubudu/uBeacon-uart-lib/blob/a7436f3491f61ffabb34e2bc3b2441cc048f5dfa/node/examples/eddystone-setter.js#L31-L36
train
seykron/json-index
lib/JsonIndex.js
function () { return new Promise((resolve, reject) => { var startTime = Date.now(); var size = fs.statSync(dataFile).size; var next = (readInfo, position) => { var jobs = [readNextChunk(readInfo)]; if (position) { jobs.push(readAndIndex(position, readInfo.readBuffer)); debug(position); } Q.all(jobs).then(results => { var nextReadInfo = results[0]; var nextPosition = results[1] || {}; readInfo.readBuffer = null; if (nextReadInfo.done && position) { debug("indexSize size: %s", (indexSize / 1024) + "KB"); debug("index ready (took %s secs)", (Date.now() - startTime) / 1000); meta.size = indexSize; debug(meta); resolve(); } else { next(nextReadInfo, nextPosition); } }).catch(err => reject(err)); }; debug("creating index"); next({ size: size, fd: openDataFile() }); }); }
javascript
function () { return new Promise((resolve, reject) => { var startTime = Date.now(); var size = fs.statSync(dataFile).size; var next = (readInfo, position) => { var jobs = [readNextChunk(readInfo)]; if (position) { jobs.push(readAndIndex(position, readInfo.readBuffer)); debug(position); } Q.all(jobs).then(results => { var nextReadInfo = results[0]; var nextPosition = results[1] || {}; readInfo.readBuffer = null; if (nextReadInfo.done && position) { debug("indexSize size: %s", (indexSize / 1024) + "KB"); debug("index ready (took %s secs)", (Date.now() - startTime) / 1000); meta.size = indexSize; debug(meta); resolve(); } else { next(nextReadInfo, nextPosition); } }).catch(err => reject(err)); }; debug("creating index"); next({ size: size, fd: openDataFile() }); }); }
[ "function", "(", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "var", "startTime", "=", "Date", ".", "now", "(", ")", ";", "var", "size", "=", "fs", ".", "statSync", "(", "dataFile", ")", ".", "size", ";", "var", "next", "=", "(", "readInfo", ",", "position", ")", "=>", "{", "var", "jobs", "=", "[", "readNextChunk", "(", "readInfo", ")", "]", ";", "if", "(", "position", ")", "{", "jobs", ".", "push", "(", "readAndIndex", "(", "position", ",", "readInfo", ".", "readBuffer", ")", ")", ";", "debug", "(", "position", ")", ";", "}", "Q", ".", "all", "(", "jobs", ")", ".", "then", "(", "results", "=>", "{", "var", "nextReadInfo", "=", "results", "[", "0", "]", ";", "var", "nextPosition", "=", "results", "[", "1", "]", "||", "{", "}", ";", "readInfo", ".", "readBuffer", "=", "null", ";", "if", "(", "nextReadInfo", ".", "done", "&&", "position", ")", "{", "debug", "(", "\"indexSize size: %s\"", ",", "(", "indexSize", "/", "1024", ")", "+", "\"KB\"", ")", ";", "debug", "(", "\"index ready (took %s secs)\"", ",", "(", "Date", ".", "now", "(", ")", "-", "startTime", ")", "/", "1000", ")", ";", "meta", ".", "size", "=", "indexSize", ";", "debug", "(", "meta", ")", ";", "resolve", "(", ")", ";", "}", "else", "{", "next", "(", "nextReadInfo", ",", "nextPosition", ")", ";", "}", "}", ")", ".", "catch", "(", "err", "=>", "reject", "(", "err", ")", ")", ";", "}", ";", "debug", "(", "\"creating index\"", ")", ";", "next", "(", "{", "size", ":", "size", ",", "fd", ":", "openDataFile", "(", ")", "}", ")", ";", "}", ")", ";", "}" ]
Creates the index. The index consist of a map from a user-specific key to the position within the buffer where the item starts and ends. Items are read lazily when it is required.
[ "Creates", "the", "index", ".", "The", "index", "consist", "of", "a", "map", "from", "a", "user", "-", "specific", "key", "to", "the", "position", "within", "the", "buffer", "where", "the", "item", "starts", "and", "ends", ".", "Items", "are", "read", "lazily", "when", "it", "is", "required", "." ]
b7f354197fc7129749032695e244f58954aa921d
https://github.com/seykron/json-index/blob/b7f354197fc7129749032695e244f58954aa921d/lib/JsonIndex.js#L261-L297
train
seykron/json-index
lib/JsonIndex.js
function (indexName, key) { return new Promise((resolve, reject) => { if (index[indexName]) { resolve(index[indexName][key] || null); } else { debug("opening index %s", indexName); storage.openIndex(indexName).then(index => { index[indexName] = index; resolve(index[indexName][key] || null); }); } }); }
javascript
function (indexName, key) { return new Promise((resolve, reject) => { if (index[indexName]) { resolve(index[indexName][key] || null); } else { debug("opening index %s", indexName); storage.openIndex(indexName).then(index => { index[indexName] = index; resolve(index[indexName][key] || null); }); } }); }
[ "function", "(", "indexName", ",", "key", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "index", "[", "indexName", "]", ")", "{", "resolve", "(", "index", "[", "indexName", "]", "[", "key", "]", "||", "null", ")", ";", "}", "else", "{", "debug", "(", "\"opening index %s\"", ",", "indexName", ")", ";", "storage", ".", "openIndex", "(", "indexName", ")", ".", "then", "(", "index", "=>", "{", "index", "[", "indexName", "]", "=", "index", ";", "resolve", "(", "index", "[", "indexName", "]", "[", "key", "]", "||", "null", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Returns an item from the index. @param {String} indexName Name of the index to query. Cannot be null. @param {String} key Unique key of the required item. Cannot be null.
[ "Returns", "an", "item", "from", "the", "index", "." ]
b7f354197fc7129749032695e244f58954aa921d
https://github.com/seykron/json-index/blob/b7f354197fc7129749032695e244f58954aa921d/lib/JsonIndex.js#L303-L315
train
WebReflection/sob
build/sob.max.amd.js
function (id) { return typeof id === 'number' ? clear(id) : void( drop(qframe, id) || drop(qidle, id) || drop(qframex, id) || drop(qidlex, id) ); }
javascript
function (id) { return typeof id === 'number' ? clear(id) : void( drop(qframe, id) || drop(qidle, id) || drop(qframex, id) || drop(qidlex, id) ); }
[ "function", "(", "id", ")", "{", "return", "typeof", "id", "===", "'number'", "?", "clear", "(", "id", ")", ":", "void", "(", "drop", "(", "qframe", ",", "id", ")", "||", "drop", "(", "qidle", ",", "id", ")", "||", "drop", "(", "qframex", ",", "id", ")", "||", "drop", "(", "qidlex", ",", "id", ")", ")", ";", "}" ]
remove a scheduled frame, idle, or timer operation
[ "remove", "a", "scheduled", "frame", "idle", "or", "timer", "operation" ]
8f62b2dd3454ea4955f27c6cdce0dab64142288a
https://github.com/WebReflection/sob/blob/8f62b2dd3454ea4955f27c6cdce0dab64142288a/build/sob.max.amd.js#L87-L96
train
WebReflection/sob
build/sob.max.amd.js
animationLoop
function animationLoop() { var // grab current time t = time(), // calculate how many millisends we have fps = 1000 / next.minFPS, // used to flag overtime in case we exceed milliseconds overTime = false, // take current frame queue length length = getLength(qframe, qframex) ; // if there is actually something to do if (length) { // reschedule upfront next animation frame // this prevents the need for a try/catch within the while loop requestAnimationFrame(animationLoop); // reassign qframex cleaning current animation frame queue qframex = qframe.splice(0, length); while (qframex.length) { // if some of them fails, it's OK // next round will re-prioritize the animation frame queue exec(qframex.shift()); // if we exceeded the frame time, get out this loop overTime = (time() - t) >= fps; if ((next.isOverloaded = overTime)) break; } // if overtime and debug is true, warn about it if (overTime && next.debug) console.warn('overloaded frame'); } else { // all frame callbacks have been executed // we can actually stop asking for animation frames frameRunning = false; // and flag it as non busy/overloaded anymore next.isOverloaded = frameRunning; } }
javascript
function animationLoop() { var // grab current time t = time(), // calculate how many millisends we have fps = 1000 / next.minFPS, // used to flag overtime in case we exceed milliseconds overTime = false, // take current frame queue length length = getLength(qframe, qframex) ; // if there is actually something to do if (length) { // reschedule upfront next animation frame // this prevents the need for a try/catch within the while loop requestAnimationFrame(animationLoop); // reassign qframex cleaning current animation frame queue qframex = qframe.splice(0, length); while (qframex.length) { // if some of them fails, it's OK // next round will re-prioritize the animation frame queue exec(qframex.shift()); // if we exceeded the frame time, get out this loop overTime = (time() - t) >= fps; if ((next.isOverloaded = overTime)) break; } // if overtime and debug is true, warn about it if (overTime && next.debug) console.warn('overloaded frame'); } else { // all frame callbacks have been executed // we can actually stop asking for animation frames frameRunning = false; // and flag it as non busy/overloaded anymore next.isOverloaded = frameRunning; } }
[ "function", "animationLoop", "(", ")", "{", "var", "t", "=", "time", "(", ")", ",", "fps", "=", "1000", "/", "next", ".", "minFPS", ",", "overTime", "=", "false", ",", "length", "=", "getLength", "(", "qframe", ",", "qframex", ")", ";", "if", "(", "length", ")", "{", "requestAnimationFrame", "(", "animationLoop", ")", ";", "qframex", "=", "qframe", ".", "splice", "(", "0", ",", "length", ")", ";", "while", "(", "qframex", ".", "length", ")", "{", "exec", "(", "qframex", ".", "shift", "(", ")", ")", ";", "overTime", "=", "(", "time", "(", ")", "-", "t", ")", ">=", "fps", ";", "if", "(", "(", "next", ".", "isOverloaded", "=", "overTime", ")", ")", "break", ";", "}", "if", "(", "overTime", "&&", "next", ".", "debug", ")", "console", ".", "warn", "(", "'overloaded frame'", ")", ";", "}", "else", "{", "frameRunning", "=", "false", ";", "next", ".", "isOverloaded", "=", "frameRunning", ";", "}", "}" ]
responsible for centralized requestAnimationFrame operations
[ "responsible", "for", "centralized", "requestAnimationFrame", "operations" ]
8f62b2dd3454ea4955f27c6cdce0dab64142288a
https://github.com/WebReflection/sob/blob/8f62b2dd3454ea4955f27c6cdce0dab64142288a/build/sob.max.amd.js#L158-L193
train
WebReflection/sob
build/sob.max.amd.js
create
function create(callback) { /* jslint validthis: true */ for (var queue = this, args = [], info = { id: {}, fn: callback, ar: args }, i = 1; i < arguments.length; i++ ) args[i - 1] = arguments[i]; return infoId(queue, info) || (queue.push(info), info.id); }
javascript
function create(callback) { /* jslint validthis: true */ for (var queue = this, args = [], info = { id: {}, fn: callback, ar: args }, i = 1; i < arguments.length; i++ ) args[i - 1] = arguments[i]; return infoId(queue, info) || (queue.push(info), info.id); }
[ "function", "create", "(", "callback", ")", "{", "for", "(", "var", "queue", "=", "this", ",", "args", "=", "[", "]", ",", "info", "=", "{", "id", ":", "{", "}", ",", "fn", ":", "callback", ",", "ar", ":", "args", "}", ",", "i", "=", "1", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "args", "[", "i", "-", "1", "]", "=", "arguments", "[", "i", "]", ";", "return", "infoId", "(", "queue", ",", "info", ")", "||", "(", "queue", ".", "push", "(", "info", ")", ",", "info", ".", "id", ")", ";", "}" ]
create a unique id and returns it if the callback with same extra arguments was already scheduled, then returns same id
[ "create", "a", "unique", "id", "and", "returns", "it", "if", "the", "callback", "with", "same", "extra", "arguments", "was", "already", "scheduled", "then", "returns", "same", "id" ]
8f62b2dd3454ea4955f27c6cdce0dab64142288a
https://github.com/WebReflection/sob/blob/8f62b2dd3454ea4955f27c6cdce0dab64142288a/build/sob.max.amd.js#L198-L211
train
WebReflection/sob
build/sob.max.amd.js
drop
function drop(queue, id) { var i = findIndex(queue, id), found = -1 < i ; if (found) queue.splice(i, 1); return found; }
javascript
function drop(queue, id) { var i = findIndex(queue, id), found = -1 < i ; if (found) queue.splice(i, 1); return found; }
[ "function", "drop", "(", "queue", ",", "id", ")", "{", "var", "i", "=", "findIndex", "(", "queue", ",", "id", ")", ",", "found", "=", "-", "1", "<", "i", ";", "if", "(", "found", ")", "queue", ".", "splice", "(", "i", ",", "1", ")", ";", "return", "found", ";", "}" ]
remove a scheduled id from a queue
[ "remove", "a", "scheduled", "id", "from", "a", "queue" ]
8f62b2dd3454ea4955f27c6cdce0dab64142288a
https://github.com/WebReflection/sob/blob/8f62b2dd3454ea4955f27c6cdce0dab64142288a/build/sob.max.amd.js#L231-L238
train
WebReflection/sob
build/sob.max.amd.js
findIndex
function findIndex(queue, id) { var i = queue.length; while (i-- && queue[i].id !== id); return i; }
javascript
function findIndex(queue, id) { var i = queue.length; while (i-- && queue[i].id !== id); return i; }
[ "function", "findIndex", "(", "queue", ",", "id", ")", "{", "var", "i", "=", "queue", ".", "length", ";", "while", "(", "i", "--", "&&", "queue", "[", "i", "]", ".", "id", "!==", "id", ")", ";", "return", "i", ";", "}" ]
find queue index by id
[ "find", "queue", "index", "by", "id" ]
8f62b2dd3454ea4955f27c6cdce0dab64142288a
https://github.com/WebReflection/sob/blob/8f62b2dd3454ea4955f27c6cdce0dab64142288a/build/sob.max.amd.js#L246-L250
train
WebReflection/sob
build/sob.max.amd.js
getLength
function getLength(queue, queuex) { // if previous call didn't execute all callbacks return queuex.length ? // reprioritize the queue putting those in front queue.unshift.apply(queue, queuex) : queue.length; }
javascript
function getLength(queue, queuex) { // if previous call didn't execute all callbacks return queuex.length ? // reprioritize the queue putting those in front queue.unshift.apply(queue, queuex) : queue.length; }
[ "function", "getLength", "(", "queue", ",", "queuex", ")", "{", "return", "queuex", ".", "length", "?", "queue", ".", "unshift", ".", "apply", "(", "queue", ",", "queuex", ")", ":", "queue", ".", "length", ";", "}" ]
return the right queue length to consider re-prioritizing scheduled callbacks
[ "return", "the", "right", "queue", "length", "to", "consider", "re", "-", "prioritizing", "scheduled", "callbacks" ]
8f62b2dd3454ea4955f27c6cdce0dab64142288a
https://github.com/WebReflection/sob/blob/8f62b2dd3454ea4955f27c6cdce0dab64142288a/build/sob.max.amd.js#L254-L260
train
WebReflection/sob
build/sob.max.amd.js
idleLoop
function idleLoop(deadline) { var length = getLength(qidle, qidlex), didTimeout = deadline.didTimeout ; if (length) { // reschedule upfront next idle callback requestIdleCallback(idleLoop, {timeout: next.maxIdle}); // this prevents the need for a try/catch within the while loop // reassign qidlex cleaning current idle queue qidlex = qidle.splice(0, didTimeout ? 1 : length); while (qidlex.length && (didTimeout || deadline.timeRemaining())) exec(qidlex.shift()); } else { // all idle callbacks have been executed // we can actually stop asking for idle operations idleRunning = false; } }
javascript
function idleLoop(deadline) { var length = getLength(qidle, qidlex), didTimeout = deadline.didTimeout ; if (length) { // reschedule upfront next idle callback requestIdleCallback(idleLoop, {timeout: next.maxIdle}); // this prevents the need for a try/catch within the while loop // reassign qidlex cleaning current idle queue qidlex = qidle.splice(0, didTimeout ? 1 : length); while (qidlex.length && (didTimeout || deadline.timeRemaining())) exec(qidlex.shift()); } else { // all idle callbacks have been executed // we can actually stop asking for idle operations idleRunning = false; } }
[ "function", "idleLoop", "(", "deadline", ")", "{", "var", "length", "=", "getLength", "(", "qidle", ",", "qidlex", ")", ",", "didTimeout", "=", "deadline", ".", "didTimeout", ";", "if", "(", "length", ")", "{", "requestIdleCallback", "(", "idleLoop", ",", "{", "timeout", ":", "next", ".", "maxIdle", "}", ")", ";", "qidlex", "=", "qidle", ".", "splice", "(", "0", ",", "didTimeout", "?", "1", ":", "length", ")", ";", "while", "(", "qidlex", ".", "length", "&&", "(", "didTimeout", "||", "deadline", ".", "timeRemaining", "(", ")", ")", ")", "exec", "(", "qidlex", ".", "shift", "(", ")", ")", ";", "}", "else", "{", "idleRunning", "=", "false", ";", "}", "}" ]
responsible for centralized requestIdleCallback operations
[ "responsible", "for", "centralized", "requestIdleCallback", "operations" ]
8f62b2dd3454ea4955f27c6cdce0dab64142288a
https://github.com/WebReflection/sob/blob/8f62b2dd3454ea4955f27c6cdce0dab64142288a/build/sob.max.amd.js#L263-L281
train
WebReflection/sob
build/sob.max.amd.js
infoId
function infoId(queue, info) { for (var i = 0, length = queue.length, tmp; i < length; i++) { tmp = queue[i]; if ( tmp.fn === info.fn && sameValues(tmp.ar, info.ar) ) return tmp.id; } return null; }
javascript
function infoId(queue, info) { for (var i = 0, length = queue.length, tmp; i < length; i++) { tmp = queue[i]; if ( tmp.fn === info.fn && sameValues(tmp.ar, info.ar) ) return tmp.id; } return null; }
[ "function", "infoId", "(", "queue", ",", "info", ")", "{", "for", "(", "var", "i", "=", "0", ",", "length", "=", "queue", ".", "length", ",", "tmp", ";", "i", "<", "length", ";", "i", "++", ")", "{", "tmp", "=", "queue", "[", "i", "]", ";", "if", "(", "tmp", ".", "fn", "===", "info", ".", "fn", "&&", "sameValues", "(", "tmp", ".", "ar", ",", "info", ".", "ar", ")", ")", "return", "tmp", ".", "id", ";", "}", "return", "null", ";", "}" ]
return a scheduled unique id through similar info
[ "return", "a", "scheduled", "unique", "id", "through", "similar", "info" ]
8f62b2dd3454ea4955f27c6cdce0dab64142288a
https://github.com/WebReflection/sob/blob/8f62b2dd3454ea4955f27c6cdce0dab64142288a/build/sob.max.amd.js#L284-L293
train
WebReflection/sob
build/sob.max.amd.js
sameValues
function sameValues(a, b) { var i = a.length, j = b.length, k = i === j ; if (k) { while (i--) { if (a[i] !== b[i]) { return !k; } } } return k; }
javascript
function sameValues(a, b) { var i = a.length, j = b.length, k = i === j ; if (k) { while (i--) { if (a[i] !== b[i]) { return !k; } } } return k; }
[ "function", "sameValues", "(", "a", ",", "b", ")", "{", "var", "i", "=", "a", ".", "length", ",", "j", "=", "b", ".", "length", ",", "k", "=", "i", "===", "j", ";", "if", "(", "k", ")", "{", "while", "(", "i", "--", ")", "{", "if", "(", "a", "[", "i", "]", "!==", "b", "[", "i", "]", ")", "{", "return", "!", "k", ";", "}", "}", "}", "return", "k", ";", "}" ]
compare two arrays values
[ "compare", "two", "arrays", "values" ]
8f62b2dd3454ea4955f27c6cdce0dab64142288a
https://github.com/WebReflection/sob/blob/8f62b2dd3454ea4955f27c6cdce0dab64142288a/build/sob.max.amd.js#L307-L321
train
apparebit/js-junction
packages/knowledge/json-ld/state.js
asPath
function asPath({ ancestors }) { const path = []; for (const { key } of ancestors) { if (key != null) { if (typeof key === 'number') { path.push(`[${key}]`); } else { path.push(`['${stringify(key).slice(1, -1)}']`); } } } return path.join(''); }
javascript
function asPath({ ancestors }) { const path = []; for (const { key } of ancestors) { if (key != null) { if (typeof key === 'number') { path.push(`[${key}]`); } else { path.push(`['${stringify(key).slice(1, -1)}']`); } } } return path.join(''); }
[ "function", "asPath", "(", "{", "ancestors", "}", ")", "{", "const", "path", "=", "[", "]", ";", "for", "(", "const", "{", "key", "}", "of", "ancestors", ")", "{", "if", "(", "key", "!=", "null", ")", "{", "if", "(", "typeof", "key", "===", "'number'", ")", "{", "path", ".", "push", "(", "`", "${", "key", "}", "`", ")", ";", "}", "else", "{", "path", ".", "push", "(", "`", "${", "stringify", "(", "key", ")", ".", "slice", "(", "1", ",", "-", "1", ")", "}", "`", ")", ";", "}", "}", "}", "return", "path", ".", "join", "(", "''", ")", ";", "}" ]
Based on `key` in ancestral records, format property path to offending entity.
[ "Based", "on", "key", "in", "ancestral", "records", "format", "property", "path", "to", "offending", "entity", "." ]
240b15961c35f19c3a1effd9df51e0bf8e0bbffc
https://github.com/apparebit/js-junction/blob/240b15961c35f19c3a1effd9df51e0bf8e0bbffc/packages/knowledge/json-ld/state.js#L11-L25
train
jaredhanson/junction-disco
lib/junction-disco/elements/identity.js
Identity
function Identity(category, type, name) { Element.call(this, 'identity', 'http://jabber.org/protocol/disco#info'); this.category = category; this.type = type; this.displayName = name; }
javascript
function Identity(category, type, name) { Element.call(this, 'identity', 'http://jabber.org/protocol/disco#info'); this.category = category; this.type = type; this.displayName = name; }
[ "function", "Identity", "(", "category", ",", "type", ",", "name", ")", "{", "Element", ".", "call", "(", "this", ",", "'identity'", ",", "'http://jabber.org/protocol/disco#info'", ")", ";", "this", ".", "category", "=", "category", ";", "this", ".", "type", "=", "type", ";", "this", ".", "displayName", "=", "name", ";", "}" ]
Initialize a new `Identity` element. @param {String} category @param {String} type @param {String} name @api public
[ "Initialize", "a", "new", "Identity", "element", "." ]
89f2d222518b3b0f282d54b25d6405b5e35c1383
https://github.com/jaredhanson/junction-disco/blob/89f2d222518b3b0f282d54b25d6405b5e35c1383/lib/junction-disco/elements/identity.js#L15-L20
train
observing/exception
index.js
Exception
function Exception(err, options) { if (!(this instanceof Exception)) return new Exception(err, options); if ('string' === typeof err) err = { stack: (new Error(err)).stack, message: err }; debug('generating a new exception for: %s', err.message); options = options || {}; this.initialize(options); this.message = err.message || 'An unknown Exception has occurred'; this.timeout = options.timeout || 10000; this.stack = err.stack || ''; this.human = !!options.human; this.filename = new Date().toDateString().split(' ').concat([ this.appname, // Name of the library or app that included us. process.pid, // The current process id this.id // Unique id for this exception. ]).filter(Boolean).join('-'); this.capture = this.toJSON(); }
javascript
function Exception(err, options) { if (!(this instanceof Exception)) return new Exception(err, options); if ('string' === typeof err) err = { stack: (new Error(err)).stack, message: err }; debug('generating a new exception for: %s', err.message); options = options || {}; this.initialize(options); this.message = err.message || 'An unknown Exception has occurred'; this.timeout = options.timeout || 10000; this.stack = err.stack || ''; this.human = !!options.human; this.filename = new Date().toDateString().split(' ').concat([ this.appname, // Name of the library or app that included us. process.pid, // The current process id this.id // Unique id for this exception. ]).filter(Boolean).join('-'); this.capture = this.toJSON(); }
[ "function", "Exception", "(", "err", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Exception", ")", ")", "return", "new", "Exception", "(", "err", ",", "options", ")", ";", "if", "(", "'string'", "===", "typeof", "err", ")", "err", "=", "{", "stack", ":", "(", "new", "Error", "(", "err", ")", ")", ".", "stack", ",", "message", ":", "err", "}", ";", "debug", "(", "'generating a new exception for: %s'", ",", "err", ".", "message", ")", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "initialize", "(", "options", ")", ";", "this", ".", "message", "=", "err", ".", "message", "||", "'An unknown Exception has occurred'", ";", "this", ".", "timeout", "=", "options", ".", "timeout", "||", "10000", ";", "this", ".", "stack", "=", "err", ".", "stack", "||", "''", ";", "this", ".", "human", "=", "!", "!", "options", ".", "human", ";", "this", ".", "filename", "=", "new", "Date", "(", ")", ".", "toDateString", "(", ")", ".", "split", "(", "' '", ")", ".", "concat", "(", "[", "this", ".", "appname", ",", "process", ".", "pid", ",", "this", ".", "id", "]", ")", ".", "filter", "(", "Boolean", ")", ".", "join", "(", "'-'", ")", ";", "this", ".", "capture", "=", "this", ".", "toJSON", "(", ")", ";", "}" ]
Generates a new Exception. Options: - timeout: Timeout for remote saving data before we call the supplied abortion callback. - human: Provide a human readable console output. @constructor @param {Error} err The error that caused the exception. @param {Object} options Configuration. @api public
[ "Generates", "a", "new", "Exception", "." ]
f6a89b51710ee858b32d6640706ae41f9bb87270
https://github.com/observing/exception/blob/f6a89b51710ee858b32d6640706ae41f9bb87270/index.js#L37-L61
train
observing/exception
index.js
bytes
function bytes(b) { if (!readable) return b; var tb = ((1 << 30) * 1024) , gb = 1 << 30 , mb = 1 << 20 , kb = 1 << 10 , abs = Math.abs(b); if (abs >= tb) return (Math.round(b / tb * 100) / 100) + 'tb'; if (abs >= gb) return (Math.round(b / gb * 100) / 100) + 'gb'; if (abs >= mb) return (Math.round(b / mb * 100) / 100) + 'mb'; if (abs >= kb) return (Math.round(b / kb * 100) / 100) + 'kb'; return b + 'b'; }
javascript
function bytes(b) { if (!readable) return b; var tb = ((1 << 30) * 1024) , gb = 1 << 30 , mb = 1 << 20 , kb = 1 << 10 , abs = Math.abs(b); if (abs >= tb) return (Math.round(b / tb * 100) / 100) + 'tb'; if (abs >= gb) return (Math.round(b / gb * 100) / 100) + 'gb'; if (abs >= mb) return (Math.round(b / mb * 100) / 100) + 'mb'; if (abs >= kb) return (Math.round(b / kb * 100) / 100) + 'kb'; return b + 'b'; }
[ "function", "bytes", "(", "b", ")", "{", "if", "(", "!", "readable", ")", "return", "b", ";", "var", "tb", "=", "(", "(", "1", "<<", "30", ")", "*", "1024", ")", ",", "gb", "=", "1", "<<", "30", ",", "mb", "=", "1", "<<", "20", ",", "kb", "=", "1", "<<", "10", ",", "abs", "=", "Math", ".", "abs", "(", "b", ")", ";", "if", "(", "abs", ">=", "tb", ")", "return", "(", "Math", ".", "round", "(", "b", "/", "tb", "*", "100", ")", "/", "100", ")", "+", "'tb'", ";", "if", "(", "abs", ">=", "gb", ")", "return", "(", "Math", ".", "round", "(", "b", "/", "gb", "*", "100", ")", "/", "100", ")", "+", "'gb'", ";", "if", "(", "abs", ">=", "mb", ")", "return", "(", "Math", ".", "round", "(", "b", "/", "mb", "*", "100", ")", "/", "100", ")", "+", "'mb'", ";", "if", "(", "abs", ">=", "kb", ")", "return", "(", "Math", ".", "round", "(", "b", "/", "kb", "*", "100", ")", "/", "100", ")", "+", "'kb'", ";", "return", "b", "+", "'b'", ";", "}" ]
Make the bytes human readable if needed. @param {Number} b Bytes @returns {String|Number} @api private
[ "Make", "the", "bytes", "human", "readable", "if", "needed", "." ]
f6a89b51710ee858b32d6640706ae41f9bb87270
https://github.com/observing/exception/blob/f6a89b51710ee858b32d6640706ae41f9bb87270/index.js#L140-L155
train
BeLi4L/subz-hero
src/util/file-util.js
readBytes
async function readBytes ({ file, start, chunkSize }) { const buffer = Buffer.alloc(chunkSize) const fileDescriptor = await fs.open(file, 'r') const { bytesRead } = await fs.read( fileDescriptor, buffer, // buffer to write to 0, // offset in the buffer to start writing at chunkSize, // number of bytes to read start // where to begin reading from in the file ) // Slice the buffer in case chunkSize > fileSize - start return buffer.slice(0, bytesRead) }
javascript
async function readBytes ({ file, start, chunkSize }) { const buffer = Buffer.alloc(chunkSize) const fileDescriptor = await fs.open(file, 'r') const { bytesRead } = await fs.read( fileDescriptor, buffer, // buffer to write to 0, // offset in the buffer to start writing at chunkSize, // number of bytes to read start // where to begin reading from in the file ) // Slice the buffer in case chunkSize > fileSize - start return buffer.slice(0, bytesRead) }
[ "async", "function", "readBytes", "(", "{", "file", ",", "start", ",", "chunkSize", "}", ")", "{", "const", "buffer", "=", "Buffer", ".", "alloc", "(", "chunkSize", ")", "const", "fileDescriptor", "=", "await", "fs", ".", "open", "(", "file", ",", "'r'", ")", "const", "{", "bytesRead", "}", "=", "await", "fs", ".", "read", "(", "fileDescriptor", ",", "buffer", ",", "0", ",", "chunkSize", ",", "start", ")", "return", "buffer", ".", "slice", "(", "0", ",", "bytesRead", ")", "}" ]
Read `chunkSize` bytes from the given `file`, starting from byte number `start`. @param {string} file - path to a file @param {number} start - byte to start reading from @param {number} chunkSize - number of bytes to read @returns {Promise<Buffer>}
[ "Read", "chunkSize", "bytes", "from", "the", "given", "file", "starting", "from", "byte", "number", "start", "." ]
c22c6df7c2d80c00685a9326043e1ceae3cbf53d
https://github.com/BeLi4L/subz-hero/blob/c22c6df7c2d80c00685a9326043e1ceae3cbf53d/src/util/file-util.js#L22-L37
train
rootsdev/gedcomx-js
src/atom/AtomGenerator.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomGenerator)){ return new AtomGenerator(json); } // If the given object is already an instance then just return it. DON'T copy it. if(AtomGenerator.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomGenerator)){ return new AtomGenerator(json); } // If the given object is already an instance then just return it. DON'T copy it. if(AtomGenerator.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AtomGenerator", ")", ")", "{", "return", "new", "AtomGenerator", "(", "json", ")", ";", "}", "if", "(", "AtomGenerator", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
The agent used to generate a feed @see {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/atom-model-specification.md#atom-json-media-type|GEDCOM X Atom JSON Spec} @see {@link https://tools.ietf.org/html/rfc4287#section-4.2.4|RFC 4287} @class AtomGenerator @extends AtomCommon @param {Object} [json]
[ "The", "agent", "used", "to", "generate", "a", "feed" ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/atom/AtomGenerator.js#L16-L29
train
rootsdev/gedcomx-js
src/core/Relationship.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Relationship)){ return new Relationship(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Relationship.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Relationship)){ return new Relationship(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Relationship.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Relationship", ")", ")", "{", "return", "new", "Relationship", "(", "json", ")", ";", "}", "if", "(", "Relationship", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A relationship. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#relationship|GEDCOM X JSON Spec} @class @extends Subject @param {Object} [json]
[ "A", "relationship", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Relationship.js#L13-L26
train
chromaway/blockchainjs
lib/storage/localstorage.js
LocalStorage
function LocalStorage (opts) { if (!isLocalStorageSupported()) { console.warn('localStorage not supported! (data will be stored in memory)') } var self = this Storage.call(self, opts) opts = _.extend({ keyName: 'blockchainjs_' + self.networkName }, opts) if (!this.compactMode) { throw new errors.Storage.FullMode.NotSupported() } self._storage = getStorage() self._keyName = opts.keyName // load this._data Promise.try(function () { self._init() self._save() }) .then(function () { self.emit('ready') }) .catch(function (err) { self.emit('error', err) }) }
javascript
function LocalStorage (opts) { if (!isLocalStorageSupported()) { console.warn('localStorage not supported! (data will be stored in memory)') } var self = this Storage.call(self, opts) opts = _.extend({ keyName: 'blockchainjs_' + self.networkName }, opts) if (!this.compactMode) { throw new errors.Storage.FullMode.NotSupported() } self._storage = getStorage() self._keyName = opts.keyName // load this._data Promise.try(function () { self._init() self._save() }) .then(function () { self.emit('ready') }) .catch(function (err) { self.emit('error', err) }) }
[ "function", "LocalStorage", "(", "opts", ")", "{", "if", "(", "!", "isLocalStorageSupported", "(", ")", ")", "{", "console", ".", "warn", "(", "'localStorage not supported! (data will be stored in memory)'", ")", "}", "var", "self", "=", "this", "Storage", ".", "call", "(", "self", ",", "opts", ")", "opts", "=", "_", ".", "extend", "(", "{", "keyName", ":", "'blockchainjs_'", "+", "self", ".", "networkName", "}", ",", "opts", ")", "if", "(", "!", "this", ".", "compactMode", ")", "{", "throw", "new", "errors", ".", "Storage", ".", "FullMode", ".", "NotSupported", "(", ")", "}", "self", ".", "_storage", "=", "getStorage", "(", ")", "self", ".", "_keyName", "=", "opts", ".", "keyName", "Promise", ".", "try", "(", "function", "(", ")", "{", "self", ".", "_init", "(", ")", "self", ".", "_save", "(", ")", "}", ")", ".", "then", "(", "function", "(", ")", "{", "self", ".", "emit", "(", "'ready'", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", "}", ")", "}" ]
Only compactMode supported @class LocalStorage @extends Storage @param {Object} [opts] @param {string} [opts.networkName=livenet] @param {boolean} [opts.compactMode=false] @param {string} [opts.keyName] Recommended for use with network name
[ "Only", "compactMode", "supported" ]
82ae80147cc24cca42f1e1b6113ea41c45e6aae8
https://github.com/chromaway/blockchainjs/blob/82ae80147cc24cca42f1e1b6113ea41c45e6aae8/lib/storage/localstorage.js#L80-L106
train
rootsdev/gedcomx-js
src/rs/Links.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Links)){ return new Links(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Links.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Links)){ return new Links(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Links.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Links", ")", ")", "{", "return", "new", "Links", "(", "json", ")", ";", "}", "if", "(", "Links", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A list of Links {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/rs-specification.md#json-type-member|GEDCOM X RS Spec} @class Links @extends Base @param {Object} [json]
[ "A", "list", "of", "Links" ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/rs/Links.js#L15-L28
train
rootsdev/gedcomx-js
src/rs/PlaceDisplayProperties.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof PlaceDisplayProperties)){ return new PlaceDisplayProperties(json); } // If the given object is already an instance then just return it. DON'T copy it. if(PlaceDisplayProperties.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof PlaceDisplayProperties)){ return new PlaceDisplayProperties(json); } // If the given object is already an instance then just return it. DON'T copy it. if(PlaceDisplayProperties.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "PlaceDisplayProperties", ")", ")", "{", "return", "new", "PlaceDisplayProperties", "(", "json", ")", ";", "}", "if", "(", "PlaceDisplayProperties", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A set of properties for convenience in displaying a summary of a place. @see {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/rs-specification.md#place-display-properties-data-type|GEDCOM X RS Spec} @class PlaceDisplayProperties @extends Base @param {Object} [json]
[ "A", "set", "of", "properties", "for", "convenience", "in", "displaying", "a", "summary", "of", "a", "place", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/rs/PlaceDisplayProperties.js#L15-L28
train
eduardoportilho/trafikverket
src/train-announcement.js
getDepartures
function getDepartures (fromStationId, toStationId, fromTime, toTime) { fromTime = fromTime || '-00:30:00' toTime = toTime || '03:00:00' let optionalFilters = '' if (toStationId) { optionalFilters += '<OR>' + `<EQ name="ViaToLocation.LocationName" value="${toStationId}"/>` + `<EQ name="ToLocation.LocationName" value="${toStationId}"/>` + '</OR>' } let xmlRequest = fs.readFileSync(xmlRequestFile) .toString() .replace('{apikey}', env.apiKey) .replace('{fromStationId}', fromStationId) .replace('{optionalFilters}', optionalFilters) .replace('{fromTime}', fromTime) .replace('{toTime}', toTime) return new Promise(function (resolve, reject) { request( {method: 'POST', url: env.url, body: xmlRequest}, function (err, response, body) { if (err) { return reject(err) } let bodyObj = JSON.parse(body) let departures = handleDeparturesResponse(bodyObj) resolve(deduplicateDepartures(departures)) } ) }).then(function (departures) { let stationIds = getStationIdsFromDepartures(departures) return trainStationService.getTrainStationsInfo(stationIds) .then(function (stationsInfo) { return replaceStationIdsForNamesInDepartures(departures, stationsInfo) }) }) }
javascript
function getDepartures (fromStationId, toStationId, fromTime, toTime) { fromTime = fromTime || '-00:30:00' toTime = toTime || '03:00:00' let optionalFilters = '' if (toStationId) { optionalFilters += '<OR>' + `<EQ name="ViaToLocation.LocationName" value="${toStationId}"/>` + `<EQ name="ToLocation.LocationName" value="${toStationId}"/>` + '</OR>' } let xmlRequest = fs.readFileSync(xmlRequestFile) .toString() .replace('{apikey}', env.apiKey) .replace('{fromStationId}', fromStationId) .replace('{optionalFilters}', optionalFilters) .replace('{fromTime}', fromTime) .replace('{toTime}', toTime) return new Promise(function (resolve, reject) { request( {method: 'POST', url: env.url, body: xmlRequest}, function (err, response, body) { if (err) { return reject(err) } let bodyObj = JSON.parse(body) let departures = handleDeparturesResponse(bodyObj) resolve(deduplicateDepartures(departures)) } ) }).then(function (departures) { let stationIds = getStationIdsFromDepartures(departures) return trainStationService.getTrainStationsInfo(stationIds) .then(function (stationsInfo) { return replaceStationIdsForNamesInDepartures(departures, stationsInfo) }) }) }
[ "function", "getDepartures", "(", "fromStationId", ",", "toStationId", ",", "fromTime", ",", "toTime", ")", "{", "fromTime", "=", "fromTime", "||", "'-00:30:00'", "toTime", "=", "toTime", "||", "'03:00:00'", "let", "optionalFilters", "=", "''", "if", "(", "toStationId", ")", "{", "optionalFilters", "+=", "'<OR>'", "+", "`", "${", "toStationId", "}", "`", "+", "`", "${", "toStationId", "}", "`", "+", "'</OR>'", "}", "let", "xmlRequest", "=", "fs", ".", "readFileSync", "(", "xmlRequestFile", ")", ".", "toString", "(", ")", ".", "replace", "(", "'{apikey}'", ",", "env", ".", "apiKey", ")", ".", "replace", "(", "'{fromStationId}'", ",", "fromStationId", ")", ".", "replace", "(", "'{optionalFilters}'", ",", "optionalFilters", ")", ".", "replace", "(", "'{fromTime}'", ",", "fromTime", ")", ".", "replace", "(", "'{toTime}'", ",", "toTime", ")", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "request", "(", "{", "method", ":", "'POST'", ",", "url", ":", "env", ".", "url", ",", "body", ":", "xmlRequest", "}", ",", "function", "(", "err", ",", "response", ",", "body", ")", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", "}", "let", "bodyObj", "=", "JSON", ".", "parse", "(", "body", ")", "let", "departures", "=", "handleDeparturesResponse", "(", "bodyObj", ")", "resolve", "(", "deduplicateDepartures", "(", "departures", ")", ")", "}", ")", "}", ")", ".", "then", "(", "function", "(", "departures", ")", "{", "let", "stationIds", "=", "getStationIdsFromDepartures", "(", "departures", ")", "return", "trainStationService", ".", "getTrainStationsInfo", "(", "stationIds", ")", ".", "then", "(", "function", "(", "stationsInfo", ")", "{", "return", "replaceStationIdsForNamesInDepartures", "(", "departures", ",", "stationsInfo", ")", "}", ")", "}", ")", "}" ]
Query the departures from a station @param {string} fromStationId Id of the station of departure @param {string} toStationId Id of a station on the route of the train (optional) @param {string} fromTime HH:mm:ss Includes trains leaving how long AFTER the current time? (default: -00:30:00) - If the value is negative, includes trains leaving before the current time @param {string} toTime HH:mm:ss Excludes trains leaving how long AFTER the current time? (default: 03:00:00) @return {array} Array of departure objects containing the following keys: - train {string}: Train id - track {string}: Track nunber at departing station - cancelled {boolean}: Departure cancelled? - delayed {boolean}: Departure delayed? - deviation {string[]}: Deiations, for example: "Bus Replacement" - date {string}: Date of departure (DD/MM/YYYY) - time {string}: Time of departure (HH:mm:ss) - estimatedDate {string}: Estimated date of departure (DD/MM/YYYY) - estimatedTime {string}: Estimated time of departure (HH:mm:ss) - plannedEstimatedDate {string}: Planned delayed departure date (DD/MM/YYYY) - plannedEstimatedTime {string}: Planned delayed departure time (HH:mm:ss) - scheduledDepartureDate {string}: The train's announced departure date (DD/MM/YYYY) - scheduledDepartureTime {string}: The train's announced departure time (HH:mm:ss) - destination {string}: Name of the final destination station - via {string[]}: Name of the stations where the train stops
[ "Query", "the", "departures", "from", "a", "station" ]
da4d4c68838ca83b29fa621e9812587d55020e0b
https://github.com/eduardoportilho/trafikverket/blob/da4d4c68838ca83b29fa621e9812587d55020e0b/src/train-announcement.js#L33-L71
train
rootsdev/gedcomx-js
src/core/Gender.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Gender)){ return new Gender(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Gender.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Gender)){ return new Gender(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Gender.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Gender", ")", ")", "{", "return", "new", "Gender", "(", "json", ")", ";", "}", "if", "(", "Gender", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A gender conclusion. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#gender-conclusion|GEDCOM X JSON Spec} @class @extends Conclusion @param {Object} [json]
[ "A", "gender", "conclusion", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Gender.js#L13-L26
train
AppGeo/cartodb
lib/joinclause.js
on
function on(first, operator, second) { var data, bool = this._bool(); switch (arguments.length) { case 1: { if (typeof first === 'object' && typeof first.toSQL !== 'function') { var i = -1, keys = Object.keys(first); var method = bool === 'or' ? 'orOn' : 'on'; while (++i < keys.length) { this[method](keys[i], first[keys[i]]); } return this; } else { data = [bool, 'on', first]; } break; } case 2: data = [bool, 'on', first, '=', operator]; break; default: data = [bool, 'on', first, operator, second]; } this.clauses.push(data); return this; }
javascript
function on(first, operator, second) { var data, bool = this._bool(); switch (arguments.length) { case 1: { if (typeof first === 'object' && typeof first.toSQL !== 'function') { var i = -1, keys = Object.keys(first); var method = bool === 'or' ? 'orOn' : 'on'; while (++i < keys.length) { this[method](keys[i], first[keys[i]]); } return this; } else { data = [bool, 'on', first]; } break; } case 2: data = [bool, 'on', first, '=', operator]; break; default: data = [bool, 'on', first, operator, second]; } this.clauses.push(data); return this; }
[ "function", "on", "(", "first", ",", "operator", ",", "second", ")", "{", "var", "data", ",", "bool", "=", "this", ".", "_bool", "(", ")", ";", "switch", "(", "arguments", ".", "length", ")", "{", "case", "1", ":", "{", "if", "(", "typeof", "first", "===", "'object'", "&&", "typeof", "first", ".", "toSQL", "!==", "'function'", ")", "{", "var", "i", "=", "-", "1", ",", "keys", "=", "Object", ".", "keys", "(", "first", ")", ";", "var", "method", "=", "bool", "===", "'or'", "?", "'orOn'", ":", "'on'", ";", "while", "(", "++", "i", "<", "keys", ".", "length", ")", "{", "this", "[", "method", "]", "(", "keys", "[", "i", "]", ",", "first", "[", "keys", "[", "i", "]", "]", ")", ";", "}", "return", "this", ";", "}", "else", "{", "data", "=", "[", "bool", ",", "'on'", ",", "first", "]", ";", "}", "break", ";", "}", "case", "2", ":", "data", "=", "[", "bool", ",", "'on'", ",", "first", ",", "'='", ",", "operator", "]", ";", "break", ";", "default", ":", "data", "=", "[", "bool", ",", "'on'", ",", "first", ",", "operator", ",", "second", "]", ";", "}", "this", ".", "clauses", ".", "push", "(", "data", ")", ";", "return", "this", ";", "}" ]
Adds an "on" clause to the current join object.
[ "Adds", "an", "on", "clause", "to", "the", "current", "join", "object", "." ]
4cc624975d359800961bf34cb74de97488d2efb5
https://github.com/AppGeo/cartodb/blob/4cc624975d359800961bf34cb74de97488d2efb5/lib/joinclause.js#L24-L51
train
rootsdev/gedcomx-js
src/records/RecordDescriptor.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof RecordDescriptor)){ return new RecordDescriptor(json); } // If the given object is already an instance then just return it. DON'T copy it. if(RecordDescriptor.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof RecordDescriptor)){ return new RecordDescriptor(json); } // If the given object is already an instance then just return it. DON'T copy it. if(RecordDescriptor.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "RecordDescriptor", ")", ")", "{", "return", "new", "RecordDescriptor", "(", "json", ")", ";", "}", "if", "(", "RecordDescriptor", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
Metadata about the structure and layout of a record, as well as the expected data to be extracted from a record. @see {@link https://github.com/FamilySearch/gedcomx-record/blob/master/specifications/record-specification.md#record-descriptor|GEDCOM X Records Spec} @class RecordDescriptor @extends ExtensibleData @param {Object} [json]
[ "Metadata", "about", "the", "structure", "and", "layout", "of", "a", "record", "as", "well", "as", "the", "expected", "data", "to", "be", "extracted", "from", "a", "record", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/records/RecordDescriptor.js#L15-L28
train
jpettersson/node-ordered-merge-stream
index.js
emitData
function emitData() { for(var i=0;i<streamQueue.length;i++) { var dataQueue = streamQueue[i].dataQueue; if(streamQueue[i].pending) { return; } for(var j=0;j<dataQueue.length;j++) { var data = dataQueue[j]; if(!!data) { _this.emit('data', data); dataQueue[j] = null; return emitData(); } } } if(currentStream === streamQueue.length) { _this.emit('end'); } }
javascript
function emitData() { for(var i=0;i<streamQueue.length;i++) { var dataQueue = streamQueue[i].dataQueue; if(streamQueue[i].pending) { return; } for(var j=0;j<dataQueue.length;j++) { var data = dataQueue[j]; if(!!data) { _this.emit('data', data); dataQueue[j] = null; return emitData(); } } } if(currentStream === streamQueue.length) { _this.emit('end'); } }
[ "function", "emitData", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "streamQueue", ".", "length", ";", "i", "++", ")", "{", "var", "dataQueue", "=", "streamQueue", "[", "i", "]", ".", "dataQueue", ";", "if", "(", "streamQueue", "[", "i", "]", ".", "pending", ")", "{", "return", ";", "}", "for", "(", "var", "j", "=", "0", ";", "j", "<", "dataQueue", ".", "length", ";", "j", "++", ")", "{", "var", "data", "=", "dataQueue", "[", "j", "]", ";", "if", "(", "!", "!", "data", ")", "{", "_this", ".", "emit", "(", "'data'", ",", "data", ")", ";", "dataQueue", "[", "j", "]", "=", "null", ";", "return", "emitData", "(", ")", ";", "}", "}", "}", "if", "(", "currentStream", "===", "streamQueue", ".", "length", ")", "{", "_this", ".", "emit", "(", "'end'", ")", ";", "}", "}" ]
Emit everything available so far in the queue
[ "Emit", "everything", "available", "so", "far", "in", "the", "queue" ]
5e19cd3dae8ffbdce4a74a147edb7f6b1c97f3ab
https://github.com/jpettersson/node-ordered-merge-stream/blob/5e19cd3dae8ffbdce4a74a147edb7f6b1c97f3ab/index.js#L14-L36
train
sethvincent/store-emitter
index.js
store
function store (action) { if (!action || !isPlainObject(action)) { throw new Error('action parameter is required and must be a plain object') } if (!action.type || typeof action.type !== 'string') { throw new Error('type property of action is required and must be a string') } if (isEmitting) { throw new Error('modifiers may not emit actions') } isEmitting = true var oldState = extend(state) state = modifier(action, oldState) var newState = extend(state) emitter.emit(action.type, action, newState, oldState) isEmitting = false }
javascript
function store (action) { if (!action || !isPlainObject(action)) { throw new Error('action parameter is required and must be a plain object') } if (!action.type || typeof action.type !== 'string') { throw new Error('type property of action is required and must be a string') } if (isEmitting) { throw new Error('modifiers may not emit actions') } isEmitting = true var oldState = extend(state) state = modifier(action, oldState) var newState = extend(state) emitter.emit(action.type, action, newState, oldState) isEmitting = false }
[ "function", "store", "(", "action", ")", "{", "if", "(", "!", "action", "||", "!", "isPlainObject", "(", "action", ")", ")", "{", "throw", "new", "Error", "(", "'action parameter is required and must be a plain object'", ")", "}", "if", "(", "!", "action", ".", "type", "||", "typeof", "action", ".", "type", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'type property of action is required and must be a string'", ")", "}", "if", "(", "isEmitting", ")", "{", "throw", "new", "Error", "(", "'modifiers may not emit actions'", ")", "}", "isEmitting", "=", "true", "var", "oldState", "=", "extend", "(", "state", ")", "state", "=", "modifier", "(", "action", ",", "oldState", ")", "var", "newState", "=", "extend", "(", "state", ")", "emitter", ".", "emit", "(", "action", ".", "type", ",", "action", ",", "newState", ",", "oldState", ")", "isEmitting", "=", "false", "}" ]
Send an action to the store. Takes a single object parameter. Object must include a `type` property with a string value, and can contain any other properties. @name store @param {object} action @param {string} action.type @example store({ type: 'example' exampleValue: 'anything' })
[ "Send", "an", "action", "to", "the", "store", ".", "Takes", "a", "single", "object", "parameter", ".", "Object", "must", "include", "a", "type", "property", "with", "a", "string", "value", "and", "can", "contain", "any", "other", "properties", "." ]
a58d19390f1ef08477d795831738019993f074d5
https://github.com/sethvincent/store-emitter/blob/a58d19390f1ef08477d795831738019993f074d5/index.js#L46-L66
train
rootsdev/gedcomx-js
src/core/Qualifier.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Qualifier)){ return new Qualifier(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Qualifier.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Qualifier)){ return new Qualifier(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Qualifier.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Qualifier", ")", ")", "{", "return", "new", "Qualifier", "(", "json", ")", ";", "}", "if", "(", "Qualifier", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
Qualifiers are used to supply additional details about a piece of data. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#qualifier|GEDCOM X JSON Spec} @class @extends Base @param {Object} [json]
[ "Qualifiers", "are", "used", "to", "supply", "additional", "details", "about", "a", "piece", "of", "data", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Qualifier.js#L13-L26
train
fullcube/loopback-component-templates
lib/index.js
hasRemoteMethod
function hasRemoteMethod(model, methodName) { return model.sharedClass .methods({ includeDisabled: false }) .map(sharedMethod => sharedMethod.name) .includes(methodName) }
javascript
function hasRemoteMethod(model, methodName) { return model.sharedClass .methods({ includeDisabled: false }) .map(sharedMethod => sharedMethod.name) .includes(methodName) }
[ "function", "hasRemoteMethod", "(", "model", ",", "methodName", ")", "{", "return", "model", ".", "sharedClass", ".", "methods", "(", "{", "includeDisabled", ":", "false", "}", ")", ".", "map", "(", "sharedMethod", "=>", "sharedMethod", ".", "name", ")", ".", "includes", "(", "methodName", ")", "}" ]
Helper method to check if a remote method exists on a model @param model The LoopBack Model @param methodName The name of the Remote Method @returns {boolean}
[ "Helper", "method", "to", "check", "if", "a", "remote", "method", "exists", "on", "a", "model" ]
8fc81955d1ddae805bc6d66743d8e359d1cfac5f
https://github.com/fullcube/loopback-component-templates/blob/8fc81955d1ddae805bc6d66743d8e359d1cfac5f/lib/index.js#L13-L18
train
fullcube/loopback-component-templates
lib/index.js
addRemoteMethods
function addRemoteMethods(app) { return Object.keys(app.models).forEach(modelName => { const Model = app.models[modelName] if (typeof Model._templates !== 'function') { return null } return Object.keys(Model._templates()).forEach(templateName => { const fnName = `_template_${templateName}` const fnNameRemote = `_template_${templateName}_remote` const path = `/${fnName}` // Don't add the method if it already exists on the model if (typeof Model[fnName] === 'function') { debug('Method already exists: %s.%s', Model.modelName, fnName) return null } // Don't add the remote method if it already exists on the model if (hasRemoteMethod(Model, fnNameRemote)) { debug('Remote method already exists: %s.%s', Model.modelName, fnName) return null } debug('Create remote method for %s.%s', Model.modelName, fnName) // The normal method does not need to be wrapped in a promise Model[fnName] = (options, params) => { // Get the random data const template = Model._templates(params)[templateName] // Overwrite the template with the passed in options _.forEach(options, (value, key) => { _.set(template, key, value) }) return template } const fnSpecRemote = { description: `Generate template ${templateName}`, accepts: [ { type: 'Object', arg: 'options', description: 'Overwrite values of template' }, { type: 'Object', arg: 'params', description: 'Pass parameters into the template method' }, ], returns: [ { type: 'Object', arg: 'result', root: true } ], http: { path, verb: 'get' }, } // Support for loopback 2.x. if (app.loopback.version.startsWith(2)) { fnSpecRemote.isStatic = true } // Define the remote method on the model Model.remoteMethod(fnNameRemote, fnSpecRemote) // The remote method needs to be wrapped in a promise Model[fnNameRemote] = (options, params) => new Promise(resolve => resolve(Model[fnName](options, params))) // Send result as plain text if the content is a string Model.afterRemote(fnNameRemote, (ctx, result, next) => { if (typeof ctx.result !== 'string') { return next() } ctx.res.setHeader('Content-Type', 'text/plain') return ctx.res.end(ctx.result) }) return true }) }) }
javascript
function addRemoteMethods(app) { return Object.keys(app.models).forEach(modelName => { const Model = app.models[modelName] if (typeof Model._templates !== 'function') { return null } return Object.keys(Model._templates()).forEach(templateName => { const fnName = `_template_${templateName}` const fnNameRemote = `_template_${templateName}_remote` const path = `/${fnName}` // Don't add the method if it already exists on the model if (typeof Model[fnName] === 'function') { debug('Method already exists: %s.%s', Model.modelName, fnName) return null } // Don't add the remote method if it already exists on the model if (hasRemoteMethod(Model, fnNameRemote)) { debug('Remote method already exists: %s.%s', Model.modelName, fnName) return null } debug('Create remote method for %s.%s', Model.modelName, fnName) // The normal method does not need to be wrapped in a promise Model[fnName] = (options, params) => { // Get the random data const template = Model._templates(params)[templateName] // Overwrite the template with the passed in options _.forEach(options, (value, key) => { _.set(template, key, value) }) return template } const fnSpecRemote = { description: `Generate template ${templateName}`, accepts: [ { type: 'Object', arg: 'options', description: 'Overwrite values of template' }, { type: 'Object', arg: 'params', description: 'Pass parameters into the template method' }, ], returns: [ { type: 'Object', arg: 'result', root: true } ], http: { path, verb: 'get' }, } // Support for loopback 2.x. if (app.loopback.version.startsWith(2)) { fnSpecRemote.isStatic = true } // Define the remote method on the model Model.remoteMethod(fnNameRemote, fnSpecRemote) // The remote method needs to be wrapped in a promise Model[fnNameRemote] = (options, params) => new Promise(resolve => resolve(Model[fnName](options, params))) // Send result as plain text if the content is a string Model.afterRemote(fnNameRemote, (ctx, result, next) => { if (typeof ctx.result !== 'string') { return next() } ctx.res.setHeader('Content-Type', 'text/plain') return ctx.res.end(ctx.result) }) return true }) }) }
[ "function", "addRemoteMethods", "(", "app", ")", "{", "return", "Object", ".", "keys", "(", "app", ".", "models", ")", ".", "forEach", "(", "modelName", "=>", "{", "const", "Model", "=", "app", ".", "models", "[", "modelName", "]", "if", "(", "typeof", "Model", ".", "_templates", "!==", "'function'", ")", "{", "return", "null", "}", "return", "Object", ".", "keys", "(", "Model", ".", "_templates", "(", ")", ")", ".", "forEach", "(", "templateName", "=>", "{", "const", "fnName", "=", "`", "${", "templateName", "}", "`", "const", "fnNameRemote", "=", "`", "${", "templateName", "}", "`", "const", "path", "=", "`", "${", "fnName", "}", "`", "if", "(", "typeof", "Model", "[", "fnName", "]", "===", "'function'", ")", "{", "debug", "(", "'Method already exists: %s.%s'", ",", "Model", ".", "modelName", ",", "fnName", ")", "return", "null", "}", "if", "(", "hasRemoteMethod", "(", "Model", ",", "fnNameRemote", ")", ")", "{", "debug", "(", "'Remote method already exists: %s.%s'", ",", "Model", ".", "modelName", ",", "fnName", ")", "return", "null", "}", "debug", "(", "'Create remote method for %s.%s'", ",", "Model", ".", "modelName", ",", "fnName", ")", "Model", "[", "fnName", "]", "=", "(", "options", ",", "params", ")", "=>", "{", "const", "template", "=", "Model", ".", "_templates", "(", "params", ")", "[", "templateName", "]", "_", ".", "forEach", "(", "options", ",", "(", "value", ",", "key", ")", "=>", "{", "_", ".", "set", "(", "template", ",", "key", ",", "value", ")", "}", ")", "return", "template", "}", "const", "fnSpecRemote", "=", "{", "description", ":", "`", "${", "templateName", "}", "`", ",", "accepts", ":", "[", "{", "type", ":", "'Object'", ",", "arg", ":", "'options'", ",", "description", ":", "'Overwrite values of template'", "}", ",", "{", "type", ":", "'Object'", ",", "arg", ":", "'params'", ",", "description", ":", "'Pass parameters into the template method'", "}", ",", "]", ",", "returns", ":", "[", "{", "type", ":", "'Object'", ",", "arg", ":", "'result'", ",", "root", ":", "true", "}", "]", ",", "http", ":", "{", "path", ",", "verb", ":", "'get'", "}", ",", "}", "if", "(", "app", ".", "loopback", ".", "version", ".", "startsWith", "(", "2", ")", ")", "{", "fnSpecRemote", ".", "isStatic", "=", "true", "}", "Model", ".", "remoteMethod", "(", "fnNameRemote", ",", "fnSpecRemote", ")", "Model", "[", "fnNameRemote", "]", "=", "(", "options", ",", "params", ")", "=>", "new", "Promise", "(", "resolve", "=>", "resolve", "(", "Model", "[", "fnName", "]", "(", "options", ",", "params", ")", ")", ")", "Model", ".", "afterRemote", "(", "fnNameRemote", ",", "(", "ctx", ",", "result", ",", "next", ")", "=>", "{", "if", "(", "typeof", "ctx", ".", "result", "!==", "'string'", ")", "{", "return", "next", "(", ")", "}", "ctx", ".", "res", ".", "setHeader", "(", "'Content-Type'", ",", "'text/plain'", ")", "return", "ctx", ".", "res", ".", "end", "(", "ctx", ".", "result", ")", "}", ")", "return", "true", "}", ")", "}", ")", "}" ]
Add remote methods for each template. @param {Object} app loopback application @param {Object} config component configuration
[ "Add", "remote", "methods", "for", "each", "template", "." ]
8fc81955d1ddae805bc6d66743d8e359d1cfac5f
https://github.com/fullcube/loopback-component-templates/blob/8fc81955d1ddae805bc6d66743d8e359d1cfac5f/lib/index.js#L26-L98
train
fullcube/loopback-component-templates
lib/index.js
addAcls
function addAcls(app, config) { config.acls = config.acls || [] return Promise.resolve(Object.keys(app.models)).mapSeries(modelName => { const Model = app.models[modelName] if (typeof Model._templates !== 'function') { return null } return Promise.resolve(Object.keys(Model._templates())) .mapSeries(templateName => { const fnNameRemote = `_template_${templateName}_remote` return Promise.resolve(config.acls).mapSeries(acl => { const templateAcl = Object.assign({}, acl) templateAcl.model = modelName templateAcl.property = fnNameRemote debug('Create ACL entry for %s.%s ', modelName, fnNameRemote) return app.models.ACL.create(templateAcl) }) }) }) }
javascript
function addAcls(app, config) { config.acls = config.acls || [] return Promise.resolve(Object.keys(app.models)).mapSeries(modelName => { const Model = app.models[modelName] if (typeof Model._templates !== 'function') { return null } return Promise.resolve(Object.keys(Model._templates())) .mapSeries(templateName => { const fnNameRemote = `_template_${templateName}_remote` return Promise.resolve(config.acls).mapSeries(acl => { const templateAcl = Object.assign({}, acl) templateAcl.model = modelName templateAcl.property = fnNameRemote debug('Create ACL entry for %s.%s ', modelName, fnNameRemote) return app.models.ACL.create(templateAcl) }) }) }) }
[ "function", "addAcls", "(", "app", ",", "config", ")", "{", "config", ".", "acls", "=", "config", ".", "acls", "||", "[", "]", "return", "Promise", ".", "resolve", "(", "Object", ".", "keys", "(", "app", ".", "models", ")", ")", ".", "mapSeries", "(", "modelName", "=>", "{", "const", "Model", "=", "app", ".", "models", "[", "modelName", "]", "if", "(", "typeof", "Model", ".", "_templates", "!==", "'function'", ")", "{", "return", "null", "}", "return", "Promise", ".", "resolve", "(", "Object", ".", "keys", "(", "Model", ".", "_templates", "(", ")", ")", ")", ".", "mapSeries", "(", "templateName", "=>", "{", "const", "fnNameRemote", "=", "`", "${", "templateName", "}", "`", "return", "Promise", ".", "resolve", "(", "config", ".", "acls", ")", ".", "mapSeries", "(", "acl", "=>", "{", "const", "templateAcl", "=", "Object", ".", "assign", "(", "{", "}", ",", "acl", ")", "templateAcl", ".", "model", "=", "modelName", "templateAcl", ".", "property", "=", "fnNameRemote", "debug", "(", "'Create ACL entry for %s.%s '", ",", "modelName", ",", "fnNameRemote", ")", "return", "app", ".", "models", ".", "ACL", ".", "create", "(", "templateAcl", ")", "}", ")", "}", ")", "}", ")", "}" ]
Add ACLs for each template. @param {Object} app loopback application @param {Object} config component configuration
[ "Add", "ACLs", "for", "each", "template", "." ]
8fc81955d1ddae805bc6d66743d8e359d1cfac5f
https://github.com/fullcube/loopback-component-templates/blob/8fc81955d1ddae805bc6d66743d8e359d1cfac5f/lib/index.js#L106-L130
train
FormBucket/xander
src/router.js
match
function match(routes = [], path) { for (var i = 0; i < routes.length; i++) { var re = pathRegexps[routes[i].path] || pathToRegexp(routes[i].path); pathRegexps[routes[i].path] = re; if (re && re.test(path)) { return { re, route: routes[i] }; } } return false; }
javascript
function match(routes = [], path) { for (var i = 0; i < routes.length; i++) { var re = pathRegexps[routes[i].path] || pathToRegexp(routes[i].path); pathRegexps[routes[i].path] = re; if (re && re.test(path)) { return { re, route: routes[i] }; } } return false; }
[ "function", "match", "(", "routes", "=", "[", "]", ",", "path", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "routes", ".", "length", ";", "i", "++", ")", "{", "var", "re", "=", "pathRegexps", "[", "routes", "[", "i", "]", ".", "path", "]", "||", "pathToRegexp", "(", "routes", "[", "i", "]", ".", "path", ")", ";", "pathRegexps", "[", "routes", "[", "i", "]", ".", "path", "]", "=", "re", ";", "if", "(", "re", "&&", "re", ".", "test", "(", "path", ")", ")", "{", "return", "{", "re", ",", "route", ":", "routes", "[", "i", "]", "}", ";", "}", "}", "return", "false", ";", "}" ]
Return the first matching route.
[ "Return", "the", "first", "matching", "route", "." ]
6e63fdaa5cbacd125f661e87d703a4160d564e9f
https://github.com/FormBucket/xander/blob/6e63fdaa5cbacd125f661e87d703a4160d564e9f/src/router.js#L24-L35
train
rootsdev/gedcomx-js
src/rs/DisplayProperties.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof DisplayProperties)){ return new DisplayProperties(json); } // If the given object is already an instance then just return it. DON'T copy it. if(DisplayProperties.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof DisplayProperties)){ return new DisplayProperties(json); } // If the given object is already an instance then just return it. DON'T copy it. if(DisplayProperties.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "DisplayProperties", ")", ")", "{", "return", "new", "DisplayProperties", "(", "json", ")", ";", "}", "if", "(", "DisplayProperties", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A set of properties for convenience in displaying a summary of a person to a user. @see {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/rs-specification.md#display-properties-data-type|GEDCOM X RS Spec} @class DisplayProperties @extends Base @param {Object} [json]
[ "A", "set", "of", "properties", "for", "convenience", "in", "displaying", "a", "summary", "of", "a", "person", "to", "a", "user", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/rs/DisplayProperties.js#L15-L28
train
rootsdev/gedcomx-js
src/atom/AtomEntry.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomEntry)){ return new AtomEntry(json); } // If the given object is already an instance then just return it. DON'T copy it. if(AtomEntry.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomEntry)){ return new AtomEntry(json); } // If the given object is already an instance then just return it. DON'T copy it. if(AtomEntry.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AtomEntry", ")", ")", "{", "return", "new", "AtomEntry", "(", "json", ")", ";", "}", "if", "(", "AtomEntry", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
An individual atom feed entry. @see {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/atom-model-specification.md#atom-json-media-type|GEDCOM X Atom JSON Spec} @see {@link https://tools.ietf.org/html/rfc4287#section-4.1.2|RFC 4287} @class AtomEntry @extends AtomCommon @param {Object} [json]
[ "An", "individual", "atom", "feed", "entry", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/atom/AtomEntry.js#L16-L29
train
FormBucket/xander
src/store.js
Dispatcher
function Dispatcher() { let lastId = 1; let prefix = "ID_"; let callbacks = {}; let isPending = {}; let isHandled = {}; let isDispatching = false; let pendingPayload = null; function invokeCallback(id) { isPending[id] = true; callbacks[id](pendingPayload); isHandled[id] = true; } this.register = callback => { let id = prefix + lastId++; callbacks[id] = callback; return id; }; this.unregister = id => { if (!callbacks.hasOwnProperty(id)) return new Error("Cannot unregister unknown ID!"); delete callbacks[id]; return id; }; this.waitFor = ids => { for (var i = 0; i < ids.length; i++) { var id = ids[id]; if (isPending[id]) { return new Error("Circular dependency waiting for " + id); } if (!callbacks[id]) { return new Error(`waitFor: ${id} is not a registered callback.`); } invokeCallback(id); } return undefined; }; this.dispatch = payload => { if (isDispatching) return new Error("Cannot dispatch while dispatching."); // start for (var id in callbacks) { isPending[id] = false; isHandled[id] = false; } pendingPayload = payload; isDispatching = true; // run each callback. try { for (var id in callbacks) { if (isPending[id]) continue; invokeCallback(id); } } finally { pendingPayload = null; isDispatching = false; } return payload; }; }
javascript
function Dispatcher() { let lastId = 1; let prefix = "ID_"; let callbacks = {}; let isPending = {}; let isHandled = {}; let isDispatching = false; let pendingPayload = null; function invokeCallback(id) { isPending[id] = true; callbacks[id](pendingPayload); isHandled[id] = true; } this.register = callback => { let id = prefix + lastId++; callbacks[id] = callback; return id; }; this.unregister = id => { if (!callbacks.hasOwnProperty(id)) return new Error("Cannot unregister unknown ID!"); delete callbacks[id]; return id; }; this.waitFor = ids => { for (var i = 0; i < ids.length; i++) { var id = ids[id]; if (isPending[id]) { return new Error("Circular dependency waiting for " + id); } if (!callbacks[id]) { return new Error(`waitFor: ${id} is not a registered callback.`); } invokeCallback(id); } return undefined; }; this.dispatch = payload => { if (isDispatching) return new Error("Cannot dispatch while dispatching."); // start for (var id in callbacks) { isPending[id] = false; isHandled[id] = false; } pendingPayload = payload; isDispatching = true; // run each callback. try { for (var id in callbacks) { if (isPending[id]) continue; invokeCallback(id); } } finally { pendingPayload = null; isDispatching = false; } return payload; }; }
[ "function", "Dispatcher", "(", ")", "{", "let", "lastId", "=", "1", ";", "let", "prefix", "=", "\"ID_\"", ";", "let", "callbacks", "=", "{", "}", ";", "let", "isPending", "=", "{", "}", ";", "let", "isHandled", "=", "{", "}", ";", "let", "isDispatching", "=", "false", ";", "let", "pendingPayload", "=", "null", ";", "function", "invokeCallback", "(", "id", ")", "{", "isPending", "[", "id", "]", "=", "true", ";", "callbacks", "[", "id", "]", "(", "pendingPayload", ")", ";", "isHandled", "[", "id", "]", "=", "true", ";", "}", "this", ".", "register", "=", "callback", "=>", "{", "let", "id", "=", "prefix", "+", "lastId", "++", ";", "callbacks", "[", "id", "]", "=", "callback", ";", "return", "id", ";", "}", ";", "this", ".", "unregister", "=", "id", "=>", "{", "if", "(", "!", "callbacks", ".", "hasOwnProperty", "(", "id", ")", ")", "return", "new", "Error", "(", "\"Cannot unregister unknown ID!\"", ")", ";", "delete", "callbacks", "[", "id", "]", ";", "return", "id", ";", "}", ";", "this", ".", "waitFor", "=", "ids", "=>", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ids", ".", "length", ";", "i", "++", ")", "{", "var", "id", "=", "ids", "[", "id", "]", ";", "if", "(", "isPending", "[", "id", "]", ")", "{", "return", "new", "Error", "(", "\"Circular dependency waiting for \"", "+", "id", ")", ";", "}", "if", "(", "!", "callbacks", "[", "id", "]", ")", "{", "return", "new", "Error", "(", "`", "${", "id", "}", "`", ")", ";", "}", "invokeCallback", "(", "id", ")", ";", "}", "return", "undefined", ";", "}", ";", "this", ".", "dispatch", "=", "payload", "=>", "{", "if", "(", "isDispatching", ")", "return", "new", "Error", "(", "\"Cannot dispatch while dispatching.\"", ")", ";", "for", "(", "var", "id", "in", "callbacks", ")", "{", "isPending", "[", "id", "]", "=", "false", ";", "isHandled", "[", "id", "]", "=", "false", ";", "}", "pendingPayload", "=", "payload", ";", "isDispatching", "=", "true", ";", "try", "{", "for", "(", "var", "id", "in", "callbacks", ")", "{", "if", "(", "isPending", "[", "id", "]", ")", "continue", ";", "invokeCallback", "(", "id", ")", ";", "}", "}", "finally", "{", "pendingPayload", "=", "null", ";", "isDispatching", "=", "false", ";", "}", "return", "payload", ";", "}", ";", "}" ]
Based on Facebook's Flux dispatcher class.
[ "Based", "on", "Facebook", "s", "Flux", "dispatcher", "class", "." ]
6e63fdaa5cbacd125f661e87d703a4160d564e9f
https://github.com/FormBucket/xander/blob/6e63fdaa5cbacd125f661e87d703a4160d564e9f/src/store.js#L5-L75
train
neagle/smartgamer
index.js
function () { if (sequence) { var localNodes = sequence.nodes; var localIndex = (localNodes) ? localNodes.indexOf(node) : null; if (localNodes) { if (localIndex === (localNodes.length - 1)) { return sequence.sequences || []; } else { return []; } } } }
javascript
function () { if (sequence) { var localNodes = sequence.nodes; var localIndex = (localNodes) ? localNodes.indexOf(node) : null; if (localNodes) { if (localIndex === (localNodes.length - 1)) { return sequence.sequences || []; } else { return []; } } } }
[ "function", "(", ")", "{", "if", "(", "sequence", ")", "{", "var", "localNodes", "=", "sequence", ".", "nodes", ";", "var", "localIndex", "=", "(", "localNodes", ")", "?", "localNodes", ".", "indexOf", "(", "node", ")", ":", "null", ";", "if", "(", "localNodes", ")", "{", "if", "(", "localIndex", "===", "(", "localNodes", ".", "length", "-", "1", ")", ")", "{", "return", "sequence", ".", "sequences", "||", "[", "]", ";", "}", "else", "{", "return", "[", "]", ";", "}", "}", "}", "}" ]
Return any variations available at the current move
[ "Return", "any", "variations", "available", "at", "the", "current", "move" ]
83a4b47c476729a19f8d04c165c0c10b69095d62
https://github.com/neagle/smartgamer/blob/83a4b47c476729a19f8d04c165c0c10b69095d62/index.js#L65-L78
train
neagle/smartgamer
index.js
function (variation) { variation = variation || 0; var localNodes = sequence.nodes; var localIndex = (localNodes) ? localNodes.indexOf(node) : null; // If there are no additional nodes in this sequence, // advance to the next one if (localIndex === null || localIndex >= (localNodes.length - 1)) { if (sequence.sequences) { if (sequence.sequences[variation]) { sequence = sequence.sequences[variation]; } else { sequence = sequence.sequences[0]; } node = sequence.nodes[0]; // Note the fork chosen for this variation in the path this.path[this.path.m] = variation; this.path.m += 1; } else { // End of sequence / game return this; } } else { node = localNodes[localIndex + 1]; this.path.m += 1; } return this; }
javascript
function (variation) { variation = variation || 0; var localNodes = sequence.nodes; var localIndex = (localNodes) ? localNodes.indexOf(node) : null; // If there are no additional nodes in this sequence, // advance to the next one if (localIndex === null || localIndex >= (localNodes.length - 1)) { if (sequence.sequences) { if (sequence.sequences[variation]) { sequence = sequence.sequences[variation]; } else { sequence = sequence.sequences[0]; } node = sequence.nodes[0]; // Note the fork chosen for this variation in the path this.path[this.path.m] = variation; this.path.m += 1; } else { // End of sequence / game return this; } } else { node = localNodes[localIndex + 1]; this.path.m += 1; } return this; }
[ "function", "(", "variation", ")", "{", "variation", "=", "variation", "||", "0", ";", "var", "localNodes", "=", "sequence", ".", "nodes", ";", "var", "localIndex", "=", "(", "localNodes", ")", "?", "localNodes", ".", "indexOf", "(", "node", ")", ":", "null", ";", "if", "(", "localIndex", "===", "null", "||", "localIndex", ">=", "(", "localNodes", ".", "length", "-", "1", ")", ")", "{", "if", "(", "sequence", ".", "sequences", ")", "{", "if", "(", "sequence", ".", "sequences", "[", "variation", "]", ")", "{", "sequence", "=", "sequence", ".", "sequences", "[", "variation", "]", ";", "}", "else", "{", "sequence", "=", "sequence", ".", "sequences", "[", "0", "]", ";", "}", "node", "=", "sequence", ".", "nodes", "[", "0", "]", ";", "this", ".", "path", "[", "this", ".", "path", ".", "m", "]", "=", "variation", ";", "this", ".", "path", ".", "m", "+=", "1", ";", "}", "else", "{", "return", "this", ";", "}", "}", "else", "{", "node", "=", "localNodes", "[", "localIndex", "+", "1", "]", ";", "this", ".", "path", ".", "m", "+=", "1", ";", "}", "return", "this", ";", "}" ]
Go to the next move
[ "Go", "to", "the", "next", "move" ]
83a4b47c476729a19f8d04c165c0c10b69095d62
https://github.com/neagle/smartgamer/blob/83a4b47c476729a19f8d04c165c0c10b69095d62/index.js#L83-L114
train
neagle/smartgamer
index.js
function () { var localNodes = sequence.nodes; var localIndex = (localNodes) ? localNodes.indexOf(node) : null; // Delete any variation forks at this point // TODO: Make this configurable... we should keep this if we're // remembering chosen paths delete this.path[this.path.m]; if (!localIndex || localIndex === 0) { if (sequence.parent && !sequence.parent.gameTrees) { sequence = sequence.parent; if (sequence.nodes) { node = sequence.nodes[sequence.nodes.length - 1]; this.path.m -= 1; } else { node = null; } } else { // Already at the beginning return this; } } else { node = localNodes[localIndex - 1]; this.path.m -= 1; } return this; }
javascript
function () { var localNodes = sequence.nodes; var localIndex = (localNodes) ? localNodes.indexOf(node) : null; // Delete any variation forks at this point // TODO: Make this configurable... we should keep this if we're // remembering chosen paths delete this.path[this.path.m]; if (!localIndex || localIndex === 0) { if (sequence.parent && !sequence.parent.gameTrees) { sequence = sequence.parent; if (sequence.nodes) { node = sequence.nodes[sequence.nodes.length - 1]; this.path.m -= 1; } else { node = null; } } else { // Already at the beginning return this; } } else { node = localNodes[localIndex - 1]; this.path.m -= 1; } return this; }
[ "function", "(", ")", "{", "var", "localNodes", "=", "sequence", ".", "nodes", ";", "var", "localIndex", "=", "(", "localNodes", ")", "?", "localNodes", ".", "indexOf", "(", "node", ")", ":", "null", ";", "delete", "this", ".", "path", "[", "this", ".", "path", ".", "m", "]", ";", "if", "(", "!", "localIndex", "||", "localIndex", "===", "0", ")", "{", "if", "(", "sequence", ".", "parent", "&&", "!", "sequence", ".", "parent", ".", "gameTrees", ")", "{", "sequence", "=", "sequence", ".", "parent", ";", "if", "(", "sequence", ".", "nodes", ")", "{", "node", "=", "sequence", ".", "nodes", "[", "sequence", ".", "nodes", ".", "length", "-", "1", "]", ";", "this", ".", "path", ".", "m", "-=", "1", ";", "}", "else", "{", "node", "=", "null", ";", "}", "}", "else", "{", "return", "this", ";", "}", "}", "else", "{", "node", "=", "localNodes", "[", "localIndex", "-", "1", "]", ";", "this", ".", "path", ".", "m", "-=", "1", ";", "}", "return", "this", ";", "}" ]
Go to the previous move
[ "Go", "to", "the", "previous", "move" ]
83a4b47c476729a19f8d04c165c0c10b69095d62
https://github.com/neagle/smartgamer/blob/83a4b47c476729a19f8d04c165c0c10b69095d62/index.js#L119-L147
train
neagle/smartgamer
index.js
function (path) { if (typeof path === 'string') { path = this.pathTransform(path, 'object'); } else if (typeof path === 'number') { path = { m: path }; } this.reset(); var n = node; for (var i = 0; i < path.m && n; i += 1) { // Check for a variation in the path for the upcoming move var variation = path[i + 1] || 0; n = this.next(variation); } return this; }
javascript
function (path) { if (typeof path === 'string') { path = this.pathTransform(path, 'object'); } else if (typeof path === 'number') { path = { m: path }; } this.reset(); var n = node; for (var i = 0; i < path.m && n; i += 1) { // Check for a variation in the path for the upcoming move var variation = path[i + 1] || 0; n = this.next(variation); } return this; }
[ "function", "(", "path", ")", "{", "if", "(", "typeof", "path", "===", "'string'", ")", "{", "path", "=", "this", ".", "pathTransform", "(", "path", ",", "'object'", ")", ";", "}", "else", "if", "(", "typeof", "path", "===", "'number'", ")", "{", "path", "=", "{", "m", ":", "path", "}", ";", "}", "this", ".", "reset", "(", ")", ";", "var", "n", "=", "node", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "path", ".", "m", "&&", "n", ";", "i", "+=", "1", ")", "{", "var", "variation", "=", "path", "[", "i", "+", "1", "]", "||", "0", ";", "n", "=", "this", ".", "next", "(", "variation", ")", ";", "}", "return", "this", ";", "}" ]
Go to a particular move, specified as a a) number b) path string c) path object
[ "Go", "to", "a", "particular", "move", "specified", "as", "a", "a", ")", "number", "b", ")", "path", "string", "c", ")", "path", "object" ]
83a4b47c476729a19f8d04c165c0c10b69095d62
https://github.com/neagle/smartgamer/blob/83a4b47c476729a19f8d04c165c0c10b69095d62/index.js#L172-L190
train
neagle/smartgamer
index.js
function () { var localSequence = this.game; var moves = 0; while(localSequence) { moves += localSequence.nodes.length; if (localSequence.sequences) { localSequence = localSequence.sequences[0]; } else { localSequence = null; } } // TODO: Right now we're *assuming* that the root node doesn't have a // move in it, which is *recommended* but not required practice. // @see http://www.red-bean.com/sgf/sgf4.html // "Note: it's bad style to have move properties in root nodes. // (it isn't forbidden though)" return moves - 1; }
javascript
function () { var localSequence = this.game; var moves = 0; while(localSequence) { moves += localSequence.nodes.length; if (localSequence.sequences) { localSequence = localSequence.sequences[0]; } else { localSequence = null; } } // TODO: Right now we're *assuming* that the root node doesn't have a // move in it, which is *recommended* but not required practice. // @see http://www.red-bean.com/sgf/sgf4.html // "Note: it's bad style to have move properties in root nodes. // (it isn't forbidden though)" return moves - 1; }
[ "function", "(", ")", "{", "var", "localSequence", "=", "this", ".", "game", ";", "var", "moves", "=", "0", ";", "while", "(", "localSequence", ")", "{", "moves", "+=", "localSequence", ".", "nodes", ".", "length", ";", "if", "(", "localSequence", ".", "sequences", ")", "{", "localSequence", "=", "localSequence", ".", "sequences", "[", "0", "]", ";", "}", "else", "{", "localSequence", "=", "null", ";", "}", "}", "return", "moves", "-", "1", ";", "}" ]
Get the total number of moves in a game
[ "Get", "the", "total", "number", "of", "moves", "in", "a", "game" ]
83a4b47c476729a19f8d04c165c0c10b69095d62
https://github.com/neagle/smartgamer/blob/83a4b47c476729a19f8d04c165c0c10b69095d62/index.js#L202-L221
train
neagle/smartgamer
index.js
function (text) { if (typeof text === 'undefined') { // Unescape characters if (node.C) { return node.C.replace(/\\([\\:\]])/g, '$1'); } else { return ''; } } else { // Escape characters node.C = text.replace(/[\\:\]]/g, '\\$&'); } }
javascript
function (text) { if (typeof text === 'undefined') { // Unescape characters if (node.C) { return node.C.replace(/\\([\\:\]])/g, '$1'); } else { return ''; } } else { // Escape characters node.C = text.replace(/[\\:\]]/g, '\\$&'); } }
[ "function", "(", "text", ")", "{", "if", "(", "typeof", "text", "===", "'undefined'", ")", "{", "if", "(", "node", ".", "C", ")", "{", "return", "node", ".", "C", ".", "replace", "(", "/", "\\\\([\\\\:\\]])", "/", "g", ",", "'$1'", ")", ";", "}", "else", "{", "return", "''", ";", "}", "}", "else", "{", "node", ".", "C", "=", "text", ".", "replace", "(", "/", "[\\\\:\\]]", "/", "g", ",", "'\\\\$&'", ")", ";", "}", "}" ]
Get or set a comment on the current node @see http://www.red-bean.com/sgf/sgf4.html#text
[ "Get", "or", "set", "a", "comment", "on", "the", "current", "node" ]
83a4b47c476729a19f8d04c165c0c10b69095d62
https://github.com/neagle/smartgamer/blob/83a4b47c476729a19f8d04c165c0c10b69095d62/index.js#L225-L237
train