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
wanchain/wanx
src/btc/utils.js
buildIncompleteRedeem
function buildIncompleteRedeem(network, txid, address, value) { const bitcoinNetwork = bitcoin.networks[network]; // NB: storemen address validation requires that vout is 0 const vout = 0; const txb = new bitcoin.TransactionBuilder(bitcoinNetwork); txb.setVersion(1); txb.addInput(hex.stripPrefix(txid), vout); txb.addOutput(address, parseInt(value)); return txb.buildIncomplete(); }
javascript
function buildIncompleteRedeem(network, txid, address, value) { const bitcoinNetwork = bitcoin.networks[network]; // NB: storemen address validation requires that vout is 0 const vout = 0; const txb = new bitcoin.TransactionBuilder(bitcoinNetwork); txb.setVersion(1); txb.addInput(hex.stripPrefix(txid), vout); txb.addOutput(address, parseInt(value)); return txb.buildIncomplete(); }
[ "function", "buildIncompleteRedeem", "(", "network", ",", "txid", ",", "address", ",", "value", ")", "{", "const", "bitcoinNetwork", "=", "bitcoin", ".", "networks", "[", "network", "]", ";", "const", "vout", "=", "0", ";", "const", "txb", "=", "new", "bitcoin", ".", "TransactionBuilder", "(", "bitcoinNetwork", ")", ";", "txb", ".", "setVersion", "(", "1", ")", ";", "txb", ".", "addInput", "(", "hex", ".", "stripPrefix", "(", "txid", ")", ",", "vout", ")", ";", "txb", ".", "addOutput", "(", "address", ",", "parseInt", "(", "value", ")", ")", ";", "return", "txb", ".", "buildIncomplete", "(", ")", ";", "}" ]
Build incomplete redeem transaction @param {string} network - Network name (mainnet, testnet) @param {string} txid - The txid for the UTXO being spent @param {string} address - The address to receive funds @param {string|number} value - The amount of funds to be sent (in Satoshis) @returns {Object} Incomplete redeem transaction
[ "Build", "incomplete", "redeem", "transaction" ]
1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875
https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/btc/utils.js#L136-L149
train
wanchain/wanx
src/btc/utils.js
buildRedeemTx
function buildRedeemTx(network, txid, value, redeemScript, x, publicKey, signedSigHash, toAddress) { const bitcoinNetwork = bitcoin.networks[network]; // if toAddress is not supplied, derive it from the publicKey if (! toAddress) { const { address } = bitcoin.payments.p2pkh({ network: bitcoinNetwork, pubkey: Buffer.from(publicKey, 'hex'), }); toAddress = address; } const tx = btcUtil.buildIncompleteRedeem(network, txid, toAddress, value); const signature = bitcoin.script.signature.encode( new Buffer.from(signedSigHash, 'base64'), bitcoin.Transaction.SIGHASH_ALL ); const scriptSig = bitcoin.payments.p2sh({ redeem: { input: bitcoin.script.compile([ signature, Buffer.from(publicKey, 'hex'), Buffer.from(x, 'hex'), bitcoin.opcodes.OP_TRUE, ]), output: new Buffer.from(redeemScript, 'hex'), }, network: bitcoinNetwork, }).input; tx.setInputScript(0, scriptSig); return tx.toHex(); }
javascript
function buildRedeemTx(network, txid, value, redeemScript, x, publicKey, signedSigHash, toAddress) { const bitcoinNetwork = bitcoin.networks[network]; // if toAddress is not supplied, derive it from the publicKey if (! toAddress) { const { address } = bitcoin.payments.p2pkh({ network: bitcoinNetwork, pubkey: Buffer.from(publicKey, 'hex'), }); toAddress = address; } const tx = btcUtil.buildIncompleteRedeem(network, txid, toAddress, value); const signature = bitcoin.script.signature.encode( new Buffer.from(signedSigHash, 'base64'), bitcoin.Transaction.SIGHASH_ALL ); const scriptSig = bitcoin.payments.p2sh({ redeem: { input: bitcoin.script.compile([ signature, Buffer.from(publicKey, 'hex'), Buffer.from(x, 'hex'), bitcoin.opcodes.OP_TRUE, ]), output: new Buffer.from(redeemScript, 'hex'), }, network: bitcoinNetwork, }).input; tx.setInputScript(0, scriptSig); return tx.toHex(); }
[ "function", "buildRedeemTx", "(", "network", ",", "txid", ",", "value", ",", "redeemScript", ",", "x", ",", "publicKey", ",", "signedSigHash", ",", "toAddress", ")", "{", "const", "bitcoinNetwork", "=", "bitcoin", ".", "networks", "[", "network", "]", ";", "if", "(", "!", "toAddress", ")", "{", "const", "{", "address", "}", "=", "bitcoin", ".", "payments", ".", "p2pkh", "(", "{", "network", ":", "bitcoinNetwork", ",", "pubkey", ":", "Buffer", ".", "from", "(", "publicKey", ",", "'hex'", ")", ",", "}", ")", ";", "toAddress", "=", "address", ";", "}", "const", "tx", "=", "btcUtil", ".", "buildIncompleteRedeem", "(", "network", ",", "txid", ",", "toAddress", ",", "value", ")", ";", "const", "signature", "=", "bitcoin", ".", "script", ".", "signature", ".", "encode", "(", "new", "Buffer", ".", "from", "(", "signedSigHash", ",", "'base64'", ")", ",", "bitcoin", ".", "Transaction", ".", "SIGHASH_ALL", ")", ";", "const", "scriptSig", "=", "bitcoin", ".", "payments", ".", "p2sh", "(", "{", "redeem", ":", "{", "input", ":", "bitcoin", ".", "script", ".", "compile", "(", "[", "signature", ",", "Buffer", ".", "from", "(", "publicKey", ",", "'hex'", ")", ",", "Buffer", ".", "from", "(", "x", ",", "'hex'", ")", ",", "bitcoin", ".", "opcodes", ".", "OP_TRUE", ",", "]", ")", ",", "output", ":", "new", "Buffer", ".", "from", "(", "redeemScript", ",", "'hex'", ")", ",", "}", ",", "network", ":", "bitcoinNetwork", ",", "}", ")", ".", "input", ";", "tx", ".", "setInputScript", "(", "0", ",", "scriptSig", ")", ";", "return", "tx", ".", "toHex", "(", ")", ";", "}" ]
Create redeem transaction using signed sigHash @param {string} network - Network name (mainnet, testnet) @param {string} txid - The txid for the UTXO being spent @param {string|number} value - The amount of funds to be sent (in Satoshis) @param {string} redeemScript - The redeemScript of the P2SH address @param {string} x - The x value for the transaction @param {string} publicKey - The publicKey of the redeemer @param {string} signedSigHash - The sigHash signed by the redeemer @param {string} toAddress - The address where to send funds (defaults to redeemer) @returns {string} Signed transaction as hex string
[ "Create", "redeem", "transaction", "using", "signed", "sigHash" ]
1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875
https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/btc/utils.js#L188-L225
train
aantthony/javascript-cas
examples/solver.js
solveLinearIntersect
function solveLinearIntersect(a,b, c, d,e, f) { // ax + by = c; // dx + ey = d; console.log('WORKED: ', arguments); if(a === 0) { var y = c/b; var x = (d-e*y)/x; return [x, y]; } var denom = e-d/a * b; if(denom === 0) { // Either infinite solutions or no solutions return [undefined, undefined]; } var y = (f-d*c/a)/denom; var x = (c-b*y) / a; return [x, y]; }
javascript
function solveLinearIntersect(a,b, c, d,e, f) { // ax + by = c; // dx + ey = d; console.log('WORKED: ', arguments); if(a === 0) { var y = c/b; var x = (d-e*y)/x; return [x, y]; } var denom = e-d/a * b; if(denom === 0) { // Either infinite solutions or no solutions return [undefined, undefined]; } var y = (f-d*c/a)/denom; var x = (c-b*y) / a; return [x, y]; }
[ "function", "solveLinearIntersect", "(", "a", ",", "b", ",", "c", ",", "d", ",", "e", ",", "f", ")", "{", "console", ".", "log", "(", "'WORKED: '", ",", "arguments", ")", ";", "if", "(", "a", "===", "0", ")", "{", "var", "y", "=", "c", "/", "b", ";", "var", "x", "=", "(", "d", "-", "e", "*", "y", ")", "/", "x", ";", "return", "[", "x", ",", "y", "]", ";", "}", "var", "denom", "=", "e", "-", "d", "/", "a", "*", "b", ";", "if", "(", "denom", "===", "0", ")", "{", "return", "[", "undefined", ",", "undefined", "]", ";", "}", "var", "y", "=", "(", "f", "-", "d", "*", "c", "/", "a", ")", "/", "denom", ";", "var", "x", "=", "(", "c", "-", "b", "*", "y", ")", "/", "a", ";", "return", "[", "x", ",", "y", "]", ";", "}" ]
Does not work!!!, but a general idea of how it would once bugs are fixed.
[ "Does", "not", "work!!!", "but", "a", "general", "idea", "of", "how", "it", "would", "once", "bugs", "are", "fixed", "." ]
d13ca4eb1a8aee3b712a8d48e06280b87bf96ed3
https://github.com/aantthony/javascript-cas/blob/d13ca4eb1a8aee3b712a8d48e06280b87bf96ed3/examples/solver.js#L3-L20
train
wanchain/wanx
src/lib/hex.js
fromString
function fromString(str) { const bytes = []; for (let n = 0, l = str.length; n < l; n++) { const hex = Number(str.charCodeAt(n)).toString(16); bytes.push(hex); } return '0x' + bytes.join(''); }
javascript
function fromString(str) { const bytes = []; for (let n = 0, l = str.length; n < l; n++) { const hex = Number(str.charCodeAt(n)).toString(16); bytes.push(hex); } return '0x' + bytes.join(''); }
[ "function", "fromString", "(", "str", ")", "{", "const", "bytes", "=", "[", "]", ";", "for", "(", "let", "n", "=", "0", ",", "l", "=", "str", ".", "length", ";", "n", "<", "l", ";", "n", "++", ")", "{", "const", "hex", "=", "Number", "(", "str", ".", "charCodeAt", "(", "n", ")", ")", ".", "toString", "(", "16", ")", ";", "bytes", ".", "push", "(", "hex", ")", ";", "}", "return", "'0x'", "+", "bytes", ".", "join", "(", "''", ")", ";", "}" ]
Convert ascii `String` to hex @param {String} str @return {String}
[ "Convert", "ascii", "String", "to", "hex" ]
1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875
https://github.com/wanchain/wanx/blob/1136b7b8ae79cc6e5499f5eb63d5cdb1e6080875/src/lib/hex.js#L62-L71
train
siffogh/eslint-plugin-better-styled-components
lib/rules/sort-declarations-alphabetically.js
isValidAtomicRule
function isValidAtomicRule(rule) { const decls = rule.nodes.filter(node => node.type === "decl"); if (decls.length < 0) { return { isValid: true }; } for (let i = 1; i < decls.length; i++) { const current = decls[i].prop; const prev = decls[i - 1].prop; if (current < prev) { const loc = { start: { line: decls[i - 1].source.start.line, column: decls[i - 1].source.start.column - 1 }, end: { line: decls[i].source.end.line, column: decls[i].source.end.column - 1 } }; return { isValid: false, loc }; } } return { isValid: true }; }
javascript
function isValidAtomicRule(rule) { const decls = rule.nodes.filter(node => node.type === "decl"); if (decls.length < 0) { return { isValid: true }; } for (let i = 1; i < decls.length; i++) { const current = decls[i].prop; const prev = decls[i - 1].prop; if (current < prev) { const loc = { start: { line: decls[i - 1].source.start.line, column: decls[i - 1].source.start.column - 1 }, end: { line: decls[i].source.end.line, column: decls[i].source.end.column - 1 } }; return { isValid: false, loc }; } } return { isValid: true }; }
[ "function", "isValidAtomicRule", "(", "rule", ")", "{", "const", "decls", "=", "rule", ".", "nodes", ".", "filter", "(", "node", "=>", "node", ".", "type", "===", "\"decl\"", ")", ";", "if", "(", "decls", ".", "length", "<", "0", ")", "{", "return", "{", "isValid", ":", "true", "}", ";", "}", "for", "(", "let", "i", "=", "1", ";", "i", "<", "decls", ".", "length", ";", "i", "++", ")", "{", "const", "current", "=", "decls", "[", "i", "]", ".", "prop", ";", "const", "prev", "=", "decls", "[", "i", "-", "1", "]", ".", "prop", ";", "if", "(", "current", "<", "prev", ")", "{", "const", "loc", "=", "{", "start", ":", "{", "line", ":", "decls", "[", "i", "-", "1", "]", ".", "source", ".", "start", ".", "line", ",", "column", ":", "decls", "[", "i", "-", "1", "]", ".", "source", ".", "start", ".", "column", "-", "1", "}", ",", "end", ":", "{", "line", ":", "decls", "[", "i", "]", ".", "source", ".", "end", ".", "line", ",", "column", ":", "decls", "[", "i", "]", ".", "source", ".", "end", ".", "column", "-", "1", "}", "}", ";", "return", "{", "isValid", ":", "false", ",", "loc", "}", ";", "}", "}", "return", "{", "isValid", ":", "true", "}", ";", "}" ]
An atomic rule is a rule without nested rules.
[ "An", "atomic", "rule", "is", "a", "rule", "without", "nested", "rules", "." ]
0728200fa2f0a58af5fac6c94538bda292ab1d2a
https://github.com/siffogh/eslint-plugin-better-styled-components/blob/0728200fa2f0a58af5fac6c94538bda292ab1d2a/lib/rules/sort-declarations-alphabetically.js#L14-L40
train
frozzare/json-to-html
index.js
html
function html(obj, indents) { indents = indents || 1; function indent() { return Array(indents).join(' '); } if ('string' == typeof obj) { var str = escape(obj); if (urlRegex().test(obj)) { str = '<a href="' + str + '">' + str + '</a>'; } return span('string value', '"' + str + '"'); } if ('number' == typeof obj) { return span('number', obj); } if ('boolean' == typeof obj) { return span('boolean', obj); } if (null === obj) { return span('null', 'null'); } var buf; if (Array.isArray(obj)) { ++indents; buf = '[\n' + obj.map(function(val){ return indent() + html(val, indents); }).join(',\n'); --indents; buf += '\n' + indent() + ']'; return buf; } buf = '{'; var keys = Object.keys(obj); var len = keys.length; if (len) buf += '\n'; ++indents; buf += keys.map(function(key){ var val = obj[key]; key = '"' + key + '"'; key = span('string key', key); return indent() + key + ': ' + html(val, indents); }).join(',\n'); --indents; if (len) buf += '\n' + indent(); buf += '}'; return buf; }
javascript
function html(obj, indents) { indents = indents || 1; function indent() { return Array(indents).join(' '); } if ('string' == typeof obj) { var str = escape(obj); if (urlRegex().test(obj)) { str = '<a href="' + str + '">' + str + '</a>'; } return span('string value', '"' + str + '"'); } if ('number' == typeof obj) { return span('number', obj); } if ('boolean' == typeof obj) { return span('boolean', obj); } if (null === obj) { return span('null', 'null'); } var buf; if (Array.isArray(obj)) { ++indents; buf = '[\n' + obj.map(function(val){ return indent() + html(val, indents); }).join(',\n'); --indents; buf += '\n' + indent() + ']'; return buf; } buf = '{'; var keys = Object.keys(obj); var len = keys.length; if (len) buf += '\n'; ++indents; buf += keys.map(function(key){ var val = obj[key]; key = '"' + key + '"'; key = span('string key', key); return indent() + key + ': ' + html(val, indents); }).join(',\n'); --indents; if (len) buf += '\n' + indent(); buf += '}'; return buf; }
[ "function", "html", "(", "obj", ",", "indents", ")", "{", "indents", "=", "indents", "||", "1", ";", "function", "indent", "(", ")", "{", "return", "Array", "(", "indents", ")", ".", "join", "(", "' '", ")", ";", "}", "if", "(", "'string'", "==", "typeof", "obj", ")", "{", "var", "str", "=", "escape", "(", "obj", ")", ";", "if", "(", "urlRegex", "(", ")", ".", "test", "(", "obj", ")", ")", "{", "str", "=", "'<a href=\"'", "+", "str", "+", "'\">'", "+", "str", "+", "'</a>'", ";", "}", "return", "span", "(", "'string value'", ",", "'\"'", "+", "str", "+", "'\"'", ")", ";", "}", "if", "(", "'number'", "==", "typeof", "obj", ")", "{", "return", "span", "(", "'number'", ",", "obj", ")", ";", "}", "if", "(", "'boolean'", "==", "typeof", "obj", ")", "{", "return", "span", "(", "'boolean'", ",", "obj", ")", ";", "}", "if", "(", "null", "===", "obj", ")", "{", "return", "span", "(", "'null'", ",", "'null'", ")", ";", "}", "var", "buf", ";", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "++", "indents", ";", "buf", "=", "'[\\n'", "+", "\\n", ";", "obj", ".", "map", "(", "function", "(", "val", ")", "{", "return", "indent", "(", ")", "+", "html", "(", "val", ",", "indents", ")", ";", "}", ")", ".", "join", "(", "',\\n'", ")", "\\n", "--", "indents", ";", "}", "buf", "+=", "'\\n'", "+", "\\n", "+", "indent", "(", ")", ";", "']'", "return", "buf", ";", "buf", "=", "'{'", ";", "var", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ";", "var", "len", "=", "keys", ".", "length", ";", "if", "(", "len", ")", "buf", "+=", "'\\n'", ";", "\\n", "++", "indents", ";", "buf", "+=", "keys", ".", "map", "(", "function", "(", "key", ")", "{", "var", "val", "=", "obj", "[", "key", "]", ";", "key", "=", "'\"'", "+", "key", "+", "'\"'", ";", "key", "=", "span", "(", "'string key'", ",", "key", ")", ";", "return", "indent", "(", ")", "+", "key", "+", "': '", "+", "html", "(", "val", ",", "indents", ")", ";", "}", ")", ".", "join", "(", "',\\n'", ")", ";", "}" ]
Convert JSON Object to html. @param {Object} obj @return {String} @api public
[ "Convert", "JSON", "Object", "to", "html", "." ]
07c45bf5e686855fd7ccab0c99d58effef3e744c
https://github.com/frozzare/json-to-html/blob/07c45bf5e686855fd7ccab0c99d58effef3e744c/index.js#L47-L106
train
thauburger/js-heap
heap.js
function(sort) { this._array = []; this._sort = sort; Object.defineProperty(this, 'length', { enumerable: true, get: function() { return this._array.length }, }); if (typeof this._sort !== 'function') { this._sort = function(a, b) { return a - b; } } }
javascript
function(sort) { this._array = []; this._sort = sort; Object.defineProperty(this, 'length', { enumerable: true, get: function() { return this._array.length }, }); if (typeof this._sort !== 'function') { this._sort = function(a, b) { return a - b; } } }
[ "function", "(", "sort", ")", "{", "this", ".", "_array", "=", "[", "]", ";", "this", ".", "_sort", "=", "sort", ";", "Object", ".", "defineProperty", "(", "this", ",", "'length'", ",", "{", "enumerable", ":", "true", ",", "get", ":", "function", "(", ")", "{", "return", "this", ".", "_array", ".", "length", "}", ",", "}", ")", ";", "if", "(", "typeof", "this", ".", "_sort", "!==", "'function'", ")", "{", "this", ".", "_sort", "=", "function", "(", "a", ",", "b", ")", "{", "return", "a", "-", "b", ";", "}", "}", "}" ]
heap.js JS heap implementation
[ "heap", ".", "js", "JS", "heap", "implementation" ]
019d4b6ad4aa8a424760d17405d99a1fc5bca84d
https://github.com/thauburger/js-heap/blob/019d4b6ad4aa8a424760d17405d99a1fc5bca84d/heap.js#L6-L20
train
ozum/auto-generate
lib/auto-generate.js
autoStartLine
function autoStartLine(name) { var pre = new Array(Math.floor((60 - name.length) / 2) - 3).join('-'); var post = new Array(60 - pre.length - name.length).join('-'); return signature + 'S' + pre + ' Auto Start: ' + name + ' ' + post + '\n'; }
javascript
function autoStartLine(name) { var pre = new Array(Math.floor((60 - name.length) / 2) - 3).join('-'); var post = new Array(60 - pre.length - name.length).join('-'); return signature + 'S' + pre + ' Auto Start: ' + name + ' ' + post + '\n'; }
[ "function", "autoStartLine", "(", "name", ")", "{", "var", "pre", "=", "new", "Array", "(", "Math", ".", "floor", "(", "(", "60", "-", "name", ".", "length", ")", "/", "2", ")", "-", "3", ")", ".", "join", "(", "'-'", ")", ";", "var", "post", "=", "new", "Array", "(", "60", "-", "pre", ".", "length", "-", "name", ".", "length", ")", ".", "join", "(", "'-'", ")", ";", "return", "signature", "+", "'S'", "+", "pre", "+", "' Auto Start: '", "+", "name", "+", "' '", "+", "post", "+", "'\\n'", ";", "}" ]
Object which contains detailed info of an auto generated part. @private @typedef {Object} partInfo @property {string} startLine - Start line (opening tag / marker) of auto generated part. @property {string} warningLine - Warning message line of auto generated part. @property {string} content - Auto generated content. @property {string} md5Line - Line which contains md5 of the content. @property {string} oldDigest - MD5 which is written in the file. @property {string} newDigest - MD5 calculated freshly for the content. @property {boolean} isChanged - Indicates if part is modified by comparing MD5 written in file with new calculated MD5 @property {string} endLine - End line (closing tag / marker) of auto generated part. Generates and returns start line (opening tag / marker) of auto generated part. @private @param {string} name - name of the auto generated part @returns {string} - first line of the auto generated part.
[ "Object", "which", "contains", "detailed", "info", "of", "an", "auto", "generated", "part", "." ]
5b8574514d5095d647545e93e6042cd585f90d48
https://github.com/ozum/auto-generate/blob/5b8574514d5095d647545e93e6042cd585f90d48/lib/auto-generate.js#L105-L109
train
ozum/auto-generate
lib/auto-generate.js
makeBackup
function makeBackup(filePath) { var dateString = new Date().toISOString().replace(/:/g, '.').replace('Z', '').replace('T', ' '); try { fs.mkdirSync(path.join(path.dirname(filePath), 'BACKUP')); } catch(err) { if (err.code != 'EEXIST') { throw err } } fs.writeFileSync(path.join(path.dirname(filePath), 'BACKUP', dateString + ' ' + path.basename(filePath) ), fs.readFileSync(path.normalize(filePath))); }
javascript
function makeBackup(filePath) { var dateString = new Date().toISOString().replace(/:/g, '.').replace('Z', '').replace('T', ' '); try { fs.mkdirSync(path.join(path.dirname(filePath), 'BACKUP')); } catch(err) { if (err.code != 'EEXIST') { throw err } } fs.writeFileSync(path.join(path.dirname(filePath), 'BACKUP', dateString + ' ' + path.basename(filePath) ), fs.readFileSync(path.normalize(filePath))); }
[ "function", "makeBackup", "(", "filePath", ")", "{", "var", "dateString", "=", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ".", "replace", "(", "/", ":", "/", "g", ",", "'.'", ")", ".", "replace", "(", "'Z'", ",", "''", ")", ".", "replace", "(", "'T'", ",", "' '", ")", ";", "try", "{", "fs", ".", "mkdirSync", "(", "path", ".", "join", "(", "path", ".", "dirname", "(", "filePath", ")", ",", "'BACKUP'", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "if", "(", "err", ".", "code", "!=", "'EEXIST'", ")", "{", "throw", "err", "}", "}", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "path", ".", "dirname", "(", "filePath", ")", ",", "'BACKUP'", ",", "dateString", "+", "' '", "+", "path", ".", "basename", "(", "filePath", ")", ")", ",", "fs", ".", "readFileSync", "(", "path", ".", "normalize", "(", "filePath", ")", ")", ")", ";", "}" ]
Creates backup of a file. To do this, it creates a directory called BACKUP in the same directory where original file is located in. Backup file name has a suffix of ISO style date and time. ie. 'model.js' becomes '2014-01-12 22.02.23.345 model.js' @private @param {string} filePath - Absolute path of file
[ "Creates", "backup", "of", "a", "file", ".", "To", "do", "this", "it", "creates", "a", "directory", "called", "BACKUP", "in", "the", "same", "directory", "where", "original", "file", "is", "located", "in", ".", "Backup", "file", "name", "has", "a", "suffix", "of", "ISO", "style", "date", "and", "time", ".", "ie", ".", "model", ".", "js", "becomes", "2014", "-", "01", "-", "12", "22", ".", "02", ".", "23", ".", "345", "model", ".", "js" ]
5b8574514d5095d647545e93e6042cd585f90d48
https://github.com/ozum/auto-generate/blob/5b8574514d5095d647545e93e6042cd585f90d48/lib/auto-generate.js#L130-L135
train
ozum/auto-generate
lib/auto-generate.js
getPart
function getPart(name, fileContent, options) { if (!name || !options) { throw new Error('name and options are required.'); } var parts = fileContent.match(getRegularExpression(name)); if ( parts ) { // Aranan bölüm varsa var fileContentDigest = calculateMD5(parts[3], options); return { all : parts[0], startLine : parts[1], warningLine : parts[2], content : parts[3], md5Line : parts[4], oldDigest : parts[5], newDigest : fileContentDigest, isChanged : fileContentDigest != parts[5], endLine : parts[6] } } else { return null; } }
javascript
function getPart(name, fileContent, options) { if (!name || !options) { throw new Error('name and options are required.'); } var parts = fileContent.match(getRegularExpression(name)); if ( parts ) { // Aranan bölüm varsa var fileContentDigest = calculateMD5(parts[3], options); return { all : parts[0], startLine : parts[1], warningLine : parts[2], content : parts[3], md5Line : parts[4], oldDigest : parts[5], newDigest : fileContentDigest, isChanged : fileContentDigest != parts[5], endLine : parts[6] } } else { return null; } }
[ "function", "getPart", "(", "name", ",", "fileContent", ",", "options", ")", "{", "if", "(", "!", "name", "||", "!", "options", ")", "{", "throw", "new", "Error", "(", "'name and options are required.'", ")", ";", "}", "var", "parts", "=", "fileContent", ".", "match", "(", "getRegularExpression", "(", "name", ")", ")", ";", "if", "(", "parts", ")", "{", "var", "fileContentDigest", "=", "calculateMD5", "(", "parts", "[", "3", "]", ",", "options", ")", ";", "return", "{", "all", ":", "parts", "[", "0", "]", ",", "startLine", ":", "parts", "[", "1", "]", ",", "warningLine", ":", "parts", "[", "2", "]", ",", "content", ":", "parts", "[", "3", "]", ",", "md5Line", ":", "parts", "[", "4", "]", ",", "oldDigest", ":", "parts", "[", "5", "]", ",", "newDigest", ":", "fileContentDigest", ",", "isChanged", ":", "fileContentDigest", "!=", "parts", "[", "5", "]", ",", "endLine", ":", "parts", "[", "6", "]", "}", "}", "else", "{", "return", "null", ";", "}", "}" ]
Finds auto generated part and returns an object which contains information about auto generated part. If auto part with requested name cannot be found, it returns null. @private @param name - Name of the auto generated part. @param fileContent - content of the file which part is searched in. @param {genOptions} options - Options how part is generated. @returns {partInfo|null} - Object which contains info about auto generated part.
[ "Finds", "auto", "generated", "part", "and", "returns", "an", "object", "which", "contains", "information", "about", "auto", "generated", "part", ".", "If", "auto", "part", "with", "requested", "name", "cannot", "be", "found", "it", "returns", "null", "." ]
5b8574514d5095d647545e93e6042cd585f90d48
https://github.com/ozum/auto-generate/blob/5b8574514d5095d647545e93e6042cd585f90d48/lib/auto-generate.js#L180-L202
train
ozum/auto-generate
lib/auto-generate.js
fileExists
function fileExists(file) { try { var targetStat = fs.statSync(file); if (targetStat.isDirectory() ) { throw new Error("File exists but it's a driectory: " + file); } } catch(err) { if (err.code == 'ENOENT') { // No such file or directory return false; } else { throw err; } } return true; }
javascript
function fileExists(file) { try { var targetStat = fs.statSync(file); if (targetStat.isDirectory() ) { throw new Error("File exists but it's a driectory: " + file); } } catch(err) { if (err.code == 'ENOENT') { // No such file or directory return false; } else { throw err; } } return true; }
[ "function", "fileExists", "(", "file", ")", "{", "try", "{", "var", "targetStat", "=", "fs", ".", "statSync", "(", "file", ")", ";", "if", "(", "targetStat", ".", "isDirectory", "(", ")", ")", "{", "throw", "new", "Error", "(", "\"File exists but it's a driectory: \"", "+", "file", ")", ";", "}", "}", "catch", "(", "err", ")", "{", "if", "(", "err", ".", "code", "==", "'ENOENT'", ")", "{", "return", "false", ";", "}", "else", "{", "throw", "err", ";", "}", "}", "return", "true", ";", "}" ]
Checks if the file exists at the given path. Returns true if it exists, false otherwise. @private @param {string} file - Path of the file to check @returns {boolean}
[ "Checks", "if", "the", "file", "exists", "at", "the", "given", "path", ".", "Returns", "true", "if", "it", "exists", "false", "otherwise", "." ]
5b8574514d5095d647545e93e6042cd585f90d48
https://github.com/ozum/auto-generate/blob/5b8574514d5095d647545e93e6042cd585f90d48/lib/auto-generate.js#L210-L226
train
goto-bus-stop/browser-pack-flat
example/out/flat.js
walk
function walk (newNode, oldNode) { // if (DEBUG) { // console.log( // 'walk\nold\n %s\nnew\n %s', // oldNode && oldNode.outerHTML, // newNode && newNode.outerHTML // ) // } if (!oldNode) { return newNode } else if (!newNode) { return null } else if (newNode.isSameNode && newNode.isSameNode(oldNode)) { return oldNode } else if (newNode.tagName !== oldNode.tagName) { return newNode } else { _$morph_11(newNode, oldNode) updateChildren(newNode, oldNode) return oldNode } }
javascript
function walk (newNode, oldNode) { // if (DEBUG) { // console.log( // 'walk\nold\n %s\nnew\n %s', // oldNode && oldNode.outerHTML, // newNode && newNode.outerHTML // ) // } if (!oldNode) { return newNode } else if (!newNode) { return null } else if (newNode.isSameNode && newNode.isSameNode(oldNode)) { return oldNode } else if (newNode.tagName !== oldNode.tagName) { return newNode } else { _$morph_11(newNode, oldNode) updateChildren(newNode, oldNode) return oldNode } }
[ "function", "walk", "(", "newNode", ",", "oldNode", ")", "{", "if", "(", "!", "oldNode", ")", "{", "return", "newNode", "}", "else", "if", "(", "!", "newNode", ")", "{", "return", "null", "}", "else", "if", "(", "newNode", ".", "isSameNode", "&&", "newNode", ".", "isSameNode", "(", "oldNode", ")", ")", "{", "return", "oldNode", "}", "else", "if", "(", "newNode", ".", "tagName", "!==", "oldNode", ".", "tagName", ")", "{", "return", "newNode", "}", "else", "{", "_$morph_11", "(", "newNode", ",", "oldNode", ")", "updateChildren", "(", "newNode", ",", "oldNode", ")", "return", "oldNode", "}", "}" ]
Walk and morph a dom tree
[ "Walk", "and", "morph", "a", "dom", "tree" ]
c12e407a027a0a07c6d750781125317d6a166327
https://github.com/goto-bus-stop/browser-pack-flat/blob/c12e407a027a0a07c6d750781125317d6a166327/example/out/flat.js#L270-L291
train
byteclubfr/js-hal
hal.js
Link
function Link (rel, value) { if (!(this instanceof Link)) { return new Link(rel, value); } if (!rel) throw new Error('Required <link> attribute "rel"'); this.rel = rel; if (typeof value === 'object') { // If value is a hashmap, just copy properties if (!value.href) throw new Error('Required <link> attribute "href"'); var expectedAttributes = ['rel', 'href', 'name', 'hreflang', 'title', 'templated', 'icon', 'align', 'method']; for (var attr in value) { if (value.hasOwnProperty(attr)) { if (!~expectedAttributes.indexOf(attr)) { // Unexpected attribute: ignore it continue; } this[attr] = value[attr]; } } } else { // value is a scalar: use its value as href if (!value) throw new Error('Required <link> attribute "href"'); this.href = String(value); } }
javascript
function Link (rel, value) { if (!(this instanceof Link)) { return new Link(rel, value); } if (!rel) throw new Error('Required <link> attribute "rel"'); this.rel = rel; if (typeof value === 'object') { // If value is a hashmap, just copy properties if (!value.href) throw new Error('Required <link> attribute "href"'); var expectedAttributes = ['rel', 'href', 'name', 'hreflang', 'title', 'templated', 'icon', 'align', 'method']; for (var attr in value) { if (value.hasOwnProperty(attr)) { if (!~expectedAttributes.indexOf(attr)) { // Unexpected attribute: ignore it continue; } this[attr] = value[attr]; } } } else { // value is a scalar: use its value as href if (!value) throw new Error('Required <link> attribute "href"'); this.href = String(value); } }
[ "function", "Link", "(", "rel", ",", "value", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Link", ")", ")", "{", "return", "new", "Link", "(", "rel", ",", "value", ")", ";", "}", "if", "(", "!", "rel", ")", "throw", "new", "Error", "(", "'Required <link> attribute \"rel\"'", ")", ";", "this", ".", "rel", "=", "rel", ";", "if", "(", "typeof", "value", "===", "'object'", ")", "{", "if", "(", "!", "value", ".", "href", ")", "throw", "new", "Error", "(", "'Required <link> attribute \"href\"'", ")", ";", "var", "expectedAttributes", "=", "[", "'rel'", ",", "'href'", ",", "'name'", ",", "'hreflang'", ",", "'title'", ",", "'templated'", ",", "'icon'", ",", "'align'", ",", "'method'", "]", ";", "for", "(", "var", "attr", "in", "value", ")", "{", "if", "(", "value", ".", "hasOwnProperty", "(", "attr", ")", ")", "{", "if", "(", "!", "~", "expectedAttributes", ".", "indexOf", "(", "attr", ")", ")", "{", "continue", ";", "}", "this", "[", "attr", "]", "=", "value", "[", "attr", "]", ";", "}", "}", "}", "else", "{", "if", "(", "!", "value", ")", "throw", "new", "Error", "(", "'Required <link> attribute \"href\"'", ")", ";", "this", ".", "href", "=", "String", "(", "value", ")", ";", "}", "}" ]
Link to another hypermedia @param String rel → the relation identifier @param String|Object value → the href, or the hash of all attributes (including href)
[ "Link", "to", "another", "hypermedia" ]
16c1e6d15093b7eee28f874b56081a58ed7f4f03
https://github.com/byteclubfr/js-hal/blob/16c1e6d15093b7eee28f874b56081a58ed7f4f03/hal.js#L8-L39
train
byteclubfr/js-hal
hal.js
Resource
function Resource (object, uri) { // new Resource(resource) === resource if (object instanceof Resource) { return object; } // Still work if "new" is omitted if (!(this instanceof Resource)) { return new Resource(object, uri); } // Initialize _links and _embedded properties this._links = {}; this._embedded = {}; // Copy properties from object // we copy AFTER initializing _links and _embedded so that user // **CAN** (but should not) overwrite them for (var property in object) { if (object.hasOwnProperty(property)) { this[property] = object[property]; } } // Use uri or object.href to initialize the only required <link>: rel = self uri = uri || this.href; if (uri === this.href) { delete this.href; } // If we have a URI, add this link // If not, we won't have a valid object (this may lead to a fatal error later) if (uri) this.link(new Link('self', uri)); }
javascript
function Resource (object, uri) { // new Resource(resource) === resource if (object instanceof Resource) { return object; } // Still work if "new" is omitted if (!(this instanceof Resource)) { return new Resource(object, uri); } // Initialize _links and _embedded properties this._links = {}; this._embedded = {}; // Copy properties from object // we copy AFTER initializing _links and _embedded so that user // **CAN** (but should not) overwrite them for (var property in object) { if (object.hasOwnProperty(property)) { this[property] = object[property]; } } // Use uri or object.href to initialize the only required <link>: rel = self uri = uri || this.href; if (uri === this.href) { delete this.href; } // If we have a URI, add this link // If not, we won't have a valid object (this may lead to a fatal error later) if (uri) this.link(new Link('self', uri)); }
[ "function", "Resource", "(", "object", ",", "uri", ")", "{", "if", "(", "object", "instanceof", "Resource", ")", "{", "return", "object", ";", "}", "if", "(", "!", "(", "this", "instanceof", "Resource", ")", ")", "{", "return", "new", "Resource", "(", "object", ",", "uri", ")", ";", "}", "this", ".", "_links", "=", "{", "}", ";", "this", ".", "_embedded", "=", "{", "}", ";", "for", "(", "var", "property", "in", "object", ")", "{", "if", "(", "object", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "this", "[", "property", "]", "=", "object", "[", "property", "]", ";", "}", "}", "uri", "=", "uri", "||", "this", ".", "href", ";", "if", "(", "uri", "===", "this", ".", "href", ")", "{", "delete", "this", ".", "href", ";", "}", "if", "(", "uri", ")", "this", ".", "link", "(", "new", "Link", "(", "'self'", ",", "uri", ")", ")", ";", "}" ]
A hypertext resource @param Object object → the base properties Define "href" if you choose not to pass parameter "uri" Do not define "_links" and "_embedded" unless you know what you're doing @param String uri → href for the <link rel="self"> (can use reserved "href" property instead)
[ "A", "hypertext", "resource" ]
16c1e6d15093b7eee28f874b56081a58ed7f4f03
https://github.com/byteclubfr/js-hal/blob/16c1e6d15093b7eee28f874b56081a58ed7f4f03/hal.js#L74-L107
train
byteclubfr/js-hal
hal.js
resourceToJsonObject
function resourceToJsonObject (resource) { var result = {}; for (var prop in resource) { if (prop === '_links') { if (Object.keys(resource._links).length > 0) { // Note: we need to copy data to remove "rel" property without corrupting original Link object result._links = Object.keys(resource._links).reduce(function (links, rel) { if (Array.isArray(resource._links[rel])) { links[rel] = new Array() for (var i=0; i < resource._links[rel].length; i++) links[rel].push(resource._links[rel][i].toJSON()) } else { var link = resource._links[rel].toJSON(); links[rel] = link; delete link.rel; } return links; }, {}); } } else if (prop === '_embedded') { if (Object.keys(resource._embedded).length > 0) { // Note that we do not reformat _embedded // which means we voluntarily DO NOT RESPECT the following constraint: // > Relations with one corresponding Resource/Link have a single object // > value, relations with multiple corresponding HAL elements have an // > array of objects as their value. // Come on, resource one is *really* dumb. result._embedded = {}; for (var rel in resource._embedded) { result._embedded[rel] = resource._embedded[rel].map(resourceToJsonObject); } } } else if (resource.hasOwnProperty(prop)) { result[prop] = resource[prop]; } } return result; }
javascript
function resourceToJsonObject (resource) { var result = {}; for (var prop in resource) { if (prop === '_links') { if (Object.keys(resource._links).length > 0) { // Note: we need to copy data to remove "rel" property without corrupting original Link object result._links = Object.keys(resource._links).reduce(function (links, rel) { if (Array.isArray(resource._links[rel])) { links[rel] = new Array() for (var i=0; i < resource._links[rel].length; i++) links[rel].push(resource._links[rel][i].toJSON()) } else { var link = resource._links[rel].toJSON(); links[rel] = link; delete link.rel; } return links; }, {}); } } else if (prop === '_embedded') { if (Object.keys(resource._embedded).length > 0) { // Note that we do not reformat _embedded // which means we voluntarily DO NOT RESPECT the following constraint: // > Relations with one corresponding Resource/Link have a single object // > value, relations with multiple corresponding HAL elements have an // > array of objects as their value. // Come on, resource one is *really* dumb. result._embedded = {}; for (var rel in resource._embedded) { result._embedded[rel] = resource._embedded[rel].map(resourceToJsonObject); } } } else if (resource.hasOwnProperty(prop)) { result[prop] = resource[prop]; } } return result; }
[ "function", "resourceToJsonObject", "(", "resource", ")", "{", "var", "result", "=", "{", "}", ";", "for", "(", "var", "prop", "in", "resource", ")", "{", "if", "(", "prop", "===", "'_links'", ")", "{", "if", "(", "Object", ".", "keys", "(", "resource", ".", "_links", ")", ".", "length", ">", "0", ")", "{", "result", ".", "_links", "=", "Object", ".", "keys", "(", "resource", ".", "_links", ")", ".", "reduce", "(", "function", "(", "links", ",", "rel", ")", "{", "if", "(", "Array", ".", "isArray", "(", "resource", ".", "_links", "[", "rel", "]", ")", ")", "{", "links", "[", "rel", "]", "=", "new", "Array", "(", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "resource", ".", "_links", "[", "rel", "]", ".", "length", ";", "i", "++", ")", "links", "[", "rel", "]", ".", "push", "(", "resource", ".", "_links", "[", "rel", "]", "[", "i", "]", ".", "toJSON", "(", ")", ")", "}", "else", "{", "var", "link", "=", "resource", ".", "_links", "[", "rel", "]", ".", "toJSON", "(", ")", ";", "links", "[", "rel", "]", "=", "link", ";", "delete", "link", ".", "rel", ";", "}", "return", "links", ";", "}", ",", "{", "}", ")", ";", "}", "}", "else", "if", "(", "prop", "===", "'_embedded'", ")", "{", "if", "(", "Object", ".", "keys", "(", "resource", ".", "_embedded", ")", ".", "length", ">", "0", ")", "{", "result", ".", "_embedded", "=", "{", "}", ";", "for", "(", "var", "rel", "in", "resource", ".", "_embedded", ")", "{", "result", ".", "_embedded", "[", "rel", "]", "=", "resource", ".", "_embedded", "[", "rel", "]", ".", "map", "(", "resourceToJsonObject", ")", ";", "}", "}", "}", "else", "if", "(", "resource", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "result", "[", "prop", "]", "=", "resource", "[", "prop", "]", ";", "}", "}", "return", "result", ";", "}" ]
Convert a resource to a stringifiable anonymous object @private @param Resource resource
[ "Convert", "a", "resource", "to", "a", "stringifiable", "anonymous", "object" ]
16c1e6d15093b7eee28f874b56081a58ed7f4f03
https://github.com/byteclubfr/js-hal/blob/16c1e6d15093b7eee28f874b56081a58ed7f4f03/hal.js#L169-L211
train
byteclubfr/js-hal
hal.js
resourceToXml
function resourceToXml (resource, rel, currentIndent, nextIndent) { // Do not add line feeds if no indentation is asked var LF = (currentIndent || nextIndent) ? '\n' : ''; // Resource tag var xml = currentIndent + '<resource'; // Resource attributes: rel, href, name if (rel) xml += ' rel="' + escapeXml(rel) + '"'; if (resource.href || resource._links.self) xml += ' href="' + escapeXml(resource.href || resource._links.self.href) + '"'; if (resource.name) xml += ' name="' + escapeXml(resource.name) + '"'; xml += '>' + LF; // Add <link> tags for (var rel in resource._links) { if (!resource.href && rel === 'self') continue; xml += currentIndent + nextIndent + resource._links[rel].toXML() + LF; } // Add embedded for (var embed in resource._embedded) { // [Naive singularize](https://github.com/naholyr/js-hal#why-this-crappy-singularplural-management%E2%80%AF) var rel = embed.replace(/s$/, ''); resource._embedded[embed].forEach(function (res) { xml += resourceToXml(res, rel, currentIndent + nextIndent, currentIndent + nextIndent + nextIndent) + LF; }); } // Add properties as tags for (var prop in resource) { if (resource.hasOwnProperty(prop) && prop !== '_links' && prop !== '_embedded') { xml += currentIndent + nextIndent + '<' + prop + '>' + String(resource[prop]) + '</' + prop + '>' + LF; } } // Close tag and return the shit xml += currentIndent + '</resource>'; return xml; }
javascript
function resourceToXml (resource, rel, currentIndent, nextIndent) { // Do not add line feeds if no indentation is asked var LF = (currentIndent || nextIndent) ? '\n' : ''; // Resource tag var xml = currentIndent + '<resource'; // Resource attributes: rel, href, name if (rel) xml += ' rel="' + escapeXml(rel) + '"'; if (resource.href || resource._links.self) xml += ' href="' + escapeXml(resource.href || resource._links.self.href) + '"'; if (resource.name) xml += ' name="' + escapeXml(resource.name) + '"'; xml += '>' + LF; // Add <link> tags for (var rel in resource._links) { if (!resource.href && rel === 'self') continue; xml += currentIndent + nextIndent + resource._links[rel].toXML() + LF; } // Add embedded for (var embed in resource._embedded) { // [Naive singularize](https://github.com/naholyr/js-hal#why-this-crappy-singularplural-management%E2%80%AF) var rel = embed.replace(/s$/, ''); resource._embedded[embed].forEach(function (res) { xml += resourceToXml(res, rel, currentIndent + nextIndent, currentIndent + nextIndent + nextIndent) + LF; }); } // Add properties as tags for (var prop in resource) { if (resource.hasOwnProperty(prop) && prop !== '_links' && prop !== '_embedded') { xml += currentIndent + nextIndent + '<' + prop + '>' + String(resource[prop]) + '</' + prop + '>' + LF; } } // Close tag and return the shit xml += currentIndent + '</resource>'; return xml; }
[ "function", "resourceToXml", "(", "resource", ",", "rel", ",", "currentIndent", ",", "nextIndent", ")", "{", "var", "LF", "=", "(", "currentIndent", "||", "nextIndent", ")", "?", "'\\n'", ":", "\\n", ";", "''", "var", "xml", "=", "currentIndent", "+", "'<resource'", ";", "if", "(", "rel", ")", "xml", "+=", "' rel=\"'", "+", "escapeXml", "(", "rel", ")", "+", "'\"'", ";", "if", "(", "resource", ".", "href", "||", "resource", ".", "_links", ".", "self", ")", "xml", "+=", "' href=\"'", "+", "escapeXml", "(", "resource", ".", "href", "||", "resource", ".", "_links", ".", "self", ".", "href", ")", "+", "'\"'", ";", "if", "(", "resource", ".", "name", ")", "xml", "+=", "' name=\"'", "+", "escapeXml", "(", "resource", ".", "name", ")", "+", "'\"'", ";", "xml", "+=", "'>'", "+", "LF", ";", "for", "(", "var", "rel", "in", "resource", ".", "_links", ")", "{", "if", "(", "!", "resource", ".", "href", "&&", "rel", "===", "'self'", ")", "continue", ";", "xml", "+=", "currentIndent", "+", "nextIndent", "+", "resource", ".", "_links", "[", "rel", "]", ".", "toXML", "(", ")", "+", "LF", ";", "}", "for", "(", "var", "embed", "in", "resource", ".", "_embedded", ")", "{", "var", "rel", "=", "embed", ".", "replace", "(", "/", "s$", "/", ",", "''", ")", ";", "resource", ".", "_embedded", "[", "embed", "]", ".", "forEach", "(", "function", "(", "res", ")", "{", "xml", "+=", "resourceToXml", "(", "res", ",", "rel", ",", "currentIndent", "+", "nextIndent", ",", "currentIndent", "+", "nextIndent", "+", "nextIndent", ")", "+", "LF", ";", "}", ")", ";", "}", "for", "(", "var", "prop", "in", "resource", ")", "{", "if", "(", "resource", ".", "hasOwnProperty", "(", "prop", ")", "&&", "prop", "!==", "'_links'", "&&", "prop", "!==", "'_embedded'", ")", "{", "xml", "+=", "currentIndent", "+", "nextIndent", "+", "'<'", "+", "prop", "+", "'>'", "+", "String", "(", "resource", "[", "prop", "]", ")", "+", "'</'", "+", "prop", "+", "'>'", "+", "LF", ";", "}", "}", "xml", "+=", "currentIndent", "+", "'</resource>'", ";", "}" ]
Convert a resource to its XML representation @private @param Resource resource @param String rel → relation identifier for embedded object @param String currentIdent → current indentation @param String nextIndent → next indentation
[ "Convert", "a", "resource", "to", "its", "XML", "representation" ]
16c1e6d15093b7eee28f874b56081a58ed7f4f03
https://github.com/byteclubfr/js-hal/blob/16c1e6d15093b7eee28f874b56081a58ed7f4f03/hal.js#L238-L277
train
akamai/akamai-gen-edgerc
bin/gen-edgerc.js
init
function init() { // Retrieve any arguments passed in via the command line args = cliConfig.getArguments(); // Supply usage info if help argument was passed if (args.help) { console.log(cliConfig.getUsage()); process.exit(0); } getClientAuth(function(data) { parseClientAuth(data, function(err, data) { if (err) { console.error(err.message); process.exit(0); } writeEdgerc(data, function(err) { if (err) { if (err.errno == -13) { console.error("Unable to access " + err.path + ". Please make sure you " + "have permission to access this file or perhaps try running the " + "command as sudo."); process.exit(0); } } console.log("The section '" + args.section + "' has been succesfully added to " + args.path + "\n"); }); }); }); }
javascript
function init() { // Retrieve any arguments passed in via the command line args = cliConfig.getArguments(); // Supply usage info if help argument was passed if (args.help) { console.log(cliConfig.getUsage()); process.exit(0); } getClientAuth(function(data) { parseClientAuth(data, function(err, data) { if (err) { console.error(err.message); process.exit(0); } writeEdgerc(data, function(err) { if (err) { if (err.errno == -13) { console.error("Unable to access " + err.path + ". Please make sure you " + "have permission to access this file or perhaps try running the " + "command as sudo."); process.exit(0); } } console.log("The section '" + args.section + "' has been succesfully added to " + args.path + "\n"); }); }); }); }
[ "function", "init", "(", ")", "{", "args", "=", "cliConfig", ".", "getArguments", "(", ")", ";", "if", "(", "args", ".", "help", ")", "{", "console", ".", "log", "(", "cliConfig", ".", "getUsage", "(", ")", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "getClientAuth", "(", "function", "(", "data", ")", "{", "parseClientAuth", "(", "data", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "err", ".", "message", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "writeEdgerc", "(", "data", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "errno", "==", "-", "13", ")", "{", "console", ".", "error", "(", "\"Unable to access \"", "+", "err", ".", "path", "+", "\". Please make sure you \"", "+", "\"have permission to access this file or perhaps try running the \"", "+", "\"command as sudo.\"", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "}", "console", ".", "log", "(", "\"The section '\"", "+", "args", ".", "section", "+", "\"' has been succesfully added to \"", "+", "args", ".", "path", "+", "\"\\n\"", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Initialize the script, setting up default values, and prepping the CLI params.
[ "Initialize", "the", "script", "setting", "up", "default", "values", "and", "prepping", "the", "CLI", "params", "." ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/bin/gen-edgerc.js#L35-L64
train
akamai/akamai-gen-edgerc
bin/gen-edgerc.js
getClientAuth
function getClientAuth(callback) { console.log("This script will create a section named '" + args.section + "'" + "in the local file " + args.path + ".\n"); // Read the client authorization file. If not found, notify user. if (args.file) { clientAuthData = fs.readFileSync(args.file, 'utf8'); console.log("+++ Found authorization file: " + args.file); callback(clientAuthData); } else { // Present user with input dialogue requesting copy and paste of // client auth data. var input = []; var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var msg = "After authorizing your client in the OPEN API Administration " + "tool, \nexport the credentials and paste the contents of the export file " + "below (making sure to include the final blank line). \nThen enter " + "control-D to continue: \n\n>>>\n"; rl.setPrompt(msg); rl.prompt(); rl.on('line', function(cmd) { input.push(cmd); }); rl.on('close', function(cmd) { if (input.length < 1) { // Data was not input, assumed early exit from the program. console.log("Kill command received without input. Exiting program."); process.exit(0); } console.log("\n<<<\n\n"); clientAuthData = input.join('\n'); callback(clientAuthData); }); } }
javascript
function getClientAuth(callback) { console.log("This script will create a section named '" + args.section + "'" + "in the local file " + args.path + ".\n"); // Read the client authorization file. If not found, notify user. if (args.file) { clientAuthData = fs.readFileSync(args.file, 'utf8'); console.log("+++ Found authorization file: " + args.file); callback(clientAuthData); } else { // Present user with input dialogue requesting copy and paste of // client auth data. var input = []; var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); var msg = "After authorizing your client in the OPEN API Administration " + "tool, \nexport the credentials and paste the contents of the export file " + "below (making sure to include the final blank line). \nThen enter " + "control-D to continue: \n\n>>>\n"; rl.setPrompt(msg); rl.prompt(); rl.on('line', function(cmd) { input.push(cmd); }); rl.on('close', function(cmd) { if (input.length < 1) { // Data was not input, assumed early exit from the program. console.log("Kill command received without input. Exiting program."); process.exit(0); } console.log("\n<<<\n\n"); clientAuthData = input.join('\n'); callback(clientAuthData); }); } }
[ "function", "getClientAuth", "(", "callback", ")", "{", "console", ".", "log", "(", "\"This script will create a section named '\"", "+", "args", ".", "section", "+", "\"'\"", "+", "\"in the local file \"", "+", "args", ".", "path", "+", "\".\\n\"", ")", ";", "\\n", "}" ]
Gets the client authorization data by either reading the file path passed in by the user or requesting the user to copy and paste the data directly into the command line. @param {Function} callback Callback function accepting a data param which will be called once the data is ready.
[ "Gets", "the", "client", "authorization", "data", "by", "either", "reading", "the", "file", "path", "passed", "in", "by", "the", "user", "or", "requesting", "the", "user", "to", "copy", "and", "paste", "the", "data", "directly", "into", "the", "command", "line", "." ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/bin/gen-edgerc.js#L76-L118
train
akamai/akamai-gen-edgerc
bin/gen-edgerc.js
parseClientAuth
function parseClientAuth(data, callback) { authParser.parseAuth(data, function(err, data) { if (err) callback(err, null); callback(null, data); }); }
javascript
function parseClientAuth(data, callback) { authParser.parseAuth(data, function(err, data) { if (err) callback(err, null); callback(null, data); }); }
[ "function", "parseClientAuth", "(", "data", ",", "callback", ")", "{", "authParser", ".", "parseAuth", "(", "data", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "callback", "(", "err", ",", "null", ")", ";", "callback", "(", "null", ",", "data", ")", ";", "}", ")", ";", "}" ]
Parses the client authorization file. @param {String} data Parsed array of client authorization data @param {Function} callback Callback function accepting an error parameter
[ "Parses", "the", "client", "authorization", "file", "." ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/bin/gen-edgerc.js#L126-L131
train
akamai/akamai-gen-edgerc
bin/gen-edgerc.js
writeEdgerc
function writeEdgerc(data, callback) { try { edgercWriter.writeEdgercSection( args.path, args.section, data["URL:"], data["Secret:"], data["Tokens:"], data["token:"], data["max-body"] ); } catch (err) { callback(err); } return callback(); }
javascript
function writeEdgerc(data, callback) { try { edgercWriter.writeEdgercSection( args.path, args.section, data["URL:"], data["Secret:"], data["Tokens:"], data["token:"], data["max-body"] ); } catch (err) { callback(err); } return callback(); }
[ "function", "writeEdgerc", "(", "data", ",", "callback", ")", "{", "try", "{", "edgercWriter", ".", "writeEdgercSection", "(", "args", ".", "path", ",", "args", ".", "section", ",", "data", "[", "\"URL:\"", "]", ",", "data", "[", "\"Secret:\"", "]", ",", "data", "[", "\"Tokens:\"", "]", ",", "data", "[", "\"token:\"", "]", ",", "data", "[", "\"max-body\"", "]", ")", ";", "}", "catch", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", "return", "callback", "(", ")", ";", "}" ]
Writes the parsed client auth data to the .edgerc file. @param {Array} data Array of parsed client auth data @param {Function} callback unction to receive errors and handle completion
[ "Writes", "the", "parsed", "client", "auth", "data", "to", "the", ".", "edgerc", "file", "." ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/bin/gen-edgerc.js#L139-L155
train
shannonmoeller/handlebars-group-by
index.js
groupBy
function groupBy(handlebars) { var helpers = { /** * @method group * @param {Array} list * @param {Object} options * @param {Object} options.hash * @param {String} options.hash.by * @return {String} Rendered partial. */ group: function (list, options) { options = options || {}; var fn = options.fn || noop, inverse = options.inverse || noop, hash = options.hash, prop = hash && hash.by, keys = [], groups = {}; if (!prop || !list || !list.length) { return inverse(this); } function groupKey(item) { var key = get(item, prop); if (keys.indexOf(key) === -1) { keys.push(key); } if (!groups[key]) { groups[key] = { value: key, items: [] }; } groups[key].items.push(item); } function renderGroup(buffer, key) { return buffer + fn(groups[key]); } list.forEach(groupKey); return keys.reduce(renderGroup, ''); } }; handlebars.registerHelper(helpers); return handlebars; }
javascript
function groupBy(handlebars) { var helpers = { /** * @method group * @param {Array} list * @param {Object} options * @param {Object} options.hash * @param {String} options.hash.by * @return {String} Rendered partial. */ group: function (list, options) { options = options || {}; var fn = options.fn || noop, inverse = options.inverse || noop, hash = options.hash, prop = hash && hash.by, keys = [], groups = {}; if (!prop || !list || !list.length) { return inverse(this); } function groupKey(item) { var key = get(item, prop); if (keys.indexOf(key) === -1) { keys.push(key); } if (!groups[key]) { groups[key] = { value: key, items: [] }; } groups[key].items.push(item); } function renderGroup(buffer, key) { return buffer + fn(groups[key]); } list.forEach(groupKey); return keys.reduce(renderGroup, ''); } }; handlebars.registerHelper(helpers); return handlebars; }
[ "function", "groupBy", "(", "handlebars", ")", "{", "var", "helpers", "=", "{", "group", ":", "function", "(", "list", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "fn", "=", "options", ".", "fn", "||", "noop", ",", "inverse", "=", "options", ".", "inverse", "||", "noop", ",", "hash", "=", "options", ".", "hash", ",", "prop", "=", "hash", "&&", "hash", ".", "by", ",", "keys", "=", "[", "]", ",", "groups", "=", "{", "}", ";", "if", "(", "!", "prop", "||", "!", "list", "||", "!", "list", ".", "length", ")", "{", "return", "inverse", "(", "this", ")", ";", "}", "function", "groupKey", "(", "item", ")", "{", "var", "key", "=", "get", "(", "item", ",", "prop", ")", ";", "if", "(", "keys", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "keys", ".", "push", "(", "key", ")", ";", "}", "if", "(", "!", "groups", "[", "key", "]", ")", "{", "groups", "[", "key", "]", "=", "{", "value", ":", "key", ",", "items", ":", "[", "]", "}", ";", "}", "groups", "[", "key", "]", ".", "items", ".", "push", "(", "item", ")", ";", "}", "function", "renderGroup", "(", "buffer", ",", "key", ")", "{", "return", "buffer", "+", "fn", "(", "groups", "[", "key", "]", ")", ";", "}", "list", ".", "forEach", "(", "groupKey", ")", ";", "return", "keys", ".", "reduce", "(", "renderGroup", ",", "''", ")", ";", "}", "}", ";", "handlebars", ".", "registerHelper", "(", "helpers", ")", ";", "return", "handlebars", ";", "}" ]
Registers a group helper on an instance of Handlebars. @type {Function} @param {Object} handlebars Handlebars instance. @return {Object} Handlebars instance.
[ "Registers", "a", "group", "helper", "on", "an", "instance", "of", "Handlebars", "." ]
bd3e48f787ea253b8beaec6145b9151b326bcb32
https://github.com/shannonmoeller/handlebars-group-by/blob/bd3e48f787ea253b8beaec6145b9151b326bcb32/index.js#L29-L83
train
goto-bus-stop/browser-pack-flat
index.js
markDuplicateVariableNames
function markDuplicateVariableNames (row, i, rows) { var ast = row[kAst] var scope = scan.scope(ast) if (scope) { scope.forEach(function (binding, name) { binding[kShouldRename] = rows.usedGlobalVariables.has(name) rows.usedGlobalVariables.add(name) }) } }
javascript
function markDuplicateVariableNames (row, i, rows) { var ast = row[kAst] var scope = scan.scope(ast) if (scope) { scope.forEach(function (binding, name) { binding[kShouldRename] = rows.usedGlobalVariables.has(name) rows.usedGlobalVariables.add(name) }) } }
[ "function", "markDuplicateVariableNames", "(", "row", ",", "i", ",", "rows", ")", "{", "var", "ast", "=", "row", "[", "kAst", "]", "var", "scope", "=", "scan", ".", "scope", "(", "ast", ")", "if", "(", "scope", ")", "{", "scope", ".", "forEach", "(", "function", "(", "binding", ",", "name", ")", "{", "binding", "[", "kShouldRename", "]", "=", "rows", ".", "usedGlobalVariables", ".", "has", "(", "name", ")", "rows", ".", "usedGlobalVariables", ".", "add", "(", "name", ")", "}", ")", "}", "}" ]
Mark module variables that collide with variable names from other modules so we can rewrite them.
[ "Mark", "module", "variables", "that", "collide", "with", "variable", "names", "from", "other", "modules", "so", "we", "can", "rewrite", "them", "." ]
c12e407a027a0a07c6d750781125317d6a166327
https://github.com/goto-bus-stop/browser-pack-flat/blob/c12e407a027a0a07c6d750781125317d6a166327/index.js#L295-L305
train
goto-bus-stop/browser-pack-flat
index.js
detectCycles
function detectCycles (rows) { var cyclicalModules = new Set() var checked = new Set() rows.forEach(function (module) { var visited = [] check(module) function check (row) { var i = visited.indexOf(row) if (i !== -1) { checked.add(row) for (; i < visited.length; i++) { cyclicalModules.add(visited[i]) } return } if (checked.has(row)) return visited.push(row) Object.keys(row.deps).forEach(function (k) { var dep = row.deps[k] var other = rows.byId[dep] if (other) check(other, visited) }) visited.pop() } }) // mark cyclical dependencies for (var i = 0; i < rows.length; i++) { rows[i][kEvaluateOnDemand] = cyclicalModules.has(rows[i]) } return cyclicalModules.size > 0 }
javascript
function detectCycles (rows) { var cyclicalModules = new Set() var checked = new Set() rows.forEach(function (module) { var visited = [] check(module) function check (row) { var i = visited.indexOf(row) if (i !== -1) { checked.add(row) for (; i < visited.length; i++) { cyclicalModules.add(visited[i]) } return } if (checked.has(row)) return visited.push(row) Object.keys(row.deps).forEach(function (k) { var dep = row.deps[k] var other = rows.byId[dep] if (other) check(other, visited) }) visited.pop() } }) // mark cyclical dependencies for (var i = 0; i < rows.length; i++) { rows[i][kEvaluateOnDemand] = cyclicalModules.has(rows[i]) } return cyclicalModules.size > 0 }
[ "function", "detectCycles", "(", "rows", ")", "{", "var", "cyclicalModules", "=", "new", "Set", "(", ")", "var", "checked", "=", "new", "Set", "(", ")", "rows", ".", "forEach", "(", "function", "(", "module", ")", "{", "var", "visited", "=", "[", "]", "check", "(", "module", ")", "function", "check", "(", "row", ")", "{", "var", "i", "=", "visited", ".", "indexOf", "(", "row", ")", "if", "(", "i", "!==", "-", "1", ")", "{", "checked", ".", "add", "(", "row", ")", "for", "(", ";", "i", "<", "visited", ".", "length", ";", "i", "++", ")", "{", "cyclicalModules", ".", "add", "(", "visited", "[", "i", "]", ")", "}", "return", "}", "if", "(", "checked", ".", "has", "(", "row", ")", ")", "return", "visited", ".", "push", "(", "row", ")", "Object", ".", "keys", "(", "row", ".", "deps", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "var", "dep", "=", "row", ".", "deps", "[", "k", "]", "var", "other", "=", "rows", ".", "byId", "[", "dep", "]", "if", "(", "other", ")", "check", "(", "other", ",", "visited", ")", "}", ")", "visited", ".", "pop", "(", ")", "}", "}", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "i", "++", ")", "{", "rows", "[", "i", "]", "[", "kEvaluateOnDemand", "]", "=", "cyclicalModules", ".", "has", "(", "rows", "[", "i", "]", ")", "}", "return", "cyclicalModules", ".", "size", ">", "0", "}" ]
Detect cyclical dependencies in the bundle. All modules in a dependency cycle are moved to the top of the bundle and wrapped in functions so they're not evaluated immediately. When other modules need a module that's in a dependency cycle, instead of using the module's exportName, it'll call the `createModuleFactory` runtime function, which will execute the requested module and return its exports.
[ "Detect", "cyclical", "dependencies", "in", "the", "bundle", ".", "All", "modules", "in", "a", "dependency", "cycle", "are", "moved", "to", "the", "top", "of", "the", "bundle", "and", "wrapped", "in", "functions", "so", "they", "re", "not", "evaluated", "immediately", ".", "When", "other", "modules", "need", "a", "module", "that", "s", "in", "a", "dependency", "cycle", "instead", "of", "using", "the", "module", "s", "exportName", "it", "ll", "call", "the", "createModuleFactory", "runtime", "function", "which", "will", "execute", "the", "requested", "module", "and", "return", "its", "exports", "." ]
c12e407a027a0a07c6d750781125317d6a166327
https://github.com/goto-bus-stop/browser-pack-flat/blob/c12e407a027a0a07c6d750781125317d6a166327/index.js#L567-L600
train
akamai/akamai-gen-edgerc
src/edgerc-writer.js
createSectionObj
function createSectionObj( host, secret, accessToken, clientToken, maxBody) { var section = {}; section.client_secret = secret; section.host = host; section.access_token = accessToken; section.client_token = clientToken; section["max-body"] = maxBody ? maxBody : "131072"; return section; }
javascript
function createSectionObj( host, secret, accessToken, clientToken, maxBody) { var section = {}; section.client_secret = secret; section.host = host; section.access_token = accessToken; section.client_token = clientToken; section["max-body"] = maxBody ? maxBody : "131072"; return section; }
[ "function", "createSectionObj", "(", "host", ",", "secret", ",", "accessToken", ",", "clientToken", ",", "maxBody", ")", "{", "var", "section", "=", "{", "}", ";", "section", ".", "client_secret", "=", "secret", ";", "section", ".", "host", "=", "host", ";", "section", ".", "access_token", "=", "accessToken", ";", "section", ".", "client_token", "=", "clientToken", ";", "section", "[", "\"max-body\"", "]", "=", "maxBody", "?", "maxBody", ":", "\"131072\"", ";", "return", "section", ";", "}" ]
Creates a properly formatted .edgerc section Object @param {String} section The section title @param {String} host The host value @param {String} secret The secret value @param {String} accessToken The access token value @param {String} clientToken The client token value @param {String} max-body The max body value @return {String} A properly formatted section block Object
[ "Creates", "a", "properly", "formatted", ".", "edgerc", "section", "Object" ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/src/edgerc-writer.js#L94-L108
train
nknapp/html5-media-converter
src/VideoConverter.js
VideoConverter
function VideoConverter(options) { var _this = this; this.name = function() { return options.name; }; this.extName = function () { return options.ext; }; /** * Generate a stream from the video converter * @param size * @returns {*} */ this.toStream = function (size) { var factory = ps.factory(false, !options.streamEncoding, function (input, output, callback) { var stream = this; var ffm = _this.convert(input, size, output, callback); ['start','progress','error'].forEach(function(event) { ffm.on(event, function() { stream.emit.apply(stream,[event].concat(arguments)); }); }); }); factory.videoConverter = this; return factory; }; this.convert = function (input, size, output, callback) { var ffm = ffmpeg(input).outputOptions(options.args); ffm.on('start', function(commandLine) { console.log('Spawned Ffmpeg with command: ' + commandLine); }); if (size) { var match = size.match(/(\d+)x(\d+)/); if (match) { ffm.addOutputOptions("-vf", scale(match[1], match[2])); } else { throw new Error("Illegal size specification: "+size); } } ffm.output(output); ffm.on("error", function (error, stdout, stderr) { error.stderr = stderr; callback(error); }); ffm.run(); if (typeof(output) === "string") { // If 'output' is a file, the callback must be called after ffmpeg has finished (only then is the file ready) ffm.on("end", function () { callback(); }); } else { callback(); } return ffm; } }
javascript
function VideoConverter(options) { var _this = this; this.name = function() { return options.name; }; this.extName = function () { return options.ext; }; /** * Generate a stream from the video converter * @param size * @returns {*} */ this.toStream = function (size) { var factory = ps.factory(false, !options.streamEncoding, function (input, output, callback) { var stream = this; var ffm = _this.convert(input, size, output, callback); ['start','progress','error'].forEach(function(event) { ffm.on(event, function() { stream.emit.apply(stream,[event].concat(arguments)); }); }); }); factory.videoConverter = this; return factory; }; this.convert = function (input, size, output, callback) { var ffm = ffmpeg(input).outputOptions(options.args); ffm.on('start', function(commandLine) { console.log('Spawned Ffmpeg with command: ' + commandLine); }); if (size) { var match = size.match(/(\d+)x(\d+)/); if (match) { ffm.addOutputOptions("-vf", scale(match[1], match[2])); } else { throw new Error("Illegal size specification: "+size); } } ffm.output(output); ffm.on("error", function (error, stdout, stderr) { error.stderr = stderr; callback(error); }); ffm.run(); if (typeof(output) === "string") { // If 'output' is a file, the callback must be called after ffmpeg has finished (only then is the file ready) ffm.on("end", function () { callback(); }); } else { callback(); } return ffm; } }
[ "function", "VideoConverter", "(", "options", ")", "{", "var", "_this", "=", "this", ";", "this", ".", "name", "=", "function", "(", ")", "{", "return", "options", ".", "name", ";", "}", ";", "this", ".", "extName", "=", "function", "(", ")", "{", "return", "options", ".", "ext", ";", "}", ";", "this", ".", "toStream", "=", "function", "(", "size", ")", "{", "var", "factory", "=", "ps", ".", "factory", "(", "false", ",", "!", "options", ".", "streamEncoding", ",", "function", "(", "input", ",", "output", ",", "callback", ")", "{", "var", "stream", "=", "this", ";", "var", "ffm", "=", "_this", ".", "convert", "(", "input", ",", "size", ",", "output", ",", "callback", ")", ";", "[", "'start'", ",", "'progress'", ",", "'error'", "]", ".", "forEach", "(", "function", "(", "event", ")", "{", "ffm", ".", "on", "(", "event", ",", "function", "(", ")", "{", "stream", ".", "emit", ".", "apply", "(", "stream", ",", "[", "event", "]", ".", "concat", "(", "arguments", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "factory", ".", "videoConverter", "=", "this", ";", "return", "factory", ";", "}", ";", "this", ".", "convert", "=", "function", "(", "input", ",", "size", ",", "output", ",", "callback", ")", "{", "var", "ffm", "=", "ffmpeg", "(", "input", ")", ".", "outputOptions", "(", "options", ".", "args", ")", ";", "ffm", ".", "on", "(", "'start'", ",", "function", "(", "commandLine", ")", "{", "console", ".", "log", "(", "'Spawned Ffmpeg with command: '", "+", "commandLine", ")", ";", "}", ")", ";", "if", "(", "size", ")", "{", "var", "match", "=", "size", ".", "match", "(", "/", "(\\d+)x(\\d+)", "/", ")", ";", "if", "(", "match", ")", "{", "ffm", ".", "addOutputOptions", "(", "\"-vf\"", ",", "scale", "(", "match", "[", "1", "]", ",", "match", "[", "2", "]", ")", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Illegal size specification: \"", "+", "size", ")", ";", "}", "}", "ffm", ".", "output", "(", "output", ")", ";", "ffm", ".", "on", "(", "\"error\"", ",", "function", "(", "error", ",", "stdout", ",", "stderr", ")", "{", "error", ".", "stderr", "=", "stderr", ";", "callback", "(", "error", ")", ";", "}", ")", ";", "ffm", ".", "run", "(", ")", ";", "if", "(", "typeof", "(", "output", ")", "===", "\"string\"", ")", "{", "ffm", ".", "on", "(", "\"end\"", ",", "function", "(", ")", "{", "callback", "(", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "return", "ffm", ";", "}", "}" ]
Creates a new @param options.streamEncoding {Boolean} @param options.args {Array.<String>} @param options.ext {String} @param options.name {String} a name for the converter @constructor
[ "Creates", "a", "new" ]
1411ac7dd2102facfaa0d08f9b9e2f0718d12690
https://github.com/nknapp/html5-media-converter/blob/1411ac7dd2102facfaa0d08f9b9e2f0718d12690/src/VideoConverter.js#L13-L73
train
parro-it/libui-napi
index.js
initAsyncResource
function initAsyncResource(asyncId, type, triggerAsyncId, resource) { if (wakingup) { return; } wakingup = true; setImmediate(() => { EventLoop.wakeupBackgroundThread(); wakingup = false; }); }
javascript
function initAsyncResource(asyncId, type, triggerAsyncId, resource) { if (wakingup) { return; } wakingup = true; setImmediate(() => { EventLoop.wakeupBackgroundThread(); wakingup = false; }); }
[ "function", "initAsyncResource", "(", "asyncId", ",", "type", ",", "triggerAsyncId", ",", "resource", ")", "{", "if", "(", "wakingup", ")", "{", "return", ";", "}", "wakingup", "=", "true", ";", "setImmediate", "(", "(", ")", "=>", "{", "EventLoop", ".", "wakeupBackgroundThread", "(", ")", ";", "wakingup", "=", "false", ";", "}", ")", ";", "}" ]
This is called when a new async handle is created. It's used to signal the background thread to stop awaiting calls and upgrade it's list of handles it's awaiting for.
[ "This", "is", "called", "when", "a", "new", "async", "handle", "is", "created", ".", "It", "s", "used", "to", "signal", "the", "background", "thread", "to", "stop", "awaiting", "calls", "and", "upgrade", "it", "s", "list", "of", "handles", "it", "s", "awaiting", "for", "." ]
5e32314516a163bc91da36cb709382cbc656e56f
https://github.com/parro-it/libui-napi/blob/5e32314516a163bc91da36cb709382cbc656e56f/index.js#L268-L277
train
NiklasGollenstede/native-ext
extension/common/exe-url.js
getUrl
function getUrl(version = current) { const name = `native-ext-v${version}-${os}-${arch}.${ext}`; return `https://github.com/NiklasGollenstede/native-ext/releases/download/v${version}/`+ name; }
javascript
function getUrl(version = current) { const name = `native-ext-v${version}-${os}-${arch}.${ext}`; return `https://github.com/NiklasGollenstede/native-ext/releases/download/v${version}/`+ name; }
[ "function", "getUrl", "(", "version", "=", "current", ")", "{", "const", "name", "=", "`", "${", "version", "}", "${", "os", "}", "${", "arch", "}", "${", "ext", "}", "`", ";", "return", "`", "${", "version", "}", "`", "+", "name", ";", "}" ]
no support for other OSs or ARM
[ "no", "support", "for", "other", "OSs", "or", "ARM" ]
c353d551d5890343faa9e89309a6fcf7fbdd5569
https://github.com/NiklasGollenstede/native-ext/blob/c353d551d5890343faa9e89309a6fcf7fbdd5569/extension/common/exe-url.js#L11-L14
train
dawsbot/satoshi-bitcoin
index.js
function(satoshi) { //validate arg var satoshiType = typeof satoshi; if (satoshiType === 'string') { satoshi = toNumber(satoshi); satoshiType = 'number'; } if (satoshiType !== 'number'){ throw new TypeError('toBitcoin must be called on a number or string, got ' + satoshiType); } if (!Number.isInteger(satoshi)) { throw new TypeError('toBitcoin must be called on a whole number or string format whole number'); } var bigSatoshi = new Big(satoshi); return Number(bigSatoshi.div(conversion)); }
javascript
function(satoshi) { //validate arg var satoshiType = typeof satoshi; if (satoshiType === 'string') { satoshi = toNumber(satoshi); satoshiType = 'number'; } if (satoshiType !== 'number'){ throw new TypeError('toBitcoin must be called on a number or string, got ' + satoshiType); } if (!Number.isInteger(satoshi)) { throw new TypeError('toBitcoin must be called on a whole number or string format whole number'); } var bigSatoshi = new Big(satoshi); return Number(bigSatoshi.div(conversion)); }
[ "function", "(", "satoshi", ")", "{", "var", "satoshiType", "=", "typeof", "satoshi", ";", "if", "(", "satoshiType", "===", "'string'", ")", "{", "satoshi", "=", "toNumber", "(", "satoshi", ")", ";", "satoshiType", "=", "'number'", ";", "}", "if", "(", "satoshiType", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'toBitcoin must be called on a number or string, got '", "+", "satoshiType", ")", ";", "}", "if", "(", "!", "Number", ".", "isInteger", "(", "satoshi", ")", ")", "{", "throw", "new", "TypeError", "(", "'toBitcoin must be called on a whole number or string format whole number'", ")", ";", "}", "var", "bigSatoshi", "=", "new", "Big", "(", "satoshi", ")", ";", "return", "Number", "(", "bigSatoshi", ".", "div", "(", "conversion", ")", ")", ";", "}" ]
Convert Satoshi to Bitcoin @param {number|string} satoshi Amount of Satoshi to convert. Must be a whole number @throws {TypeError} Thrown if input is not a number or string @throws {TypeError} Thrown if input is not a whole number or string format whole number @returns {number}
[ "Convert", "Satoshi", "to", "Bitcoin" ]
bf3d74d4f58f0bc98c340f065937a786ce3cf86d
https://github.com/dawsbot/satoshi-bitcoin/blob/bf3d74d4f58f0bc98c340f065937a786ce3cf86d/index.js#L31-L47
train
dawsbot/satoshi-bitcoin
index.js
function(bitcoin) { //validate arg var bitcoinType = typeof bitcoin; if (bitcoinType === 'string') { bitcoin = toNumber(bitcoin); bitcoinType = 'number'; } if (bitcoinType !== 'number'){ throw new TypeError('toSatoshi must be called on a number or string, got ' + bitcoinType); } var bigBitcoin = new Big(bitcoin); return Number(bigBitcoin.times(conversion)); }
javascript
function(bitcoin) { //validate arg var bitcoinType = typeof bitcoin; if (bitcoinType === 'string') { bitcoin = toNumber(bitcoin); bitcoinType = 'number'; } if (bitcoinType !== 'number'){ throw new TypeError('toSatoshi must be called on a number or string, got ' + bitcoinType); } var bigBitcoin = new Big(bitcoin); return Number(bigBitcoin.times(conversion)); }
[ "function", "(", "bitcoin", ")", "{", "var", "bitcoinType", "=", "typeof", "bitcoin", ";", "if", "(", "bitcoinType", "===", "'string'", ")", "{", "bitcoin", "=", "toNumber", "(", "bitcoin", ")", ";", "bitcoinType", "=", "'number'", ";", "}", "if", "(", "bitcoinType", "!==", "'number'", ")", "{", "throw", "new", "TypeError", "(", "'toSatoshi must be called on a number or string, got '", "+", "bitcoinType", ")", ";", "}", "var", "bigBitcoin", "=", "new", "Big", "(", "bitcoin", ")", ";", "return", "Number", "(", "bigBitcoin", ".", "times", "(", "conversion", ")", ")", ";", "}" ]
Convert Bitcoin to Satoshi @param {number|string} bitcoin Amount of Bitcoin to convert @throws {TypeError} Thrown if input is not a number or string @returns {number}
[ "Convert", "Bitcoin", "to", "Satoshi" ]
bf3d74d4f58f0bc98c340f065937a786ce3cf86d
https://github.com/dawsbot/satoshi-bitcoin/blob/bf3d74d4f58f0bc98c340f065937a786ce3cf86d/index.js#L55-L68
train
akamai/akamai-gen-edgerc
src/cli-config.js
createArguments
function createArguments() { var cli = commandLineArgs([{ name: 'file', alias: 'f', type: String, defaultValue: "", description: "Full path to the credentials file.", required: true }, { name: 'section', alias: 's', type: String, defaultValue: "default", description: "Title of the section that will be added to the .edgerc file." }, { name: 'path', alias: 'p', type: String, defaultValue: os.homedir() + "/.edgerc", description: "Full path to the .edgerc file." }, { name: 'help', alias: 'h', description: "Display help and usage information." }]); return cli; }
javascript
function createArguments() { var cli = commandLineArgs([{ name: 'file', alias: 'f', type: String, defaultValue: "", description: "Full path to the credentials file.", required: true }, { name: 'section', alias: 's', type: String, defaultValue: "default", description: "Title of the section that will be added to the .edgerc file." }, { name: 'path', alias: 'p', type: String, defaultValue: os.homedir() + "/.edgerc", description: "Full path to the .edgerc file." }, { name: 'help', alias: 'h', description: "Display help and usage information." }]); return cli; }
[ "function", "createArguments", "(", ")", "{", "var", "cli", "=", "commandLineArgs", "(", "[", "{", "name", ":", "'file'", ",", "alias", ":", "'f'", ",", "type", ":", "String", ",", "defaultValue", ":", "\"\"", ",", "description", ":", "\"Full path to the credentials file.\"", ",", "required", ":", "true", "}", ",", "{", "name", ":", "'section'", ",", "alias", ":", "'s'", ",", "type", ":", "String", ",", "defaultValue", ":", "\"default\"", ",", "description", ":", "\"Title of the section that will be added to the .edgerc file.\"", "}", ",", "{", "name", ":", "'path'", ",", "alias", ":", "'p'", ",", "type", ":", "String", ",", "defaultValue", ":", "os", ".", "homedir", "(", ")", "+", "\"/.edgerc\"", ",", "description", ":", "\"Full path to the .edgerc file.\"", "}", ",", "{", "name", ":", "'help'", ",", "alias", ":", "'h'", ",", "description", ":", "\"Display help and usage information.\"", "}", "]", ")", ";", "return", "cli", ";", "}" ]
Create and return an instance of the CommandLineArgs object with the desired arguments specified.
[ "Create", "and", "return", "an", "instance", "of", "the", "CommandLineArgs", "object", "with", "the", "desired", "arguments", "specified", "." ]
12f522cc2d595a04af635a15046d0bd1ac3550b2
https://github.com/akamai/akamai-gen-edgerc/blob/12f522cc2d595a04af635a15046d0bd1ac3550b2/src/cli-config.js#L36-L63
train
Streampunk/ledger
model/Device.js
Device
function Device(id, version, label, type, node_id, senders, receivers) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * [Device type]{@link deviceTypes} URN. * @type {string} * @readonly */ this.type = this.generateType(type); /** * Globally unique UUID identifier for the {@link Node} which initially created * the Device. * @type {string} * @readonly */ this.node_id = this.generateNodeID(node_id); /** * UUIDs of [Senders]{@link Sender} attached to the Device. * @type {string[]} * @readonly */ this.senders = this.generateSenders(senders); /** * UUIDs of [Receivers]{@link Receiver} attached to the Device. * @type {string[]} * @readonly */ this.receivers = this.generateReceivers(receivers); return immutable(this, { prototype: Device.prototype }); }
javascript
function Device(id, version, label, type, node_id, senders, receivers) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * [Device type]{@link deviceTypes} URN. * @type {string} * @readonly */ this.type = this.generateType(type); /** * Globally unique UUID identifier for the {@link Node} which initially created * the Device. * @type {string} * @readonly */ this.node_id = this.generateNodeID(node_id); /** * UUIDs of [Senders]{@link Sender} attached to the Device. * @type {string[]} * @readonly */ this.senders = this.generateSenders(senders); /** * UUIDs of [Receivers]{@link Receiver} attached to the Device. * @type {string[]} * @readonly */ this.receivers = this.generateReceivers(receivers); return immutable(this, { prototype: Device.prototype }); }
[ "function", "Device", "(", "id", ",", "version", ",", "label", ",", "type", ",", "node_id", ",", "senders", ",", "receivers", ")", "{", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "this", ".", "type", "=", "this", ".", "generateType", "(", "type", ")", ";", "this", ".", "node_id", "=", "this", ".", "generateNodeID", "(", "node_id", ")", ";", "this", ".", "senders", "=", "this", ".", "generateSenders", "(", "senders", ")", ";", "this", ".", "receivers", "=", "this", ".", "generateReceivers", "(", "receivers", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Device", ".", "prototype", "}", ")", ";", "}" ]
Describes a Device. Immutable value. @constructor @augments Versionned @param {String} id Globally unique UUID identifier for the Device. @param {string} version String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;) indicating precisely when an attribute of the resource last changed. @param {string} label Freeform string label for the Device. @param {string} type [Device type]{@link deviceTypes} URN. @param {string} node_id Globally unique UUID identifier for the {@link Node} which initially created the Device. @param {string[]} senders UUIDs of {@link Senders} attached to the Device. @param {string[]} receivers UUIDs of Receivers attached to the Device
[ "Describes", "a", "Device", ".", "Immutable", "value", "." ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Device.js#L36-L66
train
DeMille/node-usbmux
lib/usbmux.js
pack
function pack(payload_obj) { var payload_plist = plist.build(payload_obj) , payload_buf = new Buffer(payload_plist); var header = { len: payload_buf.length + 16, version: 1, request: 8, tag: 1 }; var header_buf = new Buffer(16); header_buf.fill(0); header_buf.writeUInt32LE(header.len, 0); header_buf.writeUInt32LE(header.version, 4); header_buf.writeUInt32LE(header.request, 8); header_buf.writeUInt32LE(header.tag, 12); return Buffer.concat([header_buf, payload_buf]); }
javascript
function pack(payload_obj) { var payload_plist = plist.build(payload_obj) , payload_buf = new Buffer(payload_plist); var header = { len: payload_buf.length + 16, version: 1, request: 8, tag: 1 }; var header_buf = new Buffer(16); header_buf.fill(0); header_buf.writeUInt32LE(header.len, 0); header_buf.writeUInt32LE(header.version, 4); header_buf.writeUInt32LE(header.request, 8); header_buf.writeUInt32LE(header.tag, 12); return Buffer.concat([header_buf, payload_buf]); }
[ "function", "pack", "(", "payload_obj", ")", "{", "var", "payload_plist", "=", "plist", ".", "build", "(", "payload_obj", ")", ",", "payload_buf", "=", "new", "Buffer", "(", "payload_plist", ")", ";", "var", "header", "=", "{", "len", ":", "payload_buf", ".", "length", "+", "16", ",", "version", ":", "1", ",", "request", ":", "8", ",", "tag", ":", "1", "}", ";", "var", "header_buf", "=", "new", "Buffer", "(", "16", ")", ";", "header_buf", ".", "fill", "(", "0", ")", ";", "header_buf", ".", "writeUInt32LE", "(", "header", ".", "len", ",", "0", ")", ";", "header_buf", ".", "writeUInt32LE", "(", "header", ".", "version", ",", "4", ")", ";", "header_buf", ".", "writeUInt32LE", "(", "header", ".", "request", ",", "8", ")", ";", "header_buf", ".", "writeUInt32LE", "(", "header", ".", "tag", ",", "12", ")", ";", "return", "Buffer", ".", "concat", "(", "[", "header_buf", ",", "payload_buf", "]", ")", ";", "}" ]
Pack a request object into a buffer for usbmuxd @param {object} payload_obj @return {Buffer}
[ "Pack", "a", "request", "object", "into", "a", "buffer", "for", "usbmuxd" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/lib/usbmux.js#L98-L117
train
DeMille/node-usbmux
lib/usbmux.js
UsbmuxdError
function UsbmuxdError(message, number) { this.name = 'UsbmuxdError'; this.message = message; if (number) { this.number = number; this.message += ', Err #' + number; } if (number === 2) this.message += ": Device isn't connected"; if (number === 3) this.message += ": Port isn't available or open"; if (number === 5) this.message += ": Malformed request"; }
javascript
function UsbmuxdError(message, number) { this.name = 'UsbmuxdError'; this.message = message; if (number) { this.number = number; this.message += ', Err #' + number; } if (number === 2) this.message += ": Device isn't connected"; if (number === 3) this.message += ": Port isn't available or open"; if (number === 5) this.message += ": Malformed request"; }
[ "function", "UsbmuxdError", "(", "message", ",", "number", ")", "{", "this", ".", "name", "=", "'UsbmuxdError'", ";", "this", ".", "message", "=", "message", ";", "if", "(", "number", ")", "{", "this", ".", "number", "=", "number", ";", "this", ".", "message", "+=", "', Err #'", "+", "number", ";", "}", "if", "(", "number", "===", "2", ")", "this", ".", "message", "+=", "\": Device isn't connected\"", ";", "if", "(", "number", "===", "3", ")", "this", ".", "message", "+=", "\": Port isn't available or open\"", ";", "if", "(", "number", "===", "5", ")", "this", ".", "message", "+=", "\": Malformed request\"", ";", "}" ]
Custom usbmuxd error There's no documentation for usbmuxd responses, but I think I've figured out these result numbers: 0 - Success 2 - Device requested isn't connected 3 - Port requested isn't available \ open 5 - Malformed request @param {string} message - Error message @param {integer} [number] - Error number given from usbmuxd response
[ "Custom", "usbmuxd", "error" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/lib/usbmux.js#L229-L240
train
DeMille/node-usbmux
lib/usbmux.js
createListener
function createListener() { var conn = net.connect(address) , req = protocol.listen; /** * Handle complete messages from usbmuxd * @function */ var parse = protocol.makeParser(function onMsgComplete(msg) { debug.listen('Response: \n%o', msg); // first response always acknowledges / denies the request: if (msg.MessageType === 'Result' && msg.Number !== 0) { conn.emit('error', new UsbmuxdError('Listen failed', msg.Number)); conn.end(); } // subsequent responses report on connected device status: if (msg.MessageType === 'Attached') { devices[msg.Properties.SerialNumber] = msg.Properties; conn.emit('attached', msg.Properties.SerialNumber); } if (msg.MessageType === 'Detached') { // given msg.DeviceID, find matching device and remove it Object.keys(devices).forEach(function(key) { if (devices[key].DeviceID === msg.DeviceID) { conn.emit('detached', devices[key].SerialNumber); delete devices[key]; } }); } }); debug.listen('Request: \n%s', req.slice(16).toString()); conn.on('data', parse); process.nextTick(function() { conn.write(req); }); return conn; }
javascript
function createListener() { var conn = net.connect(address) , req = protocol.listen; /** * Handle complete messages from usbmuxd * @function */ var parse = protocol.makeParser(function onMsgComplete(msg) { debug.listen('Response: \n%o', msg); // first response always acknowledges / denies the request: if (msg.MessageType === 'Result' && msg.Number !== 0) { conn.emit('error', new UsbmuxdError('Listen failed', msg.Number)); conn.end(); } // subsequent responses report on connected device status: if (msg.MessageType === 'Attached') { devices[msg.Properties.SerialNumber] = msg.Properties; conn.emit('attached', msg.Properties.SerialNumber); } if (msg.MessageType === 'Detached') { // given msg.DeviceID, find matching device and remove it Object.keys(devices).forEach(function(key) { if (devices[key].DeviceID === msg.DeviceID) { conn.emit('detached', devices[key].SerialNumber); delete devices[key]; } }); } }); debug.listen('Request: \n%s', req.slice(16).toString()); conn.on('data', parse); process.nextTick(function() { conn.write(req); }); return conn; }
[ "function", "createListener", "(", ")", "{", "var", "conn", "=", "net", ".", "connect", "(", "address", ")", ",", "req", "=", "protocol", ".", "listen", ";", "var", "parse", "=", "protocol", ".", "makeParser", "(", "function", "onMsgComplete", "(", "msg", ")", "{", "debug", ".", "listen", "(", "'Response: \\n%o'", ",", "\\n", ")", ";", "msg", "if", "(", "msg", ".", "MessageType", "===", "'Result'", "&&", "msg", ".", "Number", "!==", "0", ")", "{", "conn", ".", "emit", "(", "'error'", ",", "new", "UsbmuxdError", "(", "'Listen failed'", ",", "msg", ".", "Number", ")", ")", ";", "conn", ".", "end", "(", ")", ";", "}", "if", "(", "msg", ".", "MessageType", "===", "'Attached'", ")", "{", "devices", "[", "msg", ".", "Properties", ".", "SerialNumber", "]", "=", "msg", ".", "Properties", ";", "conn", ".", "emit", "(", "'attached'", ",", "msg", ".", "Properties", ".", "SerialNumber", ")", ";", "}", "}", ")", ";", "if", "(", "msg", ".", "MessageType", "===", "'Detached'", ")", "{", "Object", ".", "keys", "(", "devices", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "devices", "[", "key", "]", ".", "DeviceID", "===", "msg", ".", "DeviceID", ")", "{", "conn", ".", "emit", "(", "'detached'", ",", "devices", "[", "key", "]", ".", "SerialNumber", ")", ";", "delete", "devices", "[", "key", "]", ";", "}", "}", ")", ";", "}", "debug", ".", "listen", "(", "'Request: \\n%s'", ",", "\\n", ")", ";", "req", ".", "slice", "(", "16", ")", ".", "toString", "(", ")", "conn", ".", "on", "(", "'data'", ",", "parse", ")", ";", "}" ]
Connects to usbmuxd and listens for ios devices This connection stays open, listening as devices are plugged/unplugged and cant be upgraded into a tcp tunnel. You have to start a second connection with connect() to actually make tunnel. @return {net.Socket} - Socket with 2 bolted on events, attached & detached: Fires when devices are plugged in or first found by the listener @event net.Socket#attached @type {string} - UDID Fires when devices are unplugged @event net.Socket#detached @type {string} - UDID @public
[ "Connects", "to", "usbmuxd", "and", "listens", "for", "ios", "devices" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/lib/usbmux.js#L264-L306
train
DeMille/node-usbmux
lib/usbmux.js
connect
function connect(deviceID, devicePort) { return Q.Promise(function(resolve, reject) { var conn = net.connect(address) , req = protocol.connect(deviceID, devicePort); /** * Handle complete messages from usbmuxd * @function */ var parse = protocol.makeParser(function onMsgComplete(msg) { debug.connect('Response: \n%o', msg); if (msg.MessageType === 'Result' && msg.Number === 0) { conn.removeListener('data', parse); resolve(conn); return; } // anything other response means it failed reject(new UsbmuxdError('Tunnel failed', msg.Number)); conn.end(); }); debug.connect('Request: \n%s', req.slice(16).toString()); conn.on('data', parse); process.nextTick(function() { conn.write(req); }); }); }
javascript
function connect(deviceID, devicePort) { return Q.Promise(function(resolve, reject) { var conn = net.connect(address) , req = protocol.connect(deviceID, devicePort); /** * Handle complete messages from usbmuxd * @function */ var parse = protocol.makeParser(function onMsgComplete(msg) { debug.connect('Response: \n%o', msg); if (msg.MessageType === 'Result' && msg.Number === 0) { conn.removeListener('data', parse); resolve(conn); return; } // anything other response means it failed reject(new UsbmuxdError('Tunnel failed', msg.Number)); conn.end(); }); debug.connect('Request: \n%s', req.slice(16).toString()); conn.on('data', parse); process.nextTick(function() { conn.write(req); }); }); }
[ "function", "connect", "(", "deviceID", ",", "devicePort", ")", "{", "return", "Q", ".", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "conn", "=", "net", ".", "connect", "(", "address", ")", ",", "req", "=", "protocol", ".", "connect", "(", "deviceID", ",", "devicePort", ")", ";", "var", "parse", "=", "protocol", ".", "makeParser", "(", "function", "onMsgComplete", "(", "msg", ")", "{", "debug", ".", "connect", "(", "'Response: \\n%o'", ",", "\\n", ")", ";", "msg", "if", "(", "msg", ".", "MessageType", "===", "'Result'", "&&", "msg", ".", "Number", "===", "0", ")", "{", "conn", ".", "removeListener", "(", "'data'", ",", "parse", ")", ";", "resolve", "(", "conn", ")", ";", "return", ";", "}", "reject", "(", "new", "UsbmuxdError", "(", "'Tunnel failed'", ",", "msg", ".", "Number", ")", ")", ";", "}", ")", ";", "conn", ".", "end", "(", ")", ";", "debug", ".", "connect", "(", "'Request: \\n%s'", ",", "\\n", ")", ";", "req", ".", "slice", "(", "16", ")", ".", "toString", "(", ")", "}", ")", ";", "}" ]
Connects to a device through usbmuxd for a tunneled tcp connection @param {string} deviceID - Target device's usbmuxd ID @param {integer} devicePort - Port on ios device to connect to @return {Q.promise} - resolves {net.Socket} - Tunneled tcp connection to device - rejects {Error}
[ "Connects", "to", "a", "device", "through", "usbmuxd", "for", "a", "tunneled", "tcp", "connection" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/lib/usbmux.js#L318-L348
train
DeMille/node-usbmux
lib/usbmux.js
Relay
function Relay(devicePort, relayPort, opts) { if (!(this instanceof Relay)) return new Relay(arguments); this._devicePort = devicePort; this._relayPort = relayPort; opts = opts || {}; this._udid = opts.udid; this._startListener(opts.timeout); this._startServer(); }
javascript
function Relay(devicePort, relayPort, opts) { if (!(this instanceof Relay)) return new Relay(arguments); this._devicePort = devicePort; this._relayPort = relayPort; opts = opts || {}; this._udid = opts.udid; this._startListener(opts.timeout); this._startServer(); }
[ "function", "Relay", "(", "devicePort", ",", "relayPort", ",", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Relay", ")", ")", "return", "new", "Relay", "(", "arguments", ")", ";", "this", ".", "_devicePort", "=", "devicePort", ";", "this", ".", "_relayPort", "=", "relayPort", ";", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "_udid", "=", "opts", ".", "udid", ";", "this", ".", "_startListener", "(", "opts", ".", "timeout", ")", ";", "this", ".", "_startServer", "(", ")", ";", "}" ]
Creates a new tcp relay to a port on connected usb device @constructor @param {integer} devicePort - Port to connect to on device @param {integer} relayPort - Local port that will listen as relay @param {object} [opts] - Options @param {integer} [opts.timeout=1000] - Search time (ms) before warning @param {string} [opts.udid] - UDID of specific device to connect to @public
[ "Creates", "a", "new", "tcp", "relay", "to", "a", "port", "on", "connected", "usb", "device" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/lib/usbmux.js#L363-L374
train
layerhq/web-xdk
src/ui/adapters/angular.js
initAngular
function initAngular(angular) { // Define the layerXDKController const controllers = angular.module('layerXDKControllers', []); // Setup the properties for the given widget that is being generated function setupProps(scope, elem, attrs, props) { /* * For each property we are going to do the following: * * 1. See if there is an initial value * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value * 3. $observe() for any changes in the property * 4. $watch() for any changes in the output of scope.$eval() * * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE * this code triggers and corrects those values. This can cause errors. * * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER * its been evaluated. * * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-` * works better. * * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files. */ props.forEach((prop) => { const ngPropertyName = prop.propertyName.indexOf('on') === 0 ? 'ng' + prop.propertyName.substring(2) : 'ng' + prop.propertyName.substring(0, 1).toUpperCase() + prop.propertyName.substring(1); // Observe for changes to the attribute value and apply them to the property value attrs.$observe(prop.propertyName, (value) => { if (elem.properties) { elem[prop.propertyName] = value; } else { if (!elem.properties) elem.properties = {}; elem.properties[prop.propertyName] = value; } }); // Observe for changes to the attribute value prefixed with "ng-" and watch the scoped expression for changes // that need to be applied to the property value. attrs.$observe(ngPropertyName, (expression) => { scope.$watch(expression, (value) => { if (!elem.properties) elem.properties = {}; if (elem.properties._internalState && !elem.properties._internalState.disableSetters) { elem[prop.propertyName] = value; } else { elem.properties[prop.propertyName] = value; } }); }); }); } // Gather all UI Components Object.keys(ComponentsHash) .forEach((componentName) => { const component = ComponentsHash[componentName]; // Get the camel case controller name const controllerName = componentName.replace(/-(.)/g, (str, value) => value.toUpperCase()); controllers.directive(controllerName, () => ({ restrict: 'E', link: (scope, elem, attrs) => { const functionProps = component.properties; setupProps(scope, elem[0], attrs, functionProps); }, })); }); }
javascript
function initAngular(angular) { // Define the layerXDKController const controllers = angular.module('layerXDKControllers', []); // Setup the properties for the given widget that is being generated function setupProps(scope, elem, attrs, props) { /* * For each property we are going to do the following: * * 1. See if there is an initial value * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value * 3. $observe() for any changes in the property * 4. $watch() for any changes in the output of scope.$eval() * * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE * this code triggers and corrects those values. This can cause errors. * * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER * its been evaluated. * * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-` * works better. * * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files. */ props.forEach((prop) => { const ngPropertyName = prop.propertyName.indexOf('on') === 0 ? 'ng' + prop.propertyName.substring(2) : 'ng' + prop.propertyName.substring(0, 1).toUpperCase() + prop.propertyName.substring(1); // Observe for changes to the attribute value and apply them to the property value attrs.$observe(prop.propertyName, (value) => { if (elem.properties) { elem[prop.propertyName] = value; } else { if (!elem.properties) elem.properties = {}; elem.properties[prop.propertyName] = value; } }); // Observe for changes to the attribute value prefixed with "ng-" and watch the scoped expression for changes // that need to be applied to the property value. attrs.$observe(ngPropertyName, (expression) => { scope.$watch(expression, (value) => { if (!elem.properties) elem.properties = {}; if (elem.properties._internalState && !elem.properties._internalState.disableSetters) { elem[prop.propertyName] = value; } else { elem.properties[prop.propertyName] = value; } }); }); }); } // Gather all UI Components Object.keys(ComponentsHash) .forEach((componentName) => { const component = ComponentsHash[componentName]; // Get the camel case controller name const controllerName = componentName.replace(/-(.)/g, (str, value) => value.toUpperCase()); controllers.directive(controllerName, () => ({ restrict: 'E', link: (scope, elem, attrs) => { const functionProps = component.properties; setupProps(scope, elem[0], attrs, functionProps); }, })); }); }
[ "function", "initAngular", "(", "angular", ")", "{", "const", "controllers", "=", "angular", ".", "module", "(", "'layerXDKControllers'", ",", "[", "]", ")", ";", "function", "setupProps", "(", "scope", ",", "elem", ",", "attrs", ",", "props", ")", "{", "props", ".", "forEach", "(", "(", "prop", ")", "=>", "{", "const", "ngPropertyName", "=", "prop", ".", "propertyName", ".", "indexOf", "(", "'on'", ")", "===", "0", "?", "'ng'", "+", "prop", ".", "propertyName", ".", "substring", "(", "2", ")", ":", "'ng'", "+", "prop", ".", "propertyName", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "prop", ".", "propertyName", ".", "substring", "(", "1", ")", ";", "attrs", ".", "$observe", "(", "prop", ".", "propertyName", ",", "(", "value", ")", "=>", "{", "if", "(", "elem", ".", "properties", ")", "{", "elem", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "else", "{", "if", "(", "!", "elem", ".", "properties", ")", "elem", ".", "properties", "=", "{", "}", ";", "elem", ".", "properties", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "}", ")", ";", "attrs", ".", "$observe", "(", "ngPropertyName", ",", "(", "expression", ")", "=>", "{", "scope", ".", "$watch", "(", "expression", ",", "(", "value", ")", "=>", "{", "if", "(", "!", "elem", ".", "properties", ")", "elem", ".", "properties", "=", "{", "}", ";", "if", "(", "elem", ".", "properties", ".", "_internalState", "&&", "!", "elem", ".", "properties", ".", "_internalState", ".", "disableSetters", ")", "{", "elem", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "else", "{", "elem", ".", "properties", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "Object", ".", "keys", "(", "ComponentsHash", ")", ".", "forEach", "(", "(", "componentName", ")", "=>", "{", "const", "component", "=", "ComponentsHash", "[", "componentName", "]", ";", "const", "controllerName", "=", "componentName", ".", "replace", "(", "/", "-(.)", "/", "g", ",", "(", "str", ",", "value", ")", "=>", "value", ".", "toUpperCase", "(", ")", ")", ";", "controllers", ".", "directive", "(", "controllerName", ",", "(", ")", "=>", "(", "{", "restrict", ":", "'E'", ",", "link", ":", "(", "scope", ",", "elem", ",", "attrs", ")", "=>", "{", "const", "functionProps", "=", "component", ".", "properties", ";", "setupProps", "(", "scope", ",", "elem", "[", "0", "]", ",", "attrs", ",", "functionProps", ")", ";", "}", ",", "}", ")", ")", ";", "}", ")", ";", "}" ]
Call this function to initialize all of the angular 1.x directives needed to handle the Layer UI for Web widgets. When passing scope values/function into widget properties, prefix the property with `ng-`; for functions, replace `on-` with `ng-`. If passing in a literal, do NOT prefix with `ng-`: ``` <layer-notifier notify-in-foreground="toast"></layer-notifier> <layer-conversation-view ng-query="myscopeProp.query"></layer-conversation-view> <layer-conversation-list ng-conversation-selected="myscope.handleSelectionFunc"></layer-conversation-list> <layer-send-button></layer-send-button> <layer-file-upload-button></layer-file-upload-button> ``` Call this function to initialize angular 1.x Directives which will be part of the "layerXDKControllers" controller: ``` import '@layerhq/web-xdk/ui/adapters/angular'; Layer.UI.adapters.angular(angular); // Creates the layerXDKControllers controller angular.module('MyApp', ['layerXDKControllers']); ``` Now you can put `<layer-conversation-view>` and other widgets into angular templates and expect them to work. Prefix ALL property names with `ng-` to insure that scope is evaluated prior to passing the value on to the webcomponent. ### Bindings Bindings should work... except when put within Replaceable Content; the following will *not* work: ``` <layer-conversation-view> <div layer-replaceable-name="composerButtonPanelRight"> <div>{{displayName}}</div> <layer-send-button></layer-send-button> <layer-file-upload-button></layer-file-upload-button> </div> </layer-conversation-view> ``` The above code correctly inserts the send button and upload button, but will not lookup `displayName` in your scope. Note that the above technique of using `layer-replaceable-name` only works for non-repeating content; to customize nodes that repeat, you will need to use a callback function, best accomplished using: ```javascript document.getElementById('my-layer-conversation-view').replaceableContent = { conversationRowRightSide: function(widget) { return domNodeOrInnerHTML; } }; ``` ### Importing Not included with the standard build. To import: ``` import '@layerhq/web-xdk/ui/adapters/angular'; ``` @class Layer.UI.adapters.angular @singleton @param {Object} angular Pass in the AngularJS library
[ "Call", "this", "function", "to", "initialize", "all", "of", "the", "angular", "1", ".", "x", "directives", "needed", "to", "handle", "the", "Layer", "UI", "for", "Web", "widgets", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/adapters/angular.js#L69-L145
train
layerhq/web-xdk
src/ui/adapters/angular.js
setupProps
function setupProps(scope, elem, attrs, props) { /* * For each property we are going to do the following: * * 1. See if there is an initial value * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value * 3. $observe() for any changes in the property * 4. $watch() for any changes in the output of scope.$eval() * * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE * this code triggers and corrects those values. This can cause errors. * * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER * its been evaluated. * * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-` * works better. * * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files. */ props.forEach((prop) => { const ngPropertyName = prop.propertyName.indexOf('on') === 0 ? 'ng' + prop.propertyName.substring(2) : 'ng' + prop.propertyName.substring(0, 1).toUpperCase() + prop.propertyName.substring(1); // Observe for changes to the attribute value and apply them to the property value attrs.$observe(prop.propertyName, (value) => { if (elem.properties) { elem[prop.propertyName] = value; } else { if (!elem.properties) elem.properties = {}; elem.properties[prop.propertyName] = value; } }); // Observe for changes to the attribute value prefixed with "ng-" and watch the scoped expression for changes // that need to be applied to the property value. attrs.$observe(ngPropertyName, (expression) => { scope.$watch(expression, (value) => { if (!elem.properties) elem.properties = {}; if (elem.properties._internalState && !elem.properties._internalState.disableSetters) { elem[prop.propertyName] = value; } else { elem.properties[prop.propertyName] = value; } }); }); }); }
javascript
function setupProps(scope, elem, attrs, props) { /* * For each property we are going to do the following: * * 1. See if there is an initial value * 2. Evaluate it against the scope via scope.$eval() so we have a resolved value * 3. $observe() for any changes in the property * 4. $watch() for any changes in the output of scope.$eval() * * One complicating factor here: while we do support passing in values such as `query` or `query-id`, these * values, if placed within an html template, will be passed directly on to a webcomponent BEFORE * this code triggers and corrects those values. This can cause errors. * * Instead, if one passes `ng-query` or `ng-query-id` in via the html template, there is no `ng-query` property * to pass this value on to until the code below triggers. The code below will map `ng-query` to `query` AFTER * its been evaluated. * * The above steps are applied once for `query-id`, and a second time for `ng-query-id` so that either one works, but `ng-` * works better. * * Best Practice therefore: Use `ng-` prefix on all properties passed via html template files. */ props.forEach((prop) => { const ngPropertyName = prop.propertyName.indexOf('on') === 0 ? 'ng' + prop.propertyName.substring(2) : 'ng' + prop.propertyName.substring(0, 1).toUpperCase() + prop.propertyName.substring(1); // Observe for changes to the attribute value and apply them to the property value attrs.$observe(prop.propertyName, (value) => { if (elem.properties) { elem[prop.propertyName] = value; } else { if (!elem.properties) elem.properties = {}; elem.properties[prop.propertyName] = value; } }); // Observe for changes to the attribute value prefixed with "ng-" and watch the scoped expression for changes // that need to be applied to the property value. attrs.$observe(ngPropertyName, (expression) => { scope.$watch(expression, (value) => { if (!elem.properties) elem.properties = {}; if (elem.properties._internalState && !elem.properties._internalState.disableSetters) { elem[prop.propertyName] = value; } else { elem.properties[prop.propertyName] = value; } }); }); }); }
[ "function", "setupProps", "(", "scope", ",", "elem", ",", "attrs", ",", "props", ")", "{", "props", ".", "forEach", "(", "(", "prop", ")", "=>", "{", "const", "ngPropertyName", "=", "prop", ".", "propertyName", ".", "indexOf", "(", "'on'", ")", "===", "0", "?", "'ng'", "+", "prop", ".", "propertyName", ".", "substring", "(", "2", ")", ":", "'ng'", "+", "prop", ".", "propertyName", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", "+", "prop", ".", "propertyName", ".", "substring", "(", "1", ")", ";", "attrs", ".", "$observe", "(", "prop", ".", "propertyName", ",", "(", "value", ")", "=>", "{", "if", "(", "elem", ".", "properties", ")", "{", "elem", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "else", "{", "if", "(", "!", "elem", ".", "properties", ")", "elem", ".", "properties", "=", "{", "}", ";", "elem", ".", "properties", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "}", ")", ";", "attrs", ".", "$observe", "(", "ngPropertyName", ",", "(", "expression", ")", "=>", "{", "scope", ".", "$watch", "(", "expression", ",", "(", "value", ")", "=>", "{", "if", "(", "!", "elem", ".", "properties", ")", "elem", ".", "properties", "=", "{", "}", ";", "if", "(", "elem", ".", "properties", ".", "_internalState", "&&", "!", "elem", ".", "properties", ".", "_internalState", ".", "disableSetters", ")", "{", "elem", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "else", "{", "elem", ".", "properties", "[", "prop", ".", "propertyName", "]", "=", "value", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Setup the properties for the given widget that is being generated
[ "Setup", "the", "properties", "for", "the", "given", "widget", "that", "is", "being", "generated" ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/adapters/angular.js#L75-L126
train
layerhq/web-xdk
src/ui/components/component.js
setupDomNodes
function setupDomNodes() { this.nodes = {}; this._findNodesWithin(this, (node, isComponent) => { const layerId = node.getAttribute && node.getAttribute('layer-id'); if (layerId) this.nodes[layerId] = node; if (isComponent) { if (!node.properties) node.properties = {}; node.properties.parentComponent = this; } }); }
javascript
function setupDomNodes() { this.nodes = {}; this._findNodesWithin(this, (node, isComponent) => { const layerId = node.getAttribute && node.getAttribute('layer-id'); if (layerId) this.nodes[layerId] = node; if (isComponent) { if (!node.properties) node.properties = {}; node.properties.parentComponent = this; } }); }
[ "function", "setupDomNodes", "(", ")", "{", "this", ".", "nodes", "=", "{", "}", ";", "this", ".", "_findNodesWithin", "(", "this", ",", "(", "node", ",", "isComponent", ")", "=>", "{", "const", "layerId", "=", "node", ".", "getAttribute", "&&", "node", ".", "getAttribute", "(", "'layer-id'", ")", ";", "if", "(", "layerId", ")", "this", ".", "nodes", "[", "layerId", "]", "=", "node", ";", "if", "(", "isComponent", ")", "{", "if", "(", "!", "node", ".", "properties", ")", "node", ".", "properties", "=", "{", "}", ";", "node", ".", "properties", ".", "parentComponent", "=", "this", ";", "}", "}", ")", ";", "}" ]
The setupDomNodes method looks at all child nodes of this node that have layer-id properties and indexes them in the `nodes` property. Typically, this node has child nodes loaded via its template, and ready by the time your `created` method is called. This call is made on your behalf prior to calling `created`, but if using templates after `created` is called, you may need to call this directly. @method setupDomNodes @protected
[ "The", "setupDomNodes", "method", "looks", "at", "all", "child", "nodes", "of", "this", "node", "that", "have", "layer", "-", "id", "properties", "and", "indexes", "them", "in", "the", "nodes", "property", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1550-L1562
train
layerhq/web-xdk
src/ui/components/component.js
_findNodesWithin
function _findNodesWithin(node, callback) { const children = node.childNodes; for (let i = 0; i < children.length; i++) { const innerNode = children[i]; if (innerNode instanceof HTMLElement) { const isLUIComponent = Boolean(ComponentsHash[innerNode.tagName.toLowerCase()]); const result = callback(innerNode, isLUIComponent); if (result) return result; // If its not a custom webcomponent with children that it manages and owns, iterate on it if (!isLUIComponent) { const innerResult = this._findNodesWithin(innerNode, callback); if (innerResult) return innerResult; } } } }
javascript
function _findNodesWithin(node, callback) { const children = node.childNodes; for (let i = 0; i < children.length; i++) { const innerNode = children[i]; if (innerNode instanceof HTMLElement) { const isLUIComponent = Boolean(ComponentsHash[innerNode.tagName.toLowerCase()]); const result = callback(innerNode, isLUIComponent); if (result) return result; // If its not a custom webcomponent with children that it manages and owns, iterate on it if (!isLUIComponent) { const innerResult = this._findNodesWithin(innerNode, callback); if (innerResult) return innerResult; } } } }
[ "function", "_findNodesWithin", "(", "node", ",", "callback", ")", "{", "const", "children", "=", "node", ".", "childNodes", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "children", ".", "length", ";", "i", "++", ")", "{", "const", "innerNode", "=", "children", "[", "i", "]", ";", "if", "(", "innerNode", "instanceof", "HTMLElement", ")", "{", "const", "isLUIComponent", "=", "Boolean", "(", "ComponentsHash", "[", "innerNode", ".", "tagName", ".", "toLowerCase", "(", ")", "]", ")", ";", "const", "result", "=", "callback", "(", "innerNode", ",", "isLUIComponent", ")", ";", "if", "(", "result", ")", "return", "result", ";", "if", "(", "!", "isLUIComponent", ")", "{", "const", "innerResult", "=", "this", ".", "_findNodesWithin", "(", "innerNode", ",", "callback", ")", ";", "if", "(", "innerResult", ")", "return", "innerResult", ";", "}", "}", "}", "}" ]
Iterate over all child nodes generated by the template; skip all subcomponent's child nodes. If callback returns a value, then what is sought has been found; stop searching. The returned value is the return value for this function. If searching for ALL matches, do not return a value in your callback. @method _findNodesWithin @private @param {HTMLElement} node Node whose subtree should be called with the callback @param {Function} callback Function to call on each node in the tree @param {HTMLElement} callback.node Node that the callback is called on @param {Boolean} callback.isComponent Is the node a Component from this framework
[ "Iterate", "over", "all", "child", "nodes", "generated", "by", "the", "template", ";", "skip", "all", "subcomponent", "s", "child", "nodes", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1579-L1595
train
layerhq/web-xdk
src/ui/components/component.js
getTemplate
function getTemplate() { const tagName = this.tagName.toLocaleLowerCase(); if (ComponentsHash[tagName].style) { const styleNode = document.createElement('style'); styleNode.id = 'style-' + this.tagName.toLowerCase(); styleNode.innerHTML = ComponentsHash[tagName].style; document.getElementsByTagName('head')[0].appendChild(styleNode); ComponentsHash[tagName].style = ''; // insure it doesn't get added to head a second time } return ComponentsHash[tagName].template; }
javascript
function getTemplate() { const tagName = this.tagName.toLocaleLowerCase(); if (ComponentsHash[tagName].style) { const styleNode = document.createElement('style'); styleNode.id = 'style-' + this.tagName.toLowerCase(); styleNode.innerHTML = ComponentsHash[tagName].style; document.getElementsByTagName('head')[0].appendChild(styleNode); ComponentsHash[tagName].style = ''; // insure it doesn't get added to head a second time } return ComponentsHash[tagName].template; }
[ "function", "getTemplate", "(", ")", "{", "const", "tagName", "=", "this", ".", "tagName", ".", "toLocaleLowerCase", "(", ")", ";", "if", "(", "ComponentsHash", "[", "tagName", "]", ".", "style", ")", "{", "const", "styleNode", "=", "document", ".", "createElement", "(", "'style'", ")", ";", "styleNode", ".", "id", "=", "'style-'", "+", "this", ".", "tagName", ".", "toLowerCase", "(", ")", ";", "styleNode", ".", "innerHTML", "=", "ComponentsHash", "[", "tagName", "]", ".", "style", ";", "document", ".", "getElementsByTagName", "(", "'head'", ")", "[", "0", "]", ".", "appendChild", "(", "styleNode", ")", ";", "ComponentsHash", "[", "tagName", "]", ".", "style", "=", "''", ";", "}", "return", "ComponentsHash", "[", "tagName", "]", ".", "template", ";", "}" ]
Return the template for this Component. Get the default template: ``` var template = widget.getTemplate(); ``` Typical components should not need to call this; this will be called automatically prior to calling the Component's `created` method. Some components wanting to reset dom to initial state may use this method explicitly: ``` var template = this.getTemplate(); var clone = document.importNode(template.content, true); this.appendChild(clone); this.setupDomNodes(); ``` @method getTemplate @protected @returns {HTMLTemplateElement}
[ "Return", "the", "template", "for", "this", "Component", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1620-L1631
train
layerhq/web-xdk
src/ui/components/component.js
trigger
function trigger(eventName, details) { const evt = new CustomEvent(eventName, { detail: details, bubbles: true, cancelable: true, }); this.dispatchEvent(evt); return !evt.defaultPrevented; }
javascript
function trigger(eventName, details) { const evt = new CustomEvent(eventName, { detail: details, bubbles: true, cancelable: true, }); this.dispatchEvent(evt); return !evt.defaultPrevented; }
[ "function", "trigger", "(", "eventName", ",", "details", ")", "{", "const", "evt", "=", "new", "CustomEvent", "(", "eventName", ",", "{", "detail", ":", "details", ",", "bubbles", ":", "true", ",", "cancelable", ":", "true", ",", "}", ")", ";", "this", ".", "dispatchEvent", "(", "evt", ")", ";", "return", "!", "evt", ".", "defaultPrevented", ";", "}" ]
Triggers a dom level event which bubbles up the dom. Call with an event name and a `detail` object: ``` this.trigger('something-happened', { someSortOf: 'value' }); ``` The `someSortOf` key, and any other keys you pass into that object can be accessed via `evt.detail.someSortOf` or `evt.detail.xxxx`: ``` // Listen for the something-happened event which because it bubbles up the dom, // can be listened for from any parent node document.body.addEventListener('something-happened', function(evt) { console.log(evt.detail.someSortOf); }); ``` {@link Layer.UI.Component#events} can be used to generate properties to go with your events, allowing the following widget property to be used: ``` this.onSomethingHappened = function(evt) { console.log(evt.detail.someSortOf); }); ``` Note that events may be canceled via `evt.preventDefault()` and your code may need to handle this: ``` if (this.trigger('something-is-happening')) { doSomething(); } else { cancelSomething(); } ``` @method trigger @protected @param {String} eventName @param {Object} detail @returns {Boolean} True if process should continue with its actions, false if application has canceled the default action using `evt.preventDefault()`
[ "Triggers", "a", "dom", "level", "event", "which", "bubbles", "up", "the", "dom", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1680-L1688
train
layerhq/web-xdk
src/ui/components/component.js
toggleClass
function toggleClass(...args) { const cssClass = args[0]; const enable = (args.length === 2) ? args[1] : !this.classList.contains(cssClass); this.classList[enable ? 'add' : 'remove'](cssClass); }
javascript
function toggleClass(...args) { const cssClass = args[0]; const enable = (args.length === 2) ? args[1] : !this.classList.contains(cssClass); this.classList[enable ? 'add' : 'remove'](cssClass); }
[ "function", "toggleClass", "(", "...", "args", ")", "{", "const", "cssClass", "=", "args", "[", "0", "]", ";", "const", "enable", "=", "(", "args", ".", "length", "===", "2", ")", "?", "args", "[", "1", "]", ":", "!", "this", ".", "classList", ".", "contains", "(", "cssClass", ")", ";", "this", ".", "classList", "[", "enable", "?", "'add'", ":", "'remove'", "]", "(", "cssClass", ")", ";", "}" ]
Toggle a CSS Class. Why do we have this? Well, sadly as long as we support IE11 which has an incorrect implementation of node.classList.toggle, we will have to do this ourselves. @method toggleClass @param {String} className @param {Boolean} [enable=!enable]
[ "Toggle", "a", "CSS", "Class", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1714-L1718
train
layerhq/web-xdk
src/ui/components/component.js
createElement
function createElement(tagName, properties) { const node = document.createElement(tagName); node.parentComponent = this; const ignore = ['parentNode', 'name', 'classList', 'noCreate']; Object.keys(properties).forEach((propName) => { if (ignore.indexOf(propName) === -1) node[propName] = properties[propName]; }); if (properties.classList) properties.classList.forEach(className => node.classList.add(className)); if (properties.parentNode) properties.parentNode.appendChild(node); if (properties.name) this.nodes[properties.name] = node; if (!properties.noCreate) { if (typeof CustomElements !== 'undefined') CustomElements.upgradeAll(node); if (node._onAfterCreate) node._onAfterCreate(); } return node; }
javascript
function createElement(tagName, properties) { const node = document.createElement(tagName); node.parentComponent = this; const ignore = ['parentNode', 'name', 'classList', 'noCreate']; Object.keys(properties).forEach((propName) => { if (ignore.indexOf(propName) === -1) node[propName] = properties[propName]; }); if (properties.classList) properties.classList.forEach(className => node.classList.add(className)); if (properties.parentNode) properties.parentNode.appendChild(node); if (properties.name) this.nodes[properties.name] = node; if (!properties.noCreate) { if (typeof CustomElements !== 'undefined') CustomElements.upgradeAll(node); if (node._onAfterCreate) node._onAfterCreate(); } return node; }
[ "function", "createElement", "(", "tagName", ",", "properties", ")", "{", "const", "node", "=", "document", ".", "createElement", "(", "tagName", ")", ";", "node", ".", "parentComponent", "=", "this", ";", "const", "ignore", "=", "[", "'parentNode'", ",", "'name'", ",", "'classList'", ",", "'noCreate'", "]", ";", "Object", ".", "keys", "(", "properties", ")", ".", "forEach", "(", "(", "propName", ")", "=>", "{", "if", "(", "ignore", ".", "indexOf", "(", "propName", ")", "===", "-", "1", ")", "node", "[", "propName", "]", "=", "properties", "[", "propName", "]", ";", "}", ")", ";", "if", "(", "properties", ".", "classList", ")", "properties", ".", "classList", ".", "forEach", "(", "className", "=>", "node", ".", "classList", ".", "add", "(", "className", ")", ")", ";", "if", "(", "properties", ".", "parentNode", ")", "properties", ".", "parentNode", ".", "appendChild", "(", "node", ")", ";", "if", "(", "properties", ".", "name", ")", "this", ".", "nodes", "[", "properties", ".", "name", "]", "=", "node", ";", "if", "(", "!", "properties", ".", "noCreate", ")", "{", "if", "(", "typeof", "CustomElements", "!==", "'undefined'", ")", "CustomElements", ".", "upgradeAll", "(", "node", ")", ";", "if", "(", "node", ".", "_onAfterCreate", ")", "node", ".", "_onAfterCreate", "(", ")", ";", "}", "return", "node", ";", "}" ]
Shorthand for `document.createElement` followed by a bunch of standard setup. ``` var avatar = this.createElement({ name: "myavatar", size: "large", users: [client.user], parentNode: this.nodes.avatarContainer }); console.log(avatar === this.nodes.myavatar); // returns true ``` TODO: Most `document.createElement` calls in this UI Framework should be updated to use this. Note that because all properties are initialized by this call, there is no need for asynchronous initialization, so unless suppressed with the `noCreate` parameter, all initialization is completed synchronously. @method createElement @param {String} tagName The type of HTMLElement to create (includes Layer.UI.Component instances) @param {Object} properties The properties to initialize the HTMLElement with @param {HTMLElement} [properties.parentNode] The node to setup as the `parentNode` of our new UI Component @param {String} [properties.name] Set `this.nodes[name] = newUIElement` @param {String[]} [properties.classList] Array of CSS Class names to add to the new UI Component @param {Boolean} [properties.noCreate=false] Do not call `_onAfterCreate()`; allow the lifecycle to flow asyncrhonously instead of rush it through synchronously.
[ "Shorthand", "for", "document", ".", "createElement", "followed", "by", "a", "bunch", "of", "standard", "setup", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L1746-L1763
train
layerhq/web-xdk
src/ui/components/component.js
destroy
function destroy() { if (this.properties._internalState.onDestroyCalled) return; if (this.parentNode) { this.parentNode.removeChild(this); } Object.keys(this.nodes || {}).forEach((name) => { if (this.nodes[name] && this.nodes[name].destroy) this.nodes[name].destroy(); }); this.onDestroy(); }
javascript
function destroy() { if (this.properties._internalState.onDestroyCalled) return; if (this.parentNode) { this.parentNode.removeChild(this); } Object.keys(this.nodes || {}).forEach((name) => { if (this.nodes[name] && this.nodes[name].destroy) this.nodes[name].destroy(); }); this.onDestroy(); }
[ "function", "destroy", "(", ")", "{", "if", "(", "this", ".", "properties", ".", "_internalState", ".", "onDestroyCalled", ")", "return", ";", "if", "(", "this", ".", "parentNode", ")", "{", "this", ".", "parentNode", ".", "removeChild", "(", "this", ")", ";", "}", "Object", ".", "keys", "(", "this", ".", "nodes", "||", "{", "}", ")", ".", "forEach", "(", "(", "name", ")", "=>", "{", "if", "(", "this", ".", "nodes", "[", "name", "]", "&&", "this", ".", "nodes", "[", "name", "]", ".", "destroy", ")", "this", ".", "nodes", "[", "name", "]", ".", "destroy", "(", ")", ";", "}", ")", ";", "this", ".", "onDestroy", "(", ")", ";", "}" ]
Call this to destroy the UI Component. Destroying will cause it to be removed from its parent node, it will call destroy on all child nodes, and then call the {@link #onDestroy} method. > *Note* > > destroy is called to remove a component, but it is not a lifecycle method; a component that has been removed > from the DOM some otherway will cause {@link #onDestroy} to be called but `destroy()` will _not_ be called. @method destroy
[ "Call", "this", "to", "destroy", "the", "UI", "Component", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L2078-L2087
train
layerhq/web-xdk
src/ui/components/component.js
_registerAll
function _registerAll() { if (!registerAllCalled) { registerAllCalled = true; Object.keys(ComponentsHash) .filter(tagName => typeof ComponentsHash[tagName] !== 'function') .forEach(tagName => _registerComponent(tagName)); } }
javascript
function _registerAll() { if (!registerAllCalled) { registerAllCalled = true; Object.keys(ComponentsHash) .filter(tagName => typeof ComponentsHash[tagName] !== 'function') .forEach(tagName => _registerComponent(tagName)); } }
[ "function", "_registerAll", "(", ")", "{", "if", "(", "!", "registerAllCalled", ")", "{", "registerAllCalled", "=", "true", ";", "Object", ".", "keys", "(", "ComponentsHash", ")", ".", "filter", "(", "tagName", "=>", "typeof", "ComponentsHash", "[", "tagName", "]", "!==", "'function'", ")", ".", "forEach", "(", "tagName", "=>", "_registerComponent", "(", "tagName", ")", ")", ";", "}", "}" ]
Registers all defined components with the browser as WebComponents. This is called by `Layer.init()` and should not be called directly. @private @method _registerAll
[ "Registers", "all", "defined", "components", "with", "the", "browser", "as", "WebComponents", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/component.js#L2137-L2144
train
layerhq/web-xdk
src/ui/components/layer-message-list/layer-message-item-mixin.js
onRender
function onRender() { try { // Setup the layer-sender-name if (this.nodes.sender) { this.nodes.sender.innerHTML = this.item.sender.displayName; } if (this.nodes.avatar) { this.nodes.avatar.users = [this.item.sender]; } // Setup the layer-date if (this.nodes.date && !this.item.isNew()) { if (this.dateRenderer) this.nodes.date.dateRenderer = this.dateRenderer; this.nodes.date.date = this.item.sentAt; } // Setup the layer-message-status if (this.nodes.status && this.messageStatusRenderer) { this.nodes.status.messageStatusRenderer = this.messageStatusRenderer; } // Setup the layer-delete if (this.nodes.delete) { this.nodes.delete.enabled = this.getDeleteEnabled ? this.getDeleteEnabled(this.properties.item) : true; } // Generate the renderer for this Message's MessageParts. this._applyContentTag(); // Render all mutable data this.onRerender(); } catch (err) { logger.error('layer-message-item.render(): ', err); } }
javascript
function onRender() { try { // Setup the layer-sender-name if (this.nodes.sender) { this.nodes.sender.innerHTML = this.item.sender.displayName; } if (this.nodes.avatar) { this.nodes.avatar.users = [this.item.sender]; } // Setup the layer-date if (this.nodes.date && !this.item.isNew()) { if (this.dateRenderer) this.nodes.date.dateRenderer = this.dateRenderer; this.nodes.date.date = this.item.sentAt; } // Setup the layer-message-status if (this.nodes.status && this.messageStatusRenderer) { this.nodes.status.messageStatusRenderer = this.messageStatusRenderer; } // Setup the layer-delete if (this.nodes.delete) { this.nodes.delete.enabled = this.getDeleteEnabled ? this.getDeleteEnabled(this.properties.item) : true; } // Generate the renderer for this Message's MessageParts. this._applyContentTag(); // Render all mutable data this.onRerender(); } catch (err) { logger.error('layer-message-item.render(): ', err); } }
[ "function", "onRender", "(", ")", "{", "try", "{", "if", "(", "this", ".", "nodes", ".", "sender", ")", "{", "this", ".", "nodes", ".", "sender", ".", "innerHTML", "=", "this", ".", "item", ".", "sender", ".", "displayName", ";", "}", "if", "(", "this", ".", "nodes", ".", "avatar", ")", "{", "this", ".", "nodes", ".", "avatar", ".", "users", "=", "[", "this", ".", "item", ".", "sender", "]", ";", "}", "if", "(", "this", ".", "nodes", ".", "date", "&&", "!", "this", ".", "item", ".", "isNew", "(", ")", ")", "{", "if", "(", "this", ".", "dateRenderer", ")", "this", ".", "nodes", ".", "date", ".", "dateRenderer", "=", "this", ".", "dateRenderer", ";", "this", ".", "nodes", ".", "date", ".", "date", "=", "this", ".", "item", ".", "sentAt", ";", "}", "if", "(", "this", ".", "nodes", ".", "status", "&&", "this", ".", "messageStatusRenderer", ")", "{", "this", ".", "nodes", ".", "status", ".", "messageStatusRenderer", "=", "this", ".", "messageStatusRenderer", ";", "}", "if", "(", "this", ".", "nodes", ".", "delete", ")", "{", "this", ".", "nodes", ".", "delete", ".", "enabled", "=", "this", ".", "getDeleteEnabled", "?", "this", ".", "getDeleteEnabled", "(", "this", ".", "properties", ".", "item", ")", ":", "true", ";", "}", "this", ".", "_applyContentTag", "(", ")", ";", "this", ".", "onRerender", "(", ")", ";", "}", "catch", "(", "err", ")", "{", "logger", ".", "error", "(", "'layer-message-item.render(): '", ",", "err", ")", ";", "}", "}" ]
Lifecycle method sets up the Message to render
[ "Lifecycle", "method", "sets", "up", "the", "Message", "to", "render" ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/ui/components/layer-message-list/layer-message-item-mixin.js#L237-L273
train
Streampunk/ledger
model/Versionned.js
Versionned
function Versionned(id, version, label) { /** * Globally unique UUID identifier for the resource. * @type {string} * @readonly */ this.id = this.generateID(id); /** * String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;) * indicating precisely when an attribute of the resource last changed. * @type {string} * @readonly */ this.version = this.generateVersion(version); /** * Freeform string label for the resource. * @type {string} * @readonly */ this.label = this.generateLabel(label); return immutable(this, {prototype: Versionned.prototype}); }
javascript
function Versionned(id, version, label) { /** * Globally unique UUID identifier for the resource. * @type {string} * @readonly */ this.id = this.generateID(id); /** * String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;) * indicating precisely when an attribute of the resource last changed. * @type {string} * @readonly */ this.version = this.generateVersion(version); /** * Freeform string label for the resource. * @type {string} * @readonly */ this.label = this.generateLabel(label); return immutable(this, {prototype: Versionned.prototype}); }
[ "function", "Versionned", "(", "id", ",", "version", ",", "label", ")", "{", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Versionned", ".", "prototype", "}", ")", ";", "}" ]
Supertype of every class that has UUID identity, version numbers and labels. Methods are designed to be mixed in piecemeal as required. @constructor @param {string} id Globally unique UUID identifier for the resource. @param {string} version String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds<em>&gt;) indicating precisely when an attribute of the resource last changed. @param {string} label Freeform string label for the resource.
[ "Supertype", "of", "every", "class", "that", "has", "UUID", "identity", "version", "numbers", "and", "labels", ".", "Methods", "are", "designed", "to", "be", "mixed", "in", "piecemeal", "as", "required", "." ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Versionned.js#L41-L62
train
layerhq/web-xdk
src/core/root.js
initClass
function initClass(newClass, className, namespace) { // Make sure our new class has a name property try { if (newClass.name !== className) newClass.altName = className; } catch (e) { // No-op } // Make sure our new class has a _supportedEvents, _ignoredEvents, _inObjectIgnore and EVENTS properties if (!newClass._supportedEvents) newClass._supportedEvents = Root._supportedEvents; if (!newClass._ignoredEvents) newClass._ignoredEvents = Root._ignoredEvents; if (newClass.mixins) { newClass.mixins.forEach((mixin) => { if (mixin.events) newClass._supportedEvents = newClass._supportedEvents.concat(mixin.events); Object.keys(mixin.staticMethods || {}) .forEach(methodName => (newClass[methodName] = mixin.staticMethods[methodName])); if (mixin.properties) { Object.keys(mixin.properties).forEach((key) => { newClass.prototype[key] = mixin.properties[key]; }); } if (mixin.methods) { Object.keys(mixin.methods).forEach((key) => { newClass.prototype[key] = mixin.methods[key]; }); } }); } // Generate a list of properties for this class; we don't include any // properties from Layer.Core.Root const keys = Object.keys(newClass.prototype).filter(key => newClass.prototype.hasOwnProperty(key) && !Root.prototype.hasOwnProperty(key) && typeof newClass.prototype[key] !== 'function'); // Define getters/setters for any property that has __adjust or __update methods defined keys.forEach(name => defineProperty(newClass, name)); if (namespace) namespace[className] = newClass; }
javascript
function initClass(newClass, className, namespace) { // Make sure our new class has a name property try { if (newClass.name !== className) newClass.altName = className; } catch (e) { // No-op } // Make sure our new class has a _supportedEvents, _ignoredEvents, _inObjectIgnore and EVENTS properties if (!newClass._supportedEvents) newClass._supportedEvents = Root._supportedEvents; if (!newClass._ignoredEvents) newClass._ignoredEvents = Root._ignoredEvents; if (newClass.mixins) { newClass.mixins.forEach((mixin) => { if (mixin.events) newClass._supportedEvents = newClass._supportedEvents.concat(mixin.events); Object.keys(mixin.staticMethods || {}) .forEach(methodName => (newClass[methodName] = mixin.staticMethods[methodName])); if (mixin.properties) { Object.keys(mixin.properties).forEach((key) => { newClass.prototype[key] = mixin.properties[key]; }); } if (mixin.methods) { Object.keys(mixin.methods).forEach((key) => { newClass.prototype[key] = mixin.methods[key]; }); } }); } // Generate a list of properties for this class; we don't include any // properties from Layer.Core.Root const keys = Object.keys(newClass.prototype).filter(key => newClass.prototype.hasOwnProperty(key) && !Root.prototype.hasOwnProperty(key) && typeof newClass.prototype[key] !== 'function'); // Define getters/setters for any property that has __adjust or __update methods defined keys.forEach(name => defineProperty(newClass, name)); if (namespace) namespace[className] = newClass; }
[ "function", "initClass", "(", "newClass", ",", "className", ",", "namespace", ")", "{", "try", "{", "if", "(", "newClass", ".", "name", "!==", "className", ")", "newClass", ".", "altName", "=", "className", ";", "}", "catch", "(", "e", ")", "{", "}", "if", "(", "!", "newClass", ".", "_supportedEvents", ")", "newClass", ".", "_supportedEvents", "=", "Root", ".", "_supportedEvents", ";", "if", "(", "!", "newClass", ".", "_ignoredEvents", ")", "newClass", ".", "_ignoredEvents", "=", "Root", ".", "_ignoredEvents", ";", "if", "(", "newClass", ".", "mixins", ")", "{", "newClass", ".", "mixins", ".", "forEach", "(", "(", "mixin", ")", "=>", "{", "if", "(", "mixin", ".", "events", ")", "newClass", ".", "_supportedEvents", "=", "newClass", ".", "_supportedEvents", ".", "concat", "(", "mixin", ".", "events", ")", ";", "Object", ".", "keys", "(", "mixin", ".", "staticMethods", "||", "{", "}", ")", ".", "forEach", "(", "methodName", "=>", "(", "newClass", "[", "methodName", "]", "=", "mixin", ".", "staticMethods", "[", "methodName", "]", ")", ")", ";", "if", "(", "mixin", ".", "properties", ")", "{", "Object", ".", "keys", "(", "mixin", ".", "properties", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "newClass", ".", "prototype", "[", "key", "]", "=", "mixin", ".", "properties", "[", "key", "]", ";", "}", ")", ";", "}", "if", "(", "mixin", ".", "methods", ")", "{", "Object", ".", "keys", "(", "mixin", ".", "methods", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "newClass", ".", "prototype", "[", "key", "]", "=", "mixin", ".", "methods", "[", "key", "]", ";", "}", ")", ";", "}", "}", ")", ";", "}", "const", "keys", "=", "Object", ".", "keys", "(", "newClass", ".", "prototype", ")", ".", "filter", "(", "key", "=>", "newClass", ".", "prototype", ".", "hasOwnProperty", "(", "key", ")", "&&", "!", "Root", ".", "prototype", ".", "hasOwnProperty", "(", "key", ")", "&&", "typeof", "newClass", ".", "prototype", "[", "key", "]", "!==", "'function'", ")", ";", "keys", ".", "forEach", "(", "name", "=>", "defineProperty", "(", "newClass", ",", "name", ")", ")", ";", "if", "(", "namespace", ")", "namespace", "[", "className", "]", "=", "newClass", ";", "}" ]
Initialize a class definition that is a subclass of Root. ``` class myClass extends Root { } Root.initClass(myClass, 'myClass'); console.log(Layer.Core.myClass); ``` With namespace: ``` const MyNameSpace = {}; class myClass extends Root { } Root.initClass(myClass, 'myClass', MyNameSpace); console.log(MyNameSpace.myClass); ``` Defining a class without calling this method means * none of the property getters/setters/adjusters will work; * Mixins won't be used * _supportedEvents won't be setup which means no events can be subscribed to on this class @method initClass @static @param {Function} newClass Class definition @param {String} className Class name @param {Object} [namespace=] Object to write this class definition to
[ "Initialize", "a", "class", "definition", "that", "is", "a", "subclass", "of", "Root", "." ]
a2d61e62d22db6511c2920e7989ba2afb4dad274
https://github.com/layerhq/web-xdk/blob/a2d61e62d22db6511c2920e7989ba2afb4dad274/src/core/root.js#L661-L703
train
Streampunk/ledger
model/Receiver.js
Receiver
function Receiver(id, version, label, description, format, caps, tags, device_id, transport, subscription) { // Globally unique identifier for the Receiver this.id = this.generateID(id); // String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating // precisely when an attribute of the resource last changed. this.version = this.generateVersion(version); // Freeform string label for the Receiver this.label = this.generateLabel(label); // Detailed description of the Receiver this.description = this.generateDescription(description); // Type of Flow accepted by the Receiver as a URN this.format = this.generateFormat(format); // Capabilities (not yet defined) this.caps = this.generateCaps(caps); // Key value set of freeform string tags to aid in filtering sources. // Values should be represented as an array of strings. Can be empty. this.tags = this.generateTags(tags); // Device ID which this Receiver forms part of. this.device_id = this.generateDeviceID(device_id); // Transport type accepted by the Receiver in URN format this.transport = this.generateTransport(transport); // Object containing the 'sender_id' currently subscribed to. Sender_id // should be null on initialisation. this.subscription = this.generateSubscription(subscription); return immutable(this, { prototype : Receiver.prototype }); }
javascript
function Receiver(id, version, label, description, format, caps, tags, device_id, transport, subscription) { // Globally unique identifier for the Receiver this.id = this.generateID(id); // String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating // precisely when an attribute of the resource last changed. this.version = this.generateVersion(version); // Freeform string label for the Receiver this.label = this.generateLabel(label); // Detailed description of the Receiver this.description = this.generateDescription(description); // Type of Flow accepted by the Receiver as a URN this.format = this.generateFormat(format); // Capabilities (not yet defined) this.caps = this.generateCaps(caps); // Key value set of freeform string tags to aid in filtering sources. // Values should be represented as an array of strings. Can be empty. this.tags = this.generateTags(tags); // Device ID which this Receiver forms part of. this.device_id = this.generateDeviceID(device_id); // Transport type accepted by the Receiver in URN format this.transport = this.generateTransport(transport); // Object containing the 'sender_id' currently subscribed to. Sender_id // should be null on initialisation. this.subscription = this.generateSubscription(subscription); return immutable(this, { prototype : Receiver.prototype }); }
[ "function", "Receiver", "(", "id", ",", "version", ",", "label", ",", "description", ",", "format", ",", "caps", ",", "tags", ",", "device_id", ",", "transport", ",", "subscription", ")", "{", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "this", ".", "description", "=", "this", ".", "generateDescription", "(", "description", ")", ";", "this", ".", "format", "=", "this", ".", "generateFormat", "(", "format", ")", ";", "this", ".", "caps", "=", "this", ".", "generateCaps", "(", "caps", ")", ";", "this", ".", "tags", "=", "this", ".", "generateTags", "(", "tags", ")", ";", "this", ".", "device_id", "=", "this", ".", "generateDeviceID", "(", "device_id", ")", ";", "this", ".", "transport", "=", "this", ".", "generateTransport", "(", "transport", ")", ";", "this", ".", "subscription", "=", "this", ".", "generateSubscription", "(", "subscription", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Receiver", ".", "prototype", "}", ")", ";", "}" ]
Describes a receiver
[ "Describes", "a", "receiver" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Receiver.js#L21-L47
train
Streampunk/ledger
api/NodeAPI.js
registerResources
function registerResources(rs) { registerPromise = registerPromise.then(() => { return Promise.all(rs.map((r) => { return Promise.denodeify(pushResource)(r); })); }); }
javascript
function registerResources(rs) { registerPromise = registerPromise.then(() => { return Promise.all(rs.map((r) => { return Promise.denodeify(pushResource)(r); })); }); }
[ "function", "registerResources", "(", "rs", ")", "{", "registerPromise", "=", "registerPromise", ".", "then", "(", "(", ")", "=>", "{", "return", "Promise", ".", "all", "(", "rs", ".", "map", "(", "(", "r", ")", "=>", "{", "return", "Promise", ".", "denodeify", "(", "pushResource", ")", "(", "r", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}" ]
only use registerResources for independent resources
[ "only", "use", "registerResources", "for", "independent", "resources" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/api/NodeAPI.js#L680-L684
train
DeMille/node-usbmux
bin/cli.js
info
function info() { if (argv.verbose !== 1) return; var args = Array.prototype.slice.call(arguments); if (!args[args.length-1]) args.pop(); // if last arg is undefined, remove it console.log.apply(console, args); }
javascript
function info() { if (argv.verbose !== 1) return; var args = Array.prototype.slice.call(arguments); if (!args[args.length-1]) args.pop(); // if last arg is undefined, remove it console.log.apply(console, args); }
[ "function", "info", "(", ")", "{", "if", "(", "argv", ".", "verbose", "!==", "1", ")", "return", ";", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "if", "(", "!", "args", "[", "args", ".", "length", "-", "1", "]", ")", "args", ".", "pop", "(", ")", ";", "console", ".", "log", ".", "apply", "(", "console", ",", "args", ")", ";", "}" ]
Shows debugging info only for verbosity = 1 @param {*...} arguments
[ "Shows", "debugging", "info", "only", "for", "verbosity", "=", "1" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/bin/cli.js#L32-L37
train
DeMille/node-usbmux
bin/cli.js
onErr
function onErr(err) { // local port is in use if (err.code === 'EADDRINUSE') { panic('Local port is in use \nFailing...'); } // usbmux not there if (err.code === 'ECONNREFUSED' || err.code === 'EADDRNOTAVAIL') { panic('Usbmuxd not found at', usbmux.address, '\nFailing...'); } // other panic('%s \nFailing...', err); }
javascript
function onErr(err) { // local port is in use if (err.code === 'EADDRINUSE') { panic('Local port is in use \nFailing...'); } // usbmux not there if (err.code === 'ECONNREFUSED' || err.code === 'EADDRNOTAVAIL') { panic('Usbmuxd not found at', usbmux.address, '\nFailing...'); } // other panic('%s \nFailing...', err); }
[ "function", "onErr", "(", "err", ")", "{", "if", "(", "err", ".", "code", "===", "'EADDRINUSE'", ")", "{", "panic", "(", "'Local port is in use \\nFailing...'", ")", ";", "}", "\\n", "if", "(", "err", ".", "code", "===", "'ECONNREFUSED'", "||", "err", ".", "code", "===", "'EADDRNOTAVAIL'", ")", "{", "panic", "(", "'Usbmuxd not found at'", ",", "usbmux", ".", "address", ",", "'\\nFailing...'", ")", ";", "}", "}" ]
Error handler for listener and relay @param {Error} err
[ "Error", "handler", "for", "listener", "and", "relay" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/bin/cli.js#L54-L65
train
DeMille/node-usbmux
bin/cli.js
listenForDevices
function listenForDevices() { console.log('Listening for connected devices... \n'); usbmux.createListener() .on('error', onErr) .on('attached', function(udid) { console.log('Device found: ', udid); }) .on('detached', function(udid) { console.log('Device removed: ', udid); }); }
javascript
function listenForDevices() { console.log('Listening for connected devices... \n'); usbmux.createListener() .on('error', onErr) .on('attached', function(udid) { console.log('Device found: ', udid); }) .on('detached', function(udid) { console.log('Device removed: ', udid); }); }
[ "function", "listenForDevices", "(", ")", "{", "console", ".", "log", "(", "'Listening for connected devices... \\n'", ")", ";", "\\n", "}" ]
Listen for and report connected devices
[ "Listen", "for", "and", "report", "connected", "devices" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/bin/cli.js#L70-L81
train
DeMille/node-usbmux
bin/cli.js
startRelay
function startRelay(portPair) { var devicePort = portPair[0] , relayPort = portPair[1]; console.log('Starting relay from local port: %s -> device port: %s', relayPort, devicePort); new usbmux.Relay(devicePort, relayPort, {udid: argv.udid}) .on('error', onErr) .on('warning', console.log.bind(console, 'Warning: device not found...')) .on('ready', info.bind(this, 'Device ready: ')) .on('attached', info.bind(this, 'Device attached: ')) .on('detached', info.bind(this, 'Device detached: ')) .on('connect', info.bind(this, 'New connection to relay started.')) .on('disconnect', info.bind(this, 'Connection to relay closed.')) .on('close', info.bind(this, 'Relay has closed.')); }
javascript
function startRelay(portPair) { var devicePort = portPair[0] , relayPort = portPair[1]; console.log('Starting relay from local port: %s -> device port: %s', relayPort, devicePort); new usbmux.Relay(devicePort, relayPort, {udid: argv.udid}) .on('error', onErr) .on('warning', console.log.bind(console, 'Warning: device not found...')) .on('ready', info.bind(this, 'Device ready: ')) .on('attached', info.bind(this, 'Device attached: ')) .on('detached', info.bind(this, 'Device detached: ')) .on('connect', info.bind(this, 'New connection to relay started.')) .on('disconnect', info.bind(this, 'Connection to relay closed.')) .on('close', info.bind(this, 'Relay has closed.')); }
[ "function", "startRelay", "(", "portPair", ")", "{", "var", "devicePort", "=", "portPair", "[", "0", "]", ",", "relayPort", "=", "portPair", "[", "1", "]", ";", "console", ".", "log", "(", "'Starting relay from local port: %s -> device port: %s'", ",", "relayPort", ",", "devicePort", ")", ";", "new", "usbmux", ".", "Relay", "(", "devicePort", ",", "relayPort", ",", "{", "udid", ":", "argv", ".", "udid", "}", ")", ".", "on", "(", "'error'", ",", "onErr", ")", ".", "on", "(", "'warning'", ",", "console", ".", "log", ".", "bind", "(", "console", ",", "'Warning: device not found...'", ")", ")", ".", "on", "(", "'ready'", ",", "info", ".", "bind", "(", "this", ",", "'Device ready: '", ")", ")", ".", "on", "(", "'attached'", ",", "info", ".", "bind", "(", "this", ",", "'Device attached: '", ")", ")", ".", "on", "(", "'detached'", ",", "info", ".", "bind", "(", "this", ",", "'Device detached: '", ")", ")", ".", "on", "(", "'connect'", ",", "info", ".", "bind", "(", "this", ",", "'New connection to relay started.'", ")", ")", ".", "on", "(", "'disconnect'", ",", "info", ".", "bind", "(", "this", ",", "'Connection to relay closed.'", ")", ")", ".", "on", "(", "'close'", ",", "info", ".", "bind", "(", "this", ",", "'Relay has closed.'", ")", ")", ";", "}" ]
Start a new relay from a pair of given ports @param {integer[]} portPair - [devicePort, relayPort]
[ "Start", "a", "new", "relay", "from", "a", "pair", "of", "given", "ports" ]
54cafd659947d3c7761e4498392a49ad73c2ad60
https://github.com/DeMille/node-usbmux/blob/54cafd659947d3c7761e4498392a49ad73c2ad60/bin/cli.js#L111-L127
train
Streampunk/ledger
model/Source.js
Source
function Source(id, version, label, description, format, caps, tags, device_id, parents) { // Globally unique identifier for the Source this.id = this.generateID(id); // String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating // precisely when an attribute of the resource last changed this.version = this.generateVersion(version); // Freeform string label for the Source this.label = this.generateLabel(label); // Detailed description of the Source this.description = this.generateDescription(description); // Format of the data coming from the Source as a URN this.format = this.generateFormat(format); // Capabilities (not yet defined) this.caps = this.generateCaps(caps); // Key value set of freeform string tags to aid in filtering Sources. Values // should be represented as an array of strings. Can be empty. this.tags = this.generateTags(tags); // Globally unique identifier for the Device which initially created the Source this.device_id = this.generateDeviceID(device_id); // Array of UUIDs representing the Source IDs of Grains which came together at // the input to this Source (may change over the lifetime of this Source) this.parents = this.generateParents(parents); return immutable(this, { prototype: Source.prototype }); }
javascript
function Source(id, version, label, description, format, caps, tags, device_id, parents) { // Globally unique identifier for the Source this.id = this.generateID(id); // String formatted PTP timestamp (<seconds>:<nanoseconds>) indicating // precisely when an attribute of the resource last changed this.version = this.generateVersion(version); // Freeform string label for the Source this.label = this.generateLabel(label); // Detailed description of the Source this.description = this.generateDescription(description); // Format of the data coming from the Source as a URN this.format = this.generateFormat(format); // Capabilities (not yet defined) this.caps = this.generateCaps(caps); // Key value set of freeform string tags to aid in filtering Sources. Values // should be represented as an array of strings. Can be empty. this.tags = this.generateTags(tags); // Globally unique identifier for the Device which initially created the Source this.device_id = this.generateDeviceID(device_id); // Array of UUIDs representing the Source IDs of Grains which came together at // the input to this Source (may change over the lifetime of this Source) this.parents = this.generateParents(parents); return immutable(this, { prototype: Source.prototype }); }
[ "function", "Source", "(", "id", ",", "version", ",", "label", ",", "description", ",", "format", ",", "caps", ",", "tags", ",", "device_id", ",", "parents", ")", "{", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "this", ".", "description", "=", "this", ".", "generateDescription", "(", "description", ")", ";", "this", ".", "format", "=", "this", ".", "generateFormat", "(", "format", ")", ";", "this", ".", "caps", "=", "this", ".", "generateCaps", "(", "caps", ")", ";", "this", ".", "tags", "=", "this", ".", "generateTags", "(", "tags", ")", ";", "this", ".", "device_id", "=", "this", ".", "generateDeviceID", "(", "device_id", ")", ";", "this", ".", "parents", "=", "this", ".", "generateParents", "(", "parents", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Source", ".", "prototype", "}", ")", ";", "}" ]
Describes a source
[ "Describes", "a", "source" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Source.js#L21-L46
train
Streampunk/ledger
api/RegistrationAPI.js
validStore
function validStore(store) { return store && typeof store.getNodes === 'function' && typeof store.getNode === 'function' && typeof store.getDevices === 'function' && typeof store.getDevice === 'function' && typeof store.getSources === 'function' && typeof store.getSource === 'function' && typeof store.getSenders === 'function' && typeof store.getSender === 'function' && typeof store.getReceivers === 'function' && typeof store.getReceiver === 'function' && typeof store.getFlows === 'function' && typeof store.getFlow === 'function'; // TODO add more of the required methods ... or drop this check? }
javascript
function validStore(store) { return store && typeof store.getNodes === 'function' && typeof store.getNode === 'function' && typeof store.getDevices === 'function' && typeof store.getDevice === 'function' && typeof store.getSources === 'function' && typeof store.getSource === 'function' && typeof store.getSenders === 'function' && typeof store.getSender === 'function' && typeof store.getReceivers === 'function' && typeof store.getReceiver === 'function' && typeof store.getFlows === 'function' && typeof store.getFlow === 'function'; // TODO add more of the required methods ... or drop this check? }
[ "function", "validStore", "(", "store", ")", "{", "return", "store", "&&", "typeof", "store", ".", "getNodes", "===", "'function'", "&&", "typeof", "store", ".", "getNode", "===", "'function'", "&&", "typeof", "store", ".", "getDevices", "===", "'function'", "&&", "typeof", "store", ".", "getDevice", "===", "'function'", "&&", "typeof", "store", ".", "getSources", "===", "'function'", "&&", "typeof", "store", ".", "getSource", "===", "'function'", "&&", "typeof", "store", ".", "getSenders", "===", "'function'", "&&", "typeof", "store", ".", "getSender", "===", "'function'", "&&", "typeof", "store", ".", "getReceivers", "===", "'function'", "&&", "typeof", "store", ".", "getReceiver", "===", "'function'", "&&", "typeof", "store", ".", "getFlows", "===", "'function'", "&&", "typeof", "store", ".", "getFlow", "===", "'function'", ";", "}" ]
Check that a store has a sufficient contract for this API
[ "Check", "that", "a", "store", "has", "a", "sufficient", "contract", "for", "this", "API" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/api/RegistrationAPI.js#L460-L475
train
Streampunk/ledger
api/NodeRAMStore.js
checkSkip
function checkSkip (skip, keys) { if (skip && typeof skip === 'string') skip = +skip; if (!skip || Number(skip) !== skip || skip % 1 !== 0 || skip < 0) skip = 0; if (skip > keys.length) skip = keys.length; return skip; }
javascript
function checkSkip (skip, keys) { if (skip && typeof skip === 'string') skip = +skip; if (!skip || Number(skip) !== skip || skip % 1 !== 0 || skip < 0) skip = 0; if (skip > keys.length) skip = keys.length; return skip; }
[ "function", "checkSkip", "(", "skip", ",", "keys", ")", "{", "if", "(", "skip", "&&", "typeof", "skip", "===", "'string'", ")", "skip", "=", "+", "skip", ";", "if", "(", "!", "skip", "||", "Number", "(", "skip", ")", "!==", "skip", "||", "skip", "%", "1", "!==", "0", "||", "skip", "<", "0", ")", "skip", "=", "0", ";", "if", "(", "skip", ">", "keys", ".", "length", ")", "skip", "=", "keys", ".", "length", ";", "return", "skip", ";", "}" ]
Check that the skip parameter is withing range, or set defaults
[ "Check", "that", "the", "skip", "parameter", "is", "withing", "range", "or", "set", "defaults" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/api/NodeRAMStore.js#L34-L41
train
Streampunk/ledger
api/NodeRAMStore.js
checkLimit
function checkLimit (limit, keys) { if (limit && typeof limit === 'string') limit = +limit; if (!limit || Number(limit) !== limit || limit % 1 !== 0 || limit > keys.length) limit = keys.length; if (limit < 0) limit = 0; return limit; }
javascript
function checkLimit (limit, keys) { if (limit && typeof limit === 'string') limit = +limit; if (!limit || Number(limit) !== limit || limit % 1 !== 0 || limit > keys.length) limit = keys.length; if (limit < 0) limit = 0; return limit; }
[ "function", "checkLimit", "(", "limit", ",", "keys", ")", "{", "if", "(", "limit", "&&", "typeof", "limit", "===", "'string'", ")", "limit", "=", "+", "limit", ";", "if", "(", "!", "limit", "||", "Number", "(", "limit", ")", "!==", "limit", "||", "limit", "%", "1", "!==", "0", "||", "limit", ">", "keys", ".", "length", ")", "limit", "=", "keys", ".", "length", ";", "if", "(", "limit", "<", "0", ")", "limit", "=", "0", ";", "return", "limit", ";", "}" ]
Check that the limit parameter is withing range, or set defaults
[ "Check", "that", "the", "limit", "parameter", "is", "withing", "range", "or", "set", "defaults" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/api/NodeRAMStore.js#L44-L51
train
Streampunk/ledger
api/NodeRAMStore.js
getCollection
function getCollection(items, query, cb, argsLength) { var skip = 0, limit = Number.MAX_SAFE_INTEGER; setImmediate(function() { if (argsLength === 1) { cb = query; } else { skip = (query.skip) ? query.skip : 0; limit = (query.limit) ? query.limit : Number.MAX_SAFE_INTEGER; } var sortedKeys = Object.keys(items); var qKeys = remove(remove(Object.keys(query), /skip/), /limit/); qKeys.forEach(function (k) { try { var re = new RegExp(query[k]); sortedKeys = sortedKeys.filter(function (l) { return items[l][k].toString().match(re); }); } catch (e) { console.error(`Problem filtering collection for parameter ${k}.`, e.message); } }); skip = checkSkip(skip, sortedKeys); limit = checkLimit(limit, sortedKeys); if (sortedKeys.length === 0 || limit === 0 || skip >= sortedKeys.length) { return cb(null, [], sortedKeys.length, 1, 1, 0); } var pages = Math.ceil(sortedKeys.length / limit); var pageOf = Math.ceil(skip / limit) + 1; var itemArray = new Array(); for ( var x = skip ; x < Math.min(skip + limit, sortedKeys.length) ; x++ ) { itemArray.push(items[sortedKeys[x]]); } cb(null, itemArray, sortedKeys.length, pageOf, pages, itemArray.length); }); }
javascript
function getCollection(items, query, cb, argsLength) { var skip = 0, limit = Number.MAX_SAFE_INTEGER; setImmediate(function() { if (argsLength === 1) { cb = query; } else { skip = (query.skip) ? query.skip : 0; limit = (query.limit) ? query.limit : Number.MAX_SAFE_INTEGER; } var sortedKeys = Object.keys(items); var qKeys = remove(remove(Object.keys(query), /skip/), /limit/); qKeys.forEach(function (k) { try { var re = new RegExp(query[k]); sortedKeys = sortedKeys.filter(function (l) { return items[l][k].toString().match(re); }); } catch (e) { console.error(`Problem filtering collection for parameter ${k}.`, e.message); } }); skip = checkSkip(skip, sortedKeys); limit = checkLimit(limit, sortedKeys); if (sortedKeys.length === 0 || limit === 0 || skip >= sortedKeys.length) { return cb(null, [], sortedKeys.length, 1, 1, 0); } var pages = Math.ceil(sortedKeys.length / limit); var pageOf = Math.ceil(skip / limit) + 1; var itemArray = new Array(); for ( var x = skip ; x < Math.min(skip + limit, sortedKeys.length) ; x++ ) { itemArray.push(items[sortedKeys[x]]); } cb(null, itemArray, sortedKeys.length, pageOf, pages, itemArray.length); }); }
[ "function", "getCollection", "(", "items", ",", "query", ",", "cb", ",", "argsLength", ")", "{", "var", "skip", "=", "0", ",", "limit", "=", "Number", ".", "MAX_SAFE_INTEGER", ";", "setImmediate", "(", "function", "(", ")", "{", "if", "(", "argsLength", "===", "1", ")", "{", "cb", "=", "query", ";", "}", "else", "{", "skip", "=", "(", "query", ".", "skip", ")", "?", "query", ".", "skip", ":", "0", ";", "limit", "=", "(", "query", ".", "limit", ")", "?", "query", ".", "limit", ":", "Number", ".", "MAX_SAFE_INTEGER", ";", "}", "var", "sortedKeys", "=", "Object", ".", "keys", "(", "items", ")", ";", "var", "qKeys", "=", "remove", "(", "remove", "(", "Object", ".", "keys", "(", "query", ")", ",", "/", "skip", "/", ")", ",", "/", "limit", "/", ")", ";", "qKeys", ".", "forEach", "(", "function", "(", "k", ")", "{", "try", "{", "var", "re", "=", "new", "RegExp", "(", "query", "[", "k", "]", ")", ";", "sortedKeys", "=", "sortedKeys", ".", "filter", "(", "function", "(", "l", ")", "{", "return", "items", "[", "l", "]", "[", "k", "]", ".", "toString", "(", ")", ".", "match", "(", "re", ")", ";", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "`", "${", "k", "}", "`", ",", "e", ".", "message", ")", ";", "}", "}", ")", ";", "skip", "=", "checkSkip", "(", "skip", ",", "sortedKeys", ")", ";", "limit", "=", "checkLimit", "(", "limit", ",", "sortedKeys", ")", ";", "if", "(", "sortedKeys", ".", "length", "===", "0", "||", "limit", "===", "0", "||", "skip", ">=", "sortedKeys", ".", "length", ")", "{", "return", "cb", "(", "null", ",", "[", "]", ",", "sortedKeys", ".", "length", ",", "1", ",", "1", ",", "0", ")", ";", "}", "var", "pages", "=", "Math", ".", "ceil", "(", "sortedKeys", ".", "length", "/", "limit", ")", ";", "var", "pageOf", "=", "Math", ".", "ceil", "(", "skip", "/", "limit", ")", "+", "1", ";", "var", "itemArray", "=", "new", "Array", "(", ")", ";", "for", "(", "var", "x", "=", "skip", ";", "x", "<", "Math", ".", "min", "(", "skip", "+", "limit", ",", "sortedKeys", ".", "length", ")", ";", "x", "++", ")", "{", "itemArray", ".", "push", "(", "items", "[", "sortedKeys", "[", "x", "]", "]", ")", ";", "}", "cb", "(", "null", ",", "itemArray", ",", "sortedKeys", ".", "length", ",", "pageOf", ",", "pages", ",", "itemArray", ".", "length", ")", ";", "}", ")", ";", "}" ]
Generic get collection methods that returns an ordered sequence of items
[ "Generic", "get", "collection", "methods", "that", "returns", "an", "ordered", "sequence", "of", "items" ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/api/NodeRAMStore.js#L68-L103
train
Streampunk/ledger
model/Node.js
Node
function Node(id, version, label, href, hostname, caps, services) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * HTTP access href for the Node's API. * @type {string} * @readonly */ this.href = this.generateHref(href); /** * Node hostname - set to null when not present. * @type {string} * @readonly */ this.hostname = this.generateHostname(hostname); /** * [Capabilities]{@link capabilities} (not yet defined). * @type {Object} * @readonly */ this.caps = this.generateCaps(caps); /** * Array of objects containing a URN format type and href. * @type {Object[]} * @readonly */ this.services = this.generateServices(services); return immutable(this, { prototype : Node.prototype }); }
javascript
function Node(id, version, label, href, hostname, caps, services) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * HTTP access href for the Node's API. * @type {string} * @readonly */ this.href = this.generateHref(href); /** * Node hostname - set to null when not present. * @type {string} * @readonly */ this.hostname = this.generateHostname(hostname); /** * [Capabilities]{@link capabilities} (not yet defined). * @type {Object} * @readonly */ this.caps = this.generateCaps(caps); /** * Array of objects containing a URN format type and href. * @type {Object[]} * @readonly */ this.services = this.generateServices(services); return immutable(this, { prototype : Node.prototype }); }
[ "function", "Node", "(", "id", ",", "version", ",", "label", ",", "href", ",", "hostname", ",", "caps", ",", "services", ")", "{", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "this", ".", "href", "=", "this", ".", "generateHref", "(", "href", ")", ";", "this", ".", "hostname", "=", "this", ".", "generateHostname", "(", "hostname", ")", ";", "this", ".", "caps", "=", "this", ".", "generateCaps", "(", "caps", ")", ";", "this", ".", "services", "=", "this", ".", "generateServices", "(", "services", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Node", ".", "prototype", "}", ")", ";", "}" ]
Describes a Node. Immutable value. @constructor @augments Versionned @param {string} id Globally unique UUID identifier for the Node. @param {string} version String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;) indicating precisely when an attribute of the resource last changed. @param {string} label Freeform string label for the Node. @param {string} href HTTP access href for the Node's API. @param {string} hostname Node hostname - set to null when not present. @param {Object} caps [Capabilities]{@link capabilities} (not yet defined). @param {Object[]} services Array of objects containing a URN format type and href.
[ "Describes", "a", "Node", ".", "Immutable", "value", "." ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Node.js#L37-L66
train
Streampunk/ledger
model/Flow.js
Flow
function Flow(id, version, label, description, format, tags, source_id, parents) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * Detailed description of the Flow. * @type {string} * @readonly */ this.description = this.generateDescription(description); /** * [Format]{@link formats} of the data coming from the Flow as a URN. * @type {string} * @readonly */ this.format = this.generateFormat(format); /** * Key value set of freeform string tags to aid in filtering Flows. Can be * empty. * @type {Array.<string, string[]>} * @readonly */ this.tags = this.generateTags(tags); // Treating as a required property /** * Globally unique UUID identifier for the [source]{@link Source} which initially * created the Flow. * @type {string} * @readonly */ this.source_id = this.generateSourceID(source_id); /** * Array of UUIDs representing the Flow IDs of Grains which came together to * generate this Flow. (May change over the lifetime of this Flow.) */ this.parents = this.generateParents(parents); return immutable(this, { prototype: Flow.prototype }); }
javascript
function Flow(id, version, label, description, format, tags, source_id, parents) { this.id = this.generateID(id); this.version = this.generateVersion(version); this.label = this.generateLabel(label); /** * Detailed description of the Flow. * @type {string} * @readonly */ this.description = this.generateDescription(description); /** * [Format]{@link formats} of the data coming from the Flow as a URN. * @type {string} * @readonly */ this.format = this.generateFormat(format); /** * Key value set of freeform string tags to aid in filtering Flows. Can be * empty. * @type {Array.<string, string[]>} * @readonly */ this.tags = this.generateTags(tags); // Treating as a required property /** * Globally unique UUID identifier for the [source]{@link Source} which initially * created the Flow. * @type {string} * @readonly */ this.source_id = this.generateSourceID(source_id); /** * Array of UUIDs representing the Flow IDs of Grains which came together to * generate this Flow. (May change over the lifetime of this Flow.) */ this.parents = this.generateParents(parents); return immutable(this, { prototype: Flow.prototype }); }
[ "function", "Flow", "(", "id", ",", "version", ",", "label", ",", "description", ",", "format", ",", "tags", ",", "source_id", ",", "parents", ")", "{", "this", ".", "id", "=", "this", ".", "generateID", "(", "id", ")", ";", "this", ".", "version", "=", "this", ".", "generateVersion", "(", "version", ")", ";", "this", ".", "label", "=", "this", ".", "generateLabel", "(", "label", ")", ";", "this", ".", "description", "=", "this", ".", "generateDescription", "(", "description", ")", ";", "this", ".", "format", "=", "this", ".", "generateFormat", "(", "format", ")", ";", "this", ".", "tags", "=", "this", ".", "generateTags", "(", "tags", ")", ";", "this", ".", "source_id", "=", "this", ".", "generateSourceID", "(", "source_id", ")", ";", "this", ".", "parents", "=", "this", ".", "generateParents", "(", "parents", ")", ";", "return", "immutable", "(", "this", ",", "{", "prototype", ":", "Flow", ".", "prototype", "}", ")", ";", "}" ]
Describes a Flow Describes a Flow. Immutable value. @constructor @augments Versionned @param {string} id Globally unique UUID identifier for the Flow. @param {string} version String formatted PTP timestamp (&lt;<em>seconds</em>&gt;:&lt;<em>nanoseconds</em>&gt;) indicating precisely when an attribute of the resource last changed. @param {string} label Freeform string label for the Flow. @param {string} description Detailed description of the Flow. @param {string} format [Format]{@link formats} of the data coming from the Flow as a URN. @param {Object.<string, string[]>} tags Key value set of freeform string tags to aid in filtering Flows. Can be empty. @param {string} source_id Globally unique UUID for the [source]{@link Source} which initially created the Flow. @param {string[]} parents Array of UUIDs representing the Flow IDs of Grains which came together to generate this Flow. (May change over the lifetime of this Flow).
[ "Describes", "a", "Flow", "Describes", "a", "Flow", ".", "Immutable", "value", "." ]
561ee93e15e8620d505bfcddfbe357375f5d0e07
https://github.com/Streampunk/ledger/blob/561ee93e15e8620d505bfcddfbe357375f5d0e07/model/Flow.js#L42-L79
train
SINTEF-9012/Proto2TypeScript
command.js
generateNames
function generateNames(model, prefix, name) { if (name === void 0) { name = ""; } model.fullPackageName = prefix + (name != "." ? name : ""); // Copies the settings (I'm lazy) model.properties = argv.properties; model.explicitRequired = argv.explicitRequired; model.camelCaseProperties = argv.camelCaseProperties; model.camelCaseGetSet = argv.camelCaseGetSet; model.underscoreGetSet = argv.underscoreGetSet; model.generateBuilders = argv.generateBuilders; var newDefinitions = {}; // Generate names for messages // Recursive call for all messages var key; for (key in model.messages) { var message = model.messages[key]; newDefinitions[message.name] = "Builder"; generateNames(message, model.fullPackageName, "." + (model.name ? model.name : "")); } // Generate names for enums for (key in model.enums) { var currentEnum = model.enums[key]; newDefinitions[currentEnum.name] = ""; currentEnum.fullPackageName = model.fullPackageName + (model.name ? "." + model.name : ""); } // For fields of types which are defined in the same message, // update the field type in consequence for (key in model.fields) { var field = model.fields[key]; if (typeof newDefinitions[field.type] !== "undefined") { field.type = model.name + "." + field.type; } } model.oneofsArray = []; for (key in model.oneofs) { var oneof = model.oneofs[key]; model.oneofsArray.push({ name: key, value: oneof }); } // Add the new definitions in the model for generate builders var definitions = []; for (key in newDefinitions) { definitions.push({ name: key, type: ((model.name ? (model.name + ".") : "") + key) + newDefinitions[key] }); } model.definitions = definitions; }
javascript
function generateNames(model, prefix, name) { if (name === void 0) { name = ""; } model.fullPackageName = prefix + (name != "." ? name : ""); // Copies the settings (I'm lazy) model.properties = argv.properties; model.explicitRequired = argv.explicitRequired; model.camelCaseProperties = argv.camelCaseProperties; model.camelCaseGetSet = argv.camelCaseGetSet; model.underscoreGetSet = argv.underscoreGetSet; model.generateBuilders = argv.generateBuilders; var newDefinitions = {}; // Generate names for messages // Recursive call for all messages var key; for (key in model.messages) { var message = model.messages[key]; newDefinitions[message.name] = "Builder"; generateNames(message, model.fullPackageName, "." + (model.name ? model.name : "")); } // Generate names for enums for (key in model.enums) { var currentEnum = model.enums[key]; newDefinitions[currentEnum.name] = ""; currentEnum.fullPackageName = model.fullPackageName + (model.name ? "." + model.name : ""); } // For fields of types which are defined in the same message, // update the field type in consequence for (key in model.fields) { var field = model.fields[key]; if (typeof newDefinitions[field.type] !== "undefined") { field.type = model.name + "." + field.type; } } model.oneofsArray = []; for (key in model.oneofs) { var oneof = model.oneofs[key]; model.oneofsArray.push({ name: key, value: oneof }); } // Add the new definitions in the model for generate builders var definitions = []; for (key in newDefinitions) { definitions.push({ name: key, type: ((model.name ? (model.name + ".") : "") + key) + newDefinitions[key] }); } model.definitions = definitions; }
[ "function", "generateNames", "(", "model", ",", "prefix", ",", "name", ")", "{", "if", "(", "name", "===", "void", "0", ")", "{", "name", "=", "\"\"", ";", "}", "model", ".", "fullPackageName", "=", "prefix", "+", "(", "name", "!=", "\".\"", "?", "name", ":", "\"\"", ")", ";", "model", ".", "properties", "=", "argv", ".", "properties", ";", "model", ".", "explicitRequired", "=", "argv", ".", "explicitRequired", ";", "model", ".", "camelCaseProperties", "=", "argv", ".", "camelCaseProperties", ";", "model", ".", "camelCaseGetSet", "=", "argv", ".", "camelCaseGetSet", ";", "model", ".", "underscoreGetSet", "=", "argv", ".", "underscoreGetSet", ";", "model", ".", "generateBuilders", "=", "argv", ".", "generateBuilders", ";", "var", "newDefinitions", "=", "{", "}", ";", "var", "key", ";", "for", "(", "key", "in", "model", ".", "messages", ")", "{", "var", "message", "=", "model", ".", "messages", "[", "key", "]", ";", "newDefinitions", "[", "message", ".", "name", "]", "=", "\"Builder\"", ";", "generateNames", "(", "message", ",", "model", ".", "fullPackageName", ",", "\".\"", "+", "(", "model", ".", "name", "?", "model", ".", "name", ":", "\"\"", ")", ")", ";", "}", "for", "(", "key", "in", "model", ".", "enums", ")", "{", "var", "currentEnum", "=", "model", ".", "enums", "[", "key", "]", ";", "newDefinitions", "[", "currentEnum", ".", "name", "]", "=", "\"\"", ";", "currentEnum", ".", "fullPackageName", "=", "model", ".", "fullPackageName", "+", "(", "model", ".", "name", "?", "\".\"", "+", "model", ".", "name", ":", "\"\"", ")", ";", "}", "for", "(", "key", "in", "model", ".", "fields", ")", "{", "var", "field", "=", "model", ".", "fields", "[", "key", "]", ";", "if", "(", "typeof", "newDefinitions", "[", "field", ".", "type", "]", "!==", "\"undefined\"", ")", "{", "field", ".", "type", "=", "model", ".", "name", "+", "\".\"", "+", "field", ".", "type", ";", "}", "}", "model", ".", "oneofsArray", "=", "[", "]", ";", "for", "(", "key", "in", "model", ".", "oneofs", ")", "{", "var", "oneof", "=", "model", ".", "oneofs", "[", "key", "]", ";", "model", ".", "oneofsArray", ".", "push", "(", "{", "name", ":", "key", ",", "value", ":", "oneof", "}", ")", ";", "}", "var", "definitions", "=", "[", "]", ";", "for", "(", "key", "in", "newDefinitions", ")", "{", "definitions", ".", "push", "(", "{", "name", ":", "key", ",", "type", ":", "(", "(", "model", ".", "name", "?", "(", "model", ".", "name", "+", "\".\"", ")", ":", "\"\"", ")", "+", "key", ")", "+", "newDefinitions", "[", "key", "]", "}", ")", ";", "}", "model", ".", "definitions", "=", "definitions", ";", "}" ]
Generate the names for the model, the types, and the interfaces
[ "Generate", "the", "names", "for", "the", "model", "the", "types", "and", "the", "interfaces" ]
d96cfd3dc7afcdbea86114cefca1a761fe0d59ca
https://github.com/SINTEF-9012/Proto2TypeScript/blob/d96cfd3dc7afcdbea86114cefca1a761fe0d59ca/command.js#L83-L127
train
elsehow/signal-protocol
src/curve25519_wrapper.js
_allocate
function _allocate(bytes) { var address = Module._malloc(bytes.length); Module.HEAPU8.set(bytes, address); return address; }
javascript
function _allocate(bytes) { var address = Module._malloc(bytes.length); Module.HEAPU8.set(bytes, address); return address; }
[ "function", "_allocate", "(", "bytes", ")", "{", "var", "address", "=", "Module", ".", "_malloc", "(", "bytes", ".", "length", ")", ";", "Module", ".", "HEAPU8", ".", "set", "(", "bytes", ",", "address", ")", ";", "return", "address", ";", "}" ]
Insert some bytes into the emscripten memory and return a pointer
[ "Insert", "some", "bytes", "into", "the", "emscripten", "memory", "and", "return", "a", "pointer" ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/src/curve25519_wrapper.js#L7-L12
train
elsehow/signal-protocol
build/curve25519_compiled.js
doRun
function doRun() { if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening Module['calledRun'] = true; if (ABORT) return; ensureInitRuntime(); preMain(); if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized'](); if (Module['_main'] && shouldRunNow) Module['callMain'](args); postRun(); }
javascript
function doRun() { if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening Module['calledRun'] = true; if (ABORT) return; ensureInitRuntime(); preMain(); if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized'](); if (Module['_main'] && shouldRunNow) Module['callMain'](args); postRun(); }
[ "function", "doRun", "(", ")", "{", "if", "(", "Module", "[", "'calledRun'", "]", ")", "return", ";", "Module", "[", "'calledRun'", "]", "=", "true", ";", "if", "(", "ABORT", ")", "return", ";", "ensureInitRuntime", "(", ")", ";", "preMain", "(", ")", ";", "if", "(", "Module", "[", "'onRuntimeInitialized'", "]", ")", "Module", "[", "'onRuntimeInitialized'", "]", "(", ")", ";", "if", "(", "Module", "[", "'_main'", "]", "&&", "shouldRunNow", ")", "Module", "[", "'callMain'", "]", "(", "args", ")", ";", "postRun", "(", ")", ";", "}" ]
run may have just been called through dependencies being fulfilled just in this very frame
[ "run", "may", "have", "just", "been", "called", "through", "dependencies", "being", "fulfilled", "just", "in", "this", "very", "frame" ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/curve25519_compiled.js#L20596-L20612
train
doublemarked/loopback-console
repl.js
wrapReplEval
function wrapReplEval(replServer) { const defaultEval = replServer.eval; return function(code, context, file, cb) { return defaultEval.call(this, code, context, file, (err, result) => { if (!result || !result.then) { return cb(err, result); } result.then(resolved => { resolvePromises(result, resolved); cb(null, resolved); }).catch(err => { resolvePromises(result, err); console.log('\x1b[31m' + '[Promise Rejection]' + '\x1b[0m'); if (err && err.message) { console.log('\x1b[31m' + err.message + '\x1b[0m'); } // Application errors are not REPL errors cb(null, err); }); }); function resolvePromises(promise, resolved) { Object.keys(context).forEach(key => { // Replace any promise handles in the REPL context with the resolved promise if (context[key] === promise) { context[key] = resolved; } }); } }; }
javascript
function wrapReplEval(replServer) { const defaultEval = replServer.eval; return function(code, context, file, cb) { return defaultEval.call(this, code, context, file, (err, result) => { if (!result || !result.then) { return cb(err, result); } result.then(resolved => { resolvePromises(result, resolved); cb(null, resolved); }).catch(err => { resolvePromises(result, err); console.log('\x1b[31m' + '[Promise Rejection]' + '\x1b[0m'); if (err && err.message) { console.log('\x1b[31m' + err.message + '\x1b[0m'); } // Application errors are not REPL errors cb(null, err); }); }); function resolvePromises(promise, resolved) { Object.keys(context).forEach(key => { // Replace any promise handles in the REPL context with the resolved promise if (context[key] === promise) { context[key] = resolved; } }); } }; }
[ "function", "wrapReplEval", "(", "replServer", ")", "{", "const", "defaultEval", "=", "replServer", ".", "eval", ";", "return", "function", "(", "code", ",", "context", ",", "file", ",", "cb", ")", "{", "return", "defaultEval", ".", "call", "(", "this", ",", "code", ",", "context", ",", "file", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "!", "result", "||", "!", "result", ".", "then", ")", "{", "return", "cb", "(", "err", ",", "result", ")", ";", "}", "result", ".", "then", "(", "resolved", "=>", "{", "resolvePromises", "(", "result", ",", "resolved", ")", ";", "cb", "(", "null", ",", "resolved", ")", ";", "}", ")", ".", "catch", "(", "err", "=>", "{", "resolvePromises", "(", "result", ",", "err", ")", ";", "console", ".", "log", "(", "'\\x1b[31m'", "+", "\\x1b", "+", "'[Promise Rejection]'", ")", ";", "'\\x1b[0m'", "\\x1b", "}", ")", ";", "}", ")", ";", "if", "(", "err", "&&", "err", ".", "message", ")", "{", "console", ".", "log", "(", "'\\x1b[31m'", "+", "\\x1b", "+", "err", ".", "message", ")", ";", "}", "}", ";", "}" ]
Wrap the default eval with a handler that resolves promises
[ "Wrap", "the", "default", "eval", "with", "a", "handler", "that", "resolves", "promises" ]
b3259ad6bd79ef9c529ca07b2a72bf998925cff4
https://github.com/doublemarked/loopback-console/blob/b3259ad6bd79ef9c529ca07b2a72bf998925cff4/repl.js#L101-L135
train
TheRoSS/mongodb-autoincrement
index.js
getNextId
function getNextId(db, collectionName, fieldName, callback) { if (typeof fieldName == "function") { callback = fieldName; fieldName = null; } fieldName = fieldName || getOption(collectionName, "field"); var collection = db.collection(defaultSettings.collection); var step = getOption(collectionName, "step"); collection.findAndModify( {_id: collectionName, field: fieldName}, null, {$inc: {seq: step}}, {upsert: true, new: true}, function (err, result) { if (err) { if (err.code == 11000) { process.nextTick(getNextId.bind(null, db, collectionName, fieldName, callback)); } else { callback(err); } } else { if (result.value && result.value.seq) { callback(null, result.value.seq); } else { callback(null, result.seq); } } } ); }
javascript
function getNextId(db, collectionName, fieldName, callback) { if (typeof fieldName == "function") { callback = fieldName; fieldName = null; } fieldName = fieldName || getOption(collectionName, "field"); var collection = db.collection(defaultSettings.collection); var step = getOption(collectionName, "step"); collection.findAndModify( {_id: collectionName, field: fieldName}, null, {$inc: {seq: step}}, {upsert: true, new: true}, function (err, result) { if (err) { if (err.code == 11000) { process.nextTick(getNextId.bind(null, db, collectionName, fieldName, callback)); } else { callback(err); } } else { if (result.value && result.value.seq) { callback(null, result.value.seq); } else { callback(null, result.seq); } } } ); }
[ "function", "getNextId", "(", "db", ",", "collectionName", ",", "fieldName", ",", "callback", ")", "{", "if", "(", "typeof", "fieldName", "==", "\"function\"", ")", "{", "callback", "=", "fieldName", ";", "fieldName", "=", "null", ";", "}", "fieldName", "=", "fieldName", "||", "getOption", "(", "collectionName", ",", "\"field\"", ")", ";", "var", "collection", "=", "db", ".", "collection", "(", "defaultSettings", ".", "collection", ")", ";", "var", "step", "=", "getOption", "(", "collectionName", ",", "\"step\"", ")", ";", "collection", ".", "findAndModify", "(", "{", "_id", ":", "collectionName", ",", "field", ":", "fieldName", "}", ",", "null", ",", "{", "$inc", ":", "{", "seq", ":", "step", "}", "}", ",", "{", "upsert", ":", "true", ",", "new", ":", "true", "}", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "if", "(", "err", ".", "code", "==", "11000", ")", "{", "process", ".", "nextTick", "(", "getNextId", ".", "bind", "(", "null", ",", "db", ",", "collectionName", ",", "fieldName", ",", "callback", ")", ")", ";", "}", "else", "{", "callback", "(", "err", ")", ";", "}", "}", "else", "{", "if", "(", "result", ".", "value", "&&", "result", ".", "value", ".", "seq", ")", "{", "callback", "(", "null", ",", "result", ".", "value", ".", "seq", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "result", ".", "seq", ")", ";", "}", "}", "}", ")", ";", "}" ]
Get next auto increment index for the given collection @param {MongodbNativeDriver} db @param {String} collectionName @param {String} [fieldName] @param {Function} callback
[ "Get", "next", "auto", "increment", "index", "for", "the", "given", "collection" ]
b36f0a172cc17b7d1bc0bfaa9ee48a7a57c30803
https://github.com/TheRoSS/mongodb-autoincrement/blob/b36f0a172cc17b7d1bc0bfaa9ee48a7a57c30803/index.js#L102-L133
train
elsehow/signal-protocol
build/components_concat.js
mkNumber
function mkNumber(val) { var sign = 1; if (val.charAt(0) == '-') { sign = -1; val = val.substring(1); } if (Lang.NUMBER_DEC.test(val)) return sign * parseInt(val, 10); else if (Lang.NUMBER_HEX.test(val)) return sign * parseInt(val.substring(2), 16); else if (Lang.NUMBER_OCT.test(val)) return sign * parseInt(val.substring(1), 8); else if (val === 'inf') return sign * Infinity; else if (val === 'nan') return NaN; else if (Lang.NUMBER_FLT.test(val)) return sign * parseFloat(val); throw Error("illegal number value: " + (sign < 0 ? '-' : '') + val); }
javascript
function mkNumber(val) { var sign = 1; if (val.charAt(0) == '-') { sign = -1; val = val.substring(1); } if (Lang.NUMBER_DEC.test(val)) return sign * parseInt(val, 10); else if (Lang.NUMBER_HEX.test(val)) return sign * parseInt(val.substring(2), 16); else if (Lang.NUMBER_OCT.test(val)) return sign * parseInt(val.substring(1), 8); else if (val === 'inf') return sign * Infinity; else if (val === 'nan') return NaN; else if (Lang.NUMBER_FLT.test(val)) return sign * parseFloat(val); throw Error("illegal number value: " + (sign < 0 ? '-' : '') + val); }
[ "function", "mkNumber", "(", "val", ")", "{", "var", "sign", "=", "1", ";", "if", "(", "val", ".", "charAt", "(", "0", ")", "==", "'-'", ")", "{", "sign", "=", "-", "1", ";", "val", "=", "val", ".", "substring", "(", "1", ")", ";", "}", "if", "(", "Lang", ".", "NUMBER_DEC", ".", "test", "(", "val", ")", ")", "return", "sign", "*", "parseInt", "(", "val", ",", "10", ")", ";", "else", "if", "(", "Lang", ".", "NUMBER_HEX", ".", "test", "(", "val", ")", ")", "return", "sign", "*", "parseInt", "(", "val", ".", "substring", "(", "2", ")", ",", "16", ")", ";", "else", "if", "(", "Lang", ".", "NUMBER_OCT", ".", "test", "(", "val", ")", ")", "return", "sign", "*", "parseInt", "(", "val", ".", "substring", "(", "1", ")", ",", "8", ")", ";", "else", "if", "(", "val", "===", "'inf'", ")", "return", "sign", "*", "Infinity", ";", "else", "if", "(", "val", "===", "'nan'", ")", "return", "NaN", ";", "else", "if", "(", "Lang", ".", "NUMBER_FLT", ".", "test", "(", "val", ")", ")", "return", "sign", "*", "parseFloat", "(", "val", ")", ";", "throw", "Error", "(", "\"illegal number value: \"", "+", "(", "sign", "<", "0", "?", "'-'", ":", "''", ")", "+", "val", ")", ";", "}" ]
Converts a numerical string to a number. @param {string} val @returns {number} @inner
[ "Converts", "a", "numerical", "string", "to", "a", "number", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L5340-L5359
train
elsehow/signal-protocol
build/components_concat.js
setOption
function setOption(options, name, value) { if (typeof options[name] === 'undefined') options[name] = value; else { if (!Array.isArray(options[name])) options[name] = [ options[name] ]; options[name].push(value); } }
javascript
function setOption(options, name, value) { if (typeof options[name] === 'undefined') options[name] = value; else { if (!Array.isArray(options[name])) options[name] = [ options[name] ]; options[name].push(value); } }
[ "function", "setOption", "(", "options", ",", "name", ",", "value", ")", "{", "if", "(", "typeof", "options", "[", "name", "]", "===", "'undefined'", ")", "options", "[", "name", "]", "=", "value", ";", "else", "{", "if", "(", "!", "Array", ".", "isArray", "(", "options", "[", "name", "]", ")", ")", "options", "[", "name", "]", "=", "[", "options", "[", "name", "]", "]", ";", "options", "[", "name", "]", ".", "push", "(", "value", ")", ";", "}", "}" ]
Sets an option on the specified options object. @param {!Object.<string,*>} options @param {string} name @param {string|number|boolean} value @inner
[ "Sets", "an", "option", "on", "the", "specified", "options", "object", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L5447-L5455
train
elsehow/signal-protocol
build/components_concat.js
function(builder, parent, name) { /** * Builder reference. * @type {!ProtoBuf.Builder} * @expose */ this.builder = builder; /** * Parent object. * @type {?ProtoBuf.Reflect.T} * @expose */ this.parent = parent; /** * Object name in namespace. * @type {string} * @expose */ this.name = name; /** * Fully qualified class name * @type {string} * @expose */ this.className; }
javascript
function(builder, parent, name) { /** * Builder reference. * @type {!ProtoBuf.Builder} * @expose */ this.builder = builder; /** * Parent object. * @type {?ProtoBuf.Reflect.T} * @expose */ this.parent = parent; /** * Object name in namespace. * @type {string} * @expose */ this.name = name; /** * Fully qualified class name * @type {string} * @expose */ this.className; }
[ "function", "(", "builder", ",", "parent", ",", "name", ")", "{", "this", ".", "builder", "=", "builder", ";", "this", ".", "parent", "=", "parent", ";", "this", ".", "name", "=", "name", ";", "this", ".", "className", ";", "}" ]
Constructs a Reflect base class. @exports ProtoBuf.Reflect.T @constructor @abstract @param {!ProtoBuf.Builder} builder Builder reference @param {?ProtoBuf.Reflect.T} parent Parent object @param {string} name Object name
[ "Constructs", "a", "Reflect", "base", "class", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L5910-L5939
train
elsehow/signal-protocol
build/components_concat.js
function(builder, parent, name, options, syntax) { T.call(this, builder, parent, name); /** * @override */ this.className = "Namespace"; /** * Children inside the namespace. * @type {!Array.<ProtoBuf.Reflect.T>} */ this.children = []; /** * Options. * @type {!Object.<string, *>} */ this.options = options || {}; /** * Syntax level (e.g., proto2 or proto3). * @type {!string} */ this.syntax = syntax || "proto2"; }
javascript
function(builder, parent, name, options, syntax) { T.call(this, builder, parent, name); /** * @override */ this.className = "Namespace"; /** * Children inside the namespace. * @type {!Array.<ProtoBuf.Reflect.T>} */ this.children = []; /** * Options. * @type {!Object.<string, *>} */ this.options = options || {}; /** * Syntax level (e.g., proto2 or proto3). * @type {!string} */ this.syntax = syntax || "proto2"; }
[ "function", "(", "builder", ",", "parent", ",", "name", ",", "options", ",", "syntax", ")", "{", "T", ".", "call", "(", "this", ",", "builder", ",", "parent", ",", "name", ")", ";", "this", ".", "className", "=", "\"Namespace\"", ";", "this", ".", "children", "=", "[", "]", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "syntax", "=", "syntax", "||", "\"proto2\"", ";", "}" ]
Constructs a new Namespace. @exports ProtoBuf.Reflect.Namespace @param {!ProtoBuf.Builder} builder Builder reference @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent @param {string} name Namespace name @param {Object.<string,*>=} options Namespace options @param {string?} syntax The syntax level of this definition (e.g., proto3) @constructor @extends ProtoBuf.Reflect.T
[ "Constructs", "a", "new", "Namespace", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L6000-L6025
train
elsehow/signal-protocol
build/components_concat.js
function(type, resolvedType, isMapKey, syntax) { /** * Element type, as a string (e.g., int32). * @type {{name: string, wireType: number}} */ this.type = type; /** * Element type reference to submessage or enum definition, if needed. * @type {ProtoBuf.Reflect.T|null} */ this.resolvedType = resolvedType; /** * Element is a map key. * @type {boolean} */ this.isMapKey = isMapKey; /** * Syntax level of defining message type, e.g., proto2 or proto3. * @type {string} */ this.syntax = syntax; if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0) throw Error("Invalid map key type: " + type.name); }
javascript
function(type, resolvedType, isMapKey, syntax) { /** * Element type, as a string (e.g., int32). * @type {{name: string, wireType: number}} */ this.type = type; /** * Element type reference to submessage or enum definition, if needed. * @type {ProtoBuf.Reflect.T|null} */ this.resolvedType = resolvedType; /** * Element is a map key. * @type {boolean} */ this.isMapKey = isMapKey; /** * Syntax level of defining message type, e.g., proto2 or proto3. * @type {string} */ this.syntax = syntax; if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0) throw Error("Invalid map key type: " + type.name); }
[ "function", "(", "type", ",", "resolvedType", ",", "isMapKey", ",", "syntax", ")", "{", "this", ".", "type", "=", "type", ";", "this", ".", "resolvedType", "=", "resolvedType", ";", "this", ".", "isMapKey", "=", "isMapKey", ";", "this", ".", "syntax", "=", "syntax", ";", "if", "(", "isMapKey", "&&", "ProtoBuf", ".", "MAP_KEY_TYPES", ".", "indexOf", "(", "type", ")", "<", "0", ")", "throw", "Error", "(", "\"Invalid map key type: \"", "+", "type", ".", "name", ")", ";", "}" ]
Constructs a new Element implementation that checks and converts values for a particular field type, as appropriate. An Element represents a single value: either the value of a singular field, or a value contained in one entry of a repeated field or map field. This class does not implement these higher-level concepts; it only encapsulates the low-level typechecking and conversion. @exports ProtoBuf.Reflect.Element @param {{name: string, wireType: number}} type Resolved data type @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant (e.g. submessage field). @param {boolean} isMapKey Is this element a Map key? The value will be converted to string form if so. @param {string} syntax Syntax level of defining message type, e.g., proto2 or proto3. @constructor
[ "Constructs", "a", "new", "Element", "implementation", "that", "checks", "and", "converts", "values", "for", "a", "particular", "field", "type", "as", "appropriate", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L6218-L6246
train
elsehow/signal-protocol
build/components_concat.js
mkLong
function mkLong(value, unsigned) { if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean' && value.low === value.low && value.high === value.high) return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned); if (typeof value === 'string') return ProtoBuf.Long.fromString(value, unsigned || false, 10); if (typeof value === 'number') return ProtoBuf.Long.fromNumber(value, unsigned || false); throw Error("not convertible to Long"); }
javascript
function mkLong(value, unsigned) { if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean' && value.low === value.low && value.high === value.high) return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned); if (typeof value === 'string') return ProtoBuf.Long.fromString(value, unsigned || false, 10); if (typeof value === 'number') return ProtoBuf.Long.fromNumber(value, unsigned || false); throw Error("not convertible to Long"); }
[ "function", "mkLong", "(", "value", ",", "unsigned", ")", "{", "if", "(", "value", "&&", "typeof", "value", ".", "low", "===", "'number'", "&&", "typeof", "value", ".", "high", "===", "'number'", "&&", "typeof", "value", ".", "unsigned", "===", "'boolean'", "&&", "value", ".", "low", "===", "value", ".", "low", "&&", "value", ".", "high", "===", "value", ".", "high", ")", "return", "new", "ProtoBuf", ".", "Long", "(", "value", ".", "low", ",", "value", ".", "high", ",", "typeof", "unsigned", "===", "'undefined'", "?", "value", ".", "unsigned", ":", "unsigned", ")", ";", "if", "(", "typeof", "value", "===", "'string'", ")", "return", "ProtoBuf", ".", "Long", ".", "fromString", "(", "value", ",", "unsigned", "||", "false", ",", "10", ")", ";", "if", "(", "typeof", "value", "===", "'number'", ")", "return", "ProtoBuf", ".", "Long", ".", "fromNumber", "(", "value", ",", "unsigned", "||", "false", ")", ";", "throw", "Error", "(", "\"not convertible to Long\"", ")", ";", "}" ]
Makes a Long from a value. @param {{low: number, high: number, unsigned: boolean}|string|number} value Value @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for strings and numbers @returns {!Long} @throws {Error} If the value cannot be converted to a Long @inner
[ "Makes", "a", "Long", "from", "a", "value", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L6283-L6292
train
elsehow/signal-protocol
build/components_concat.js
function(builder, parent, name, options, isGroup, syntax) { Namespace.call(this, builder, parent, name, options, syntax); /** * @override */ this.className = "Message"; /** * Extensions range. * @type {!Array.<number>|undefined} * @expose */ this.extensions = undefined; /** * Runtime message class. * @type {?function(new:ProtoBuf.Builder.Message)} * @expose */ this.clazz = null; /** * Whether this is a legacy group or not. * @type {boolean} * @expose */ this.isGroup = !!isGroup; // The following cached collections are used to efficiently iterate over or look up fields when decoding. /** * Cached fields. * @type {?Array.<!ProtoBuf.Reflect.Message.Field>} * @private */ this._fields = null; /** * Cached fields by id. * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>} * @private */ this._fieldsById = null; /** * Cached fields by name. * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>} * @private */ this._fieldsByName = null; }
javascript
function(builder, parent, name, options, isGroup, syntax) { Namespace.call(this, builder, parent, name, options, syntax); /** * @override */ this.className = "Message"; /** * Extensions range. * @type {!Array.<number>|undefined} * @expose */ this.extensions = undefined; /** * Runtime message class. * @type {?function(new:ProtoBuf.Builder.Message)} * @expose */ this.clazz = null; /** * Whether this is a legacy group or not. * @type {boolean} * @expose */ this.isGroup = !!isGroup; // The following cached collections are used to efficiently iterate over or look up fields when decoding. /** * Cached fields. * @type {?Array.<!ProtoBuf.Reflect.Message.Field>} * @private */ this._fields = null; /** * Cached fields by id. * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>} * @private */ this._fieldsById = null; /** * Cached fields by name. * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>} * @private */ this._fieldsByName = null; }
[ "function", "(", "builder", ",", "parent", ",", "name", ",", "options", ",", "isGroup", ",", "syntax", ")", "{", "Namespace", ".", "call", "(", "this", ",", "builder", ",", "parent", ",", "name", ",", "options", ",", "syntax", ")", ";", "this", ".", "className", "=", "\"Message\"", ";", "this", ".", "extensions", "=", "undefined", ";", "this", ".", "clazz", "=", "null", ";", "this", ".", "isGroup", "=", "!", "!", "isGroup", ";", "this", ".", "_fields", "=", "null", ";", "this", ".", "_fieldsById", "=", "null", ";", "this", ".", "_fieldsByName", "=", "null", ";", "}" ]
Constructs a new Message. @exports ProtoBuf.Reflect.Message @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace @param {string} name Message name @param {Object.<string,*>=} options Message options @param {boolean=} isGroup `true` if this is a legacy group @param {string?} syntax The syntax level of this definition (e.g., proto3) @constructor @extends ProtoBuf.Reflect.Namespace
[ "Constructs", "a", "new", "Message", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L6786-L6837
train
elsehow/signal-protocol
build/components_concat.js
function(values, var_args) { ProtoBuf.Builder.Message.call(this); // Create virtual oneof properties for (var i=0, k=oneofs.length; i<k; ++i) this[oneofs[i].name] = null; // Create fields and set default values for (i=0, k=fields.length; i<k; ++i) { var field = fields[i]; this[field.name] = field.repeated ? [] : (field.map ? new ProtoBuf.Map(field) : null); if ((field.required || T.syntax === 'proto3') && field.defaultValue !== null) this[field.name] = field.defaultValue; } if (arguments.length > 0) { var value; // Set field values from a values object if (arguments.length === 1 && values !== null && typeof values === 'object' && /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) && /* not a repeated field */ !Array.isArray(values) && /* not a Map */ !(values instanceof ProtoBuf.Map) && /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) && /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) && /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) { this.$set(values); } else // Set field values from arguments, in declaration order for (i=0, k=arguments.length; i<k; ++i) if (typeof (value = arguments[i]) !== 'undefined') this.$set(fields[i].name, value); // May throw } }
javascript
function(values, var_args) { ProtoBuf.Builder.Message.call(this); // Create virtual oneof properties for (var i=0, k=oneofs.length; i<k; ++i) this[oneofs[i].name] = null; // Create fields and set default values for (i=0, k=fields.length; i<k; ++i) { var field = fields[i]; this[field.name] = field.repeated ? [] : (field.map ? new ProtoBuf.Map(field) : null); if ((field.required || T.syntax === 'proto3') && field.defaultValue !== null) this[field.name] = field.defaultValue; } if (arguments.length > 0) { var value; // Set field values from a values object if (arguments.length === 1 && values !== null && typeof values === 'object' && /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) && /* not a repeated field */ !Array.isArray(values) && /* not a Map */ !(values instanceof ProtoBuf.Map) && /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) && /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) && /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) { this.$set(values); } else // Set field values from arguments, in declaration order for (i=0, k=arguments.length; i<k; ++i) if (typeof (value = arguments[i]) !== 'undefined') this.$set(fields[i].name, value); // May throw } }
[ "function", "(", "values", ",", "var_args", ")", "{", "ProtoBuf", ".", "Builder", ".", "Message", ".", "call", "(", "this", ")", ";", "for", "(", "var", "i", "=", "0", ",", "k", "=", "oneofs", ".", "length", ";", "i", "<", "k", ";", "++", "i", ")", "this", "[", "oneofs", "[", "i", "]", ".", "name", "]", "=", "null", ";", "for", "(", "i", "=", "0", ",", "k", "=", "fields", ".", "length", ";", "i", "<", "k", ";", "++", "i", ")", "{", "var", "field", "=", "fields", "[", "i", "]", ";", "this", "[", "field", ".", "name", "]", "=", "field", ".", "repeated", "?", "[", "]", ":", "(", "field", ".", "map", "?", "new", "ProtoBuf", ".", "Map", "(", "field", ")", ":", "null", ")", ";", "if", "(", "(", "field", ".", "required", "||", "T", ".", "syntax", "===", "'proto3'", ")", "&&", "field", ".", "defaultValue", "!==", "null", ")", "this", "[", "field", ".", "name", "]", "=", "field", ".", "defaultValue", ";", "}", "if", "(", "arguments", ".", "length", ">", "0", ")", "{", "var", "value", ";", "if", "(", "arguments", ".", "length", "===", "1", "&&", "values", "!==", "null", "&&", "typeof", "values", "===", "'object'", "&&", "(", "typeof", "values", ".", "encode", "!==", "'function'", "||", "values", "instanceof", "Message", ")", "&&", "!", "Array", ".", "isArray", "(", "values", ")", "&&", "!", "(", "values", "instanceof", "ProtoBuf", ".", "Map", ")", "&&", "!", "ByteBuffer", ".", "isByteBuffer", "(", "values", ")", "&&", "!", "(", "values", "instanceof", "ArrayBuffer", ")", "&&", "!", "(", "ProtoBuf", ".", "Long", "&&", "values", "instanceof", "ProtoBuf", ".", "Long", ")", ")", "{", "this", ".", "$set", "(", "values", ")", ";", "}", "else", "for", "(", "i", "=", "0", ",", "k", "=", "arguments", ".", "length", ";", "i", "<", "k", ";", "++", "i", ")", "if", "(", "typeof", "(", "value", "=", "arguments", "[", "i", "]", ")", "!==", "'undefined'", ")", "this", ".", "$set", "(", "fields", "[", "i", "]", ".", "name", ",", "value", ")", ";", "}", "}" ]
Constructs a new runtime Message. @name ProtoBuf.Builder.Message @class Barebone of all runtime messages. @param {!Object.<string,*>|string} values Preset values @param {...string} var_args @constructor @throws {Error} If the message cannot be created
[ "Constructs", "a", "new", "runtime", "Message", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L6872-L6905
train
elsehow/signal-protocol
build/components_concat.js
cloneRaw
function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) { if (obj === null || typeof obj !== 'object') { // Convert enum values to their respective names if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) { var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj); if (name !== null) return name; } // Pass-through string, number, boolean, null... return obj; } // Convert ByteBuffers to raw buffer or strings if (ByteBuffer.isByteBuffer(obj)) return binaryAsBase64 ? obj.toBase64() : obj.toBuffer(); // Convert Longs to proper objects or strings if (ProtoBuf.Long.isLong(obj)) return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj); var clone; // Clone arrays if (Array.isArray(obj)) { clone = []; obj.forEach(function(v, k) { clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType); }); return clone; } clone = {}; // Convert maps to objects if (obj instanceof ProtoBuf.Map) { var it = obj.entries(); for (var e = it.next(); !e.done; e = it.next()) clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType); return clone; } // Everything else is a non-null object var type = obj.$type, field = undefined; for (var i in obj) if (obj.hasOwnProperty(i)) { if (type && (field = type.getChild(i))) clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType); else clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings); } return clone; }
javascript
function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) { if (obj === null || typeof obj !== 'object') { // Convert enum values to their respective names if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) { var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj); if (name !== null) return name; } // Pass-through string, number, boolean, null... return obj; } // Convert ByteBuffers to raw buffer or strings if (ByteBuffer.isByteBuffer(obj)) return binaryAsBase64 ? obj.toBase64() : obj.toBuffer(); // Convert Longs to proper objects or strings if (ProtoBuf.Long.isLong(obj)) return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj); var clone; // Clone arrays if (Array.isArray(obj)) { clone = []; obj.forEach(function(v, k) { clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType); }); return clone; } clone = {}; // Convert maps to objects if (obj instanceof ProtoBuf.Map) { var it = obj.entries(); for (var e = it.next(); !e.done; e = it.next()) clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType); return clone; } // Everything else is a non-null object var type = obj.$type, field = undefined; for (var i in obj) if (obj.hasOwnProperty(i)) { if (type && (field = type.getChild(i))) clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType); else clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings); } return clone; }
[ "function", "cloneRaw", "(", "obj", ",", "binaryAsBase64", ",", "longsAsStrings", ",", "resolvedType", ")", "{", "if", "(", "obj", "===", "null", "||", "typeof", "obj", "!==", "'object'", ")", "{", "if", "(", "resolvedType", "&&", "resolvedType", "instanceof", "ProtoBuf", ".", "Reflect", ".", "Enum", ")", "{", "var", "name", "=", "ProtoBuf", ".", "Reflect", ".", "Enum", ".", "getName", "(", "resolvedType", ".", "object", ",", "obj", ")", ";", "if", "(", "name", "!==", "null", ")", "return", "name", ";", "}", "return", "obj", ";", "}", "if", "(", "ByteBuffer", ".", "isByteBuffer", "(", "obj", ")", ")", "return", "binaryAsBase64", "?", "obj", ".", "toBase64", "(", ")", ":", "obj", ".", "toBuffer", "(", ")", ";", "if", "(", "ProtoBuf", ".", "Long", ".", "isLong", "(", "obj", ")", ")", "return", "longsAsStrings", "?", "obj", ".", "toString", "(", ")", ":", "ProtoBuf", ".", "Long", ".", "fromValue", "(", "obj", ")", ";", "var", "clone", ";", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "clone", "=", "[", "]", ";", "obj", ".", "forEach", "(", "function", "(", "v", ",", "k", ")", "{", "clone", "[", "k", "]", "=", "cloneRaw", "(", "v", ",", "binaryAsBase64", ",", "longsAsStrings", ",", "resolvedType", ")", ";", "}", ")", ";", "return", "clone", ";", "}", "clone", "=", "{", "}", ";", "if", "(", "obj", "instanceof", "ProtoBuf", ".", "Map", ")", "{", "var", "it", "=", "obj", ".", "entries", "(", ")", ";", "for", "(", "var", "e", "=", "it", ".", "next", "(", ")", ";", "!", "e", ".", "done", ";", "e", "=", "it", ".", "next", "(", ")", ")", "clone", "[", "obj", ".", "keyElem", ".", "valueToString", "(", "e", ".", "value", "[", "0", "]", ")", "]", "=", "cloneRaw", "(", "e", ".", "value", "[", "1", "]", ",", "binaryAsBase64", ",", "longsAsStrings", ",", "obj", ".", "valueElem", ".", "resolvedType", ")", ";", "return", "clone", ";", "}", "var", "type", "=", "obj", ".", "$type", ",", "field", "=", "undefined", ";", "for", "(", "var", "i", "in", "obj", ")", "if", "(", "obj", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "if", "(", "type", "&&", "(", "field", "=", "type", ".", "getChild", "(", "i", ")", ")", ")", "clone", "[", "i", "]", "=", "cloneRaw", "(", "obj", "[", "i", "]", ",", "binaryAsBase64", ",", "longsAsStrings", ",", "field", ".", "resolvedType", ")", ";", "else", "clone", "[", "i", "]", "=", "cloneRaw", "(", "obj", "[", "i", "]", ",", "binaryAsBase64", ",", "longsAsStrings", ")", ";", "}", "return", "clone", ";", "}" ]
Clones a message object or field value to a raw object. @param {*} obj Object to clone @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise @param {boolean} longsAsStrings Whether to encode longs as strings @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field @returns {*} Cloned object @inner
[ "Clones", "a", "message", "object", "or", "field", "value", "to", "a", "raw", "object", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L7341-L7386
train
elsehow/signal-protocol
build/components_concat.js
skipTillGroupEnd
function skipTillGroupEnd(expectedId, buf) { var tag = buf.readVarint32(), // Throws on OOB wireType = tag & 0x07, id = tag >>> 3; switch (wireType) { case ProtoBuf.WIRE_TYPES.VARINT: do tag = buf.readUint8(); while ((tag & 0x80) === 0x80); break; case ProtoBuf.WIRE_TYPES.BITS64: buf.offset += 8; break; case ProtoBuf.WIRE_TYPES.LDELIM: tag = buf.readVarint32(); // reads the varint buf.offset += tag; // skips n bytes break; case ProtoBuf.WIRE_TYPES.STARTGROUP: skipTillGroupEnd(id, buf); break; case ProtoBuf.WIRE_TYPES.ENDGROUP: if (id === expectedId) return false; else throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)"); case ProtoBuf.WIRE_TYPES.BITS32: buf.offset += 4; break; default: throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType); } return true; }
javascript
function skipTillGroupEnd(expectedId, buf) { var tag = buf.readVarint32(), // Throws on OOB wireType = tag & 0x07, id = tag >>> 3; switch (wireType) { case ProtoBuf.WIRE_TYPES.VARINT: do tag = buf.readUint8(); while ((tag & 0x80) === 0x80); break; case ProtoBuf.WIRE_TYPES.BITS64: buf.offset += 8; break; case ProtoBuf.WIRE_TYPES.LDELIM: tag = buf.readVarint32(); // reads the varint buf.offset += tag; // skips n bytes break; case ProtoBuf.WIRE_TYPES.STARTGROUP: skipTillGroupEnd(id, buf); break; case ProtoBuf.WIRE_TYPES.ENDGROUP: if (id === expectedId) return false; else throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)"); case ProtoBuf.WIRE_TYPES.BITS32: buf.offset += 4; break; default: throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType); } return true; }
[ "function", "skipTillGroupEnd", "(", "expectedId", ",", "buf", ")", "{", "var", "tag", "=", "buf", ".", "readVarint32", "(", ")", ",", "wireType", "=", "tag", "&", "0x07", ",", "id", "=", "tag", ">>>", "3", ";", "switch", "(", "wireType", ")", "{", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "VARINT", ":", "do", "tag", "=", "buf", ".", "readUint8", "(", ")", ";", "while", "(", "(", "tag", "&", "0x80", ")", "===", "0x80", ")", ";", "break", ";", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "BITS64", ":", "buf", ".", "offset", "+=", "8", ";", "break", ";", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "LDELIM", ":", "tag", "=", "buf", ".", "readVarint32", "(", ")", ";", "buf", ".", "offset", "+=", "tag", ";", "break", ";", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "STARTGROUP", ":", "skipTillGroupEnd", "(", "id", ",", "buf", ")", ";", "break", ";", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "ENDGROUP", ":", "if", "(", "id", "===", "expectedId", ")", "return", "false", ";", "else", "throw", "Error", "(", "\"Illegal GROUPEND after unknown group: \"", "+", "id", "+", "\" (\"", "+", "expectedId", "+", "\" expected)\"", ")", ";", "case", "ProtoBuf", ".", "WIRE_TYPES", ".", "BITS32", ":", "buf", ".", "offset", "+=", "4", ";", "break", ";", "default", ":", "throw", "Error", "(", "\"Illegal wire type in unknown group \"", "+", "expectedId", "+", "\": \"", "+", "wireType", ")", ";", "}", "return", "true", ";", "}" ]
Skips all data until the end of the specified group has been reached. @param {number} expectedId Expected GROUPEND id @param {!ByteBuffer} buf ByteBuffer @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch) @inner
[ "Skips", "all", "data", "until", "the", "end", "of", "the", "specified", "group", "has", "been", "reached", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L7656-L7687
train
elsehow/signal-protocol
build/components_concat.js
function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) { T.call(this, builder, message, name); /** * @override */ this.className = "Message.Field"; /** * Message field required flag. * @type {boolean} * @expose */ this.required = rule === "required"; /** * Message field repeated flag. * @type {boolean} * @expose */ this.repeated = rule === "repeated"; /** * Message field map flag. * @type {boolean} * @expose */ this.map = rule === "map"; /** * Message field key type. Type reference string if unresolved, protobuf * type if resolved. Valid only if this.map === true, null otherwise. * @type {string|{name: string, wireType: number}|null} * @expose */ this.keyType = keytype || null; /** * Message field type. Type reference string if unresolved, protobuf type if * resolved. In a map field, this is the value type. * @type {string|{name: string, wireType: number}} * @expose */ this.type = type; /** * Resolved type reference inside the global namespace. * @type {ProtoBuf.Reflect.T|null} * @expose */ this.resolvedType = null; /** * Unique message field id. * @type {number} * @expose */ this.id = id; /** * Message field options. * @type {!Object.<string,*>} * @dict * @expose */ this.options = options || {}; /** * Default value. * @type {*} * @expose */ this.defaultValue = null; /** * Enclosing OneOf. * @type {?ProtoBuf.Reflect.Message.OneOf} * @expose */ this.oneof = oneof || null; /** * Syntax level of this definition (e.g., proto3). * @type {string} * @expose */ this.syntax = syntax || 'proto2'; /** * Original field name. * @type {string} * @expose */ this.originalName = this.name; // Used to revert camelcase transformation on naming collisions /** * Element implementation. Created in build() after types are resolved. * @type {ProtoBuf.Element} * @expose */ this.element = null; /** * Key element implementation, for map fields. Created in build() after * types are resolved. * @type {ProtoBuf.Element} * @expose */ this.keyElement = null; // Convert field names to camel case notation if the override is set if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField)) this.name = ProtoBuf.Util.toCamelCase(this.name); }
javascript
function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) { T.call(this, builder, message, name); /** * @override */ this.className = "Message.Field"; /** * Message field required flag. * @type {boolean} * @expose */ this.required = rule === "required"; /** * Message field repeated flag. * @type {boolean} * @expose */ this.repeated = rule === "repeated"; /** * Message field map flag. * @type {boolean} * @expose */ this.map = rule === "map"; /** * Message field key type. Type reference string if unresolved, protobuf * type if resolved. Valid only if this.map === true, null otherwise. * @type {string|{name: string, wireType: number}|null} * @expose */ this.keyType = keytype || null; /** * Message field type. Type reference string if unresolved, protobuf type if * resolved. In a map field, this is the value type. * @type {string|{name: string, wireType: number}} * @expose */ this.type = type; /** * Resolved type reference inside the global namespace. * @type {ProtoBuf.Reflect.T|null} * @expose */ this.resolvedType = null; /** * Unique message field id. * @type {number} * @expose */ this.id = id; /** * Message field options. * @type {!Object.<string,*>} * @dict * @expose */ this.options = options || {}; /** * Default value. * @type {*} * @expose */ this.defaultValue = null; /** * Enclosing OneOf. * @type {?ProtoBuf.Reflect.Message.OneOf} * @expose */ this.oneof = oneof || null; /** * Syntax level of this definition (e.g., proto3). * @type {string} * @expose */ this.syntax = syntax || 'proto2'; /** * Original field name. * @type {string} * @expose */ this.originalName = this.name; // Used to revert camelcase transformation on naming collisions /** * Element implementation. Created in build() after types are resolved. * @type {ProtoBuf.Element} * @expose */ this.element = null; /** * Key element implementation, for map fields. Created in build() after * types are resolved. * @type {ProtoBuf.Element} * @expose */ this.keyElement = null; // Convert field names to camel case notation if the override is set if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField)) this.name = ProtoBuf.Util.toCamelCase(this.name); }
[ "function", "(", "builder", ",", "message", ",", "rule", ",", "keytype", ",", "type", ",", "name", ",", "id", ",", "options", ",", "oneof", ",", "syntax", ")", "{", "T", ".", "call", "(", "this", ",", "builder", ",", "message", ",", "name", ")", ";", "this", ".", "className", "=", "\"Message.Field\"", ";", "this", ".", "required", "=", "rule", "===", "\"required\"", ";", "this", ".", "repeated", "=", "rule", "===", "\"repeated\"", ";", "this", ".", "map", "=", "rule", "===", "\"map\"", ";", "this", ".", "keyType", "=", "keytype", "||", "null", ";", "this", ".", "type", "=", "type", ";", "this", ".", "resolvedType", "=", "null", ";", "this", ".", "id", "=", "id", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "defaultValue", "=", "null", ";", "this", ".", "oneof", "=", "oneof", "||", "null", ";", "this", ".", "syntax", "=", "syntax", "||", "'proto2'", ";", "this", ".", "originalName", "=", "this", ".", "name", ";", "this", ".", "element", "=", "null", ";", "this", ".", "keyElement", "=", "null", ";", "if", "(", "this", ".", "builder", ".", "options", "[", "'convertFieldsToCamelCase'", "]", "&&", "!", "(", "this", "instanceof", "Message", ".", "ExtensionField", ")", ")", "this", ".", "name", "=", "ProtoBuf", ".", "Util", ".", "toCamelCase", "(", "this", ".", "name", ")", ";", "}" ]
Constructs a new Message Field. @exports ProtoBuf.Reflect.Message.Field @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Message} message Message reference @param {string} rule Rule, one of requried, optional, repeated @param {string?} keytype Key data type, if any. @param {string} type Data type, e.g. int32 @param {string} name Field name @param {number} id Unique field id @param {Object.<string,*>=} options Options @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf @param {string?} syntax The syntax level of this definition (e.g., proto3) @constructor @extends ProtoBuf.Reflect.T
[ "Constructs", "a", "new", "Message", "Field", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L7791-L7904
train
elsehow/signal-protocol
build/components_concat.js
function(builder, message, rule, type, name, id, options) { Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options); /** * Extension reference. * @type {!ProtoBuf.Reflect.Extension} * @expose */ this.extension; }
javascript
function(builder, message, rule, type, name, id, options) { Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options); /** * Extension reference. * @type {!ProtoBuf.Reflect.Extension} * @expose */ this.extension; }
[ "function", "(", "builder", ",", "message", ",", "rule", ",", "type", ",", "name", ",", "id", ",", "options", ")", "{", "Field", ".", "call", "(", "this", ",", "builder", ",", "message", ",", "rule", ",", "null", ",", "type", ",", "name", ",", "id", ",", "options", ")", ";", "this", ".", "extension", ";", "}" ]
Constructs a new Message ExtensionField. @exports ProtoBuf.Reflect.Message.ExtensionField @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Message} message Message reference @param {string} rule Rule, one of requried, optional, repeated @param {string} type Data type, e.g. int32 @param {string} name Field name @param {number} id Unique field id @param {!Object.<string,*>=} options Options @constructor @extends ProtoBuf.Reflect.Message.Field
[ "Constructs", "a", "new", "Message", "ExtensionField", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8253-L8262
train
elsehow/signal-protocol
build/components_concat.js
function(builder, parent, name, options, syntax) { Namespace.call(this, builder, parent, name, options, syntax); /** * @override */ this.className = "Enum"; /** * Runtime enum object. * @type {Object.<string,number>|null} * @expose */ this.object = null; }
javascript
function(builder, parent, name, options, syntax) { Namespace.call(this, builder, parent, name, options, syntax); /** * @override */ this.className = "Enum"; /** * Runtime enum object. * @type {Object.<string,number>|null} * @expose */ this.object = null; }
[ "function", "(", "builder", ",", "parent", ",", "name", ",", "options", ",", "syntax", ")", "{", "Namespace", ".", "call", "(", "this", ",", "builder", ",", "parent", ",", "name", ",", "options", ",", "syntax", ")", ";", "this", ".", "className", "=", "\"Enum\"", ";", "this", ".", "object", "=", "null", ";", "}" ]
Constructs a new Enum. @exports ProtoBuf.Reflect.Enum @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.T} parent Parent Reflect object @param {string} name Enum name @param {Object.<string,*>=} options Enum options @param {string?} syntax The syntax level (e.g., proto3) @constructor @extends ProtoBuf.Reflect.Namespace
[ "Constructs", "a", "new", "Enum", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8310-L8324
train
elsehow/signal-protocol
build/components_concat.js
function(builder, enm, name, id) { T.call(this, builder, enm, name); /** * @override */ this.className = "Enum.Value"; /** * Unique enum value id. * @type {number} * @expose */ this.id = id; }
javascript
function(builder, enm, name, id) { T.call(this, builder, enm, name); /** * @override */ this.className = "Enum.Value"; /** * Unique enum value id. * @type {number} * @expose */ this.id = id; }
[ "function", "(", "builder", ",", "enm", ",", "name", ",", "id", ")", "{", "T", ".", "call", "(", "this", ",", "builder", ",", "enm", ",", "name", ")", ";", "this", ".", "className", "=", "\"Enum.Value\"", ";", "this", ".", "id", "=", "id", ";", "}" ]
Constructs a new Enum Value. @exports ProtoBuf.Reflect.Enum.Value @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Enum} enm Enum reference @param {string} name Field name @param {number} id Unique field id @constructor @extends ProtoBuf.Reflect.T
[ "Constructs", "a", "new", "Enum", "Value", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8384-L8398
train
elsehow/signal-protocol
build/components_concat.js
function(builder, root, name, options) { Namespace.call(this, builder, root, name, options); /** * @override */ this.className = "Service"; /** * Built runtime service class. * @type {?function(new:ProtoBuf.Builder.Service)} */ this.clazz = null; }
javascript
function(builder, root, name, options) { Namespace.call(this, builder, root, name, options); /** * @override */ this.className = "Service"; /** * Built runtime service class. * @type {?function(new:ProtoBuf.Builder.Service)} */ this.clazz = null; }
[ "function", "(", "builder", ",", "root", ",", "name", ",", "options", ")", "{", "Namespace", ".", "call", "(", "this", ",", "builder", ",", "root", ",", "name", ",", "options", ")", ";", "this", ".", "className", "=", "\"Service\"", ";", "this", ".", "clazz", "=", "null", ";", "}" ]
Constructs a new Service. @exports ProtoBuf.Reflect.Service @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Namespace} root Root @param {string} name Service name @param {Object.<string,*>=} options Options @constructor @extends ProtoBuf.Reflect.Namespace
[ "Constructs", "a", "new", "Service", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8448-L8461
train
elsehow/signal-protocol
build/components_concat.js
function(rpcImpl) { ProtoBuf.Builder.Service.call(this); /** * Service implementation. * @name ProtoBuf.Builder.Service#rpcImpl * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} * @expose */ this.rpcImpl = rpcImpl || function(name, msg, callback) { // This is what a user has to implement: A function receiving the method name, the actual message to // send (type checked) and the callback that's either provided with the error as its first // argument or null and the actual response message. setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async! }; }
javascript
function(rpcImpl) { ProtoBuf.Builder.Service.call(this); /** * Service implementation. * @name ProtoBuf.Builder.Service#rpcImpl * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} * @expose */ this.rpcImpl = rpcImpl || function(name, msg, callback) { // This is what a user has to implement: A function receiving the method name, the actual message to // send (type checked) and the callback that's either provided with the error as its first // argument or null and the actual response message. setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async! }; }
[ "function", "(", "rpcImpl", ")", "{", "ProtoBuf", ".", "Builder", ".", "Service", ".", "call", "(", "this", ")", ";", "this", ".", "rpcImpl", "=", "rpcImpl", "||", "function", "(", "name", ",", "msg", ",", "callback", ")", "{", "setTimeout", "(", "callback", ".", "bind", "(", "this", ",", "Error", "(", "\"Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services\"", ")", ")", ",", "0", ")", ";", "}", ";", "}" ]
Constructs a new runtime Service. @name ProtoBuf.Builder.Service @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message @class Barebone of all runtime services. @constructor @throws {Error} If the service cannot be created
[ "Constructs", "a", "new", "runtime", "Service", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8492-L8507
train
elsehow/signal-protocol
build/components_concat.js
function(builder, svc, name, options) { T.call(this, builder, svc, name); /** * @override */ this.className = "Service.Method"; /** * Options. * @type {Object.<string, *>} * @expose */ this.options = options || {}; }
javascript
function(builder, svc, name, options) { T.call(this, builder, svc, name); /** * @override */ this.className = "Service.Method"; /** * Options. * @type {Object.<string, *>} * @expose */ this.options = options || {}; }
[ "function", "(", "builder", ",", "svc", ",", "name", ",", "options", ")", "{", "T", ".", "call", "(", "this", ",", "builder", ",", "svc", ",", "name", ")", ";", "this", ".", "className", "=", "\"Service.Method\"", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "}" ]
Abstract service method. @exports ProtoBuf.Reflect.Service.Method @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Service} svc Service @param {string} name Method name @param {Object.<string,*>=} options Options @constructor @extends ProtoBuf.Reflect.T
[ "Abstract", "service", "method", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8646-L8660
train
elsehow/signal-protocol
build/components_concat.js
function(builder, svc, name, request, response, request_stream, response_stream, options) { Method.call(this, builder, svc, name, options); /** * @override */ this.className = "Service.RPCMethod"; /** * Request message name. * @type {string} * @expose */ this.requestName = request; /** * Response message name. * @type {string} * @expose */ this.responseName = response; /** * Whether requests are streamed * @type {bool} * @expose */ this.requestStream = request_stream; /** * Whether responses are streamed * @type {bool} * @expose */ this.responseStream = response_stream; /** * Resolved request message type. * @type {ProtoBuf.Reflect.Message} * @expose */ this.resolvedRequestType = null; /** * Resolved response message type. * @type {ProtoBuf.Reflect.Message} * @expose */ this.resolvedResponseType = null; }
javascript
function(builder, svc, name, request, response, request_stream, response_stream, options) { Method.call(this, builder, svc, name, options); /** * @override */ this.className = "Service.RPCMethod"; /** * Request message name. * @type {string} * @expose */ this.requestName = request; /** * Response message name. * @type {string} * @expose */ this.responseName = response; /** * Whether requests are streamed * @type {bool} * @expose */ this.requestStream = request_stream; /** * Whether responses are streamed * @type {bool} * @expose */ this.responseStream = response_stream; /** * Resolved request message type. * @type {ProtoBuf.Reflect.Message} * @expose */ this.resolvedRequestType = null; /** * Resolved response message type. * @type {ProtoBuf.Reflect.Message} * @expose */ this.resolvedResponseType = null; }
[ "function", "(", "builder", ",", "svc", ",", "name", ",", "request", ",", "response", ",", "request_stream", ",", "response_stream", ",", "options", ")", "{", "Method", ".", "call", "(", "this", ",", "builder", ",", "svc", ",", "name", ",", "options", ")", ";", "this", ".", "className", "=", "\"Service.RPCMethod\"", ";", "this", ".", "requestName", "=", "request", ";", "this", ".", "responseName", "=", "response", ";", "this", ".", "requestStream", "=", "request_stream", ";", "this", ".", "responseStream", "=", "response_stream", ";", "this", ".", "resolvedRequestType", "=", "null", ";", "this", ".", "resolvedResponseType", "=", "null", ";", "}" ]
RPC service method. @exports ProtoBuf.Reflect.Service.RPCMethod @param {!ProtoBuf.Builder} builder Builder reference @param {!ProtoBuf.Reflect.Service} svc Service @param {string} name Method name @param {string} request Request message name @param {string} response Response message name @param {boolean} request_stream Whether requests are streamed @param {boolean} response_stream Whether responses are streamed @param {Object.<string,*>=} options Options @constructor @extends ProtoBuf.Reflect.Service.Method
[ "RPC", "service", "method", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8696-L8745
train
elsehow/signal-protocol
build/components_concat.js
function(options) { /** * Namespace. * @type {ProtoBuf.Reflect.Namespace} * @expose */ this.ns = new Reflect.Namespace(this, null, ""); // Global namespace /** * Namespace pointer. * @type {ProtoBuf.Reflect.T} * @expose */ this.ptr = this.ns; /** * Resolved flag. * @type {boolean} * @expose */ this.resolved = false; /** * The current building result. * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null} * @expose */ this.result = null; /** * Imported files. * @type {Array.<string>} * @expose */ this.files = {}; /** * Import root override. * @type {?string} * @expose */ this.importRoot = null; /** * Options. * @type {!Object.<string, *>} * @expose */ this.options = options || {}; }
javascript
function(options) { /** * Namespace. * @type {ProtoBuf.Reflect.Namespace} * @expose */ this.ns = new Reflect.Namespace(this, null, ""); // Global namespace /** * Namespace pointer. * @type {ProtoBuf.Reflect.T} * @expose */ this.ptr = this.ns; /** * Resolved flag. * @type {boolean} * @expose */ this.resolved = false; /** * The current building result. * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null} * @expose */ this.result = null; /** * Imported files. * @type {Array.<string>} * @expose */ this.files = {}; /** * Import root override. * @type {?string} * @expose */ this.importRoot = null; /** * Options. * @type {!Object.<string, *>} * @expose */ this.options = options || {}; }
[ "function", "(", "options", ")", "{", "this", ".", "ns", "=", "new", "Reflect", ".", "Namespace", "(", "this", ",", "null", ",", "\"\"", ")", ";", "this", ".", "ptr", "=", "this", ".", "ns", ";", "this", ".", "resolved", "=", "false", ";", "this", ".", "result", "=", "null", ";", "this", ".", "files", "=", "{", "}", ";", "this", ".", "importRoot", "=", "null", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "}" ]
Constructs a new Builder. @exports ProtoBuf.Builder @class Provides the functionality to build protocol messages. @param {Object.<string,*>=} options Options @constructor
[ "Constructs", "a", "new", "Builder", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L8774-L8824
train
elsehow/signal-protocol
build/components_concat.js
propagateSyntax
function propagateSyntax(parent) { if (parent['messages']) { parent['messages'].forEach(function(child) { child["syntax"] = parent["syntax"]; propagateSyntax(child); }); } if (parent['enums']) { parent['enums'].forEach(function(child) { child["syntax"] = parent["syntax"]; }); } }
javascript
function propagateSyntax(parent) { if (parent['messages']) { parent['messages'].forEach(function(child) { child["syntax"] = parent["syntax"]; propagateSyntax(child); }); } if (parent['enums']) { parent['enums'].forEach(function(child) { child["syntax"] = parent["syntax"]; }); } }
[ "function", "propagateSyntax", "(", "parent", ")", "{", "if", "(", "parent", "[", "'messages'", "]", ")", "{", "parent", "[", "'messages'", "]", ".", "forEach", "(", "function", "(", "child", ")", "{", "child", "[", "\"syntax\"", "]", "=", "parent", "[", "\"syntax\"", "]", ";", "propagateSyntax", "(", "child", ")", ";", "}", ")", ";", "}", "if", "(", "parent", "[", "'enums'", "]", ")", "{", "parent", "[", "'enums'", "]", ".", "forEach", "(", "function", "(", "child", ")", "{", "child", "[", "\"syntax\"", "]", "=", "parent", "[", "\"syntax\"", "]", ";", "}", ")", ";", "}", "}" ]
Propagates syntax to all children. @param {!Object} parent @inner
[ "Propagates", "syntax", "to", "all", "children", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L9097-L9109
train
elsehow/signal-protocol
build/components_concat.js
function(field, contents) { if (!field.map) throw Error("field is not a map"); /** * The field corresponding to this map. * @type {!ProtoBuf.Reflect.Field} */ this.field = field; /** * Element instance corresponding to key type. * @type {!ProtoBuf.Reflect.Element} */ this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax); /** * Element instance corresponding to value type. * @type {!ProtoBuf.Reflect.Element} */ this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax); /** * Internal map: stores mapping of (string form of key) -> (key, value) * pair. * * We provide map semantics for arbitrary key types, but we build on top * of an Object, which has only string keys. In order to avoid the need * to convert a string key back to its native type in many situations, * we store the native key value alongside the value. Thus, we only need * a one-way mapping from a key type to its string form that guarantees * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1 * === K2). * * @type {!Object<string, {key: *, value: *}>} */ this.map = {}; /** * Returns the number of elements in the map. */ Object.defineProperty(this, "size", { get: function() { return Object.keys(this.map).length; } }); // Fill initial contents from a raw object. if (contents) { var keys = Object.keys(contents); for (var i = 0; i < keys.length; i++) { var key = this.keyElem.valueFromString(keys[i]); var val = this.valueElem.verifyValue(contents[keys[i]]); this.map[this.keyElem.valueToString(key)] = { key: key, value: val }; } } }
javascript
function(field, contents) { if (!field.map) throw Error("field is not a map"); /** * The field corresponding to this map. * @type {!ProtoBuf.Reflect.Field} */ this.field = field; /** * Element instance corresponding to key type. * @type {!ProtoBuf.Reflect.Element} */ this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax); /** * Element instance corresponding to value type. * @type {!ProtoBuf.Reflect.Element} */ this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax); /** * Internal map: stores mapping of (string form of key) -> (key, value) * pair. * * We provide map semantics for arbitrary key types, but we build on top * of an Object, which has only string keys. In order to avoid the need * to convert a string key back to its native type in many situations, * we store the native key value alongside the value. Thus, we only need * a one-way mapping from a key type to its string form that guarantees * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1 * === K2). * * @type {!Object<string, {key: *, value: *}>} */ this.map = {}; /** * Returns the number of elements in the map. */ Object.defineProperty(this, "size", { get: function() { return Object.keys(this.map).length; } }); // Fill initial contents from a raw object. if (contents) { var keys = Object.keys(contents); for (var i = 0; i < keys.length; i++) { var key = this.keyElem.valueFromString(keys[i]); var val = this.valueElem.verifyValue(contents[keys[i]]); this.map[this.keyElem.valueToString(key)] = { key: key, value: val }; } } }
[ "function", "(", "field", ",", "contents", ")", "{", "if", "(", "!", "field", ".", "map", ")", "throw", "Error", "(", "\"field is not a map\"", ")", ";", "this", ".", "field", "=", "field", ";", "this", ".", "keyElem", "=", "new", "Reflect", ".", "Element", "(", "field", ".", "keyType", ",", "null", ",", "true", ",", "field", ".", "syntax", ")", ";", "this", ".", "valueElem", "=", "new", "Reflect", ".", "Element", "(", "field", ".", "type", ",", "field", ".", "resolvedType", ",", "false", ",", "field", ".", "syntax", ")", ";", "this", ".", "map", "=", "{", "}", ";", "Object", ".", "defineProperty", "(", "this", ",", "\"size\"", ",", "{", "get", ":", "function", "(", ")", "{", "return", "Object", ".", "keys", "(", "this", ".", "map", ")", ".", "length", ";", "}", "}", ")", ";", "if", "(", "contents", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "contents", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "var", "key", "=", "this", ".", "keyElem", ".", "valueFromString", "(", "keys", "[", "i", "]", ")", ";", "var", "val", "=", "this", ".", "valueElem", ".", "verifyValue", "(", "contents", "[", "keys", "[", "i", "]", "]", ")", ";", "this", ".", "map", "[", "this", ".", "keyElem", ".", "valueToString", "(", "key", ")", "]", "=", "{", "key", ":", "key", ",", "value", ":", "val", "}", ";", "}", "}", "}" ]
Constructs a new Map. A Map is a container that is used to implement map fields on message objects. It closely follows the ES6 Map API; however, it is distinct because we do not want to depend on external polyfills or on ES6 itself. @exports ProtoBuf.Map @param {!ProtoBuf.Reflect.Field} field Map field @param {Object.<string,*>=} contents Initial contents @constructor
[ "Constructs", "a", "new", "Map", ".", "A", "Map", "is", "a", "container", "that", "is", "used", "to", "implement", "map", "fields", "on", "message", "objects", ".", "It", "closely", "follows", "the", "ES6", "Map", "API", ";", "however", "it", "is", "distinct", "because", "we", "do", "not", "want", "to", "depend", "on", "external", "polyfills", "or", "on", "ES6", "itself", "." ]
221be558728f4e1ff35627d68033911dd928b9fa
https://github.com/elsehow/signal-protocol/blob/221be558728f4e1ff35627d68033911dd928b9fa/build/components_concat.js#L9396-L9451
train
espadrine/sc
lib/camp.js
getCompressedStream
function getCompressedStream(req, res) { var encoding = req.headers['accept-encoding'] || ''; var stream; var contentEncodingHeader = res.getHeader('Content-Encoding'); if ((contentEncodingHeader === 'gzip') || /\bgzip\b/.test(encoding)) { if (!contentEncodingHeader) { res.setHeader('Content-Encoding', 'gzip'); } stream = zlib.createGzip(); stream.pipe(res); } else if ((contentEncodingHeader === 'deflate') || /\bdeflate\b/.test(encoding)) { if (!contentEncodingHeader) { res.setHeader('Content-Encoding', 'deflate'); } stream = zlib.createDeflate(); stream.pipe(res); } return stream; }
javascript
function getCompressedStream(req, res) { var encoding = req.headers['accept-encoding'] || ''; var stream; var contentEncodingHeader = res.getHeader('Content-Encoding'); if ((contentEncodingHeader === 'gzip') || /\bgzip\b/.test(encoding)) { if (!contentEncodingHeader) { res.setHeader('Content-Encoding', 'gzip'); } stream = zlib.createGzip(); stream.pipe(res); } else if ((contentEncodingHeader === 'deflate') || /\bdeflate\b/.test(encoding)) { if (!contentEncodingHeader) { res.setHeader('Content-Encoding', 'deflate'); } stream = zlib.createDeflate(); stream.pipe(res); } return stream; }
[ "function", "getCompressedStream", "(", "req", ",", "res", ")", "{", "var", "encoding", "=", "req", ".", "headers", "[", "'accept-encoding'", "]", "||", "''", ";", "var", "stream", ";", "var", "contentEncodingHeader", "=", "res", ".", "getHeader", "(", "'Content-Encoding'", ")", ";", "if", "(", "(", "contentEncodingHeader", "===", "'gzip'", ")", "||", "/", "\\bgzip\\b", "/", ".", "test", "(", "encoding", ")", ")", "{", "if", "(", "!", "contentEncodingHeader", ")", "{", "res", ".", "setHeader", "(", "'Content-Encoding'", ",", "'gzip'", ")", ";", "}", "stream", "=", "zlib", ".", "createGzip", "(", ")", ";", "stream", ".", "pipe", "(", "res", ")", ";", "}", "else", "if", "(", "(", "contentEncodingHeader", "===", "'deflate'", ")", "||", "/", "\\bdeflate\\b", "/", ".", "test", "(", "encoding", ")", ")", "{", "if", "(", "!", "contentEncodingHeader", ")", "{", "res", ".", "setHeader", "(", "'Content-Encoding'", ",", "'deflate'", ")", ";", "}", "stream", "=", "zlib", ".", "createDeflate", "(", ")", ";", "stream", ".", "pipe", "(", "res", ")", ";", "}", "return", "stream", ";", "}" ]
Return a writable response stream, using compression when possible.
[ "Return", "a", "writable", "response", "stream", "using", "compression", "when", "possible", "." ]
c1042e58fb849e1a2ec87dc22695d21329b0e8e1
https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L247-L266
train
espadrine/sc
lib/camp.js
concatStreams
function concatStreams(array) { var concat = new stream.PassThrough(); function pipe(i) { if (i < array.length - 1) { array[i].pipe(concat, {end: false}); array[i].on('end', function () { pipe(i + 1) }); } else { array[i].pipe(concat); } } if (array.length > 0) { pipe(0); } return concat; }
javascript
function concatStreams(array) { var concat = new stream.PassThrough(); function pipe(i) { if (i < array.length - 1) { array[i].pipe(concat, {end: false}); array[i].on('end', function () { pipe(i + 1) }); } else { array[i].pipe(concat); } } if (array.length > 0) { pipe(0); } return concat; }
[ "function", "concatStreams", "(", "array", ")", "{", "var", "concat", "=", "new", "stream", ".", "PassThrough", "(", ")", ";", "function", "pipe", "(", "i", ")", "{", "if", "(", "i", "<", "array", ".", "length", "-", "1", ")", "{", "array", "[", "i", "]", ".", "pipe", "(", "concat", ",", "{", "end", ":", "false", "}", ")", ";", "array", "[", "i", "]", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "pipe", "(", "i", "+", "1", ")", "}", ")", ";", "}", "else", "{", "array", "[", "i", "]", ".", "pipe", "(", "concat", ")", ";", "}", "}", "if", "(", "array", ".", "length", ">", "0", ")", "{", "pipe", "(", "0", ")", ";", "}", "return", "concat", ";", "}" ]
Concatenate an array of streams into a single stream.
[ "Concatenate", "an", "array", "of", "streams", "into", "a", "single", "stream", "." ]
c1042e58fb849e1a2ec87dc22695d21329b0e8e1
https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L269-L285
train
espadrine/sc
lib/camp.js
augmentServer
function augmentServer(server, opts) { server.templateReader = opts.templateReader || templateReader; server.documentRoot = opts.documentRoot || p.join(process.cwd(), 'web'); server.saveRequestChunks = !!opts.saveRequestChunks; server.template = template; server.stack = []; server.stackInsertion = 0; defaultRoute.forEach(function(mkfn) { server.handle(mkfn(server)); }); server.stackInsertion = 0; server.on('request', function(req, res) { listener(server, req, res) }); }
javascript
function augmentServer(server, opts) { server.templateReader = opts.templateReader || templateReader; server.documentRoot = opts.documentRoot || p.join(process.cwd(), 'web'); server.saveRequestChunks = !!opts.saveRequestChunks; server.template = template; server.stack = []; server.stackInsertion = 0; defaultRoute.forEach(function(mkfn) { server.handle(mkfn(server)); }); server.stackInsertion = 0; server.on('request', function(req, res) { listener(server, req, res) }); }
[ "function", "augmentServer", "(", "server", ",", "opts", ")", "{", "server", ".", "templateReader", "=", "opts", ".", "templateReader", "||", "templateReader", ";", "server", ".", "documentRoot", "=", "opts", ".", "documentRoot", "||", "p", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'web'", ")", ";", "server", ".", "saveRequestChunks", "=", "!", "!", "opts", ".", "saveRequestChunks", ";", "server", ".", "template", "=", "template", ";", "server", ".", "stack", "=", "[", "]", ";", "server", ".", "stackInsertion", "=", "0", ";", "defaultRoute", ".", "forEach", "(", "function", "(", "mkfn", ")", "{", "server", ".", "handle", "(", "mkfn", "(", "server", ")", ")", ";", "}", ")", ";", "server", ".", "stackInsertion", "=", "0", ";", "server", ".", "on", "(", "'request'", ",", "function", "(", "req", ",", "res", ")", "{", "listener", "(", "server", ",", "req", ",", "res", ")", "}", ")", ";", "}" ]
Camp class is classy. Camp has a router function that returns the stack of functions to call, one after the other, in order to process the request.
[ "Camp", "class", "is", "classy", ".", "Camp", "has", "a", "router", "function", "that", "returns", "the", "stack", "of", "functions", "to", "call", "one", "after", "the", "other", "in", "order", "to", "process", "the", "request", "." ]
c1042e58fb849e1a2ec87dc22695d21329b0e8e1
https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L356-L366
train
espadrine/sc
lib/camp.js
listener
function listener(server, req, res) { augmentReqRes(req, res, server); var ask = new Ask(server, req, res); req.ask = ask; // Legacy. bubble(ask, 0); }
javascript
function listener(server, req, res) { augmentReqRes(req, res, server); var ask = new Ask(server, req, res); req.ask = ask; // Legacy. bubble(ask, 0); }
[ "function", "listener", "(", "server", ",", "req", ",", "res", ")", "{", "augmentReqRes", "(", "req", ",", "res", ",", "server", ")", ";", "var", "ask", "=", "new", "Ask", "(", "server", ",", "req", ",", "res", ")", ";", "req", ".", "ask", "=", "ask", ";", "bubble", "(", "ask", ",", "0", ")", ";", "}" ]
Default request listener.
[ "Default", "request", "listener", "." ]
c1042e58fb849e1a2ec87dc22695d21329b0e8e1
https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L404-L409
train
espadrine/sc
lib/camp.js
bubble
function bubble(ask, layer) { ask.server.stack[layer](ask.req, ask.res, function next() { if (ask.server.stack.length > layer + 1) bubble(ask, layer + 1); else { ask.res.statusCode = 500; ask.res.end('Internal Server Error\n'); } }); }
javascript
function bubble(ask, layer) { ask.server.stack[layer](ask.req, ask.res, function next() { if (ask.server.stack.length > layer + 1) bubble(ask, layer + 1); else { ask.res.statusCode = 500; ask.res.end('Internal Server Error\n'); } }); }
[ "function", "bubble", "(", "ask", ",", "layer", ")", "{", "ask", ".", "server", ".", "stack", "[", "layer", "]", "(", "ask", ".", "req", ",", "ask", ".", "res", ",", "function", "next", "(", ")", "{", "if", "(", "ask", ".", "server", ".", "stack", ".", "length", ">", "layer", "+", "1", ")", "bubble", "(", "ask", ",", "layer", "+", "1", ")", ";", "else", "{", "ask", ".", "res", ".", "statusCode", "=", "500", ";", "ask", ".", "res", ".", "end", "(", "'Internal Server Error\\n'", ")", ";", "}", "}", ")", ";", "}" ]
The bubble goes through each layer of the stack until it reaches the surface. The surface is a Server Error, btw.
[ "The", "bubble", "goes", "through", "each", "layer", "of", "the", "stack", "until", "it", "reaches", "the", "surface", ".", "The", "surface", "is", "a", "Server", "Error", "btw", "." ]
c1042e58fb849e1a2ec87dc22695d21329b0e8e1
https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L413-L421
train
espadrine/sc
lib/camp.js
genericUnit
function genericUnit (server) { var processors = []; server.handler = function (f) { processors.push(f); }; return function genericLayer (req, res, next) { for (var i = 0; i < processors.length; i++) { var keep = processors[i](req.ask); if (keep) { return; } // Don't call next, nor the rest. } next(); // We never catch that request. }; }
javascript
function genericUnit (server) { var processors = []; server.handler = function (f) { processors.push(f); }; return function genericLayer (req, res, next) { for (var i = 0; i < processors.length; i++) { var keep = processors[i](req.ask); if (keep) { return; } // Don't call next, nor the rest. } next(); // We never catch that request. }; }
[ "function", "genericUnit", "(", "server", ")", "{", "var", "processors", "=", "[", "]", ";", "server", ".", "handler", "=", "function", "(", "f", ")", "{", "processors", ".", "push", "(", "f", ")", ";", "}", ";", "return", "function", "genericLayer", "(", "req", ",", "res", ",", "next", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "processors", ".", "length", ";", "i", "++", ")", "{", "var", "keep", "=", "processors", "[", "i", "]", "(", "req", ".", "ask", ")", ";", "if", "(", "keep", ")", "{", "return", ";", "}", "}", "next", "(", ")", ";", "}", ";", "}" ]
Generic unit. Deprecated.
[ "Generic", "unit", ".", "Deprecated", "." ]
c1042e58fb849e1a2ec87dc22695d21329b0e8e1
https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L444-L454
train
espadrine/sc
lib/camp.js
socketUnit
function socketUnit (server) { var io = server.io; // Client-side: <script src="/$socket.io/socket.io.js"></script> return function socketLayer (req, res, next) { // Socket.io doesn't care about anything but /$socket.io now. if (req.path.slice(1, 11) !== '$socket.io') next(); }; }
javascript
function socketUnit (server) { var io = server.io; // Client-side: <script src="/$socket.io/socket.io.js"></script> return function socketLayer (req, res, next) { // Socket.io doesn't care about anything but /$socket.io now. if (req.path.slice(1, 11) !== '$socket.io') next(); }; }
[ "function", "socketUnit", "(", "server", ")", "{", "var", "io", "=", "server", ".", "io", ";", "return", "function", "socketLayer", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "path", ".", "slice", "(", "1", ",", "11", ")", "!==", "'$socket.io'", ")", "next", "(", ")", ";", "}", ";", "}" ]
Socket.io unit.
[ "Socket", ".", "io", "unit", "." ]
c1042e58fb849e1a2ec87dc22695d21329b0e8e1
https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L457-L465
train
espadrine/sc
lib/camp.js
wsUnit
function wsUnit (server) { var chanPool = server.wsChannels = {}; // Main WebSocket API: // ws(channel :: String, conListener :: function(socket)) server.ws = function ws (channel, conListener) { if (channel[0] !== '/') { channel = '/$websocket:' + channel; // Deprecated API. } if (chanPool[channel] !== undefined) { chanPool[channel].close(); } chanPool[channel] = new WebSocket.Server({ server: server, path: channel, }); chanPool[channel].on('connection', conListener); return chanPool[channel]; }; // WebSocket broadcast API. // webBroadcast(channel :: String, recvListener :: function(data, end)) server.wsBroadcast = function wsBroadcast (channel, recvListener) { if (channel[0] === '/') { return server.ws(channel, function (socket) { socket.on('message', function wsBroadcastRecv (data, flags) { recvListener({data: data, flags: flags}, { send: function wsBroadcastSend (dataBack) { chanPool[channel].clients.forEach(function (s) { s.send(dataBack); }); }, }); }); }); } else { // Deprecated API return server.ws(channel, function (socket) { socket.on('message', function wsBroadcastRecv (data, flags) { recvListener(data, function wsBroadcastSend (dataBack) { chanPool[channel].clients.forEach(function (s) { s.send(dataBack); }); }); }); }); } }; return function wsLayer (req, res, next) { // This doesn't actually get run, since ws overrides it at the root. if (chanPool[req.path] === undefined) return next(); }; }
javascript
function wsUnit (server) { var chanPool = server.wsChannels = {}; // Main WebSocket API: // ws(channel :: String, conListener :: function(socket)) server.ws = function ws (channel, conListener) { if (channel[0] !== '/') { channel = '/$websocket:' + channel; // Deprecated API. } if (chanPool[channel] !== undefined) { chanPool[channel].close(); } chanPool[channel] = new WebSocket.Server({ server: server, path: channel, }); chanPool[channel].on('connection', conListener); return chanPool[channel]; }; // WebSocket broadcast API. // webBroadcast(channel :: String, recvListener :: function(data, end)) server.wsBroadcast = function wsBroadcast (channel, recvListener) { if (channel[0] === '/') { return server.ws(channel, function (socket) { socket.on('message', function wsBroadcastRecv (data, flags) { recvListener({data: data, flags: flags}, { send: function wsBroadcastSend (dataBack) { chanPool[channel].clients.forEach(function (s) { s.send(dataBack); }); }, }); }); }); } else { // Deprecated API return server.ws(channel, function (socket) { socket.on('message', function wsBroadcastRecv (data, flags) { recvListener(data, function wsBroadcastSend (dataBack) { chanPool[channel].clients.forEach(function (s) { s.send(dataBack); }); }); }); }); } }; return function wsLayer (req, res, next) { // This doesn't actually get run, since ws overrides it at the root. if (chanPool[req.path] === undefined) return next(); }; }
[ "function", "wsUnit", "(", "server", ")", "{", "var", "chanPool", "=", "server", ".", "wsChannels", "=", "{", "}", ";", "server", ".", "ws", "=", "function", "ws", "(", "channel", ",", "conListener", ")", "{", "if", "(", "channel", "[", "0", "]", "!==", "'/'", ")", "{", "channel", "=", "'/$websocket:'", "+", "channel", ";", "}", "if", "(", "chanPool", "[", "channel", "]", "!==", "undefined", ")", "{", "chanPool", "[", "channel", "]", ".", "close", "(", ")", ";", "}", "chanPool", "[", "channel", "]", "=", "new", "WebSocket", ".", "Server", "(", "{", "server", ":", "server", ",", "path", ":", "channel", ",", "}", ")", ";", "chanPool", "[", "channel", "]", ".", "on", "(", "'connection'", ",", "conListener", ")", ";", "return", "chanPool", "[", "channel", "]", ";", "}", ";", "server", ".", "wsBroadcast", "=", "function", "wsBroadcast", "(", "channel", ",", "recvListener", ")", "{", "if", "(", "channel", "[", "0", "]", "===", "'/'", ")", "{", "return", "server", ".", "ws", "(", "channel", ",", "function", "(", "socket", ")", "{", "socket", ".", "on", "(", "'message'", ",", "function", "wsBroadcastRecv", "(", "data", ",", "flags", ")", "{", "recvListener", "(", "{", "data", ":", "data", ",", "flags", ":", "flags", "}", ",", "{", "send", ":", "function", "wsBroadcastSend", "(", "dataBack", ")", "{", "chanPool", "[", "channel", "]", ".", "clients", ".", "forEach", "(", "function", "(", "s", ")", "{", "s", ".", "send", "(", "dataBack", ")", ";", "}", ")", ";", "}", ",", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "else", "{", "return", "server", ".", "ws", "(", "channel", ",", "function", "(", "socket", ")", "{", "socket", ".", "on", "(", "'message'", ",", "function", "wsBroadcastRecv", "(", "data", ",", "flags", ")", "{", "recvListener", "(", "data", ",", "function", "wsBroadcastSend", "(", "dataBack", ")", "{", "chanPool", "[", "channel", "]", ".", "clients", ".", "forEach", "(", "function", "(", "s", ")", "{", "s", ".", "send", "(", "dataBack", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}", ";", "return", "function", "wsLayer", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "chanPool", "[", "req", ".", "path", "]", "===", "undefined", ")", "return", "next", "(", ")", ";", "}", ";", "}" ]
WebSocket unit.
[ "WebSocket", "unit", "." ]
c1042e58fb849e1a2ec87dc22695d21329b0e8e1
https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L468-L516
train
espadrine/sc
lib/camp.js
ajaxUnit
function ajaxUnit (server) { var ajax = server.ajax = new EventEmitter(); // Register events to be fired before loading the ajax data. var ajaxReq = server.ajaxReq = new EventEmitter(); return function ajaxLayer (req, res, next) { if (req.path[1] !== '$') { return next(); } var action = req.path.slice(2); if (ajax.listeners(action).length <= 0) { return next(); } res.setHeader('Content-Type', mime.json); ajaxReq.emit(action, req.ask); // Get all data requests. getQueries(req, function(err) { if (err == null) { ajax.emit(action, req.query, function ajaxEnd(data) { res.compressed().end(JSON.stringify(data || {})); }, req.ask); } else { log('While parsing', req.url + ':\n' + err , 'error'); return next(); } }); }; }
javascript
function ajaxUnit (server) { var ajax = server.ajax = new EventEmitter(); // Register events to be fired before loading the ajax data. var ajaxReq = server.ajaxReq = new EventEmitter(); return function ajaxLayer (req, res, next) { if (req.path[1] !== '$') { return next(); } var action = req.path.slice(2); if (ajax.listeners(action).length <= 0) { return next(); } res.setHeader('Content-Type', mime.json); ajaxReq.emit(action, req.ask); // Get all data requests. getQueries(req, function(err) { if (err == null) { ajax.emit(action, req.query, function ajaxEnd(data) { res.compressed().end(JSON.stringify(data || {})); }, req.ask); } else { log('While parsing', req.url + ':\n' + err , 'error'); return next(); } }); }; }
[ "function", "ajaxUnit", "(", "server", ")", "{", "var", "ajax", "=", "server", ".", "ajax", "=", "new", "EventEmitter", "(", ")", ";", "var", "ajaxReq", "=", "server", ".", "ajaxReq", "=", "new", "EventEmitter", "(", ")", ";", "return", "function", "ajaxLayer", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "req", ".", "path", "[", "1", "]", "!==", "'$'", ")", "{", "return", "next", "(", ")", ";", "}", "var", "action", "=", "req", ".", "path", ".", "slice", "(", "2", ")", ";", "if", "(", "ajax", ".", "listeners", "(", "action", ")", ".", "length", "<=", "0", ")", "{", "return", "next", "(", ")", ";", "}", "res", ".", "setHeader", "(", "'Content-Type'", ",", "mime", ".", "json", ")", ";", "ajaxReq", ".", "emit", "(", "action", ",", "req", ".", "ask", ")", ";", "getQueries", "(", "req", ",", "function", "(", "err", ")", "{", "if", "(", "err", "==", "null", ")", "{", "ajax", ".", "emit", "(", "action", ",", "req", ".", "query", ",", "function", "ajaxEnd", "(", "data", ")", "{", "res", ".", "compressed", "(", ")", ".", "end", "(", "JSON", ".", "stringify", "(", "data", "||", "{", "}", ")", ")", ";", "}", ",", "req", ".", "ask", ")", ";", "}", "else", "{", "log", "(", "'While parsing'", ",", "req", ".", "url", "+", "':\\n'", "+", "\\n", ",", "err", ")", ";", "'error'", "}", "}", ")", ";", "}", ";", "}" ]
Ajax unit.
[ "Ajax", "unit", "." ]
c1042e58fb849e1a2ec87dc22695d21329b0e8e1
https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L519-L547
train
espadrine/sc
lib/camp.js
staticUnit
function staticUnit (server) { return function staticLayer (req, res, next) { respondWithFile(req, res, req.path, next); }; }
javascript
function staticUnit (server) { return function staticLayer (req, res, next) { respondWithFile(req, res, req.path, next); }; }
[ "function", "staticUnit", "(", "server", ")", "{", "return", "function", "staticLayer", "(", "req", ",", "res", ",", "next", ")", "{", "respondWithFile", "(", "req", ",", "res", ",", "req", ".", "path", ",", "next", ")", ";", "}", ";", "}" ]
Static unit.
[ "Static", "unit", "." ]
c1042e58fb849e1a2ec87dc22695d21329b0e8e1
https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L699-L703
train
espadrine/sc
lib/camp.js
routeUnit
function routeUnit (server) { var regexes = []; var callbacks = []; function route (paths, literalCall) { regexes.push(RegExp(paths)); callbacks.push(literalCall); } server.route = route; return function routeLayer (req, res, next) { var matched = null; var cbindex = -1; for (var i = 0; i < regexes.length; i++) { matched = req.path.match (regexes[i]); if (matched !== null) { cbindex = i; break; } } if (cbindex >= 0) { catchpath(req, res, matched, callbacks[cbindex], server.templateReader); } else { next(); } }; }
javascript
function routeUnit (server) { var regexes = []; var callbacks = []; function route (paths, literalCall) { regexes.push(RegExp(paths)); callbacks.push(literalCall); } server.route = route; return function routeLayer (req, res, next) { var matched = null; var cbindex = -1; for (var i = 0; i < regexes.length; i++) { matched = req.path.match (regexes[i]); if (matched !== null) { cbindex = i; break; } } if (cbindex >= 0) { catchpath(req, res, matched, callbacks[cbindex], server.templateReader); } else { next(); } }; }
[ "function", "routeUnit", "(", "server", ")", "{", "var", "regexes", "=", "[", "]", ";", "var", "callbacks", "=", "[", "]", ";", "function", "route", "(", "paths", ",", "literalCall", ")", "{", "regexes", ".", "push", "(", "RegExp", "(", "paths", ")", ")", ";", "callbacks", ".", "push", "(", "literalCall", ")", ";", "}", "server", ".", "route", "=", "route", ";", "return", "function", "routeLayer", "(", "req", ",", "res", ",", "next", ")", "{", "var", "matched", "=", "null", ";", "var", "cbindex", "=", "-", "1", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "regexes", ".", "length", ";", "i", "++", ")", "{", "matched", "=", "req", ".", "path", ".", "match", "(", "regexes", "[", "i", "]", ")", ";", "if", "(", "matched", "!==", "null", ")", "{", "cbindex", "=", "i", ";", "break", ";", "}", "}", "if", "(", "cbindex", ">=", "0", ")", "{", "catchpath", "(", "req", ",", "res", ",", "matched", ",", "callbacks", "[", "cbindex", "]", ",", "server", ".", "templateReader", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}", ";", "}" ]
Template unit.
[ "Template", "unit", "." ]
c1042e58fb849e1a2ec87dc22695d21329b0e8e1
https://github.com/espadrine/sc/blob/c1042e58fb849e1a2ec87dc22695d21329b0e8e1/lib/camp.js#L854-L878
train
damoclark/node-persistent-queue
index.js
removeJob
function removeJob(self,id) { if(id === undefined) { id = self.queue.shift().id ; } else { // Search queue for id and remove if exists for(var i=0;i<self.queue.length;i++) { if(self.queue[i].id === id) { self.queue.splice(i,1) ; break ; } } } return new Promise(function(resolve,reject) { if(self.db === null) reject('Open queue database before starting queue') ; if(self.debug) console.log('About to delete') ; if(self.debug) console.log('Removing job: '+id) ; if(self.debug) console.log('From table: '+table) ; if(self.debug) console.log('With queue length: '+self.length) ; self.db.run("DELETE FROM " + table + " WHERE id = ?", id, function(err) { if(err !== null) reject(err) ; if(this.changes) // Number of rows affected (0 == false) resolve(id) ; reject("Job id "+id+" was not removed from queue") ; }); }) ; }
javascript
function removeJob(self,id) { if(id === undefined) { id = self.queue.shift().id ; } else { // Search queue for id and remove if exists for(var i=0;i<self.queue.length;i++) { if(self.queue[i].id === id) { self.queue.splice(i,1) ; break ; } } } return new Promise(function(resolve,reject) { if(self.db === null) reject('Open queue database before starting queue') ; if(self.debug) console.log('About to delete') ; if(self.debug) console.log('Removing job: '+id) ; if(self.debug) console.log('From table: '+table) ; if(self.debug) console.log('With queue length: '+self.length) ; self.db.run("DELETE FROM " + table + " WHERE id = ?", id, function(err) { if(err !== null) reject(err) ; if(this.changes) // Number of rows affected (0 == false) resolve(id) ; reject("Job id "+id+" was not removed from queue") ; }); }) ; }
[ "function", "removeJob", "(", "self", ",", "id", ")", "{", "if", "(", "id", "===", "undefined", ")", "{", "id", "=", "self", ".", "queue", ".", "shift", "(", ")", ".", "id", ";", "}", "else", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "self", ".", "queue", ".", "length", ";", "i", "++", ")", "{", "if", "(", "self", ".", "queue", "[", "i", "]", ".", "id", "===", "id", ")", "{", "self", ".", "queue", ".", "splice", "(", "i", ",", "1", ")", ";", "break", ";", "}", "}", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "self", ".", "db", "===", "null", ")", "reject", "(", "'Open queue database before starting queue'", ")", ";", "if", "(", "self", ".", "debug", ")", "console", ".", "log", "(", "'About to delete'", ")", ";", "if", "(", "self", ".", "debug", ")", "console", ".", "log", "(", "'Removing job: '", "+", "id", ")", ";", "if", "(", "self", ".", "debug", ")", "console", ".", "log", "(", "'From table: '", "+", "table", ")", ";", "if", "(", "self", ".", "debug", ")", "console", ".", "log", "(", "'With queue length: '", "+", "self", ".", "length", ")", ";", "self", ".", "db", ".", "run", "(", "\"DELETE FROM \"", "+", "table", "+", "\" WHERE id = ?\"", ",", "id", ",", "function", "(", "err", ")", "{", "if", "(", "err", "!==", "null", ")", "reject", "(", "err", ")", ";", "if", "(", "this", ".", "changes", ")", "resolve", "(", "id", ")", ";", "reject", "(", "\"Job id \"", "+", "id", "+", "\" was not removed from queue\"", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
This function will remove the given or current job from the database and in-memory array @param {PersistentQueue} self Instance to work with @param {integer} [id] Optional job id number to remove, if omitted, remove current job at front of queue @return {Promise}
[ "This", "function", "will", "remove", "the", "given", "or", "current", "job", "from", "the", "database", "and", "in", "-", "memory", "array" ]
061d631c28e1434570b779bb3c3c732c4a9dd9c1
https://github.com/damoclark/node-persistent-queue/blob/061d631c28e1434570b779bb3c3c732c4a9dd9c1/index.js#L530-L562
train