id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
16,900
aeternity/aepp-sdk-js
es/ae/index.js
transferFunds
async function transferFunds (percentage, recipientId, options = { excludeFee: false }) { if (percentage < 0 || percentage > 1) throw new Error(`Percentage should be a number between 0 and 1, got ${percentage}`) const opt = R.merge(this.Ae.defaults, options) const requestTransferAmount = BigNumber(await this.balance(await this.address())).times(percentage) let spendTx = await this.spendTx(R.merge(opt, { senderId: await this.address(), recipientId, amount: requestTransferAmount })) const { tx: txObject } = TxBuilder.unpackTx(spendTx) // If the requestTransferAmount should include the fee keep calculating the fee let amount = requestTransferAmount if (!options.excludeFee) { while (amount.plus(txObject.fee).gt(requestTransferAmount)) { amount = requestTransferAmount.minus(txObject.fee) } } // Rebuild tx spendTx = await this.spendTx(R.merge(opt, { senderId: await this.address(), recipientId, amount })) return this.send(spendTx, opt) }
javascript
async function transferFunds (percentage, recipientId, options = { excludeFee: false }) { if (percentage < 0 || percentage > 1) throw new Error(`Percentage should be a number between 0 and 1, got ${percentage}`) const opt = R.merge(this.Ae.defaults, options) const requestTransferAmount = BigNumber(await this.balance(await this.address())).times(percentage) let spendTx = await this.spendTx(R.merge(opt, { senderId: await this.address(), recipientId, amount: requestTransferAmount })) const { tx: txObject } = TxBuilder.unpackTx(spendTx) // If the requestTransferAmount should include the fee keep calculating the fee let amount = requestTransferAmount if (!options.excludeFee) { while (amount.plus(txObject.fee).gt(requestTransferAmount)) { amount = requestTransferAmount.minus(txObject.fee) } } // Rebuild tx spendTx = await this.spendTx(R.merge(opt, { senderId: await this.address(), recipientId, amount })) return this.send(spendTx, opt) }
[ "async", "function", "transferFunds", "(", "percentage", ",", "recipientId", ",", "options", "=", "{", "excludeFee", ":", "false", "}", ")", "{", "if", "(", "percentage", "<", "0", "||", "percentage", ">", "1", ")", "throw", "new", "Error", "(", "`", "${", "percentage", "}", "`", ")", "const", "opt", "=", "R", ".", "merge", "(", "this", ".", "Ae", ".", "defaults", ",", "options", ")", "const", "requestTransferAmount", "=", "BigNumber", "(", "await", "this", ".", "balance", "(", "await", "this", ".", "address", "(", ")", ")", ")", ".", "times", "(", "percentage", ")", "let", "spendTx", "=", "await", "this", ".", "spendTx", "(", "R", ".", "merge", "(", "opt", ",", "{", "senderId", ":", "await", "this", ".", "address", "(", ")", ",", "recipientId", ",", "amount", ":", "requestTransferAmount", "}", ")", ")", "const", "{", "tx", ":", "txObject", "}", "=", "TxBuilder", ".", "unpackTx", "(", "spendTx", ")", "// If the requestTransferAmount should include the fee keep calculating the fee", "let", "amount", "=", "requestTransferAmount", "if", "(", "!", "options", ".", "excludeFee", ")", "{", "while", "(", "amount", ".", "plus", "(", "txObject", ".", "fee", ")", ".", "gt", "(", "requestTransferAmount", ")", ")", "{", "amount", "=", "requestTransferAmount", ".", "minus", "(", "txObject", ".", "fee", ")", "}", "}", "// Rebuild tx", "spendTx", "=", "await", "this", ".", "spendTx", "(", "R", ".", "merge", "(", "opt", ",", "{", "senderId", ":", "await", "this", ".", "address", "(", ")", ",", "recipientId", ",", "amount", "}", ")", ")", "return", "this", ".", "send", "(", "spendTx", ",", "opt", ")", "}" ]
Send a percentage of funds to another account @instance @category async @rtype (percentage: Number|String, recipientId: String, options?: Object) => Promise[String] @param {Number|String} percentage - Percentage of amount to spend @param {String} recipientId - Address of recipient account @param {Object} options - Options @return {String|String} Transaction or transaction hash
[ "Send", "a", "percentage", "of", "funds", "to", "another", "account" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/index.js#L75-L95
16,901
aeternity/aepp-sdk-js
es/ae/aens.js
transfer
async function transfer (nameId, account, options = {}) { const opt = R.merge(this.Ae.defaults, options) const nameTransferTx = await this.nameTransferTx(R.merge(opt, { nameId, accountId: await this.address(), recipientId: account })) return this.send(nameTransferTx, opt) }
javascript
async function transfer (nameId, account, options = {}) { const opt = R.merge(this.Ae.defaults, options) const nameTransferTx = await this.nameTransferTx(R.merge(opt, { nameId, accountId: await this.address(), recipientId: account })) return this.send(nameTransferTx, opt) }
[ "async", "function", "transfer", "(", "nameId", ",", "account", ",", "options", "=", "{", "}", ")", "{", "const", "opt", "=", "R", ".", "merge", "(", "this", ".", "Ae", ".", "defaults", ",", "options", ")", "const", "nameTransferTx", "=", "await", "this", ".", "nameTransferTx", "(", "R", ".", "merge", "(", "opt", ",", "{", "nameId", ",", "accountId", ":", "await", "this", ".", "address", "(", ")", ",", "recipientId", ":", "account", "}", ")", ")", "return", "this", ".", "send", "(", "nameTransferTx", ",", "opt", ")", "}" ]
Transfer a domain to another account @instance @function @alias module:@aeternity/aepp-sdk/es/ae/aens @category async @param {String} nameId @param {String} account @param {Object} [options={}] @return {Promise<Object>}
[ "Transfer", "a", "domain", "to", "another", "account" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/aens.js#L45-L55
16,902
aeternity/aepp-sdk-js
es/ae/aens.js
revoke
async function revoke (nameId, options = {}) { const opt = R.merge(this.Ae.defaults, options) const nameRevokeTx = await this.nameRevokeTx(R.merge(opt, { nameId, accountId: await this.address() })) return this.send(nameRevokeTx, opt) }
javascript
async function revoke (nameId, options = {}) { const opt = R.merge(this.Ae.defaults, options) const nameRevokeTx = await this.nameRevokeTx(R.merge(opt, { nameId, accountId: await this.address() })) return this.send(nameRevokeTx, opt) }
[ "async", "function", "revoke", "(", "nameId", ",", "options", "=", "{", "}", ")", "{", "const", "opt", "=", "R", ".", "merge", "(", "this", ".", "Ae", ".", "defaults", ",", "options", ")", "const", "nameRevokeTx", "=", "await", "this", ".", "nameRevokeTx", "(", "R", ".", "merge", "(", "opt", ",", "{", "nameId", ",", "accountId", ":", "await", "this", ".", "address", "(", ")", "}", ")", ")", "return", "this", ".", "send", "(", "nameRevokeTx", ",", "opt", ")", "}" ]
Revoke a domain @instance @function @alias module:@aeternity/aepp-sdk/es/ae/aens @category async @param {String} nameId @param {Object} [options={}] @return {Promise<Object>}
[ "Revoke", "a", "domain" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/aens.js#L67-L76
16,903
aeternity/aepp-sdk-js
es/ae/aens.js
classify
function classify (s) { const keys = { ak: 'account_pubkey', ok: 'oracle_pubkey' } if (!s.match(/^[a-z]{2}_.+/)) { throw Error('Not a valid hash') } const klass = s.substr(0, 2) if (klass in keys) { return keys[klass] } else { throw Error(`Unknown class ${klass}`) } }
javascript
function classify (s) { const keys = { ak: 'account_pubkey', ok: 'oracle_pubkey' } if (!s.match(/^[a-z]{2}_.+/)) { throw Error('Not a valid hash') } const klass = s.substr(0, 2) if (klass in keys) { return keys[klass] } else { throw Error(`Unknown class ${klass}`) } }
[ "function", "classify", "(", "s", ")", "{", "const", "keys", "=", "{", "ak", ":", "'account_pubkey'", ",", "ok", ":", "'oracle_pubkey'", "}", "if", "(", "!", "s", ".", "match", "(", "/", "^[a-z]{2}_.+", "/", ")", ")", "{", "throw", "Error", "(", "'Not a valid hash'", ")", "}", "const", "klass", "=", "s", ".", "substr", "(", "0", ",", "2", ")", "if", "(", "klass", "in", "keys", ")", "{", "return", "keys", "[", "klass", "]", "}", "else", "{", "throw", "Error", "(", "`", "${", "klass", "}", "`", ")", "}", "}" ]
What kind of a hash is this? If it begins with 'ak_' it is an account key, if with 'ok_' it's an oracle key. @param s - the hash. returns the type, or throws an exception if type not found.
[ "What", "kind", "of", "a", "hash", "is", "this?", "If", "it", "begins", "with", "ak_", "it", "is", "an", "account", "key", "if", "with", "ok_", "it", "s", "an", "oracle", "key", "." ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/aens.js#L85-L101
16,904
aeternity/aepp-sdk-js
es/ae/aens.js
update
async function update (nameId, target, options = {}) { const opt = R.merge(this.Ae.defaults, options) const nameUpdateTx = await this.nameUpdateTx(R.merge(opt, { nameId: nameId, accountId: await this.address(), pointers: [R.fromPairs([['id', target], ['key', classify(target)]])] })) return this.send(nameUpdateTx, opt) }
javascript
async function update (nameId, target, options = {}) { const opt = R.merge(this.Ae.defaults, options) const nameUpdateTx = await this.nameUpdateTx(R.merge(opt, { nameId: nameId, accountId: await this.address(), pointers: [R.fromPairs([['id', target], ['key', classify(target)]])] })) return this.send(nameUpdateTx, opt) }
[ "async", "function", "update", "(", "nameId", ",", "target", ",", "options", "=", "{", "}", ")", "{", "const", "opt", "=", "R", ".", "merge", "(", "this", ".", "Ae", ".", "defaults", ",", "options", ")", "const", "nameUpdateTx", "=", "await", "this", ".", "nameUpdateTx", "(", "R", ".", "merge", "(", "opt", ",", "{", "nameId", ":", "nameId", ",", "accountId", ":", "await", "this", ".", "address", "(", ")", ",", "pointers", ":", "[", "R", ".", "fromPairs", "(", "[", "[", "'id'", ",", "target", "]", ",", "[", "'key'", ",", "classify", "(", "target", ")", "]", "]", ")", "]", "}", ")", ")", "return", "this", ".", "send", "(", "nameUpdateTx", ",", "opt", ")", "}" ]
Update an aens entry @instance @function @alias module:@aeternity/aepp-sdk/es/ae/aens @param nameId domain hash @param target new target @param options @return {Object}
[ "Update", "an", "aens", "entry" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/aens.js#L113-L122
16,905
aeternity/aepp-sdk-js
es/ae/aens.js
query
async function query (name) { const o = await this.getName(name) const nameId = o.id return Object.freeze(Object.assign(o, { pointers: o.pointers || {}, update: async (target, options) => { return { ...(await this.aensUpdate(nameId, target, options)), ...(await this.aensQuery(name)) } }, transfer: async (account, options) => { return { ...(await this.aensTransfer(nameId, account, options)), ...(await this.aensQuery(name)) } }, revoke: async (options) => this.aensRevoke(nameId, options) })) }
javascript
async function query (name) { const o = await this.getName(name) const nameId = o.id return Object.freeze(Object.assign(o, { pointers: o.pointers || {}, update: async (target, options) => { return { ...(await this.aensUpdate(nameId, target, options)), ...(await this.aensQuery(name)) } }, transfer: async (account, options) => { return { ...(await this.aensTransfer(nameId, account, options)), ...(await this.aensQuery(name)) } }, revoke: async (options) => this.aensRevoke(nameId, options) })) }
[ "async", "function", "query", "(", "name", ")", "{", "const", "o", "=", "await", "this", ".", "getName", "(", "name", ")", "const", "nameId", "=", "o", ".", "id", "return", "Object", ".", "freeze", "(", "Object", ".", "assign", "(", "o", ",", "{", "pointers", ":", "o", ".", "pointers", "||", "{", "}", ",", "update", ":", "async", "(", "target", ",", "options", ")", "=>", "{", "return", "{", "...", "(", "await", "this", ".", "aensUpdate", "(", "nameId", ",", "target", ",", "options", ")", ")", ",", "...", "(", "await", "this", ".", "aensQuery", "(", "name", ")", ")", "}", "}", ",", "transfer", ":", "async", "(", "account", ",", "options", ")", "=>", "{", "return", "{", "...", "(", "await", "this", ".", "aensTransfer", "(", "nameId", ",", "account", ",", "options", ")", ")", ",", "...", "(", "await", "this", ".", "aensQuery", "(", "name", ")", ")", "}", "}", ",", "revoke", ":", "async", "(", "options", ")", "=>", "this", ".", "aensRevoke", "(", "nameId", ",", "options", ")", "}", ")", ")", "}" ]
Query the status of an AENS registration @instance @function @alias module:@aeternity/aepp-sdk/es/ae/aens @param {string} name @return {Promise<Object>}
[ "Query", "the", "status", "of", "an", "AENS", "registration" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/aens.js#L132-L152
16,906
aeternity/aepp-sdk-js
es/ae/aens.js
claim
async function claim (name, salt, waitForHeight, options = {}) { const opt = R.merge(this.Ae.defaults, options) // wait until block was mined before send claim transaction // if (waitForHeight) await this.awaitHeight(waitForHeight, { attempts: 200 }) const claimTx = await this.nameClaimTx(R.merge(opt, { accountId: await this.address(), nameSalt: salt, name: `nm_${encodeBase58Check(Buffer.from(name))}` })) const result = await this.send(claimTx, opt) return { ...result, ...(await this.aensQuery(name)) } }
javascript
async function claim (name, salt, waitForHeight, options = {}) { const opt = R.merge(this.Ae.defaults, options) // wait until block was mined before send claim transaction // if (waitForHeight) await this.awaitHeight(waitForHeight, { attempts: 200 }) const claimTx = await this.nameClaimTx(R.merge(opt, { accountId: await this.address(), nameSalt: salt, name: `nm_${encodeBase58Check(Buffer.from(name))}` })) const result = await this.send(claimTx, opt) return { ...result, ...(await this.aensQuery(name)) } }
[ "async", "function", "claim", "(", "name", ",", "salt", ",", "waitForHeight", ",", "options", "=", "{", "}", ")", "{", "const", "opt", "=", "R", ".", "merge", "(", "this", ".", "Ae", ".", "defaults", ",", "options", ")", "// wait until block was mined before send claim transaction", "// if (waitForHeight) await this.awaitHeight(waitForHeight, { attempts: 200 })", "const", "claimTx", "=", "await", "this", ".", "nameClaimTx", "(", "R", ".", "merge", "(", "opt", ",", "{", "accountId", ":", "await", "this", ".", "address", "(", ")", ",", "nameSalt", ":", "salt", ",", "name", ":", "`", "${", "encodeBase58Check", "(", "Buffer", ".", "from", "(", "name", ")", ")", "}", "`", "}", ")", ")", "const", "result", "=", "await", "this", ".", "send", "(", "claimTx", ",", "opt", ")", "return", "{", "...", "result", ",", "...", "(", "await", "this", ".", "aensQuery", "(", "name", ")", ")", "}", "}" ]
Claim a previously preclaimed registration. This can only be done after the preclaim step @instance @function @alias module:@aeternity/aepp-sdk/es/ae/aens @param {String} name @param {String} salt @param {Number} waitForHeight @param {Record} [options={}] @return {Promise<Object>} the result of the claim
[ "Claim", "a", "previously", "preclaimed", "registration", ".", "This", "can", "only", "be", "done", "after", "the", "preclaim", "step" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/aens.js#L166-L182
16,907
aeternity/aepp-sdk-js
es/ae/aens.js
preclaim
async function preclaim (name, options = {}) { const opt = R.merge(this.Ae.defaults, options) const _salt = salt() const height = await this.height() const hash = await commitmentHash(name, _salt) const preclaimTx = await this.namePreclaimTx(R.merge(opt, { accountId: await this.address(), commitmentId: hash })) const result = await this.send(preclaimTx, opt) return Object.freeze({ ...result, height, claim: options => this.aensClaim(name, _salt, (height + 1), options), salt: _salt, commitmentId: hash }) }
javascript
async function preclaim (name, options = {}) { const opt = R.merge(this.Ae.defaults, options) const _salt = salt() const height = await this.height() const hash = await commitmentHash(name, _salt) const preclaimTx = await this.namePreclaimTx(R.merge(opt, { accountId: await this.address(), commitmentId: hash })) const result = await this.send(preclaimTx, opt) return Object.freeze({ ...result, height, claim: options => this.aensClaim(name, _salt, (height + 1), options), salt: _salt, commitmentId: hash }) }
[ "async", "function", "preclaim", "(", "name", ",", "options", "=", "{", "}", ")", "{", "const", "opt", "=", "R", ".", "merge", "(", "this", ".", "Ae", ".", "defaults", ",", "options", ")", "const", "_salt", "=", "salt", "(", ")", "const", "height", "=", "await", "this", ".", "height", "(", ")", "const", "hash", "=", "await", "commitmentHash", "(", "name", ",", "_salt", ")", "const", "preclaimTx", "=", "await", "this", ".", "namePreclaimTx", "(", "R", ".", "merge", "(", "opt", ",", "{", "accountId", ":", "await", "this", ".", "address", "(", ")", ",", "commitmentId", ":", "hash", "}", ")", ")", "const", "result", "=", "await", "this", ".", "send", "(", "preclaimTx", ",", "opt", ")", "return", "Object", ".", "freeze", "(", "{", "...", "result", ",", "height", ",", "claim", ":", "options", "=>", "this", ".", "aensClaim", "(", "name", ",", "_salt", ",", "(", "height", "+", "1", ")", ",", "options", ")", ",", "salt", ":", "_salt", ",", "commitmentId", ":", "hash", "}", ")", "}" ]
Preclaim a name. Sends a hash of the name and a random salt to the node @instance @function @alias module:@aeternity/aepp-sdk/es/ae/aens @param {string} name @param {Record} [options={}] @return {Promise<Object>}
[ "Preclaim", "a", "name", ".", "Sends", "a", "hash", "of", "the", "name", "and", "a", "random", "salt", "to", "the", "node" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/aens.js#L193-L213
16,908
aeternity/aepp-sdk-js
es/ae/contract.js
handleCallError
async function handleCallError (result) { const error = Buffer.from(result.returnValue).toString() if (isBase64(error.slice(3))) { const decodedError = Buffer.from(error.slice(3), 'base64').toString() throw Object.assign(Error(`Invocation failed: ${error}. Decoded: ${decodedError}`), R.merge(result, { error, decodedError })) } const decodedError = await this.contractDecodeData('string', error) throw Object.assign(Error(`Invocation failed: ${error}. Decoded: ${decodedError}`), R.merge(result, { error, decodedError })) }
javascript
async function handleCallError (result) { const error = Buffer.from(result.returnValue).toString() if (isBase64(error.slice(3))) { const decodedError = Buffer.from(error.slice(3), 'base64').toString() throw Object.assign(Error(`Invocation failed: ${error}. Decoded: ${decodedError}`), R.merge(result, { error, decodedError })) } const decodedError = await this.contractDecodeData('string', error) throw Object.assign(Error(`Invocation failed: ${error}. Decoded: ${decodedError}`), R.merge(result, { error, decodedError })) }
[ "async", "function", "handleCallError", "(", "result", ")", "{", "const", "error", "=", "Buffer", ".", "from", "(", "result", ".", "returnValue", ")", ".", "toString", "(", ")", "if", "(", "isBase64", "(", "error", ".", "slice", "(", "3", ")", ")", ")", "{", "const", "decodedError", "=", "Buffer", ".", "from", "(", "error", ".", "slice", "(", "3", ")", ",", "'base64'", ")", ".", "toString", "(", ")", "throw", "Object", ".", "assign", "(", "Error", "(", "`", "${", "error", "}", "${", "decodedError", "}", "`", ")", ",", "R", ".", "merge", "(", "result", ",", "{", "error", ",", "decodedError", "}", ")", ")", "}", "const", "decodedError", "=", "await", "this", ".", "contractDecodeData", "(", "'string'", ",", "error", ")", "throw", "Object", ".", "assign", "(", "Error", "(", "`", "${", "error", "}", "${", "decodedError", "}", "`", ")", ",", "R", ".", "merge", "(", "result", ",", "{", "error", ",", "decodedError", "}", ")", ")", "}" ]
Handle contract call error @function @alias module:@aeternity/aepp-sdk/es/ae/contract @category async @param {Object} result call result object @throws Error Decoded error @return {Promise<void>}
[ "Handle", "contract", "call", "error" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/contract.js#L46-L55
16,909
aeternity/aepp-sdk-js
es/ae/contract.js
contractCall
async function contractCall (source, address, name, args = [], options = {}) { const opt = R.merge(this.Ae.defaults, options) const tx = await this.contractCallTx(R.merge(opt, { callerId: await this.address(), contractId: address, callData: await this.contractEncodeCall(source, name, args) })) const { hash, rawTx } = await this.send(tx, opt) const result = await this.getTxInfo(hash) if (result.returnType === 'ok') { return { hash, rawTx, result, decode: (type) => this.contractDecodeData(type, result.returnValue) } } else { await this.handleCallError(result) } }
javascript
async function contractCall (source, address, name, args = [], options = {}) { const opt = R.merge(this.Ae.defaults, options) const tx = await this.contractCallTx(R.merge(opt, { callerId: await this.address(), contractId: address, callData: await this.contractEncodeCall(source, name, args) })) const { hash, rawTx } = await this.send(tx, opt) const result = await this.getTxInfo(hash) if (result.returnType === 'ok') { return { hash, rawTx, result, decode: (type) => this.contractDecodeData(type, result.returnValue) } } else { await this.handleCallError(result) } }
[ "async", "function", "contractCall", "(", "source", ",", "address", ",", "name", ",", "args", "=", "[", "]", ",", "options", "=", "{", "}", ")", "{", "const", "opt", "=", "R", ".", "merge", "(", "this", ".", "Ae", ".", "defaults", ",", "options", ")", "const", "tx", "=", "await", "this", ".", "contractCallTx", "(", "R", ".", "merge", "(", "opt", ",", "{", "callerId", ":", "await", "this", ".", "address", "(", ")", ",", "contractId", ":", "address", ",", "callData", ":", "await", "this", ".", "contractEncodeCall", "(", "source", ",", "name", ",", "args", ")", "}", ")", ")", "const", "{", "hash", ",", "rawTx", "}", "=", "await", "this", ".", "send", "(", "tx", ",", "opt", ")", "const", "result", "=", "await", "this", ".", "getTxInfo", "(", "hash", ")", "if", "(", "result", ".", "returnType", "===", "'ok'", ")", "{", "return", "{", "hash", ",", "rawTx", ",", "result", ",", "decode", ":", "(", "type", ")", "=>", "this", ".", "contractDecodeData", "(", "type", ",", "result", ".", "returnValue", ")", "}", "}", "else", "{", "await", "this", ".", "handleCallError", "(", "result", ")", "}", "}" ]
Call contract function @function @alias module:@aeternity/aepp-sdk/es/ae/contract @category async @param {String} source Contract source code @param {String} address Contract address @param {String} name Name of function to call @param {Array} args Argument's for call function @param {Object} options Transaction options (fee, ttl, gas, amount, deposit) @return {Promise<Object>} Result object @example const callResult = await client.contractCall(source, address, fnName, args = [], options) { hash: TX_HASH, result: TX_DATA, decode: (type) => Decode call result }
[ "Call", "contract", "function" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/contract.js#L158-L180
16,910
aeternity/aepp-sdk-js
es/ae/contract.js
contractDeploy
async function contractDeploy (code, source, initState = [], options = {}) { const opt = R.merge(this.Ae.defaults, options) const callData = await this.contractEncodeCall(source, 'init', initState) const ownerId = await this.address() const { tx, contractId } = await this.contractCreateTx(R.merge(opt, { callData, code, ownerId })) const { hash, rawTx } = await this.send(tx, opt) const result = await this.getTxInfo(hash) return Object.freeze({ result, owner: ownerId, transaction: hash, rawTx, address: contractId, call: async (name, args = [], options) => this.contractCall(source, contractId, name, args, options), callStatic: async (name, args = [], options) => this.contractCallStatic(source, contractId, name, args, options), createdAt: new Date() }) }
javascript
async function contractDeploy (code, source, initState = [], options = {}) { const opt = R.merge(this.Ae.defaults, options) const callData = await this.contractEncodeCall(source, 'init', initState) const ownerId = await this.address() const { tx, contractId } = await this.contractCreateTx(R.merge(opt, { callData, code, ownerId })) const { hash, rawTx } = await this.send(tx, opt) const result = await this.getTxInfo(hash) return Object.freeze({ result, owner: ownerId, transaction: hash, rawTx, address: contractId, call: async (name, args = [], options) => this.contractCall(source, contractId, name, args, options), callStatic: async (name, args = [], options) => this.contractCallStatic(source, contractId, name, args, options), createdAt: new Date() }) }
[ "async", "function", "contractDeploy", "(", "code", ",", "source", ",", "initState", "=", "[", "]", ",", "options", "=", "{", "}", ")", "{", "const", "opt", "=", "R", ".", "merge", "(", "this", ".", "Ae", ".", "defaults", ",", "options", ")", "const", "callData", "=", "await", "this", ".", "contractEncodeCall", "(", "source", ",", "'init'", ",", "initState", ")", "const", "ownerId", "=", "await", "this", ".", "address", "(", ")", "const", "{", "tx", ",", "contractId", "}", "=", "await", "this", ".", "contractCreateTx", "(", "R", ".", "merge", "(", "opt", ",", "{", "callData", ",", "code", ",", "ownerId", "}", ")", ")", "const", "{", "hash", ",", "rawTx", "}", "=", "await", "this", ".", "send", "(", "tx", ",", "opt", ")", "const", "result", "=", "await", "this", ".", "getTxInfo", "(", "hash", ")", "return", "Object", ".", "freeze", "(", "{", "result", ",", "owner", ":", "ownerId", ",", "transaction", ":", "hash", ",", "rawTx", ",", "address", ":", "contractId", ",", "call", ":", "async", "(", "name", ",", "args", "=", "[", "]", ",", "options", ")", "=>", "this", ".", "contractCall", "(", "source", ",", "contractId", ",", "name", ",", "args", ",", "options", ")", ",", "callStatic", ":", "async", "(", "name", ",", "args", "=", "[", "]", ",", "options", ")", "=>", "this", ".", "contractCallStatic", "(", "source", ",", "contractId", ",", "name", ",", "args", ",", "options", ")", ",", "createdAt", ":", "new", "Date", "(", ")", "}", ")", "}" ]
Deploy contract to the node @function @alias module:@aeternity/aepp-sdk/es/ae/contract @category async @param {String} code Compiled contract @param {String} source Contract source code @param {Array} initState Arguments of contract constructor(init) function @param {Object} options Transaction options (fee, ttl, gas, amount, deposit) @return {Promise<Object>} Result object @example const deployed = await client.contractDeploy(bytecode, source, init = [], options) { owner: OWNER_PUB_KEY, transaction: TX_HASH, address: CONTRACT_ADDRESS, createdAt: Date, result: DEPLOY_TX_DATA, call: (fnName, args = [], options) => Call contract function, callStatic: (fnName, args = [], options) => Static all contract function }
[ "Deploy", "contract", "to", "the", "node" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/contract.js#L204-L228
16,911
aeternity/aepp-sdk-js
es/ae/contract.js
contractCompile
async function contractCompile (source, options = {}) { const bytecode = await this.compileContractAPI(source, options) return Object.freeze(Object.assign({ encodeCall: async (name, args) => this.contractEncodeCall(source, name, args), deploy: async (init, options = {}) => this.contractDeploy(bytecode, source, init, options) }, { bytecode })) }
javascript
async function contractCompile (source, options = {}) { const bytecode = await this.compileContractAPI(source, options) return Object.freeze(Object.assign({ encodeCall: async (name, args) => this.contractEncodeCall(source, name, args), deploy: async (init, options = {}) => this.contractDeploy(bytecode, source, init, options) }, { bytecode })) }
[ "async", "function", "contractCompile", "(", "source", ",", "options", "=", "{", "}", ")", "{", "const", "bytecode", "=", "await", "this", ".", "compileContractAPI", "(", "source", ",", "options", ")", "return", "Object", ".", "freeze", "(", "Object", ".", "assign", "(", "{", "encodeCall", ":", "async", "(", "name", ",", "args", ")", "=>", "this", ".", "contractEncodeCall", "(", "source", ",", "name", ",", "args", ")", ",", "deploy", ":", "async", "(", "init", ",", "options", "=", "{", "}", ")", "=>", "this", ".", "contractDeploy", "(", "bytecode", ",", "source", ",", "init", ",", "options", ")", "}", ",", "{", "bytecode", "}", ")", ")", "}" ]
Compile contract source code @function @alias module:@aeternity/aepp-sdk/es/ae/contract @category async @param {String} source Contract sourece code @param {Object} options Transaction options (fee, ttl, gas, amount, deposit) @return {Promise<Object>} Result object @example const compiled = await client.contractCompile(SOURCE_CODE) { bytecode: CONTRACT_BYTE_CODE, deploy: (init = [], options = {}) => Deploy Contract, encodeCall: (fnName, args = []) => Prepare callData }
[ "Compile", "contract", "source", "code" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/ae/contract.js#L246-L252
16,912
aeternity/aepp-sdk-js
es/contract/aci.js
transform
function transform (type, value) { let { t, generic } = readType(type) // contract TestContract = ... // fn(ct: TestContract) if (typeof value === 'string' && value.slice(0, 2) === 'ct') t = SOPHIA_TYPES.address // Handle Contract address transformation switch (t) { case SOPHIA_TYPES.string: return `"${value}"` case SOPHIA_TYPES.list: return `[${value.map(el => transform(generic, el))}]` case SOPHIA_TYPES.tuple: return `(${value.map((el, i) => transform(generic[i], el))})` case SOPHIA_TYPES.address: return `#${decode(value).toString('hex')}` case SOPHIA_TYPES.record: return `{${generic.reduce( (acc, { name, type }, i) => { if (i !== 0) acc += ',' acc += `${name} = ${transform(type[0], value[name])}` return acc }, '' )}}` } return `${value}` }
javascript
function transform (type, value) { let { t, generic } = readType(type) // contract TestContract = ... // fn(ct: TestContract) if (typeof value === 'string' && value.slice(0, 2) === 'ct') t = SOPHIA_TYPES.address // Handle Contract address transformation switch (t) { case SOPHIA_TYPES.string: return `"${value}"` case SOPHIA_TYPES.list: return `[${value.map(el => transform(generic, el))}]` case SOPHIA_TYPES.tuple: return `(${value.map((el, i) => transform(generic[i], el))})` case SOPHIA_TYPES.address: return `#${decode(value).toString('hex')}` case SOPHIA_TYPES.record: return `{${generic.reduce( (acc, { name, type }, i) => { if (i !== 0) acc += ',' acc += `${name} = ${transform(type[0], value[name])}` return acc }, '' )}}` } return `${value}` }
[ "function", "transform", "(", "type", ",", "value", ")", "{", "let", "{", "t", ",", "generic", "}", "=", "readType", "(", "type", ")", "// contract TestContract = ...", "// fn(ct: TestContract)", "if", "(", "typeof", "value", "===", "'string'", "&&", "value", ".", "slice", "(", "0", ",", "2", ")", "===", "'ct'", ")", "t", "=", "SOPHIA_TYPES", ".", "address", "// Handle Contract address transformation", "switch", "(", "t", ")", "{", "case", "SOPHIA_TYPES", ".", "string", ":", "return", "`", "${", "value", "}", "`", "case", "SOPHIA_TYPES", ".", "list", ":", "return", "`", "${", "value", ".", "map", "(", "el", "=>", "transform", "(", "generic", ",", "el", ")", ")", "}", "`", "case", "SOPHIA_TYPES", ".", "tuple", ":", "return", "`", "${", "value", ".", "map", "(", "(", "el", ",", "i", ")", "=>", "transform", "(", "generic", "[", "i", "]", ",", "el", ")", ")", "}", "`", "case", "SOPHIA_TYPES", ".", "address", ":", "return", "`", "${", "decode", "(", "value", ")", ".", "toString", "(", "'hex'", ")", "}", "`", "case", "SOPHIA_TYPES", ".", "record", ":", "return", "`", "${", "generic", ".", "reduce", "(", "(", "acc", ",", "{", "name", ",", "type", "}", ",", "i", ")", "=>", "{", "if", "(", "i", "!==", "0", ")", "acc", "+=", "','", "acc", "+=", "`", "${", "name", "}", "${", "transform", "(", "type", "[", "0", "]", ",", "value", "[", "name", "]", ")", "}", "`", "return", "acc", "}", ",", "''", ")", "}", "`", "}", "return", "`", "${", "value", "}", "`", "}" ]
Transform JS type to Sophia-type @param type @param value @return {string}
[ "Transform", "JS", "type", "to", "Sophia", "-", "type" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/contract/aci.js#L50-L78
16,913
aeternity/aepp-sdk-js
es/contract/aci.js
readType
function readType (type, returnType = false) { const [t] = Array.isArray(type) ? type : [type] // Base types if (typeof t === 'string') return { t } // Map, Tuple, List if (typeof t === 'object') { const [[baseType, generic]] = Object.entries(t) return { t: baseType, generic } } }
javascript
function readType (type, returnType = false) { const [t] = Array.isArray(type) ? type : [type] // Base types if (typeof t === 'string') return { t } // Map, Tuple, List if (typeof t === 'object') { const [[baseType, generic]] = Object.entries(t) return { t: baseType, generic } } }
[ "function", "readType", "(", "type", ",", "returnType", "=", "false", ")", "{", "const", "[", "t", "]", "=", "Array", ".", "isArray", "(", "type", ")", "?", "type", ":", "[", "type", "]", "// Base types", "if", "(", "typeof", "t", "===", "'string'", ")", "return", "{", "t", "}", "// Map, Tuple, List", "if", "(", "typeof", "t", "===", "'object'", ")", "{", "const", "[", "[", "baseType", ",", "generic", "]", "]", "=", "Object", ".", "entries", "(", "t", ")", "return", "{", "t", ":", "baseType", ",", "generic", "}", "}", "}" ]
Parse sophia type @param type @param returnType @return {*}
[ "Parse", "sophia", "type" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/contract/aci.js#L86-L96
16,914
aeternity/aepp-sdk-js
es/contract/aci.js
validate
function validate (type, value) { const { t } = readType(type) if (value === undefined || value === null) return { require: true } switch (t) { case SOPHIA_TYPES.int: return isNaN(value) || ['boolean'].includes(typeof value) case SOPHIA_TYPES.bool: return typeof value !== 'boolean' case SOPHIA_TYPES.address: return !(value[2] === '_' && ['ak', 'ct'].includes(value.slice(0, 2))) default: return false } }
javascript
function validate (type, value) { const { t } = readType(type) if (value === undefined || value === null) return { require: true } switch (t) { case SOPHIA_TYPES.int: return isNaN(value) || ['boolean'].includes(typeof value) case SOPHIA_TYPES.bool: return typeof value !== 'boolean' case SOPHIA_TYPES.address: return !(value[2] === '_' && ['ak', 'ct'].includes(value.slice(0, 2))) default: return false } }
[ "function", "validate", "(", "type", ",", "value", ")", "{", "const", "{", "t", "}", "=", "readType", "(", "type", ")", "if", "(", "value", "===", "undefined", "||", "value", "===", "null", ")", "return", "{", "require", ":", "true", "}", "switch", "(", "t", ")", "{", "case", "SOPHIA_TYPES", ".", "int", ":", "return", "isNaN", "(", "value", ")", "||", "[", "'boolean'", "]", ".", "includes", "(", "typeof", "value", ")", "case", "SOPHIA_TYPES", ".", "bool", ":", "return", "typeof", "value", "!==", "'boolean'", "case", "SOPHIA_TYPES", ".", "address", ":", "return", "!", "(", "value", "[", "2", "]", "===", "'_'", "&&", "[", "'ak'", ",", "'ct'", "]", ".", "includes", "(", "value", ".", "slice", "(", "0", ",", "2", ")", ")", ")", "default", ":", "return", "false", "}", "}" ]
Validate argument sophia-type @param type @param value @return {*}
[ "Validate", "argument", "sophia", "-", "type" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/contract/aci.js#L104-L118
16,915
aeternity/aepp-sdk-js
es/contract/aci.js
transformDecodedData
function transformDecodedData (aci, result, { skipTransformDecoded = false, addressPrefix = 'ak' } = {}) { if (skipTransformDecoded) return result const { t, generic } = readType(aci, true) switch (t) { case SOPHIA_TYPES.bool: return !!result.value case SOPHIA_TYPES.address: return result.value === 0 ? 0 : encodeAddress(toBytes(result.value, true), addressPrefix) case SOPHIA_TYPES.map: const [keyT, valueT] = generic return result.value .reduce( (acc, { key, val }, i) => { key = transformDecodedData(keyT, { value: key.value }) val = transformDecodedData(valueT, { value: val.value }) acc[i] = { key, val } return acc }, {} ) case SOPHIA_TYPES.list: return result.value.map(({ value }) => transformDecodedData(generic, { value })) case SOPHIA_TYPES.tuple: return result.value.map(({ value }, i) => { return transformDecodedData(generic[i], { value }) }) case SOPHIA_TYPES.record: return result.value.reduce( (acc, { name, value }, i) => ({ ...acc, [generic[i].name]: transformDecodedData(generic[i].type, { value }) }), {} ) } return result.value }
javascript
function transformDecodedData (aci, result, { skipTransformDecoded = false, addressPrefix = 'ak' } = {}) { if (skipTransformDecoded) return result const { t, generic } = readType(aci, true) switch (t) { case SOPHIA_TYPES.bool: return !!result.value case SOPHIA_TYPES.address: return result.value === 0 ? 0 : encodeAddress(toBytes(result.value, true), addressPrefix) case SOPHIA_TYPES.map: const [keyT, valueT] = generic return result.value .reduce( (acc, { key, val }, i) => { key = transformDecodedData(keyT, { value: key.value }) val = transformDecodedData(valueT, { value: val.value }) acc[i] = { key, val } return acc }, {} ) case SOPHIA_TYPES.list: return result.value.map(({ value }) => transformDecodedData(generic, { value })) case SOPHIA_TYPES.tuple: return result.value.map(({ value }, i) => { return transformDecodedData(generic[i], { value }) }) case SOPHIA_TYPES.record: return result.value.reduce( (acc, { name, value }, i) => ({ ...acc, [generic[i].name]: transformDecodedData(generic[i].type, { value }) }), {} ) } return result.value }
[ "function", "transformDecodedData", "(", "aci", ",", "result", ",", "{", "skipTransformDecoded", "=", "false", ",", "addressPrefix", "=", "'ak'", "}", "=", "{", "}", ")", "{", "if", "(", "skipTransformDecoded", ")", "return", "result", "const", "{", "t", ",", "generic", "}", "=", "readType", "(", "aci", ",", "true", ")", "switch", "(", "t", ")", "{", "case", "SOPHIA_TYPES", ".", "bool", ":", "return", "!", "!", "result", ".", "value", "case", "SOPHIA_TYPES", ".", "address", ":", "return", "result", ".", "value", "===", "0", "?", "0", ":", "encodeAddress", "(", "toBytes", "(", "result", ".", "value", ",", "true", ")", ",", "addressPrefix", ")", "case", "SOPHIA_TYPES", ".", "map", ":", "const", "[", "keyT", ",", "valueT", "]", "=", "generic", "return", "result", ".", "value", ".", "reduce", "(", "(", "acc", ",", "{", "key", ",", "val", "}", ",", "i", ")", "=>", "{", "key", "=", "transformDecodedData", "(", "keyT", ",", "{", "value", ":", "key", ".", "value", "}", ")", "val", "=", "transformDecodedData", "(", "valueT", ",", "{", "value", ":", "val", ".", "value", "}", ")", "acc", "[", "i", "]", "=", "{", "key", ",", "val", "}", "return", "acc", "}", ",", "{", "}", ")", "case", "SOPHIA_TYPES", ".", "list", ":", "return", "result", ".", "value", ".", "map", "(", "(", "{", "value", "}", ")", "=>", "transformDecodedData", "(", "generic", ",", "{", "value", "}", ")", ")", "case", "SOPHIA_TYPES", ".", "tuple", ":", "return", "result", ".", "value", ".", "map", "(", "(", "{", "value", "}", ",", "i", ")", "=>", "{", "return", "transformDecodedData", "(", "generic", "[", "i", "]", ",", "{", "value", "}", ")", "}", ")", "case", "SOPHIA_TYPES", ".", "record", ":", "return", "result", ".", "value", ".", "reduce", "(", "(", "acc", ",", "{", "name", ",", "value", "}", ",", "i", ")", "=>", "(", "{", "...", "acc", ",", "[", "generic", "[", "i", "]", ".", "name", "]", ":", "transformDecodedData", "(", "generic", "[", "i", "]", ".", "type", ",", "{", "value", "}", ")", "}", ")", ",", "{", "}", ")", "}", "return", "result", ".", "value", "}" ]
Transform decoded data to JS type @param aci @param result @param transformDecodedData @return {*}
[ "Transform", "decoded", "data", "to", "JS", "type" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/contract/aci.js#L132-L170
16,916
aeternity/aepp-sdk-js
es/contract/aci.js
prepareArgsForEncode
function prepareArgsForEncode (aci, params) { if (!aci) return params // Validation const validation = aci.arguments .map( ({ type }, i) => validate(type, params[i]) ? `Argument index: ${i}, value: [${params[i]}] must be of type [${type}]` : false ).filter(e => e) if (validation.length) throw new Error('Validation error: ' + JSON.stringify(validation)) return aci.arguments.map(({ type }, i) => transform(type, params[i])) }
javascript
function prepareArgsForEncode (aci, params) { if (!aci) return params // Validation const validation = aci.arguments .map( ({ type }, i) => validate(type, params[i]) ? `Argument index: ${i}, value: [${params[i]}] must be of type [${type}]` : false ).filter(e => e) if (validation.length) throw new Error('Validation error: ' + JSON.stringify(validation)) return aci.arguments.map(({ type }, i) => transform(type, params[i])) }
[ "function", "prepareArgsForEncode", "(", "aci", ",", "params", ")", "{", "if", "(", "!", "aci", ")", "return", "params", "// Validation", "const", "validation", "=", "aci", ".", "arguments", ".", "map", "(", "(", "{", "type", "}", ",", "i", ")", "=>", "validate", "(", "type", ",", "params", "[", "i", "]", ")", "?", "`", "${", "i", "}", "${", "params", "[", "i", "]", "}", "${", "type", "}", "`", ":", "false", ")", ".", "filter", "(", "e", "=>", "e", ")", "if", "(", "validation", ".", "length", ")", "throw", "new", "Error", "(", "'Validation error: '", "+", "JSON", ".", "stringify", "(", "validation", ")", ")", "return", "aci", ".", "arguments", ".", "map", "(", "(", "{", "type", "}", ",", "i", ")", "=>", "transform", "(", "type", ",", "params", "[", "i", "]", ")", ")", "}" ]
Validated contract call arguments using contract ACI @function validateCallParams @rtype (aci: Object, params: Array) => Object @param {Object} aci Contract ACI @param {Array} params Contract call arguments @return {Array} Object with validation errors
[ "Validated", "contract", "call", "arguments", "using", "contract", "ACI" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/contract/aci.js#L180-L193
16,917
aeternity/aepp-sdk-js
es/contract/aci.js
getFunctionACI
function getFunctionACI (aci, name) { const fn = aci.functions.find(f => f.name === name) if (!fn && name !== 'init') throw new Error(`Function ${name} doesn't exist in contract`) return fn }
javascript
function getFunctionACI (aci, name) { const fn = aci.functions.find(f => f.name === name) if (!fn && name !== 'init') throw new Error(`Function ${name} doesn't exist in contract`) return fn }
[ "function", "getFunctionACI", "(", "aci", ",", "name", ")", "{", "const", "fn", "=", "aci", ".", "functions", ".", "find", "(", "f", "=>", "f", ".", "name", "===", "name", ")", "if", "(", "!", "fn", "&&", "name", "!==", "'init'", ")", "throw", "new", "Error", "(", "`", "${", "name", "}", "`", ")", "return", "fn", "}" ]
Get function schema from contract ACI object @param {Object} aci Contract ACI object @param {String} name Function name @return {Object} function ACI
[ "Get", "function", "schema", "from", "contract", "ACI", "object" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/contract/aci.js#L201-L206
16,918
aeternity/aepp-sdk-js
es/contract/aci.js
getContractInstance
async function getContractInstance (source, { aci, contractAddress } = {}) { aci = aci || await this.contractGetACI(source) const instance = { interface: aci.interface, aci: aci.encoded_aci.contract, source, compiled: null, deployInfo: { address: contractAddress } } /** * Compile contract * @alias module:@aeternity/aepp-sdk/es/contract/aci * @rtype () => ContractInstance: Object * @return {ContractInstance} Contract ACI object with predefined js methods for contract usage */ instance.compile = compile(this).bind(instance) /** * Deploy contract * @alias module:@aeternity/aepp-sdk/es/contract/aci * @rtype (init: Array, options: Object = { skipArgsConvert: false }) => ContractInstance: Object * @param {Array} init Contract init function arguments array * @param {Object} [options={}] options Options object * @param {Boolean} [options.skipArgsConvert=false] Skip Validation and Transforming arguments before prepare call-data * @return {ContractInstance} Contract ACI object with predefined js methods for contract usage */ instance.deploy = deploy(this).bind(instance) /** * Call contract function * @alias module:@aeternity/aepp-sdk/es/contract/aci * @rtype (init: Array, options: Object = { skipArgsConvert: false, skipTransformDecoded: false, callStatic: false }) => CallResult: Object * @param {String} fn Function name * @param {Array} params Array of function arguments * @param {Object} [options={}] Array of function arguments * @param {Boolean} [options.skipArgsConvert=false] Skip Validation and Transforming arguments before prepare call-data * @param {Boolean} [options.skipTransformDecoded=false] Skip Transform decoded data to JS type * @param {Boolean} [options.callStatic=false] Static function call * @return {Object} CallResult */ instance.call = call(this).bind(instance) return instance }
javascript
async function getContractInstance (source, { aci, contractAddress } = {}) { aci = aci || await this.contractGetACI(source) const instance = { interface: aci.interface, aci: aci.encoded_aci.contract, source, compiled: null, deployInfo: { address: contractAddress } } /** * Compile contract * @alias module:@aeternity/aepp-sdk/es/contract/aci * @rtype () => ContractInstance: Object * @return {ContractInstance} Contract ACI object with predefined js methods for contract usage */ instance.compile = compile(this).bind(instance) /** * Deploy contract * @alias module:@aeternity/aepp-sdk/es/contract/aci * @rtype (init: Array, options: Object = { skipArgsConvert: false }) => ContractInstance: Object * @param {Array} init Contract init function arguments array * @param {Object} [options={}] options Options object * @param {Boolean} [options.skipArgsConvert=false] Skip Validation and Transforming arguments before prepare call-data * @return {ContractInstance} Contract ACI object with predefined js methods for contract usage */ instance.deploy = deploy(this).bind(instance) /** * Call contract function * @alias module:@aeternity/aepp-sdk/es/contract/aci * @rtype (init: Array, options: Object = { skipArgsConvert: false, skipTransformDecoded: false, callStatic: false }) => CallResult: Object * @param {String} fn Function name * @param {Array} params Array of function arguments * @param {Object} [options={}] Array of function arguments * @param {Boolean} [options.skipArgsConvert=false] Skip Validation and Transforming arguments before prepare call-data * @param {Boolean} [options.skipTransformDecoded=false] Skip Transform decoded data to JS type * @param {Boolean} [options.callStatic=false] Static function call * @return {Object} CallResult */ instance.call = call(this).bind(instance) return instance }
[ "async", "function", "getContractInstance", "(", "source", ",", "{", "aci", ",", "contractAddress", "}", "=", "{", "}", ")", "{", "aci", "=", "aci", "||", "await", "this", ".", "contractGetACI", "(", "source", ")", "const", "instance", "=", "{", "interface", ":", "aci", ".", "interface", ",", "aci", ":", "aci", ".", "encoded_aci", ".", "contract", ",", "source", ",", "compiled", ":", "null", ",", "deployInfo", ":", "{", "address", ":", "contractAddress", "}", "}", "/**\n * Compile contract\n * @alias module:@aeternity/aepp-sdk/es/contract/aci\n * @rtype () => ContractInstance: Object\n * @return {ContractInstance} Contract ACI object with predefined js methods for contract usage\n */", "instance", ".", "compile", "=", "compile", "(", "this", ")", ".", "bind", "(", "instance", ")", "/**\n * Deploy contract\n * @alias module:@aeternity/aepp-sdk/es/contract/aci\n * @rtype (init: Array, options: Object = { skipArgsConvert: false }) => ContractInstance: Object\n * @param {Array} init Contract init function arguments array\n * @param {Object} [options={}] options Options object\n * @param {Boolean} [options.skipArgsConvert=false] Skip Validation and Transforming arguments before prepare call-data\n * @return {ContractInstance} Contract ACI object with predefined js methods for contract usage\n */", "instance", ".", "deploy", "=", "deploy", "(", "this", ")", ".", "bind", "(", "instance", ")", "/**\n * Call contract function\n * @alias module:@aeternity/aepp-sdk/es/contract/aci\n * @rtype (init: Array, options: Object = { skipArgsConvert: false, skipTransformDecoded: false, callStatic: false }) => CallResult: Object\n * @param {String} fn Function name\n * @param {Array} params Array of function arguments\n * @param {Object} [options={}] Array of function arguments\n * @param {Boolean} [options.skipArgsConvert=false] Skip Validation and Transforming arguments before prepare call-data\n * @param {Boolean} [options.skipTransformDecoded=false] Skip Transform decoded data to JS type\n * @param {Boolean} [options.callStatic=false] Static function call\n * @return {Object} CallResult\n */", "instance", ".", "call", "=", "call", "(", "this", ")", ".", "bind", "(", "instance", ")", "return", "instance", "}" ]
Generate contract ACI object with predefined js methods for contract usage @alias module:@aeternity/aepp-sdk/es/contract/aci @param {String} source Contract source code @param {Object} [options] Options object @param {Object} [options.aci] Contract ACI @return {ContractInstance} JS Contract API @example const contractIns = await client.getContractInstance(sourceCode) await contractIns.compile() await contractIns.deploy([321]) const callResult = await contractIns.call('setState', [123]) const staticCallResult = await contractIns.call('setState', [123], { callStatic: true })
[ "Generate", "contract", "ACI", "object", "with", "predefined", "js", "methods", "for", "contract", "usage" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/contract/aci.js#L222-L263
16,919
aeternity/aepp-sdk-js
es/account/memory.js
setKeypair
function setKeypair (keypair) { if (keypair.hasOwnProperty('priv') && keypair.hasOwnProperty('pub')) { keypair = { secretKey: keypair.priv, publicKey: keypair.pub } console.warn('pub/priv naming for accounts has been deprecated, please use secretKey/publicKey') } secrets.set(this, { secretKey: Buffer.from(keypair.secretKey, 'hex'), publicKey: keypair.publicKey }) }
javascript
function setKeypair (keypair) { if (keypair.hasOwnProperty('priv') && keypair.hasOwnProperty('pub')) { keypair = { secretKey: keypair.priv, publicKey: keypair.pub } console.warn('pub/priv naming for accounts has been deprecated, please use secretKey/publicKey') } secrets.set(this, { secretKey: Buffer.from(keypair.secretKey, 'hex'), publicKey: keypair.publicKey }) }
[ "function", "setKeypair", "(", "keypair", ")", "{", "if", "(", "keypair", ".", "hasOwnProperty", "(", "'priv'", ")", "&&", "keypair", ".", "hasOwnProperty", "(", "'pub'", ")", ")", "{", "keypair", "=", "{", "secretKey", ":", "keypair", ".", "priv", ",", "publicKey", ":", "keypair", ".", "pub", "}", "console", ".", "warn", "(", "'pub/priv naming for accounts has been deprecated, please use secretKey/publicKey'", ")", "}", "secrets", ".", "set", "(", "this", ",", "{", "secretKey", ":", "Buffer", ".", "from", "(", "keypair", ".", "secretKey", ",", "'hex'", ")", ",", "publicKey", ":", "keypair", ".", "publicKey", "}", ")", "}" ]
Select specific account @alias module:@aeternity/aepp-sdk/es/account/memory @function @instance @rtype (keypair: {publicKey: String, secretKey: String}) => Void @param {Object} keypair - Key pair to use @param {String} keypair.publicKey - Public key @param {String} keypair.secretKey - Private key @return {Void} @example setKeypair(keypair)
[ "Select", "specific", "account" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/account/memory.js#L50-L59
16,920
aeternity/aepp-sdk-js
es/tx/builder/index.js
deserializeField
function deserializeField (value, type, prefix) { if (!value) return '' switch (type) { case FIELD_TYPES.int: return readInt(value) case FIELD_TYPES.id: return readId(value) case FIELD_TYPES.ids: return value.map(readId) case FIELD_TYPES.bool: return value[0] === 1 case FIELD_TYPES.binary: return encode(value, prefix) case FIELD_TYPES.string: return value.toString() case FIELD_TYPES.pointers: return readPointers(value) case FIELD_TYPES.rlpBinary: return unpackTx(value, true) case FIELD_TYPES.rlpBinaries: return value.map(v => unpackTx(v, true)) case FIELD_TYPES.rawBinary: return value case FIELD_TYPES.hex: return value.toString('hex') case FIELD_TYPES.offChainUpdates: return value.map(v => unpackTx(v, true)) case FIELD_TYPES.callStack: // TODO: fix this return [readInt(value)] case FIELD_TYPES.mptree: return value.map(mpt.deserialize) case FIELD_TYPES.callReturnType: switch (readInt(value)) { case '0': return 'ok' case '1': return 'error' case '2': return 'revert' default: return value } default: return value } }
javascript
function deserializeField (value, type, prefix) { if (!value) return '' switch (type) { case FIELD_TYPES.int: return readInt(value) case FIELD_TYPES.id: return readId(value) case FIELD_TYPES.ids: return value.map(readId) case FIELD_TYPES.bool: return value[0] === 1 case FIELD_TYPES.binary: return encode(value, prefix) case FIELD_TYPES.string: return value.toString() case FIELD_TYPES.pointers: return readPointers(value) case FIELD_TYPES.rlpBinary: return unpackTx(value, true) case FIELD_TYPES.rlpBinaries: return value.map(v => unpackTx(v, true)) case FIELD_TYPES.rawBinary: return value case FIELD_TYPES.hex: return value.toString('hex') case FIELD_TYPES.offChainUpdates: return value.map(v => unpackTx(v, true)) case FIELD_TYPES.callStack: // TODO: fix this return [readInt(value)] case FIELD_TYPES.mptree: return value.map(mpt.deserialize) case FIELD_TYPES.callReturnType: switch (readInt(value)) { case '0': return 'ok' case '1': return 'error' case '2': return 'revert' default: return value } default: return value } }
[ "function", "deserializeField", "(", "value", ",", "type", ",", "prefix", ")", "{", "if", "(", "!", "value", ")", "return", "''", "switch", "(", "type", ")", "{", "case", "FIELD_TYPES", ".", "int", ":", "return", "readInt", "(", "value", ")", "case", "FIELD_TYPES", ".", "id", ":", "return", "readId", "(", "value", ")", "case", "FIELD_TYPES", ".", "ids", ":", "return", "value", ".", "map", "(", "readId", ")", "case", "FIELD_TYPES", ".", "bool", ":", "return", "value", "[", "0", "]", "===", "1", "case", "FIELD_TYPES", ".", "binary", ":", "return", "encode", "(", "value", ",", "prefix", ")", "case", "FIELD_TYPES", ".", "string", ":", "return", "value", ".", "toString", "(", ")", "case", "FIELD_TYPES", ".", "pointers", ":", "return", "readPointers", "(", "value", ")", "case", "FIELD_TYPES", ".", "rlpBinary", ":", "return", "unpackTx", "(", "value", ",", "true", ")", "case", "FIELD_TYPES", ".", "rlpBinaries", ":", "return", "value", ".", "map", "(", "v", "=>", "unpackTx", "(", "v", ",", "true", ")", ")", "case", "FIELD_TYPES", ".", "rawBinary", ":", "return", "value", "case", "FIELD_TYPES", ".", "hex", ":", "return", "value", ".", "toString", "(", "'hex'", ")", "case", "FIELD_TYPES", ".", "offChainUpdates", ":", "return", "value", ".", "map", "(", "v", "=>", "unpackTx", "(", "v", ",", "true", ")", ")", "case", "FIELD_TYPES", ".", "callStack", ":", "// TODO: fix this", "return", "[", "readInt", "(", "value", ")", "]", "case", "FIELD_TYPES", ".", "mptree", ":", "return", "value", ".", "map", "(", "mpt", ".", "deserialize", ")", "case", "FIELD_TYPES", ".", "callReturnType", ":", "switch", "(", "readInt", "(", "value", ")", ")", "{", "case", "'0'", ":", "return", "'ok'", "case", "'1'", ":", "return", "'error'", "case", "'2'", ":", "return", "'revert'", "default", ":", "return", "value", "}", "default", ":", "return", "value", "}", "}" ]
SERIALIZE AND DESERIALIZE PART
[ "SERIALIZE", "AND", "DESERIALIZE", "PART" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/tx/builder/index.js#L34-L76
16,921
aeternity/aepp-sdk-js
es/tx/tx.js
calculateTtl
async function calculateTtl (ttl = 0, relative = true) { if (ttl === 0) return 0 if (ttl < 0) throw new Error('ttl must be greater than 0') if (relative) { const { height } = await this.api.getCurrentKeyBlock() return +(height) + ttl } return ttl }
javascript
async function calculateTtl (ttl = 0, relative = true) { if (ttl === 0) return 0 if (ttl < 0) throw new Error('ttl must be greater than 0') if (relative) { const { height } = await this.api.getCurrentKeyBlock() return +(height) + ttl } return ttl }
[ "async", "function", "calculateTtl", "(", "ttl", "=", "0", ",", "relative", "=", "true", ")", "{", "if", "(", "ttl", "===", "0", ")", "return", "0", "if", "(", "ttl", "<", "0", ")", "throw", "new", "Error", "(", "'ttl must be greater than 0'", ")", "if", "(", "relative", ")", "{", "const", "{", "height", "}", "=", "await", "this", ".", "api", ".", "getCurrentKeyBlock", "(", ")", "return", "+", "(", "height", ")", "+", "ttl", "}", "return", "ttl", "}" ]
Compute the absolute ttl by adding the ttl to the current height of the chain @param {number} ttl @param {boolean} relative ttl is absolute or relative(default: true(relative)) @return {number} Absolute Ttl
[ "Compute", "the", "absolute", "ttl", "by", "adding", "the", "ttl", "to", "the", "current", "height", "of", "the", "chain" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/tx/tx.js#L365-L374
16,922
aeternity/aepp-sdk-js
es/tx/tx.js
getAccountNonce
async function getAccountNonce (accountId, nonce) { if (nonce) return nonce const { nonce: accountNonce } = await this.api.getAccountByPubkey(accountId).catch(() => ({ nonce: 0 })) return accountNonce + 1 }
javascript
async function getAccountNonce (accountId, nonce) { if (nonce) return nonce const { nonce: accountNonce } = await this.api.getAccountByPubkey(accountId).catch(() => ({ nonce: 0 })) return accountNonce + 1 }
[ "async", "function", "getAccountNonce", "(", "accountId", ",", "nonce", ")", "{", "if", "(", "nonce", ")", "return", "nonce", "const", "{", "nonce", ":", "accountNonce", "}", "=", "await", "this", ".", "api", ".", "getAccountByPubkey", "(", "accountId", ")", ".", "catch", "(", "(", ")", "=>", "(", "{", "nonce", ":", "0", "}", ")", ")", "return", "accountNonce", "+", "1", "}" ]
Get the next nonce to be used for a transaction for an account @param {string} accountId @param {number} nonce @return {number} Next Nonce
[ "Get", "the", "next", "nonce", "to", "be", "used", "for", "a", "transaction", "for", "an", "account" ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/tx/tx.js#L383-L387
16,923
aeternity/aepp-sdk-js
es/utils/keystore.js
str2buf
function str2buf (str, enc) { if (!str || str.constructor !== String) return str if (!enc && isHex(str)) enc = 'hex' if (!enc && isBase64(str)) enc = 'base64' return Buffer.from(str, enc) }
javascript
function str2buf (str, enc) { if (!str || str.constructor !== String) return str if (!enc && isHex(str)) enc = 'hex' if (!enc && isBase64(str)) enc = 'base64' return Buffer.from(str, enc) }
[ "function", "str2buf", "(", "str", ",", "enc", ")", "{", "if", "(", "!", "str", "||", "str", ".", "constructor", "!==", "String", ")", "return", "str", "if", "(", "!", "enc", "&&", "isHex", "(", "str", ")", ")", "enc", "=", "'hex'", "if", "(", "!", "enc", "&&", "isBase64", "(", "str", ")", ")", "enc", "=", "'base64'", "return", "Buffer", ".", "from", "(", "str", ",", "enc", ")", "}" ]
Convert a string to a Buffer. If encoding is not specified, hex-encoding will be used if the input is valid hex. If the input is valid base64 but not valid hex, base64 will be used. Otherwise, utf8 will be used. @param {string} str String to be converted. @param {string=} enc Encoding of the input string (optional). @return {buffer} Buffer (bytearray) containing the input data.
[ "Convert", "a", "string", "to", "a", "Buffer", ".", "If", "encoding", "is", "not", "specified", "hex", "-", "encoding", "will", "be", "used", "if", "the", "input", "is", "valid", "hex", ".", "If", "the", "input", "is", "valid", "base64", "but", "not", "valid", "hex", "base64", "will", "be", "used", ".", "Otherwise", "utf8", "will", "be", "used", "." ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/utils/keystore.js#L69-L74
16,924
aeternity/aepp-sdk-js
es/utils/keystore.js
deriveKey
async function deriveKey (password, nonce, options = { kdf_params: DEFAULTS.crypto.kdf_params, kdf: DEFAULTS.crypto.kdf }) { if (typeof password === 'undefined' || password === null || !nonce) { throw new Error('Must provide password and nonce to derive a key') } if (!DERIVED_KEY_FUNCTIONS.hasOwnProperty(options.kdf)) throw new Error('Unsupported kdf type') return DERIVED_KEY_FUNCTIONS[options.kdf](password, nonce, options) }
javascript
async function deriveKey (password, nonce, options = { kdf_params: DEFAULTS.crypto.kdf_params, kdf: DEFAULTS.crypto.kdf }) { if (typeof password === 'undefined' || password === null || !nonce) { throw new Error('Must provide password and nonce to derive a key') } if (!DERIVED_KEY_FUNCTIONS.hasOwnProperty(options.kdf)) throw new Error('Unsupported kdf type') return DERIVED_KEY_FUNCTIONS[options.kdf](password, nonce, options) }
[ "async", "function", "deriveKey", "(", "password", ",", "nonce", ",", "options", "=", "{", "kdf_params", ":", "DEFAULTS", ".", "crypto", ".", "kdf_params", ",", "kdf", ":", "DEFAULTS", ".", "crypto", ".", "kdf", "}", ")", "{", "if", "(", "typeof", "password", "===", "'undefined'", "||", "password", "===", "null", "||", "!", "nonce", ")", "{", "throw", "new", "Error", "(", "'Must provide password and nonce to derive a key'", ")", "}", "if", "(", "!", "DERIVED_KEY_FUNCTIONS", ".", "hasOwnProperty", "(", "options", ".", "kdf", ")", ")", "throw", "new", "Error", "(", "'Unsupported kdf type'", ")", "return", "DERIVED_KEY_FUNCTIONS", "[", "options", ".", "kdf", "]", "(", "password", ",", "nonce", ",", "options", ")", "}" ]
Derive secret key from password with key derivation function. @param {string} password User-supplied password. @param {buffer|Uint8Array} nonce Randomly generated nonce. @param {Object=} options Encryption parameters. @param {string=} options.kdf Key derivation function (default: DEFAULTS.crypto.kdf). @param {Object=} options.kdf_params KDF parameters (default: DEFAULTS.crypto.kdf_params). @return {buffer} Secret key derived from password.
[ "Derive", "secret", "key", "from", "password", "with", "key", "derivation", "function", "." ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/utils/keystore.js#L111-L122
16,925
aeternity/aepp-sdk-js
es/utils/keystore.js
marshal
function marshal (name, derivedKey, privateKey, nonce, salt, options = {}) { const opt = Object.assign({}, DEFAULTS.crypto, options) return Object.assign( { name, version: 1, public_key: getAddressFromPriv(privateKey), id: uuid.v4() }, { crypto: Object.assign( { secret_type: opt.secret_type, symmetric_alg: opt.symmetric_alg, ciphertext: Buffer.from(encrypt(Buffer.from(privateKey), derivedKey, nonce, opt.symmetric_alg)).toString('hex'), cipher_params: { nonce: Buffer.from(nonce).toString('hex') } }, { kdf: opt.kdf, kdf_params: { ...opt.kdf_params, salt: Buffer.from(salt).toString('hex') } } ) } ) }
javascript
function marshal (name, derivedKey, privateKey, nonce, salt, options = {}) { const opt = Object.assign({}, DEFAULTS.crypto, options) return Object.assign( { name, version: 1, public_key: getAddressFromPriv(privateKey), id: uuid.v4() }, { crypto: Object.assign( { secret_type: opt.secret_type, symmetric_alg: opt.symmetric_alg, ciphertext: Buffer.from(encrypt(Buffer.from(privateKey), derivedKey, nonce, opt.symmetric_alg)).toString('hex'), cipher_params: { nonce: Buffer.from(nonce).toString('hex') } }, { kdf: opt.kdf, kdf_params: { ...opt.kdf_params, salt: Buffer.from(salt).toString('hex') } } ) } ) }
[ "function", "marshal", "(", "name", ",", "derivedKey", ",", "privateKey", ",", "nonce", ",", "salt", ",", "options", "=", "{", "}", ")", "{", "const", "opt", "=", "Object", ".", "assign", "(", "{", "}", ",", "DEFAULTS", ".", "crypto", ",", "options", ")", "return", "Object", ".", "assign", "(", "{", "name", ",", "version", ":", "1", ",", "public_key", ":", "getAddressFromPriv", "(", "privateKey", ")", ",", "id", ":", "uuid", ".", "v4", "(", ")", "}", ",", "{", "crypto", ":", "Object", ".", "assign", "(", "{", "secret_type", ":", "opt", ".", "secret_type", ",", "symmetric_alg", ":", "opt", ".", "symmetric_alg", ",", "ciphertext", ":", "Buffer", ".", "from", "(", "encrypt", "(", "Buffer", ".", "from", "(", "privateKey", ")", ",", "derivedKey", ",", "nonce", ",", "opt", ".", "symmetric_alg", ")", ")", ".", "toString", "(", "'hex'", ")", ",", "cipher_params", ":", "{", "nonce", ":", "Buffer", ".", "from", "(", "nonce", ")", ".", "toString", "(", "'hex'", ")", "}", "}", ",", "{", "kdf", ":", "opt", ".", "kdf", ",", "kdf_params", ":", "{", "...", "opt", ".", "kdf_params", ",", "salt", ":", "Buffer", ".", "from", "(", "salt", ")", ".", "toString", "(", "'hex'", ")", "}", "}", ")", "}", ")", "}" ]
Assemble key data object in secret-storage format. @param {buffer} name Key name. @param {buffer} derivedKey Password-derived secret key. @param {buffer} privateKey Private key. @param {buffer} nonce Randomly generated 24byte nonce. @param {buffer} salt Randomly generated 16byte salt. @param {Object=} options Encryption parameters. @param {string=} options.kdf Key derivation function (default: argon2id). @param {string=} options.cipher Symmetric cipher (default: constants.cipher). @param {Object=} options.kdf_params KDF parameters (default: constants.<kdf>). @return {Object}
[ "Assemble", "key", "data", "object", "in", "secret", "-", "storage", "format", "." ]
1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6
https://github.com/aeternity/aepp-sdk-js/blob/1ad86b72235e88d357a03d6ae4dd4ce1a4158ca6/es/utils/keystore.js#L137-L153
16,926
sendinblue/APIv3-nodejs-library
src/model/GetChildInfo.js
function(email, firstName, lastName, companyName, password) { var _this = this; GetClient.call(_this, email, firstName, lastName, companyName); _this['password'] = password; }
javascript
function(email, firstName, lastName, companyName, password) { var _this = this; GetClient.call(_this, email, firstName, lastName, companyName); _this['password'] = password; }
[ "function", "(", "email", ",", "firstName", ",", "lastName", ",", "companyName", ",", "password", ")", "{", "var", "_this", "=", "this", ";", "GetClient", ".", "call", "(", "_this", ",", "email", ",", "firstName", ",", "lastName", ",", "companyName", ")", ";", "_this", "[", "'password'", "]", "=", "password", ";", "}" ]
The GetChildInfo model module. @module model/GetChildInfo @version 7.x.x Constructs a new <code>GetChildInfo</code>. @alias module:model/GetChildInfo @class @implements module:model/GetClient @param email {String} Login Email @param firstName {String} First Name @param lastName {String} Last Name @param companyName {String} Name of the company @param password {String} The encrypted password of child account
[ "The", "GetChildInfo", "model", "module", "." ]
9663ee86370be7577853d2b7565b11380d5fe736
https://github.com/sendinblue/APIv3-nodejs-library/blob/9663ee86370be7577853d2b7565b11380d5fe736/src/model/GetChildInfo.js#L54-L63
16,927
sendinblue/APIv3-nodejs-library
src/model/GetAccount.js
function(email, firstName, lastName, companyName, address, plan, relay) { var _this = this; GetExtendedClient.call(_this, email, firstName, lastName, companyName, address); _this['plan'] = plan; _this['relay'] = relay; }
javascript
function(email, firstName, lastName, companyName, address, plan, relay) { var _this = this; GetExtendedClient.call(_this, email, firstName, lastName, companyName, address); _this['plan'] = plan; _this['relay'] = relay; }
[ "function", "(", "email", ",", "firstName", ",", "lastName", ",", "companyName", ",", "address", ",", "plan", ",", "relay", ")", "{", "var", "_this", "=", "this", ";", "GetExtendedClient", ".", "call", "(", "_this", ",", "email", ",", "firstName", ",", "lastName", ",", "companyName", ",", "address", ")", ";", "_this", "[", "'plan'", "]", "=", "plan", ";", "_this", "[", "'relay'", "]", "=", "relay", ";", "}" ]
The GetAccount model module. @module model/GetAccount @version 7.x.x Constructs a new <code>GetAccount</code>. @alias module:model/GetAccount @class @implements module:model/GetExtendedClient @param email {String} Login Email @param firstName {String} First Name @param lastName {String} Last Name @param companyName {String} Name of the company @param address {module:model/GetExtendedClientAddress} @param plan {Array.<module:model/GetAccountPlan>} Information about your plans and credits @param relay {module:model/GetAccountRelay}
[ "The", "GetAccount", "model", "module", "." ]
9663ee86370be7577853d2b7565b11380d5fe736
https://github.com/sendinblue/APIv3-nodejs-library/blob/9663ee86370be7577853d2b7565b11380d5fe736/src/model/GetAccount.js#L56-L63
16,928
dcmjs-org/dicomweb-client
src/message.js
uint8ArrayToString
function uint8ArrayToString(arr, offset, limit) { offset = offset || 0; limit = limit || arr.length - offset; let str = ''; for (let i = offset; i < offset + limit; i++) { str += String.fromCharCode(arr[i]); } return str; }
javascript
function uint8ArrayToString(arr, offset, limit) { offset = offset || 0; limit = limit || arr.length - offset; let str = ''; for (let i = offset; i < offset + limit; i++) { str += String.fromCharCode(arr[i]); } return str; }
[ "function", "uint8ArrayToString", "(", "arr", ",", "offset", ",", "limit", ")", "{", "offset", "=", "offset", "||", "0", ";", "limit", "=", "limit", "||", "arr", ".", "length", "-", "offset", ";", "let", "str", "=", "''", ";", "for", "(", "let", "i", "=", "offset", ";", "i", "<", "offset", "+", "limit", ";", "i", "++", ")", "{", "str", "+=", "String", ".", "fromCharCode", "(", "arr", "[", "i", "]", ")", ";", "}", "return", "str", ";", "}" ]
Converts a Uint8Array to a String. @param {Uint8Array} array that should be converted @param {Number} offset array offset in case only subset of array items should be extracted (default: 0) @param {Number} limit maximum number of array items that should be extracted (defaults to length of array) @returns {String}
[ "Converts", "a", "Uint8Array", "to", "a", "String", "." ]
22bb19a19fc85aa6b34a9399734cd508d15f36ff
https://github.com/dcmjs-org/dicomweb-client/blob/22bb19a19fc85aa6b34a9399734cd508d15f36ff/src/message.js#L8-L16
16,929
dcmjs-org/dicomweb-client
src/message.js
stringToUint8Array
function stringToUint8Array(str) { const arr = new Uint8Array(str.length); for (let i = 0, j = str.length; i < j; i++) { arr[i] = str.charCodeAt(i); } return arr; }
javascript
function stringToUint8Array(str) { const arr = new Uint8Array(str.length); for (let i = 0, j = str.length; i < j; i++) { arr[i] = str.charCodeAt(i); } return arr; }
[ "function", "stringToUint8Array", "(", "str", ")", "{", "const", "arr", "=", "new", "Uint8Array", "(", "str", ".", "length", ")", ";", "for", "(", "let", "i", "=", "0", ",", "j", "=", "str", ".", "length", ";", "i", "<", "j", ";", "i", "++", ")", "{", "arr", "[", "i", "]", "=", "str", ".", "charCodeAt", "(", "i", ")", ";", "}", "return", "arr", ";", "}" ]
Converts a String to a Uint8Array. @param {String} str string that should be converted @returns {Uint8Array}
[ "Converts", "a", "String", "to", "a", "Uint8Array", "." ]
22bb19a19fc85aa6b34a9399734cd508d15f36ff
https://github.com/dcmjs-org/dicomweb-client/blob/22bb19a19fc85aa6b34a9399734cd508d15f36ff/src/message.js#L24-L30
16,930
dcmjs-org/dicomweb-client
src/message.js
containsToken
function containsToken(message, token, offset=0) { if (offset + token.length > message.length) { return false; } let index = offset; for (let i = 0; i < token.length; i++) { if (token[i] !== message[index++]) { return false; } } return true; }
javascript
function containsToken(message, token, offset=0) { if (offset + token.length > message.length) { return false; } let index = offset; for (let i = 0; i < token.length; i++) { if (token[i] !== message[index++]) { return false; } } return true; }
[ "function", "containsToken", "(", "message", ",", "token", ",", "offset", "=", "0", ")", "{", "if", "(", "offset", "+", "token", ".", "length", ">", "message", ".", "length", ")", "{", "return", "false", ";", "}", "let", "index", "=", "offset", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "token", ".", "length", ";", "i", "++", ")", "{", "if", "(", "token", "[", "i", "]", "!==", "message", "[", "index", "++", "]", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks whether a given token is contained by a message at a given offset. @param {Uint8Array} message message content @param {Uint8Array} token substring that should be present @param {Number} offset offset in message content from where search should start @returns {Boolean} whether message contains token at offset
[ "Checks", "whether", "a", "given", "token", "is", "contained", "by", "a", "message", "at", "a", "given", "offset", "." ]
22bb19a19fc85aa6b34a9399734cd508d15f36ff
https://github.com/dcmjs-org/dicomweb-client/blob/22bb19a19fc85aa6b34a9399734cd508d15f36ff/src/message.js#L56-L68
16,931
dcmjs-org/dicomweb-client
src/message.js
findToken
function findToken(message, token, offset=0, maxSearchLength) { let searchLength = message.length; if (maxSearchLength) { searchLength = Math.min(offset + maxSearchLength, message.length); } for (let i = offset; i < searchLength; i++) { // If the first value of the message matches // the first value of the token, check if // this is the full token. if (message[i] === token[0]) { if (containsToken(message, token, i)) { return i; } } } return -1; }
javascript
function findToken(message, token, offset=0, maxSearchLength) { let searchLength = message.length; if (maxSearchLength) { searchLength = Math.min(offset + maxSearchLength, message.length); } for (let i = offset; i < searchLength; i++) { // If the first value of the message matches // the first value of the token, check if // this is the full token. if (message[i] === token[0]) { if (containsToken(message, token, i)) { return i; } } } return -1; }
[ "function", "findToken", "(", "message", ",", "token", ",", "offset", "=", "0", ",", "maxSearchLength", ")", "{", "let", "searchLength", "=", "message", ".", "length", ";", "if", "(", "maxSearchLength", ")", "{", "searchLength", "=", "Math", ".", "min", "(", "offset", "+", "maxSearchLength", ",", "message", ".", "length", ")", ";", "}", "for", "(", "let", "i", "=", "offset", ";", "i", "<", "searchLength", ";", "i", "++", ")", "{", "// If the first value of the message matches", "// the first value of the token, check if", "// this is the full token.", "if", "(", "message", "[", "i", "]", "===", "token", "[", "0", "]", ")", "{", "if", "(", "containsToken", "(", "message", ",", "token", ",", "i", ")", ")", "{", "return", "i", ";", "}", "}", "}", "return", "-", "1", ";", "}" ]
Finds a given token in a message at a given offset. @param {Uint8Array} message message content @param {Uint8Array} token substring that should be found @param {String} offset message body offset from where search should start @returns {Boolean} whether message has a part at given offset or not
[ "Finds", "a", "given", "token", "in", "a", "message", "at", "a", "given", "offset", "." ]
22bb19a19fc85aa6b34a9399734cd508d15f36ff
https://github.com/dcmjs-org/dicomweb-client/blob/22bb19a19fc85aa6b34a9399734cd508d15f36ff/src/message.js#L78-L96
16,932
dcmjs-org/dicomweb-client
src/message.js
multipartDecode
function multipartDecode(response) { const message = new Uint8Array(response); /* Set a maximum length to search for the header boundaries, otherwise findToken can run for a long time */ const maxSearchLength = 1000; // First look for the multipart mime header let separator = stringToUint8Array('\r\n\r\n'); let headerIndex = findToken(message, separator, 0, maxSearchLength); if (headerIndex === -1) { throw new Error('Response message has no multipart mime header'); } const header = uint8ArrayToString(message, 0, headerIndex); const boundaryString = identifyBoundary(header); if (!boundaryString) { throw new Error('Header of response message does not specify boundary'); } const boundary = stringToUint8Array(boundaryString); const boundaryLength = boundary.length; const components = []; let offset = headerIndex + separator.length; // Loop until we cannot find any more boundaries let boundaryIndex; while (boundaryIndex !== -1) { // Search for the next boundary in the message, starting // from the current offset position boundaryIndex = findToken(message, boundary, offset); // If no further boundaries are found, stop here. if (boundaryIndex === -1) { break; } // Extract data from response message, excluding "\r\n" const spacingLength = 2; const length = boundaryIndex - offset - spacingLength; const data = response.slice(offset, offset + length); // Add the data to the array of results components.push(data); // Move the offset to the end of the current section, // plus the identified boundary offset += length + spacingLength + boundaryLength; } return components; }
javascript
function multipartDecode(response) { const message = new Uint8Array(response); /* Set a maximum length to search for the header boundaries, otherwise findToken can run for a long time */ const maxSearchLength = 1000; // First look for the multipart mime header let separator = stringToUint8Array('\r\n\r\n'); let headerIndex = findToken(message, separator, 0, maxSearchLength); if (headerIndex === -1) { throw new Error('Response message has no multipart mime header'); } const header = uint8ArrayToString(message, 0, headerIndex); const boundaryString = identifyBoundary(header); if (!boundaryString) { throw new Error('Header of response message does not specify boundary'); } const boundary = stringToUint8Array(boundaryString); const boundaryLength = boundary.length; const components = []; let offset = headerIndex + separator.length; // Loop until we cannot find any more boundaries let boundaryIndex; while (boundaryIndex !== -1) { // Search for the next boundary in the message, starting // from the current offset position boundaryIndex = findToken(message, boundary, offset); // If no further boundaries are found, stop here. if (boundaryIndex === -1) { break; } // Extract data from response message, excluding "\r\n" const spacingLength = 2; const length = boundaryIndex - offset - spacingLength; const data = response.slice(offset, offset + length); // Add the data to the array of results components.push(data); // Move the offset to the end of the current section, // plus the identified boundary offset += length + spacingLength + boundaryLength; } return components; }
[ "function", "multipartDecode", "(", "response", ")", "{", "const", "message", "=", "new", "Uint8Array", "(", "response", ")", ";", "/* Set a maximum length to search for the header boundaries, otherwise\n findToken can run for a long time\n */", "const", "maxSearchLength", "=", "1000", ";", "// First look for the multipart mime header", "let", "separator", "=", "stringToUint8Array", "(", "'\\r\\n\\r\\n'", ")", ";", "let", "headerIndex", "=", "findToken", "(", "message", ",", "separator", ",", "0", ",", "maxSearchLength", ")", ";", "if", "(", "headerIndex", "===", "-", "1", ")", "{", "throw", "new", "Error", "(", "'Response message has no multipart mime header'", ")", ";", "}", "const", "header", "=", "uint8ArrayToString", "(", "message", ",", "0", ",", "headerIndex", ")", ";", "const", "boundaryString", "=", "identifyBoundary", "(", "header", ")", ";", "if", "(", "!", "boundaryString", ")", "{", "throw", "new", "Error", "(", "'Header of response message does not specify boundary'", ")", ";", "}", "const", "boundary", "=", "stringToUint8Array", "(", "boundaryString", ")", ";", "const", "boundaryLength", "=", "boundary", ".", "length", ";", "const", "components", "=", "[", "]", ";", "let", "offset", "=", "headerIndex", "+", "separator", ".", "length", ";", "// Loop until we cannot find any more boundaries", "let", "boundaryIndex", ";", "while", "(", "boundaryIndex", "!==", "-", "1", ")", "{", "// Search for the next boundary in the message, starting", "// from the current offset position", "boundaryIndex", "=", "findToken", "(", "message", ",", "boundary", ",", "offset", ")", ";", "// If no further boundaries are found, stop here.", "if", "(", "boundaryIndex", "===", "-", "1", ")", "{", "break", ";", "}", "// Extract data from response message, excluding \"\\r\\n\"", "const", "spacingLength", "=", "2", ";", "const", "length", "=", "boundaryIndex", "-", "offset", "-", "spacingLength", ";", "const", "data", "=", "response", ".", "slice", "(", "offset", ",", "offset", "+", "length", ")", ";", "// Add the data to the array of results", "components", ".", "push", "(", "data", ")", ";", "// Move the offset to the end of the current section,", "// plus the identified boundary", "offset", "+=", "length", "+", "spacingLength", "+", "boundaryLength", ";", "}", "return", "components", ";", "}" ]
Decode a Multipart encoded ArrayBuffer and return the components as an Array. @param {ArrayBuffer} response Data encoded as a 'multipart/related' message @returns {Array} The content
[ "Decode", "a", "Multipart", "encoded", "ArrayBuffer", "and", "return", "the", "components", "as", "an", "Array", "." ]
22bb19a19fc85aa6b34a9399734cd508d15f36ff
https://github.com/dcmjs-org/dicomweb-client/blob/22bb19a19fc85aa6b34a9399734cd508d15f36ff/src/message.js#L164-L219
16,933
koola/pix-diff
lib/camelCase.js
camelCase
function camelCase(text) { text = text || ''; return text.replace(/(?:^\w|[A-Z]|\b\w)/g, (letter, index) => { return index === 0 ? letter.toLowerCase() : letter.toUpperCase(); }).replace(/\s+/g, ''); }
javascript
function camelCase(text) { text = text || ''; return text.replace(/(?:^\w|[A-Z]|\b\w)/g, (letter, index) => { return index === 0 ? letter.toLowerCase() : letter.toUpperCase(); }).replace(/\s+/g, ''); }
[ "function", "camelCase", "(", "text", ")", "{", "text", "=", "text", "||", "''", ";", "return", "text", ".", "replace", "(", "/", "(?:^\\w|[A-Z]|\\b\\w)", "/", "g", ",", "(", "letter", ",", "index", ")", "=>", "{", "return", "index", "===", "0", "?", "letter", ".", "toLowerCase", "(", ")", ":", "letter", ".", "toUpperCase", "(", ")", ";", "}", ")", ".", "replace", "(", "/", "\\s+", "/", "g", ",", "''", ")", ";", "}" ]
Converts string to a camel cased string @method camelCase @param {string} text @returns {string} @public
[ "Converts", "string", "to", "a", "camel", "cased", "string" ]
0402b9bec5f1d577ef0b73419ac8e52f52cad81b
https://github.com/koola/pix-diff/blob/0402b9bec5f1d577ef0b73419ac8e52f52cad81b/lib/camelCase.js#L12-L17
16,934
wireapp/wire-web-packages
packages/cryptobox/src/demo/benchmark.js
createCryptobox
async function createCryptobox(storeName, amountOfPreKeys = 1) { const engine = new MemoryEngine(); await engine.init(storeName); return new Cryptobox(engine, amountOfPreKeys); }
javascript
async function createCryptobox(storeName, amountOfPreKeys = 1) { const engine = new MemoryEngine(); await engine.init(storeName); return new Cryptobox(engine, amountOfPreKeys); }
[ "async", "function", "createCryptobox", "(", "storeName", ",", "amountOfPreKeys", "=", "1", ")", "{", "const", "engine", "=", "new", "MemoryEngine", "(", ")", ";", "await", "engine", ".", "init", "(", "storeName", ")", ";", "return", "new", "Cryptobox", "(", "engine", ",", "amountOfPreKeys", ")", ";", "}" ]
Creates a Cryptobox with an initialized store.
[ "Creates", "a", "Cryptobox", "with", "an", "initialized", "store", "." ]
b352ac2ba63bf069f13f3d0c706cbb98f2f8e719
https://github.com/wireapp/wire-web-packages/blob/b352ac2ba63bf069f13f3d0c706cbb98f2f8e719/packages/cryptobox/src/demo/benchmark.js#L25-L29
16,935
wireapp/wire-web-packages
packages/cryptobox/src/demo/benchmark.js
initialSetup
async function initialSetup() { const alice = await createCryptobox('alice', 1); await alice.create(); const bob = await createCryptobox('bob', 1); await bob.create(); const bobBundle = Proteus.keys.PreKeyBundle.new( bob.identity.public_key, await bob.store.load_prekey(Proteus.keys.PreKey.MAX_PREKEY_ID) ); const cipherMessage = await alice.encrypt(createSessionId(bob), 'Hello', bobBundle.serialise()); await bob.decrypt(createSessionId(alice), cipherMessage); return {alice, bob}; }
javascript
async function initialSetup() { const alice = await createCryptobox('alice', 1); await alice.create(); const bob = await createCryptobox('bob', 1); await bob.create(); const bobBundle = Proteus.keys.PreKeyBundle.new( bob.identity.public_key, await bob.store.load_prekey(Proteus.keys.PreKey.MAX_PREKEY_ID) ); const cipherMessage = await alice.encrypt(createSessionId(bob), 'Hello', bobBundle.serialise()); await bob.decrypt(createSessionId(alice), cipherMessage); return {alice, bob}; }
[ "async", "function", "initialSetup", "(", ")", "{", "const", "alice", "=", "await", "createCryptobox", "(", "'alice'", ",", "1", ")", ";", "await", "alice", ".", "create", "(", ")", ";", "const", "bob", "=", "await", "createCryptobox", "(", "'bob'", ",", "1", ")", ";", "await", "bob", ".", "create", "(", ")", ";", "const", "bobBundle", "=", "Proteus", ".", "keys", ".", "PreKeyBundle", ".", "new", "(", "bob", ".", "identity", ".", "public_key", ",", "await", "bob", ".", "store", ".", "load_prekey", "(", "Proteus", ".", "keys", ".", "PreKey", ".", "MAX_PREKEY_ID", ")", ")", ";", "const", "cipherMessage", "=", "await", "alice", ".", "encrypt", "(", "createSessionId", "(", "bob", ")", ",", "'Hello'", ",", "bobBundle", ".", "serialise", "(", ")", ")", ";", "await", "bob", ".", "decrypt", "(", "createSessionId", "(", "alice", ")", ",", "cipherMessage", ")", ";", "return", "{", "alice", ",", "bob", "}", ";", "}" ]
Creates participants and establishes sessions between them.
[ "Creates", "participants", "and", "establishes", "sessions", "between", "them", "." ]
b352ac2ba63bf069f13f3d0c706cbb98f2f8e719
https://github.com/wireapp/wire-web-packages/blob/b352ac2ba63bf069f13f3d0c706cbb98f2f8e719/packages/cryptobox/src/demo/benchmark.js#L32-L48
16,936
wireapp/wire-web-packages
packages/cryptobox/src/demo/benchmark.js
encryptBeforeDecrypt
async function encryptBeforeDecrypt({alice, bob}, messageCount) { const numbers = numbersInArray(messageCount); // Encryption process.stdout.write(`Measuring encryption time for "${messageCount}" messages ... `); let startTime = process.hrtime(); const encryptedMessages = await Promise.all( numbers.map(value => alice.encrypt(createSessionId(bob), `This is a long message with number ${value.toString()}`)) ); let stopTime = getTimeInSeconds(startTime); process.stdout.write('Done.\n'); console.info(`Execution time: ${stopTime} seconds.\n`); // Decryption process.stdout.write(`Measuring decryption time for "${messageCount}" messages ... `); startTime = process.hrtime(); await Promise.all( encryptedMessages.map(async encryptedMessage => await bob.decrypt(createSessionId(alice), encryptedMessage)) ); stopTime = getTimeInSeconds(startTime); process.stdout.write('Done.\n'); console.info(`Execution time: ${stopTime} seconds.\n`); }
javascript
async function encryptBeforeDecrypt({alice, bob}, messageCount) { const numbers = numbersInArray(messageCount); // Encryption process.stdout.write(`Measuring encryption time for "${messageCount}" messages ... `); let startTime = process.hrtime(); const encryptedMessages = await Promise.all( numbers.map(value => alice.encrypt(createSessionId(bob), `This is a long message with number ${value.toString()}`)) ); let stopTime = getTimeInSeconds(startTime); process.stdout.write('Done.\n'); console.info(`Execution time: ${stopTime} seconds.\n`); // Decryption process.stdout.write(`Measuring decryption time for "${messageCount}" messages ... `); startTime = process.hrtime(); await Promise.all( encryptedMessages.map(async encryptedMessage => await bob.decrypt(createSessionId(alice), encryptedMessage)) ); stopTime = getTimeInSeconds(startTime); process.stdout.write('Done.\n'); console.info(`Execution time: ${stopTime} seconds.\n`); }
[ "async", "function", "encryptBeforeDecrypt", "(", "{", "alice", ",", "bob", "}", ",", "messageCount", ")", "{", "const", "numbers", "=", "numbersInArray", "(", "messageCount", ")", ";", "// Encryption", "process", ".", "stdout", ".", "write", "(", "`", "${", "messageCount", "}", "`", ")", ";", "let", "startTime", "=", "process", ".", "hrtime", "(", ")", ";", "const", "encryptedMessages", "=", "await", "Promise", ".", "all", "(", "numbers", ".", "map", "(", "value", "=>", "alice", ".", "encrypt", "(", "createSessionId", "(", "bob", ")", ",", "`", "${", "value", ".", "toString", "(", ")", "}", "`", ")", ")", ")", ";", "let", "stopTime", "=", "getTimeInSeconds", "(", "startTime", ")", ";", "process", ".", "stdout", ".", "write", "(", "'Done.\\n'", ")", ";", "console", ".", "info", "(", "`", "${", "stopTime", "}", "\\n", "`", ")", ";", "// Decryption", "process", ".", "stdout", ".", "write", "(", "`", "${", "messageCount", "}", "`", ")", ";", "startTime", "=", "process", ".", "hrtime", "(", ")", ";", "await", "Promise", ".", "all", "(", "encryptedMessages", ".", "map", "(", "async", "encryptedMessage", "=>", "await", "bob", ".", "decrypt", "(", "createSessionId", "(", "alice", ")", ",", "encryptedMessage", ")", ")", ")", ";", "stopTime", "=", "getTimeInSeconds", "(", "startTime", ")", ";", "process", ".", "stdout", ".", "write", "(", "'Done.\\n'", ")", ";", "console", ".", "info", "(", "`", "${", "stopTime", "}", "\\n", "`", ")", ";", "}" ]
Runs the test scenario and measures times.
[ "Runs", "the", "test", "scenario", "and", "measures", "times", "." ]
b352ac2ba63bf069f13f3d0c706cbb98f2f8e719
https://github.com/wireapp/wire-web-packages/blob/b352ac2ba63bf069f13f3d0c706cbb98f2f8e719/packages/cryptobox/src/demo/benchmark.js#L51-L75
16,937
donatj/CsvToMarkdownTable
lib/CsvToMarkdown.js
csvToMarkdown
function csvToMarkdown(csvContent, delimiter, hasHeader) { if (delimiter === void 0) { delimiter = "\t"; } if (hasHeader === void 0) { hasHeader = false; } if (delimiter != "\t") { csvContent = csvContent.replace(/\t/g, " "); } var columns = csvContent.split("\n"); var tabularData = []; var maxRowLen = []; columns.forEach(function (e, i) { if (typeof tabularData[i] == "undefined") { tabularData[i] = []; } var regex = new RegExp(delimiter + '(?![^"]*"\\B)'); var row = e.split(regex); row.forEach(function (ee, ii) { if (typeof maxRowLen[ii] == "undefined") { maxRowLen[ii] = 0; } maxRowLen[ii] = Math.max(maxRowLen[ii], ee.length); tabularData[i][ii] = ee; }); }); var headerOutput = ""; var seperatorOutput = ""; maxRowLen.forEach(function (len) { var sizer = Array(len + 1 + 2); seperatorOutput += "|" + sizer.join("-"); headerOutput += "|" + sizer.join(" "); }); headerOutput += "| \n"; seperatorOutput += "| \n"; if (hasHeader) { headerOutput = ""; } var rowOutput = ""; tabularData.forEach(function (col, i) { maxRowLen.forEach(function (len, y) { var row = typeof col[y] == "undefined" ? "" : col[y]; var spacing = Array((len - row.length) + 1).join(" "); var out = "| " + row + spacing + " "; if (hasHeader && i === 0) { headerOutput += out; } else { rowOutput += out; } }); if (hasHeader && i === 0) { headerOutput += "| \n"; } else { rowOutput += "| \n"; } }); return "" + headerOutput + seperatorOutput + rowOutput; }
javascript
function csvToMarkdown(csvContent, delimiter, hasHeader) { if (delimiter === void 0) { delimiter = "\t"; } if (hasHeader === void 0) { hasHeader = false; } if (delimiter != "\t") { csvContent = csvContent.replace(/\t/g, " "); } var columns = csvContent.split("\n"); var tabularData = []; var maxRowLen = []; columns.forEach(function (e, i) { if (typeof tabularData[i] == "undefined") { tabularData[i] = []; } var regex = new RegExp(delimiter + '(?![^"]*"\\B)'); var row = e.split(regex); row.forEach(function (ee, ii) { if (typeof maxRowLen[ii] == "undefined") { maxRowLen[ii] = 0; } maxRowLen[ii] = Math.max(maxRowLen[ii], ee.length); tabularData[i][ii] = ee; }); }); var headerOutput = ""; var seperatorOutput = ""; maxRowLen.forEach(function (len) { var sizer = Array(len + 1 + 2); seperatorOutput += "|" + sizer.join("-"); headerOutput += "|" + sizer.join(" "); }); headerOutput += "| \n"; seperatorOutput += "| \n"; if (hasHeader) { headerOutput = ""; } var rowOutput = ""; tabularData.forEach(function (col, i) { maxRowLen.forEach(function (len, y) { var row = typeof col[y] == "undefined" ? "" : col[y]; var spacing = Array((len - row.length) + 1).join(" "); var out = "| " + row + spacing + " "; if (hasHeader && i === 0) { headerOutput += out; } else { rowOutput += out; } }); if (hasHeader && i === 0) { headerOutput += "| \n"; } else { rowOutput += "| \n"; } }); return "" + headerOutput + seperatorOutput + rowOutput; }
[ "function", "csvToMarkdown", "(", "csvContent", ",", "delimiter", ",", "hasHeader", ")", "{", "if", "(", "delimiter", "===", "void", "0", ")", "{", "delimiter", "=", "\"\\t\"", ";", "}", "if", "(", "hasHeader", "===", "void", "0", ")", "{", "hasHeader", "=", "false", ";", "}", "if", "(", "delimiter", "!=", "\"\\t\"", ")", "{", "csvContent", "=", "csvContent", ".", "replace", "(", "/", "\\t", "/", "g", ",", "\" \"", ")", ";", "}", "var", "columns", "=", "csvContent", ".", "split", "(", "\"\\n\"", ")", ";", "var", "tabularData", "=", "[", "]", ";", "var", "maxRowLen", "=", "[", "]", ";", "columns", ".", "forEach", "(", "function", "(", "e", ",", "i", ")", "{", "if", "(", "typeof", "tabularData", "[", "i", "]", "==", "\"undefined\"", ")", "{", "tabularData", "[", "i", "]", "=", "[", "]", ";", "}", "var", "regex", "=", "new", "RegExp", "(", "delimiter", "+", "'(?![^\"]*\"\\\\B)'", ")", ";", "var", "row", "=", "e", ".", "split", "(", "regex", ")", ";", "row", ".", "forEach", "(", "function", "(", "ee", ",", "ii", ")", "{", "if", "(", "typeof", "maxRowLen", "[", "ii", "]", "==", "\"undefined\"", ")", "{", "maxRowLen", "[", "ii", "]", "=", "0", ";", "}", "maxRowLen", "[", "ii", "]", "=", "Math", ".", "max", "(", "maxRowLen", "[", "ii", "]", ",", "ee", ".", "length", ")", ";", "tabularData", "[", "i", "]", "[", "ii", "]", "=", "ee", ";", "}", ")", ";", "}", ")", ";", "var", "headerOutput", "=", "\"\"", ";", "var", "seperatorOutput", "=", "\"\"", ";", "maxRowLen", ".", "forEach", "(", "function", "(", "len", ")", "{", "var", "sizer", "=", "Array", "(", "len", "+", "1", "+", "2", ")", ";", "seperatorOutput", "+=", "\"|\"", "+", "sizer", ".", "join", "(", "\"-\"", ")", ";", "headerOutput", "+=", "\"|\"", "+", "sizer", ".", "join", "(", "\" \"", ")", ";", "}", ")", ";", "headerOutput", "+=", "\"| \\n\"", ";", "seperatorOutput", "+=", "\"| \\n\"", ";", "if", "(", "hasHeader", ")", "{", "headerOutput", "=", "\"\"", ";", "}", "var", "rowOutput", "=", "\"\"", ";", "tabularData", ".", "forEach", "(", "function", "(", "col", ",", "i", ")", "{", "maxRowLen", ".", "forEach", "(", "function", "(", "len", ",", "y", ")", "{", "var", "row", "=", "typeof", "col", "[", "y", "]", "==", "\"undefined\"", "?", "\"\"", ":", "col", "[", "y", "]", ";", "var", "spacing", "=", "Array", "(", "(", "len", "-", "row", ".", "length", ")", "+", "1", ")", ".", "join", "(", "\" \"", ")", ";", "var", "out", "=", "\"| \"", "+", "row", "+", "spacing", "+", "\" \"", ";", "if", "(", "hasHeader", "&&", "i", "===", "0", ")", "{", "headerOutput", "+=", "out", ";", "}", "else", "{", "rowOutput", "+=", "out", ";", "}", "}", ")", ";", "if", "(", "hasHeader", "&&", "i", "===", "0", ")", "{", "headerOutput", "+=", "\"| \\n\"", ";", "}", "else", "{", "rowOutput", "+=", "\"| \\n\"", ";", "}", "}", ")", ";", "return", "\"\"", "+", "headerOutput", "+", "seperatorOutput", "+", "rowOutput", ";", "}" ]
Converts CSV to Markdown Table @param {string} csvContent - The string content of the CSV @param {string} delimiter - The character(s) to use as the CSV column delimiter @param {boolean} hasHeader - Whether to use the first row of Data as headers @returns {string}
[ "Converts", "CSV", "to", "Markdown", "Table" ]
2f3182f99e84a88f393d0d02d23e9dc7e499b2f3
https://github.com/donatj/CsvToMarkdownTable/blob/2f3182f99e84a88f393d0d02d23e9dc7e499b2f3/lib/CsvToMarkdown.js#L11-L67
16,938
wcm-io-frontend/aem-clientlib-generator
lib/clientlib.js
writeClientLibJson
function writeClientLibJson(item, options) { var content = { 'jcr:primaryType': 'cq:ClientLibraryFolder' }; // if categories is a config entry append the values to the array, else use item.name if (item.hasOwnProperty('categories')) { content.categories = item['categories']; } else { content.categories = [item.name]; } clientLibDirectoryFields.forEach(function (nodeKey) { if (item.hasOwnProperty(nodeKey)) { content[nodeKey] = item[nodeKey]; } }); var jsonFile = path.join(item.path, item.name + ".json"); options.verbose && console.log("write clientlib json file: " + jsonFile); if (!options.dry) { fse.writeJsonSync(jsonFile, content, {spaces: 2}); } }
javascript
function writeClientLibJson(item, options) { var content = { 'jcr:primaryType': 'cq:ClientLibraryFolder' }; // if categories is a config entry append the values to the array, else use item.name if (item.hasOwnProperty('categories')) { content.categories = item['categories']; } else { content.categories = [item.name]; } clientLibDirectoryFields.forEach(function (nodeKey) { if (item.hasOwnProperty(nodeKey)) { content[nodeKey] = item[nodeKey]; } }); var jsonFile = path.join(item.path, item.name + ".json"); options.verbose && console.log("write clientlib json file: " + jsonFile); if (!options.dry) { fse.writeJsonSync(jsonFile, content, {spaces: 2}); } }
[ "function", "writeClientLibJson", "(", "item", ",", "options", ")", "{", "var", "content", "=", "{", "'jcr:primaryType'", ":", "'cq:ClientLibraryFolder'", "}", ";", "// if categories is a config entry append the values to the array, else use item.name", "if", "(", "item", ".", "hasOwnProperty", "(", "'categories'", ")", ")", "{", "content", ".", "categories", "=", "item", "[", "'categories'", "]", ";", "}", "else", "{", "content", ".", "categories", "=", "[", "item", ".", "name", "]", ";", "}", "clientLibDirectoryFields", ".", "forEach", "(", "function", "(", "nodeKey", ")", "{", "if", "(", "item", ".", "hasOwnProperty", "(", "nodeKey", ")", ")", "{", "content", "[", "nodeKey", "]", "=", "item", "[", "nodeKey", "]", ";", "}", "}", ")", ";", "var", "jsonFile", "=", "path", ".", "join", "(", "item", ".", "path", ",", "item", ".", "name", "+", "\".json\"", ")", ";", "options", ".", "verbose", "&&", "console", ".", "log", "(", "\"write clientlib json file: \"", "+", "jsonFile", ")", ";", "if", "(", "!", "options", ".", "dry", ")", "{", "fse", ".", "writeJsonSync", "(", "jsonFile", ",", "content", ",", "{", "spaces", ":", "2", "}", ")", ";", "}", "}" ]
Write a configuration JSON file for a clientlib with the given properties in `item` @param {ClientLibItem} item - clientlib configuration properties @param {Object} options - further options
[ "Write", "a", "configuration", "JSON", "file", "for", "a", "clientlib", "with", "the", "given", "properties", "in", "item" ]
1693581f1da375f8c5ac60a33e5e1636df6e8f35
https://github.com/wcm-io-frontend/aem-clientlib-generator/blob/1693581f1da375f8c5ac60a33e5e1636df6e8f35/lib/clientlib.js#L154-L178
16,939
wcm-io-frontend/aem-clientlib-generator
lib/clientlib.js
writeClientLibXml
function writeClientLibXml(item, options) { var content = '<?xml version="1.0" encoding="UTF-8"?>' + '<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"' + ' jcr:primaryType="cq:ClientLibraryFolder"'; if (item.hasOwnProperty('categories')) { var fieldValue = item.categories.join(','); content += ' categories="[' + fieldValue + ']"'; } else { content += ' categories="[' + item.name + ']" '; } clientLibDirectoryFields.forEach(function (fieldKey) { if (item.hasOwnProperty(fieldKey)) { if (typeof item[fieldKey] === 'boolean') { // Boolean value content += ' ' + fieldKey + '="{Boolean}' + item[fieldKey] + '"'; } else if (Array.isArray(item[fieldKey])) { // Array of strings var fieldValue = item[fieldKey].join(','); content += ' ' + fieldKey + '="[' + fieldValue + ']"'; } else if (typeof item[fieldKey] === 'string') { // String value content += ' ' + fieldKey + '="' + item[fieldKey] + '"'; } } }); content += "/>"; var outputPath = item.outputPath || path.join(item.path, item.name); var contentXml = path.join(outputPath + "/.content.xml"); options.verbose && console.log("write clientlib json file: " + contentXml); fse.writeFileSync(contentXml, content); }
javascript
function writeClientLibXml(item, options) { var content = '<?xml version="1.0" encoding="UTF-8"?>' + '<jcr:root xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0"' + ' jcr:primaryType="cq:ClientLibraryFolder"'; if (item.hasOwnProperty('categories')) { var fieldValue = item.categories.join(','); content += ' categories="[' + fieldValue + ']"'; } else { content += ' categories="[' + item.name + ']" '; } clientLibDirectoryFields.forEach(function (fieldKey) { if (item.hasOwnProperty(fieldKey)) { if (typeof item[fieldKey] === 'boolean') { // Boolean value content += ' ' + fieldKey + '="{Boolean}' + item[fieldKey] + '"'; } else if (Array.isArray(item[fieldKey])) { // Array of strings var fieldValue = item[fieldKey].join(','); content += ' ' + fieldKey + '="[' + fieldValue + ']"'; } else if (typeof item[fieldKey] === 'string') { // String value content += ' ' + fieldKey + '="' + item[fieldKey] + '"'; } } }); content += "/>"; var outputPath = item.outputPath || path.join(item.path, item.name); var contentXml = path.join(outputPath + "/.content.xml"); options.verbose && console.log("write clientlib json file: " + contentXml); fse.writeFileSync(contentXml, content); }
[ "function", "writeClientLibXml", "(", "item", ",", "options", ")", "{", "var", "content", "=", "'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'", "+", "'<jcr:root xmlns:cq=\"http://www.day.com/jcr/cq/1.0\" xmlns:jcr=\"http://www.jcp.org/jcr/1.0\"'", "+", "' jcr:primaryType=\"cq:ClientLibraryFolder\"'", ";", "if", "(", "item", ".", "hasOwnProperty", "(", "'categories'", ")", ")", "{", "var", "fieldValue", "=", "item", ".", "categories", ".", "join", "(", "','", ")", ";", "content", "+=", "' categories=\"['", "+", "fieldValue", "+", "']\"'", ";", "}", "else", "{", "content", "+=", "' categories=\"['", "+", "item", ".", "name", "+", "']\" '", ";", "}", "clientLibDirectoryFields", ".", "forEach", "(", "function", "(", "fieldKey", ")", "{", "if", "(", "item", ".", "hasOwnProperty", "(", "fieldKey", ")", ")", "{", "if", "(", "typeof", "item", "[", "fieldKey", "]", "===", "'boolean'", ")", "{", "// Boolean value", "content", "+=", "' '", "+", "fieldKey", "+", "'=\"{Boolean}'", "+", "item", "[", "fieldKey", "]", "+", "'\"'", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "item", "[", "fieldKey", "]", ")", ")", "{", "// Array of strings", "var", "fieldValue", "=", "item", "[", "fieldKey", "]", ".", "join", "(", "','", ")", ";", "content", "+=", "' '", "+", "fieldKey", "+", "'=\"['", "+", "fieldValue", "+", "']\"'", ";", "}", "else", "if", "(", "typeof", "item", "[", "fieldKey", "]", "===", "'string'", ")", "{", "// String value", "content", "+=", "' '", "+", "fieldKey", "+", "'=\"'", "+", "item", "[", "fieldKey", "]", "+", "'\"'", ";", "}", "}", "}", ")", ";", "content", "+=", "\"/>\"", ";", "var", "outputPath", "=", "item", ".", "outputPath", "||", "path", ".", "join", "(", "item", ".", "path", ",", "item", ".", "name", ")", ";", "var", "contentXml", "=", "path", ".", "join", "(", "outputPath", "+", "\"/.content.xml\"", ")", ";", "options", ".", "verbose", "&&", "console", ".", "log", "(", "\"write clientlib json file: \"", "+", "contentXml", ")", ";", "fse", ".", "writeFileSync", "(", "contentXml", ",", "content", ")", ";", "}" ]
Write a configuration XML file for a clientlib with the given properties in `item` @param {ClientLibItem} item - clientlib configuration properties @param {Object} options - further options
[ "Write", "a", "configuration", "XML", "file", "for", "a", "clientlib", "with", "the", "given", "properties", "in", "item" ]
1693581f1da375f8c5ac60a33e5e1636df6e8f35
https://github.com/wcm-io-frontend/aem-clientlib-generator/blob/1693581f1da375f8c5ac60a33e5e1636df6e8f35/lib/clientlib.js#L186-L221
16,940
wcm-io-frontend/aem-clientlib-generator
lib/clientlib.js
start
function start(itemList, options, done) { if (_.isFunction(options)) { done = options; options = {}; } if (!_.isArray(itemList)) { itemList = [itemList]; } if (options.context || options.cwd) { options.cwd = options.context || options.cwd; process.chdir(options.cwd); } if (options.verbose) { console.log("\nstart aem-clientlib-generator"); console.log(" working directory: " + process.cwd()); } options.dry && console.log("\nDRY MODE - without write options!"); async.eachSeries(itemList, function (item, processItemDone) { processItem(item, options, processItemDone); }, done); }
javascript
function start(itemList, options, done) { if (_.isFunction(options)) { done = options; options = {}; } if (!_.isArray(itemList)) { itemList = [itemList]; } if (options.context || options.cwd) { options.cwd = options.context || options.cwd; process.chdir(options.cwd); } if (options.verbose) { console.log("\nstart aem-clientlib-generator"); console.log(" working directory: " + process.cwd()); } options.dry && console.log("\nDRY MODE - without write options!"); async.eachSeries(itemList, function (item, processItemDone) { processItem(item, options, processItemDone); }, done); }
[ "function", "start", "(", "itemList", ",", "options", ",", "done", ")", "{", "if", "(", "_", ".", "isFunction", "(", "options", ")", ")", "{", "done", "=", "options", ";", "options", "=", "{", "}", ";", "}", "if", "(", "!", "_", ".", "isArray", "(", "itemList", ")", ")", "{", "itemList", "=", "[", "itemList", "]", ";", "}", "if", "(", "options", ".", "context", "||", "options", ".", "cwd", ")", "{", "options", ".", "cwd", "=", "options", ".", "context", "||", "options", ".", "cwd", ";", "process", ".", "chdir", "(", "options", ".", "cwd", ")", ";", "}", "if", "(", "options", ".", "verbose", ")", "{", "console", ".", "log", "(", "\"\\nstart aem-clientlib-generator\"", ")", ";", "console", ".", "log", "(", "\" working directory: \"", "+", "process", ".", "cwd", "(", ")", ")", ";", "}", "options", ".", "dry", "&&", "console", ".", "log", "(", "\"\\nDRY MODE - without write options!\"", ")", ";", "async", ".", "eachSeries", "(", "itemList", ",", "function", "(", "item", ",", "processItemDone", ")", "{", "processItem", "(", "item", ",", "options", ",", "processItemDone", ")", ";", "}", ",", "done", ")", ";", "}" ]
Iterate through the given array of clientlib configuration objects and process them asynchronously. @param {Array<ClientLibItem>} itemList - array of clientlib configuration items @param {Object} [options] - global configuration options @param {Function} done - to be called if everything is done
[ "Iterate", "through", "the", "given", "array", "of", "clientlib", "configuration", "objects", "and", "process", "them", "asynchronously", "." ]
1693581f1da375f8c5ac60a33e5e1636df6e8f35
https://github.com/wcm-io-frontend/aem-clientlib-generator/blob/1693581f1da375f8c5ac60a33e5e1636df6e8f35/lib/clientlib.js#L230-L255
16,941
wcm-io-frontend/aem-clientlib-generator
lib/clientlib.js
normalizeAssets
function normalizeAssets(clientLibPath, assets) { var list = assets; // transform object to array if (!_.isArray(assets)) { list = []; _.keys(assets).forEach(function (assetKey) { var assetItem = assets[assetKey]; // check/transform short version if (_.isArray(assetItem)) { assetItem = { files: assetItem }; } if (!assetItem.base) { assetItem.base = assetKey; } assetItem.type = assetKey; list.push(assetItem); }); } // transform files to scr-dest mapping list.forEach(function (asset) { var mapping = []; var flatName = typeof asset.flatten !== "boolean" ? true : asset.flatten; var assetPath = path.posix.join(clientLibPath, asset.base); var globOptions = {}; if (asset.cwd) { globOptions.cwd = asset.cwd; } asset.files.forEach(function (file) { var fileItem = file; // convert simple syntax to object if (_.isString(file)) { fileItem = { src: file }; } // no magic pattern -> default behaviour if (!glob.hasMagic(fileItem.src)) { // determine default dest if (!fileItem.dest) { fileItem.dest = path.posix.basename(file); } // generate full path fileItem.dest = path.posix.join(assetPath, fileItem.dest); mapping.push(fileItem); } // resolve magic pattern else { var files = glob.sync(fileItem.src, globOptions); var hasCwd = !!globOptions.cwd; var dest = fileItem.dest ? path.posix.join(assetPath, fileItem.dest) : assetPath; files.forEach(function (resolvedFile) { // check 'flatten' option -> strip dir name var destFile = flatName ? path.posix.basename(resolvedFile) : resolvedFile; var item = { src: resolvedFile, dest: path.posix.join(dest, destFile) }; // check "cwd" option -> rebuild path, because it was stripped by glob.sync() if (hasCwd) { item.src = path.posix.join(globOptions.cwd, resolvedFile); } mapping.push(item); }); } }); asset.files = mapping; }); return list; }
javascript
function normalizeAssets(clientLibPath, assets) { var list = assets; // transform object to array if (!_.isArray(assets)) { list = []; _.keys(assets).forEach(function (assetKey) { var assetItem = assets[assetKey]; // check/transform short version if (_.isArray(assetItem)) { assetItem = { files: assetItem }; } if (!assetItem.base) { assetItem.base = assetKey; } assetItem.type = assetKey; list.push(assetItem); }); } // transform files to scr-dest mapping list.forEach(function (asset) { var mapping = []; var flatName = typeof asset.flatten !== "boolean" ? true : asset.flatten; var assetPath = path.posix.join(clientLibPath, asset.base); var globOptions = {}; if (asset.cwd) { globOptions.cwd = asset.cwd; } asset.files.forEach(function (file) { var fileItem = file; // convert simple syntax to object if (_.isString(file)) { fileItem = { src: file }; } // no magic pattern -> default behaviour if (!glob.hasMagic(fileItem.src)) { // determine default dest if (!fileItem.dest) { fileItem.dest = path.posix.basename(file); } // generate full path fileItem.dest = path.posix.join(assetPath, fileItem.dest); mapping.push(fileItem); } // resolve magic pattern else { var files = glob.sync(fileItem.src, globOptions); var hasCwd = !!globOptions.cwd; var dest = fileItem.dest ? path.posix.join(assetPath, fileItem.dest) : assetPath; files.forEach(function (resolvedFile) { // check 'flatten' option -> strip dir name var destFile = flatName ? path.posix.basename(resolvedFile) : resolvedFile; var item = { src: resolvedFile, dest: path.posix.join(dest, destFile) }; // check "cwd" option -> rebuild path, because it was stripped by glob.sync() if (hasCwd) { item.src = path.posix.join(globOptions.cwd, resolvedFile); } mapping.push(item); }); } }); asset.files = mapping; }); return list; }
[ "function", "normalizeAssets", "(", "clientLibPath", ",", "assets", ")", "{", "var", "list", "=", "assets", ";", "// transform object to array", "if", "(", "!", "_", ".", "isArray", "(", "assets", ")", ")", "{", "list", "=", "[", "]", ";", "_", ".", "keys", "(", "assets", ")", ".", "forEach", "(", "function", "(", "assetKey", ")", "{", "var", "assetItem", "=", "assets", "[", "assetKey", "]", ";", "// check/transform short version", "if", "(", "_", ".", "isArray", "(", "assetItem", ")", ")", "{", "assetItem", "=", "{", "files", ":", "assetItem", "}", ";", "}", "if", "(", "!", "assetItem", ".", "base", ")", "{", "assetItem", ".", "base", "=", "assetKey", ";", "}", "assetItem", ".", "type", "=", "assetKey", ";", "list", ".", "push", "(", "assetItem", ")", ";", "}", ")", ";", "}", "// transform files to scr-dest mapping", "list", ".", "forEach", "(", "function", "(", "asset", ")", "{", "var", "mapping", "=", "[", "]", ";", "var", "flatName", "=", "typeof", "asset", ".", "flatten", "!==", "\"boolean\"", "?", "true", ":", "asset", ".", "flatten", ";", "var", "assetPath", "=", "path", ".", "posix", ".", "join", "(", "clientLibPath", ",", "asset", ".", "base", ")", ";", "var", "globOptions", "=", "{", "}", ";", "if", "(", "asset", ".", "cwd", ")", "{", "globOptions", ".", "cwd", "=", "asset", ".", "cwd", ";", "}", "asset", ".", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "var", "fileItem", "=", "file", ";", "// convert simple syntax to object", "if", "(", "_", ".", "isString", "(", "file", ")", ")", "{", "fileItem", "=", "{", "src", ":", "file", "}", ";", "}", "// no magic pattern -> default behaviour", "if", "(", "!", "glob", ".", "hasMagic", "(", "fileItem", ".", "src", ")", ")", "{", "// determine default dest", "if", "(", "!", "fileItem", ".", "dest", ")", "{", "fileItem", ".", "dest", "=", "path", ".", "posix", ".", "basename", "(", "file", ")", ";", "}", "// generate full path", "fileItem", ".", "dest", "=", "path", ".", "posix", ".", "join", "(", "assetPath", ",", "fileItem", ".", "dest", ")", ";", "mapping", ".", "push", "(", "fileItem", ")", ";", "}", "// resolve magic pattern", "else", "{", "var", "files", "=", "glob", ".", "sync", "(", "fileItem", ".", "src", ",", "globOptions", ")", ";", "var", "hasCwd", "=", "!", "!", "globOptions", ".", "cwd", ";", "var", "dest", "=", "fileItem", ".", "dest", "?", "path", ".", "posix", ".", "join", "(", "assetPath", ",", "fileItem", ".", "dest", ")", ":", "assetPath", ";", "files", ".", "forEach", "(", "function", "(", "resolvedFile", ")", "{", "// check 'flatten' option -> strip dir name", "var", "destFile", "=", "flatName", "?", "path", ".", "posix", ".", "basename", "(", "resolvedFile", ")", ":", "resolvedFile", ";", "var", "item", "=", "{", "src", ":", "resolvedFile", ",", "dest", ":", "path", ".", "posix", ".", "join", "(", "dest", ",", "destFile", ")", "}", ";", "// check \"cwd\" option -> rebuild path, because it was stripped by glob.sync()", "if", "(", "hasCwd", ")", "{", "item", ".", "src", "=", "path", ".", "posix", ".", "join", "(", "globOptions", ".", "cwd", ",", "resolvedFile", ")", ";", "}", "mapping", ".", "push", "(", "item", ")", ";", "}", ")", ";", "}", "}", ")", ";", "asset", ".", "files", "=", "mapping", ";", "}", ")", ";", "return", "list", ";", "}" ]
Normalize different asset configuration options. @param {String} clientLibPath - clientlib subfolder @param {Object} assets - asset configuration object @returns {*}
[ "Normalize", "different", "asset", "configuration", "options", "." ]
1693581f1da375f8c5ac60a33e5e1636df6e8f35
https://github.com/wcm-io-frontend/aem-clientlib-generator/blob/1693581f1da375f8c5ac60a33e5e1636df6e8f35/lib/clientlib.js#L263-L351
16,942
wcm-io-frontend/aem-clientlib-generator
lib/clientlib.js
processItem
function processItem(item, options, processDone) { if (!item.path) { item.path = options.clientLibRoot; } options.verbose && console.log("\n\nprocessing clientlib: " + item.name); // remove current files if exists removeClientLib(item, function (err) { var clientLibPath = item.outputPath || path.join(item.path, item.name); // create clientlib directory fse.mkdirsSync(clientLibPath); var serializationFormat = (item.serializationFormat === SERIALIZATION_FORMAT_XML) ? SERIALIZATION_FORMAT_XML : SERIALIZATION_FORMAT_JSON; options.verbose && console.log("Write node configuration using serialization format: " + serializationFormat); if (serializationFormat === SERIALIZATION_FORMAT_JSON) { // write configuration JSON writeClientLibJson(item, options); } else { writeClientLibXml(item, options); } var assetList = normalizeAssets(clientLibPath, item.assets); // iterate through assets async.eachSeries(assetList, function (asset, assetDone) { // write clientlib creator files if (asset.type === "js" || asset.type === "css") { options.verbose && console.log(""); writeAssetTxt(clientLibPath, asset, options); } // copy files for given asset async.eachSeries(asset.files, function (fileItem, copyDone) { if (fileItem.src == fileItem.dest) { options.verbose && console.log(`${fileItem.src} already in output directory`); return copyDone(); } options.verbose && console.log("copy:", fileItem.src, fileItem.dest); if (options.dry) { return copyDone(); } // create directories separately or it will be copied recursively if (fs.lstatSync(fileItem.src).isDirectory()) { fs.mkdir(fileItem.dest, copyDone); } else { fse.copy(fileItem.src, fileItem.dest, copyDone); } }, assetDone); }, processDone); }); }
javascript
function processItem(item, options, processDone) { if (!item.path) { item.path = options.clientLibRoot; } options.verbose && console.log("\n\nprocessing clientlib: " + item.name); // remove current files if exists removeClientLib(item, function (err) { var clientLibPath = item.outputPath || path.join(item.path, item.name); // create clientlib directory fse.mkdirsSync(clientLibPath); var serializationFormat = (item.serializationFormat === SERIALIZATION_FORMAT_XML) ? SERIALIZATION_FORMAT_XML : SERIALIZATION_FORMAT_JSON; options.verbose && console.log("Write node configuration using serialization format: " + serializationFormat); if (serializationFormat === SERIALIZATION_FORMAT_JSON) { // write configuration JSON writeClientLibJson(item, options); } else { writeClientLibXml(item, options); } var assetList = normalizeAssets(clientLibPath, item.assets); // iterate through assets async.eachSeries(assetList, function (asset, assetDone) { // write clientlib creator files if (asset.type === "js" || asset.type === "css") { options.verbose && console.log(""); writeAssetTxt(clientLibPath, asset, options); } // copy files for given asset async.eachSeries(asset.files, function (fileItem, copyDone) { if (fileItem.src == fileItem.dest) { options.verbose && console.log(`${fileItem.src} already in output directory`); return copyDone(); } options.verbose && console.log("copy:", fileItem.src, fileItem.dest); if (options.dry) { return copyDone(); } // create directories separately or it will be copied recursively if (fs.lstatSync(fileItem.src).isDirectory()) { fs.mkdir(fileItem.dest, copyDone); } else { fse.copy(fileItem.src, fileItem.dest, copyDone); } }, assetDone); }, processDone); }); }
[ "function", "processItem", "(", "item", ",", "options", ",", "processDone", ")", "{", "if", "(", "!", "item", ".", "path", ")", "{", "item", ".", "path", "=", "options", ".", "clientLibRoot", ";", "}", "options", ".", "verbose", "&&", "console", ".", "log", "(", "\"\\n\\nprocessing clientlib: \"", "+", "item", ".", "name", ")", ";", "// remove current files if exists", "removeClientLib", "(", "item", ",", "function", "(", "err", ")", "{", "var", "clientLibPath", "=", "item", ".", "outputPath", "||", "path", ".", "join", "(", "item", ".", "path", ",", "item", ".", "name", ")", ";", "// create clientlib directory", "fse", ".", "mkdirsSync", "(", "clientLibPath", ")", ";", "var", "serializationFormat", "=", "(", "item", ".", "serializationFormat", "===", "SERIALIZATION_FORMAT_XML", ")", "?", "SERIALIZATION_FORMAT_XML", ":", "SERIALIZATION_FORMAT_JSON", ";", "options", ".", "verbose", "&&", "console", ".", "log", "(", "\"Write node configuration using serialization format: \"", "+", "serializationFormat", ")", ";", "if", "(", "serializationFormat", "===", "SERIALIZATION_FORMAT_JSON", ")", "{", "// write configuration JSON", "writeClientLibJson", "(", "item", ",", "options", ")", ";", "}", "else", "{", "writeClientLibXml", "(", "item", ",", "options", ")", ";", "}", "var", "assetList", "=", "normalizeAssets", "(", "clientLibPath", ",", "item", ".", "assets", ")", ";", "// iterate through assets", "async", ".", "eachSeries", "(", "assetList", ",", "function", "(", "asset", ",", "assetDone", ")", "{", "// write clientlib creator files", "if", "(", "asset", ".", "type", "===", "\"js\"", "||", "asset", ".", "type", "===", "\"css\"", ")", "{", "options", ".", "verbose", "&&", "console", ".", "log", "(", "\"\"", ")", ";", "writeAssetTxt", "(", "clientLibPath", ",", "asset", ",", "options", ")", ";", "}", "// copy files for given asset", "async", ".", "eachSeries", "(", "asset", ".", "files", ",", "function", "(", "fileItem", ",", "copyDone", ")", "{", "if", "(", "fileItem", ".", "src", "==", "fileItem", ".", "dest", ")", "{", "options", ".", "verbose", "&&", "console", ".", "log", "(", "`", "${", "fileItem", ".", "src", "}", "`", ")", ";", "return", "copyDone", "(", ")", ";", "}", "options", ".", "verbose", "&&", "console", ".", "log", "(", "\"copy:\"", ",", "fileItem", ".", "src", ",", "fileItem", ".", "dest", ")", ";", "if", "(", "options", ".", "dry", ")", "{", "return", "copyDone", "(", ")", ";", "}", "// create directories separately or it will be copied recursively", "if", "(", "fs", ".", "lstatSync", "(", "fileItem", ".", "src", ")", ".", "isDirectory", "(", ")", ")", "{", "fs", ".", "mkdir", "(", "fileItem", ".", "dest", ",", "copyDone", ")", ";", "}", "else", "{", "fse", ".", "copy", "(", "fileItem", ".", "src", ",", "fileItem", ".", "dest", ",", "copyDone", ")", ";", "}", "}", ",", "assetDone", ")", ";", "}", ",", "processDone", ")", ";", "}", ")", ";", "}" ]
Process the given clientlib configuration object. @param {ClientLibItem} item - clientlib configuration object @param {Object} options - configuration options @param {Function} processDone - to be called if everything is done
[ "Process", "the", "given", "clientlib", "configuration", "object", "." ]
1693581f1da375f8c5ac60a33e5e1636df6e8f35
https://github.com/wcm-io-frontend/aem-clientlib-generator/blob/1693581f1da375f8c5ac60a33e5e1636df6e8f35/lib/clientlib.js#L359-L418
16,943
vsiakka/gherkin-lint
src/rules/no-restricted-patterns.js
checkFeatureChildNode
function checkFeatureChildNode(node, restrictedPatterns, errors) { checkNameAndDescription(node, restrictedPatterns, errors); node.steps.forEach(function(step) { // Use the node type of the parent to determine which rule configuration to use checkStepNode(step, restrictedPatterns[node.type], errors); }); }
javascript
function checkFeatureChildNode(node, restrictedPatterns, errors) { checkNameAndDescription(node, restrictedPatterns, errors); node.steps.forEach(function(step) { // Use the node type of the parent to determine which rule configuration to use checkStepNode(step, restrictedPatterns[node.type], errors); }); }
[ "function", "checkFeatureChildNode", "(", "node", ",", "restrictedPatterns", ",", "errors", ")", "{", "checkNameAndDescription", "(", "node", ",", "restrictedPatterns", ",", "errors", ")", ";", "node", ".", "steps", ".", "forEach", "(", "function", "(", "step", ")", "{", "// Use the node type of the parent to determine which rule configuration to use", "checkStepNode", "(", "step", ",", "restrictedPatterns", "[", "node", ".", "type", "]", ",", "errors", ")", ";", "}", ")", ";", "}" ]
Background, Scenarios and Scenario Outlines are children of a feature
[ "Background", "Scenarios", "and", "Scenario", "Outlines", "are", "children", "of", "a", "feature" ]
59ea830b8d84e95642290d74f6e8ff592f8c849a
https://github.com/vsiakka/gherkin-lint/blob/59ea830b8d84e95642290d74f6e8ff592f8c849a/src/rules/no-restricted-patterns.js#L54-L60
16,944
vsiakka/gherkin-lint
src/feature-finder.js
getFeatureFiles
function getFeatureFiles(args, ignoreArg) { var files = []; var patterns = args.length ? args : ['.']; patterns.forEach(function(pattern) { // First we need to fix up the pattern so that it only matches .feature files // and it's in the format that glob expects it to be var fixedPattern; if (pattern == '.') { fixedPattern = '**/*.feature'; } else if (pattern.match(/.*\/\*\*/)) { fixedPattern = pattern + '/**.feature'; } else if (pattern.match(/.*\.feature/)) { fixedPattern = pattern; } else { try { if (fs.statSync(pattern).isDirectory()) { fixedPattern = path.join(pattern, '**/*.feature'); } } catch(e) { // Don't show the fs callstack, we will print a custom error message bellow instead } } if (!fixedPattern) { logger.boldError(`Invalid format of the feature file path/pattern: "${pattern}".\nTo run the linter please specify an existing feature file, directory or glob.`); process.exit(1); return; // This line will only be hit by tests that stub process.exit } var globOptions = {ignore: getIgnorePatterns(ignoreArg)}; files = files.concat(glob.sync(fixedPattern, globOptions)); }); return _.uniq(files); }
javascript
function getFeatureFiles(args, ignoreArg) { var files = []; var patterns = args.length ? args : ['.']; patterns.forEach(function(pattern) { // First we need to fix up the pattern so that it only matches .feature files // and it's in the format that glob expects it to be var fixedPattern; if (pattern == '.') { fixedPattern = '**/*.feature'; } else if (pattern.match(/.*\/\*\*/)) { fixedPattern = pattern + '/**.feature'; } else if (pattern.match(/.*\.feature/)) { fixedPattern = pattern; } else { try { if (fs.statSync(pattern).isDirectory()) { fixedPattern = path.join(pattern, '**/*.feature'); } } catch(e) { // Don't show the fs callstack, we will print a custom error message bellow instead } } if (!fixedPattern) { logger.boldError(`Invalid format of the feature file path/pattern: "${pattern}".\nTo run the linter please specify an existing feature file, directory or glob.`); process.exit(1); return; // This line will only be hit by tests that stub process.exit } var globOptions = {ignore: getIgnorePatterns(ignoreArg)}; files = files.concat(glob.sync(fixedPattern, globOptions)); }); return _.uniq(files); }
[ "function", "getFeatureFiles", "(", "args", ",", "ignoreArg", ")", "{", "var", "files", "=", "[", "]", ";", "var", "patterns", "=", "args", ".", "length", "?", "args", ":", "[", "'.'", "]", ";", "patterns", ".", "forEach", "(", "function", "(", "pattern", ")", "{", "// First we need to fix up the pattern so that it only matches .feature files", "// and it's in the format that glob expects it to be", "var", "fixedPattern", ";", "if", "(", "pattern", "==", "'.'", ")", "{", "fixedPattern", "=", "'**/*.feature'", ";", "}", "else", "if", "(", "pattern", ".", "match", "(", "/", ".*\\/\\*\\*", "/", ")", ")", "{", "fixedPattern", "=", "pattern", "+", "'/**.feature'", ";", "}", "else", "if", "(", "pattern", ".", "match", "(", "/", ".*\\.feature", "/", ")", ")", "{", "fixedPattern", "=", "pattern", ";", "}", "else", "{", "try", "{", "if", "(", "fs", ".", "statSync", "(", "pattern", ")", ".", "isDirectory", "(", ")", ")", "{", "fixedPattern", "=", "path", ".", "join", "(", "pattern", ",", "'**/*.feature'", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "// Don't show the fs callstack, we will print a custom error message bellow instead", "}", "}", "if", "(", "!", "fixedPattern", ")", "{", "logger", ".", "boldError", "(", "`", "${", "pattern", "}", "\\n", "`", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "return", ";", "// This line will only be hit by tests that stub process.exit", "}", "var", "globOptions", "=", "{", "ignore", ":", "getIgnorePatterns", "(", "ignoreArg", ")", "}", ";", "files", "=", "files", ".", "concat", "(", "glob", ".", "sync", "(", "fixedPattern", ",", "globOptions", ")", ")", ";", "}", ")", ";", "return", "_", ".", "uniq", "(", "files", ")", ";", "}" ]
Ignore node_modules by default
[ "Ignore", "node_modules", "by", "default" ]
59ea830b8d84e95642290d74f6e8ff592f8c849a
https://github.com/vsiakka/gherkin-lint/blob/59ea830b8d84e95642290d74f6e8ff592f8c849a/src/feature-finder.js#L10-L44
16,945
CleverCloud/clever-tools
src/models/log.js
getContinuousLogs
function getContinuousLogs (api, appId, before, after, search, deploymentId) { function makeUrl (retryTimestamp) { const newAfter = retryTimestamp === null || after.getTime() > retryTimestamp.getTime() ? after : retryTimestamp; return getWsLogUrl(appId, newAfter.toISOString(), search, deploymentId); }; return WsStream .openStream(makeUrl, api.session.getAuthorization('GET', getAppLogsUrl(appId), {})) .filter((line) => { const lineDate = Date.parse(line._source['@timestamp']); const isBefore = !before || lineDate < before.getTime(); const isAfter = !after || lineDate > after.getTime(); return isBefore && isAfter; }); }
javascript
function getContinuousLogs (api, appId, before, after, search, deploymentId) { function makeUrl (retryTimestamp) { const newAfter = retryTimestamp === null || after.getTime() > retryTimestamp.getTime() ? after : retryTimestamp; return getWsLogUrl(appId, newAfter.toISOString(), search, deploymentId); }; return WsStream .openStream(makeUrl, api.session.getAuthorization('GET', getAppLogsUrl(appId), {})) .filter((line) => { const lineDate = Date.parse(line._source['@timestamp']); const isBefore = !before || lineDate < before.getTime(); const isAfter = !after || lineDate > after.getTime(); return isBefore && isAfter; }); }
[ "function", "getContinuousLogs", "(", "api", ",", "appId", ",", "before", ",", "after", ",", "search", ",", "deploymentId", ")", "{", "function", "makeUrl", "(", "retryTimestamp", ")", "{", "const", "newAfter", "=", "retryTimestamp", "===", "null", "||", "after", ".", "getTime", "(", ")", ">", "retryTimestamp", ".", "getTime", "(", ")", "?", "after", ":", "retryTimestamp", ";", "return", "getWsLogUrl", "(", "appId", ",", "newAfter", ".", "toISOString", "(", ")", ",", "search", ",", "deploymentId", ")", ";", "}", ";", "return", "WsStream", ".", "openStream", "(", "makeUrl", ",", "api", ".", "session", ".", "getAuthorization", "(", "'GET'", ",", "getAppLogsUrl", "(", "appId", ")", ",", "{", "}", ")", ")", ".", "filter", "(", "(", "line", ")", "=>", "{", "const", "lineDate", "=", "Date", ".", "parse", "(", "line", ".", "_source", "[", "'@timestamp'", "]", ")", ";", "const", "isBefore", "=", "!", "before", "||", "lineDate", "<", "before", ".", "getTime", "(", ")", ";", "const", "isAfter", "=", "!", "after", "||", "lineDate", ">", "after", ".", "getTime", "(", ")", ";", "return", "isBefore", "&&", "isAfter", ";", "}", ")", ";", "}" ]
Get logs as they arrive from a web socket. Automatically reconnect if the connexion is closed. api: The API object appId: The appId of the application before (Date): only display log lines that happened before this date after (Date): only display log lines that happened after this date deploymentId: Only display log lines corresponding to this deployment
[ "Get", "logs", "as", "they", "arrive", "from", "a", "web", "socket", ".", "Automatically", "reconnect", "if", "the", "connexion", "is", "closed", "." ]
82fbfadf7ae33cfa61d93148432a98c1274a877d
https://github.com/CleverCloud/clever-tools/blob/82fbfadf7ae33cfa61d93148432a98c1274a877d/src/models/log.js#L43-L57
16,946
CleverCloud/clever-tools
src/models/ws-stream.js
openStream
function openStream (makeUrl, authorization, endTimestamp, retries = MAX_RETRY_COUNT) { const endTs = endTimestamp || null; const s_websocket = openWebSocket(makeUrl(endTs), authorization); // Stream which contains only one element: the date at which the websocket closed const s_endTimestamp = s_websocket.filter(false).mapEnd(new Date()); const s_interruption = s_endTimestamp.flatMapLatest((endTimestamp) => { Logger.warn('WebSocket connexion closed, reconnecting...'); if (retries === 0) { return new Bacon.Error(`WebSocket connexion failed ${MAX_RETRY_COUNT} times!`); } return Bacon.later(RETRY_DELAY, null).flatMapLatest(() => { return openStream(makeUrl, authorization, endTimestamp, retries - 1); }); }); return Bacon.mergeAll(s_websocket, s_interruption); }
javascript
function openStream (makeUrl, authorization, endTimestamp, retries = MAX_RETRY_COUNT) { const endTs = endTimestamp || null; const s_websocket = openWebSocket(makeUrl(endTs), authorization); // Stream which contains only one element: the date at which the websocket closed const s_endTimestamp = s_websocket.filter(false).mapEnd(new Date()); const s_interruption = s_endTimestamp.flatMapLatest((endTimestamp) => { Logger.warn('WebSocket connexion closed, reconnecting...'); if (retries === 0) { return new Bacon.Error(`WebSocket connexion failed ${MAX_RETRY_COUNT} times!`); } return Bacon.later(RETRY_DELAY, null).flatMapLatest(() => { return openStream(makeUrl, authorization, endTimestamp, retries - 1); }); }); return Bacon.mergeAll(s_websocket, s_interruption); }
[ "function", "openStream", "(", "makeUrl", ",", "authorization", ",", "endTimestamp", ",", "retries", "=", "MAX_RETRY_COUNT", ")", "{", "const", "endTs", "=", "endTimestamp", "||", "null", ";", "const", "s_websocket", "=", "openWebSocket", "(", "makeUrl", "(", "endTs", ")", ",", "authorization", ")", ";", "// Stream which contains only one element: the date at which the websocket closed", "const", "s_endTimestamp", "=", "s_websocket", ".", "filter", "(", "false", ")", ".", "mapEnd", "(", "new", "Date", "(", ")", ")", ";", "const", "s_interruption", "=", "s_endTimestamp", ".", "flatMapLatest", "(", "(", "endTimestamp", ")", "=>", "{", "Logger", ".", "warn", "(", "'WebSocket connexion closed, reconnecting...'", ")", ";", "if", "(", "retries", "===", "0", ")", "{", "return", "new", "Bacon", ".", "Error", "(", "`", "${", "MAX_RETRY_COUNT", "}", "`", ")", ";", "}", "return", "Bacon", ".", "later", "(", "RETRY_DELAY", ",", "null", ")", ".", "flatMapLatest", "(", "(", ")", "=>", "{", "return", "openStream", "(", "makeUrl", ",", "authorization", ",", "endTimestamp", ",", "retries", "-", "1", ")", ";", "}", ")", ";", "}", ")", ";", "return", "Bacon", ".", "mergeAll", "(", "s_websocket", ",", "s_interruption", ")", ";", "}" ]
Open a never-ending stream of events, backed by a websocket. If websocket connection is closed, it is automatically re-opened. Ping messages are regularly sent to the server to keep the connection alive and avoid disconnections. makeUrl: Timestamp => String : The WS URL can be constructed based on the closing date, in case the WS supports resuming. On the first WS connection, this value will be null authorization: The content of the authorization message sent to server
[ "Open", "a", "never", "-", "ending", "stream", "of", "events", "backed", "by", "a", "websocket", ".", "If", "websocket", "connection", "is", "closed", "it", "is", "automatically", "re", "-", "opened", ".", "Ping", "messages", "are", "regularly", "sent", "to", "the", "server", "to", "keep", "the", "connection", "alive", "and", "avoid", "disconnections", "." ]
82fbfadf7ae33cfa61d93148432a98c1274a877d
https://github.com/CleverCloud/clever-tools/blob/82fbfadf7ae33cfa61d93148432a98c1274a877d/src/models/ws-stream.js#L65-L82
16,947
CleverCloud/clever-tools
src/commands/login.js
randomToken
function randomToken () { return crypto.randomBytes(20).toString('base64').replace(/\//g, '-').replace(/\+/g, '_').replace(/=/g, ''); }
javascript
function randomToken () { return crypto.randomBytes(20).toString('base64').replace(/\//g, '-').replace(/\+/g, '_').replace(/=/g, ''); }
[ "function", "randomToken", "(", ")", "{", "return", "crypto", ".", "randomBytes", "(", "20", ")", ".", "toString", "(", "'base64'", ")", ".", "replace", "(", "/", "\\/", "/", "g", ",", "'-'", ")", ".", "replace", "(", "/", "\\+", "/", "g", ",", "'_'", ")", ".", "replace", "(", "/", "=", "/", "g", ",", "''", ")", ";", "}" ]
20 random bytes as Base64URL
[ "20", "random", "bytes", "as", "Base64URL" ]
82fbfadf7ae33cfa61d93148432a98c1274a877d
https://github.com/CleverCloud/clever-tools/blob/82fbfadf7ae33cfa61d93148432a98c1274a877d/src/commands/login.js#L19-L21
16,948
CleverCloud/clever-tools
src/models/addon.js
performPreorder
function performPreorder (api, orgaId, name, planId, providerId, region) { const params = orgaId ? [orgaId] : []; return api.owner(orgaId).addons.preorders.post().withParams(params).send(JSON.stringify({ name: name, plan: planId, providerId: providerId, region: region, })); }
javascript
function performPreorder (api, orgaId, name, planId, providerId, region) { const params = orgaId ? [orgaId] : []; return api.owner(orgaId).addons.preorders.post().withParams(params).send(JSON.stringify({ name: name, plan: planId, providerId: providerId, region: region, })); }
[ "function", "performPreorder", "(", "api", ",", "orgaId", ",", "name", ",", "planId", ",", "providerId", ",", "region", ")", "{", "const", "params", "=", "orgaId", "?", "[", "orgaId", "]", ":", "[", "]", ";", "return", "api", ".", "owner", "(", "orgaId", ")", ".", "addons", ".", "preorders", ".", "post", "(", ")", ".", "withParams", "(", "params", ")", ".", "send", "(", "JSON", ".", "stringify", "(", "{", "name", ":", "name", ",", "plan", ":", "planId", ",", "providerId", ":", "providerId", ",", "region", ":", "region", ",", "}", ")", ")", ";", "}" ]
Generate a preview creation, to get access to the price that will be charged, as well as to verify that the payment methods are correctly configured
[ "Generate", "a", "preview", "creation", "to", "get", "access", "to", "the", "price", "that", "will", "be", "charged", "as", "well", "as", "to", "verify", "that", "the", "payment", "methods", "are", "correctly", "configured" ]
82fbfadf7ae33cfa61d93148432a98c1274a877d
https://github.com/CleverCloud/clever-tools/blob/82fbfadf7ae33cfa61d93148432a98c1274a877d/src/models/addon.js#L103-L111
16,949
latelierco/vue-application-insights
src/index.js
setupPageTracking
function setupPageTracking(options, Vue) { const router = options.router const baseName = options.baseName || '(Vue App)' router.beforeEach( (route, from, next) => { const name = baseName + ' / ' + route.name; Vue.appInsights.startTrackPage(name) next() }) router.afterEach( route => { const name = baseName + ' / ' + route.name; const url = location.protocol + '//' + location.host + '/' + route.fullPath; Vue.appInsights.stopTrackPage(name, url); }) }
javascript
function setupPageTracking(options, Vue) { const router = options.router const baseName = options.baseName || '(Vue App)' router.beforeEach( (route, from, next) => { const name = baseName + ' / ' + route.name; Vue.appInsights.startTrackPage(name) next() }) router.afterEach( route => { const name = baseName + ' / ' + route.name; const url = location.protocol + '//' + location.host + '/' + route.fullPath; Vue.appInsights.stopTrackPage(name, url); }) }
[ "function", "setupPageTracking", "(", "options", ",", "Vue", ")", "{", "const", "router", "=", "options", ".", "router", "const", "baseName", "=", "options", ".", "baseName", "||", "'(Vue App)'", "router", ".", "beforeEach", "(", "(", "route", ",", "from", ",", "next", ")", "=>", "{", "const", "name", "=", "baseName", "+", "' / '", "+", "route", ".", "name", ";", "Vue", ".", "appInsights", ".", "startTrackPage", "(", "name", ")", "next", "(", ")", "}", ")", "router", ".", "afterEach", "(", "route", "=>", "{", "const", "name", "=", "baseName", "+", "' / '", "+", "route", ".", "name", ";", "const", "url", "=", "location", ".", "protocol", "+", "'//'", "+", "location", ".", "host", "+", "'/'", "+", "route", ".", "fullPath", ";", "Vue", ".", "appInsights", ".", "stopTrackPage", "(", "name", ",", "url", ")", ";", "}", ")", "}" ]
Track route changes as page views with AppInsights @param options
[ "Track", "route", "changes", "as", "page", "views", "with", "AppInsights" ]
9f9d7cfddc2a8f9f67c0776a2f285910775d412b
https://github.com/latelierco/vue-application-insights/blob/9f9d7cfddc2a8f9f67c0776a2f285910775d412b/src/index.js#L44-L61
16,950
mapbox/cwlogs
lib/readable.js
readable
function readable(options) { options = options || {}; if (!options.region || typeof options.region !== 'string') return invalid(); if (!options.group || typeof options.group !== 'string') return invalid(); if (options.start && typeof options.start !== 'number') return invalid(); if (options.end && typeof options.end !== 'number') return invalid(); if (options.pattern && typeof options.pattern !== 'string') return invalid(); if (options.retry && typeof options.retry !== 'function') return invalid(); if (options.messages && typeof options.messages !== 'boolean') return invalid(); options.objectMode = !options.messages; options.start = options.start || Date.now() - 15 * 60 * 1000; options.end = options.end || Date.now(); options.retry = options.retry || function() {}; var logs = new AWS.CloudWatchLogs({ region: options.region }); var params = { logGroupName: options.group, endTime: options.end, filterPattern: options.pattern ? '"' + options.pattern + '"' : undefined, interleaved: true, startTime: options.start }; var logStream = new stream.Readable(options); var nextRequest = logs.filterLogEvents(params); var pending = false; var events = []; function makeRequest(request) { pending = true; request .on('error', function(err) { logStream.emit('error', err); }) .on('retry', options.retry) .on('success', function(response) { pending = false; nextRequest = response.hasNextPage() ? response.nextPage() : false; for (var i = 0; i < response.data.events.length; i++) { var item = options.messages ? response.data.events[i].message.trim() + '\n' : response.data.events[i]; events.push(item); } logStream._read(); }).send(); } logStream._read = function() { var status = true; while (status && events.length) status = logStream.push(events.shift()); if (events.length) return; if (!nextRequest) return logStream.push(null); if (status && !pending) makeRequest(nextRequest); }; return logStream; }
javascript
function readable(options) { options = options || {}; if (!options.region || typeof options.region !== 'string') return invalid(); if (!options.group || typeof options.group !== 'string') return invalid(); if (options.start && typeof options.start !== 'number') return invalid(); if (options.end && typeof options.end !== 'number') return invalid(); if (options.pattern && typeof options.pattern !== 'string') return invalid(); if (options.retry && typeof options.retry !== 'function') return invalid(); if (options.messages && typeof options.messages !== 'boolean') return invalid(); options.objectMode = !options.messages; options.start = options.start || Date.now() - 15 * 60 * 1000; options.end = options.end || Date.now(); options.retry = options.retry || function() {}; var logs = new AWS.CloudWatchLogs({ region: options.region }); var params = { logGroupName: options.group, endTime: options.end, filterPattern: options.pattern ? '"' + options.pattern + '"' : undefined, interleaved: true, startTime: options.start }; var logStream = new stream.Readable(options); var nextRequest = logs.filterLogEvents(params); var pending = false; var events = []; function makeRequest(request) { pending = true; request .on('error', function(err) { logStream.emit('error', err); }) .on('retry', options.retry) .on('success', function(response) { pending = false; nextRequest = response.hasNextPage() ? response.nextPage() : false; for (var i = 0; i < response.data.events.length; i++) { var item = options.messages ? response.data.events[i].message.trim() + '\n' : response.data.events[i]; events.push(item); } logStream._read(); }).send(); } logStream._read = function() { var status = true; while (status && events.length) status = logStream.push(events.shift()); if (events.length) return; if (!nextRequest) return logStream.push(null); if (status && !pending) makeRequest(nextRequest); }; return logStream; }
[ "function", "readable", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "options", ".", "region", "||", "typeof", "options", ".", "region", "!==", "'string'", ")", "return", "invalid", "(", ")", ";", "if", "(", "!", "options", ".", "group", "||", "typeof", "options", ".", "group", "!==", "'string'", ")", "return", "invalid", "(", ")", ";", "if", "(", "options", ".", "start", "&&", "typeof", "options", ".", "start", "!==", "'number'", ")", "return", "invalid", "(", ")", ";", "if", "(", "options", ".", "end", "&&", "typeof", "options", ".", "end", "!==", "'number'", ")", "return", "invalid", "(", ")", ";", "if", "(", "options", ".", "pattern", "&&", "typeof", "options", ".", "pattern", "!==", "'string'", ")", "return", "invalid", "(", ")", ";", "if", "(", "options", ".", "retry", "&&", "typeof", "options", ".", "retry", "!==", "'function'", ")", "return", "invalid", "(", ")", ";", "if", "(", "options", ".", "messages", "&&", "typeof", "options", ".", "messages", "!==", "'boolean'", ")", "return", "invalid", "(", ")", ";", "options", ".", "objectMode", "=", "!", "options", ".", "messages", ";", "options", ".", "start", "=", "options", ".", "start", "||", "Date", ".", "now", "(", ")", "-", "15", "*", "60", "*", "1000", ";", "options", ".", "end", "=", "options", ".", "end", "||", "Date", ".", "now", "(", ")", ";", "options", ".", "retry", "=", "options", ".", "retry", "||", "function", "(", ")", "{", "}", ";", "var", "logs", "=", "new", "AWS", ".", "CloudWatchLogs", "(", "{", "region", ":", "options", ".", "region", "}", ")", ";", "var", "params", "=", "{", "logGroupName", ":", "options", ".", "group", ",", "endTime", ":", "options", ".", "end", ",", "filterPattern", ":", "options", ".", "pattern", "?", "'\"'", "+", "options", ".", "pattern", "+", "'\"'", ":", "undefined", ",", "interleaved", ":", "true", ",", "startTime", ":", "options", ".", "start", "}", ";", "var", "logStream", "=", "new", "stream", ".", "Readable", "(", "options", ")", ";", "var", "nextRequest", "=", "logs", ".", "filterLogEvents", "(", "params", ")", ";", "var", "pending", "=", "false", ";", "var", "events", "=", "[", "]", ";", "function", "makeRequest", "(", "request", ")", "{", "pending", "=", "true", ";", "request", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "logStream", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ".", "on", "(", "'retry'", ",", "options", ".", "retry", ")", ".", "on", "(", "'success'", ",", "function", "(", "response", ")", "{", "pending", "=", "false", ";", "nextRequest", "=", "response", ".", "hasNextPage", "(", ")", "?", "response", ".", "nextPage", "(", ")", ":", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "response", ".", "data", ".", "events", ".", "length", ";", "i", "++", ")", "{", "var", "item", "=", "options", ".", "messages", "?", "response", ".", "data", ".", "events", "[", "i", "]", ".", "message", ".", "trim", "(", ")", "+", "'\\n'", ":", "response", ".", "data", ".", "events", "[", "i", "]", ";", "events", ".", "push", "(", "item", ")", ";", "}", "logStream", ".", "_read", "(", ")", ";", "}", ")", ".", "send", "(", ")", ";", "}", "logStream", ".", "_read", "=", "function", "(", ")", "{", "var", "status", "=", "true", ";", "while", "(", "status", "&&", "events", ".", "length", ")", "status", "=", "logStream", ".", "push", "(", "events", ".", "shift", "(", ")", ")", ";", "if", "(", "events", ".", "length", ")", "return", ";", "if", "(", "!", "nextRequest", ")", "return", "logStream", ".", "push", "(", "null", ")", ";", "if", "(", "status", "&&", "!", "pending", ")", "makeRequest", "(", "nextRequest", ")", ";", "}", ";", "return", "logStream", ";", "}" ]
Provide a readable stream of log events for a particular log group @memberof cwlogs @param {object} options - default Node.js [ReadableStream options](https://nodejs.org/api/stream.html#stream_class_stream_readable_1) with extensions detailed below. @param {string} options.group - the name of the LogGroup to read @param {string} options.region - the AWS region in which the LogGroup resides @param {string} [options.pattern] - a search string to use to filter log events @param {number} [options.start=15 minutes ago] - read log events after the provided time (in ms since since Jan 01 1970) @param {number} [options.end=now] - read log events until the provided time (in ms since since Jan 01 1970) @param {boolean} [options.messages=false] - if set to true, the stream will be in objectMode: false and will provide only log event messages @param {function} [options.retry] - a function to handle retry events from AWS requests @returns {object} a Node.js [ReadableStream](https://nodejs.org/api/stream.html#stream_class_stream_readable_1) @example var readable = cwlogs.readable({ group: '/aws/lambda/my-lambda-function-name', region: 'us-east-1', messages: true, start: 1464984431610, end: 1464985321508, pattern: 'error' }); readable.pipe(process.stdout);
[ "Provide", "a", "readable", "stream", "of", "log", "events", "for", "a", "particular", "log", "group" ]
15fd2140b52fff29c676c6d3972066235f5159e2
https://github.com/mapbox/cwlogs/blob/15fd2140b52fff29c676c6d3972066235f5159e2/lib/readable.js#L35-L95
16,951
joe-sky/nornj
dist/nornj.runtime.common.js
camelCase
function camelCase(str) { if (str.indexOf('-') > -1) { str = str.replace(/-\w/g, function (letter) { return letter.substr(1).toUpperCase(); }); } return str; }
javascript
function camelCase(str) { if (str.indexOf('-') > -1) { str = str.replace(/-\w/g, function (letter) { return letter.substr(1).toUpperCase(); }); } return str; }
[ "function", "camelCase", "(", "str", ")", "{", "if", "(", "str", ".", "indexOf", "(", "'-'", ")", ">", "-", "1", ")", "{", "str", "=", "str", ".", "replace", "(", "/", "-\\w", "/", "g", ",", "function", "(", "letter", ")", "{", "return", "letter", ".", "substr", "(", "1", ")", ".", "toUpperCase", "(", ")", ";", "}", ")", ";", "}", "return", "str", ";", "}" ]
Transform to camel-case
[ "Transform", "to", "camel", "-", "case" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.runtime.common.js#L207-L215
16,952
joe-sky/nornj
dist/nornj.runtime.common.js
getData
function getData(prop, data, hasSource) { var value, obj; if (!data) { data = this.data; } for (var i = 0, l = data.length; i < l; i++) { obj = data[i]; if (obj) { value = obj[prop]; if (value !== undefined) { if (hasSource) { return { source: obj, value: value, prop: prop, _njSrc: true }; } return value; } } } }
javascript
function getData(prop, data, hasSource) { var value, obj; if (!data) { data = this.data; } for (var i = 0, l = data.length; i < l; i++) { obj = data[i]; if (obj) { value = obj[prop]; if (value !== undefined) { if (hasSource) { return { source: obj, value: value, prop: prop, _njSrc: true }; } return value; } } } }
[ "function", "getData", "(", "prop", ",", "data", ",", "hasSource", ")", "{", "var", "value", ",", "obj", ";", "if", "(", "!", "data", ")", "{", "data", "=", "this", ".", "data", ";", "}", "for", "(", "var", "i", "=", "0", ",", "l", "=", "data", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "obj", "=", "data", "[", "i", "]", ";", "if", "(", "obj", ")", "{", "value", "=", "obj", "[", "prop", "]", ";", "if", "(", "value", "!==", "undefined", ")", "{", "if", "(", "hasSource", ")", "{", "return", "{", "source", ":", "obj", ",", "value", ":", "value", ",", "prop", ":", "prop", ",", "_njSrc", ":", "true", "}", ";", "}", "return", "value", ";", "}", "}", "}", "}" ]
Get value from multiple datas
[ "Get", "value", "from", "multiple", "datas" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.runtime.common.js#L421-L448
16,953
joe-sky/nornj
dist/nornj.runtime.common.js
newContext
function newContext(context, params) { if (!params) { return context; } return assign({}, context, { data: params.data ? arrayPush(params.data, context.data) : context.data, parent: params.newParent ? context : context.parent, index: 'index' in params ? params.index : context.index, item: 'item' in params ? params.item : context.item }); }
javascript
function newContext(context, params) { if (!params) { return context; } return assign({}, context, { data: params.data ? arrayPush(params.data, context.data) : context.data, parent: params.newParent ? context : context.parent, index: 'index' in params ? params.index : context.index, item: 'item' in params ? params.item : context.item }); }
[ "function", "newContext", "(", "context", ",", "params", ")", "{", "if", "(", "!", "params", ")", "{", "return", "context", ";", "}", "return", "assign", "(", "{", "}", ",", "context", ",", "{", "data", ":", "params", ".", "data", "?", "arrayPush", "(", "params", ".", "data", ",", "context", ".", "data", ")", ":", "context", ".", "data", ",", "parent", ":", "params", ".", "newParent", "?", "context", ":", "context", ".", "parent", ",", "index", ":", "'index'", "in", "params", "?", "params", ".", "index", ":", "context", ".", "index", ",", "item", ":", "'item'", "in", "params", "?", "params", ".", "item", ":", "context", ".", "item", "}", ")", ";", "}" ]
Rebuild local variables in the new context
[ "Rebuild", "local", "variables", "in", "the", "new", "context" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.runtime.common.js#L497-L508
16,954
joe-sky/nornj
dist/nornj.runtime.common.js
registerExtension
function registerExtension(name, extension, options, mergeConfig) { var params = name; if (!isObject(name)) { params = {}; params[name] = { extension: extension, options: options }; } each(params, function (v, name) { if (v) { var _extension = v.extension, _options3 = v.options; if (_extension) { extensions[name] = _extension; } else if (!mergeConfig) { extensions[name] = v; } if (mergeConfig) { if (!extensionConfig[name]) { extensionConfig[name] = _config(); } assign(extensionConfig[name], _options3); } else { extensionConfig[name] = _config(_options3); } } }, false); }
javascript
function registerExtension(name, extension, options, mergeConfig) { var params = name; if (!isObject(name)) { params = {}; params[name] = { extension: extension, options: options }; } each(params, function (v, name) { if (v) { var _extension = v.extension, _options3 = v.options; if (_extension) { extensions[name] = _extension; } else if (!mergeConfig) { extensions[name] = v; } if (mergeConfig) { if (!extensionConfig[name]) { extensionConfig[name] = _config(); } assign(extensionConfig[name], _options3); } else { extensionConfig[name] = _config(_options3); } } }, false); }
[ "function", "registerExtension", "(", "name", ",", "extension", ",", "options", ",", "mergeConfig", ")", "{", "var", "params", "=", "name", ";", "if", "(", "!", "isObject", "(", "name", ")", ")", "{", "params", "=", "{", "}", ";", "params", "[", "name", "]", "=", "{", "extension", ":", "extension", ",", "options", ":", "options", "}", ";", "}", "each", "(", "params", ",", "function", "(", "v", ",", "name", ")", "{", "if", "(", "v", ")", "{", "var", "_extension", "=", "v", ".", "extension", ",", "_options3", "=", "v", ".", "options", ";", "if", "(", "_extension", ")", "{", "extensions", "[", "name", "]", "=", "_extension", ";", "}", "else", "if", "(", "!", "mergeConfig", ")", "{", "extensions", "[", "name", "]", "=", "v", ";", "}", "if", "(", "mergeConfig", ")", "{", "if", "(", "!", "extensionConfig", "[", "name", "]", ")", "{", "extensionConfig", "[", "name", "]", "=", "_config", "(", ")", ";", "}", "assign", "(", "extensionConfig", "[", "name", "]", ",", "_options3", ")", ";", "}", "else", "{", "extensionConfig", "[", "name", "]", "=", "_config", "(", "_options3", ")", ";", "}", "}", "}", ",", "false", ")", ";", "}" ]
Register extension and also can batch add
[ "Register", "extension", "and", "also", "can", "batch", "add" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.runtime.common.js#L985-L1018
16,955
joe-sky/nornj
dist/nornj.runtime.common.js
_
function _(obj, prop, options) { if (obj == null) { return obj; } return getAccessorData(obj[prop], options.context); }
javascript
function _(obj, prop, options) { if (obj == null) { return obj; } return getAccessorData(obj[prop], options.context); }
[ "function", "_", "(", "obj", ",", "prop", ",", "options", ")", "{", "if", "(", "obj", "==", "null", ")", "{", "return", "obj", ";", "}", "return", "getAccessorData", "(", "obj", "[", "prop", "]", ",", "options", ".", "context", ")", ";", "}" ]
Get accessor properties
[ "Get", "accessor", "properties" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.runtime.common.js#L1066-L1072
16,956
joe-sky/nornj
dist/nornj.runtime.common.js
int
function int(val) { var radix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; var ret = parseInt(val, radix); return isNaN(ret) ? 0 : ret; }
javascript
function int(val) { var radix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; var ret = parseInt(val, radix); return isNaN(ret) ? 0 : ret; }
[ "function", "int", "(", "val", ")", "{", "var", "radix", "=", "arguments", ".", "length", ">", "1", "&&", "arguments", "[", "1", "]", "!==", "undefined", "?", "arguments", "[", "1", "]", ":", "10", ";", "var", "ret", "=", "parseInt", "(", "val", ",", "radix", ")", ";", "return", "isNaN", "(", "ret", ")", "?", "0", ":", "ret", ";", "}" ]
Convert to int
[ "Convert", "to", "int" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.runtime.common.js#L1089-L1093
16,957
joe-sky/nornj
dist/nornj.runtime.common.js
float
function float(val, bit) { var ret = parseFloat(val); return isNaN(ret) ? 0 : bit != null ? ret.toFixed(bit) : ret; }
javascript
function float(val, bit) { var ret = parseFloat(val); return isNaN(ret) ? 0 : bit != null ? ret.toFixed(bit) : ret; }
[ "function", "float", "(", "val", ",", "bit", ")", "{", "var", "ret", "=", "parseFloat", "(", "val", ")", ";", "return", "isNaN", "(", "ret", ")", "?", "0", ":", "bit", "!=", "null", "?", "ret", ".", "toFixed", "(", "bit", ")", ":", "ret", ";", "}" ]
Convert to float
[ "Convert", "to", "float" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.runtime.common.js#L1095-L1098
16,958
joe-sky/nornj
dist/nornj.runtime.common.js
registerFilter
function registerFilter(name, filter, options, mergeConfig) { var params = name; if (!isObject(name)) { params = {}; params[name] = { filter: filter, options: options }; } each(params, function (v, name) { if (v) { var _filter = v.filter, _options = v.options; if (_options) { if (_options.isOperator) { var createRegexOperators = nj.createRegexOperators; if (createRegexOperators) { createRegexOperators(name); } } var alias = _options.alias; if (alias) { var createFilterAlias = nj.createFilterAlias; if (createFilterAlias) { createFilterAlias(name, alias); name = alias; } } } if (_filter) { filters[name] = _filter; } else if (!mergeConfig) { filters[name] = v; } if (mergeConfig) { if (!filterConfig[name]) { filterConfig[name] = _config$1(); } assign(filterConfig[name], _options); } else { filterConfig[name] = _config$1(_options); } } }, false); }
javascript
function registerFilter(name, filter, options, mergeConfig) { var params = name; if (!isObject(name)) { params = {}; params[name] = { filter: filter, options: options }; } each(params, function (v, name) { if (v) { var _filter = v.filter, _options = v.options; if (_options) { if (_options.isOperator) { var createRegexOperators = nj.createRegexOperators; if (createRegexOperators) { createRegexOperators(name); } } var alias = _options.alias; if (alias) { var createFilterAlias = nj.createFilterAlias; if (createFilterAlias) { createFilterAlias(name, alias); name = alias; } } } if (_filter) { filters[name] = _filter; } else if (!mergeConfig) { filters[name] = v; } if (mergeConfig) { if (!filterConfig[name]) { filterConfig[name] = _config$1(); } assign(filterConfig[name], _options); } else { filterConfig[name] = _config$1(_options); } } }, false); }
[ "function", "registerFilter", "(", "name", ",", "filter", ",", "options", ",", "mergeConfig", ")", "{", "var", "params", "=", "name", ";", "if", "(", "!", "isObject", "(", "name", ")", ")", "{", "params", "=", "{", "}", ";", "params", "[", "name", "]", "=", "{", "filter", ":", "filter", ",", "options", ":", "options", "}", ";", "}", "each", "(", "params", ",", "function", "(", "v", ",", "name", ")", "{", "if", "(", "v", ")", "{", "var", "_filter", "=", "v", ".", "filter", ",", "_options", "=", "v", ".", "options", ";", "if", "(", "_options", ")", "{", "if", "(", "_options", ".", "isOperator", ")", "{", "var", "createRegexOperators", "=", "nj", ".", "createRegexOperators", ";", "if", "(", "createRegexOperators", ")", "{", "createRegexOperators", "(", "name", ")", ";", "}", "}", "var", "alias", "=", "_options", ".", "alias", ";", "if", "(", "alias", ")", "{", "var", "createFilterAlias", "=", "nj", ".", "createFilterAlias", ";", "if", "(", "createFilterAlias", ")", "{", "createFilterAlias", "(", "name", ",", "alias", ")", ";", "name", "=", "alias", ";", "}", "}", "}", "if", "(", "_filter", ")", "{", "filters", "[", "name", "]", "=", "_filter", ";", "}", "else", "if", "(", "!", "mergeConfig", ")", "{", "filters", "[", "name", "]", "=", "v", ";", "}", "if", "(", "mergeConfig", ")", "{", "if", "(", "!", "filterConfig", "[", "name", "]", ")", "{", "filterConfig", "[", "name", "]", "=", "_config$1", "(", ")", ";", "}", "assign", "(", "filterConfig", "[", "name", "]", ",", "_options", ")", ";", "}", "else", "{", "filterConfig", "[", "name", "]", "=", "_config$1", "(", "_options", ")", ";", "}", "}", "}", ",", "false", ")", ";", "}" ]
Register filter and also can batch add
[ "Register", "filter", "and", "also", "can", "batch", "add" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.runtime.common.js#L1240-L1294
16,959
joe-sky/nornj
src/utils/createTmplRule.js
_clearRepeat
function _clearRepeat(str) { let ret = '', i = 0, l = str.length, char; for (; i < l; i++) { char = str[i]; if (ret.indexOf(char) < 0) { ret += char; } } return ret; }
javascript
function _clearRepeat(str) { let ret = '', i = 0, l = str.length, char; for (; i < l; i++) { char = str[i]; if (ret.indexOf(char) < 0) { ret += char; } } return ret; }
[ "function", "_clearRepeat", "(", "str", ")", "{", "let", "ret", "=", "''", ",", "i", "=", "0", ",", "l", "=", "str", ".", "length", ",", "char", ";", "for", "(", ";", "i", "<", "l", ";", "i", "++", ")", "{", "char", "=", "str", "[", "i", "]", ";", "if", "(", "ret", ".", "indexOf", "(", "char", ")", "<", "0", ")", "{", "ret", "+=", "char", ";", "}", "}", "return", "ret", ";", "}" ]
Clear the repeated characters
[ "Clear", "the", "repeated", "characters" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/src/utils/createTmplRule.js#L9-L23
16,960
joe-sky/nornj
dist/nornj.common.js
getOpenTagParams
function getOpenTagParams(tag, tmplRule) { var pattern = tmplRule.openTagParams, matchArr, ret; while (matchArr = pattern.exec(tag)) { var key = matchArr[1]; if (key === '/') { //If match to the last of "/", then continue the loop. continue; } if (!ret) { ret = []; } var value = matchArr[8], onlyBrace = matchArr[4] != null ? matchArr[4] : matchArr[6], onlyKey = false; if (value != null) { value = clearQuot(value); //Remove quotation marks } else { value = key; //Match to Similar to "checked" or "disabled" attribute. if (!onlyBrace) { onlyKey = true; } } //Removed at the end of "/>", ">" or "/". if (!matchArr[9] && !matchArr[10]) { if (/\/>$/.test(value)) { value = value.substr(0, value.length - 2); } else if (/>$/.test(value) || /\/$/.test(value)) { value = value.substr(0, value.length - 1); } } //Transform special key var hasColon = void 0; if (key[0] === ':') { key = key.substr(1); hasColon = true; } ret.push({ key: key, value: value, onlyBrace: onlyBrace, hasColon: hasColon, onlyKey: onlyKey }); } return ret; }
javascript
function getOpenTagParams(tag, tmplRule) { var pattern = tmplRule.openTagParams, matchArr, ret; while (matchArr = pattern.exec(tag)) { var key = matchArr[1]; if (key === '/') { //If match to the last of "/", then continue the loop. continue; } if (!ret) { ret = []; } var value = matchArr[8], onlyBrace = matchArr[4] != null ? matchArr[4] : matchArr[6], onlyKey = false; if (value != null) { value = clearQuot(value); //Remove quotation marks } else { value = key; //Match to Similar to "checked" or "disabled" attribute. if (!onlyBrace) { onlyKey = true; } } //Removed at the end of "/>", ">" or "/". if (!matchArr[9] && !matchArr[10]) { if (/\/>$/.test(value)) { value = value.substr(0, value.length - 2); } else if (/>$/.test(value) || /\/$/.test(value)) { value = value.substr(0, value.length - 1); } } //Transform special key var hasColon = void 0; if (key[0] === ':') { key = key.substr(1); hasColon = true; } ret.push({ key: key, value: value, onlyBrace: onlyBrace, hasColon: hasColon, onlyKey: onlyKey }); } return ret; }
[ "function", "getOpenTagParams", "(", "tag", ",", "tmplRule", ")", "{", "var", "pattern", "=", "tmplRule", ".", "openTagParams", ",", "matchArr", ",", "ret", ";", "while", "(", "matchArr", "=", "pattern", ".", "exec", "(", "tag", ")", ")", "{", "var", "key", "=", "matchArr", "[", "1", "]", ";", "if", "(", "key", "===", "'/'", ")", "{", "//If match to the last of \"/\", then continue the loop.", "continue", ";", "}", "if", "(", "!", "ret", ")", "{", "ret", "=", "[", "]", ";", "}", "var", "value", "=", "matchArr", "[", "8", "]", ",", "onlyBrace", "=", "matchArr", "[", "4", "]", "!=", "null", "?", "matchArr", "[", "4", "]", ":", "matchArr", "[", "6", "]", ",", "onlyKey", "=", "false", ";", "if", "(", "value", "!=", "null", ")", "{", "value", "=", "clearQuot", "(", "value", ")", ";", "//Remove quotation marks", "}", "else", "{", "value", "=", "key", ";", "//Match to Similar to \"checked\" or \"disabled\" attribute.", "if", "(", "!", "onlyBrace", ")", "{", "onlyKey", "=", "true", ";", "}", "}", "//Removed at the end of \"/>\", \">\" or \"/\".", "if", "(", "!", "matchArr", "[", "9", "]", "&&", "!", "matchArr", "[", "10", "]", ")", "{", "if", "(", "/", "\\/>$", "/", ".", "test", "(", "value", ")", ")", "{", "value", "=", "value", ".", "substr", "(", "0", ",", "value", ".", "length", "-", "2", ")", ";", "}", "else", "if", "(", "/", ">$", "/", ".", "test", "(", "value", ")", "||", "/", "\\/$", "/", ".", "test", "(", "value", ")", ")", "{", "value", "=", "value", ".", "substr", "(", "0", ",", "value", ".", "length", "-", "1", ")", ";", "}", "}", "//Transform special key", "var", "hasColon", "=", "void", "0", ";", "if", "(", "key", "[", "0", "]", "===", "':'", ")", "{", "key", "=", "key", ".", "substr", "(", "1", ")", ";", "hasColon", "=", "true", ";", "}", "ret", ".", "push", "(", "{", "key", ":", "key", ",", "value", ":", "value", ",", "onlyBrace", ":", "onlyBrace", ",", "hasColon", ":", "hasColon", ",", "onlyKey", ":", "onlyKey", "}", ")", ";", "}", "return", "ret", ";", "}" ]
Extract parameters inside the xml open tag
[ "Extract", "parameters", "inside", "the", "xml", "open", "tag" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.common.js#L1886-L1944
16,961
joe-sky/nornj
dist/nornj.common.js
addParamsEx
function addParamsEx(node, parent, isDirective, isSubTag) { var exPropsName = 'paramsEx'; if (!parent[exPropsName]) { var exPropsNode; if (isDirective || isSubTag) { exPropsNode = { type: 'nj_ex', ex: 'props', content: [node] }; } else { exPropsNode = node; } exPropsNode.parentType = parent.type; parent[exPropsName] = exPropsNode; } else { arrayPush(parent[exPropsName].content, isDirective || isSubTag ? [node] : node.content); } }
javascript
function addParamsEx(node, parent, isDirective, isSubTag) { var exPropsName = 'paramsEx'; if (!parent[exPropsName]) { var exPropsNode; if (isDirective || isSubTag) { exPropsNode = { type: 'nj_ex', ex: 'props', content: [node] }; } else { exPropsNode = node; } exPropsNode.parentType = parent.type; parent[exPropsName] = exPropsNode; } else { arrayPush(parent[exPropsName].content, isDirective || isSubTag ? [node] : node.content); } }
[ "function", "addParamsEx", "(", "node", ",", "parent", ",", "isDirective", ",", "isSubTag", ")", "{", "var", "exPropsName", "=", "'paramsEx'", ";", "if", "(", "!", "parent", "[", "exPropsName", "]", ")", "{", "var", "exPropsNode", ";", "if", "(", "isDirective", "||", "isSubTag", ")", "{", "exPropsNode", "=", "{", "type", ":", "'nj_ex'", ",", "ex", ":", "'props'", ",", "content", ":", "[", "node", "]", "}", ";", "}", "else", "{", "exPropsNode", "=", "node", ";", "}", "exPropsNode", ".", "parentType", "=", "parent", ".", "type", ";", "parent", "[", "exPropsName", "]", "=", "exPropsNode", ";", "}", "else", "{", "arrayPush", "(", "parent", "[", "exPropsName", "]", ".", "content", ",", "isDirective", "||", "isSubTag", "?", "[", "node", "]", ":", "node", ".", "content", ")", ";", "}", "}" ]
Add to the "paramsEx" property of the parent node
[ "Add", "to", "the", "paramsEx", "property", "of", "the", "parent", "node" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.common.js#L1997-L2018
16,962
joe-sky/nornj
dist/nornj.common.js
_setElem
function _setElem(elem, elemName, elemParams, elemArr, bySelfClose, tmplRule, outputH) { var ret, paramsEx, fixedExTagName = fixExTagName(elemName, tmplRule); if (fixedExTagName) { elemName = fixedExTagName; } if (isEx(elemName, tmplRule, true)) { ret = elem.substring(1, elem.length - 1); if (fixedExTagName) { ret = tmplRule.extensionRule + lowerFirst(ret); } } else if (isStrPropS(elemName, tmplRule)) { ret = _transformToEx(true, elemName, elemParams, tmplRule); } else if (isPropS(elemName, tmplRule)) { ret = _transformToEx(false, elemName, elemParams, tmplRule); } else { var retS = _getSplitParams(elem, tmplRule, outputH); ret = retS.elem; paramsEx = retS.params; } if (bySelfClose) { var retC = [ret]; if (paramsEx) { retC.push(paramsEx); } elemArr.push(retC); } else { elemArr.push(ret); if (paramsEx) { elemArr.push(paramsEx); } } }
javascript
function _setElem(elem, elemName, elemParams, elemArr, bySelfClose, tmplRule, outputH) { var ret, paramsEx, fixedExTagName = fixExTagName(elemName, tmplRule); if (fixedExTagName) { elemName = fixedExTagName; } if (isEx(elemName, tmplRule, true)) { ret = elem.substring(1, elem.length - 1); if (fixedExTagName) { ret = tmplRule.extensionRule + lowerFirst(ret); } } else if (isStrPropS(elemName, tmplRule)) { ret = _transformToEx(true, elemName, elemParams, tmplRule); } else if (isPropS(elemName, tmplRule)) { ret = _transformToEx(false, elemName, elemParams, tmplRule); } else { var retS = _getSplitParams(elem, tmplRule, outputH); ret = retS.elem; paramsEx = retS.params; } if (bySelfClose) { var retC = [ret]; if (paramsEx) { retC.push(paramsEx); } elemArr.push(retC); } else { elemArr.push(ret); if (paramsEx) { elemArr.push(paramsEx); } } }
[ "function", "_setElem", "(", "elem", ",", "elemName", ",", "elemParams", ",", "elemArr", ",", "bySelfClose", ",", "tmplRule", ",", "outputH", ")", "{", "var", "ret", ",", "paramsEx", ",", "fixedExTagName", "=", "fixExTagName", "(", "elemName", ",", "tmplRule", ")", ";", "if", "(", "fixedExTagName", ")", "{", "elemName", "=", "fixedExTagName", ";", "}", "if", "(", "isEx", "(", "elemName", ",", "tmplRule", ",", "true", ")", ")", "{", "ret", "=", "elem", ".", "substring", "(", "1", ",", "elem", ".", "length", "-", "1", ")", ";", "if", "(", "fixedExTagName", ")", "{", "ret", "=", "tmplRule", ".", "extensionRule", "+", "lowerFirst", "(", "ret", ")", ";", "}", "}", "else", "if", "(", "isStrPropS", "(", "elemName", ",", "tmplRule", ")", ")", "{", "ret", "=", "_transformToEx", "(", "true", ",", "elemName", ",", "elemParams", ",", "tmplRule", ")", ";", "}", "else", "if", "(", "isPropS", "(", "elemName", ",", "tmplRule", ")", ")", "{", "ret", "=", "_transformToEx", "(", "false", ",", "elemName", ",", "elemParams", ",", "tmplRule", ")", ";", "}", "else", "{", "var", "retS", "=", "_getSplitParams", "(", "elem", ",", "tmplRule", ",", "outputH", ")", ";", "ret", "=", "retS", ".", "elem", ";", "paramsEx", "=", "retS", ".", "params", ";", "}", "if", "(", "bySelfClose", ")", "{", "var", "retC", "=", "[", "ret", "]", ";", "if", "(", "paramsEx", ")", "{", "retC", ".", "push", "(", "paramsEx", ")", ";", "}", "elemArr", ".", "push", "(", "retC", ")", ";", "}", "else", "{", "elemArr", ".", "push", "(", "ret", ")", ";", "if", "(", "paramsEx", ")", "{", "elemArr", ".", "push", "(", "paramsEx", ")", ";", "}", "}", "}" ]
Set element node
[ "Set", "element", "node" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.common.js#L3353-L3394
16,963
joe-sky/nornj
dist/nornj.common.js
_getSplitParams
function _getSplitParams(elem, tmplRule, outputH) { var extensionRule = tmplRule.extensionRule, startRule = tmplRule.startRule, endRule = tmplRule.endRule, firstChar = tmplRule.firstChar, lastChar = tmplRule.lastChar, spreadProp = tmplRule.spreadProp, directives = tmplRule.directives; var paramsEx; //Replace the parameter like "{...props}". elem = elem.replace(spreadProp, function (all, g1, propR, g3, prop) { if (propR) { prop = propR; } if (!paramsEx) { paramsEx = [extensionRule + 'props']; } paramsEx.push([extensionRule + 'spread ' + (propR ? firstChar : '') + startRule + prop.replace(/\.\.\./, '') + endRule + (propR ? lastChar : '') + '/']); return ' '; }); //Replace the parameter like "#show={false}". elem = elem.replace(directives, function (all, g1, g2, g3, g4, g5, g6, key, hasColon, hasEx, name, hasEqual, value) { if (hasEx == null) { return all; } if (!paramsEx) { paramsEx = [extensionRule + 'props']; } var args, modifiers; name = name.replace(REGEX_EX_ATTR, function (all, name, modifier, g3, arg) { if (arg) { args = arg.substr(1).split('-').map(function (item) { var argStr; var modifierStr = ''; var strs = item.split(/[$.]/); strs.forEach(function (str, i) { if (i == 0) { argStr = 'name:\'' + str + '\'' + (i < strs.length - 1 ? ',' : ''); } else { modifierStr += '\'' + str + '\'' + (i < strs.length - 1 ? ',' : ''); } }); return '{' + argStr + (modifierStr != '' ? 'modifiers:[' + modifierStr + ']' : '') + '}'; }); } if (modifier) { modifiers = modifier.substr(1).split(/[$.]/).map(function (item) { return '\'' + item + '\''; }); } return name; }); var exPreAst = [extensionRule + name + ' _njIsDirective' + (args ? ' arguments="' + firstChar + startRule + '[' + args.join(',') + ']' + endRule + lastChar + '"' : '') + (modifiers ? ' modifiers="' + startRule + '[' + modifiers.join(',') + ']' + endRule + '"' : '') + (hasEqual ? '' : ' /')]; hasEqual && exPreAst.push((hasColon ? (outputH ? firstChar : '') + startRule + ' ' : '') + clearQuot(value) + (hasColon ? ' ' + endRule + (outputH ? lastChar : '') : '')); paramsEx.push(exPreAst); return ' '; }); return { elem: elem, params: paramsEx }; }
javascript
function _getSplitParams(elem, tmplRule, outputH) { var extensionRule = tmplRule.extensionRule, startRule = tmplRule.startRule, endRule = tmplRule.endRule, firstChar = tmplRule.firstChar, lastChar = tmplRule.lastChar, spreadProp = tmplRule.spreadProp, directives = tmplRule.directives; var paramsEx; //Replace the parameter like "{...props}". elem = elem.replace(spreadProp, function (all, g1, propR, g3, prop) { if (propR) { prop = propR; } if (!paramsEx) { paramsEx = [extensionRule + 'props']; } paramsEx.push([extensionRule + 'spread ' + (propR ? firstChar : '') + startRule + prop.replace(/\.\.\./, '') + endRule + (propR ? lastChar : '') + '/']); return ' '; }); //Replace the parameter like "#show={false}". elem = elem.replace(directives, function (all, g1, g2, g3, g4, g5, g6, key, hasColon, hasEx, name, hasEqual, value) { if (hasEx == null) { return all; } if (!paramsEx) { paramsEx = [extensionRule + 'props']; } var args, modifiers; name = name.replace(REGEX_EX_ATTR, function (all, name, modifier, g3, arg) { if (arg) { args = arg.substr(1).split('-').map(function (item) { var argStr; var modifierStr = ''; var strs = item.split(/[$.]/); strs.forEach(function (str, i) { if (i == 0) { argStr = 'name:\'' + str + '\'' + (i < strs.length - 1 ? ',' : ''); } else { modifierStr += '\'' + str + '\'' + (i < strs.length - 1 ? ',' : ''); } }); return '{' + argStr + (modifierStr != '' ? 'modifiers:[' + modifierStr + ']' : '') + '}'; }); } if (modifier) { modifiers = modifier.substr(1).split(/[$.]/).map(function (item) { return '\'' + item + '\''; }); } return name; }); var exPreAst = [extensionRule + name + ' _njIsDirective' + (args ? ' arguments="' + firstChar + startRule + '[' + args.join(',') + ']' + endRule + lastChar + '"' : '') + (modifiers ? ' modifiers="' + startRule + '[' + modifiers.join(',') + ']' + endRule + '"' : '') + (hasEqual ? '' : ' /')]; hasEqual && exPreAst.push((hasColon ? (outputH ? firstChar : '') + startRule + ' ' : '') + clearQuot(value) + (hasColon ? ' ' + endRule + (outputH ? lastChar : '') : '')); paramsEx.push(exPreAst); return ' '; }); return { elem: elem, params: paramsEx }; }
[ "function", "_getSplitParams", "(", "elem", ",", "tmplRule", ",", "outputH", ")", "{", "var", "extensionRule", "=", "tmplRule", ".", "extensionRule", ",", "startRule", "=", "tmplRule", ".", "startRule", ",", "endRule", "=", "tmplRule", ".", "endRule", ",", "firstChar", "=", "tmplRule", ".", "firstChar", ",", "lastChar", "=", "tmplRule", ".", "lastChar", ",", "spreadProp", "=", "tmplRule", ".", "spreadProp", ",", "directives", "=", "tmplRule", ".", "directives", ";", "var", "paramsEx", ";", "//Replace the parameter like \"{...props}\".", "elem", "=", "elem", ".", "replace", "(", "spreadProp", ",", "function", "(", "all", ",", "g1", ",", "propR", ",", "g3", ",", "prop", ")", "{", "if", "(", "propR", ")", "{", "prop", "=", "propR", ";", "}", "if", "(", "!", "paramsEx", ")", "{", "paramsEx", "=", "[", "extensionRule", "+", "'props'", "]", ";", "}", "paramsEx", ".", "push", "(", "[", "extensionRule", "+", "'spread '", "+", "(", "propR", "?", "firstChar", ":", "''", ")", "+", "startRule", "+", "prop", ".", "replace", "(", "/", "\\.\\.\\.", "/", ",", "''", ")", "+", "endRule", "+", "(", "propR", "?", "lastChar", ":", "''", ")", "+", "'/'", "]", ")", ";", "return", "' '", ";", "}", ")", ";", "//Replace the parameter like \"#show={false}\".", "elem", "=", "elem", ".", "replace", "(", "directives", ",", "function", "(", "all", ",", "g1", ",", "g2", ",", "g3", ",", "g4", ",", "g5", ",", "g6", ",", "key", ",", "hasColon", ",", "hasEx", ",", "name", ",", "hasEqual", ",", "value", ")", "{", "if", "(", "hasEx", "==", "null", ")", "{", "return", "all", ";", "}", "if", "(", "!", "paramsEx", ")", "{", "paramsEx", "=", "[", "extensionRule", "+", "'props'", "]", ";", "}", "var", "args", ",", "modifiers", ";", "name", "=", "name", ".", "replace", "(", "REGEX_EX_ATTR", ",", "function", "(", "all", ",", "name", ",", "modifier", ",", "g3", ",", "arg", ")", "{", "if", "(", "arg", ")", "{", "args", "=", "arg", ".", "substr", "(", "1", ")", ".", "split", "(", "'-'", ")", ".", "map", "(", "function", "(", "item", ")", "{", "var", "argStr", ";", "var", "modifierStr", "=", "''", ";", "var", "strs", "=", "item", ".", "split", "(", "/", "[$.]", "/", ")", ";", "strs", ".", "forEach", "(", "function", "(", "str", ",", "i", ")", "{", "if", "(", "i", "==", "0", ")", "{", "argStr", "=", "'name:\\''", "+", "str", "+", "'\\''", "+", "(", "i", "<", "strs", ".", "length", "-", "1", "?", "','", ":", "''", ")", ";", "}", "else", "{", "modifierStr", "+=", "'\\''", "+", "str", "+", "'\\''", "+", "(", "i", "<", "strs", ".", "length", "-", "1", "?", "','", ":", "''", ")", ";", "}", "}", ")", ";", "return", "'{'", "+", "argStr", "+", "(", "modifierStr", "!=", "''", "?", "'modifiers:['", "+", "modifierStr", "+", "']'", ":", "''", ")", "+", "'}'", ";", "}", ")", ";", "}", "if", "(", "modifier", ")", "{", "modifiers", "=", "modifier", ".", "substr", "(", "1", ")", ".", "split", "(", "/", "[$.]", "/", ")", ".", "map", "(", "function", "(", "item", ")", "{", "return", "'\\''", "+", "item", "+", "'\\''", ";", "}", ")", ";", "}", "return", "name", ";", "}", ")", ";", "var", "exPreAst", "=", "[", "extensionRule", "+", "name", "+", "' _njIsDirective'", "+", "(", "args", "?", "' arguments=\"'", "+", "firstChar", "+", "startRule", "+", "'['", "+", "args", ".", "join", "(", "','", ")", "+", "']'", "+", "endRule", "+", "lastChar", "+", "'\"'", ":", "''", ")", "+", "(", "modifiers", "?", "' modifiers=\"'", "+", "startRule", "+", "'['", "+", "modifiers", ".", "join", "(", "','", ")", "+", "']'", "+", "endRule", "+", "'\"'", ":", "''", ")", "+", "(", "hasEqual", "?", "''", ":", "' /'", ")", "]", ";", "hasEqual", "&&", "exPreAst", ".", "push", "(", "(", "hasColon", "?", "(", "outputH", "?", "firstChar", ":", "''", ")", "+", "startRule", "+", "' '", ":", "''", ")", "+", "clearQuot", "(", "value", ")", "+", "(", "hasColon", "?", "' '", "+", "endRule", "+", "(", "outputH", "?", "lastChar", ":", "''", ")", ":", "''", ")", ")", ";", "paramsEx", ".", "push", "(", "exPreAst", ")", ";", "return", "' '", ";", "}", ")", ";", "return", "{", "elem", ":", "elem", ",", "params", ":", "paramsEx", "}", ";", "}" ]
Extract split parameters
[ "Extract", "split", "parameters" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.common.js#L3398-L3465
16,964
joe-sky/nornj
dist/nornj.common.js
_setSelfCloseElem
function _setSelfCloseElem(elem, elemName, elemParams, elemArr, tmplRule, outputH) { if (/\/$/.test(elemName)) { elemName = elemName.substr(0, elemName.length - 1); } _setElem(elem, elemName, elemParams, elemArr, true, tmplRule, outputH); }
javascript
function _setSelfCloseElem(elem, elemName, elemParams, elemArr, tmplRule, outputH) { if (/\/$/.test(elemName)) { elemName = elemName.substr(0, elemName.length - 1); } _setElem(elem, elemName, elemParams, elemArr, true, tmplRule, outputH); }
[ "function", "_setSelfCloseElem", "(", "elem", ",", "elemName", ",", "elemParams", ",", "elemArr", ",", "tmplRule", ",", "outputH", ")", "{", "if", "(", "/", "\\/$", "/", ".", "test", "(", "elemName", ")", ")", "{", "elemName", "=", "elemName", ".", "substr", "(", "0", ",", "elemName", ".", "length", "-", "1", ")", ";", "}", "_setElem", "(", "elem", ",", "elemName", ",", "elemParams", ",", "elemArr", ",", "true", ",", "tmplRule", ",", "outputH", ")", ";", "}" ]
Set self close element node
[ "Set", "self", "close", "element", "node" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/dist/nornj.common.js#L3468-L3474
16,965
joe-sky/nornj
examples/backbone-marionette-nornj-todomvc/js/TodoMVC.Router.js
function () { this.showHeader(this.todoList); this.showFooter(this.todoList); this.showTodoList(this.todoList); this.todoList.on('all', this.updateHiddenElements, this); this.todoList.fetch(); }
javascript
function () { this.showHeader(this.todoList); this.showFooter(this.todoList); this.showTodoList(this.todoList); this.todoList.on('all', this.updateHiddenElements, this); this.todoList.fetch(); }
[ "function", "(", ")", "{", "this", ".", "showHeader", "(", "this", ".", "todoList", ")", ";", "this", ".", "showFooter", "(", "this", ".", "todoList", ")", ";", "this", ".", "showTodoList", "(", "this", ".", "todoList", ")", ";", "this", ".", "todoList", ".", "on", "(", "'all'", ",", "this", ".", "updateHiddenElements", ",", "this", ")", ";", "this", ".", "todoList", ".", "fetch", "(", ")", ";", "}" ]
Start the app by showing the appropriate views and fetching the list of todo items, if there are any
[ "Start", "the", "app", "by", "showing", "the", "appropriate", "views", "and", "fetching", "the", "list", "of", "todo", "items", "if", "there", "are", "any" ]
63616d30475580bb358b56781a49aebb4a4fc967
https://github.com/joe-sky/nornj/blob/63616d30475580bb358b56781a49aebb4a4fc967/examples/backbone-marionette-nornj-todomvc/js/TodoMVC.Router.js#L34-L40
16,966
mapbox/which-polygon
index.js
insidePolygon
function insidePolygon(rings, p) { var inside = false; for (var i = 0, len = rings.length; i < len; i++) { var ring = rings[i]; for (var j = 0, len2 = ring.length, k = len2 - 1; j < len2; k = j++) { if (rayIntersect(p, ring[j], ring[k])) inside = !inside; } } return inside; }
javascript
function insidePolygon(rings, p) { var inside = false; for (var i = 0, len = rings.length; i < len; i++) { var ring = rings[i]; for (var j = 0, len2 = ring.length, k = len2 - 1; j < len2; k = j++) { if (rayIntersect(p, ring[j], ring[k])) inside = !inside; } } return inside; }
[ "function", "insidePolygon", "(", "rings", ",", "p", ")", "{", "var", "inside", "=", "false", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "rings", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "ring", "=", "rings", "[", "i", "]", ";", "for", "(", "var", "j", "=", "0", ",", "len2", "=", "ring", ".", "length", ",", "k", "=", "len2", "-", "1", ";", "j", "<", "len2", ";", "k", "=", "j", "++", ")", "{", "if", "(", "rayIntersect", "(", "p", ",", "ring", "[", "j", "]", ",", "ring", "[", "k", "]", ")", ")", "inside", "=", "!", "inside", ";", "}", "}", "return", "inside", ";", "}" ]
ray casting algorithm for detecting if point is in polygon
[ "ray", "casting", "algorithm", "for", "detecting", "if", "point", "is", "in", "polygon" ]
e6faafe98ba4623e3c45fc00a24bdd018169f174
https://github.com/mapbox/which-polygon/blob/e6faafe98ba4623e3c45fc00a24bdd018169f174/index.js#L78-L87
16,967
mapbox/vtcomposite
bench/rules.js
getTiles
function getTiles(name) { let tiles = []; let dir = `./node_modules/@mapbox/mvt-fixtures/real-world/${name}`; var files = fs.readdirSync(dir); files.forEach(function(file) { let buffer = fs.readFileSync(path.join(dir, '/', file)); file = file.replace('.mvt', ''); let zxy = file.split('-'); tiles.push({ buffer: buffer, z: parseInt(zxy[0]), x: parseInt(zxy[1]), y: parseInt(zxy[2]) }); }); return tiles; }
javascript
function getTiles(name) { let tiles = []; let dir = `./node_modules/@mapbox/mvt-fixtures/real-world/${name}`; var files = fs.readdirSync(dir); files.forEach(function(file) { let buffer = fs.readFileSync(path.join(dir, '/', file)); file = file.replace('.mvt', ''); let zxy = file.split('-'); tiles.push({ buffer: buffer, z: parseInt(zxy[0]), x: parseInt(zxy[1]), y: parseInt(zxy[2]) }); }); return tiles; }
[ "function", "getTiles", "(", "name", ")", "{", "let", "tiles", "=", "[", "]", ";", "let", "dir", "=", "`", "${", "name", "}", "`", ";", "var", "files", "=", "fs", ".", "readdirSync", "(", "dir", ")", ";", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "let", "buffer", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "dir", ",", "'/'", ",", "file", ")", ")", ";", "file", "=", "file", ".", "replace", "(", "'.mvt'", ",", "''", ")", ";", "let", "zxy", "=", "file", ".", "split", "(", "'-'", ")", ";", "tiles", ".", "push", "(", "{", "buffer", ":", "buffer", ",", "z", ":", "parseInt", "(", "zxy", "[", "0", "]", ")", ",", "x", ":", "parseInt", "(", "zxy", "[", "1", "]", ")", ",", "y", ":", "parseInt", "(", "zxy", "[", "2", "]", ")", "}", ")", ";", "}", ")", ";", "return", "tiles", ";", "}" ]
get all tiles
[ "get", "all", "tiles" ]
baf3b420a6e3f4c8dab9f329dfa6caab9205c234
https://github.com/mapbox/vtcomposite/blob/baf3b420a6e3f4c8dab9f329dfa6caab9205c234/bench/rules.js#L160-L171
16,968
mapbox/osm-compare
comparators/new_user_footway.js
isFootway
function isFootway(newVersion) { if ( newVersion.properties && newVersion.properties.highway === 'footway' && newVersion.properties['osm:version'] === 1 ) { return true; } return false; }
javascript
function isFootway(newVersion) { if ( newVersion.properties && newVersion.properties.highway === 'footway' && newVersion.properties['osm:version'] === 1 ) { return true; } return false; }
[ "function", "isFootway", "(", "newVersion", ")", "{", "if", "(", "newVersion", ".", "properties", "&&", "newVersion", ".", "properties", ".", "highway", "===", "'footway'", "&&", "newVersion", ".", "properties", "[", "'osm:version'", "]", "===", "1", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
check if the user is new user check if the feature is actually a footway and it is version 1 check if the footway has imposible angle check if the footway is selfintersecting
[ "check", "if", "the", "user", "is", "new", "user", "check", "if", "the", "feature", "is", "actually", "a", "footway", "and", "it", "is", "version", "1", "check", "if", "the", "footway", "has", "imposible", "angle", "check", "if", "the", "footway", "is", "selfintersecting" ]
45b0d8bb2ab6a0db0981474da707296fc2eaec72
https://github.com/mapbox/osm-compare/blob/45b0d8bb2ab6a0db0981474da707296fc2eaec72/comparators/new_user_footway.js#L12-L21
16,969
remarkablemark/html-react-parser
lib/utilities.js
camelCase
function camelCase(string) { if (typeof string !== 'string') { throw new TypeError('First argument must be a string'); } // custom property or no hyphen found if (CUSTOM_PROPERTY_OR_NO_HYPHEN_REGEX.test(string)) { return string; } // convert to camelCase return string .toLowerCase() .replace(hyphenPatternRegex, function(_, character) { return character.toUpperCase(); }); }
javascript
function camelCase(string) { if (typeof string !== 'string') { throw new TypeError('First argument must be a string'); } // custom property or no hyphen found if (CUSTOM_PROPERTY_OR_NO_HYPHEN_REGEX.test(string)) { return string; } // convert to camelCase return string .toLowerCase() .replace(hyphenPatternRegex, function(_, character) { return character.toUpperCase(); }); }
[ "function", "camelCase", "(", "string", ")", "{", "if", "(", "typeof", "string", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'First argument must be a string'", ")", ";", "}", "// custom property or no hyphen found", "if", "(", "CUSTOM_PROPERTY_OR_NO_HYPHEN_REGEX", ".", "test", "(", "string", ")", ")", "{", "return", "string", ";", "}", "// convert to camelCase", "return", "string", ".", "toLowerCase", "(", ")", ".", "replace", "(", "hyphenPatternRegex", ",", "function", "(", "_", ",", "character", ")", "{", "return", "character", ".", "toUpperCase", "(", ")", ";", "}", ")", ";", "}" ]
Converts a string to camelCase. @param {String} string - The string. @return {String}
[ "Converts", "a", "string", "to", "camelCase", "." ]
eb3085ab1d0e9c151959ae21f60a13f073d5b978
https://github.com/remarkablemark/html-react-parser/blob/eb3085ab1d0e9c151959ae21f60a13f073d5b978/lib/utilities.js#L11-L27
16,970
remarkablemark/html-react-parser
lib/utilities.js
invertObject
function invertObject(obj, override) { if (!obj || typeof obj !== 'object') { throw new TypeError('First argument must be an object'); } var key; var value; var isOverridePresent = typeof override === 'function'; var overrides = {}; var result = {}; for (key in obj) { value = obj[key]; if (isOverridePresent) { overrides = override(key, value); if (overrides && overrides.length === 2) { result[overrides[0]] = overrides[1]; continue; } } if (typeof value === 'string') { result[value] = key; } } return result; }
javascript
function invertObject(obj, override) { if (!obj || typeof obj !== 'object') { throw new TypeError('First argument must be an object'); } var key; var value; var isOverridePresent = typeof override === 'function'; var overrides = {}; var result = {}; for (key in obj) { value = obj[key]; if (isOverridePresent) { overrides = override(key, value); if (overrides && overrides.length === 2) { result[overrides[0]] = overrides[1]; continue; } } if (typeof value === 'string') { result[value] = key; } } return result; }
[ "function", "invertObject", "(", "obj", ",", "override", ")", "{", "if", "(", "!", "obj", "||", "typeof", "obj", "!==", "'object'", ")", "{", "throw", "new", "TypeError", "(", "'First argument must be an object'", ")", ";", "}", "var", "key", ";", "var", "value", ";", "var", "isOverridePresent", "=", "typeof", "override", "===", "'function'", ";", "var", "overrides", "=", "{", "}", ";", "var", "result", "=", "{", "}", ";", "for", "(", "key", "in", "obj", ")", "{", "value", "=", "obj", "[", "key", "]", ";", "if", "(", "isOverridePresent", ")", "{", "overrides", "=", "override", "(", "key", ",", "value", ")", ";", "if", "(", "overrides", "&&", "overrides", ".", "length", "===", "2", ")", "{", "result", "[", "overrides", "[", "0", "]", "]", "=", "overrides", "[", "1", "]", ";", "continue", ";", "}", "}", "if", "(", "typeof", "value", "===", "'string'", ")", "{", "result", "[", "value", "]", "=", "key", ";", "}", "}", "return", "result", ";", "}" ]
Swap key with value in an object. @param {Object} obj - The object. @param {Function} [override] - The override method. @return {Object} - The inverted object.
[ "Swap", "key", "with", "value", "in", "an", "object", "." ]
eb3085ab1d0e9c151959ae21f60a13f073d5b978
https://github.com/remarkablemark/html-react-parser/blob/eb3085ab1d0e9c151959ae21f60a13f073d5b978/lib/utilities.js#L36-L64
16,971
remarkablemark/html-react-parser
lib/utilities.js
isCustomComponent
function isCustomComponent(tagName, props) { if (tagName.indexOf('-') === -1) { return props && typeof props.is === 'string'; } switch (tagName) { // These are reserved SVG and MathML elements. // We don't mind this whitelist too much because we expect it to never grow. // The alternative is to track the namespace in a few places which is convoluted. // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts case 'annotation-xml': case 'color-profile': case 'font-face': case 'font-face-src': case 'font-face-uri': case 'font-face-format': case 'font-face-name': case 'missing-glyph': return false; default: return true; } }
javascript
function isCustomComponent(tagName, props) { if (tagName.indexOf('-') === -1) { return props && typeof props.is === 'string'; } switch (tagName) { // These are reserved SVG and MathML elements. // We don't mind this whitelist too much because we expect it to never grow. // The alternative is to track the namespace in a few places which is convoluted. // https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts case 'annotation-xml': case 'color-profile': case 'font-face': case 'font-face-src': case 'font-face-uri': case 'font-face-format': case 'font-face-name': case 'missing-glyph': return false; default: return true; } }
[ "function", "isCustomComponent", "(", "tagName", ",", "props", ")", "{", "if", "(", "tagName", ".", "indexOf", "(", "'-'", ")", "===", "-", "1", ")", "{", "return", "props", "&&", "typeof", "props", ".", "is", "===", "'string'", ";", "}", "switch", "(", "tagName", ")", "{", "// These are reserved SVG and MathML elements.", "// We don't mind this whitelist too much because we expect it to never grow.", "// The alternative is to track the namespace in a few places which is convoluted.", "// https://w3c.github.io/webcomponents/spec/custom/#custom-elements-core-concepts", "case", "'annotation-xml'", ":", "case", "'color-profile'", ":", "case", "'font-face'", ":", "case", "'font-face-src'", ":", "case", "'font-face-uri'", ":", "case", "'font-face-format'", ":", "case", "'font-face-name'", ":", "case", "'missing-glyph'", ":", "return", "false", ";", "default", ":", "return", "true", ";", "}", "}" ]
Check if a given tag is a custom component. @see {@link https://github.com/facebook/react/blob/v16.6.3/packages/react-dom/src/shared/isCustomComponent.js} @param {string} tagName - The name of the html tag. @param {Object} props - The props being passed to the element. @return {boolean}
[ "Check", "if", "a", "given", "tag", "is", "a", "custom", "component", "." ]
eb3085ab1d0e9c151959ae21f60a13f073d5b978
https://github.com/remarkablemark/html-react-parser/blob/eb3085ab1d0e9c151959ae21f60a13f073d5b978/lib/utilities.js#L75-L97
16,972
remarkablemark/html-react-parser
lib/attributes-to-props.js
attributesToProps
function attributesToProps(attributes) { attributes = attributes || {}; var props = {}; var propertyName; var propertyValue; var reactProperty; for (propertyName in attributes) { propertyValue = attributes[propertyName]; // custom attributes (`data-` and `aria-`) if (isCustomAttribute(propertyName)) { props[propertyName] = propertyValue; continue; } // make HTML DOM attribute/property consistent with React attribute/property reactProperty = config.html[propertyName.toLowerCase()]; if (reactProperty) { if ( DOMProperty.properties.hasOwnProperty(reactProperty) && DOMProperty.properties[reactProperty].hasBooleanValue ) { props[reactProperty] = true; } else { props[reactProperty] = propertyValue; } continue; } // make SVG DOM attribute/property consistent with React attribute/property reactProperty = config.svg[propertyName]; if (reactProperty) { props[reactProperty] = propertyValue; } else if (utilities.PRESERVE_CUSTOM_ATTRIBUTES) { props[propertyName] = propertyValue; } } // convert inline style to object if (attributes.style != null) { props.style = cssToJs(attributes.style); } return props; }
javascript
function attributesToProps(attributes) { attributes = attributes || {}; var props = {}; var propertyName; var propertyValue; var reactProperty; for (propertyName in attributes) { propertyValue = attributes[propertyName]; // custom attributes (`data-` and `aria-`) if (isCustomAttribute(propertyName)) { props[propertyName] = propertyValue; continue; } // make HTML DOM attribute/property consistent with React attribute/property reactProperty = config.html[propertyName.toLowerCase()]; if (reactProperty) { if ( DOMProperty.properties.hasOwnProperty(reactProperty) && DOMProperty.properties[reactProperty].hasBooleanValue ) { props[reactProperty] = true; } else { props[reactProperty] = propertyValue; } continue; } // make SVG DOM attribute/property consistent with React attribute/property reactProperty = config.svg[propertyName]; if (reactProperty) { props[reactProperty] = propertyValue; } else if (utilities.PRESERVE_CUSTOM_ATTRIBUTES) { props[propertyName] = propertyValue; } } // convert inline style to object if (attributes.style != null) { props.style = cssToJs(attributes.style); } return props; }
[ "function", "attributesToProps", "(", "attributes", ")", "{", "attributes", "=", "attributes", "||", "{", "}", ";", "var", "props", "=", "{", "}", ";", "var", "propertyName", ";", "var", "propertyValue", ";", "var", "reactProperty", ";", "for", "(", "propertyName", "in", "attributes", ")", "{", "propertyValue", "=", "attributes", "[", "propertyName", "]", ";", "// custom attributes (`data-` and `aria-`)", "if", "(", "isCustomAttribute", "(", "propertyName", ")", ")", "{", "props", "[", "propertyName", "]", "=", "propertyValue", ";", "continue", ";", "}", "// make HTML DOM attribute/property consistent with React attribute/property", "reactProperty", "=", "config", ".", "html", "[", "propertyName", ".", "toLowerCase", "(", ")", "]", ";", "if", "(", "reactProperty", ")", "{", "if", "(", "DOMProperty", ".", "properties", ".", "hasOwnProperty", "(", "reactProperty", ")", "&&", "DOMProperty", ".", "properties", "[", "reactProperty", "]", ".", "hasBooleanValue", ")", "{", "props", "[", "reactProperty", "]", "=", "true", ";", "}", "else", "{", "props", "[", "reactProperty", "]", "=", "propertyValue", ";", "}", "continue", ";", "}", "// make SVG DOM attribute/property consistent with React attribute/property", "reactProperty", "=", "config", ".", "svg", "[", "propertyName", "]", ";", "if", "(", "reactProperty", ")", "{", "props", "[", "reactProperty", "]", "=", "propertyValue", ";", "}", "else", "if", "(", "utilities", ".", "PRESERVE_CUSTOM_ATTRIBUTES", ")", "{", "props", "[", "propertyName", "]", "=", "propertyValue", ";", "}", "}", "// convert inline style to object", "if", "(", "attributes", ".", "style", "!=", "null", ")", "{", "props", ".", "style", "=", "cssToJs", "(", "attributes", ".", "style", ")", ";", "}", "return", "props", ";", "}" ]
Makes attributes compatible with React props. @param {Object} [attributes={}] - The attributes. @return {Object} - The props.
[ "Makes", "attributes", "compatible", "with", "React", "props", "." ]
eb3085ab1d0e9c151959ae21f60a13f073d5b978
https://github.com/remarkablemark/html-react-parser/blob/eb3085ab1d0e9c151959ae21f60a13f073d5b978/lib/attributes-to-props.js#L18-L62
16,973
remarkablemark/html-react-parser
lib/attributes-to-props.js
cssToJs
function cssToJs(style) { if (typeof style !== 'string') { throw new TypeError('First argument must be a string.'); } var styleObj = {}; styleToObject(style, function(propName, propValue) { // Check if it's not a comment node if (propName && propValue) { styleObj[utilities.camelCase(propName)] = propValue; } }); return styleObj; }
javascript
function cssToJs(style) { if (typeof style !== 'string') { throw new TypeError('First argument must be a string.'); } var styleObj = {}; styleToObject(style, function(propName, propValue) { // Check if it's not a comment node if (propName && propValue) { styleObj[utilities.camelCase(propName)] = propValue; } }); return styleObj; }
[ "function", "cssToJs", "(", "style", ")", "{", "if", "(", "typeof", "style", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'First argument must be a string.'", ")", ";", "}", "var", "styleObj", "=", "{", "}", ";", "styleToObject", "(", "style", ",", "function", "(", "propName", ",", "propValue", ")", "{", "// Check if it's not a comment node", "if", "(", "propName", "&&", "propValue", ")", "{", "styleObj", "[", "utilities", ".", "camelCase", "(", "propName", ")", "]", "=", "propValue", ";", "}", "}", ")", ";", "return", "styleObj", ";", "}" ]
Converts CSS style string to JS style object. @param {String} style - The CSS style. @return {Object} - The JS style object.
[ "Converts", "CSS", "style", "string", "to", "JS", "style", "object", "." ]
eb3085ab1d0e9c151959ae21f60a13f073d5b978
https://github.com/remarkablemark/html-react-parser/blob/eb3085ab1d0e9c151959ae21f60a13f073d5b978/lib/attributes-to-props.js#L70-L83
16,974
remarkablemark/html-react-parser
index.js
HTMLReactParser
function HTMLReactParser(html, options) { if (typeof html !== 'string') { throw new TypeError('First argument must be a string'); } return domToReact(htmlToDOM(html, domParserOptions), options); }
javascript
function HTMLReactParser(html, options) { if (typeof html !== 'string') { throw new TypeError('First argument must be a string'); } return domToReact(htmlToDOM(html, domParserOptions), options); }
[ "function", "HTMLReactParser", "(", "html", ",", "options", ")", "{", "if", "(", "typeof", "html", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'First argument must be a string'", ")", ";", "}", "return", "domToReact", "(", "htmlToDOM", "(", "html", ",", "domParserOptions", ")", ",", "options", ")", ";", "}" ]
Convert HTML string to React elements. @param {String} html - The HTML string. @param {Object} [options] - The additional options. @param {Function} [options.replace] - The replace method. @return {ReactElement|Array}
[ "Convert", "HTML", "string", "to", "React", "elements", "." ]
eb3085ab1d0e9c151959ae21f60a13f073d5b978
https://github.com/remarkablemark/html-react-parser/blob/eb3085ab1d0e9c151959ae21f60a13f073d5b978/index.js#L15-L20
16,975
remarkablemark/html-react-parser
lib/dom-to-react.js
domToReact
function domToReact(nodes, options) { options = options || {}; var result = []; var node; var isReplacePresent = typeof options.replace === 'function'; var replacement; var props; var children; for (var i = 0, len = nodes.length; i < len; i++) { node = nodes[i]; // replace with custom React element (if applicable) if (isReplacePresent) { replacement = options.replace(node); if (React.isValidElement(replacement)) { // specify a "key" prop if element has siblings // https://fb.me/react-warning-keys if (len > 1) { replacement = React.cloneElement(replacement, { key: replacement.key || i }); } result.push(replacement); continue; } } if (node.type === 'text') { result.push(node.data); continue; } props = node.attribs; if (!shouldPassAttributesUnaltered(node)) { // update values props = attributesToProps(node.attribs); } children = null; // node type for <script> is "script" // node type for <style> is "style" if (node.type === 'script' || node.type === 'style') { // prevent text in <script> or <style> from being escaped // https://facebook.github.io/react/tips/dangerously-set-inner-html.html if (node.children[0]) { props.dangerouslySetInnerHTML = { __html: node.children[0].data }; } } else if (node.type === 'tag') { // setting textarea value in children is an antipattern in React // https://reactjs.org/docs/forms.html#the-textarea-tag if (node.name === 'textarea' && node.children[0]) { props.defaultValue = node.children[0].data; // continue recursion of creating React elements (if applicable) } else if (node.children && node.children.length) { children = domToReact(node.children, options); } // skip all other cases (e.g., comment) } else { continue; } // specify a "key" prop if element has siblings // https://fb.me/react-warning-keys if (len > 1) { props.key = i; } result.push(React.createElement(node.name, props, children)); } return result.length === 1 ? result[0] : result; }
javascript
function domToReact(nodes, options) { options = options || {}; var result = []; var node; var isReplacePresent = typeof options.replace === 'function'; var replacement; var props; var children; for (var i = 0, len = nodes.length; i < len; i++) { node = nodes[i]; // replace with custom React element (if applicable) if (isReplacePresent) { replacement = options.replace(node); if (React.isValidElement(replacement)) { // specify a "key" prop if element has siblings // https://fb.me/react-warning-keys if (len > 1) { replacement = React.cloneElement(replacement, { key: replacement.key || i }); } result.push(replacement); continue; } } if (node.type === 'text') { result.push(node.data); continue; } props = node.attribs; if (!shouldPassAttributesUnaltered(node)) { // update values props = attributesToProps(node.attribs); } children = null; // node type for <script> is "script" // node type for <style> is "style" if (node.type === 'script' || node.type === 'style') { // prevent text in <script> or <style> from being escaped // https://facebook.github.io/react/tips/dangerously-set-inner-html.html if (node.children[0]) { props.dangerouslySetInnerHTML = { __html: node.children[0].data }; } } else if (node.type === 'tag') { // setting textarea value in children is an antipattern in React // https://reactjs.org/docs/forms.html#the-textarea-tag if (node.name === 'textarea' && node.children[0]) { props.defaultValue = node.children[0].data; // continue recursion of creating React elements (if applicable) } else if (node.children && node.children.length) { children = domToReact(node.children, options); } // skip all other cases (e.g., comment) } else { continue; } // specify a "key" prop if element has siblings // https://fb.me/react-warning-keys if (len > 1) { props.key = i; } result.push(React.createElement(node.name, props, children)); } return result.length === 1 ? result[0] : result; }
[ "function", "domToReact", "(", "nodes", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "result", "=", "[", "]", ";", "var", "node", ";", "var", "isReplacePresent", "=", "typeof", "options", ".", "replace", "===", "'function'", ";", "var", "replacement", ";", "var", "props", ";", "var", "children", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "nodes", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "node", "=", "nodes", "[", "i", "]", ";", "// replace with custom React element (if applicable)", "if", "(", "isReplacePresent", ")", "{", "replacement", "=", "options", ".", "replace", "(", "node", ")", ";", "if", "(", "React", ".", "isValidElement", "(", "replacement", ")", ")", "{", "// specify a \"key\" prop if element has siblings", "// https://fb.me/react-warning-keys", "if", "(", "len", ">", "1", ")", "{", "replacement", "=", "React", ".", "cloneElement", "(", "replacement", ",", "{", "key", ":", "replacement", ".", "key", "||", "i", "}", ")", ";", "}", "result", ".", "push", "(", "replacement", ")", ";", "continue", ";", "}", "}", "if", "(", "node", ".", "type", "===", "'text'", ")", "{", "result", ".", "push", "(", "node", ".", "data", ")", ";", "continue", ";", "}", "props", "=", "node", ".", "attribs", ";", "if", "(", "!", "shouldPassAttributesUnaltered", "(", "node", ")", ")", "{", "// update values", "props", "=", "attributesToProps", "(", "node", ".", "attribs", ")", ";", "}", "children", "=", "null", ";", "// node type for <script> is \"script\"", "// node type for <style> is \"style\"", "if", "(", "node", ".", "type", "===", "'script'", "||", "node", ".", "type", "===", "'style'", ")", "{", "// prevent text in <script> or <style> from being escaped", "// https://facebook.github.io/react/tips/dangerously-set-inner-html.html", "if", "(", "node", ".", "children", "[", "0", "]", ")", "{", "props", ".", "dangerouslySetInnerHTML", "=", "{", "__html", ":", "node", ".", "children", "[", "0", "]", ".", "data", "}", ";", "}", "}", "else", "if", "(", "node", ".", "type", "===", "'tag'", ")", "{", "// setting textarea value in children is an antipattern in React", "// https://reactjs.org/docs/forms.html#the-textarea-tag", "if", "(", "node", ".", "name", "===", "'textarea'", "&&", "node", ".", "children", "[", "0", "]", ")", "{", "props", ".", "defaultValue", "=", "node", ".", "children", "[", "0", "]", ".", "data", ";", "// continue recursion of creating React elements (if applicable)", "}", "else", "if", "(", "node", ".", "children", "&&", "node", ".", "children", ".", "length", ")", "{", "children", "=", "domToReact", "(", "node", ".", "children", ",", "options", ")", ";", "}", "// skip all other cases (e.g., comment)", "}", "else", "{", "continue", ";", "}", "// specify a \"key\" prop if element has siblings", "// https://fb.me/react-warning-keys", "if", "(", "len", ">", "1", ")", "{", "props", ".", "key", "=", "i", ";", "}", "result", ".", "push", "(", "React", ".", "createElement", "(", "node", ".", "name", ",", "props", ",", "children", ")", ")", ";", "}", "return", "result", ".", "length", "===", "1", "?", "result", "[", "0", "]", ":", "result", ";", "}" ]
Converts DOM nodes to React elements. @param {Array} nodes - The DOM nodes. @param {Object} [options] - The additional options. @param {Function} [options.replace] - The replace method. @return {ReactElement|Array}
[ "Converts", "DOM", "nodes", "to", "React", "elements", "." ]
eb3085ab1d0e9c151959ae21f60a13f073d5b978
https://github.com/remarkablemark/html-react-parser/blob/eb3085ab1d0e9c151959ae21f60a13f073d5b978/lib/dom-to-react.js#L13-L91
16,976
CrystalComputerCorp/smpte-timecode
smpte-timecode.js
function ( timeCode, frameRate, dropFrame ) { // Make this class safe for use without "new" if (!(this instanceof Timecode)) return new Timecode( timeCode, frameRate, dropFrame); // Get frame rate if (typeof frameRate === 'undefined') this.frameRate = 29.97; else if (typeof frameRate === 'number' && frameRate>0) this.frameRate = frameRate; else throw new Error('Number expected as framerate'); if (this.frameRate!==23.976 && this.frameRate!==24 && this.frameRate!==25 && this.frameRate!==29.97 && this.frameRate!==30 && this.frameRate!==50 && this.frameRate!==59.94 && this.frameRate!==60 ) throw new Error('Unsupported framerate'); // If we are passed dropFrame, we need to use it if (typeof dropFrame === 'boolean') this.dropFrame = dropFrame; else this.dropFrame = (this.frameRate===29.97 || this.frameRate===59.94); // by default, assume DF for 29.97 and 59.94, NDF otherwise // Now either get the frame count, string or datetime if (typeof timeCode === 'number') { this.frameCount = Math.round(timeCode); this._frameCountToTimeCode(); } else if (typeof timeCode === 'string') { // pick it apart var parts = timeCode.match('^([012]\\d):(\\d\\d):(\\d\\d)(:|;|\\.)(\\d\\d)$'); if (!parts) throw new Error("Timecode string expected as HH:MM:SS:FF or HH:MM:SS;FF"); this.hours = parseInt(parts[1]); this.minutes = parseInt(parts[2]); this.seconds = parseInt(parts[3]); // do not override input parameters if (typeof dropFrame !== 'boolean') { this.dropFrame = parts[4]!==':'; } this.frames = parseInt(parts[5]); this._timeCodeToFrameCount(); } else if (typeof timeCode === 'object' && timeCode instanceof Date) { var midnight = new Date(timeCode.getFullYear(), timeCode.getMonth(), timeCode.getDate(),0,0,0); var midnight_tz = midnight.getTimezoneOffset() * 60 * 1000; var timecode_tz = timeCode.getTimezoneOffset() * 60 * 1000; this.frameCount = Math.round(((timeCode-midnight + (midnight_tz - timecode_tz))*this.frameRate)/1000); this._frameCountToTimeCode(); } else if (typeof timeCode === 'object' && timeCode.hours >= 0) { this.hours = timeCode.hours; this.minutes = timeCode.minutes; this.seconds = timeCode.seconds; this.frames = timeCode.frames; this._timeCodeToFrameCount(); } else if (typeof timeCode === 'undefined') { this.frameCount = 0; } else { throw new Error('Timecode() constructor expects a number, timecode string, or Date()'); } this._validate(timeCode); return this; }
javascript
function ( timeCode, frameRate, dropFrame ) { // Make this class safe for use without "new" if (!(this instanceof Timecode)) return new Timecode( timeCode, frameRate, dropFrame); // Get frame rate if (typeof frameRate === 'undefined') this.frameRate = 29.97; else if (typeof frameRate === 'number' && frameRate>0) this.frameRate = frameRate; else throw new Error('Number expected as framerate'); if (this.frameRate!==23.976 && this.frameRate!==24 && this.frameRate!==25 && this.frameRate!==29.97 && this.frameRate!==30 && this.frameRate!==50 && this.frameRate!==59.94 && this.frameRate!==60 ) throw new Error('Unsupported framerate'); // If we are passed dropFrame, we need to use it if (typeof dropFrame === 'boolean') this.dropFrame = dropFrame; else this.dropFrame = (this.frameRate===29.97 || this.frameRate===59.94); // by default, assume DF for 29.97 and 59.94, NDF otherwise // Now either get the frame count, string or datetime if (typeof timeCode === 'number') { this.frameCount = Math.round(timeCode); this._frameCountToTimeCode(); } else if (typeof timeCode === 'string') { // pick it apart var parts = timeCode.match('^([012]\\d):(\\d\\d):(\\d\\d)(:|;|\\.)(\\d\\d)$'); if (!parts) throw new Error("Timecode string expected as HH:MM:SS:FF or HH:MM:SS;FF"); this.hours = parseInt(parts[1]); this.minutes = parseInt(parts[2]); this.seconds = parseInt(parts[3]); // do not override input parameters if (typeof dropFrame !== 'boolean') { this.dropFrame = parts[4]!==':'; } this.frames = parseInt(parts[5]); this._timeCodeToFrameCount(); } else if (typeof timeCode === 'object' && timeCode instanceof Date) { var midnight = new Date(timeCode.getFullYear(), timeCode.getMonth(), timeCode.getDate(),0,0,0); var midnight_tz = midnight.getTimezoneOffset() * 60 * 1000; var timecode_tz = timeCode.getTimezoneOffset() * 60 * 1000; this.frameCount = Math.round(((timeCode-midnight + (midnight_tz - timecode_tz))*this.frameRate)/1000); this._frameCountToTimeCode(); } else if (typeof timeCode === 'object' && timeCode.hours >= 0) { this.hours = timeCode.hours; this.minutes = timeCode.minutes; this.seconds = timeCode.seconds; this.frames = timeCode.frames; this._timeCodeToFrameCount(); } else if (typeof timeCode === 'undefined') { this.frameCount = 0; } else { throw new Error('Timecode() constructor expects a number, timecode string, or Date()'); } this._validate(timeCode); return this; }
[ "function", "(", "timeCode", ",", "frameRate", ",", "dropFrame", ")", "{", "// Make this class safe for use without \"new\"", "if", "(", "!", "(", "this", "instanceof", "Timecode", ")", ")", "return", "new", "Timecode", "(", "timeCode", ",", "frameRate", ",", "dropFrame", ")", ";", "// Get frame rate", "if", "(", "typeof", "frameRate", "===", "'undefined'", ")", "this", ".", "frameRate", "=", "29.97", ";", "else", "if", "(", "typeof", "frameRate", "===", "'number'", "&&", "frameRate", ">", "0", ")", "this", ".", "frameRate", "=", "frameRate", ";", "else", "throw", "new", "Error", "(", "'Number expected as framerate'", ")", ";", "if", "(", "this", ".", "frameRate", "!==", "23.976", "&&", "this", ".", "frameRate", "!==", "24", "&&", "this", ".", "frameRate", "!==", "25", "&&", "this", ".", "frameRate", "!==", "29.97", "&&", "this", ".", "frameRate", "!==", "30", "&&", "this", ".", "frameRate", "!==", "50", "&&", "this", ".", "frameRate", "!==", "59.94", "&&", "this", ".", "frameRate", "!==", "60", ")", "throw", "new", "Error", "(", "'Unsupported framerate'", ")", ";", "// If we are passed dropFrame, we need to use it", "if", "(", "typeof", "dropFrame", "===", "'boolean'", ")", "this", ".", "dropFrame", "=", "dropFrame", ";", "else", "this", ".", "dropFrame", "=", "(", "this", ".", "frameRate", "===", "29.97", "||", "this", ".", "frameRate", "===", "59.94", ")", ";", "// by default, assume DF for 29.97 and 59.94, NDF otherwise", "// Now either get the frame count, string or datetime ", "if", "(", "typeof", "timeCode", "===", "'number'", ")", "{", "this", ".", "frameCount", "=", "Math", ".", "round", "(", "timeCode", ")", ";", "this", ".", "_frameCountToTimeCode", "(", ")", ";", "}", "else", "if", "(", "typeof", "timeCode", "===", "'string'", ")", "{", "// pick it apart", "var", "parts", "=", "timeCode", ".", "match", "(", "'^([012]\\\\d):(\\\\d\\\\d):(\\\\d\\\\d)(:|;|\\\\.)(\\\\d\\\\d)$'", ")", ";", "if", "(", "!", "parts", ")", "throw", "new", "Error", "(", "\"Timecode string expected as HH:MM:SS:FF or HH:MM:SS;FF\"", ")", ";", "this", ".", "hours", "=", "parseInt", "(", "parts", "[", "1", "]", ")", ";", "this", ".", "minutes", "=", "parseInt", "(", "parts", "[", "2", "]", ")", ";", "this", ".", "seconds", "=", "parseInt", "(", "parts", "[", "3", "]", ")", ";", "// do not override input parameters", "if", "(", "typeof", "dropFrame", "!==", "'boolean'", ")", "{", "this", ".", "dropFrame", "=", "parts", "[", "4", "]", "!==", "':'", ";", "}", "this", ".", "frames", "=", "parseInt", "(", "parts", "[", "5", "]", ")", ";", "this", ".", "_timeCodeToFrameCount", "(", ")", ";", "}", "else", "if", "(", "typeof", "timeCode", "===", "'object'", "&&", "timeCode", "instanceof", "Date", ")", "{", "var", "midnight", "=", "new", "Date", "(", "timeCode", ".", "getFullYear", "(", ")", ",", "timeCode", ".", "getMonth", "(", ")", ",", "timeCode", ".", "getDate", "(", ")", ",", "0", ",", "0", ",", "0", ")", ";", "var", "midnight_tz", "=", "midnight", ".", "getTimezoneOffset", "(", ")", "*", "60", "*", "1000", ";", "var", "timecode_tz", "=", "timeCode", ".", "getTimezoneOffset", "(", ")", "*", "60", "*", "1000", ";", "this", ".", "frameCount", "=", "Math", ".", "round", "(", "(", "(", "timeCode", "-", "midnight", "+", "(", "midnight_tz", "-", "timecode_tz", ")", ")", "*", "this", ".", "frameRate", ")", "/", "1000", ")", ";", "this", ".", "_frameCountToTimeCode", "(", ")", ";", "}", "else", "if", "(", "typeof", "timeCode", "===", "'object'", "&&", "timeCode", ".", "hours", ">=", "0", ")", "{", "this", ".", "hours", "=", "timeCode", ".", "hours", ";", "this", ".", "minutes", "=", "timeCode", ".", "minutes", ";", "this", ".", "seconds", "=", "timeCode", ".", "seconds", ";", "this", ".", "frames", "=", "timeCode", ".", "frames", ";", "this", ".", "_timeCodeToFrameCount", "(", ")", ";", "}", "else", "if", "(", "typeof", "timeCode", "===", "'undefined'", ")", "{", "this", ".", "frameCount", "=", "0", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Timecode() constructor expects a number, timecode string, or Date()'", ")", ";", "}", "this", ".", "_validate", "(", "timeCode", ")", ";", "return", "this", ";", "}" ]
Timecode object constructor @param {number|String|Date|Object} timeCode Frame count as number, "HH:MM:SS(:|;|.)FF", Date(), or object. @param {number} [frameRate=29.97] Frame rate @param {boolean} [dropFrame=true] Whether the timecode is drop-frame or not @constructor @returns {Timecode} timecode
[ "Timecode", "object", "constructor" ]
fb9031de573ab648fbbbb1fbb0d2a4e78859e0fe
https://github.com/CrystalComputerCorp/smpte-timecode/blob/fb9031de573ab648fbbbb1fbb0d2a4e78859e0fe/smpte-timecode.js#L13-L73
16,977
namics/webpack-config-plugins
packages/ts-config-webpack-plugin/src/TsConfigValidator.js
verifyTsConfig
function verifyTsConfig(configFilePath) { /** * @type {string[]} */ const warnings = []; const createConfigFileHost = { onUnRecoverableConfigFileDiagnostic() {}, useCaseSensitiveFileNames: false, readDirectory: typescript.sys.readDirectory, fileExists: typescript.sys.fileExists, readFile: typescript.sys.readFile, getCurrentDirectory: typescript.sys.getCurrentDirectory, }; const tsconfig = typescript.getParsedCommandLineOfConfigFile(configFilePath, {}, createConfigFileHost); if (!tsconfig) { return [`could not parse "${configFilePath}"`]; } if (tsconfig.options.skipLibCheck === undefined) { warnings.push( 'skipLibCheck option was NOT specified\n' + 'By default the fork-ts-checker-webpack-plugin will check all types inside the node_modules directory\n' + 'even for unused dependencies and slow down the type checking a lot.\n' + 'To skip that checking add the following line to your tsconfig.json compilerOptions configuration:\n' + '"skipLibCheck": true\n' + 'To keep the default behaviour with possible performance penalties set skipLibCheck to false to hide this warning.\n' ); } if (tsconfig.options.moduleResolution === undefined) { warnings.push( 'moduleResolution option was NOT specified\n' + 'This will result in typescript warnings like "module not found".\n' + 'To fix that add the following line to your tsconfig.json compilerOptions configuration:\n' + '"moduleResolution": "node"\n' + 'To keep the default behaviour with possible type checking errors set moduleResolution to "classic" to hide this warning.\n' ); } return warnings; }
javascript
function verifyTsConfig(configFilePath) { /** * @type {string[]} */ const warnings = []; const createConfigFileHost = { onUnRecoverableConfigFileDiagnostic() {}, useCaseSensitiveFileNames: false, readDirectory: typescript.sys.readDirectory, fileExists: typescript.sys.fileExists, readFile: typescript.sys.readFile, getCurrentDirectory: typescript.sys.getCurrentDirectory, }; const tsconfig = typescript.getParsedCommandLineOfConfigFile(configFilePath, {}, createConfigFileHost); if (!tsconfig) { return [`could not parse "${configFilePath}"`]; } if (tsconfig.options.skipLibCheck === undefined) { warnings.push( 'skipLibCheck option was NOT specified\n' + 'By default the fork-ts-checker-webpack-plugin will check all types inside the node_modules directory\n' + 'even for unused dependencies and slow down the type checking a lot.\n' + 'To skip that checking add the following line to your tsconfig.json compilerOptions configuration:\n' + '"skipLibCheck": true\n' + 'To keep the default behaviour with possible performance penalties set skipLibCheck to false to hide this warning.\n' ); } if (tsconfig.options.moduleResolution === undefined) { warnings.push( 'moduleResolution option was NOT specified\n' + 'This will result in typescript warnings like "module not found".\n' + 'To fix that add the following line to your tsconfig.json compilerOptions configuration:\n' + '"moduleResolution": "node"\n' + 'To keep the default behaviour with possible type checking errors set moduleResolution to "classic" to hide this warning.\n' ); } return warnings; }
[ "function", "verifyTsConfig", "(", "configFilePath", ")", "{", "/**\n\t * @type {string[]}\n\t */", "const", "warnings", "=", "[", "]", ";", "const", "createConfigFileHost", "=", "{", "onUnRecoverableConfigFileDiagnostic", "(", ")", "{", "}", ",", "useCaseSensitiveFileNames", ":", "false", ",", "readDirectory", ":", "typescript", ".", "sys", ".", "readDirectory", ",", "fileExists", ":", "typescript", ".", "sys", ".", "fileExists", ",", "readFile", ":", "typescript", ".", "sys", ".", "readFile", ",", "getCurrentDirectory", ":", "typescript", ".", "sys", ".", "getCurrentDirectory", ",", "}", ";", "const", "tsconfig", "=", "typescript", ".", "getParsedCommandLineOfConfigFile", "(", "configFilePath", ",", "{", "}", ",", "createConfigFileHost", ")", ";", "if", "(", "!", "tsconfig", ")", "{", "return", "[", "`", "${", "configFilePath", "}", "`", "]", ";", "}", "if", "(", "tsconfig", ".", "options", ".", "skipLibCheck", "===", "undefined", ")", "{", "warnings", ".", "push", "(", "'skipLibCheck option was NOT specified\\n'", "+", "'By default the fork-ts-checker-webpack-plugin will check all types inside the node_modules directory\\n'", "+", "'even for unused dependencies and slow down the type checking a lot.\\n'", "+", "'To skip that checking add the following line to your tsconfig.json compilerOptions configuration:\\n'", "+", "'\"skipLibCheck\": true\\n'", "+", "'To keep the default behaviour with possible performance penalties set skipLibCheck to false to hide this warning.\\n'", ")", ";", "}", "if", "(", "tsconfig", ".", "options", ".", "moduleResolution", "===", "undefined", ")", "{", "warnings", ".", "push", "(", "'moduleResolution option was NOT specified\\n'", "+", "'This will result in typescript warnings like \"module not found\".\\n'", "+", "'To fix that add the following line to your tsconfig.json compilerOptions configuration:\\n'", "+", "'\"moduleResolution\": \"node\"\\n'", "+", "'To keep the default behaviour with possible type checking errors set moduleResolution to \"classic\" to hide this warning.\\n'", ")", ";", "}", "return", "warnings", ";", "}" ]
Check for known TSConfig issues and output warnings @param {string} configFilePath @returns {string[]} warnings
[ "Check", "for", "known", "TSConfig", "issues", "and", "output", "warnings" ]
74f04974b98226e2afac25422cc57dfb96e4f77b
https://github.com/namics/webpack-config-plugins/blob/74f04974b98226e2afac25422cc57dfb96e4f77b/packages/ts-config-webpack-plugin/src/TsConfigValidator.js#L20-L58
16,978
TooTallNate/node-time
index.js
listTimezones
function listTimezones () { if (arguments.length == 0) { throw new Error("You must set a callback"); } if (typeof arguments[arguments.length - 1] != "function") { throw new Error("You must set a callback"); } var cb = arguments[arguments.length - 1] , subset = (arguments.length > 1 ? arguments[0] : null) return listTimezonesFolder(subset ? subset + "/" : "", subset ? path.join(TZDIR, "/" + subset) : TZDIR, function (err, tzs) { if (err) return cb(err); cb(null, tzs.sort()); }); }
javascript
function listTimezones () { if (arguments.length == 0) { throw new Error("You must set a callback"); } if (typeof arguments[arguments.length - 1] != "function") { throw new Error("You must set a callback"); } var cb = arguments[arguments.length - 1] , subset = (arguments.length > 1 ? arguments[0] : null) return listTimezonesFolder(subset ? subset + "/" : "", subset ? path.join(TZDIR, "/" + subset) : TZDIR, function (err, tzs) { if (err) return cb(err); cb(null, tzs.sort()); }); }
[ "function", "listTimezones", "(", ")", "{", "if", "(", "arguments", ".", "length", "==", "0", ")", "{", "throw", "new", "Error", "(", "\"You must set a callback\"", ")", ";", "}", "if", "(", "typeof", "arguments", "[", "arguments", ".", "length", "-", "1", "]", "!=", "\"function\"", ")", "{", "throw", "new", "Error", "(", "\"You must set a callback\"", ")", ";", "}", "var", "cb", "=", "arguments", "[", "arguments", ".", "length", "-", "1", "]", ",", "subset", "=", "(", "arguments", ".", "length", ">", "1", "?", "arguments", "[", "0", "]", ":", "null", ")", "return", "listTimezonesFolder", "(", "subset", "?", "subset", "+", "\"/\"", ":", "\"\"", ",", "subset", "?", "path", ".", "join", "(", "TZDIR", ",", "\"/\"", "+", "subset", ")", ":", "TZDIR", ",", "function", "(", "err", ",", "tzs", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "cb", "(", "null", ",", "tzs", ".", "sort", "(", ")", ")", ";", "}", ")", ";", "}" ]
Lists the timezones that the current system can accept. It does this by going on a recursive walk through the timezone dir and collecting filenames.
[ "Lists", "the", "timezones", "that", "the", "current", "system", "can", "accept", ".", "It", "does", "this", "by", "going", "on", "a", "recursive", "walk", "through", "the", "timezone", "dir", "and", "collecting", "filenames", "." ]
2739eac5d5e11d47f4048af7711f68556ae893d4
https://github.com/TooTallNate/node-time/blob/2739eac5d5e11d47f4048af7711f68556ae893d4/index.js#L177-L191
16,979
TooTallNate/node-time
index.js
pad
function pad (num, padLen) { var padding = '0000'; num = String(num); return padding.substring(0, padLen - num.length) + num; }
javascript
function pad (num, padLen) { var padding = '0000'; num = String(num); return padding.substring(0, padLen - num.length) + num; }
[ "function", "pad", "(", "num", ",", "padLen", ")", "{", "var", "padding", "=", "'0000'", ";", "num", "=", "String", "(", "num", ")", ";", "return", "padding", ".", "substring", "(", "0", ",", "padLen", "-", "num", ".", "length", ")", "+", "num", ";", "}" ]
Pads a number with 0s if required.
[ "Pads", "a", "number", "with", "0s", "if", "required", "." ]
2739eac5d5e11d47f4048af7711f68556ae893d4
https://github.com/TooTallNate/node-time/blob/2739eac5d5e11d47f4048af7711f68556ae893d4/index.js#L635-L639
16,980
assistunion/xml-stream
lib/xml-stream.js
normalizeSelector
function normalizeSelector(selector) { var parts = selector.match(/[^\s>]+|>/ig); selector = (parts) ? parts.join(' ') : ''; return { normalized: selector, parts: parts || [] }; }
javascript
function normalizeSelector(selector) { var parts = selector.match(/[^\s>]+|>/ig); selector = (parts) ? parts.join(' ') : ''; return { normalized: selector, parts: parts || [] }; }
[ "function", "normalizeSelector", "(", "selector", ")", "{", "var", "parts", "=", "selector", ".", "match", "(", "/", "[^\\s>]+|>", "/", "ig", ")", ";", "selector", "=", "(", "parts", ")", "?", "parts", ".", "join", "(", "' '", ")", ":", "''", ";", "return", "{", "normalized", ":", "selector", ",", "parts", ":", "parts", "||", "[", "]", "}", ";", "}" ]
Normalizes the selector and returns the new version and its parts.
[ "Normalizes", "the", "selector", "and", "returns", "the", "new", "version", "and", "its", "parts", "." ]
d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c
https://github.com/assistunion/xml-stream/blob/d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c/lib/xml-stream.js#L210-L217
16,981
assistunion/xml-stream
lib/xml-stream.js
parseEvent
function parseEvent(event) { var eventParts = event.match(/^((?:start|end|update)Element|text):?(.*)/); if (eventParts === null) { return null; } var eventType = eventParts[1]; var selector = normalizeSelector(eventParts[2]); return { selector: selector, type: eventType, name: (eventParts[2]) ? eventType + ': ' + selector.normalized : eventType }; }
javascript
function parseEvent(event) { var eventParts = event.match(/^((?:start|end|update)Element|text):?(.*)/); if (eventParts === null) { return null; } var eventType = eventParts[1]; var selector = normalizeSelector(eventParts[2]); return { selector: selector, type: eventType, name: (eventParts[2]) ? eventType + ': ' + selector.normalized : eventType }; }
[ "function", "parseEvent", "(", "event", ")", "{", "var", "eventParts", "=", "event", ".", "match", "(", "/", "^((?:start|end|update)Element|text):?(.*)", "/", ")", ";", "if", "(", "eventParts", "===", "null", ")", "{", "return", "null", ";", "}", "var", "eventType", "=", "eventParts", "[", "1", "]", ";", "var", "selector", "=", "normalizeSelector", "(", "eventParts", "[", "2", "]", ")", ";", "return", "{", "selector", ":", "selector", ",", "type", ":", "eventType", ",", "name", ":", "(", "eventParts", "[", "2", "]", ")", "?", "eventType", "+", "': '", "+", "selector", ".", "normalized", ":", "eventType", "}", ";", "}" ]
Parses the selector event string and returns event information.
[ "Parses", "the", "selector", "event", "string", "and", "returns", "event", "information", "." ]
d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c
https://github.com/assistunion/xml-stream/blob/d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c/lib/xml-stream.js#L220-L233
16,982
assistunion/xml-stream
lib/xml-stream.js
getFinalState
function getFinalState(selector) { if (__own.call(this._finalStates, selector.normalized)) { var finalState = this._finalStates[selector.normalized]; } else { var n = selector.parts.length; var immediate = false; this._startState[this._lastState] = true; for (var i = 0; i < n; i++) { var part = selector.parts[i]; if (part === '>') { immediate = true; } else { if (!immediate) { this._fa.transition(this._lastState, '', this._lastState); } this._fa.transition(this._lastState, part, ++this._lastState); immediate = false; } } var finalState = this._lastState++; this._finalStates[selector.normalized] = finalState; } return finalState; }
javascript
function getFinalState(selector) { if (__own.call(this._finalStates, selector.normalized)) { var finalState = this._finalStates[selector.normalized]; } else { var n = selector.parts.length; var immediate = false; this._startState[this._lastState] = true; for (var i = 0; i < n; i++) { var part = selector.parts[i]; if (part === '>') { immediate = true; } else { if (!immediate) { this._fa.transition(this._lastState, '', this._lastState); } this._fa.transition(this._lastState, part, ++this._lastState); immediate = false; } } var finalState = this._lastState++; this._finalStates[selector.normalized] = finalState; } return finalState; }
[ "function", "getFinalState", "(", "selector", ")", "{", "if", "(", "__own", ".", "call", "(", "this", ".", "_finalStates", ",", "selector", ".", "normalized", ")", ")", "{", "var", "finalState", "=", "this", ".", "_finalStates", "[", "selector", ".", "normalized", "]", ";", "}", "else", "{", "var", "n", "=", "selector", ".", "parts", ".", "length", ";", "var", "immediate", "=", "false", ";", "this", ".", "_startState", "[", "this", ".", "_lastState", "]", "=", "true", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "part", "=", "selector", ".", "parts", "[", "i", "]", ";", "if", "(", "part", "===", "'>'", ")", "{", "immediate", "=", "true", ";", "}", "else", "{", "if", "(", "!", "immediate", ")", "{", "this", ".", "_fa", ".", "transition", "(", "this", ".", "_lastState", ",", "''", ",", "this", ".", "_lastState", ")", ";", "}", "this", ".", "_fa", ".", "transition", "(", "this", ".", "_lastState", ",", "part", ",", "++", "this", ".", "_lastState", ")", ";", "immediate", "=", "false", ";", "}", "}", "var", "finalState", "=", "this", ".", "_lastState", "++", ";", "this", ".", "_finalStates", "[", "selector", ".", "normalized", "]", "=", "finalState", ";", "}", "return", "finalState", ";", "}" ]
Compiles a given selector object to a finite automata and returns its last state.
[ "Compiles", "a", "given", "selector", "object", "to", "a", "finite", "automata", "and", "returns", "its", "last", "state", "." ]
d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c
https://github.com/assistunion/xml-stream/blob/d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c/lib/xml-stream.js#L237-L260
16,983
assistunion/xml-stream
lib/xml-stream.js
emitStart
function emitStart(name, attrs) { this.emit('data', '<' + name); for (var attr in attrs) if (__own.call(attrs, attr)) { this.emit('data', ' ' + attr + '="' + escape(attrs[attr]) + '"'); } this.emit('data', '>'); }
javascript
function emitStart(name, attrs) { this.emit('data', '<' + name); for (var attr in attrs) if (__own.call(attrs, attr)) { this.emit('data', ' ' + attr + '="' + escape(attrs[attr]) + '"'); } this.emit('data', '>'); }
[ "function", "emitStart", "(", "name", ",", "attrs", ")", "{", "this", ".", "emit", "(", "'data'", ",", "'<'", "+", "name", ")", ";", "for", "(", "var", "attr", "in", "attrs", ")", "if", "(", "__own", ".", "call", "(", "attrs", ",", "attr", ")", ")", "{", "this", ".", "emit", "(", "'data'", ",", "' '", "+", "attr", "+", "'=\"'", "+", "escape", "(", "attrs", "[", "attr", "]", ")", "+", "'\"'", ")", ";", "}", "this", ".", "emit", "(", "'data'", ",", "'>'", ")", ";", "}" ]
Emits XML for element opening tag.
[ "Emits", "XML", "for", "element", "opening", "tag", "." ]
d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c
https://github.com/assistunion/xml-stream/blob/d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c/lib/xml-stream.js#L263-L269
16,984
assistunion/xml-stream
lib/xml-stream.js
emitElement
function emitElement(element, name, onLeave) { if (Array.isArray(element)) { var i; for (i = 0; i < element.length - 1; i++) { emitOneElement.call(this, element[i], name); } emitOneElement.call(this, element[i], name, onLeave); } else { emitOneElement.call(this, element, name, onLeave); } }
javascript
function emitElement(element, name, onLeave) { if (Array.isArray(element)) { var i; for (i = 0; i < element.length - 1; i++) { emitOneElement.call(this, element[i], name); } emitOneElement.call(this, element[i], name, onLeave); } else { emitOneElement.call(this, element, name, onLeave); } }
[ "function", "emitElement", "(", "element", ",", "name", ",", "onLeave", ")", "{", "if", "(", "Array", ".", "isArray", "(", "element", ")", ")", "{", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "element", ".", "length", "-", "1", ";", "i", "++", ")", "{", "emitOneElement", ".", "call", "(", "this", ",", "element", "[", "i", "]", ",", "name", ")", ";", "}", "emitOneElement", ".", "call", "(", "this", ",", "element", "[", "i", "]", ",", "name", ",", "onLeave", ")", ";", "}", "else", "{", "emitOneElement", ".", "call", "(", "this", ",", "element", ",", "name", ",", "onLeave", ")", ";", "}", "}" ]
Emits a single element and its descendants, or an array of elements.
[ "Emits", "a", "single", "element", "and", "its", "descendants", "or", "an", "array", "of", "elements", "." ]
d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c
https://github.com/assistunion/xml-stream/blob/d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c/lib/xml-stream.js#L282-L292
16,985
assistunion/xml-stream
lib/xml-stream.js
emitChildren
function emitChildren(elements) { var i; for (i = 0; i < elements.length; i++) { var element = elements[i]; if (typeof element === 'object') { emitStart.call(this, element.$name, element.$); emitChildren.call(this, element.$children); emitEnd.call(this, element.$name); } else { emitText.call(this, element); } } }
javascript
function emitChildren(elements) { var i; for (i = 0; i < elements.length; i++) { var element = elements[i]; if (typeof element === 'object') { emitStart.call(this, element.$name, element.$); emitChildren.call(this, element.$children); emitEnd.call(this, element.$name); } else { emitText.call(this, element); } } }
[ "function", "emitChildren", "(", "elements", ")", "{", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "++", ")", "{", "var", "element", "=", "elements", "[", "i", "]", ";", "if", "(", "typeof", "element", "===", "'object'", ")", "{", "emitStart", ".", "call", "(", "this", ",", "element", ".", "$name", ",", "element", ".", "$", ")", ";", "emitChildren", ".", "call", "(", "this", ",", "element", ".", "$children", ")", ";", "emitEnd", ".", "call", "(", "this", ",", "element", ".", "$name", ")", ";", "}", "else", "{", "emitText", ".", "call", "(", "this", ",", "element", ")", ";", "}", "}", "}" ]
Emits child element collection and their descendants. Works only with preserved nodes.
[ "Emits", "child", "element", "collection", "and", "their", "descendants", ".", "Works", "only", "with", "preserved", "nodes", "." ]
d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c
https://github.com/assistunion/xml-stream/blob/d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c/lib/xml-stream.js#L296-L308
16,986
assistunion/xml-stream
lib/xml-stream.js
emitOneElement
function emitOneElement(element, name, onLeave) { if (typeof element === 'object') { emitStart.call(this, name, element.$); if (__own.call(element, '$children')) { emitChildren.call(this, element.$children); } else { var hasText = false; for (var child in element) { if (__own.call(element, child) && child !== '$' && child != '$name') { if (child === '$text') { hasText = true; } else { emitElement.call(this, element[child], child); } } } if (hasText) { emitText.call(this, element.$text); } } } else { emitStart.call(this, name, element.$); emitText.call(this, element); } if (!onLeave) { emitEnd.call(this, name); } }
javascript
function emitOneElement(element, name, onLeave) { if (typeof element === 'object') { emitStart.call(this, name, element.$); if (__own.call(element, '$children')) { emitChildren.call(this, element.$children); } else { var hasText = false; for (var child in element) { if (__own.call(element, child) && child !== '$' && child != '$name') { if (child === '$text') { hasText = true; } else { emitElement.call(this, element[child], child); } } } if (hasText) { emitText.call(this, element.$text); } } } else { emitStart.call(this, name, element.$); emitText.call(this, element); } if (!onLeave) { emitEnd.call(this, name); } }
[ "function", "emitOneElement", "(", "element", ",", "name", ",", "onLeave", ")", "{", "if", "(", "typeof", "element", "===", "'object'", ")", "{", "emitStart", ".", "call", "(", "this", ",", "name", ",", "element", ".", "$", ")", ";", "if", "(", "__own", ".", "call", "(", "element", ",", "'$children'", ")", ")", "{", "emitChildren", ".", "call", "(", "this", ",", "element", ".", "$children", ")", ";", "}", "else", "{", "var", "hasText", "=", "false", ";", "for", "(", "var", "child", "in", "element", ")", "{", "if", "(", "__own", ".", "call", "(", "element", ",", "child", ")", "&&", "child", "!==", "'$'", "&&", "child", "!=", "'$name'", ")", "{", "if", "(", "child", "===", "'$text'", ")", "{", "hasText", "=", "true", ";", "}", "else", "{", "emitElement", ".", "call", "(", "this", ",", "element", "[", "child", "]", ",", "child", ")", ";", "}", "}", "}", "if", "(", "hasText", ")", "{", "emitText", ".", "call", "(", "this", ",", "element", ".", "$text", ")", ";", "}", "}", "}", "else", "{", "emitStart", ".", "call", "(", "this", ",", "name", ",", "element", ".", "$", ")", ";", "emitText", ".", "call", "(", "this", ",", "element", ")", ";", "}", "if", "(", "!", "onLeave", ")", "{", "emitEnd", ".", "call", "(", "this", ",", "name", ")", ";", "}", "}" ]
Recursively emits a given element and its descendants.
[ "Recursively", "emits", "a", "given", "element", "and", "its", "descendants", "." ]
d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c
https://github.com/assistunion/xml-stream/blob/d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c/lib/xml-stream.js#L311-L338
16,987
assistunion/xml-stream
lib/xml-stream.js
function(data) { if (self._encoder) { data = self._encoder.convert(data); } if (!xml.parse(data, false)) { self.emit('error', new Error(xml.getError()+" in line "+xml.getCurrentLineNumber())); } }
javascript
function(data) { if (self._encoder) { data = self._encoder.convert(data); } if (!xml.parse(data, false)) { self.emit('error', new Error(xml.getError()+" in line "+xml.getCurrentLineNumber())); } }
[ "function", "(", "data", ")", "{", "if", "(", "self", ".", "_encoder", ")", "{", "data", "=", "self", ".", "_encoder", ".", "convert", "(", "data", ")", ";", "}", "if", "(", "!", "xml", ".", "parse", "(", "data", ",", "false", ")", ")", "{", "self", ".", "emit", "(", "'error'", ",", "new", "Error", "(", "xml", ".", "getError", "(", ")", "+", "\" in line \"", "+", "xml", ".", "getCurrentLineNumber", "(", ")", ")", ")", ";", "}", "}" ]
Parse incoming chunk. Convert to UTF-8 or emit errors when appropriate.
[ "Parse", "incoming", "chunk", ".", "Convert", "to", "UTF", "-", "8", "or", "emit", "errors", "when", "appropriate", "." ]
d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c
https://github.com/assistunion/xml-stream/blob/d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c/lib/xml-stream.js#L519-L526
16,988
assistunion/xml-stream
examples/encoding.js
setup
function setup(encoding) { var stream = fs.createReadStream(path.join(__dirname, 'encoding.xml')); var xml = new XmlStream(stream, encoding); xml.on('endElement: node', function(node) { console.log(node); }); xml.on('error', function(message) { console.log('Parsing as ' + (encoding || 'auto') + ' failed: ' + message); }); return xml; }
javascript
function setup(encoding) { var stream = fs.createReadStream(path.join(__dirname, 'encoding.xml')); var xml = new XmlStream(stream, encoding); xml.on('endElement: node', function(node) { console.log(node); }); xml.on('error', function(message) { console.log('Parsing as ' + (encoding || 'auto') + ' failed: ' + message); }); return xml; }
[ "function", "setup", "(", "encoding", ")", "{", "var", "stream", "=", "fs", ".", "createReadStream", "(", "path", ".", "join", "(", "__dirname", ",", "'encoding.xml'", ")", ")", ";", "var", "xml", "=", "new", "XmlStream", "(", "stream", ",", "encoding", ")", ";", "xml", ".", "on", "(", "'endElement: node'", ",", "function", "(", "node", ")", "{", "console", ".", "log", "(", "node", ")", ";", "}", ")", ";", "xml", ".", "on", "(", "'error'", ",", "function", "(", "message", ")", "{", "console", ".", "log", "(", "'Parsing as '", "+", "(", "encoding", "||", "'auto'", ")", "+", "' failed: '", "+", "message", ")", ";", "}", ")", ";", "return", "xml", ";", "}" ]
Create a file stream and pass it to XmlStream
[ "Create", "a", "file", "stream", "and", "pass", "it", "to", "XmlStream" ]
d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c
https://github.com/assistunion/xml-stream/blob/d4b60adba5a8e8b0c08aeb2ff5129c6c2d92aa0c/examples/encoding.js#L7-L17
16,989
DHTMLX/scheduler
codebase/sources/ext/dhtmlxscheduler_mvc.js
sanitize
function sanitize(ev){ var obj = {}; for (var key in ev) if (key.indexOf("_") !== 0) obj[key] = ev[key]; if (!cfg.use_id) delete obj.id; return obj; }
javascript
function sanitize(ev){ var obj = {}; for (var key in ev) if (key.indexOf("_") !== 0) obj[key] = ev[key]; if (!cfg.use_id) delete obj.id; return obj; }
[ "function", "sanitize", "(", "ev", ")", "{", "var", "obj", "=", "{", "}", ";", "for", "(", "var", "key", "in", "ev", ")", "if", "(", "key", ".", "indexOf", "(", "\"_\"", ")", "!==", "0", ")", "obj", "[", "key", "]", "=", "ev", "[", "key", "]", ";", "if", "(", "!", "cfg", ".", "use_id", ")", "delete", "obj", ".", "id", ";", "return", "obj", ";", "}" ]
remove private properties
[ "remove", "private", "properties" ]
f1629dd8647b08978d3f8ba4d56eacc9b741f543
https://github.com/DHTMLX/scheduler/blob/f1629dd8647b08978d3f8ba4d56eacc9b741f543/codebase/sources/ext/dhtmlxscheduler_mvc.js#L16-L26
16,990
ricklupton/d3-sankey-diagram
src/sankeyLayout/link-ordering.js
orderEdgesOne
function orderEdgesOne (G, v) { const node = G.node(v) node.ports.forEach(port => { port.incoming.sort(compareDirection(G, node, false)) port.outgoing.sort(compareDirection(G, node, true)) }) }
javascript
function orderEdgesOne (G, v) { const node = G.node(v) node.ports.forEach(port => { port.incoming.sort(compareDirection(G, node, false)) port.outgoing.sort(compareDirection(G, node, true)) }) }
[ "function", "orderEdgesOne", "(", "G", ",", "v", ")", "{", "const", "node", "=", "G", ".", "node", "(", "v", ")", "node", ".", "ports", ".", "forEach", "(", "port", "=>", "{", "port", ".", "incoming", ".", "sort", "(", "compareDirection", "(", "G", ",", "node", ",", "false", ")", ")", "port", ".", "outgoing", ".", "sort", "(", "compareDirection", "(", "G", ",", "node", ",", "true", ")", ")", "}", ")", "}" ]
Order the edges at the given node. The ports have already been setup and sorted.
[ "Order", "the", "edges", "at", "the", "given", "node", ".", "The", "ports", "have", "already", "been", "setup", "and", "sorted", "." ]
baeb5bb1ca3df45af0ed175e5b733700ddddcfcb
https://github.com/ricklupton/d3-sankey-diagram/blob/baeb5bb1ca3df45af0ed175e5b733700ddddcfcb/src/sankeyLayout/link-ordering.js#L16-L22
16,991
expo/stripe-expo
index.js
_convertDetails
function _convertDetails(type, details) { var convertedDetails = {} for (var data in details) { const string = type + '[' + data + ']'; convertedDetails[string] = details[data]; } return convertedDetails; }
javascript
function _convertDetails(type, details) { var convertedDetails = {} for (var data in details) { const string = type + '[' + data + ']'; convertedDetails[string] = details[data]; } return convertedDetails; }
[ "function", "_convertDetails", "(", "type", ",", "details", ")", "{", "var", "convertedDetails", "=", "{", "}", "for", "(", "var", "data", "in", "details", ")", "{", "const", "string", "=", "type", "+", "'['", "+", "data", "+", "']'", ";", "convertedDetails", "[", "string", "]", "=", "details", "[", "data", "]", ";", "}", "return", "convertedDetails", ";", "}" ]
_convertDetails converts and returns the data in the given details to the correct Stripe format for the given type.
[ "_convertDetails", "converts", "and", "returns", "the", "data", "in", "the", "given", "details", "to", "the", "correct", "Stripe", "format", "for", "the", "given", "type", "." ]
c917a32f8bcc78f5aecb4147a16495e06d1a69c3
https://github.com/expo/stripe-expo/blob/c917a32f8bcc78f5aecb4147a16495e06d1a69c3/index.js#L37-L44
16,992
expo/stripe-expo
index.js
_parseJSON
async function _parseJSON(token) { if (token._bodyInit == null) { return token; } else { const body = await token.json(); return body; } }
javascript
async function _parseJSON(token) { if (token._bodyInit == null) { return token; } else { const body = await token.json(); return body; } }
[ "async", "function", "_parseJSON", "(", "token", ")", "{", "if", "(", "token", ".", "_bodyInit", "==", "null", ")", "{", "return", "token", ";", "}", "else", "{", "const", "body", "=", "await", "token", ".", "json", "(", ")", ";", "return", "body", ";", "}", "}" ]
Stripe gives a JSON object with the token object embedded as a JSON string. _parseJSON finds that string in and returns it as a JSON object, or an error if Stripe threw an error instead. If the JSON does not need to be parsed, returns the token.
[ "Stripe", "gives", "a", "JSON", "object", "with", "the", "token", "object", "embedded", "as", "a", "JSON", "string", ".", "_parseJSON", "finds", "that", "string", "in", "and", "returns", "it", "as", "a", "JSON", "object", "or", "an", "error", "if", "Stripe", "threw", "an", "error", "instead", ".", "If", "the", "JSON", "does", "not", "need", "to", "be", "parsed", "returns", "the", "token", "." ]
c917a32f8bcc78f5aecb4147a16495e06d1a69c3
https://github.com/expo/stripe-expo/blob/c917a32f8bcc78f5aecb4147a16495e06d1a69c3/index.js#L49-L56
16,993
hflabs/suggestions-jquery
src/includes/container.js
highlightMatches
function highlightMatches(chunks) { return $.map(chunks, function (chunk) { var text = utils.escapeHtml(chunk.text); if (text && chunk.matched) { text = '<strong>' + text + '</strong>'; } return text; }).join(''); }
javascript
function highlightMatches(chunks) { return $.map(chunks, function (chunk) { var text = utils.escapeHtml(chunk.text); if (text && chunk.matched) { text = '<strong>' + text + '</strong>'; } return text; }).join(''); }
[ "function", "highlightMatches", "(", "chunks", ")", "{", "return", "$", ".", "map", "(", "chunks", ",", "function", "(", "chunk", ")", "{", "var", "text", "=", "utils", ".", "escapeHtml", "(", "chunk", ".", "text", ")", ";", "if", "(", "text", "&&", "chunk", ".", "matched", ")", "{", "text", "=", "'<strong>'", "+", "text", "+", "'</strong>'", ";", "}", "return", "text", ";", "}", ")", ".", "join", "(", "''", ")", ";", "}" ]
Methods related to suggestions dropdown list
[ "Methods", "related", "to", "suggestions", "dropdown", "list" ]
17e3ac383790069ad4d3dd92185d9fb9e30382a7
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/container.js#L16-L25
16,994
hflabs/suggestions-jquery
src/includes/container.js
function (origin, elLayout) { var that = this, scrollLeft = that.$viewport.scrollLeft(), style; if (that.isMobile) { style = that.options.floating ? { left: scrollLeft + 'px', top: elLayout.top + elLayout.outerHeight + 'px' } : { left: origin.left - elLayout.left + scrollLeft + 'px', top: origin.top + elLayout.outerHeight + 'px' }; style.width = that.$viewport.width() + 'px'; } else { style = that.options.floating ? { left: elLayout.left + 'px', top: elLayout.top + elLayout.borderTop + elLayout.innerHeight + 'px' } : { left: origin.left + 'px', top: origin.top + elLayout.borderTop + elLayout.innerHeight + 'px' }; // Defer to let body show scrollbars utils.delay(function () { var width = that.options.width; if (width === 'auto') { width = that.el.outerWidth(); } that.$container.outerWidth(width); }); } that.$container .toggleClass(that.classes.mobile, that.isMobile) .css(style); that.containerItemsPadding = elLayout.left + elLayout.borderLeft + elLayout.paddingLeft - scrollLeft; }
javascript
function (origin, elLayout) { var that = this, scrollLeft = that.$viewport.scrollLeft(), style; if (that.isMobile) { style = that.options.floating ? { left: scrollLeft + 'px', top: elLayout.top + elLayout.outerHeight + 'px' } : { left: origin.left - elLayout.left + scrollLeft + 'px', top: origin.top + elLayout.outerHeight + 'px' }; style.width = that.$viewport.width() + 'px'; } else { style = that.options.floating ? { left: elLayout.left + 'px', top: elLayout.top + elLayout.borderTop + elLayout.innerHeight + 'px' } : { left: origin.left + 'px', top: origin.top + elLayout.borderTop + elLayout.innerHeight + 'px' }; // Defer to let body show scrollbars utils.delay(function () { var width = that.options.width; if (width === 'auto') { width = that.el.outerWidth(); } that.$container.outerWidth(width); }); } that.$container .toggleClass(that.classes.mobile, that.isMobile) .css(style); that.containerItemsPadding = elLayout.left + elLayout.borderLeft + elLayout.paddingLeft - scrollLeft; }
[ "function", "(", "origin", ",", "elLayout", ")", "{", "var", "that", "=", "this", ",", "scrollLeft", "=", "that", ".", "$viewport", ".", "scrollLeft", "(", ")", ",", "style", ";", "if", "(", "that", ".", "isMobile", ")", "{", "style", "=", "that", ".", "options", ".", "floating", "?", "{", "left", ":", "scrollLeft", "+", "'px'", ",", "top", ":", "elLayout", ".", "top", "+", "elLayout", ".", "outerHeight", "+", "'px'", "}", ":", "{", "left", ":", "origin", ".", "left", "-", "elLayout", ".", "left", "+", "scrollLeft", "+", "'px'", ",", "top", ":", "origin", ".", "top", "+", "elLayout", ".", "outerHeight", "+", "'px'", "}", ";", "style", ".", "width", "=", "that", ".", "$viewport", ".", "width", "(", ")", "+", "'px'", ";", "}", "else", "{", "style", "=", "that", ".", "options", ".", "floating", "?", "{", "left", ":", "elLayout", ".", "left", "+", "'px'", ",", "top", ":", "elLayout", ".", "top", "+", "elLayout", ".", "borderTop", "+", "elLayout", ".", "innerHeight", "+", "'px'", "}", ":", "{", "left", ":", "origin", ".", "left", "+", "'px'", ",", "top", ":", "origin", ".", "top", "+", "elLayout", ".", "borderTop", "+", "elLayout", ".", "innerHeight", "+", "'px'", "}", ";", "// Defer to let body show scrollbars", "utils", ".", "delay", "(", "function", "(", ")", "{", "var", "width", "=", "that", ".", "options", ".", "width", ";", "if", "(", "width", "===", "'auto'", ")", "{", "width", "=", "that", ".", "el", ".", "outerWidth", "(", ")", ";", "}", "that", ".", "$container", ".", "outerWidth", "(", "width", ")", ";", "}", ")", ";", "}", "that", ".", "$container", ".", "toggleClass", "(", "that", ".", "classes", ".", "mobile", ",", "that", ".", "isMobile", ")", ".", "css", "(", "style", ")", ";", "that", ".", "containerItemsPadding", "=", "elLayout", ".", "left", "+", "elLayout", ".", "borderLeft", "+", "elLayout", ".", "paddingLeft", "-", "scrollLeft", ";", "}" ]
Dropdown UI methods
[ "Dropdown", "UI", "methods" ]
17e3ac383790069ad4d3dd92185d9fb9e30382a7
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/container.js#L121-L160
16,995
hflabs/suggestions-jquery
src/includes/container.js
function () { var that = this; return that.suggestions.length > 1 || (that.suggestions.length === 1 && (!that.selection || $.trim(that.suggestions[0].value) !== $.trim(that.selection.value)) ); }
javascript
function () { var that = this; return that.suggestions.length > 1 || (that.suggestions.length === 1 && (!that.selection || $.trim(that.suggestions[0].value) !== $.trim(that.selection.value)) ); }
[ "function", "(", ")", "{", "var", "that", "=", "this", ";", "return", "that", ".", "suggestions", ".", "length", ">", "1", "||", "(", "that", ".", "suggestions", ".", "length", "===", "1", "&&", "(", "!", "that", ".", "selection", "||", "$", ".", "trim", "(", "that", ".", "suggestions", "[", "0", "]", ".", "value", ")", "!==", "$", ".", "trim", "(", "that", ".", "selection", ".", "value", ")", ")", ")", ";", "}" ]
Shows if there are any suggestions besides currently selected @returns {boolean}
[ "Shows", "if", "there", "are", "any", "suggestions", "besides", "currently", "selected" ]
17e3ac383790069ad4d3dd92185d9fb9e30382a7
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/container.js#L190-L197
16,996
hflabs/suggestions-jquery
src/includes/suggestions.js
function () { var that = this; that.uniqueId = utils.uniqueId('i'); that.createWrapper(); that.notify('initialize'); that.bindWindowEvents(); that.setOptions(); that.fixPosition(); }
javascript
function () { var that = this; that.uniqueId = utils.uniqueId('i'); that.createWrapper(); that.notify('initialize'); that.bindWindowEvents(); that.setOptions(); that.fixPosition(); }
[ "function", "(", ")", "{", "var", "that", "=", "this", ";", "that", ".", "uniqueId", "=", "utils", ".", "uniqueId", "(", "'i'", ")", ";", "that", ".", "createWrapper", "(", ")", ";", "that", ".", "notify", "(", "'initialize'", ")", ";", "that", ".", "bindWindowEvents", "(", ")", ";", "that", ".", "setOptions", "(", ")", ";", "that", ".", "fixPosition", "(", ")", ";", "}" ]
Creation and destruction
[ "Creation", "and", "destruction" ]
17e3ac383790069ad4d3dd92185d9fb9e30382a7
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/suggestions.js#L103-L115
16,997
hflabs/suggestions-jquery
src/includes/suggestions.js
function () { var that = this, events = 'mouseover focus keydown', timer, callback = function () { that.initializer.resolve(); that.enable(); }; that.initializer.always(function(){ that.el.off(events, callback); clearInterval(timer); }); that.disabled = true; that.el.on(events, callback); timer = setInterval(function(){ if (that.el.is(':visible')) { callback(); } }, that.options.initializeInterval); }
javascript
function () { var that = this, events = 'mouseover focus keydown', timer, callback = function () { that.initializer.resolve(); that.enable(); }; that.initializer.always(function(){ that.el.off(events, callback); clearInterval(timer); }); that.disabled = true; that.el.on(events, callback); timer = setInterval(function(){ if (that.el.is(':visible')) { callback(); } }, that.options.initializeInterval); }
[ "function", "(", ")", "{", "var", "that", "=", "this", ",", "events", "=", "'mouseover focus keydown'", ",", "timer", ",", "callback", "=", "function", "(", ")", "{", "that", ".", "initializer", ".", "resolve", "(", ")", ";", "that", ".", "enable", "(", ")", ";", "}", ";", "that", ".", "initializer", ".", "always", "(", "function", "(", ")", "{", "that", ".", "el", ".", "off", "(", "events", ",", "callback", ")", ";", "clearInterval", "(", "timer", ")", ";", "}", ")", ";", "that", ".", "disabled", "=", "true", ";", "that", ".", "el", ".", "on", "(", "events", ",", "callback", ")", ";", "timer", "=", "setInterval", "(", "function", "(", ")", "{", "if", "(", "that", ".", "el", ".", "is", "(", "':visible'", ")", ")", "{", "callback", "(", ")", ";", "}", "}", ",", "that", ".", "options", ".", "initializeInterval", ")", ";", "}" ]
Initialize when element is firstly interacted
[ "Initialize", "when", "element", "is", "firstly", "interacted" ]
17e3ac383790069ad4d3dd92185d9fb9e30382a7
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/suggestions.js#L120-L141
16,998
hflabs/suggestions-jquery
src/includes/suggestions.js
function (e) { var that = this, elLayout = {}, wrapperOffset, origin; that.isMobile = that.$viewport.width() <= that.options.mobileWidth; if (!that.isInitialized() || (e && e.type == 'scroll' && !(that.options.floating || that.isMobile))) return; that.$container.appendTo(that.options.floating ? that.$body : that.$wrapper); that.notify('resetPosition'); // reset input's padding to default, determined by css that.el.css('paddingLeft', ''); that.el.css('paddingRight', ''); elLayout.paddingLeft = parseFloat(that.el.css('paddingLeft')); elLayout.paddingRight = parseFloat(that.el.css('paddingRight')); $.extend(elLayout, that.el.offset()); elLayout.borderTop = that.el.css('border-top-style') == 'none' ? 0 : parseFloat(that.el.css('border-top-width')); elLayout.borderLeft = that.el.css('border-left-style') == 'none' ? 0 : parseFloat(that.el.css('border-left-width')); elLayout.innerHeight = that.el.innerHeight(); elLayout.innerWidth = that.el.innerWidth(); elLayout.outerHeight = that.el.outerHeight(); elLayout.componentsLeft = 0; elLayout.componentsRight = 0; wrapperOffset = that.$wrapper.offset(); origin = { top: elLayout.top - wrapperOffset.top, left: elLayout.left - wrapperOffset.left }; that.notify('fixPosition', origin, elLayout); if (elLayout.componentsLeft > elLayout.paddingLeft) { that.el.css('paddingLeft', elLayout.componentsLeft + 'px'); } if (elLayout.componentsRight > elLayout.paddingRight) { that.el.css('paddingRight', elLayout.componentsRight + 'px'); } }
javascript
function (e) { var that = this, elLayout = {}, wrapperOffset, origin; that.isMobile = that.$viewport.width() <= that.options.mobileWidth; if (!that.isInitialized() || (e && e.type == 'scroll' && !(that.options.floating || that.isMobile))) return; that.$container.appendTo(that.options.floating ? that.$body : that.$wrapper); that.notify('resetPosition'); // reset input's padding to default, determined by css that.el.css('paddingLeft', ''); that.el.css('paddingRight', ''); elLayout.paddingLeft = parseFloat(that.el.css('paddingLeft')); elLayout.paddingRight = parseFloat(that.el.css('paddingRight')); $.extend(elLayout, that.el.offset()); elLayout.borderTop = that.el.css('border-top-style') == 'none' ? 0 : parseFloat(that.el.css('border-top-width')); elLayout.borderLeft = that.el.css('border-left-style') == 'none' ? 0 : parseFloat(that.el.css('border-left-width')); elLayout.innerHeight = that.el.innerHeight(); elLayout.innerWidth = that.el.innerWidth(); elLayout.outerHeight = that.el.outerHeight(); elLayout.componentsLeft = 0; elLayout.componentsRight = 0; wrapperOffset = that.$wrapper.offset(); origin = { top: elLayout.top - wrapperOffset.top, left: elLayout.left - wrapperOffset.left }; that.notify('fixPosition', origin, elLayout); if (elLayout.componentsLeft > elLayout.paddingLeft) { that.el.css('paddingLeft', elLayout.componentsLeft + 'px'); } if (elLayout.componentsRight > elLayout.paddingRight) { that.el.css('paddingRight', elLayout.componentsRight + 'px'); } }
[ "function", "(", "e", ")", "{", "var", "that", "=", "this", ",", "elLayout", "=", "{", "}", ",", "wrapperOffset", ",", "origin", ";", "that", ".", "isMobile", "=", "that", ".", "$viewport", ".", "width", "(", ")", "<=", "that", ".", "options", ".", "mobileWidth", ";", "if", "(", "!", "that", ".", "isInitialized", "(", ")", "||", "(", "e", "&&", "e", ".", "type", "==", "'scroll'", "&&", "!", "(", "that", ".", "options", ".", "floating", "||", "that", ".", "isMobile", ")", ")", ")", "return", ";", "that", ".", "$container", ".", "appendTo", "(", "that", ".", "options", ".", "floating", "?", "that", ".", "$body", ":", "that", ".", "$wrapper", ")", ";", "that", ".", "notify", "(", "'resetPosition'", ")", ";", "// reset input's padding to default, determined by css", "that", ".", "el", ".", "css", "(", "'paddingLeft'", ",", "''", ")", ";", "that", ".", "el", ".", "css", "(", "'paddingRight'", ",", "''", ")", ";", "elLayout", ".", "paddingLeft", "=", "parseFloat", "(", "that", ".", "el", ".", "css", "(", "'paddingLeft'", ")", ")", ";", "elLayout", ".", "paddingRight", "=", "parseFloat", "(", "that", ".", "el", ".", "css", "(", "'paddingRight'", ")", ")", ";", "$", ".", "extend", "(", "elLayout", ",", "that", ".", "el", ".", "offset", "(", ")", ")", ";", "elLayout", ".", "borderTop", "=", "that", ".", "el", ".", "css", "(", "'border-top-style'", ")", "==", "'none'", "?", "0", ":", "parseFloat", "(", "that", ".", "el", ".", "css", "(", "'border-top-width'", ")", ")", ";", "elLayout", ".", "borderLeft", "=", "that", ".", "el", ".", "css", "(", "'border-left-style'", ")", "==", "'none'", "?", "0", ":", "parseFloat", "(", "that", ".", "el", ".", "css", "(", "'border-left-width'", ")", ")", ";", "elLayout", ".", "innerHeight", "=", "that", ".", "el", ".", "innerHeight", "(", ")", ";", "elLayout", ".", "innerWidth", "=", "that", ".", "el", ".", "innerWidth", "(", ")", ";", "elLayout", ".", "outerHeight", "=", "that", ".", "el", ".", "outerHeight", "(", ")", ";", "elLayout", ".", "componentsLeft", "=", "0", ";", "elLayout", ".", "componentsRight", "=", "0", ";", "wrapperOffset", "=", "that", ".", "$wrapper", ".", "offset", "(", ")", ";", "origin", "=", "{", "top", ":", "elLayout", ".", "top", "-", "wrapperOffset", ".", "top", ",", "left", ":", "elLayout", ".", "left", "-", "wrapperOffset", ".", "left", "}", ";", "that", ".", "notify", "(", "'fixPosition'", ",", "origin", ",", "elLayout", ")", ";", "if", "(", "elLayout", ".", "componentsLeft", ">", "elLayout", ".", "paddingLeft", ")", "{", "that", ".", "el", ".", "css", "(", "'paddingLeft'", ",", "elLayout", ".", "componentsLeft", "+", "'px'", ")", ";", "}", "if", "(", "elLayout", ".", "componentsRight", ">", "elLayout", ".", "paddingRight", ")", "{", "that", ".", "el", ".", "css", "(", "'paddingRight'", ",", "elLayout", ".", "componentsRight", "+", "'px'", ")", ";", "}", "}" ]
Common public methods
[ "Common", "public", "methods" ]
17e3ac383790069ad4d3dd92185d9fb9e30382a7
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/suggestions.js#L292-L333
16,999
hflabs/suggestions-jquery
src/includes/suggestions.js
function () { var that = this, fullQuery = that.extendedCurrentValue(), currentValue = that.el.val(), resolver = $.Deferred(); resolver .done(function (suggestion) { that.selectSuggestion(suggestion, 0, currentValue, { hasBeenEnriched: true }); that.el.trigger('suggestions-fixdata', suggestion); }) .fail(function () { that.selection = null; that.el.trigger('suggestions-fixdata'); }); if (that.isQueryRequestable(fullQuery)) { that.currentValue = fullQuery; that.getSuggestions(fullQuery, { count: 1, from_bound: null, to_bound: null }) .done(function (suggestions) { // data fetched var suggestion = suggestions[0]; if (suggestion) { resolver.resolve(suggestion); } else { resolver.reject(); } }) .fail(function () { // no data fetched resolver.reject(); }); } else { resolver.reject(); } }
javascript
function () { var that = this, fullQuery = that.extendedCurrentValue(), currentValue = that.el.val(), resolver = $.Deferred(); resolver .done(function (suggestion) { that.selectSuggestion(suggestion, 0, currentValue, { hasBeenEnriched: true }); that.el.trigger('suggestions-fixdata', suggestion); }) .fail(function () { that.selection = null; that.el.trigger('suggestions-fixdata'); }); if (that.isQueryRequestable(fullQuery)) { that.currentValue = fullQuery; that.getSuggestions(fullQuery, { count: 1, from_bound: null, to_bound: null }) .done(function (suggestions) { // data fetched var suggestion = suggestions[0]; if (suggestion) { resolver.resolve(suggestion); } else { resolver.reject(); } }) .fail(function () { // no data fetched resolver.reject(); }); } else { resolver.reject(); } }
[ "function", "(", ")", "{", "var", "that", "=", "this", ",", "fullQuery", "=", "that", ".", "extendedCurrentValue", "(", ")", ",", "currentValue", "=", "that", ".", "el", ".", "val", "(", ")", ",", "resolver", "=", "$", ".", "Deferred", "(", ")", ";", "resolver", ".", "done", "(", "function", "(", "suggestion", ")", "{", "that", ".", "selectSuggestion", "(", "suggestion", ",", "0", ",", "currentValue", ",", "{", "hasBeenEnriched", ":", "true", "}", ")", ";", "that", ".", "el", ".", "trigger", "(", "'suggestions-fixdata'", ",", "suggestion", ")", ";", "}", ")", ".", "fail", "(", "function", "(", ")", "{", "that", ".", "selection", "=", "null", ";", "that", ".", "el", ".", "trigger", "(", "'suggestions-fixdata'", ")", ";", "}", ")", ";", "if", "(", "that", ".", "isQueryRequestable", "(", "fullQuery", ")", ")", "{", "that", ".", "currentValue", "=", "fullQuery", ";", "that", ".", "getSuggestions", "(", "fullQuery", ",", "{", "count", ":", "1", ",", "from_bound", ":", "null", ",", "to_bound", ":", "null", "}", ")", ".", "done", "(", "function", "(", "suggestions", ")", "{", "// data fetched", "var", "suggestion", "=", "suggestions", "[", "0", "]", ";", "if", "(", "suggestion", ")", "{", "resolver", ".", "resolve", "(", "suggestion", ")", ";", "}", "else", "{", "resolver", ".", "reject", "(", ")", ";", "}", "}", ")", ".", "fail", "(", "function", "(", ")", "{", "// no data fetched", "resolver", ".", "reject", "(", ")", ";", "}", ")", ";", "}", "else", "{", "resolver", ".", "reject", "(", ")", ";", "}", "}" ]
Fetch full object for current INPUT's value if no suitable object found, clean input element
[ "Fetch", "full", "object", "for", "current", "INPUT", "s", "value", "if", "no", "suitable", "object", "found", "clean", "input", "element" ]
17e3ac383790069ad4d3dd92185d9fb9e30382a7
https://github.com/hflabs/suggestions-jquery/blob/17e3ac383790069ad4d3dd92185d9fb9e30382a7/src/includes/suggestions.js#L428-L463