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
15,300
byteball/ocore
my_witnesses.js
replaceWitness
function replaceWitness(old_witness, new_witness, handleResult){ if (!ValidationUtils.isValidAddress(new_witness)) return handleResult("new witness address is invalid"); readMyWitnesses(function(arrWitnesses){ if (arrWitnesses.indexOf(old_witness) === -1) return handleResult("old witness not known"); if (arrWitnesses.indexOf(new_witness) >= 0) return handleResult("new witness already present"); var doReplace = function(){ db.query("UPDATE my_witnesses SET address=? WHERE address=?", [new_witness, old_witness], function(){ handleResult(); }); }; if (conf.bLight) // absent the full database, there is nothing else to check return doReplace(); db.query( "SELECT 1 FROM unit_authors CROSS JOIN units USING(unit) WHERE address=? AND sequence='good' AND is_stable=1 LIMIT 1", [new_witness], function(rows){ if (rows.length === 0) return handleResult("no stable messages from the new witness yet"); storage.determineIfWitnessAddressDefinitionsHaveReferences(db, [new_witness], function(bHasReferences){ if (bHasReferences) return handleResult("address definition of the new witness has or had references"); doReplace(); }); } ); }); }
javascript
function replaceWitness(old_witness, new_witness, handleResult){ if (!ValidationUtils.isValidAddress(new_witness)) return handleResult("new witness address is invalid"); readMyWitnesses(function(arrWitnesses){ if (arrWitnesses.indexOf(old_witness) === -1) return handleResult("old witness not known"); if (arrWitnesses.indexOf(new_witness) >= 0) return handleResult("new witness already present"); var doReplace = function(){ db.query("UPDATE my_witnesses SET address=? WHERE address=?", [new_witness, old_witness], function(){ handleResult(); }); }; if (conf.bLight) // absent the full database, there is nothing else to check return doReplace(); db.query( "SELECT 1 FROM unit_authors CROSS JOIN units USING(unit) WHERE address=? AND sequence='good' AND is_stable=1 LIMIT 1", [new_witness], function(rows){ if (rows.length === 0) return handleResult("no stable messages from the new witness yet"); storage.determineIfWitnessAddressDefinitionsHaveReferences(db, [new_witness], function(bHasReferences){ if (bHasReferences) return handleResult("address definition of the new witness has or had references"); doReplace(); }); } ); }); }
[ "function", "replaceWitness", "(", "old_witness", ",", "new_witness", ",", "handleResult", ")", "{", "if", "(", "!", "ValidationUtils", ".", "isValidAddress", "(", "new_witness", ")", ")", "return", "handleResult", "(", "\"new witness address is invalid\"", ")", ";", "readMyWitnesses", "(", "function", "(", "arrWitnesses", ")", "{", "if", "(", "arrWitnesses", ".", "indexOf", "(", "old_witness", ")", "===", "-", "1", ")", "return", "handleResult", "(", "\"old witness not known\"", ")", ";", "if", "(", "arrWitnesses", ".", "indexOf", "(", "new_witness", ")", ">=", "0", ")", "return", "handleResult", "(", "\"new witness already present\"", ")", ";", "var", "doReplace", "=", "function", "(", ")", "{", "db", ".", "query", "(", "\"UPDATE my_witnesses SET address=? WHERE address=?\"", ",", "[", "new_witness", ",", "old_witness", "]", ",", "function", "(", ")", "{", "handleResult", "(", ")", ";", "}", ")", ";", "}", ";", "if", "(", "conf", ".", "bLight", ")", "// absent the full database, there is nothing else to check", "return", "doReplace", "(", ")", ";", "db", ".", "query", "(", "\"SELECT 1 FROM unit_authors CROSS JOIN units USING(unit) WHERE address=? AND sequence='good' AND is_stable=1 LIMIT 1\"", ",", "[", "new_witness", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "return", "handleResult", "(", "\"no stable messages from the new witness yet\"", ")", ";", "storage", ".", "determineIfWitnessAddressDefinitionsHaveReferences", "(", "db", ",", "[", "new_witness", "]", ",", "function", "(", "bHasReferences", ")", "{", "if", "(", "bHasReferences", ")", "return", "handleResult", "(", "\"address definition of the new witness has or had references\"", ")", ";", "doReplace", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
replaces old_witness with new_witness
[ "replaces", "old_witness", "with", "new_witness" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/my_witnesses.js#L38-L67
15,301
byteball/ocore
wallet.js
sendSignature
function sendSignature(device_address, signed_text, signature, signing_path, address){ device.sendMessageToDevice(device_address, "signature", {signed_text: signed_text, signature: signature, signing_path: signing_path, address: address}); }
javascript
function sendSignature(device_address, signed_text, signature, signing_path, address){ device.sendMessageToDevice(device_address, "signature", {signed_text: signed_text, signature: signature, signing_path: signing_path, address: address}); }
[ "function", "sendSignature", "(", "device_address", ",", "signed_text", ",", "signature", ",", "signing_path", ",", "address", ")", "{", "device", ".", "sendMessageToDevice", "(", "device_address", ",", "\"signature\"", ",", "{", "signed_text", ":", "signed_text", ",", "signature", ":", "signature", ",", "signing_path", ":", "signing_path", ",", "address", ":", "address", "}", ")", ";", "}" ]
called from UI after user confirms signing request initiated from another device, initiator device being the recipient of this message
[ "called", "from", "UI", "after", "user", "confirms", "signing", "request", "initiated", "from", "another", "device", "initiator", "device", "being", "the", "recipient", "of", "this", "message" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet.js#L147-L149
15,302
byteball/ocore
wallet.js
function(){ console.log("handleOnlinePrivatePayment queued, will wait for "+key); eventBus.once(key, function(bValid){ if (!bValid) return cancelAllKeys(); assocValidatedByKey[key] = true; if (bParsingComplete) checkIfAllValidated(); else console.log('parsing incomplete yet'); }); cb(); }
javascript
function(){ console.log("handleOnlinePrivatePayment queued, will wait for "+key); eventBus.once(key, function(bValid){ if (!bValid) return cancelAllKeys(); assocValidatedByKey[key] = true; if (bParsingComplete) checkIfAllValidated(); else console.log('parsing incomplete yet'); }); cb(); }
[ "function", "(", ")", "{", "console", ".", "log", "(", "\"handleOnlinePrivatePayment queued, will wait for \"", "+", "key", ")", ";", "eventBus", ".", "once", "(", "key", ",", "function", "(", "bValid", ")", "{", "if", "(", "!", "bValid", ")", "return", "cancelAllKeys", "(", ")", ";", "assocValidatedByKey", "[", "key", "]", "=", "true", ";", "if", "(", "bParsingComplete", ")", "checkIfAllValidated", "(", ")", ";", "else", "console", ".", "log", "(", "'parsing incomplete yet'", ")", ";", "}", ")", ";", "cb", "(", ")", ";", "}" ]
this is the most likely outcome for light clients
[ "this", "is", "the", "most", "likely", "outcome", "for", "light", "clients" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet.js#L670-L682
15,303
byteball/ocore
wallet.js
readFundedAndSigningAddresses
function readFundedAndSigningAddresses( asset, wallet, estimated_amount, spend_unconfirmed, fee_paying_wallet, arrSigningAddresses, arrSigningDeviceAddresses, handleFundedAndSigningAddresses) { readFundedAddresses(asset, wallet, estimated_amount, spend_unconfirmed, function(arrFundedAddresses){ if (arrFundedAddresses.length === 0) return handleFundedAndSigningAddresses([], [], []); var arrBaseFundedAddresses = []; var addSigningAddressesAndReturn = function(){ var arrPayingAddresses = _.union(arrFundedAddresses, arrBaseFundedAddresses); readAdditionalSigningAddresses(arrPayingAddresses, arrSigningAddresses, arrSigningDeviceAddresses, function(arrAdditionalAddresses){ handleFundedAndSigningAddresses(arrFundedAddresses, arrBaseFundedAddresses, arrSigningAddresses.concat(arrAdditionalAddresses)); }); }; if (!asset) return addSigningAddressesAndReturn(); readFundedAddresses(null, wallet, TYPICAL_FEE, spend_unconfirmed, function(_arrBaseFundedAddresses){ // fees will be paid from the same addresses as the asset if (_arrBaseFundedAddresses.length > 0 || !fee_paying_wallet || fee_paying_wallet === wallet){ arrBaseFundedAddresses = _arrBaseFundedAddresses; return addSigningAddressesAndReturn(); } readFundedAddresses(null, fee_paying_wallet, TYPICAL_FEE, spend_unconfirmed, function(_arrBaseFundedAddresses){ arrBaseFundedAddresses = _arrBaseFundedAddresses; addSigningAddressesAndReturn(); }); }); }); }
javascript
function readFundedAndSigningAddresses( asset, wallet, estimated_amount, spend_unconfirmed, fee_paying_wallet, arrSigningAddresses, arrSigningDeviceAddresses, handleFundedAndSigningAddresses) { readFundedAddresses(asset, wallet, estimated_amount, spend_unconfirmed, function(arrFundedAddresses){ if (arrFundedAddresses.length === 0) return handleFundedAndSigningAddresses([], [], []); var arrBaseFundedAddresses = []; var addSigningAddressesAndReturn = function(){ var arrPayingAddresses = _.union(arrFundedAddresses, arrBaseFundedAddresses); readAdditionalSigningAddresses(arrPayingAddresses, arrSigningAddresses, arrSigningDeviceAddresses, function(arrAdditionalAddresses){ handleFundedAndSigningAddresses(arrFundedAddresses, arrBaseFundedAddresses, arrSigningAddresses.concat(arrAdditionalAddresses)); }); }; if (!asset) return addSigningAddressesAndReturn(); readFundedAddresses(null, wallet, TYPICAL_FEE, spend_unconfirmed, function(_arrBaseFundedAddresses){ // fees will be paid from the same addresses as the asset if (_arrBaseFundedAddresses.length > 0 || !fee_paying_wallet || fee_paying_wallet === wallet){ arrBaseFundedAddresses = _arrBaseFundedAddresses; return addSigningAddressesAndReturn(); } readFundedAddresses(null, fee_paying_wallet, TYPICAL_FEE, spend_unconfirmed, function(_arrBaseFundedAddresses){ arrBaseFundedAddresses = _arrBaseFundedAddresses; addSigningAddressesAndReturn(); }); }); }); }
[ "function", "readFundedAndSigningAddresses", "(", "asset", ",", "wallet", ",", "estimated_amount", ",", "spend_unconfirmed", ",", "fee_paying_wallet", ",", "arrSigningAddresses", ",", "arrSigningDeviceAddresses", ",", "handleFundedAndSigningAddresses", ")", "{", "readFundedAddresses", "(", "asset", ",", "wallet", ",", "estimated_amount", ",", "spend_unconfirmed", ",", "function", "(", "arrFundedAddresses", ")", "{", "if", "(", "arrFundedAddresses", ".", "length", "===", "0", ")", "return", "handleFundedAndSigningAddresses", "(", "[", "]", ",", "[", "]", ",", "[", "]", ")", ";", "var", "arrBaseFundedAddresses", "=", "[", "]", ";", "var", "addSigningAddressesAndReturn", "=", "function", "(", ")", "{", "var", "arrPayingAddresses", "=", "_", ".", "union", "(", "arrFundedAddresses", ",", "arrBaseFundedAddresses", ")", ";", "readAdditionalSigningAddresses", "(", "arrPayingAddresses", ",", "arrSigningAddresses", ",", "arrSigningDeviceAddresses", ",", "function", "(", "arrAdditionalAddresses", ")", "{", "handleFundedAndSigningAddresses", "(", "arrFundedAddresses", ",", "arrBaseFundedAddresses", ",", "arrSigningAddresses", ".", "concat", "(", "arrAdditionalAddresses", ")", ")", ";", "}", ")", ";", "}", ";", "if", "(", "!", "asset", ")", "return", "addSigningAddressesAndReturn", "(", ")", ";", "readFundedAddresses", "(", "null", ",", "wallet", ",", "TYPICAL_FEE", ",", "spend_unconfirmed", ",", "function", "(", "_arrBaseFundedAddresses", ")", "{", "// fees will be paid from the same addresses as the asset", "if", "(", "_arrBaseFundedAddresses", ".", "length", ">", "0", "||", "!", "fee_paying_wallet", "||", "fee_paying_wallet", "===", "wallet", ")", "{", "arrBaseFundedAddresses", "=", "_arrBaseFundedAddresses", ";", "return", "addSigningAddressesAndReturn", "(", ")", ";", "}", "readFundedAddresses", "(", "null", ",", "fee_paying_wallet", ",", "TYPICAL_FEE", ",", "spend_unconfirmed", ",", "function", "(", "_arrBaseFundedAddresses", ")", "{", "arrBaseFundedAddresses", "=", "_arrBaseFundedAddresses", ";", "addSigningAddressesAndReturn", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
fee_paying_wallet is used only if there are no bytes on the asset wallet, it is a sort of fallback wallet for fees
[ "fee_paying_wallet", "is", "used", "only", "if", "there", "are", "no", "bytes", "on", "the", "asset", "wallet", "it", "is", "a", "sort", "of", "fallback", "wallet", "for", "fees" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet.js#L1401-L1429
15,304
byteball/ocore
wallet.js
checkStability
function checkStability() { db.query( "SELECT is_stable, asset, SUM(amount) AS `amount` \n\ FROM outputs JOIN units USING(unit) WHERE address=? AND sequence='good' AND is_spent=0 GROUP BY asset ORDER BY asset DESC LIMIT 1", [addrInfo.address], function(rows){ if (rows.length === 0) { cb("This textcoin either was already claimed or never existed in the network"); } else { var row = rows[0]; if (false && !row.is_stable) { cb("This payment is not confirmed yet, try again later"); } else { if (row.asset) { // claiming asset opts.asset = row.asset; opts.amount = row.amount; opts.fee_paying_addresses = [addrInfo.address]; storage.readAsset(db, row.asset, null, function(err, objAsset){ if (err && err.indexOf("not found" !== -1)) { if (!conf.bLight) // full wallets must have this asset throw Error("textcoin asset "+row.asset+" not found"); return network.requestHistoryFor([opts.asset], [], checkStability); } asset = opts.asset; opts.to_address = addressTo; if (objAsset.fixed_denominations){ // indivisible opts.tolerance_plus = 0; opts.tolerance_minus = 0; indivisibleAsset.composeAndSaveIndivisibleAssetPaymentJoint(opts); } else{ // divisible divisibleAsset.composeAndSaveDivisibleAssetPaymentJoint(opts); } }); } else {// claiming bytes opts.send_all = true; opts.outputs = [{address: addressTo, amount: 0}]; opts.callbacks = composer.getSavingCallbacks(opts.callbacks); composer.composeJoint(opts); } } } } ); }
javascript
function checkStability() { db.query( "SELECT is_stable, asset, SUM(amount) AS `amount` \n\ FROM outputs JOIN units USING(unit) WHERE address=? AND sequence='good' AND is_spent=0 GROUP BY asset ORDER BY asset DESC LIMIT 1", [addrInfo.address], function(rows){ if (rows.length === 0) { cb("This textcoin either was already claimed or never existed in the network"); } else { var row = rows[0]; if (false && !row.is_stable) { cb("This payment is not confirmed yet, try again later"); } else { if (row.asset) { // claiming asset opts.asset = row.asset; opts.amount = row.amount; opts.fee_paying_addresses = [addrInfo.address]; storage.readAsset(db, row.asset, null, function(err, objAsset){ if (err && err.indexOf("not found" !== -1)) { if (!conf.bLight) // full wallets must have this asset throw Error("textcoin asset "+row.asset+" not found"); return network.requestHistoryFor([opts.asset], [], checkStability); } asset = opts.asset; opts.to_address = addressTo; if (objAsset.fixed_denominations){ // indivisible opts.tolerance_plus = 0; opts.tolerance_minus = 0; indivisibleAsset.composeAndSaveIndivisibleAssetPaymentJoint(opts); } else{ // divisible divisibleAsset.composeAndSaveDivisibleAssetPaymentJoint(opts); } }); } else {// claiming bytes opts.send_all = true; opts.outputs = [{address: addressTo, amount: 0}]; opts.callbacks = composer.getSavingCallbacks(opts.callbacks); composer.composeJoint(opts); } } } } ); }
[ "function", "checkStability", "(", ")", "{", "db", ".", "query", "(", "\"SELECT is_stable, asset, SUM(amount) AS `amount` \\n\\\n\t\t\tFROM outputs JOIN units USING(unit) WHERE address=? AND sequence='good' AND is_spent=0 GROUP BY asset ORDER BY asset DESC LIMIT 1\"", ",", "[", "addrInfo", ".", "address", "]", ",", "function", "(", "rows", ")", "{", "if", "(", "rows", ".", "length", "===", "0", ")", "{", "cb", "(", "\"This textcoin either was already claimed or never existed in the network\"", ")", ";", "}", "else", "{", "var", "row", "=", "rows", "[", "0", "]", ";", "if", "(", "false", "&&", "!", "row", ".", "is_stable", ")", "{", "cb", "(", "\"This payment is not confirmed yet, try again later\"", ")", ";", "}", "else", "{", "if", "(", "row", ".", "asset", ")", "{", "// claiming asset", "opts", ".", "asset", "=", "row", ".", "asset", ";", "opts", ".", "amount", "=", "row", ".", "amount", ";", "opts", ".", "fee_paying_addresses", "=", "[", "addrInfo", ".", "address", "]", ";", "storage", ".", "readAsset", "(", "db", ",", "row", ".", "asset", ",", "null", ",", "function", "(", "err", ",", "objAsset", ")", "{", "if", "(", "err", "&&", "err", ".", "indexOf", "(", "\"not found\"", "!==", "-", "1", ")", ")", "{", "if", "(", "!", "conf", ".", "bLight", ")", "// full wallets must have this asset", "throw", "Error", "(", "\"textcoin asset \"", "+", "row", ".", "asset", "+", "\" not found\"", ")", ";", "return", "network", ".", "requestHistoryFor", "(", "[", "opts", ".", "asset", "]", ",", "[", "]", ",", "checkStability", ")", ";", "}", "asset", "=", "opts", ".", "asset", ";", "opts", ".", "to_address", "=", "addressTo", ";", "if", "(", "objAsset", ".", "fixed_denominations", ")", "{", "// indivisible", "opts", ".", "tolerance_plus", "=", "0", ";", "opts", ".", "tolerance_minus", "=", "0", ";", "indivisibleAsset", ".", "composeAndSaveIndivisibleAssetPaymentJoint", "(", "opts", ")", ";", "}", "else", "{", "// divisible", "divisibleAsset", ".", "composeAndSaveDivisibleAssetPaymentJoint", "(", "opts", ")", ";", "}", "}", ")", ";", "}", "else", "{", "// claiming bytes", "opts", ".", "send_all", "=", "true", ";", "opts", ".", "outputs", "=", "[", "{", "address", ":", "addressTo", ",", "amount", ":", "0", "}", "]", ";", "opts", ".", "callbacks", "=", "composer", ".", "getSavingCallbacks", "(", "opts", ".", "callbacks", ")", ";", "composer", ".", "composeJoint", "(", "opts", ")", ";", "}", "}", "}", "}", ")", ";", "}" ]
check stability of payingAddresses
[ "check", "stability", "of", "payingAddresses" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet.js#L2031-L2075
15,305
byteball/ocore
wallet.js
claimBackOldTextcoins
function claimBackOldTextcoins(to_address, days){ db.query( "SELECT mnemonic FROM sent_mnemonics LEFT JOIN unit_authors USING(address) \n\ WHERE mnemonic!='' AND unit_authors.address IS NULL AND creation_date<"+db.addTime("-"+days+" DAYS"), function(rows){ async.eachSeries( rows, function(row, cb){ receiveTextCoin(row.mnemonic, to_address, function(err, unit, asset){ if (err) console.log("failed claiming back old textcoin "+row.mnemonic+": "+err); else console.log("claimed back mnemonic "+row.mnemonic+", unit "+unit+", asset "+asset); cb(); }); } ); } ); }
javascript
function claimBackOldTextcoins(to_address, days){ db.query( "SELECT mnemonic FROM sent_mnemonics LEFT JOIN unit_authors USING(address) \n\ WHERE mnemonic!='' AND unit_authors.address IS NULL AND creation_date<"+db.addTime("-"+days+" DAYS"), function(rows){ async.eachSeries( rows, function(row, cb){ receiveTextCoin(row.mnemonic, to_address, function(err, unit, asset){ if (err) console.log("failed claiming back old textcoin "+row.mnemonic+": "+err); else console.log("claimed back mnemonic "+row.mnemonic+", unit "+unit+", asset "+asset); cb(); }); } ); } ); }
[ "function", "claimBackOldTextcoins", "(", "to_address", ",", "days", ")", "{", "db", ".", "query", "(", "\"SELECT mnemonic FROM sent_mnemonics LEFT JOIN unit_authors USING(address) \\n\\\n\t\tWHERE mnemonic!='' AND unit_authors.address IS NULL AND creation_date<\"", "+", "db", ".", "addTime", "(", "\"-\"", "+", "days", "+", "\" DAYS\"", ")", ",", "function", "(", "rows", ")", "{", "async", ".", "eachSeries", "(", "rows", ",", "function", "(", "row", ",", "cb", ")", "{", "receiveTextCoin", "(", "row", ".", "mnemonic", ",", "to_address", ",", "function", "(", "err", ",", "unit", ",", "asset", ")", "{", "if", "(", "err", ")", "console", ".", "log", "(", "\"failed claiming back old textcoin \"", "+", "row", ".", "mnemonic", "+", "\": \"", "+", "err", ")", ";", "else", "console", ".", "log", "(", "\"claimed back mnemonic \"", "+", "row", ".", "mnemonic", "+", "\", unit \"", "+", "unit", "+", "\", asset \"", "+", "asset", ")", ";", "cb", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
if a textcoin was not claimed for 'days' days, claims it back
[ "if", "a", "textcoin", "was", "not", "claimed", "for", "days", "days", "claims", "it", "back" ]
17e82e31517d62c456c04d898423dc9ab01d96a6
https://github.com/byteball/ocore/blob/17e82e31517d62c456c04d898423dc9ab01d96a6/wallet.js#L2079-L2098
15,306
googleapis/cloud-profiler-nodejs
proto/profiler.js
CreateProfileRequest
function CreateProfileRequest(properties) { this.profileType = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function CreateProfileRequest(properties) { this.profileType = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "CreateProfileRequest", "(", "properties", ")", "{", "this", ".", "profileType", "=", "[", "]", ";", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a CreateProfileRequest. @memberof google.devtools.cloudprofiler.v2 @interface ICreateProfileRequest @property {google.devtools.cloudprofiler.v2.IDeployment} [deployment] CreateProfileRequest deployment @property {Array.<google.devtools.cloudprofiler.v2.ProfileType>} [profileType] CreateProfileRequest profileType @property {google.devtools.cloudprofiler.v2.IProfile} [profile] CreateProfileRequest profile Constructs a new CreateProfileRequest. @memberof google.devtools.cloudprofiler.v2 @classdesc Represents a CreateProfileRequest. @constructor @param {google.devtools.cloudprofiler.v2.ICreateProfileRequest=} [properties] Properties to set
[ "Properties", "of", "a", "CreateProfileRequest", "." ]
59429e72b51e655e9524c274c442824810907d0b
https://github.com/googleapis/cloud-profiler-nodejs/blob/59429e72b51e655e9524c274c442824810907d0b/proto/profiler.js#L167-L173
15,307
googleapis/cloud-profiler-nodejs
proto/profiler.js
UpdateProfileRequest
function UpdateProfileRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function UpdateProfileRequest(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "UpdateProfileRequest", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of an UpdateProfileRequest. @memberof google.devtools.cloudprofiler.v2 @interface IUpdateProfileRequest @property {google.devtools.cloudprofiler.v2.IProfile} [profile] UpdateProfileRequest profile Constructs a new UpdateProfileRequest. @memberof google.devtools.cloudprofiler.v2 @classdesc Represents an UpdateProfileRequest. @constructor @param {google.devtools.cloudprofiler.v2.IUpdateProfileRequest=} [properties] Properties to set
[ "Properties", "of", "an", "UpdateProfileRequest", "." ]
59429e72b51e655e9524c274c442824810907d0b
https://github.com/googleapis/cloud-profiler-nodejs/blob/59429e72b51e655e9524c274c442824810907d0b/proto/profiler.js#L466-L471
15,308
googleapis/cloud-profiler-nodejs
proto/profiler.js
Deployment
function Deployment(properties) { this.labels = {}; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Deployment(properties) { this.labels = {}; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Deployment", "(", "properties", ")", "{", "this", ".", "labels", "=", "{", "}", ";", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Deployment. @memberof google.devtools.cloudprofiler.v2 @interface IDeployment @property {string} [projectId] Deployment projectId @property {string} [target] Deployment target @property {Object.<string,string>} [labels] Deployment labels Constructs a new Deployment. @memberof google.devtools.cloudprofiler.v2 @classdesc Represents a Deployment. @constructor @param {google.devtools.cloudprofiler.v2.IDeployment=} [properties] Properties to set
[ "Properties", "of", "a", "Deployment", "." ]
59429e72b51e655e9524c274c442824810907d0b
https://github.com/googleapis/cloud-profiler-nodejs/blob/59429e72b51e655e9524c274c442824810907d0b/proto/profiler.js#L1024-L1030
15,309
googleapis/cloud-profiler-nodejs
proto/profile.js
ValueType
function ValueType(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function ValueType(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "ValueType", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a ValueType. @memberof perftools.profiles @interface IValueType @property {number|Long} [type] ValueType type @property {number|Long} [unit] ValueType unit Constructs a new ValueType. @memberof perftools.profiles @classdesc Represents a ValueType. @constructor @param {perftools.profiles.IValueType=} [properties] Properties to set
[ "Properties", "of", "a", "ValueType", "." ]
59429e72b51e655e9524c274c442824810907d0b
https://github.com/googleapis/cloud-profiler-nodejs/blob/59429e72b51e655e9524c274c442824810907d0b/proto/profile.js#L766-L771
15,310
googleapis/cloud-profiler-nodejs
proto/profile.js
Sample
function Sample(properties) { this.locationId = []; this.value = []; this.label = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Sample(properties) { this.locationId = []; this.value = []; this.label = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Sample", "(", "properties", ")", "{", "this", ".", "locationId", "=", "[", "]", ";", "this", ".", "value", "=", "[", "]", ";", "this", ".", "label", "=", "[", "]", ";", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Sample. @memberof perftools.profiles @interface ISample @property {Array.<number|Long>} [locationId] Sample locationId @property {Array.<number|Long>} [value] Sample value @property {Array.<perftools.profiles.ILabel>} [label] Sample label Constructs a new Sample. @memberof perftools.profiles @classdesc Represents a Sample. @constructor @param {perftools.profiles.ISample=} [properties] Properties to set
[ "Properties", "of", "a", "Sample", "." ]
59429e72b51e655e9524c274c442824810907d0b
https://github.com/googleapis/cloud-profiler-nodejs/blob/59429e72b51e655e9524c274c442824810907d0b/proto/profile.js#L1004-L1012
15,311
googleapis/cloud-profiler-nodejs
proto/profile.js
Label
function Label(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Label(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Label", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Label. @memberof perftools.profiles @interface ILabel @property {number|Long} [key] Label key @property {number|Long} [str] Label str @property {number|Long} [num] Label num @property {number|Long} [numUnit] Label numUnit Constructs a new Label. @memberof perftools.profiles @classdesc Represents a Label. @constructor @param {perftools.profiles.ILabel=} [properties] Properties to set
[ "Properties", "of", "a", "Label", "." ]
59429e72b51e655e9524c274c442824810907d0b
https://github.com/googleapis/cloud-profiler-nodejs/blob/59429e72b51e655e9524c274c442824810907d0b/proto/profile.js#L1325-L1330
15,312
googleapis/cloud-profiler-nodejs
proto/profile.js
Mapping
function Mapping(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Mapping(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Mapping", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Mapping. @memberof perftools.profiles @interface IMapping @property {number|Long} [id] Mapping id @property {number|Long} [memoryStart] Mapping memoryStart @property {number|Long} [memoryLimit] Mapping memoryLimit @property {number|Long} [fileOffset] Mapping fileOffset @property {number|Long} [filename] Mapping filename @property {number|Long} [buildId] Mapping buildId @property {boolean} [hasFunctions] Mapping hasFunctions @property {boolean} [hasFilenames] Mapping hasFilenames @property {boolean} [hasLineNumbers] Mapping hasLineNumbers @property {boolean} [hasInlineFrames] Mapping hasInlineFrames Constructs a new Mapping. @memberof perftools.profiles @classdesc Represents a Mapping. @constructor @param {perftools.profiles.IMapping=} [properties] Properties to set
[ "Properties", "of", "a", "Mapping", "." ]
59429e72b51e655e9524c274c442824810907d0b
https://github.com/googleapis/cloud-profiler-nodejs/blob/59429e72b51e655e9524c274c442824810907d0b/proto/profile.js#L1640-L1645
15,313
googleapis/cloud-profiler-nodejs
proto/profile.js
Line
function Line(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Line(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Line", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Line. @memberof perftools.profiles @interface ILine @property {number|Long} [functionId] Line functionId @property {number|Long} [line] Line line Constructs a new Line. @memberof perftools.profiles @classdesc Represents a Line. @constructor @param {perftools.profiles.ILine=} [properties] Properties to set
[ "Properties", "of", "a", "Line", "." ]
59429e72b51e655e9524c274c442824810907d0b
https://github.com/googleapis/cloud-profiler-nodejs/blob/59429e72b51e655e9524c274c442824810907d0b/proto/profile.js#L2418-L2423
15,314
googleapis/cloud-profiler-nodejs
proto/profile.js
Function
function Function(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Function(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Function", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Function. @memberof perftools.profiles @interface IFunction @property {number|Long} [id] Function id @property {number|Long} [name] Function name @property {number|Long} [systemName] Function systemName @property {number|Long} [filename] Function filename @property {number|Long} [startLine] Function startLine Constructs a new Function. @memberof perftools.profiles @classdesc Represents a Function. @constructor @param {perftools.profiles.IFunction=} [properties] Properties to set
[ "Properties", "of", "a", "Function", "." ]
59429e72b51e655e9524c274c442824810907d0b
https://github.com/googleapis/cloud-profiler-nodejs/blob/59429e72b51e655e9524c274c442824810907d0b/proto/profile.js#L2658-L2663
15,315
node-modules/agentkeepalive
lib/agent.js
onTimeout
function onTimeout() { const listenerCount = socket.listeners('timeout').length; debug('%s(requests: %s, finished: %s) timeout after %sms, listeners %s', socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], getSocketTimeout(socket), listenerCount); agent.timeoutSocketCount++; const name = agent.getName(options); if (agent.freeSockets[name] && agent.freeSockets[name].indexOf(socket) !== -1) { // free socket timeout, destroy quietly socket.destroy(); // Remove it from freeSockets list immediately to prevent new requests // from being sent through this socket. agent.removeSocket(socket, options); debug('%s is free, destroy quietly', socket[SOCKET_NAME]); } else { // if there is no any request socket timeout handler, // agent need to handle socket timeout itself. // // custom request socket timeout handle logic must follow these rules: // 1. Destroy socket first // 2. Must emit socket 'agentRemove' event tell agent remove socket // from freeSockets list immediately. // Otherise you may be get 'socket hang up' error when reuse // free socket and timeout happen in the same time. if (listenerCount === 1) { const error = new Error('Socket timeout'); error.code = 'ERR_SOCKET_TIMEOUT'; error.timeout = getSocketTimeout(socket); // must manually call socket.end() or socket.destroy() to end the connection. // https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback socket.destroy(error); agent.removeSocket(socket, options); debug('%s destroy with timeout error', socket[SOCKET_NAME]); } } }
javascript
function onTimeout() { const listenerCount = socket.listeners('timeout').length; debug('%s(requests: %s, finished: %s) timeout after %sms, listeners %s', socket[SOCKET_NAME], socket[SOCKET_REQUEST_COUNT], socket[SOCKET_REQUEST_FINISHED_COUNT], getSocketTimeout(socket), listenerCount); agent.timeoutSocketCount++; const name = agent.getName(options); if (agent.freeSockets[name] && agent.freeSockets[name].indexOf(socket) !== -1) { // free socket timeout, destroy quietly socket.destroy(); // Remove it from freeSockets list immediately to prevent new requests // from being sent through this socket. agent.removeSocket(socket, options); debug('%s is free, destroy quietly', socket[SOCKET_NAME]); } else { // if there is no any request socket timeout handler, // agent need to handle socket timeout itself. // // custom request socket timeout handle logic must follow these rules: // 1. Destroy socket first // 2. Must emit socket 'agentRemove' event tell agent remove socket // from freeSockets list immediately. // Otherise you may be get 'socket hang up' error when reuse // free socket and timeout happen in the same time. if (listenerCount === 1) { const error = new Error('Socket timeout'); error.code = 'ERR_SOCKET_TIMEOUT'; error.timeout = getSocketTimeout(socket); // must manually call socket.end() or socket.destroy() to end the connection. // https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback socket.destroy(error); agent.removeSocket(socket, options); debug('%s destroy with timeout error', socket[SOCKET_NAME]); } } }
[ "function", "onTimeout", "(", ")", "{", "const", "listenerCount", "=", "socket", ".", "listeners", "(", "'timeout'", ")", ".", "length", ";", "debug", "(", "'%s(requests: %s, finished: %s) timeout after %sms, listeners %s'", ",", "socket", "[", "SOCKET_NAME", "]", ",", "socket", "[", "SOCKET_REQUEST_COUNT", "]", ",", "socket", "[", "SOCKET_REQUEST_FINISHED_COUNT", "]", ",", "getSocketTimeout", "(", "socket", ")", ",", "listenerCount", ")", ";", "agent", ".", "timeoutSocketCount", "++", ";", "const", "name", "=", "agent", ".", "getName", "(", "options", ")", ";", "if", "(", "agent", ".", "freeSockets", "[", "name", "]", "&&", "agent", ".", "freeSockets", "[", "name", "]", ".", "indexOf", "(", "socket", ")", "!==", "-", "1", ")", "{", "// free socket timeout, destroy quietly", "socket", ".", "destroy", "(", ")", ";", "// Remove it from freeSockets list immediately to prevent new requests", "// from being sent through this socket.", "agent", ".", "removeSocket", "(", "socket", ",", "options", ")", ";", "debug", "(", "'%s is free, destroy quietly'", ",", "socket", "[", "SOCKET_NAME", "]", ")", ";", "}", "else", "{", "// if there is no any request socket timeout handler,", "// agent need to handle socket timeout itself.", "//", "// custom request socket timeout handle logic must follow these rules:", "// 1. Destroy socket first", "// 2. Must emit socket 'agentRemove' event tell agent remove socket", "// from freeSockets list immediately.", "// Otherise you may be get 'socket hang up' error when reuse", "// free socket and timeout happen in the same time.", "if", "(", "listenerCount", "===", "1", ")", "{", "const", "error", "=", "new", "Error", "(", "'Socket timeout'", ")", ";", "error", ".", "code", "=", "'ERR_SOCKET_TIMEOUT'", ";", "error", ".", "timeout", "=", "getSocketTimeout", "(", "socket", ")", ";", "// must manually call socket.end() or socket.destroy() to end the connection.", "// https://nodejs.org/dist/latest-v10.x/docs/api/net.html#net_socket_settimeout_timeout_callback", "socket", ".", "destroy", "(", "error", ")", ";", "agent", ".", "removeSocket", "(", "socket", ",", "options", ")", ";", "debug", "(", "'%s destroy with timeout error'", ",", "socket", "[", "SOCKET_NAME", "]", ")", ";", "}", "}", "}" ]
start socket timeout handler
[ "start", "socket", "timeout", "handler" ]
48e01a4d3e15888d396d2a45305d976f654afdb7
https://github.com/node-modules/agentkeepalive/blob/48e01a4d3e15888d396d2a45305d976f654afdb7/lib/agent.js#L279-L314
15,316
avh4/elm-format
parser/bench/src/Native/Benchmark.js
runWithProgress
function runWithProgress(maybeTaskFn, inSuite) { return Task.asyncFunction(function(callback) { var bjsSuite = new Benchmark.Suite; var benchArray; var retData = []; var finalString = ""; var numCompleted = 0; var numToRun; switch (inSuite.ctor) { case "Suite": benchArray = List.toArray(inSuite._1); break; case "SingleBenchmark": benchArray = [inSuite._0 ]; break; } numToRun = benchArray.length; Task.perform(maybeTaskFn("Running benchmark 1 of " + numToRun)); //Initialize each benchmark in the suite for (i = 0; i < benchArray.length; i++) { var ourThunk = function (){ //Run the thing we're timing, then mark the asynch benchmark as done benchArray[i].thunk(); deferred.resolve(); } bjsSuite.add(benchArray[i].name, benchArray[i].thunk ); } //Every time a benchmark finishes, we store its results //and update our progress string bjsSuite.on('cycle', function(event) { numCompleted += 1; retData.push( { name : event.target.options.name , hz : event.target.hz , marginOfError : event.target.stats.moe , moePercent : event.target.stats.rme } ); finalString += String(event.target) + "\n"; var intermedString = "Running benchmark " + (numCompleted + 1) + " of " + numToRun + "\nLast result: " + String(event.target); Task.perform(maybeTaskFn(intermedString)); //retString += String(event.target) + "\n"; }); //When the last benchmark finishes, we show all results collected bjsSuite.on('complete', function(event) { Task.perform(maybeTaskFn("Final results:\n\n" + finalString) ); return callback(Task.succeed(Utils.Tuple2(finalString, List.fromArray(retData)))); }); //Finally: actually run the suite Task.perform( Task.asyncFunction(function(otherCallback){ bjsSuite.run({ 'async': true }); })); }); }
javascript
function runWithProgress(maybeTaskFn, inSuite) { return Task.asyncFunction(function(callback) { var bjsSuite = new Benchmark.Suite; var benchArray; var retData = []; var finalString = ""; var numCompleted = 0; var numToRun; switch (inSuite.ctor) { case "Suite": benchArray = List.toArray(inSuite._1); break; case "SingleBenchmark": benchArray = [inSuite._0 ]; break; } numToRun = benchArray.length; Task.perform(maybeTaskFn("Running benchmark 1 of " + numToRun)); //Initialize each benchmark in the suite for (i = 0; i < benchArray.length; i++) { var ourThunk = function (){ //Run the thing we're timing, then mark the asynch benchmark as done benchArray[i].thunk(); deferred.resolve(); } bjsSuite.add(benchArray[i].name, benchArray[i].thunk ); } //Every time a benchmark finishes, we store its results //and update our progress string bjsSuite.on('cycle', function(event) { numCompleted += 1; retData.push( { name : event.target.options.name , hz : event.target.hz , marginOfError : event.target.stats.moe , moePercent : event.target.stats.rme } ); finalString += String(event.target) + "\n"; var intermedString = "Running benchmark " + (numCompleted + 1) + " of " + numToRun + "\nLast result: " + String(event.target); Task.perform(maybeTaskFn(intermedString)); //retString += String(event.target) + "\n"; }); //When the last benchmark finishes, we show all results collected bjsSuite.on('complete', function(event) { Task.perform(maybeTaskFn("Final results:\n\n" + finalString) ); return callback(Task.succeed(Utils.Tuple2(finalString, List.fromArray(retData)))); }); //Finally: actually run the suite Task.perform( Task.asyncFunction(function(otherCallback){ bjsSuite.run({ 'async': true }); })); }); }
[ "function", "runWithProgress", "(", "maybeTaskFn", ",", "inSuite", ")", "{", "return", "Task", ".", "asyncFunction", "(", "function", "(", "callback", ")", "{", "var", "bjsSuite", "=", "new", "Benchmark", ".", "Suite", ";", "var", "benchArray", ";", "var", "retData", "=", "[", "]", ";", "var", "finalString", "=", "\"\"", ";", "var", "numCompleted", "=", "0", ";", "var", "numToRun", ";", "switch", "(", "inSuite", ".", "ctor", ")", "{", "case", "\"Suite\"", ":", "benchArray", "=", "List", ".", "toArray", "(", "inSuite", ".", "_1", ")", ";", "break", ";", "case", "\"SingleBenchmark\"", ":", "benchArray", "=", "[", "inSuite", ".", "_0", "]", ";", "break", ";", "}", "numToRun", "=", "benchArray", ".", "length", ";", "Task", ".", "perform", "(", "maybeTaskFn", "(", "\"Running benchmark 1 of \"", "+", "numToRun", ")", ")", ";", "//Initialize each benchmark in the suite", "for", "(", "i", "=", "0", ";", "i", "<", "benchArray", ".", "length", ";", "i", "++", ")", "{", "var", "ourThunk", "=", "function", "(", ")", "{", "//Run the thing we're timing, then mark the asynch benchmark as done", "benchArray", "[", "i", "]", ".", "thunk", "(", ")", ";", "deferred", ".", "resolve", "(", ")", ";", "}", "bjsSuite", ".", "add", "(", "benchArray", "[", "i", "]", ".", "name", ",", "benchArray", "[", "i", "]", ".", "thunk", ")", ";", "}", "//Every time a benchmark finishes, we store its results", "//and update our progress string", "bjsSuite", ".", "on", "(", "'cycle'", ",", "function", "(", "event", ")", "{", "numCompleted", "+=", "1", ";", "retData", ".", "push", "(", "{", "name", ":", "event", ".", "target", ".", "options", ".", "name", ",", "hz", ":", "event", ".", "target", ".", "hz", ",", "marginOfError", ":", "event", ".", "target", ".", "stats", ".", "moe", ",", "moePercent", ":", "event", ".", "target", ".", "stats", ".", "rme", "}", ")", ";", "finalString", "+=", "String", "(", "event", ".", "target", ")", "+", "\"\\n\"", ";", "var", "intermedString", "=", "\"Running benchmark \"", "+", "(", "numCompleted", "+", "1", ")", "+", "\" of \"", "+", "numToRun", "+", "\"\\nLast result: \"", "+", "String", "(", "event", ".", "target", ")", ";", "Task", ".", "perform", "(", "maybeTaskFn", "(", "intermedString", ")", ")", ";", "//retString += String(event.target) + \"\\n\";", "}", ")", ";", "//When the last benchmark finishes, we show all results collected", "bjsSuite", ".", "on", "(", "'complete'", ",", "function", "(", "event", ")", "{", "Task", ".", "perform", "(", "maybeTaskFn", "(", "\"Final results:\\n\\n\"", "+", "finalString", ")", ")", ";", "return", "callback", "(", "Task", ".", "succeed", "(", "Utils", ".", "Tuple2", "(", "finalString", ",", "List", ".", "fromArray", "(", "retData", ")", ")", ")", ")", ";", "}", ")", ";", "//Finally: actually run the suite", "Task", ".", "perform", "(", "Task", ".", "asyncFunction", "(", "function", "(", "otherCallback", ")", "{", "bjsSuite", ".", "run", "(", "{", "'async'", ":", "true", "}", ")", ";", "}", ")", ")", ";", "}", ")", ";", "}" ]
Generate the task for running a benchmark suite Possibly updating a given mailbox with a string describing Our progress of running the benchmarks so far
[ "Generate", "the", "task", "for", "running", "a", "benchmark", "suite", "Possibly", "updating", "a", "given", "mailbox", "with", "a", "string", "describing", "Our", "progress", "of", "running", "the", "benchmarks", "so", "far" ]
68f0fc0b595ceee32bf94538154d4cf7766817f6
https://github.com/avh4/elm-format/blob/68f0fc0b595ceee32bf94538154d4cf7766817f6/parser/bench/src/Native/Benchmark.js#L26-L94
15,317
Microsoft/tsiclient
pages/windApp/windApp.js
getOverallBarChart
function getOverallBarChart(){ var contextMenuActions = [{ name: 'Explore windmill', action: function(ae, splitBy, timestamp) { explore(splitBy); } }] var endDate = new Date(Math.floor((new Date()).valueOf()/(1000*60*60*24))*(1000*60*60*24)); var startDate = new Date(endDate.valueOf() - 1000*60*60*24*7); var aggregateExpressions = []; aggregateExpressions.push(new tsiClient.ux.AggregateExpression({predicateString: "DSCR HAS 'Grid Power'"}, {property: 'VALUE', type: "Double"}, ['sum'], { from: startDate, to: endDate, bucketSize: '1d' }, {property: 'UNIT', type: 'String'}, 'teal', 'GridPower', contextMenuActions)); authContext.getTsiToken().then(function(token){ tsiClient.server.getAggregates(token, environmentFqdn, aggregateExpressions.map(function(ae){return ae.toTsx()})).then(function(result){ var barChart = new tsiClient.ux.BarChart(document.getElementById('chart0')); var transformedResult = tsiClient.ux.transformAggregatesForVisualization(result, aggregateExpressions); barChart.render(transformedResult, {legend: 'hidden', zeroYAxis: true, keepSplitByColor: true, tooltip: true}, aggregateExpressions); }); }); }
javascript
function getOverallBarChart(){ var contextMenuActions = [{ name: 'Explore windmill', action: function(ae, splitBy, timestamp) { explore(splitBy); } }] var endDate = new Date(Math.floor((new Date()).valueOf()/(1000*60*60*24))*(1000*60*60*24)); var startDate = new Date(endDate.valueOf() - 1000*60*60*24*7); var aggregateExpressions = []; aggregateExpressions.push(new tsiClient.ux.AggregateExpression({predicateString: "DSCR HAS 'Grid Power'"}, {property: 'VALUE', type: "Double"}, ['sum'], { from: startDate, to: endDate, bucketSize: '1d' }, {property: 'UNIT', type: 'String'}, 'teal', 'GridPower', contextMenuActions)); authContext.getTsiToken().then(function(token){ tsiClient.server.getAggregates(token, environmentFqdn, aggregateExpressions.map(function(ae){return ae.toTsx()})).then(function(result){ var barChart = new tsiClient.ux.BarChart(document.getElementById('chart0')); var transformedResult = tsiClient.ux.transformAggregatesForVisualization(result, aggregateExpressions); barChart.render(transformedResult, {legend: 'hidden', zeroYAxis: true, keepSplitByColor: true, tooltip: true}, aggregateExpressions); }); }); }
[ "function", "getOverallBarChart", "(", ")", "{", "var", "contextMenuActions", "=", "[", "{", "name", ":", "'Explore windmill'", ",", "action", ":", "function", "(", "ae", ",", "splitBy", ",", "timestamp", ")", "{", "explore", "(", "splitBy", ")", ";", "}", "}", "]", "var", "endDate", "=", "new", "Date", "(", "Math", ".", "floor", "(", "(", "new", "Date", "(", ")", ")", ".", "valueOf", "(", ")", "/", "(", "1000", "*", "60", "*", "60", "*", "24", ")", ")", "*", "(", "1000", "*", "60", "*", "60", "*", "24", ")", ")", ";", "var", "startDate", "=", "new", "Date", "(", "endDate", ".", "valueOf", "(", ")", "-", "1000", "*", "60", "*", "60", "*", "24", "*", "7", ")", ";", "var", "aggregateExpressions", "=", "[", "]", ";", "aggregateExpressions", ".", "push", "(", "new", "tsiClient", ".", "ux", ".", "AggregateExpression", "(", "{", "predicateString", ":", "\"DSCR HAS 'Grid Power'\"", "}", ",", "{", "property", ":", "'VALUE'", ",", "type", ":", "\"Double\"", "}", ",", "[", "'sum'", "]", ",", "{", "from", ":", "startDate", ",", "to", ":", "endDate", ",", "bucketSize", ":", "'1d'", "}", ",", "{", "property", ":", "'UNIT'", ",", "type", ":", "'String'", "}", ",", "'teal'", ",", "'GridPower'", ",", "contextMenuActions", ")", ")", ";", "authContext", ".", "getTsiToken", "(", ")", ".", "then", "(", "function", "(", "token", ")", "{", "tsiClient", ".", "server", ".", "getAggregates", "(", "token", ",", "environmentFqdn", ",", "aggregateExpressions", ".", "map", "(", "function", "(", "ae", ")", "{", "return", "ae", ".", "toTsx", "(", ")", "}", ")", ")", ".", "then", "(", "function", "(", "result", ")", "{", "var", "barChart", "=", "new", "tsiClient", ".", "ux", ".", "BarChart", "(", "document", ".", "getElementById", "(", "'chart0'", ")", ")", ";", "var", "transformedResult", "=", "tsiClient", ".", "ux", ".", "transformAggregatesForVisualization", "(", "result", ",", "aggregateExpressions", ")", ";", "barChart", ".", "render", "(", "transformedResult", ",", "{", "legend", ":", "'hidden'", ",", "zeroYAxis", ":", "true", ",", "keepSplitByColor", ":", "true", ",", "tooltip", ":", "true", "}", ",", "aggregateExpressions", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Bar chart for overall production
[ "Bar", "chart", "for", "overall", "production" ]
a242d08fd1b0fc09bae118d71eea9530c40d47f7
https://github.com/Microsoft/tsiclient/blob/a242d08fd1b0fc09bae118d71eea9530c40d47f7/pages/windApp/windApp.js#L59-L78
15,318
Microsoft/tsiclient
pages/windApp/windApp.js
function (response) { document.getElementById("windmillWeather").innerHTML = "<div>Current conditions</div>" + '<img class="icon" src="https://openweathermap.org/img/w/' + response.weather[0].icon + '.png' + '"><span>' + response.weather[0].main + ", Temp: " + response.main.temp + "'c, Wind: " + response.wind.speed + " (m/s)</span>"; }
javascript
function (response) { document.getElementById("windmillWeather").innerHTML = "<div>Current conditions</div>" + '<img class="icon" src="https://openweathermap.org/img/w/' + response.weather[0].icon + '.png' + '"><span>' + response.weather[0].main + ", Temp: " + response.main.temp + "'c, Wind: " + response.wind.speed + " (m/s)</span>"; }
[ "function", "(", "response", ")", "{", "document", ".", "getElementById", "(", "\"windmillWeather\"", ")", ".", "innerHTML", "=", "\"<div>Current conditions</div>\"", "+", "'<img class=\"icon\" src=\"https://openweathermap.org/img/w/'", "+", "response", ".", "weather", "[", "0", "]", ".", "icon", "+", "'.png'", "+", "'\"><span>'", "+", "response", ".", "weather", "[", "0", "]", ".", "main", "+", "\", Temp: \"", "+", "response", ".", "main", ".", "temp", "+", "\"'c, Wind: \"", "+", "response", ".", "wind", ".", "speed", "+", "\" (m/s)</span>\"", ";", "}" ]
work with the response
[ "work", "with", "the", "response" ]
a242d08fd1b0fc09bae118d71eea9530c40d47f7
https://github.com/Microsoft/tsiclient/blob/a242d08fd1b0fc09bae118d71eea9530c40d47f7/pages/windApp/windApp.js#L196-L198
15,319
NativeScript/nativescript-dev-webpack
lib/utils.js
getUpdatedEmittedFiles
function getUpdatedEmittedFiles(emittedFiles, webpackRuntimeFiles) { let fallbackFiles = []; let hotHash; if (emittedFiles.some(x => x.endsWith('.hot-update.json'))) { let result = emittedFiles.slice(); const hotUpdateScripts = emittedFiles.filter(x => x.endsWith('.hot-update.js')); hotUpdateScripts.forEach(hotUpdateScript => { const { name, hash } = parseHotUpdateChunkName(hotUpdateScript); hotHash = hash; // remove bundle/vendor.js files if there's a bundle.XXX.hot-update.js or vendor.XXX.hot-update.js result = result.filter(file => file !== `${name}.js`); if (webpackRuntimeFiles && webpackRuntimeFiles.length) { // remove files containing only the Webpack runtime (e.g. runtime.js) result = result.filter(file => webpackRuntimeFiles.indexOf(file) === -1); } }); //if applying of hot update fails, we must fallback to the full files fallbackFiles = emittedFiles.filter(file => result.indexOf(file) === -1); return { emittedFiles: result, fallbackFiles, hash: hotHash }; } else { return { emittedFiles, fallbackFiles }; } }
javascript
function getUpdatedEmittedFiles(emittedFiles, webpackRuntimeFiles) { let fallbackFiles = []; let hotHash; if (emittedFiles.some(x => x.endsWith('.hot-update.json'))) { let result = emittedFiles.slice(); const hotUpdateScripts = emittedFiles.filter(x => x.endsWith('.hot-update.js')); hotUpdateScripts.forEach(hotUpdateScript => { const { name, hash } = parseHotUpdateChunkName(hotUpdateScript); hotHash = hash; // remove bundle/vendor.js files if there's a bundle.XXX.hot-update.js or vendor.XXX.hot-update.js result = result.filter(file => file !== `${name}.js`); if (webpackRuntimeFiles && webpackRuntimeFiles.length) { // remove files containing only the Webpack runtime (e.g. runtime.js) result = result.filter(file => webpackRuntimeFiles.indexOf(file) === -1); } }); //if applying of hot update fails, we must fallback to the full files fallbackFiles = emittedFiles.filter(file => result.indexOf(file) === -1); return { emittedFiles: result, fallbackFiles, hash: hotHash }; } else { return { emittedFiles, fallbackFiles }; } }
[ "function", "getUpdatedEmittedFiles", "(", "emittedFiles", ",", "webpackRuntimeFiles", ")", "{", "let", "fallbackFiles", "=", "[", "]", ";", "let", "hotHash", ";", "if", "(", "emittedFiles", ".", "some", "(", "x", "=>", "x", ".", "endsWith", "(", "'.hot-update.json'", ")", ")", ")", "{", "let", "result", "=", "emittedFiles", ".", "slice", "(", ")", ";", "const", "hotUpdateScripts", "=", "emittedFiles", ".", "filter", "(", "x", "=>", "x", ".", "endsWith", "(", "'.hot-update.js'", ")", ")", ";", "hotUpdateScripts", ".", "forEach", "(", "hotUpdateScript", "=>", "{", "const", "{", "name", ",", "hash", "}", "=", "parseHotUpdateChunkName", "(", "hotUpdateScript", ")", ";", "hotHash", "=", "hash", ";", "// remove bundle/vendor.js files if there's a bundle.XXX.hot-update.js or vendor.XXX.hot-update.js", "result", "=", "result", ".", "filter", "(", "file", "=>", "file", "!==", "`", "${", "name", "}", "`", ")", ";", "if", "(", "webpackRuntimeFiles", "&&", "webpackRuntimeFiles", ".", "length", ")", "{", "// remove files containing only the Webpack runtime (e.g. runtime.js)", "result", "=", "result", ".", "filter", "(", "file", "=>", "webpackRuntimeFiles", ".", "indexOf", "(", "file", ")", "===", "-", "1", ")", ";", "}", "}", ")", ";", "//if applying of hot update fails, we must fallback to the full files", "fallbackFiles", "=", "emittedFiles", ".", "filter", "(", "file", "=>", "result", ".", "indexOf", "(", "file", ")", "===", "-", "1", ")", ";", "return", "{", "emittedFiles", ":", "result", ",", "fallbackFiles", ",", "hash", ":", "hotHash", "}", ";", "}", "else", "{", "return", "{", "emittedFiles", ",", "fallbackFiles", "}", ";", "}", "}" ]
Checks if there's a file in the following pattern 5e0326f3bb50f9f26cf0.hot-update.json if yes this is a HMR update and remove all bundle files as we don't need them to be synced, but only the update chunks
[ "Checks", "if", "there", "s", "a", "file", "in", "the", "following", "pattern", "5e0326f3bb50f9f26cf0", ".", "hot", "-", "update", ".", "json", "if", "yes", "this", "is", "a", "HMR", "update", "and", "remove", "all", "bundle", "files", "as", "we", "don", "t", "need", "them", "to", "be", "synced", "but", "only", "the", "update", "chunks" ]
269308bb99e37f92ac214d45b57a0399f96c6ce7
https://github.com/NativeScript/nativescript-dev-webpack/blob/269308bb99e37f92ac214d45b57a0399f96c6ce7/lib/utils.js#L37-L60
15,320
NativeScript/nativescript-dev-webpack
lib/utils.js
parseHotUpdateChunkName
function parseHotUpdateChunkName(name) { const matcher = /^(.+)\.(.+)\.hot-update/gm; const matches = matcher.exec(name); return { name: matches[1] || "", hash: matches[2] || "", }; }
javascript
function parseHotUpdateChunkName(name) { const matcher = /^(.+)\.(.+)\.hot-update/gm; const matches = matcher.exec(name); return { name: matches[1] || "", hash: matches[2] || "", }; }
[ "function", "parseHotUpdateChunkName", "(", "name", ")", "{", "const", "matcher", "=", "/", "^(.+)\\.(.+)\\.hot-update", "/", "gm", ";", "const", "matches", "=", "matcher", ".", "exec", "(", "name", ")", ";", "return", "{", "name", ":", "matches", "[", "1", "]", "||", "\"\"", ",", "hash", ":", "matches", "[", "2", "]", "||", "\"\"", ",", "}", ";", "}" ]
Parse the filename of the hot update chunk. @param name bundle.deccb264c01d6d42416c.hot-update.js @returns { name: string, hash: string } { name: 'bundle', hash: 'deccb264c01d6d42416c' }
[ "Parse", "the", "filename", "of", "the", "hot", "update", "chunk", "." ]
269308bb99e37f92ac214d45b57a0399f96c6ce7
https://github.com/NativeScript/nativescript-dev-webpack/blob/269308bb99e37f92ac214d45b57a0399f96c6ce7/lib/utils.js#L67-L74
15,321
mapbox/hubdb
index.js
remove
function remove(id, callback) { repo.contents(id).fetch({ ref: options.branch }, function(err, info) { if (err) return callback(err); repo.contents(id).remove({ branch: options.branch, sha: info.sha, message: '-' }, function(err, res) { callback(err, res, id); }); }); }
javascript
function remove(id, callback) { repo.contents(id).fetch({ ref: options.branch }, function(err, info) { if (err) return callback(err); repo.contents(id).remove({ branch: options.branch, sha: info.sha, message: '-' }, function(err, res) { callback(err, res, id); }); }); }
[ "function", "remove", "(", "id", ",", "callback", ")", "{", "repo", ".", "contents", "(", "id", ")", ".", "fetch", "(", "{", "ref", ":", "options", ".", "branch", "}", ",", "function", "(", "err", ",", "info", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "repo", ".", "contents", "(", "id", ")", ".", "remove", "(", "{", "branch", ":", "options", ".", "branch", ",", "sha", ":", "info", ".", "sha", ",", "message", ":", "'-'", "}", ",", "function", "(", "err", ",", "res", ")", "{", "callback", "(", "err", ",", "res", ",", "id", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Remove an item from the database given its id and a callback. @param {String} id @param {Function} callback called with (err, result, id)
[ "Remove", "an", "item", "from", "the", "database", "given", "its", "id", "and", "a", "callback", "." ]
2cf6ff4327f3d68c3f539d86a5361f0143b3a91c
https://github.com/mapbox/hubdb/blob/2cf6ff4327f3d68c3f539d86a5361f0143b3a91c/index.js#L111-L124
15,322
mapbox/hubdb
index.js
get
function get(id, callback) { _getSHA(id, function(err, sha) { if (err) return callback(err); repo.git.blobs(sha).fetch(function(err, res) { if (err) return callback(err); callback(err, JSON.parse(atob(res.content))); }); }); }
javascript
function get(id, callback) { _getSHA(id, function(err, sha) { if (err) return callback(err); repo.git.blobs(sha).fetch(function(err, res) { if (err) return callback(err); callback(err, JSON.parse(atob(res.content))); }); }); }
[ "function", "get", "(", "id", ",", "callback", ")", "{", "_getSHA", "(", "id", ",", "function", "(", "err", ",", "sha", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "repo", ".", "git", ".", "blobs", "(", "sha", ")", ".", "fetch", "(", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "callback", "(", "err", ",", "JSON", ".", "parse", "(", "atob", "(", "res", ".", "content", ")", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get an item from the database given its id and a callback. @param {String} id @param {Function} callback called with (err, contents): contents are given as parsed JSON
[ "Get", "an", "item", "from", "the", "database", "given", "its", "id", "and", "a", "callback", "." ]
2cf6ff4327f3d68c3f539d86a5361f0143b3a91c
https://github.com/mapbox/hubdb/blob/2cf6ff4327f3d68c3f539d86a5361f0143b3a91c/index.js#L133-L141
15,323
mapbox/hubdb
index.js
_getSHA
function _getSHA(id, callback) { repo.contents("").fetch({ ref: options.branch }, function(err, res) { if (err) return callback(err); var sha = res.reduce(function(previousValue, item) { return item.name === id ? item.sha : previousValue; }, ""); callback(err, sha); }); }
javascript
function _getSHA(id, callback) { repo.contents("").fetch({ ref: options.branch }, function(err, res) { if (err) return callback(err); var sha = res.reduce(function(previousValue, item) { return item.name === id ? item.sha : previousValue; }, ""); callback(err, sha); }); }
[ "function", "_getSHA", "(", "id", ",", "callback", ")", "{", "repo", ".", "contents", "(", "\"\"", ")", ".", "fetch", "(", "{", "ref", ":", "options", ".", "branch", "}", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "var", "sha", "=", "res", ".", "reduce", "(", "function", "(", "previousValue", ",", "item", ")", "{", "return", "item", ".", "name", "===", "id", "?", "item", ".", "sha", ":", "previousValue", ";", "}", ",", "\"\"", ")", ";", "callback", "(", "err", ",", "sha", ")", ";", "}", ")", ";", "}" ]
get the SHA corresponding to id at the HEAD of options.branch @access private @param {String} id @param {Function} callback called with (err, result)
[ "get", "the", "SHA", "corresponding", "to", "id", "at", "the", "HEAD", "of", "options", ".", "branch" ]
2cf6ff4327f3d68c3f539d86a5361f0143b3a91c
https://github.com/mapbox/hubdb/blob/2cf6ff4327f3d68c3f539d86a5361f0143b3a91c/index.js#L173-L183
15,324
confluentinc/kafka-rest-node
examples/console_producer.js
processInput
function processInput(buffer, cb) { if (buffer.length == 0) return buffer; var split_char = '\n'; var lines = buffer.split(split_char); // If there are any line splits, the below logic always works, but if there are none we need to detect this and skip // any processing. if (lines[0].length == buffer.length) return buffer; // Note last item is ignored since it is the remainder (or empty) for(var i = 0; i < lines.length-1; i++) { var line = lines[i]; if (format == "binary") { target.produce(line, handleProduceResponse.bind(undefined, cb)); } else if (format == "avro") { // Avro data should be passed in its JSON-serialized form try { var avro = JSON.parse(line); } catch (e) { console.log("Couldn't parse '" + line + "' as JSON"); continue; } target.produce(valueSchema, avro, handleProduceResponse.bind(undefined, cb)); } // OR with key or partition: //target.produce({'partition': 0, 'value': line}, handleProduceResponse.bind(undefined, cb)); //target.produce({'key': 'console', 'value': line}, handleProduceResponse.bind(undefined, cb)); num_messages += 1; num_bytes += line.length; } return lines[lines.length-1]; }
javascript
function processInput(buffer, cb) { if (buffer.length == 0) return buffer; var split_char = '\n'; var lines = buffer.split(split_char); // If there are any line splits, the below logic always works, but if there are none we need to detect this and skip // any processing. if (lines[0].length == buffer.length) return buffer; // Note last item is ignored since it is the remainder (or empty) for(var i = 0; i < lines.length-1; i++) { var line = lines[i]; if (format == "binary") { target.produce(line, handleProduceResponse.bind(undefined, cb)); } else if (format == "avro") { // Avro data should be passed in its JSON-serialized form try { var avro = JSON.parse(line); } catch (e) { console.log("Couldn't parse '" + line + "' as JSON"); continue; } target.produce(valueSchema, avro, handleProduceResponse.bind(undefined, cb)); } // OR with key or partition: //target.produce({'partition': 0, 'value': line}, handleProduceResponse.bind(undefined, cb)); //target.produce({'key': 'console', 'value': line}, handleProduceResponse.bind(undefined, cb)); num_messages += 1; num_bytes += line.length; } return lines[lines.length-1]; }
[ "function", "processInput", "(", "buffer", ",", "cb", ")", "{", "if", "(", "buffer", ".", "length", "==", "0", ")", "return", "buffer", ";", "var", "split_char", "=", "'\\n'", ";", "var", "lines", "=", "buffer", ".", "split", "(", "split_char", ")", ";", "// If there are any line splits, the below logic always works, but if there are none we need to detect this and skip", "// any processing.", "if", "(", "lines", "[", "0", "]", ".", "length", "==", "buffer", ".", "length", ")", "return", "buffer", ";", "// Note last item is ignored since it is the remainder (or empty)", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lines", ".", "length", "-", "1", ";", "i", "++", ")", "{", "var", "line", "=", "lines", "[", "i", "]", ";", "if", "(", "format", "==", "\"binary\"", ")", "{", "target", ".", "produce", "(", "line", ",", "handleProduceResponse", ".", "bind", "(", "undefined", ",", "cb", ")", ")", ";", "}", "else", "if", "(", "format", "==", "\"avro\"", ")", "{", "// Avro data should be passed in its JSON-serialized form", "try", "{", "var", "avro", "=", "JSON", ".", "parse", "(", "line", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "\"Couldn't parse '\"", "+", "line", "+", "\"' as JSON\"", ")", ";", "continue", ";", "}", "target", ".", "produce", "(", "valueSchema", ",", "avro", ",", "handleProduceResponse", ".", "bind", "(", "undefined", ",", "cb", ")", ")", ";", "}", "// OR with key or partition:", "//target.produce({'partition': 0, 'value': line}, handleProduceResponse.bind(undefined, cb));", "//target.produce({'key': 'console', 'value': line}, handleProduceResponse.bind(undefined, cb));", "num_messages", "+=", "1", ";", "num_bytes", "+=", "line", ".", "length", ";", "}", "return", "lines", "[", "lines", ".", "length", "-", "1", "]", ";", "}" ]
Splits input by lines into individual messages and passes them to the producer. Tracks stats to print at exit.
[ "Splits", "input", "by", "lines", "into", "individual", "messages", "and", "passes", "them", "to", "the", "producer", ".", "Tracks", "stats", "to", "print", "at", "exit", "." ]
2169a8888e93e0d6565fbae037f95aefb64aaedd
https://github.com/confluentinc/kafka-rest-node/blob/2169a8888e93e0d6565fbae037f95aefb64aaedd/examples/console_producer.js#L98-L127
15,325
confluentinc/kafka-rest-node
examples/console_producer.js
handleProduceResponse
function handleProduceResponse(cb, err, res) { num_responses += 1; if (err) { console.log("Error producing message: " + err); } else { num_messages_acked += 1; } // We can only indicate were done if stdin was closed and we have no outstanding messages. checkSendingComplete(cb); }
javascript
function handleProduceResponse(cb, err, res) { num_responses += 1; if (err) { console.log("Error producing message: " + err); } else { num_messages_acked += 1; } // We can only indicate were done if stdin was closed and we have no outstanding messages. checkSendingComplete(cb); }
[ "function", "handleProduceResponse", "(", "cb", ",", "err", ",", "res", ")", "{", "num_responses", "+=", "1", ";", "if", "(", "err", ")", "{", "console", ".", "log", "(", "\"Error producing message: \"", "+", "err", ")", ";", "}", "else", "{", "num_messages_acked", "+=", "1", ";", "}", "// We can only indicate were done if stdin was closed and we have no outstanding messages.", "checkSendingComplete", "(", "cb", ")", ";", "}" ]
Handles produce responses
[ "Handles", "produce", "responses" ]
2169a8888e93e0d6565fbae037f95aefb64aaedd
https://github.com/confluentinc/kafka-rest-node/blob/2169a8888e93e0d6565fbae037f95aefb64aaedd/examples/console_producer.js#L132-L142
15,326
ecomfe/veui
packages/veui-loader/src/index.js
getParts
function getParts (component, options) { let { modules = [], package: pack, path: packPath = COMPONENTS_DIRNAME, transform, fileName, locale, global = [] } = options if (pack && fileName) { modules.push({ package: pack, path: packPath, transform, fileName }) } if (locale !== false) { if (!locale) { locale = 'zh-Hans' } if (!Array.isArray(locale)) { locale = [locale] } locale = locale.filter(l => typeof l === 'string') modules = locale .map(l => { return { package: 'veui', path: `locale/${l}`, transform: false, fileName: '{module}.js' } }) .concat(modules) global = locale .map(l => { return { path: `veui/locale/${l}/common.js` } }) .concat(global) } return modules.reduce( ( acc, { package: pack, path: packPath = COMPONENTS_DIRNAME, transform, fileName } ) => { let peerComponent = getPeerFilename(component, { transform, template: fileName }) let peerPath = slash(path.join(pack, packPath, peerComponent)) pushPart(acc, { path: peerPath }) return acc }, { script: [...global], style: [] } ) }
javascript
function getParts (component, options) { let { modules = [], package: pack, path: packPath = COMPONENTS_DIRNAME, transform, fileName, locale, global = [] } = options if (pack && fileName) { modules.push({ package: pack, path: packPath, transform, fileName }) } if (locale !== false) { if (!locale) { locale = 'zh-Hans' } if (!Array.isArray(locale)) { locale = [locale] } locale = locale.filter(l => typeof l === 'string') modules = locale .map(l => { return { package: 'veui', path: `locale/${l}`, transform: false, fileName: '{module}.js' } }) .concat(modules) global = locale .map(l => { return { path: `veui/locale/${l}/common.js` } }) .concat(global) } return modules.reduce( ( acc, { package: pack, path: packPath = COMPONENTS_DIRNAME, transform, fileName } ) => { let peerComponent = getPeerFilename(component, { transform, template: fileName }) let peerPath = slash(path.join(pack, packPath, peerComponent)) pushPart(acc, { path: peerPath }) return acc }, { script: [...global], style: [] } ) }
[ "function", "getParts", "(", "component", ",", "options", ")", "{", "let", "{", "modules", "=", "[", "]", ",", "package", ":", "pack", ",", "path", ":", "packPath", "=", "COMPONENTS_DIRNAME", ",", "transform", ",", "fileName", ",", "locale", ",", "global", "=", "[", "]", "}", "=", "options", "if", "(", "pack", "&&", "fileName", ")", "{", "modules", ".", "push", "(", "{", "package", ":", "pack", ",", "path", ":", "packPath", ",", "transform", ",", "fileName", "}", ")", "}", "if", "(", "locale", "!==", "false", ")", "{", "if", "(", "!", "locale", ")", "{", "locale", "=", "'zh-Hans'", "}", "if", "(", "!", "Array", ".", "isArray", "(", "locale", ")", ")", "{", "locale", "=", "[", "locale", "]", "}", "locale", "=", "locale", ".", "filter", "(", "l", "=>", "typeof", "l", "===", "'string'", ")", "modules", "=", "locale", ".", "map", "(", "l", "=>", "{", "return", "{", "package", ":", "'veui'", ",", "path", ":", "`", "${", "l", "}", "`", ",", "transform", ":", "false", ",", "fileName", ":", "'{module}.js'", "}", "}", ")", ".", "concat", "(", "modules", ")", "global", "=", "locale", ".", "map", "(", "l", "=>", "{", "return", "{", "path", ":", "`", "${", "l", "}", "`", "}", "}", ")", ".", "concat", "(", "global", ")", "}", "return", "modules", ".", "reduce", "(", "(", "acc", ",", "{", "package", ":", "pack", ",", "path", ":", "packPath", "=", "COMPONENTS_DIRNAME", ",", "transform", ",", "fileName", "}", ")", "=>", "{", "let", "peerComponent", "=", "getPeerFilename", "(", "component", ",", "{", "transform", ",", "template", ":", "fileName", "}", ")", "let", "peerPath", "=", "slash", "(", "path", ".", "join", "(", "pack", ",", "packPath", ",", "peerComponent", ")", ")", "pushPart", "(", "acc", ",", "{", "path", ":", "peerPath", "}", ")", "return", "acc", "}", ",", "{", "script", ":", "[", "...", "global", "]", ",", "style", ":", "[", "]", "}", ")", "}" ]
Extract potentially dependent parts for a component @param {string} component Component name @param {Object} options veui-loader options @returns {Object} Extracted parts metadata
[ "Extract", "potentially", "dependent", "parts", "for", "a", "component" ]
e3a47275cd2b631455f1fa1c25bc92e4588cf284
https://github.com/ecomfe/veui/blob/e3a47275cd2b631455f1fa1c25bc92e4588cf284/packages/veui-loader/src/index.js#L125-L190
15,327
ecomfe/veui
packages/veui-loader/src/index.js
patchContent
function patchContent (content, parts) { return Object.keys(parts).reduce((content, type) => { let paths = parts[type].filter(({ valid }) => valid).map(({ path }) => path) return patchType(content, type, paths) }, content) }
javascript
function patchContent (content, parts) { return Object.keys(parts).reduce((content, type) => { let paths = parts[type].filter(({ valid }) => valid).map(({ path }) => path) return patchType(content, type, paths) }, content) }
[ "function", "patchContent", "(", "content", ",", "parts", ")", "{", "return", "Object", ".", "keys", "(", "parts", ")", ".", "reduce", "(", "(", "content", ",", "type", ")", "=>", "{", "let", "paths", "=", "parts", "[", "type", "]", ".", "filter", "(", "(", "{", "valid", "}", ")", "=>", "valid", ")", ".", "map", "(", "(", "{", "path", "}", ")", "=>", "path", ")", "return", "patchType", "(", "content", ",", "type", ",", "paths", ")", "}", ",", "content", ")", "}" ]
Patch content with extracted parts metadata @param {string} content Module content @param {Object} parts Extracted parts metadata
[ "Patch", "content", "with", "extracted", "parts", "metadata" ]
e3a47275cd2b631455f1fa1c25bc92e4588cf284
https://github.com/ecomfe/veui/blob/e3a47275cd2b631455f1fa1c25bc92e4588cf284/packages/veui-loader/src/index.js#L198-L203
15,328
ecomfe/veui
packages/veui-loader/src/index.js
pushPart
function pushPart (parts, file) { let ext = getExtname(file.path) let type = Object.keys(EXT_TYPES).find(key => { return EXT_TYPES[key].includes(ext) }) parts[type.toLowerCase()].push(file) }
javascript
function pushPart (parts, file) { let ext = getExtname(file.path) let type = Object.keys(EXT_TYPES).find(key => { return EXT_TYPES[key].includes(ext) }) parts[type.toLowerCase()].push(file) }
[ "function", "pushPart", "(", "parts", ",", "file", ")", "{", "let", "ext", "=", "getExtname", "(", "file", ".", "path", ")", "let", "type", "=", "Object", ".", "keys", "(", "EXT_TYPES", ")", ".", "find", "(", "key", "=>", "{", "return", "EXT_TYPES", "[", "key", "]", ".", "includes", "(", "ext", ")", "}", ")", "parts", "[", "type", ".", "toLowerCase", "(", ")", "]", ".", "push", "(", "file", ")", "}" ]
Push peer file dependency into collected parts. @param {Object} parts Collected parts containing scripts and styles @param {Object} file The file to be appended
[ "Push", "peer", "file", "dependency", "into", "collected", "parts", "." ]
e3a47275cd2b631455f1fa1c25bc92e4588cf284
https://github.com/ecomfe/veui/blob/e3a47275cd2b631455f1fa1c25bc92e4588cf284/packages/veui-loader/src/index.js#L210-L216
15,329
ecomfe/veui
packages/veui-loader/src/index.js
patchType
function patchType (content, type, peerPaths) { let normalizedPaths = peerPaths.map(path => slash(normalize(path))) switch (type) { case 'script': let scriptImports = normalizedPaths.map(path => `import '${path}'\n`) content = content.replace(RE_SCRIPT, match => { return `${match}\n${scriptImports.join('')}` }) break case 'style': let styleImports = normalizedPaths.map(path => { let langStr = '' let ext = getExtname(path) if (ext !== 'css') { langStr = `lang="${ext}" ` } return `<style ${langStr}src="${path}"></style>\n` }) content += styleImports.join('') break default: break } return content }
javascript
function patchType (content, type, peerPaths) { let normalizedPaths = peerPaths.map(path => slash(normalize(path))) switch (type) { case 'script': let scriptImports = normalizedPaths.map(path => `import '${path}'\n`) content = content.replace(RE_SCRIPT, match => { return `${match}\n${scriptImports.join('')}` }) break case 'style': let styleImports = normalizedPaths.map(path => { let langStr = '' let ext = getExtname(path) if (ext !== 'css') { langStr = `lang="${ext}" ` } return `<style ${langStr}src="${path}"></style>\n` }) content += styleImports.join('') break default: break } return content }
[ "function", "patchType", "(", "content", ",", "type", ",", "peerPaths", ")", "{", "let", "normalizedPaths", "=", "peerPaths", ".", "map", "(", "path", "=>", "slash", "(", "normalize", "(", "path", ")", ")", ")", "switch", "(", "type", ")", "{", "case", "'script'", ":", "let", "scriptImports", "=", "normalizedPaths", ".", "map", "(", "path", "=>", "`", "${", "path", "}", "\\n", "`", ")", "content", "=", "content", ".", "replace", "(", "RE_SCRIPT", ",", "match", "=>", "{", "return", "`", "${", "match", "}", "\\n", "${", "scriptImports", ".", "join", "(", "''", ")", "}", "`", "}", ")", "break", "case", "'style'", ":", "let", "styleImports", "=", "normalizedPaths", ".", "map", "(", "path", "=>", "{", "let", "langStr", "=", "''", "let", "ext", "=", "getExtname", "(", "path", ")", "if", "(", "ext", "!==", "'css'", ")", "{", "langStr", "=", "`", "${", "ext", "}", "`", "}", "return", "`", "${", "langStr", "}", "${", "path", "}", "\\n", "`", "}", ")", "content", "+=", "styleImports", ".", "join", "(", "''", ")", "break", "default", ":", "break", "}", "return", "content", "}" ]
Patch file content according to a given type. @param {string} content Original content @param {string} type Peer type, can be `script` or `style` @param {Array<string>} peerPaths Peer module paths @returns {string} The patched content
[ "Patch", "file", "content", "according", "to", "a", "given", "type", "." ]
e3a47275cd2b631455f1fa1c25bc92e4588cf284
https://github.com/ecomfe/veui/blob/e3a47275cd2b631455f1fa1c25bc92e4588cf284/packages/veui-loader/src/index.js#L239-L264
15,330
ecomfe/veui
packages/veui-loader/src/index.js
assurePath
async function assurePath (modulePath, resolve) { if (resolveCache[modulePath] === false) { return false } else if (!(modulePath in resolveCache)) { if (typeof resolve === 'function') { try { resolveCache[modulePath] = !!(await resolve(modulePath)) } catch (e) { resolveCache[modulePath] = false } } } return resolveCache[modulePath] }
javascript
async function assurePath (modulePath, resolve) { if (resolveCache[modulePath] === false) { return false } else if (!(modulePath in resolveCache)) { if (typeof resolve === 'function') { try { resolveCache[modulePath] = !!(await resolve(modulePath)) } catch (e) { resolveCache[modulePath] = false } } } return resolveCache[modulePath] }
[ "async", "function", "assurePath", "(", "modulePath", ",", "resolve", ")", "{", "if", "(", "resolveCache", "[", "modulePath", "]", "===", "false", ")", "{", "return", "false", "}", "else", "if", "(", "!", "(", "modulePath", "in", "resolveCache", ")", ")", "{", "if", "(", "typeof", "resolve", "===", "'function'", ")", "{", "try", "{", "resolveCache", "[", "modulePath", "]", "=", "!", "!", "(", "await", "resolve", "(", "modulePath", ")", ")", "}", "catch", "(", "e", ")", "{", "resolveCache", "[", "modulePath", "]", "=", "false", "}", "}", "}", "return", "resolveCache", "[", "modulePath", "]", "}" ]
To test the target peer path exists or not. @param {string} modulePath Peer module path @param {function} resolve webpack module resolver @returns {Promise<boolean>} A promise resolved with true if the target peer path exists
[ "To", "test", "the", "target", "peer", "path", "exists", "or", "not", "." ]
e3a47275cd2b631455f1fa1c25bc92e4588cf284
https://github.com/ecomfe/veui/blob/e3a47275cd2b631455f1fa1c25bc92e4588cf284/packages/veui-loader/src/index.js#L272-L286
15,331
ecomfe/veui
packages/veui-loader/src/index.js
assurePathSync
function assurePathSync (modulePath, resolveSync) { if (resolveCache[modulePath] === false) { return false } else if (!(modulePath in resolveCache)) { if (typeof resolveSync === 'function') { try { resolveCache[modulePath] = !!resolveSync(modulePath) } catch (e) { resolveCache[modulePath] = false } } } return resolveCache[modulePath] }
javascript
function assurePathSync (modulePath, resolveSync) { if (resolveCache[modulePath] === false) { return false } else if (!(modulePath in resolveCache)) { if (typeof resolveSync === 'function') { try { resolveCache[modulePath] = !!resolveSync(modulePath) } catch (e) { resolveCache[modulePath] = false } } } return resolveCache[modulePath] }
[ "function", "assurePathSync", "(", "modulePath", ",", "resolveSync", ")", "{", "if", "(", "resolveCache", "[", "modulePath", "]", "===", "false", ")", "{", "return", "false", "}", "else", "if", "(", "!", "(", "modulePath", "in", "resolveCache", ")", ")", "{", "if", "(", "typeof", "resolveSync", "===", "'function'", ")", "{", "try", "{", "resolveCache", "[", "modulePath", "]", "=", "!", "!", "resolveSync", "(", "modulePath", ")", "}", "catch", "(", "e", ")", "{", "resolveCache", "[", "modulePath", "]", "=", "false", "}", "}", "}", "return", "resolveCache", "[", "modulePath", "]", "}" ]
To test the target peer path exists or not synchronously. @param {string} modulePath Peer module path @param {function} resolveSync webpack module resolver @returns {boolean} True if the target peer path exists
[ "To", "test", "the", "target", "peer", "path", "exists", "or", "not", "synchronously", "." ]
e3a47275cd2b631455f1fa1c25bc92e4588cf284
https://github.com/ecomfe/veui/blob/e3a47275cd2b631455f1fa1c25bc92e4588cf284/packages/veui-loader/src/index.js#L294-L308
15,332
ecomfe/veui
packages/veui-loader/src/index.js
getPeerFilename
function getPeerFilename ( name, { transform = 'kebab-case', template = '{module}.css' } ) { if (!name) { return null } switch (transform) { case 'kebab-case': name = kebabCase(name) break case 'camelCase': name = camelCase(name) break case 'PascalCase': name = pascalCase(name) break case false: default: break } return template.replace(/\$?\{module\}/g, name) }
javascript
function getPeerFilename ( name, { transform = 'kebab-case', template = '{module}.css' } ) { if (!name) { return null } switch (transform) { case 'kebab-case': name = kebabCase(name) break case 'camelCase': name = camelCase(name) break case 'PascalCase': name = pascalCase(name) break case false: default: break } return template.replace(/\$?\{module\}/g, name) }
[ "function", "getPeerFilename", "(", "name", ",", "{", "transform", "=", "'kebab-case'", ",", "template", "=", "'{module}.css'", "}", ")", "{", "if", "(", "!", "name", ")", "{", "return", "null", "}", "switch", "(", "transform", ")", "{", "case", "'kebab-case'", ":", "name", "=", "kebabCase", "(", "name", ")", "break", "case", "'camelCase'", ":", "name", "=", "camelCase", "(", "name", ")", "break", "case", "'PascalCase'", ":", "name", "=", "pascalCase", "(", "name", ")", "break", "case", "false", ":", "default", ":", "break", "}", "return", "template", ".", "replace", "(", "/", "\\$?\\{module\\}", "/", "g", ",", "name", ")", "}" ]
Convert a component name according to file name template. @param {string} name Peer module file @param {Object} options Transform options @param {string} options.transform Transform type for base name @param {string} options.template File name template @returns {string} Peer module file name
[ "Convert", "a", "component", "name", "according", "to", "file", "name", "template", "." ]
e3a47275cd2b631455f1fa1c25bc92e4588cf284
https://github.com/ecomfe/veui/blob/e3a47275cd2b631455f1fa1c25bc92e4588cf284/packages/veui-loader/src/index.js#L318-L342
15,333
ubilabs/geocomplete
jquery.geocomplete.js
GeoComplete
function GeoComplete(input, options) { this.options = $.extend(true, {}, defaults, options); // This is a fix to allow types:[] not to be overridden by defaults // so search results includes everything if (options && options.types) { this.options.types = options.types; } this.input = input; this.$input = $(input); this._defaults = defaults; this._name = 'geocomplete'; this.init(); }
javascript
function GeoComplete(input, options) { this.options = $.extend(true, {}, defaults, options); // This is a fix to allow types:[] not to be overridden by defaults // so search results includes everything if (options && options.types) { this.options.types = options.types; } this.input = input; this.$input = $(input); this._defaults = defaults; this._name = 'geocomplete'; this.init(); }
[ "function", "GeoComplete", "(", "input", ",", "options", ")", "{", "this", ".", "options", "=", "$", ".", "extend", "(", "true", ",", "{", "}", ",", "defaults", ",", "options", ")", ";", "// This is a fix to allow types:[] not to be overridden by defaults", "// so search results includes everything", "if", "(", "options", "&&", "options", ".", "types", ")", "{", "this", ".", "options", ".", "types", "=", "options", ".", "types", ";", "}", "this", ".", "input", "=", "input", ";", "this", ".", "$input", "=", "$", "(", "input", ")", ";", "this", ".", "_defaults", "=", "defaults", ";", "this", ".", "_name", "=", "'geocomplete'", ";", "this", ".", "init", "(", ")", ";", "}" ]
The actual plugin constructor.
[ "The", "actual", "plugin", "constructor", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L84-L101
15,334
ubilabs/geocomplete
jquery.geocomplete.js
function(){ if (!this.options.map){ return; } if (typeof this.options.map.setCenter == "function"){ this.map = this.options.map; return; } this.map = new google.maps.Map( $(this.options.map)[0], this.options.mapOptions ); // add click event listener on the map google.maps.event.addListener( this.map, 'click', $.proxy(this.mapClicked, this) ); // add dragend even listener on the map google.maps.event.addListener( this.map, 'dragend', $.proxy(this.mapDragged, this) ); // add idle even listener on the map google.maps.event.addListener( this.map, 'idle', $.proxy(this.mapIdle, this) ); google.maps.event.addListener( this.map, 'zoom_changed', $.proxy(this.mapZoomed, this) ); }
javascript
function(){ if (!this.options.map){ return; } if (typeof this.options.map.setCenter == "function"){ this.map = this.options.map; return; } this.map = new google.maps.Map( $(this.options.map)[0], this.options.mapOptions ); // add click event listener on the map google.maps.event.addListener( this.map, 'click', $.proxy(this.mapClicked, this) ); // add dragend even listener on the map google.maps.event.addListener( this.map, 'dragend', $.proxy(this.mapDragged, this) ); // add idle even listener on the map google.maps.event.addListener( this.map, 'idle', $.proxy(this.mapIdle, this) ); google.maps.event.addListener( this.map, 'zoom_changed', $.proxy(this.mapZoomed, this) ); }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "options", ".", "map", ")", "{", "return", ";", "}", "if", "(", "typeof", "this", ".", "options", ".", "map", ".", "setCenter", "==", "\"function\"", ")", "{", "this", ".", "map", "=", "this", ".", "options", ".", "map", ";", "return", ";", "}", "this", ".", "map", "=", "new", "google", ".", "maps", ".", "Map", "(", "$", "(", "this", ".", "options", ".", "map", ")", "[", "0", "]", ",", "this", ".", "options", ".", "mapOptions", ")", ";", "// add click event listener on the map", "google", ".", "maps", ".", "event", ".", "addListener", "(", "this", ".", "map", ",", "'click'", ",", "$", ".", "proxy", "(", "this", ".", "mapClicked", ",", "this", ")", ")", ";", "// add dragend even listener on the map", "google", ".", "maps", ".", "event", ".", "addListener", "(", "this", ".", "map", ",", "'dragend'", ",", "$", ".", "proxy", "(", "this", ".", "mapDragged", ",", "this", ")", ")", ";", "// add idle even listener on the map", "google", ".", "maps", ".", "event", ".", "addListener", "(", "this", ".", "map", ",", "'idle'", ",", "$", ".", "proxy", "(", "this", ".", "mapIdle", ",", "this", ")", ")", ";", "google", ".", "maps", ".", "event", ".", "addListener", "(", "this", ".", "map", ",", "'zoom_changed'", ",", "$", ".", "proxy", "(", "this", ".", "mapZoomed", ",", "this", ")", ")", ";", "}" ]
Initialize the map but only if the option `map` was set. This will create a `map` within the given container using the provided `mapOptions` or link to the existing map instance.
[ "Initialize", "the", "map", "but", "only", "if", "the", "option", "map", "was", "set", ".", "This", "will", "create", "a", "map", "within", "the", "given", "container", "using", "the", "provided", "mapOptions", "or", "link", "to", "the", "existing", "map", "instance", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L116-L155
15,335
ubilabs/geocomplete
jquery.geocomplete.js
function(){ if (!this.map){ return; } var options = $.extend(this.options.markerOptions, { map: this.map }); if (options.disabled){ return; } this.marker = new google.maps.Marker(options); google.maps.event.addListener( this.marker, 'dragend', $.proxy(this.markerDragged, this) ); }
javascript
function(){ if (!this.map){ return; } var options = $.extend(this.options.markerOptions, { map: this.map }); if (options.disabled){ return; } this.marker = new google.maps.Marker(options); google.maps.event.addListener( this.marker, 'dragend', $.proxy(this.markerDragged, this) ); }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "map", ")", "{", "return", ";", "}", "var", "options", "=", "$", ".", "extend", "(", "this", ".", "options", ".", "markerOptions", ",", "{", "map", ":", "this", ".", "map", "}", ")", ";", "if", "(", "options", ".", "disabled", ")", "{", "return", ";", "}", "this", ".", "marker", "=", "new", "google", ".", "maps", ".", "Marker", "(", "options", ")", ";", "google", ".", "maps", ".", "event", ".", "addListener", "(", "this", ".", "marker", ",", "'dragend'", ",", "$", ".", "proxy", "(", "this", ".", "markerDragged", ",", "this", ")", ")", ";", "}" ]
Add a marker with the provided `markerOptions` but only if the option was set. Additionally it listens for the `dragend` event to notify the plugin about changes.
[ "Add", "a", "marker", "with", "the", "provided", "markerOptions", "but", "only", "if", "the", "option", "was", "set", ".", "Additionally", "it", "listens", "for", "the", "dragend", "event", "to", "notify", "the", "plugin", "about", "changes", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L160-L173
15,336
ubilabs/geocomplete
jquery.geocomplete.js
function(){ // Indicates is user did select a result from the dropdown. var selected = false; var options = { types: this.options.types, bounds: this.options.bounds === true ? null : this.options.bounds, componentRestrictions: this.options.componentRestrictions, strictBounds: this.options.strictBounds }; if (this.options.country){ options.componentRestrictions = {country: this.options.country}; } this.autocomplete = new google.maps.places.Autocomplete( this.input, options ); this.geocoder = new google.maps.Geocoder(); // Bind autocomplete to map bounds but only if there is a map // and `options.bindToMap` is set to true. if (this.map && this.options.bounds === true){ this.autocomplete.bindTo('bounds', this.map); } // Watch `place_changed` events on the autocomplete input field. google.maps.event.addListener( this.autocomplete, 'place_changed', $.proxy(this.placeChanged, this) ); // Prevent parent form from being submitted if user hit enter. this.$input.on('keypress.' + this._name, function(event){ if (event.keyCode === 13){ return false; } }); // Assume that if user types anything after having selected a result, // the selected location is not valid any more. if (this.options.geocodeAfterResult === true){ this.$input.bind('keypress.' + this._name, $.proxy(function(){ if (event.keyCode != 9 && this.selected === true){ this.selected = false; } }, this)); } // Listen for "geocode" events and trigger find action. this.$input.bind('geocode.' + this._name, $.proxy(function(){ this.find(); }, this)); // Saves the previous input value this.$input.bind('geocode:result.' + this._name, $.proxy(function(){ this.lastInputVal = this.$input.val(); }, this)); // Trigger find action when input element is blurred out and user has // not explicitly selected a result. // (Useful for typing partial location and tabbing to the next field // or clicking somewhere else.) if (this.options.blur === true){ this.$input.on('blur.' + this._name, $.proxy(function(){ if (this.options.geocodeAfterResult === true && this.selected === true) { return; } if (this.options.restoreValueAfterBlur === true && this.selected === true) { setTimeout($.proxy(this.restoreLastValue, this), 0); } else { this.find(); } }, this)); } }
javascript
function(){ // Indicates is user did select a result from the dropdown. var selected = false; var options = { types: this.options.types, bounds: this.options.bounds === true ? null : this.options.bounds, componentRestrictions: this.options.componentRestrictions, strictBounds: this.options.strictBounds }; if (this.options.country){ options.componentRestrictions = {country: this.options.country}; } this.autocomplete = new google.maps.places.Autocomplete( this.input, options ); this.geocoder = new google.maps.Geocoder(); // Bind autocomplete to map bounds but only if there is a map // and `options.bindToMap` is set to true. if (this.map && this.options.bounds === true){ this.autocomplete.bindTo('bounds', this.map); } // Watch `place_changed` events on the autocomplete input field. google.maps.event.addListener( this.autocomplete, 'place_changed', $.proxy(this.placeChanged, this) ); // Prevent parent form from being submitted if user hit enter. this.$input.on('keypress.' + this._name, function(event){ if (event.keyCode === 13){ return false; } }); // Assume that if user types anything after having selected a result, // the selected location is not valid any more. if (this.options.geocodeAfterResult === true){ this.$input.bind('keypress.' + this._name, $.proxy(function(){ if (event.keyCode != 9 && this.selected === true){ this.selected = false; } }, this)); } // Listen for "geocode" events and trigger find action. this.$input.bind('geocode.' + this._name, $.proxy(function(){ this.find(); }, this)); // Saves the previous input value this.$input.bind('geocode:result.' + this._name, $.proxy(function(){ this.lastInputVal = this.$input.val(); }, this)); // Trigger find action when input element is blurred out and user has // not explicitly selected a result. // (Useful for typing partial location and tabbing to the next field // or clicking somewhere else.) if (this.options.blur === true){ this.$input.on('blur.' + this._name, $.proxy(function(){ if (this.options.geocodeAfterResult === true && this.selected === true) { return; } if (this.options.restoreValueAfterBlur === true && this.selected === true) { setTimeout($.proxy(this.restoreLastValue, this), 0); } else { this.find(); } }, this)); } }
[ "function", "(", ")", "{", "// Indicates is user did select a result from the dropdown.", "var", "selected", "=", "false", ";", "var", "options", "=", "{", "types", ":", "this", ".", "options", ".", "types", ",", "bounds", ":", "this", ".", "options", ".", "bounds", "===", "true", "?", "null", ":", "this", ".", "options", ".", "bounds", ",", "componentRestrictions", ":", "this", ".", "options", ".", "componentRestrictions", ",", "strictBounds", ":", "this", ".", "options", ".", "strictBounds", "}", ";", "if", "(", "this", ".", "options", ".", "country", ")", "{", "options", ".", "componentRestrictions", "=", "{", "country", ":", "this", ".", "options", ".", "country", "}", ";", "}", "this", ".", "autocomplete", "=", "new", "google", ".", "maps", ".", "places", ".", "Autocomplete", "(", "this", ".", "input", ",", "options", ")", ";", "this", ".", "geocoder", "=", "new", "google", ".", "maps", ".", "Geocoder", "(", ")", ";", "// Bind autocomplete to map bounds but only if there is a map", "// and `options.bindToMap` is set to true.", "if", "(", "this", ".", "map", "&&", "this", ".", "options", ".", "bounds", "===", "true", ")", "{", "this", ".", "autocomplete", ".", "bindTo", "(", "'bounds'", ",", "this", ".", "map", ")", ";", "}", "// Watch `place_changed` events on the autocomplete input field.", "google", ".", "maps", ".", "event", ".", "addListener", "(", "this", ".", "autocomplete", ",", "'place_changed'", ",", "$", ".", "proxy", "(", "this", ".", "placeChanged", ",", "this", ")", ")", ";", "// Prevent parent form from being submitted if user hit enter.", "this", ".", "$input", ".", "on", "(", "'keypress.'", "+", "this", ".", "_name", ",", "function", "(", "event", ")", "{", "if", "(", "event", ".", "keyCode", "===", "13", ")", "{", "return", "false", ";", "}", "}", ")", ";", "// Assume that if user types anything after having selected a result,", "// the selected location is not valid any more.", "if", "(", "this", ".", "options", ".", "geocodeAfterResult", "===", "true", ")", "{", "this", ".", "$input", ".", "bind", "(", "'keypress.'", "+", "this", ".", "_name", ",", "$", ".", "proxy", "(", "function", "(", ")", "{", "if", "(", "event", ".", "keyCode", "!=", "9", "&&", "this", ".", "selected", "===", "true", ")", "{", "this", ".", "selected", "=", "false", ";", "}", "}", ",", "this", ")", ")", ";", "}", "// Listen for \"geocode\" events and trigger find action.", "this", ".", "$input", ".", "bind", "(", "'geocode.'", "+", "this", ".", "_name", ",", "$", ".", "proxy", "(", "function", "(", ")", "{", "this", ".", "find", "(", ")", ";", "}", ",", "this", ")", ")", ";", "// Saves the previous input value", "this", ".", "$input", ".", "bind", "(", "'geocode:result.'", "+", "this", ".", "_name", ",", "$", ".", "proxy", "(", "function", "(", ")", "{", "this", ".", "lastInputVal", "=", "this", ".", "$input", ".", "val", "(", ")", ";", "}", ",", "this", ")", ")", ";", "// Trigger find action when input element is blurred out and user has", "// not explicitly selected a result.", "// (Useful for typing partial location and tabbing to the next field", "// or clicking somewhere else.)", "if", "(", "this", ".", "options", ".", "blur", "===", "true", ")", "{", "this", ".", "$input", ".", "on", "(", "'blur.'", "+", "this", ".", "_name", ",", "$", ".", "proxy", "(", "function", "(", ")", "{", "if", "(", "this", ".", "options", ".", "geocodeAfterResult", "===", "true", "&&", "this", ".", "selected", "===", "true", ")", "{", "return", ";", "}", "if", "(", "this", ".", "options", ".", "restoreValueAfterBlur", "===", "true", "&&", "this", ".", "selected", "===", "true", ")", "{", "setTimeout", "(", "$", ".", "proxy", "(", "this", ".", "restoreLastValue", ",", "this", ")", ",", "0", ")", ";", "}", "else", "{", "this", ".", "find", "(", ")", ";", "}", "}", ",", "this", ")", ")", ";", "}", "}" ]
Associate the input with the autocompleter and create a geocoder to fall back when the autocompleter does not return a value.
[ "Associate", "the", "input", "with", "the", "autocompleter", "and", "create", "a", "geocoder", "to", "fall", "back", "when", "the", "autocompleter", "does", "not", "return", "a", "value", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L177-L252
15,337
ubilabs/geocomplete
jquery.geocomplete.js
function(){ if (!this.options.details){ return; } if(this.options.detailsScope) { var $details = $(this.input).parents(this.options.detailsScope).find(this.options.details); } else { var $details = $(this.options.details); } var attribute = this.options.detailsAttribute, details = {}; function setDetail(value){ details[value] = $details.find("[" + attribute + "=" + value + "]"); } $.each(componentTypes, function(index, key){ setDetail(key); setDetail(key + "_short"); }); $.each(placesDetails, function(index, key){ setDetail(key); }); this.$details = $details; this.details = details; }
javascript
function(){ if (!this.options.details){ return; } if(this.options.detailsScope) { var $details = $(this.input).parents(this.options.detailsScope).find(this.options.details); } else { var $details = $(this.options.details); } var attribute = this.options.detailsAttribute, details = {}; function setDetail(value){ details[value] = $details.find("[" + attribute + "=" + value + "]"); } $.each(componentTypes, function(index, key){ setDetail(key); setDetail(key + "_short"); }); $.each(placesDetails, function(index, key){ setDetail(key); }); this.$details = $details; this.details = details; }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "options", ".", "details", ")", "{", "return", ";", "}", "if", "(", "this", ".", "options", ".", "detailsScope", ")", "{", "var", "$details", "=", "$", "(", "this", ".", "input", ")", ".", "parents", "(", "this", ".", "options", ".", "detailsScope", ")", ".", "find", "(", "this", ".", "options", ".", "details", ")", ";", "}", "else", "{", "var", "$details", "=", "$", "(", "this", ".", "options", ".", "details", ")", ";", "}", "var", "attribute", "=", "this", ".", "options", ".", "detailsAttribute", ",", "details", "=", "{", "}", ";", "function", "setDetail", "(", "value", ")", "{", "details", "[", "value", "]", "=", "$details", ".", "find", "(", "\"[\"", "+", "attribute", "+", "\"=\"", "+", "value", "+", "\"]\"", ")", ";", "}", "$", ".", "each", "(", "componentTypes", ",", "function", "(", "index", ",", "key", ")", "{", "setDetail", "(", "key", ")", ";", "setDetail", "(", "key", "+", "\"_short\"", ")", ";", "}", ")", ";", "$", ".", "each", "(", "placesDetails", ",", "function", "(", "index", ",", "key", ")", "{", "setDetail", "(", "key", ")", ";", "}", ")", ";", "this", ".", "$details", "=", "$details", ";", "this", ".", "details", "=", "details", ";", "}" ]
Prepare a given DOM structure to be populated when we got some data. This will cycle through the list of component types and map the corresponding elements.
[ "Prepare", "a", "given", "DOM", "structure", "to", "be", "populated", "when", "we", "got", "some", "data", ".", "This", "will", "cycle", "through", "the", "list", "of", "component", "types", "and", "map", "the", "corresponding", "elements", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L257-L284
15,338
ubilabs/geocomplete
jquery.geocomplete.js
function() { var location = this.options.location, latLng; if (!location) { return; } if (typeof location == 'string') { this.find(location); return; } if (location instanceof Array) { latLng = new google.maps.LatLng(location[0], location[1]); } if (location instanceof google.maps.LatLng){ latLng = location; } if (latLng){ if (this.map){ this.map.setCenter(latLng); } if (this.marker){ this.marker.setPosition(latLng); } } }
javascript
function() { var location = this.options.location, latLng; if (!location) { return; } if (typeof location == 'string') { this.find(location); return; } if (location instanceof Array) { latLng = new google.maps.LatLng(location[0], location[1]); } if (location instanceof google.maps.LatLng){ latLng = location; } if (latLng){ if (this.map){ this.map.setCenter(latLng); } if (this.marker){ this.marker.setPosition(latLng); } } }
[ "function", "(", ")", "{", "var", "location", "=", "this", ".", "options", ".", "location", ",", "latLng", ";", "if", "(", "!", "location", ")", "{", "return", ";", "}", "if", "(", "typeof", "location", "==", "'string'", ")", "{", "this", ".", "find", "(", "location", ")", ";", "return", ";", "}", "if", "(", "location", "instanceof", "Array", ")", "{", "latLng", "=", "new", "google", ".", "maps", ".", "LatLng", "(", "location", "[", "0", "]", ",", "location", "[", "1", "]", ")", ";", "}", "if", "(", "location", "instanceof", "google", ".", "maps", ".", "LatLng", ")", "{", "latLng", "=", "location", ";", "}", "if", "(", "latLng", ")", "{", "if", "(", "this", ".", "map", ")", "{", "this", ".", "map", ".", "setCenter", "(", "latLng", ")", ";", "}", "if", "(", "this", ".", "marker", ")", "{", "this", ".", "marker", ".", "setPosition", "(", "latLng", ")", ";", "}", "}", "}" ]
Set the initial location of the plugin if the `location` options was set. This method will care about converting the value into the right format.
[ "Set", "the", "initial", "location", "of", "the", "plugin", "if", "the", "location", "options", "was", "set", ".", "This", "method", "will", "care", "about", "converting", "the", "value", "into", "the", "right", "format", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L288-L311
15,339
ubilabs/geocomplete
jquery.geocomplete.js
function(request){ // Don't geocode if the requested address is empty if (!request.address) { return; } if (this.options.bounds && !request.bounds){ if (this.options.bounds === true){ request.bounds = this.map && this.map.getBounds(); } else { request.bounds = this.options.bounds; } } if (this.options.country){ request.region = this.options.country; } this.geocoder.geocode(request, $.proxy(this.handleGeocode, this)); }
javascript
function(request){ // Don't geocode if the requested address is empty if (!request.address) { return; } if (this.options.bounds && !request.bounds){ if (this.options.bounds === true){ request.bounds = this.map && this.map.getBounds(); } else { request.bounds = this.options.bounds; } } if (this.options.country){ request.region = this.options.country; } this.geocoder.geocode(request, $.proxy(this.handleGeocode, this)); }
[ "function", "(", "request", ")", "{", "// Don't geocode if the requested address is empty", "if", "(", "!", "request", ".", "address", ")", "{", "return", ";", "}", "if", "(", "this", ".", "options", ".", "bounds", "&&", "!", "request", ".", "bounds", ")", "{", "if", "(", "this", ".", "options", ".", "bounds", "===", "true", ")", "{", "request", ".", "bounds", "=", "this", ".", "map", "&&", "this", ".", "map", ".", "getBounds", "(", ")", ";", "}", "else", "{", "request", ".", "bounds", "=", "this", ".", "options", ".", "bounds", ";", "}", "}", "if", "(", "this", ".", "options", ".", "country", ")", "{", "request", ".", "region", "=", "this", ".", "options", ".", "country", ";", "}", "this", ".", "geocoder", ".", "geocode", "(", "request", ",", "$", ".", "proxy", "(", "this", ".", "handleGeocode", ",", "this", ")", ")", ";", "}" ]
Requests details about a given location. Additionally it will bias the requests to the provided bounds.
[ "Requests", "details", "about", "a", "given", "location", ".", "Additionally", "it", "will", "bias", "the", "requests", "to", "the", "provided", "bounds", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L337-L355
15,340
ubilabs/geocomplete
jquery.geocomplete.js
function() { //$(".pac-container").hide(); var selected = ''; // Check if any result is selected. if ($(".pac-item-selected")[0]) { selected = '-selected'; } // Get the first suggestion's text. var $span1 = $(".pac-container:visible .pac-item" + selected + ":first span:nth-child(2)").text(); var $span2 = $(".pac-container:visible .pac-item" + selected + ":first span:nth-child(3)").text(); // Adds the additional information, if available. var firstResult = $span1; if ($span2) { firstResult += " - " + $span2; } this.$input.val(firstResult); return firstResult; }
javascript
function() { //$(".pac-container").hide(); var selected = ''; // Check if any result is selected. if ($(".pac-item-selected")[0]) { selected = '-selected'; } // Get the first suggestion's text. var $span1 = $(".pac-container:visible .pac-item" + selected + ":first span:nth-child(2)").text(); var $span2 = $(".pac-container:visible .pac-item" + selected + ":first span:nth-child(3)").text(); // Adds the additional information, if available. var firstResult = $span1; if ($span2) { firstResult += " - " + $span2; } this.$input.val(firstResult); return firstResult; }
[ "function", "(", ")", "{", "//$(\".pac-container\").hide();", "var", "selected", "=", "''", ";", "// Check if any result is selected.", "if", "(", "$", "(", "\".pac-item-selected\"", ")", "[", "0", "]", ")", "{", "selected", "=", "'-selected'", ";", "}", "// Get the first suggestion's text.", "var", "$span1", "=", "$", "(", "\".pac-container:visible .pac-item\"", "+", "selected", "+", "\":first span:nth-child(2)\"", ")", ".", "text", "(", ")", ";", "var", "$span2", "=", "$", "(", "\".pac-container:visible .pac-item\"", "+", "selected", "+", "\":first span:nth-child(3)\"", ")", ".", "text", "(", ")", ";", "// Adds the additional information, if available.", "var", "firstResult", "=", "$span1", ";", "if", "(", "$span2", ")", "{", "firstResult", "+=", "\" - \"", "+", "$span2", ";", "}", "this", ".", "$input", ".", "val", "(", "firstResult", ")", ";", "return", "firstResult", ";", "}" ]
Get the selected result. If no result is selected on the list, then get the first result from the list.
[ "Get", "the", "selected", "result", ".", "If", "no", "result", "is", "selected", "on", "the", "list", "then", "get", "the", "first", "result", "from", "the", "list", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L359-L381
15,341
ubilabs/geocomplete
jquery.geocomplete.js
function(geometry){ if (geometry.viewport){ this.map.fitBounds(geometry.viewport); if (this.map.getZoom() > this.options.maxZoom){ this.map.setZoom(this.options.maxZoom); } } else { this.map.setZoom(this.options.maxZoom); this.map.setCenter(geometry.location); } if (this.marker){ this.marker.setPosition(geometry.location); this.marker.setAnimation(this.options.markerOptions.animation); } }
javascript
function(geometry){ if (geometry.viewport){ this.map.fitBounds(geometry.viewport); if (this.map.getZoom() > this.options.maxZoom){ this.map.setZoom(this.options.maxZoom); } } else { this.map.setZoom(this.options.maxZoom); this.map.setCenter(geometry.location); } if (this.marker){ this.marker.setPosition(geometry.location); this.marker.setAnimation(this.options.markerOptions.animation); } }
[ "function", "(", "geometry", ")", "{", "if", "(", "geometry", ".", "viewport", ")", "{", "this", ".", "map", ".", "fitBounds", "(", "geometry", ".", "viewport", ")", ";", "if", "(", "this", ".", "map", ".", "getZoom", "(", ")", ">", "this", ".", "options", ".", "maxZoom", ")", "{", "this", ".", "map", ".", "setZoom", "(", "this", ".", "options", ".", "maxZoom", ")", ";", "}", "}", "else", "{", "this", ".", "map", ".", "setZoom", "(", "this", ".", "options", ".", "maxZoom", ")", ";", "this", ".", "map", ".", "setCenter", "(", "geometry", ".", "location", ")", ";", "}", "if", "(", "this", ".", "marker", ")", "{", "this", ".", "marker", ".", "setPosition", "(", "geometry", ".", "location", ")", ";", "this", ".", "marker", ".", "setAnimation", "(", "this", ".", "options", ".", "markerOptions", ".", "animation", ")", ";", "}", "}" ]
Set the map to a new center by passing a `geometry`. If the geometry has a viewport, the map zooms out to fit the bounds. Additionally it updates the marker position.
[ "Set", "the", "map", "to", "a", "new", "center", "by", "passing", "a", "geometry", ".", "If", "the", "geometry", "has", "a", "viewport", "the", "map", "zooms", "out", "to", "fit", "the", "bounds", ".", "Additionally", "it", "updates", "the", "marker", "position", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L414-L429
15,342
ubilabs/geocomplete
jquery.geocomplete.js
function(result){ var data = {}, geometry = result.geometry, viewport = geometry.viewport, bounds = geometry.bounds; // Create a simplified version of the address components. $.each(result.address_components, function(index, object){ var name = object.types[0]; $.each(object.types, function(index, name){ data[name] = object.long_name; data[name + "_short"] = object.short_name; }); }); // Add properties of the places details. $.each(placesDetails, function(index, key){ data[key] = result[key]; }); // Add infos about the address and geometry. $.extend(data, { formatted_address: result.formatted_address, location_type: geometry.location_type || "PLACES", viewport: viewport, bounds: bounds, location: geometry.location, lat: geometry.location.lat(), lng: geometry.location.lng() }); // Set the values for all details. $.each(this.details, $.proxy(function(key, $detail){ var value = data[key]; this.setDetail($detail, value); }, this)); this.data = data; }
javascript
function(result){ var data = {}, geometry = result.geometry, viewport = geometry.viewport, bounds = geometry.bounds; // Create a simplified version of the address components. $.each(result.address_components, function(index, object){ var name = object.types[0]; $.each(object.types, function(index, name){ data[name] = object.long_name; data[name + "_short"] = object.short_name; }); }); // Add properties of the places details. $.each(placesDetails, function(index, key){ data[key] = result[key]; }); // Add infos about the address and geometry. $.extend(data, { formatted_address: result.formatted_address, location_type: geometry.location_type || "PLACES", viewport: viewport, bounds: bounds, location: geometry.location, lat: geometry.location.lat(), lng: geometry.location.lng() }); // Set the values for all details. $.each(this.details, $.proxy(function(key, $detail){ var value = data[key]; this.setDetail($detail, value); }, this)); this.data = data; }
[ "function", "(", "result", ")", "{", "var", "data", "=", "{", "}", ",", "geometry", "=", "result", ".", "geometry", ",", "viewport", "=", "geometry", ".", "viewport", ",", "bounds", "=", "geometry", ".", "bounds", ";", "// Create a simplified version of the address components.", "$", ".", "each", "(", "result", ".", "address_components", ",", "function", "(", "index", ",", "object", ")", "{", "var", "name", "=", "object", ".", "types", "[", "0", "]", ";", "$", ".", "each", "(", "object", ".", "types", ",", "function", "(", "index", ",", "name", ")", "{", "data", "[", "name", "]", "=", "object", ".", "long_name", ";", "data", "[", "name", "+", "\"_short\"", "]", "=", "object", ".", "short_name", ";", "}", ")", ";", "}", ")", ";", "// Add properties of the places details.", "$", ".", "each", "(", "placesDetails", ",", "function", "(", "index", ",", "key", ")", "{", "data", "[", "key", "]", "=", "result", "[", "key", "]", ";", "}", ")", ";", "// Add infos about the address and geometry.", "$", ".", "extend", "(", "data", ",", "{", "formatted_address", ":", "result", ".", "formatted_address", ",", "location_type", ":", "geometry", ".", "location_type", "||", "\"PLACES\"", ",", "viewport", ":", "viewport", ",", "bounds", ":", "bounds", ",", "location", ":", "geometry", ".", "location", ",", "lat", ":", "geometry", ".", "location", ".", "lat", "(", ")", ",", "lng", ":", "geometry", ".", "location", ".", "lng", "(", ")", "}", ")", ";", "// Set the values for all details.", "$", ".", "each", "(", "this", ".", "details", ",", "$", ".", "proxy", "(", "function", "(", "key", ",", "$detail", ")", "{", "var", "value", "=", "data", "[", "key", "]", ";", "this", ".", "setDetail", "(", "$detail", ",", "value", ")", ";", "}", ",", "this", ")", ")", ";", "this", ".", "data", "=", "data", ";", "}" ]
Populate the provided elements with new `result` data. This will lookup all elements that has an attribute with the given component type.
[ "Populate", "the", "provided", "elements", "with", "new", "result", "data", ".", "This", "will", "lookup", "all", "elements", "that", "has", "an", "attribute", "with", "the", "given", "component", "type", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L449-L489
15,343
ubilabs/geocomplete
jquery.geocomplete.js
function(){ this.marker.setPosition(this.data.location); this.setDetail(this.details.lat, this.data.location.lat()); this.setDetail(this.details.lng, this.data.location.lng()); }
javascript
function(){ this.marker.setPosition(this.data.location); this.setDetail(this.details.lat, this.data.location.lat()); this.setDetail(this.details.lng, this.data.location.lng()); }
[ "function", "(", ")", "{", "this", ".", "marker", ".", "setPosition", "(", "this", ".", "data", ".", "location", ")", ";", "this", ".", "setDetail", "(", "this", ".", "details", ".", "lat", ",", "this", ".", "data", ".", "location", ".", "lat", "(", ")", ")", ";", "this", ".", "setDetail", "(", "this", ".", "details", ".", "lng", ",", "this", ".", "data", ".", "location", ".", "lng", "(", ")", ")", ";", "}" ]
Restore the old position of the marker to the last knwon location.
[ "Restore", "the", "old", "position", "of", "the", "marker", "to", "the", "last", "knwon", "location", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L533-L537
15,344
ubilabs/geocomplete
jquery.geocomplete.js
function(){ var place = this.autocomplete.getPlace(); this.selected = true; if (!place.geometry){ if (this.options.autoselect) { // Automatically selects the highlighted item or the first item from the // suggestions list. var autoSelection = this.selectFirstResult(); this.find(autoSelection); } } else { // Use the input text if it already gives geometry. this.update(place); } }
javascript
function(){ var place = this.autocomplete.getPlace(); this.selected = true; if (!place.geometry){ if (this.options.autoselect) { // Automatically selects the highlighted item or the first item from the // suggestions list. var autoSelection = this.selectFirstResult(); this.find(autoSelection); } } else { // Use the input text if it already gives geometry. this.update(place); } }
[ "function", "(", ")", "{", "var", "place", "=", "this", ".", "autocomplete", ".", "getPlace", "(", ")", ";", "this", ".", "selected", "=", "true", ";", "if", "(", "!", "place", ".", "geometry", ")", "{", "if", "(", "this", ".", "options", ".", "autoselect", ")", "{", "// Automatically selects the highlighted item or the first item from the", "// suggestions list.", "var", "autoSelection", "=", "this", ".", "selectFirstResult", "(", ")", ";", "this", ".", "find", "(", "autoSelection", ")", ";", "}", "}", "else", "{", "// Use the input text if it already gives geometry.", "this", ".", "update", "(", "place", ")", ";", "}", "}" ]
Update the plugin after the user has selected an autocomplete entry. If the place has no geometry it passes it to the geocoder.
[ "Update", "the", "plugin", "after", "the", "user", "has", "selected", "an", "autocomplete", "entry", ".", "If", "the", "place", "has", "no", "geometry", "it", "passes", "it", "to", "the", "geocoder", "." ]
7ce2f83ac4b621b6816f85eaede8f03595e58c9a
https://github.com/ubilabs/geocomplete/blob/7ce2f83ac4b621b6816f85eaede8f03595e58c9a/jquery.geocomplete.js#L541-L556
15,345
assemble/assemble
support/docs/src/assets/js/docs.js
function(req, res) { if (!searchIdx) return res(); var results = searchIdx.search(req.term) .map(function(result) { return { label: files[result.ref].title, value: files[result.ref] }; }); res(results); }
javascript
function(req, res) { if (!searchIdx) return res(); var results = searchIdx.search(req.term) .map(function(result) { return { label: files[result.ref].title, value: files[result.ref] }; }); res(results); }
[ "function", "(", "req", ",", "res", ")", "{", "if", "(", "!", "searchIdx", ")", "return", "res", "(", ")", ";", "var", "results", "=", "searchIdx", ".", "search", "(", "req", ".", "term", ")", ".", "map", "(", "function", "(", "result", ")", "{", "return", "{", "label", ":", "files", "[", "result", ".", "ref", "]", ".", "title", ",", "value", ":", "files", "[", "result", ".", "ref", "]", "}", ";", "}", ")", ";", "res", "(", "results", ")", ";", "}" ]
use lunr search index to find a page based on specified search term
[ "use", "lunr", "search", "index", "to", "find", "a", "page", "based", "on", "specified", "search", "term" ]
b5053ee061151e3850580606df525766b4b97357
https://github.com/assemble/assemble/blob/b5053ee061151e3850580606df525766b4b97357/support/docs/src/assets/js/docs.js#L85-L96
15,346
assemble/assemble
support/docs/src/assets/js/docs.js
function(event, ui) { search.val(''); window.location = ui.item.value.url.replace('_gh_pages', ''); return false; }
javascript
function(event, ui) { search.val(''); window.location = ui.item.value.url.replace('_gh_pages', ''); return false; }
[ "function", "(", "event", ",", "ui", ")", "{", "search", ".", "val", "(", "''", ")", ";", "window", ".", "location", "=", "ui", ".", "item", ".", "value", ".", "url", ".", "replace", "(", "'_gh_pages'", ",", "''", ")", ";", "return", "false", ";", "}" ]
when selected, clear the sarch box and navigate to the selected page
[ "when", "selected", "clear", "the", "sarch", "box", "and", "navigate", "to", "the", "selected", "page" ]
b5053ee061151e3850580606df525766b4b97357
https://github.com/assemble/assemble/blob/b5053ee061151e3850580606df525766b4b97357/support/docs/src/assets/js/docs.js#L104-L108
15,347
assemble/assemble
examples/drafts-plugin/index.js
plugin
function plugin(name) { return function(app) { var files = app.getViews(name); for (var file in files) { if (files[file].data.draft) delete files[file]; } }; }
javascript
function plugin(name) { return function(app) { var files = app.getViews(name); for (var file in files) { if (files[file].data.draft) delete files[file]; } }; }
[ "function", "plugin", "(", "name", ")", "{", "return", "function", "(", "app", ")", "{", "var", "files", "=", "app", ".", "getViews", "(", "name", ")", ";", "for", "(", "var", "file", "in", "files", ")", "{", "if", "(", "files", "[", "file", "]", ".", "data", ".", "draft", ")", "delete", "files", "[", "file", "]", ";", "}", "}", ";", "}" ]
Assemble plugin to remove files marked as `draft` from a collection. @return {Function}
[ "Assemble", "plugin", "to", "remove", "files", "marked", "as", "draft", "from", "a", "collection", "." ]
b5053ee061151e3850580606df525766b4b97357
https://github.com/assemble/assemble/blob/b5053ee061151e3850580606df525766b4b97357/examples/drafts-plugin/index.js#L14-L21
15,348
assemble/assemble
bin/cli.js
handleError
function handleError(err) { if (typeof err === 'string' && errors[err]) { console.error(errors[err]); } else { if (argv.verbose) { console.error(err.stack); } else { console.error(err.message); } } process.exit(1); }
javascript
function handleError(err) { if (typeof err === 'string' && errors[err]) { console.error(errors[err]); } else { if (argv.verbose) { console.error(err.stack); } else { console.error(err.message); } } process.exit(1); }
[ "function", "handleError", "(", "err", ")", "{", "if", "(", "typeof", "err", "===", "'string'", "&&", "errors", "[", "err", "]", ")", "{", "console", ".", "error", "(", "errors", "[", "err", "]", ")", ";", "}", "else", "{", "if", "(", "argv", ".", "verbose", ")", "{", "console", ".", "error", "(", "err", ".", "stack", ")", ";", "}", "else", "{", "console", ".", "error", "(", "err", ".", "message", ")", ";", "}", "}", "process", ".", "exit", "(", "1", ")", ";", "}" ]
Handle CLI errors
[ "Handle", "CLI", "errors" ]
b5053ee061151e3850580606df525766b4b97357
https://github.com/assemble/assemble/blob/b5053ee061151e3850580606df525766b4b97357/bin/cli.js#L160-L171
15,349
assemble/assemble
examples/build-tool/build.js
concat
function concat(app) { var files = app.views.files; var css = ''; for (var file in files) { if ('.css' != path.extname(file)) continue; css += files[file].contents.toString(); delete files[file]; } css = myth(css); app.files.addView('index.css', { contents: new Buffer(css) }); }
javascript
function concat(app) { var files = app.views.files; var css = ''; for (var file in files) { if ('.css' != path.extname(file)) continue; css += files[file].contents.toString(); delete files[file]; } css = myth(css); app.files.addView('index.css', { contents: new Buffer(css) }); }
[ "function", "concat", "(", "app", ")", "{", "var", "files", "=", "app", ".", "views", ".", "files", ";", "var", "css", "=", "''", ";", "for", "(", "var", "file", "in", "files", ")", "{", "if", "(", "'.css'", "!=", "path", ".", "extname", "(", "file", ")", ")", "continue", ";", "css", "+=", "files", "[", "file", "]", ".", "contents", ".", "toString", "(", ")", ";", "delete", "files", "[", "file", "]", ";", "}", "css", "=", "myth", "(", "css", ")", ";", "app", ".", "files", ".", "addView", "(", "'index.css'", ",", "{", "contents", ":", "new", "Buffer", "(", "css", ")", "}", ")", ";", "}" ]
Concat plugin. @param {Object} `app` Assemble instance
[ "Concat", "plugin", "." ]
b5053ee061151e3850580606df525766b4b97357
https://github.com/assemble/assemble/blob/b5053ee061151e3850580606df525766b4b97357/examples/build-tool/build.js#L23-L37
15,350
assemble/assemble
examples/boilerplate/assemblefile.js
rename
function rename(files) { return function(file) { var base = path.relative(path.resolve(file.cwd), file.base); var destBase = files.options.destBase; file.dirname = path.resolve(path.join(destBase, base)); return file.base; }; }
javascript
function rename(files) { return function(file) { var base = path.relative(path.resolve(file.cwd), file.base); var destBase = files.options.destBase; file.dirname = path.resolve(path.join(destBase, base)); return file.base; }; }
[ "function", "rename", "(", "files", ")", "{", "return", "function", "(", "file", ")", "{", "var", "base", "=", "path", ".", "relative", "(", "path", ".", "resolve", "(", "file", ".", "cwd", ")", ",", "file", ".", "base", ")", ";", "var", "destBase", "=", "files", ".", "options", ".", "destBase", ";", "file", ".", "dirname", "=", "path", ".", "resolve", "(", "path", ".", "join", "(", "destBase", ",", "base", ")", ")", ";", "return", "file", ".", "base", ";", "}", ";", "}" ]
Custom rename function
[ "Custom", "rename", "function" ]
b5053ee061151e3850580606df525766b4b97357
https://github.com/assemble/assemble/blob/b5053ee061151e3850580606df525766b4b97357/examples/boilerplate/assemblefile.js#L84-L91
15,351
assemble/assemble
index.js
Assemble
function Assemble(options) { if (!(this instanceof Assemble)) { return new Assemble(options); } Core.call(this, options); this.is('assemble'); this.initAssemble(); }
javascript
function Assemble(options) { if (!(this instanceof Assemble)) { return new Assemble(options); } Core.call(this, options); this.is('assemble'); this.initAssemble(); }
[ "function", "Assemble", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Assemble", ")", ")", "{", "return", "new", "Assemble", "(", "options", ")", ";", "}", "Core", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "is", "(", "'assemble'", ")", ";", "this", ".", "initAssemble", "(", ")", ";", "}" ]
Create an `assemble` app. This is the main function exported by the assemble module. ```js var assemble = require('assemble'); var app = assemble(); ``` @param {Object} `options` Optionally pass default options to use. @api public
[ "Create", "an", "assemble", "app", ".", "This", "is", "the", "main", "function", "exported", "by", "the", "assemble", "module", "." ]
b5053ee061151e3850580606df525766b4b97357
https://github.com/assemble/assemble/blob/b5053ee061151e3850580606df525766b4b97357/index.js#L24-L31
15,352
assemble/assemble
examples/project-generator/build.js
ask
function ask(cb) { return function(app) { app.use(store('smithy')) .use(questions()) .ask(function(err, answers) { if (err) return cb(err); cb.call(app, null, answers); }); app.asyncHelper('ask', function(key, options, cb) { app.questions.options.force = true; app.ask(key, function(err, res) { if (err) return cb(err); cb(null, res[key]); }); }); }; }
javascript
function ask(cb) { return function(app) { app.use(store('smithy')) .use(questions()) .ask(function(err, answers) { if (err) return cb(err); cb.call(app, null, answers); }); app.asyncHelper('ask', function(key, options, cb) { app.questions.options.force = true; app.ask(key, function(err, res) { if (err) return cb(err); cb(null, res[key]); }); }); }; }
[ "function", "ask", "(", "cb", ")", "{", "return", "function", "(", "app", ")", "{", "app", ".", "use", "(", "store", "(", "'smithy'", ")", ")", ".", "use", "(", "questions", "(", ")", ")", ".", "ask", "(", "function", "(", "err", ",", "answers", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "cb", ".", "call", "(", "app", ",", "null", ",", "answers", ")", ";", "}", ")", ";", "app", ".", "asyncHelper", "(", "'ask'", ",", "function", "(", "key", ",", "options", ",", "cb", ")", "{", "app", ".", "questions", ".", "options", ".", "force", "=", "true", ";", "app", ".", "ask", "(", "key", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "cb", "(", "null", ",", "res", "[", "key", "]", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "}" ]
Customize the base-questions plugin
[ "Customize", "the", "base", "-", "questions", "plugin" ]
b5053ee061151e3850580606df525766b4b97357
https://github.com/assemble/assemble/blob/b5053ee061151e3850580606df525766b4b97357/examples/project-generator/build.js#L23-L41
15,353
digicorp/propeller
components/range-slider/js/wNumb.js
throwEqualError
function throwEqualError( F, a, b ) { if ( (F[a] || F[b]) && (F[a] === F[b]) ) { throw new Error(a); } }
javascript
function throwEqualError( F, a, b ) { if ( (F[a] || F[b]) && (F[a] === F[b]) ) { throw new Error(a); } }
[ "function", "throwEqualError", "(", "F", ",", "a", ",", "b", ")", "{", "if", "(", "(", "F", "[", "a", "]", "||", "F", "[", "b", "]", ")", "&&", "(", "F", "[", "a", "]", "===", "F", "[", "b", "]", ")", ")", "{", "throw", "new", "Error", "(", "a", ")", ";", "}", "}" ]
Throw an error if formatting options are incompatible.
[ "Throw", "an", "error", "if", "formatting", "options", "are", "incompatible", "." ]
151155570d9d975e16811aabc3c47e84eaeec661
https://github.com/digicorp/propeller/blob/151155570d9d975e16811aabc3c47e84eaeec661/components/range-slider/js/wNumb.js#L38-L42
15,354
digicorp/propeller
components/range-slider/js/wNumb.js
toFixed
function toFixed ( value, decimals ) { var scale = Math.pow(10, decimals); return ( Math.round(value * scale) / scale).toFixed( decimals ); }
javascript
function toFixed ( value, decimals ) { var scale = Math.pow(10, decimals); return ( Math.round(value * scale) / scale).toFixed( decimals ); }
[ "function", "toFixed", "(", "value", ",", "decimals", ")", "{", "var", "scale", "=", "Math", ".", "pow", "(", "10", ",", "decimals", ")", ";", "return", "(", "Math", ".", "round", "(", "value", "*", "scale", ")", "/", "scale", ")", ".", "toFixed", "(", "decimals", ")", ";", "}" ]
Provide rounding-accurate toFixed method.
[ "Provide", "rounding", "-", "accurate", "toFixed", "method", "." ]
151155570d9d975e16811aabc3c47e84eaeec661
https://github.com/digicorp/propeller/blob/151155570d9d975e16811aabc3c47e84eaeec661/components/range-slider/js/wNumb.js#L50-L53
15,355
digicorp/propeller
components/range-slider/js/wNumb.js
formatTo
function formatTo ( decimals, thousand, mark, prefix, postfix, encoder, decoder, negativeBefore, negative, edit, undo, input ) { var originalInput = input, inputIsNegative, inputPieces, inputBase, inputDecimals = '', output = ''; // Apply user encoder to the input. // Expected outcome: number. if ( encoder ) { input = encoder(input); } // Stop if no valid number was provided, the number is infinite or NaN. if ( !isValidNumber(input) ) { return false; } // Rounding away decimals might cause a value of -0 // when using very small ranges. Remove those cases. if ( decimals !== false && parseFloat(input.toFixed(decimals)) === 0 ) { input = 0; } // Formatting is done on absolute numbers, // decorated by an optional negative symbol. if ( input < 0 ) { inputIsNegative = true; input = Math.abs(input); } // Reduce the number of decimals to the specified option. if ( decimals !== false ) { input = toFixed( input, decimals ); } // Transform the number into a string, so it can be split. input = input.toString(); // Break the number on the decimal separator. if ( input.indexOf('.') !== -1 ) { inputPieces = input.split('.'); inputBase = inputPieces[0]; if ( mark ) { inputDecimals = mark + inputPieces[1]; } } else { // If it isn't split, the entire number will do. inputBase = input; } // Group numbers in sets of three. if ( thousand ) { inputBase = strReverse(inputBase).match(/.{1,3}/g); inputBase = strReverse(inputBase.join( strReverse( thousand ) )); } // If the number is negative, prefix with negation symbol. if ( inputIsNegative && negativeBefore ) { output += negativeBefore; } // Prefix the number if ( prefix ) { output += prefix; } // Normal negative option comes after the prefix. Defaults to '-'. if ( inputIsNegative && negative ) { output += negative; } // Append the actual number. output += inputBase; output += inputDecimals; // Apply the postfix. if ( postfix ) { output += postfix; } // Run the output through a user-specified post-formatter. if ( edit ) { output = edit ( output, originalInput ); } // All done. return output; }
javascript
function formatTo ( decimals, thousand, mark, prefix, postfix, encoder, decoder, negativeBefore, negative, edit, undo, input ) { var originalInput = input, inputIsNegative, inputPieces, inputBase, inputDecimals = '', output = ''; // Apply user encoder to the input. // Expected outcome: number. if ( encoder ) { input = encoder(input); } // Stop if no valid number was provided, the number is infinite or NaN. if ( !isValidNumber(input) ) { return false; } // Rounding away decimals might cause a value of -0 // when using very small ranges. Remove those cases. if ( decimals !== false && parseFloat(input.toFixed(decimals)) === 0 ) { input = 0; } // Formatting is done on absolute numbers, // decorated by an optional negative symbol. if ( input < 0 ) { inputIsNegative = true; input = Math.abs(input); } // Reduce the number of decimals to the specified option. if ( decimals !== false ) { input = toFixed( input, decimals ); } // Transform the number into a string, so it can be split. input = input.toString(); // Break the number on the decimal separator. if ( input.indexOf('.') !== -1 ) { inputPieces = input.split('.'); inputBase = inputPieces[0]; if ( mark ) { inputDecimals = mark + inputPieces[1]; } } else { // If it isn't split, the entire number will do. inputBase = input; } // Group numbers in sets of three. if ( thousand ) { inputBase = strReverse(inputBase).match(/.{1,3}/g); inputBase = strReverse(inputBase.join( strReverse( thousand ) )); } // If the number is negative, prefix with negation symbol. if ( inputIsNegative && negativeBefore ) { output += negativeBefore; } // Prefix the number if ( prefix ) { output += prefix; } // Normal negative option comes after the prefix. Defaults to '-'. if ( inputIsNegative && negative ) { output += negative; } // Append the actual number. output += inputBase; output += inputDecimals; // Apply the postfix. if ( postfix ) { output += postfix; } // Run the output through a user-specified post-formatter. if ( edit ) { output = edit ( output, originalInput ); } // All done. return output; }
[ "function", "formatTo", "(", "decimals", ",", "thousand", ",", "mark", ",", "prefix", ",", "postfix", ",", "encoder", ",", "decoder", ",", "negativeBefore", ",", "negative", ",", "edit", ",", "undo", ",", "input", ")", "{", "var", "originalInput", "=", "input", ",", "inputIsNegative", ",", "inputPieces", ",", "inputBase", ",", "inputDecimals", "=", "''", ",", "output", "=", "''", ";", "// Apply user encoder to the input.", "// Expected outcome: number.", "if", "(", "encoder", ")", "{", "input", "=", "encoder", "(", "input", ")", ";", "}", "// Stop if no valid number was provided, the number is infinite or NaN.", "if", "(", "!", "isValidNumber", "(", "input", ")", ")", "{", "return", "false", ";", "}", "// Rounding away decimals might cause a value of -0", "// when using very small ranges. Remove those cases.", "if", "(", "decimals", "!==", "false", "&&", "parseFloat", "(", "input", ".", "toFixed", "(", "decimals", ")", ")", "===", "0", ")", "{", "input", "=", "0", ";", "}", "// Formatting is done on absolute numbers,", "// decorated by an optional negative symbol.", "if", "(", "input", "<", "0", ")", "{", "inputIsNegative", "=", "true", ";", "input", "=", "Math", ".", "abs", "(", "input", ")", ";", "}", "// Reduce the number of decimals to the specified option.", "if", "(", "decimals", "!==", "false", ")", "{", "input", "=", "toFixed", "(", "input", ",", "decimals", ")", ";", "}", "// Transform the number into a string, so it can be split.", "input", "=", "input", ".", "toString", "(", ")", ";", "// Break the number on the decimal separator.", "if", "(", "input", ".", "indexOf", "(", "'.'", ")", "!==", "-", "1", ")", "{", "inputPieces", "=", "input", ".", "split", "(", "'.'", ")", ";", "inputBase", "=", "inputPieces", "[", "0", "]", ";", "if", "(", "mark", ")", "{", "inputDecimals", "=", "mark", "+", "inputPieces", "[", "1", "]", ";", "}", "}", "else", "{", "// If it isn't split, the entire number will do.", "inputBase", "=", "input", ";", "}", "// Group numbers in sets of three.", "if", "(", "thousand", ")", "{", "inputBase", "=", "strReverse", "(", "inputBase", ")", ".", "match", "(", "/", ".{1,3}", "/", "g", ")", ";", "inputBase", "=", "strReverse", "(", "inputBase", ".", "join", "(", "strReverse", "(", "thousand", ")", ")", ")", ";", "}", "// If the number is negative, prefix with negation symbol.", "if", "(", "inputIsNegative", "&&", "negativeBefore", ")", "{", "output", "+=", "negativeBefore", ";", "}", "// Prefix the number", "if", "(", "prefix", ")", "{", "output", "+=", "prefix", ";", "}", "// Normal negative option comes after the prefix. Defaults to '-'.", "if", "(", "inputIsNegative", "&&", "negative", ")", "{", "output", "+=", "negative", ";", "}", "// Append the actual number.", "output", "+=", "inputBase", ";", "output", "+=", "inputDecimals", ";", "// Apply the postfix.", "if", "(", "postfix", ")", "{", "output", "+=", "postfix", ";", "}", "// Run the output through a user-specified post-formatter.", "if", "(", "edit", ")", "{", "output", "=", "edit", "(", "output", ",", "originalInput", ")", ";", "}", "// All done.", "return", "output", ";", "}" ]
Formatting Accept a number as input, output formatted string.
[ "Formatting", "Accept", "a", "number", "as", "input", "output", "formatted", "string", "." ]
151155570d9d975e16811aabc3c47e84eaeec661
https://github.com/digicorp/propeller/blob/151155570d9d975e16811aabc3c47e84eaeec661/components/range-slider/js/wNumb.js#L59-L148
15,356
digicorp/propeller
components/range-slider/js/wNumb.js
formatFrom
function formatFrom ( decimals, thousand, mark, prefix, postfix, encoder, decoder, negativeBefore, negative, edit, undo, input ) { var originalInput = input, inputIsNegative, output = ''; // User defined pre-decoder. Result must be a non empty string. if ( undo ) { input = undo(input); } // Test the input. Can't be empty. if ( !input || typeof input !== 'string' ) { return false; } // If the string starts with the negativeBefore value: remove it. // Remember is was there, the number is negative. if ( negativeBefore && strStartsWith(input, negativeBefore) ) { input = input.replace(negativeBefore, ''); inputIsNegative = true; } // Repeat the same procedure for the prefix. if ( prefix && strStartsWith(input, prefix) ) { input = input.replace(prefix, ''); } // And again for negative. if ( negative && strStartsWith(input, negative) ) { input = input.replace(negative, ''); inputIsNegative = true; } // Remove the postfix. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice if ( postfix && strEndsWith(input, postfix) ) { input = input.slice(0, -1 * postfix.length); } // Remove the thousand grouping. if ( thousand ) { input = input.split(thousand).join(''); } // Set the decimal separator back to period. if ( mark ) { input = input.replace(mark, '.'); } // Prepend the negative symbol. if ( inputIsNegative ) { output += '-'; } // Add the number output += input; // Trim all non-numeric characters (allow '.' and '-'); output = output.replace(/[^0-9\.\-.]/g, ''); // The value contains no parse-able number. if ( output === '' ) { return false; } // Covert to number. output = Number(output); // Run the user-specified post-decoder. if ( decoder ) { output = decoder(output); } // Check is the output is valid, otherwise: return false. if ( !isValidNumber(output) ) { return false; } return output; }
javascript
function formatFrom ( decimals, thousand, mark, prefix, postfix, encoder, decoder, negativeBefore, negative, edit, undo, input ) { var originalInput = input, inputIsNegative, output = ''; // User defined pre-decoder. Result must be a non empty string. if ( undo ) { input = undo(input); } // Test the input. Can't be empty. if ( !input || typeof input !== 'string' ) { return false; } // If the string starts with the negativeBefore value: remove it. // Remember is was there, the number is negative. if ( negativeBefore && strStartsWith(input, negativeBefore) ) { input = input.replace(negativeBefore, ''); inputIsNegative = true; } // Repeat the same procedure for the prefix. if ( prefix && strStartsWith(input, prefix) ) { input = input.replace(prefix, ''); } // And again for negative. if ( negative && strStartsWith(input, negative) ) { input = input.replace(negative, ''); inputIsNegative = true; } // Remove the postfix. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice if ( postfix && strEndsWith(input, postfix) ) { input = input.slice(0, -1 * postfix.length); } // Remove the thousand grouping. if ( thousand ) { input = input.split(thousand).join(''); } // Set the decimal separator back to period. if ( mark ) { input = input.replace(mark, '.'); } // Prepend the negative symbol. if ( inputIsNegative ) { output += '-'; } // Add the number output += input; // Trim all non-numeric characters (allow '.' and '-'); output = output.replace(/[^0-9\.\-.]/g, ''); // The value contains no parse-able number. if ( output === '' ) { return false; } // Covert to number. output = Number(output); // Run the user-specified post-decoder. if ( decoder ) { output = decoder(output); } // Check is the output is valid, otherwise: return false. if ( !isValidNumber(output) ) { return false; } return output; }
[ "function", "formatFrom", "(", "decimals", ",", "thousand", ",", "mark", ",", "prefix", ",", "postfix", ",", "encoder", ",", "decoder", ",", "negativeBefore", ",", "negative", ",", "edit", ",", "undo", ",", "input", ")", "{", "var", "originalInput", "=", "input", ",", "inputIsNegative", ",", "output", "=", "''", ";", "// User defined pre-decoder. Result must be a non empty string.", "if", "(", "undo", ")", "{", "input", "=", "undo", "(", "input", ")", ";", "}", "// Test the input. Can't be empty.", "if", "(", "!", "input", "||", "typeof", "input", "!==", "'string'", ")", "{", "return", "false", ";", "}", "// If the string starts with the negativeBefore value: remove it.", "// Remember is was there, the number is negative.", "if", "(", "negativeBefore", "&&", "strStartsWith", "(", "input", ",", "negativeBefore", ")", ")", "{", "input", "=", "input", ".", "replace", "(", "negativeBefore", ",", "''", ")", ";", "inputIsNegative", "=", "true", ";", "}", "// Repeat the same procedure for the prefix.", "if", "(", "prefix", "&&", "strStartsWith", "(", "input", ",", "prefix", ")", ")", "{", "input", "=", "input", ".", "replace", "(", "prefix", ",", "''", ")", ";", "}", "// And again for negative.", "if", "(", "negative", "&&", "strStartsWith", "(", "input", ",", "negative", ")", ")", "{", "input", "=", "input", ".", "replace", "(", "negative", ",", "''", ")", ";", "inputIsNegative", "=", "true", ";", "}", "// Remove the postfix.", "// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice", "if", "(", "postfix", "&&", "strEndsWith", "(", "input", ",", "postfix", ")", ")", "{", "input", "=", "input", ".", "slice", "(", "0", ",", "-", "1", "*", "postfix", ".", "length", ")", ";", "}", "// Remove the thousand grouping.", "if", "(", "thousand", ")", "{", "input", "=", "input", ".", "split", "(", "thousand", ")", ".", "join", "(", "''", ")", ";", "}", "// Set the decimal separator back to period.", "if", "(", "mark", ")", "{", "input", "=", "input", ".", "replace", "(", "mark", ",", "'.'", ")", ";", "}", "// Prepend the negative symbol.", "if", "(", "inputIsNegative", ")", "{", "output", "+=", "'-'", ";", "}", "// Add the number", "output", "+=", "input", ";", "// Trim all non-numeric characters (allow '.' and '-');", "output", "=", "output", ".", "replace", "(", "/", "[^0-9\\.\\-.]", "/", "g", ",", "''", ")", ";", "// The value contains no parse-able number.", "if", "(", "output", "===", "''", ")", "{", "return", "false", ";", "}", "// Covert to number.", "output", "=", "Number", "(", "output", ")", ";", "// Run the user-specified post-decoder.", "if", "(", "decoder", ")", "{", "output", "=", "decoder", "(", "output", ")", ";", "}", "// Check is the output is valid, otherwise: return false.", "if", "(", "!", "isValidNumber", "(", "output", ")", ")", "{", "return", "false", ";", "}", "return", "output", ";", "}" ]
Accept a sting as input, output decoded number.
[ "Accept", "a", "sting", "as", "input", "output", "decoded", "number", "." ]
151155570d9d975e16811aabc3c47e84eaeec661
https://github.com/digicorp/propeller/blob/151155570d9d975e16811aabc3c47e84eaeec661/components/range-slider/js/wNumb.js#L151-L229
15,357
digicorp/propeller
components/range-slider/js/wNumb.js
validate
function validate ( inputOptions ) { var i, optionName, optionValue, filteredOptions = {}; for ( i = 0; i < FormatOptions.length; i+=1 ) { optionName = FormatOptions[i]; optionValue = inputOptions[optionName]; if ( optionValue === undefined ) { // Only default if negativeBefore isn't set. if ( optionName === 'negative' && !filteredOptions.negativeBefore ) { filteredOptions[optionName] = '-'; // Don't set a default for mark when 'thousand' is set. } else if ( optionName === 'mark' && filteredOptions.thousand !== '.' ) { filteredOptions[optionName] = '.'; } else { filteredOptions[optionName] = false; } // Floating points in JS are stable up to 7 decimals. } else if ( optionName === 'decimals' ) { if ( optionValue >= 0 && optionValue < 8 ) { filteredOptions[optionName] = optionValue; } else { throw new Error(optionName); } // These options, when provided, must be functions. } else if ( optionName === 'encoder' || optionName === 'decoder' || optionName === 'edit' || optionName === 'undo' ) { if ( typeof optionValue === 'function' ) { filteredOptions[optionName] = optionValue; } else { throw new Error(optionName); } // Other options are strings. } else { if ( typeof optionValue === 'string' ) { filteredOptions[optionName] = optionValue; } else { throw new Error(optionName); } } } // Some values can't be extracted from a // string if certain combinations are present. throwEqualError(filteredOptions, 'mark', 'thousand'); throwEqualError(filteredOptions, 'prefix', 'negative'); throwEqualError(filteredOptions, 'prefix', 'negativeBefore'); return filteredOptions; }
javascript
function validate ( inputOptions ) { var i, optionName, optionValue, filteredOptions = {}; for ( i = 0; i < FormatOptions.length; i+=1 ) { optionName = FormatOptions[i]; optionValue = inputOptions[optionName]; if ( optionValue === undefined ) { // Only default if negativeBefore isn't set. if ( optionName === 'negative' && !filteredOptions.negativeBefore ) { filteredOptions[optionName] = '-'; // Don't set a default for mark when 'thousand' is set. } else if ( optionName === 'mark' && filteredOptions.thousand !== '.' ) { filteredOptions[optionName] = '.'; } else { filteredOptions[optionName] = false; } // Floating points in JS are stable up to 7 decimals. } else if ( optionName === 'decimals' ) { if ( optionValue >= 0 && optionValue < 8 ) { filteredOptions[optionName] = optionValue; } else { throw new Error(optionName); } // These options, when provided, must be functions. } else if ( optionName === 'encoder' || optionName === 'decoder' || optionName === 'edit' || optionName === 'undo' ) { if ( typeof optionValue === 'function' ) { filteredOptions[optionName] = optionValue; } else { throw new Error(optionName); } // Other options are strings. } else { if ( typeof optionValue === 'string' ) { filteredOptions[optionName] = optionValue; } else { throw new Error(optionName); } } } // Some values can't be extracted from a // string if certain combinations are present. throwEqualError(filteredOptions, 'mark', 'thousand'); throwEqualError(filteredOptions, 'prefix', 'negative'); throwEqualError(filteredOptions, 'prefix', 'negativeBefore'); return filteredOptions; }
[ "function", "validate", "(", "inputOptions", ")", "{", "var", "i", ",", "optionName", ",", "optionValue", ",", "filteredOptions", "=", "{", "}", ";", "for", "(", "i", "=", "0", ";", "i", "<", "FormatOptions", ".", "length", ";", "i", "+=", "1", ")", "{", "optionName", "=", "FormatOptions", "[", "i", "]", ";", "optionValue", "=", "inputOptions", "[", "optionName", "]", ";", "if", "(", "optionValue", "===", "undefined", ")", "{", "// Only default if negativeBefore isn't set.", "if", "(", "optionName", "===", "'negative'", "&&", "!", "filteredOptions", ".", "negativeBefore", ")", "{", "filteredOptions", "[", "optionName", "]", "=", "'-'", ";", "// Don't set a default for mark when 'thousand' is set.", "}", "else", "if", "(", "optionName", "===", "'mark'", "&&", "filteredOptions", ".", "thousand", "!==", "'.'", ")", "{", "filteredOptions", "[", "optionName", "]", "=", "'.'", ";", "}", "else", "{", "filteredOptions", "[", "optionName", "]", "=", "false", ";", "}", "// Floating points in JS are stable up to 7 decimals.", "}", "else", "if", "(", "optionName", "===", "'decimals'", ")", "{", "if", "(", "optionValue", ">=", "0", "&&", "optionValue", "<", "8", ")", "{", "filteredOptions", "[", "optionName", "]", "=", "optionValue", ";", "}", "else", "{", "throw", "new", "Error", "(", "optionName", ")", ";", "}", "// These options, when provided, must be functions.", "}", "else", "if", "(", "optionName", "===", "'encoder'", "||", "optionName", "===", "'decoder'", "||", "optionName", "===", "'edit'", "||", "optionName", "===", "'undo'", ")", "{", "if", "(", "typeof", "optionValue", "===", "'function'", ")", "{", "filteredOptions", "[", "optionName", "]", "=", "optionValue", ";", "}", "else", "{", "throw", "new", "Error", "(", "optionName", ")", ";", "}", "// Other options are strings.", "}", "else", "{", "if", "(", "typeof", "optionValue", "===", "'string'", ")", "{", "filteredOptions", "[", "optionName", "]", "=", "optionValue", ";", "}", "else", "{", "throw", "new", "Error", "(", "optionName", ")", ";", "}", "}", "}", "// Some values can't be extracted from a", "// string if certain combinations are present.", "throwEqualError", "(", "filteredOptions", ",", "'mark'", ",", "'thousand'", ")", ";", "throwEqualError", "(", "filteredOptions", ",", "'prefix'", ",", "'negative'", ")", ";", "throwEqualError", "(", "filteredOptions", ",", "'prefix'", ",", "'negativeBefore'", ")", ";", "return", "filteredOptions", ";", "}" ]
Framework Validate formatting options
[ "Framework", "Validate", "formatting", "options" ]
151155570d9d975e16811aabc3c47e84eaeec661
https://github.com/digicorp/propeller/blob/151155570d9d975e16811aabc3c47e84eaeec661/components/range-slider/js/wNumb.js#L235-L291
15,358
digicorp/propeller
components/range-slider/js/wNumb.js
passAll
function passAll ( options, method, input ) { var i, args = []; // Add all options in order of FormatOptions for ( i = 0; i < FormatOptions.length; i+=1 ) { args.push(options[FormatOptions[i]]); } // Append the input, then call the method, presenting all // options as arguments. args.push(input); return method.apply('', args); }
javascript
function passAll ( options, method, input ) { var i, args = []; // Add all options in order of FormatOptions for ( i = 0; i < FormatOptions.length; i+=1 ) { args.push(options[FormatOptions[i]]); } // Append the input, then call the method, presenting all // options as arguments. args.push(input); return method.apply('', args); }
[ "function", "passAll", "(", "options", ",", "method", ",", "input", ")", "{", "var", "i", ",", "args", "=", "[", "]", ";", "// Add all options in order of FormatOptions", "for", "(", "i", "=", "0", ";", "i", "<", "FormatOptions", ".", "length", ";", "i", "+=", "1", ")", "{", "args", ".", "push", "(", "options", "[", "FormatOptions", "[", "i", "]", "]", ")", ";", "}", "// Append the input, then call the method, presenting all", "// options as arguments.", "args", ".", "push", "(", "input", ")", ";", "return", "method", ".", "apply", "(", "''", ",", "args", ")", ";", "}" ]
Pass all options as function arguments
[ "Pass", "all", "options", "as", "function", "arguments" ]
151155570d9d975e16811aabc3c47e84eaeec661
https://github.com/digicorp/propeller/blob/151155570d9d975e16811aabc3c47e84eaeec661/components/range-slider/js/wNumb.js#L294-L306
15,359
digicorp/propeller
components/range-slider/snippets/range-slider.js
formatDate
function formatDate ( date ) { return weekdays[date.getDay()] + ", " + date.getDate() + nth(date.getDate()) + " " + months[date.getMonth()] + " " + date.getFullYear(); }
javascript
function formatDate ( date ) { return weekdays[date.getDay()] + ", " + date.getDate() + nth(date.getDate()) + " " + months[date.getMonth()] + " " + date.getFullYear(); }
[ "function", "formatDate", "(", "date", ")", "{", "return", "weekdays", "[", "date", ".", "getDay", "(", ")", "]", "+", "\", \"", "+", "date", ".", "getDate", "(", ")", "+", "nth", "(", "date", ".", "getDate", "(", ")", ")", "+", "\" \"", "+", "months", "[", "date", ".", "getMonth", "(", ")", "]", "+", "\" \"", "+", "date", ".", "getFullYear", "(", ")", ";", "}" ]
Create a string representation of the date.
[ "Create", "a", "string", "representation", "of", "the", "date", "." ]
151155570d9d975e16811aabc3c47e84eaeec661
https://github.com/digicorp/propeller/blob/151155570d9d975e16811aabc3c47e84eaeec661/components/range-slider/snippets/range-slider.js#L90-L95
15,360
digicorp/propeller
dist/js/propeller.js
function () { function commons() {} commons.attachParentSelector = function (parentSelector, defaultSelector) { var customSelector = defaultSelector; if (parentSelector !== '' && parentSelector.length > 0) { if (parentSelector === defaultSelector) { customSelector = defaultSelector; } else if ($(parentSelector).hasClass(defaultSelector)) { customSelector = parentSelector + "" + defaultSelector; } else { customSelector = parentSelector + " " + defaultSelector; } } return customSelector; }; return commons; }
javascript
function () { function commons() {} commons.attachParentSelector = function (parentSelector, defaultSelector) { var customSelector = defaultSelector; if (parentSelector !== '' && parentSelector.length > 0) { if (parentSelector === defaultSelector) { customSelector = defaultSelector; } else if ($(parentSelector).hasClass(defaultSelector)) { customSelector = parentSelector + "" + defaultSelector; } else { customSelector = parentSelector + " " + defaultSelector; } } return customSelector; }; return commons; }
[ "function", "(", ")", "{", "function", "commons", "(", ")", "{", "}", "commons", ".", "attachParentSelector", "=", "function", "(", "parentSelector", ",", "defaultSelector", ")", "{", "var", "customSelector", "=", "defaultSelector", ";", "if", "(", "parentSelector", "!==", "''", "&&", "parentSelector", ".", "length", ">", "0", ")", "{", "if", "(", "parentSelector", "===", "defaultSelector", ")", "{", "customSelector", "=", "defaultSelector", ";", "}", "else", "if", "(", "$", "(", "parentSelector", ")", ".", "hasClass", "(", "defaultSelector", ")", ")", "{", "customSelector", "=", "parentSelector", "+", "\"\"", "+", "defaultSelector", ";", "}", "else", "{", "customSelector", "=", "parentSelector", "+", "\" \"", "+", "defaultSelector", ";", "}", "}", "return", "customSelector", ";", "}", ";", "return", "commons", ";", "}" ]
Attach Parent Selector
[ "Attach", "Parent", "Selector" ]
151155570d9d975e16811aabc3c47e84eaeec661
https://github.com/digicorp/propeller/blob/151155570d9d975e16811aabc3c47e84eaeec661/dist/js/propeller.js#L13-L30
15,361
digicorp/propeller
dist/js/propeller.js
_inherits
function _inherits(SubClass, SuperClass) { if (typeof SuperClass !== "function" && SuperClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof SuperClass); } SubClass.prototype = new SuperClass(); }
javascript
function _inherits(SubClass, SuperClass) { if (typeof SuperClass !== "function" && SuperClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof SuperClass); } SubClass.prototype = new SuperClass(); }
[ "function", "_inherits", "(", "SubClass", ",", "SuperClass", ")", "{", "if", "(", "typeof", "SuperClass", "!==", "\"function\"", "&&", "SuperClass", "!==", "null", ")", "{", "throw", "new", "TypeError", "(", "\"Super expression must either be null or a function, not \"", "+", "typeof", "SuperClass", ")", ";", "}", "SubClass", ".", "prototype", "=", "new", "SuperClass", "(", ")", ";", "}" ]
Inherit one class to another
[ "Inherit", "one", "class", "to", "another" ]
151155570d9d975e16811aabc3c47e84eaeec661
https://github.com/digicorp/propeller/blob/151155570d9d975e16811aabc3c47e84eaeec661/dist/js/propeller.js#L33-L38
15,362
digicorp/propeller
dist/js/propeller.js
onNavBarToggle
function onNavBarToggle() { $(Selector.NAVBAR_SIDEBAR).toggleClass(ClassName.OPEN); if (($(Selector.NAVBAR_SIDEBAR).hasClass(ClassName.NAVBAR_SIDEBAR)) && $(Selector.NAVBAR_SIDEBAR).hasClass(ClassName.OPEN)) { $(Selector.OVERLAY).addClass(ClassName.OVERLAY_ACTIVE); $(Selector.BODY).addClass(ClassName.BODY_OPEN); } else { $(Selector.OVERLAY).removeClass(ClassName.OVERLAY_ACTIVE); $(Selector.BODY).addClass(ClassName.BODY_OPEN); } }
javascript
function onNavBarToggle() { $(Selector.NAVBAR_SIDEBAR).toggleClass(ClassName.OPEN); if (($(Selector.NAVBAR_SIDEBAR).hasClass(ClassName.NAVBAR_SIDEBAR)) && $(Selector.NAVBAR_SIDEBAR).hasClass(ClassName.OPEN)) { $(Selector.OVERLAY).addClass(ClassName.OVERLAY_ACTIVE); $(Selector.BODY).addClass(ClassName.BODY_OPEN); } else { $(Selector.OVERLAY).removeClass(ClassName.OVERLAY_ACTIVE); $(Selector.BODY).addClass(ClassName.BODY_OPEN); } }
[ "function", "onNavBarToggle", "(", ")", "{", "$", "(", "Selector", ".", "NAVBAR_SIDEBAR", ")", ".", "toggleClass", "(", "ClassName", ".", "OPEN", ")", ";", "if", "(", "(", "$", "(", "Selector", ".", "NAVBAR_SIDEBAR", ")", ".", "hasClass", "(", "ClassName", ".", "NAVBAR_SIDEBAR", ")", ")", "&&", "$", "(", "Selector", ".", "NAVBAR_SIDEBAR", ")", ".", "hasClass", "(", "ClassName", ".", "OPEN", ")", ")", "{", "$", "(", "Selector", ".", "OVERLAY", ")", ".", "addClass", "(", "ClassName", ".", "OVERLAY_ACTIVE", ")", ";", "$", "(", "Selector", ".", "BODY", ")", ".", "addClass", "(", "ClassName", ".", "BODY_OPEN", ")", ";", "}", "else", "{", "$", "(", "Selector", ".", "OVERLAY", ")", ".", "removeClass", "(", "ClassName", ".", "OVERLAY_ACTIVE", ")", ";", "$", "(", "Selector", ".", "BODY", ")", ".", "addClass", "(", "ClassName", ".", "BODY_OPEN", ")", ";", "}", "}" ]
Nave bar in Sidebar
[ "Nave", "bar", "in", "Sidebar" ]
151155570d9d975e16811aabc3c47e84eaeec661
https://github.com/digicorp/propeller/blob/151155570d9d975e16811aabc3c47e84eaeec661/dist/js/propeller.js#L1745-L1754
15,363
digicorp/propeller
dist/js/propeller.js
onResizeWindow
function onResizeWindow(e) { var options = e.data.param1; var sideBarSelector=Selector.SIDEBAR; $(sideBarSelector).each(function () { var $this = $(this); var sideBarId = $this.attr("id"); var isOpenWidth=$("a[data-target="+sideBarId+"]").attr("is-open-width"); if($(window).width()<isOpenWidth) { if ($("#"+sideBarId).hasClass(ClassName.LEFT && ClassName.SLIDE_PUSH)) { $("#"+sideBarId).removeClass(ClassName.OPEN + ' ' + ClassName.SLIDE_PUSH); $("#"+sideBarId).addClass(ClassName.LEFT_FIXED + ' ' + ClassName.IS_SLIDEPUSH); } else { $("#"+sideBarId).removeClass(ClassName.OPEN); } }else{ if ($("#"+sideBarId).hasClass(ClassName.IS_SLIDEPUSH)) { $("#"+sideBarId).addClass(ClassName.OPEN + ' ' + ClassName.SLIDE_PUSH); $("#"+sideBarId).removeClass(ClassName.LEFT_FIXED); } else { $("#"+sideBarId).addClass(ClassName.OPEN); } } }); $(pmdSidebar.prototype.attachParentSelector(Selector.PARENT_SELECTOR, Selector.OVERLAY)).removeClass(ClassName.OVERLAY_ACTIVE); $(Selector.BODY).removeClass(ClassName.BODY_OPEN); }
javascript
function onResizeWindow(e) { var options = e.data.param1; var sideBarSelector=Selector.SIDEBAR; $(sideBarSelector).each(function () { var $this = $(this); var sideBarId = $this.attr("id"); var isOpenWidth=$("a[data-target="+sideBarId+"]").attr("is-open-width"); if($(window).width()<isOpenWidth) { if ($("#"+sideBarId).hasClass(ClassName.LEFT && ClassName.SLIDE_PUSH)) { $("#"+sideBarId).removeClass(ClassName.OPEN + ' ' + ClassName.SLIDE_PUSH); $("#"+sideBarId).addClass(ClassName.LEFT_FIXED + ' ' + ClassName.IS_SLIDEPUSH); } else { $("#"+sideBarId).removeClass(ClassName.OPEN); } }else{ if ($("#"+sideBarId).hasClass(ClassName.IS_SLIDEPUSH)) { $("#"+sideBarId).addClass(ClassName.OPEN + ' ' + ClassName.SLIDE_PUSH); $("#"+sideBarId).removeClass(ClassName.LEFT_FIXED); } else { $("#"+sideBarId).addClass(ClassName.OPEN); } } }); $(pmdSidebar.prototype.attachParentSelector(Selector.PARENT_SELECTOR, Selector.OVERLAY)).removeClass(ClassName.OVERLAY_ACTIVE); $(Selector.BODY).removeClass(ClassName.BODY_OPEN); }
[ "function", "onResizeWindow", "(", "e", ")", "{", "var", "options", "=", "e", ".", "data", ".", "param1", ";", "var", "sideBarSelector", "=", "Selector", ".", "SIDEBAR", ";", "$", "(", "sideBarSelector", ")", ".", "each", "(", "function", "(", ")", "{", "var", "$this", "=", "$", "(", "this", ")", ";", "var", "sideBarId", "=", "$this", ".", "attr", "(", "\"id\"", ")", ";", "var", "isOpenWidth", "=", "$", "(", "\"a[data-target=\"", "+", "sideBarId", "+", "\"]\"", ")", ".", "attr", "(", "\"is-open-width\"", ")", ";", "if", "(", "$", "(", "window", ")", ".", "width", "(", ")", "<", "isOpenWidth", ")", "{", "if", "(", "$", "(", "\"#\"", "+", "sideBarId", ")", ".", "hasClass", "(", "ClassName", ".", "LEFT", "&&", "ClassName", ".", "SLIDE_PUSH", ")", ")", "{", "$", "(", "\"#\"", "+", "sideBarId", ")", ".", "removeClass", "(", "ClassName", ".", "OPEN", "+", "' '", "+", "ClassName", ".", "SLIDE_PUSH", ")", ";", "$", "(", "\"#\"", "+", "sideBarId", ")", ".", "addClass", "(", "ClassName", ".", "LEFT_FIXED", "+", "' '", "+", "ClassName", ".", "IS_SLIDEPUSH", ")", ";", "}", "else", "{", "$", "(", "\"#\"", "+", "sideBarId", ")", ".", "removeClass", "(", "ClassName", ".", "OPEN", ")", ";", "}", "}", "else", "{", "if", "(", "$", "(", "\"#\"", "+", "sideBarId", ")", ".", "hasClass", "(", "ClassName", ".", "IS_SLIDEPUSH", ")", ")", "{", "$", "(", "\"#\"", "+", "sideBarId", ")", ".", "addClass", "(", "ClassName", ".", "OPEN", "+", "' '", "+", "ClassName", ".", "SLIDE_PUSH", ")", ";", "$", "(", "\"#\"", "+", "sideBarId", ")", ".", "removeClass", "(", "ClassName", ".", "LEFT_FIXED", ")", ";", "}", "else", "{", "$", "(", "\"#\"", "+", "sideBarId", ")", ".", "addClass", "(", "ClassName", ".", "OPEN", ")", ";", "}", "}", "}", ")", ";", "$", "(", "pmdSidebar", ".", "prototype", ".", "attachParentSelector", "(", "Selector", ".", "PARENT_SELECTOR", ",", "Selector", ".", "OVERLAY", ")", ")", ".", "removeClass", "(", "ClassName", ".", "OVERLAY_ACTIVE", ")", ";", "$", "(", "Selector", ".", "BODY", ")", ".", "removeClass", "(", "ClassName", ".", "BODY_OPEN", ")", ";", "}" ]
On Window Resize
[ "On", "Window", "Resize" ]
151155570d9d975e16811aabc3c47e84eaeec661
https://github.com/digicorp/propeller/blob/151155570d9d975e16811aabc3c47e84eaeec661/dist/js/propeller.js#L1767-L1792
15,364
TotallyInformation/node-red-contrib-uibuilder
nodes/uibuilder.js
localMiddleware
function localMiddleware (req, res, next) { // Tell the client what Socket.IO namespace to use, // trim the leading slash because the cookie will turn it into a %2F res.setHeader('uibuilder-namespace', node.ioNamespace) res.cookie('uibuilder-namespace', tilib.trimSlashes(node.ioNamespace), {path: node.url, sameSite: true}) next() }
javascript
function localMiddleware (req, res, next) { // Tell the client what Socket.IO namespace to use, // trim the leading slash because the cookie will turn it into a %2F res.setHeader('uibuilder-namespace', node.ioNamespace) res.cookie('uibuilder-namespace', tilib.trimSlashes(node.ioNamespace), {path: node.url, sameSite: true}) next() }
[ "function", "localMiddleware", "(", "req", ",", "res", ",", "next", ")", "{", "// Tell the client what Socket.IO namespace to use,", "// trim the leading slash because the cookie will turn it into a %2F", "res", ".", "setHeader", "(", "'uibuilder-namespace'", ",", "node", ".", "ioNamespace", ")", "res", ".", "cookie", "(", "'uibuilder-namespace'", ",", "tilib", ".", "trimSlashes", "(", "node", ".", "ioNamespace", ")", ",", "{", "path", ":", "node", ".", "url", ",", "sameSite", ":", "true", "}", ")", "next", "(", ")", "}" ]
This ExpressJS middleware runs when the uibuilder page loads @see https://expressjs.com/en/guide/using-middleware.html
[ "This", "ExpressJS", "middleware", "runs", "when", "the", "uibuilder", "page", "loads" ]
e89bf6e9d6ad183de9531301b35f87b8c7f08f7e
https://github.com/TotallyInformation/node-red-contrib-uibuilder/blob/e89bf6e9d6ad183de9531301b35f87b8c7f08f7e/nodes/uibuilder.js#L318-L324
15,365
TotallyInformation/node-red-contrib-uibuilder
nodes/uiblib.js
function(msg, node, RED, io, ioNs, log) { node.rcvMsgCount++ log.verbose(`[${node.url}] msg received via FLOW. ${node.rcvMsgCount} messages received`, msg) // If the input msg is a uibuilder control msg, then drop it to prevent loops if ( msg.hasOwnProperty('uibuilderCtrl') ) return null //setNodeStatus({fill: 'yellow', shape: 'dot', text: 'Message Received #' + node.rcvMsgCount}, node) // Remove script/style content if admin settings don't allow if ( node.allowScripts !== true ) { if ( msg.hasOwnProperty('script') ) delete msg.script } if ( node.allowStyles !== true ) { if ( msg.hasOwnProperty('style') ) delete msg.style } // pass the complete msg object to the uibuilder client // TODO: This should have some safety validation on it! if (msg._socketId) { log.debug(`[${node.url}] msg sent on to client ${msg._socketId}. Channel: ${node.ioChannels.server}`, msg) ioNs.to(msg._socketId).emit(node.ioChannels.server, msg) } else { log.debug(`[${node.url}] msg sent on to ALL clients. Channel: ${node.ioChannels.server}`, msg) ioNs.emit(node.ioChannels.server, msg) } if (node.fwdInMessages) { // Send on the input msg to output node.send(msg) log.debug(`[${node.url}] msg passed downstream to next node`, msg) } return msg }
javascript
function(msg, node, RED, io, ioNs, log) { node.rcvMsgCount++ log.verbose(`[${node.url}] msg received via FLOW. ${node.rcvMsgCount} messages received`, msg) // If the input msg is a uibuilder control msg, then drop it to prevent loops if ( msg.hasOwnProperty('uibuilderCtrl') ) return null //setNodeStatus({fill: 'yellow', shape: 'dot', text: 'Message Received #' + node.rcvMsgCount}, node) // Remove script/style content if admin settings don't allow if ( node.allowScripts !== true ) { if ( msg.hasOwnProperty('script') ) delete msg.script } if ( node.allowStyles !== true ) { if ( msg.hasOwnProperty('style') ) delete msg.style } // pass the complete msg object to the uibuilder client // TODO: This should have some safety validation on it! if (msg._socketId) { log.debug(`[${node.url}] msg sent on to client ${msg._socketId}. Channel: ${node.ioChannels.server}`, msg) ioNs.to(msg._socketId).emit(node.ioChannels.server, msg) } else { log.debug(`[${node.url}] msg sent on to ALL clients. Channel: ${node.ioChannels.server}`, msg) ioNs.emit(node.ioChannels.server, msg) } if (node.fwdInMessages) { // Send on the input msg to output node.send(msg) log.debug(`[${node.url}] msg passed downstream to next node`, msg) } return msg }
[ "function", "(", "msg", ",", "node", ",", "RED", ",", "io", ",", "ioNs", ",", "log", ")", "{", "node", ".", "rcvMsgCount", "++", "log", ".", "verbose", "(", "`", "${", "node", ".", "url", "}", "${", "node", ".", "rcvMsgCount", "}", "`", ",", "msg", ")", "// If the input msg is a uibuilder control msg, then drop it to prevent loops", "if", "(", "msg", ".", "hasOwnProperty", "(", "'uibuilderCtrl'", ")", ")", "return", "null", "//setNodeStatus({fill: 'yellow', shape: 'dot', text: 'Message Received #' + node.rcvMsgCount}, node)", "// Remove script/style content if admin settings don't allow", "if", "(", "node", ".", "allowScripts", "!==", "true", ")", "{", "if", "(", "msg", ".", "hasOwnProperty", "(", "'script'", ")", ")", "delete", "msg", ".", "script", "}", "if", "(", "node", ".", "allowStyles", "!==", "true", ")", "{", "if", "(", "msg", ".", "hasOwnProperty", "(", "'style'", ")", ")", "delete", "msg", ".", "style", "}", "// pass the complete msg object to the uibuilder client", "// TODO: This should have some safety validation on it!", "if", "(", "msg", ".", "_socketId", ")", "{", "log", ".", "debug", "(", "`", "${", "node", ".", "url", "}", "${", "msg", ".", "_socketId", "}", "${", "node", ".", "ioChannels", ".", "server", "}", "`", ",", "msg", ")", "ioNs", ".", "to", "(", "msg", ".", "_socketId", ")", ".", "emit", "(", "node", ".", "ioChannels", ".", "server", ",", "msg", ")", "}", "else", "{", "log", ".", "debug", "(", "`", "${", "node", ".", "url", "}", "${", "node", ".", "ioChannels", ".", "server", "}", "`", ",", "msg", ")", "ioNs", ".", "emit", "(", "node", ".", "ioChannels", ".", "server", ",", "msg", ")", "}", "if", "(", "node", ".", "fwdInMessages", ")", "{", "// Send on the input msg to output", "node", ".", "send", "(", "msg", ")", "log", ".", "debug", "(", "`", "${", "node", ".", "url", "}", "`", ",", "msg", ")", "}", "return", "msg", "}" ]
Complex, custom code when processing an incoming msg should go here Needs to return the msg object
[ "Complex", "custom", "code", "when", "processing", "an", "incoming", "msg", "should", "go", "here", "Needs", "to", "return", "the", "msg", "object" ]
e89bf6e9d6ad183de9531301b35f87b8c7f08f7e
https://github.com/TotallyInformation/node-red-contrib-uibuilder/blob/e89bf6e9d6ad183de9531301b35f87b8c7f08f7e/nodes/uiblib.js#L29-L63
15,366
nikgraf/belle
src/components/Toggle.js
validateChoices
function validateChoices(props, propName, componentName) { const propValue = props[propName]; if (!propValue) { return undefined; } if (!Array.isArray(propValue) || propValue.length !== 2) { return new Error(`Invalid ${propName} supplied to \`${componentName}\`, expected exactly two Choice components.`); } for (let i = 0; i < propValue.length; ++i) { const item = propValue[i]; if (!item || !isComponentOfType(Choice, item)) { return new Error(`Invalid ${propName}[${i}] supplied to \`${componentName}\`, expected a Choice component from Belle.`); } } if (first(propValue).props.value === last(propValue).props.value) { return new Error(`Invalid ${propName} supplied to \`${componentName}\`, expected different value properties for the provided Choice components.`); } return undefined; }
javascript
function validateChoices(props, propName, componentName) { const propValue = props[propName]; if (!propValue) { return undefined; } if (!Array.isArray(propValue) || propValue.length !== 2) { return new Error(`Invalid ${propName} supplied to \`${componentName}\`, expected exactly two Choice components.`); } for (let i = 0; i < propValue.length; ++i) { const item = propValue[i]; if (!item || !isComponentOfType(Choice, item)) { return new Error(`Invalid ${propName}[${i}] supplied to \`${componentName}\`, expected a Choice component from Belle.`); } } if (first(propValue).props.value === last(propValue).props.value) { return new Error(`Invalid ${propName} supplied to \`${componentName}\`, expected different value properties for the provided Choice components.`); } return undefined; }
[ "function", "validateChoices", "(", "props", ",", "propName", ",", "componentName", ")", "{", "const", "propValue", "=", "props", "[", "propName", "]", ";", "if", "(", "!", "propValue", ")", "{", "return", "undefined", ";", "}", "if", "(", "!", "Array", ".", "isArray", "(", "propValue", ")", "||", "propValue", ".", "length", "!==", "2", ")", "{", "return", "new", "Error", "(", "`", "${", "propName", "}", "\\`", "${", "componentName", "}", "\\`", "`", ")", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "propValue", ".", "length", ";", "++", "i", ")", "{", "const", "item", "=", "propValue", "[", "i", "]", ";", "if", "(", "!", "item", "||", "!", "isComponentOfType", "(", "Choice", ",", "item", ")", ")", "{", "return", "new", "Error", "(", "`", "${", "propName", "}", "${", "i", "}", "\\`", "${", "componentName", "}", "\\`", "`", ")", ";", "}", "}", "if", "(", "first", "(", "propValue", ")", ".", "props", ".", "value", "===", "last", "(", "propValue", ")", ".", "props", ".", "value", ")", "{", "return", "new", "Error", "(", "`", "${", "propName", "}", "\\`", "${", "componentName", "}", "\\`", "`", ")", ";", "}", "return", "undefined", ";", "}" ]
Verifies that the children is an array containing only two choices with a different value.
[ "Verifies", "that", "the", "children", "is", "an", "array", "containing", "only", "two", "choices", "with", "a", "different", "value", "." ]
e0f561d6ad704b5e3d66a38752de29f938b065af
https://github.com/nikgraf/belle/blob/e0f561d6ad704b5e3d66a38752de29f938b065af/src/components/Toggle.js#L17-L39
15,367
nikgraf/belle
src/components/Toggle.js
updatePseudoClassStyle
function updatePseudoClassStyle(styleId, properties, preventFocusStyleForTouchAndClick) { let focusStyle; if (preventFocusStyleForTouchAndClick) { focusStyle = { outline: 0 }; } else { focusStyle = { ...style.focusStyle, ...properties.focusStyle, }; } const styles = [ { id: styleId, style: focusStyle, pseudoClass: 'focus', }, ]; injectStyles(styles); }
javascript
function updatePseudoClassStyle(styleId, properties, preventFocusStyleForTouchAndClick) { let focusStyle; if (preventFocusStyleForTouchAndClick) { focusStyle = { outline: 0 }; } else { focusStyle = { ...style.focusStyle, ...properties.focusStyle, }; } const styles = [ { id: styleId, style: focusStyle, pseudoClass: 'focus', }, ]; injectStyles(styles); }
[ "function", "updatePseudoClassStyle", "(", "styleId", ",", "properties", ",", "preventFocusStyleForTouchAndClick", ")", "{", "let", "focusStyle", ";", "if", "(", "preventFocusStyleForTouchAndClick", ")", "{", "focusStyle", "=", "{", "outline", ":", "0", "}", ";", "}", "else", "{", "focusStyle", "=", "{", "...", "style", ".", "focusStyle", ",", "...", "properties", ".", "focusStyle", ",", "}", ";", "}", "const", "styles", "=", "[", "{", "id", ":", "styleId", ",", "style", ":", "focusStyle", ",", "pseudoClass", ":", "'focus'", ",", "}", ",", "]", ";", "injectStyles", "(", "styles", ")", ";", "}" ]
Update focus style for the speficied styleId. @param styleId {string} - a unique id that exists as class attribute in the DOM @param properties {object} - the components properties optionally containing custom styles
[ "Update", "focus", "style", "for", "the", "speficied", "styleId", "." ]
e0f561d6ad704b5e3d66a38752de29f938b065af
https://github.com/nikgraf/belle/blob/e0f561d6ad704b5e3d66a38752de29f938b065af/src/components/Toggle.js#L153-L173
15,368
nikgraf/belle
src/components/Button.js
updatePseudoClassStyle
function updatePseudoClassStyle(styleId, properties, preventFocusStyleForTouchAndClick) { const baseStyle = properties.primary ? buttonStyle.primaryStyle : buttonStyle.style; const baseDisabledStyle = properties.primary ? buttonStyle.primaryDisabledStyle : buttonStyle.disabledStyle; const disabledStyle = { ...baseStyle, ...properties.style, ...baseDisabledStyle, ...properties.disabledStyle, }; const baseActiveStyle = properties.primary ? buttonStyle.primaryActiveStyle : buttonStyle.activeStyle; const activeStyle = { ...baseActiveStyle, ...properties.activeStyle, }; let focusStyle; if (preventFocusStyleForTouchAndClick) { focusStyle = { outline: 0 }; } else { const baseFocusStyle = properties.primary ? buttonStyle.primaryFocusStyle : buttonStyle.focusStyle; focusStyle = { ...baseFocusStyle, ...properties.focusStyle, }; } const styles = [ { id: styleId, style: activeStyle, pseudoClass: 'active', }, { id: styleId, style: disabledStyle, pseudoClass: 'active', disabled: true, }, { id: styleId, style: focusStyle, pseudoClass: 'focus', }, ]; injectStyles(styles); }
javascript
function updatePseudoClassStyle(styleId, properties, preventFocusStyleForTouchAndClick) { const baseStyle = properties.primary ? buttonStyle.primaryStyle : buttonStyle.style; const baseDisabledStyle = properties.primary ? buttonStyle.primaryDisabledStyle : buttonStyle.disabledStyle; const disabledStyle = { ...baseStyle, ...properties.style, ...baseDisabledStyle, ...properties.disabledStyle, }; const baseActiveStyle = properties.primary ? buttonStyle.primaryActiveStyle : buttonStyle.activeStyle; const activeStyle = { ...baseActiveStyle, ...properties.activeStyle, }; let focusStyle; if (preventFocusStyleForTouchAndClick) { focusStyle = { outline: 0 }; } else { const baseFocusStyle = properties.primary ? buttonStyle.primaryFocusStyle : buttonStyle.focusStyle; focusStyle = { ...baseFocusStyle, ...properties.focusStyle, }; } const styles = [ { id: styleId, style: activeStyle, pseudoClass: 'active', }, { id: styleId, style: disabledStyle, pseudoClass: 'active', disabled: true, }, { id: styleId, style: focusStyle, pseudoClass: 'focus', }, ]; injectStyles(styles); }
[ "function", "updatePseudoClassStyle", "(", "styleId", ",", "properties", ",", "preventFocusStyleForTouchAndClick", ")", "{", "const", "baseStyle", "=", "properties", ".", "primary", "?", "buttonStyle", ".", "primaryStyle", ":", "buttonStyle", ".", "style", ";", "const", "baseDisabledStyle", "=", "properties", ".", "primary", "?", "buttonStyle", ".", "primaryDisabledStyle", ":", "buttonStyle", ".", "disabledStyle", ";", "const", "disabledStyle", "=", "{", "...", "baseStyle", ",", "...", "properties", ".", "style", ",", "...", "baseDisabledStyle", ",", "...", "properties", ".", "disabledStyle", ",", "}", ";", "const", "baseActiveStyle", "=", "properties", ".", "primary", "?", "buttonStyle", ".", "primaryActiveStyle", ":", "buttonStyle", ".", "activeStyle", ";", "const", "activeStyle", "=", "{", "...", "baseActiveStyle", ",", "...", "properties", ".", "activeStyle", ",", "}", ";", "let", "focusStyle", ";", "if", "(", "preventFocusStyleForTouchAndClick", ")", "{", "focusStyle", "=", "{", "outline", ":", "0", "}", ";", "}", "else", "{", "const", "baseFocusStyle", "=", "properties", ".", "primary", "?", "buttonStyle", ".", "primaryFocusStyle", ":", "buttonStyle", ".", "focusStyle", ";", "focusStyle", "=", "{", "...", "baseFocusStyle", ",", "...", "properties", ".", "focusStyle", ",", "}", ";", "}", "const", "styles", "=", "[", "{", "id", ":", "styleId", ",", "style", ":", "activeStyle", ",", "pseudoClass", ":", "'active'", ",", "}", ",", "{", "id", ":", "styleId", ",", "style", ":", "disabledStyle", ",", "pseudoClass", ":", "'active'", ",", "disabled", ":", "true", ",", "}", ",", "{", "id", ":", "styleId", ",", "style", ":", "focusStyle", ",", "pseudoClass", ":", "'focus'", ",", "}", ",", "]", ";", "injectStyles", "(", "styles", ")", ";", "}" ]
Update hover, focus & active style for the speficied styleId. @param styleId {string} - a unique id that exists as class attribute in the DOM @param properties {object} - the components properties optionally containing custom styles
[ "Update", "hover", "focus", "&", "active", "style", "for", "the", "speficied", "styleId", "." ]
e0f561d6ad704b5e3d66a38752de29f938b065af
https://github.com/nikgraf/belle/blob/e0f561d6ad704b5e3d66a38752de29f938b065af/src/components/Button.js#L53-L99
15,369
nikgraf/belle
src/components/Select.js
validateChildrenAreOptionsAndMaximumOnePlaceholder
function validateChildrenAreOptionsAndMaximumOnePlaceholder(props, propName, componentName) { const validChildren = filterReactChildren(props[propName], (node) => ( (isOption(node) || isSeparator(node) || isPlaceholder(node)) )); if (React.Children.count(props[propName]) !== React.Children.count(validChildren)) { return new Error(`Invalid children supplied to \`${componentName}\`, expected an Option, Separator or Placeholder component from Belle.`); } const placeholders = filterReactChildren(props[propName], (node) => isPlaceholder(node)); if (React.Children.count(placeholders) > 1) { return new Error(`Invalid children supplied to \`${componentName}\`, expected only one Placeholder component.`); } return undefined; }
javascript
function validateChildrenAreOptionsAndMaximumOnePlaceholder(props, propName, componentName) { const validChildren = filterReactChildren(props[propName], (node) => ( (isOption(node) || isSeparator(node) || isPlaceholder(node)) )); if (React.Children.count(props[propName]) !== React.Children.count(validChildren)) { return new Error(`Invalid children supplied to \`${componentName}\`, expected an Option, Separator or Placeholder component from Belle.`); } const placeholders = filterReactChildren(props[propName], (node) => isPlaceholder(node)); if (React.Children.count(placeholders) > 1) { return new Error(`Invalid children supplied to \`${componentName}\`, expected only one Placeholder component.`); } return undefined; }
[ "function", "validateChildrenAreOptionsAndMaximumOnePlaceholder", "(", "props", ",", "propName", ",", "componentName", ")", "{", "const", "validChildren", "=", "filterReactChildren", "(", "props", "[", "propName", "]", ",", "(", "node", ")", "=>", "(", "(", "isOption", "(", "node", ")", "||", "isSeparator", "(", "node", ")", "||", "isPlaceholder", "(", "node", ")", ")", ")", ")", ";", "if", "(", "React", ".", "Children", ".", "count", "(", "props", "[", "propName", "]", ")", "!==", "React", ".", "Children", ".", "count", "(", "validChildren", ")", ")", "{", "return", "new", "Error", "(", "`", "\\`", "${", "componentName", "}", "\\`", "`", ")", ";", "}", "const", "placeholders", "=", "filterReactChildren", "(", "props", "[", "propName", "]", ",", "(", "node", ")", "=>", "isPlaceholder", "(", "node", ")", ")", ";", "if", "(", "React", ".", "Children", ".", "count", "(", "placeholders", ")", ">", "1", ")", "{", "return", "new", "Error", "(", "`", "\\`", "${", "componentName", "}", "\\`", "`", ")", ";", "}", "return", "undefined", ";", "}" ]
Verifies that the children is an array containing only Options & at maximum one Placeholder.
[ "Verifies", "that", "the", "children", "is", "an", "array", "containing", "only", "Options", "&", "at", "maximum", "one", "Placeholder", "." ]
e0f561d6ad704b5e3d66a38752de29f938b065af
https://github.com/nikgraf/belle/blob/e0f561d6ad704b5e3d66a38752de29f938b065af/src/components/Select.js#L54-L68
15,370
nikgraf/belle
src/components/Select.js
updatePseudoClassStyle
function updatePseudoClassStyle(styleId, properties) { const hoverStyle = { ...style.hoverStyle, ...properties.hoverStyle, }; const disabledHoverStyle = { ...style.disabledHoverStyle, ...properties.disabledHoverStyle, }; const styles = [ { id: styleId, style: hoverStyle, pseudoClass: 'hover', }, { id: styleId, style: disabledHoverStyle, pseudoClass: 'hover', disabled: true, }, ]; injectStyles(styles); }
javascript
function updatePseudoClassStyle(styleId, properties) { const hoverStyle = { ...style.hoverStyle, ...properties.hoverStyle, }; const disabledHoverStyle = { ...style.disabledHoverStyle, ...properties.disabledHoverStyle, }; const styles = [ { id: styleId, style: hoverStyle, pseudoClass: 'hover', }, { id: styleId, style: disabledHoverStyle, pseudoClass: 'hover', disabled: true, }, ]; injectStyles(styles); }
[ "function", "updatePseudoClassStyle", "(", "styleId", ",", "properties", ")", "{", "const", "hoverStyle", "=", "{", "...", "style", ".", "hoverStyle", ",", "...", "properties", ".", "hoverStyle", ",", "}", ";", "const", "disabledHoverStyle", "=", "{", "...", "style", ".", "disabledHoverStyle", ",", "...", "properties", ".", "disabledHoverStyle", ",", "}", ";", "const", "styles", "=", "[", "{", "id", ":", "styleId", ",", "style", ":", "hoverStyle", ",", "pseudoClass", ":", "'hover'", ",", "}", ",", "{", "id", ":", "styleId", ",", "style", ":", "disabledHoverStyle", ",", "pseudoClass", ":", "'hover'", ",", "disabled", ":", "true", ",", "}", ",", "]", ";", "injectStyles", "(", "styles", ")", ";", "}" ]
Update hover style for the speficied styleId. @param styleId {string} - a unique id that exists as class attribute in the DOM @param properties {object} - the components properties optionally containing hoverStyle
[ "Update", "hover", "style", "for", "the", "speficied", "styleId", "." ]
e0f561d6ad704b5e3d66a38752de29f938b065af
https://github.com/nikgraf/belle/blob/e0f561d6ad704b5e3d66a38752de29f938b065af/src/components/Select.js#L121-L145
15,371
nikgraf/belle
docs/theme/initialize.js
updateStructure
function updateStructure(targetObject, object) { for (const componentName in object) { if (object.hasOwnProperty(componentName)) { for (const styleName in object[componentName]) { if (object[componentName].hasOwnProperty(styleName)) { targetObject[componentName][styleName] = object[componentName][styleName]; // eslint-disable-line no-param-reassign } } } } }
javascript
function updateStructure(targetObject, object) { for (const componentName in object) { if (object.hasOwnProperty(componentName)) { for (const styleName in object[componentName]) { if (object[componentName].hasOwnProperty(styleName)) { targetObject[componentName][styleName] = object[componentName][styleName]; // eslint-disable-line no-param-reassign } } } } }
[ "function", "updateStructure", "(", "targetObject", ",", "object", ")", "{", "for", "(", "const", "componentName", "in", "object", ")", "{", "if", "(", "object", ".", "hasOwnProperty", "(", "componentName", ")", ")", "{", "for", "(", "const", "styleName", "in", "object", "[", "componentName", "]", ")", "{", "if", "(", "object", "[", "componentName", "]", ".", "hasOwnProperty", "(", "styleName", ")", ")", "{", "targetObject", "[", "componentName", "]", "[", "styleName", "]", "=", "object", "[", "componentName", "]", "[", "styleName", "]", ";", "// eslint-disable-line no-param-reassign", "}", "}", "}", "}", "}" ]
Updates the deepest structure while keeping the original reference of the outer objects.
[ "Updates", "the", "deepest", "structure", "while", "keeping", "the", "original", "reference", "of", "the", "outer", "objects", "." ]
e0f561d6ad704b5e3d66a38752de29f938b065af
https://github.com/nikgraf/belle/blob/e0f561d6ad704b5e3d66a38752de29f938b065af/docs/theme/initialize.js#L18-L28
15,372
nikgraf/belle
src/utils/helpers.js
flattenInternal
function flattenInternal(output, element) { if (element) { element.forEach((obj) => { if (Array.isArray(obj)) { flattenInternal(output, obj); } else { output.push(obj); } }); } }
javascript
function flattenInternal(output, element) { if (element) { element.forEach((obj) => { if (Array.isArray(obj)) { flattenInternal(output, obj); } else { output.push(obj); } }); } }
[ "function", "flattenInternal", "(", "output", ",", "element", ")", "{", "if", "(", "element", ")", "{", "element", ".", "forEach", "(", "(", "obj", ")", "=>", "{", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "{", "flattenInternal", "(", "output", ",", "obj", ")", ";", "}", "else", "{", "output", ".", "push", "(", "obj", ")", ";", "}", "}", ")", ";", "}", "}" ]
Recursive function for flattening an iterable. @param {object} output - base object to be updated @param {object} element - input object to be merged into the output
[ "Recursive", "function", "for", "flattening", "an", "iterable", "." ]
e0f561d6ad704b5e3d66a38752de29f938b065af
https://github.com/nikgraf/belle/blob/e0f561d6ad704b5e3d66a38752de29f938b065af/src/utils/helpers.js#L310-L320
15,373
nikgraf/belle
src/utils/inject-style.js
createMarkupOnPseudoClass
function createMarkupOnPseudoClass(pseudoClasses, id, disabled) { return mapObject(pseudoClasses, (style, pseudoClass) => { if (style && Object.keys(style).length > 0) { const styleString = CSSPropertyOperations.createMarkupForStyles(style); const styleWithImportant = styleString.replace(/;/g, ' !important;'); return disabled ? `.${id}[disabled]:${pseudoClass} {${styleWithImportant}}` : `.${id}:${pseudoClass} {${styleWithImportant}}`; } return undefined; }); }
javascript
function createMarkupOnPseudoClass(pseudoClasses, id, disabled) { return mapObject(pseudoClasses, (style, pseudoClass) => { if (style && Object.keys(style).length > 0) { const styleString = CSSPropertyOperations.createMarkupForStyles(style); const styleWithImportant = styleString.replace(/;/g, ' !important;'); return disabled ? `.${id}[disabled]:${pseudoClass} {${styleWithImportant}}` : `.${id}:${pseudoClass} {${styleWithImportant}}`; } return undefined; }); }
[ "function", "createMarkupOnPseudoClass", "(", "pseudoClasses", ",", "id", ",", "disabled", ")", "{", "return", "mapObject", "(", "pseudoClasses", ",", "(", "style", ",", "pseudoClass", ")", "=>", "{", "if", "(", "style", "&&", "Object", ".", "keys", "(", "style", ")", ".", "length", ">", "0", ")", "{", "const", "styleString", "=", "CSSPropertyOperations", ".", "createMarkupForStyles", "(", "style", ")", ";", "const", "styleWithImportant", "=", "styleString", ".", "replace", "(", "/", ";", "/", "g", ",", "' !important;'", ")", ";", "return", "disabled", "?", "`", "${", "id", "}", "${", "pseudoClass", "}", "${", "styleWithImportant", "}", "`", ":", "`", "${", "id", "}", "${", "pseudoClass", "}", "${", "styleWithImportant", "}", "`", ";", "}", "return", "undefined", ";", "}", ")", ";", "}" ]
Constructs all the stored styles & injects them to the DOM.
[ "Constructs", "all", "the", "stored", "styles", "&", "injects", "them", "to", "the", "DOM", "." ]
e0f561d6ad704b5e3d66a38752de29f938b065af
https://github.com/nikgraf/belle/blob/e0f561d6ad704b5e3d66a38752de29f938b065af/src/utils/inject-style.js#L37-L50
15,374
nikgraf/belle
src/components/ComboBox.js
filterFunc
function filterFunc(inputValue, optionValue) { if (inputValue && optionValue) { return optionValue.toLowerCase().indexOf(inputValue.toLowerCase()) > -1; } return false; }
javascript
function filterFunc(inputValue, optionValue) { if (inputValue && optionValue) { return optionValue.toLowerCase().indexOf(inputValue.toLowerCase()) > -1; } return false; }
[ "function", "filterFunc", "(", "inputValue", ",", "optionValue", ")", "{", "if", "(", "inputValue", "&&", "optionValue", ")", "{", "return", "optionValue", ".", "toLowerCase", "(", ")", ".", "indexOf", "(", "inputValue", ".", "toLowerCase", "(", ")", ")", ">", "-", "1", ";", "}", "return", "false", ";", "}" ]
Default function used for filtering options.
[ "Default", "function", "used", "for", "filtering", "options", "." ]
e0f561d6ad704b5e3d66a38752de29f938b065af
https://github.com/nikgraf/belle/blob/e0f561d6ad704b5e3d66a38752de29f938b065af/src/components/ComboBox.js#L143-L149
15,375
nikgraf/belle
src/utils/calculate-textarea-height.js
calculateStyling
function calculateStyling(node) { const reactId = node.getAttribute('data-reactid'); // calculate the computed style only once it's not in the cache if (!computedStyleCache[reactId]) { // In order to work with legacy browsers the second paramter for pseudoClass // has to be provided http://caniuse.com/#feat=getcomputedstyle const computedStyle = window.getComputedStyle(node, null); const boxSizing = ( computedStyle.getPropertyValue('box-sizing') || computedStyle.getPropertyValue('-moz-box-sizing') || computedStyle.getPropertyValue('-webkit-box-sizing') ); let verticalPaddingSize = 0; verticalPaddingSize = ( parseFloat(computedStyle.getPropertyValue('padding-bottom')) + parseFloat(computedStyle.getPropertyValue('padding-top')) ); let verticalBorderSize = 0; verticalBorderSize = ( parseFloat(computedStyle.getPropertyValue('border-bottom-width')) + parseFloat(computedStyle.getPropertyValue('border-top-width')) ); const sizingStyle = stylesToCopy .map(styleName => `${styleName}:${computedStyle.getPropertyValue(styleName)} !important`) .join(';'); // store the style, vertical padding size, vertical border size and // boxSizing inside the cache computedStyleCache[reactId] = { style: sizingStyle, verticalPaddingSize, verticalBorderSize, boxSizing, }; } return computedStyleCache[reactId]; }
javascript
function calculateStyling(node) { const reactId = node.getAttribute('data-reactid'); // calculate the computed style only once it's not in the cache if (!computedStyleCache[reactId]) { // In order to work with legacy browsers the second paramter for pseudoClass // has to be provided http://caniuse.com/#feat=getcomputedstyle const computedStyle = window.getComputedStyle(node, null); const boxSizing = ( computedStyle.getPropertyValue('box-sizing') || computedStyle.getPropertyValue('-moz-box-sizing') || computedStyle.getPropertyValue('-webkit-box-sizing') ); let verticalPaddingSize = 0; verticalPaddingSize = ( parseFloat(computedStyle.getPropertyValue('padding-bottom')) + parseFloat(computedStyle.getPropertyValue('padding-top')) ); let verticalBorderSize = 0; verticalBorderSize = ( parseFloat(computedStyle.getPropertyValue('border-bottom-width')) + parseFloat(computedStyle.getPropertyValue('border-top-width')) ); const sizingStyle = stylesToCopy .map(styleName => `${styleName}:${computedStyle.getPropertyValue(styleName)} !important`) .join(';'); // store the style, vertical padding size, vertical border size and // boxSizing inside the cache computedStyleCache[reactId] = { style: sizingStyle, verticalPaddingSize, verticalBorderSize, boxSizing, }; } return computedStyleCache[reactId]; }
[ "function", "calculateStyling", "(", "node", ")", "{", "const", "reactId", "=", "node", ".", "getAttribute", "(", "'data-reactid'", ")", ";", "// calculate the computed style only once it's not in the cache", "if", "(", "!", "computedStyleCache", "[", "reactId", "]", ")", "{", "// In order to work with legacy browsers the second paramter for pseudoClass", "// has to be provided http://caniuse.com/#feat=getcomputedstyle", "const", "computedStyle", "=", "window", ".", "getComputedStyle", "(", "node", ",", "null", ")", ";", "const", "boxSizing", "=", "(", "computedStyle", ".", "getPropertyValue", "(", "'box-sizing'", ")", "||", "computedStyle", ".", "getPropertyValue", "(", "'-moz-box-sizing'", ")", "||", "computedStyle", ".", "getPropertyValue", "(", "'-webkit-box-sizing'", ")", ")", ";", "let", "verticalPaddingSize", "=", "0", ";", "verticalPaddingSize", "=", "(", "parseFloat", "(", "computedStyle", ".", "getPropertyValue", "(", "'padding-bottom'", ")", ")", "+", "parseFloat", "(", "computedStyle", ".", "getPropertyValue", "(", "'padding-top'", ")", ")", ")", ";", "let", "verticalBorderSize", "=", "0", ";", "verticalBorderSize", "=", "(", "parseFloat", "(", "computedStyle", ".", "getPropertyValue", "(", "'border-bottom-width'", ")", ")", "+", "parseFloat", "(", "computedStyle", ".", "getPropertyValue", "(", "'border-top-width'", ")", ")", ")", ";", "const", "sizingStyle", "=", "stylesToCopy", ".", "map", "(", "styleName", "=>", "`", "${", "styleName", "}", "${", "computedStyle", ".", "getPropertyValue", "(", "styleName", ")", "}", "`", ")", ".", "join", "(", "';'", ")", ";", "// store the style, vertical padding size, vertical border size and", "// boxSizing inside the cache", "computedStyleCache", "[", "reactId", "]", "=", "{", "style", ":", "sizingStyle", ",", "verticalPaddingSize", ",", "verticalBorderSize", ",", "boxSizing", ",", "}", ";", "}", "return", "computedStyleCache", "[", "reactId", "]", ";", "}" ]
Returns an object containing the computed style and the combined vertical padding size, combined vertical border size and box-sizing value. This style is returned as string to be applied as attribute of an element.
[ "Returns", "an", "object", "containing", "the", "computed", "style", "and", "the", "combined", "vertical", "padding", "size", "combined", "vertical", "border", "size", "and", "box", "-", "sizing", "value", "." ]
e0f561d6ad704b5e3d66a38752de29f938b065af
https://github.com/nikgraf/belle/blob/e0f561d6ad704b5e3d66a38752de29f938b065af/src/utils/calculate-textarea-height.js#L46-L88
15,376
nikgraf/belle
src/components/TextInput.js
sanitizeChildProps
function sanitizeChildProps(properties) { const childProps = omit(properties, Object.keys(textInputPropTypes)); if (typeof properties.valueLink === 'object') { childProps.value = properties.valueLink.value; } return childProps; }
javascript
function sanitizeChildProps(properties) { const childProps = omit(properties, Object.keys(textInputPropTypes)); if (typeof properties.valueLink === 'object') { childProps.value = properties.valueLink.value; } return childProps; }
[ "function", "sanitizeChildProps", "(", "properties", ")", "{", "const", "childProps", "=", "omit", "(", "properties", ",", "Object", ".", "keys", "(", "textInputPropTypes", ")", ")", ";", "if", "(", "typeof", "properties", ".", "valueLink", "===", "'object'", ")", "{", "childProps", ".", "value", "=", "properties", ".", "valueLink", ".", "value", ";", "}", "return", "childProps", ";", "}" ]
Returns an object with properties that are relevant for the TextInput's textarea. As the height of the textarea needs to be calculated valueLink can not be passed down to the textarea, but made available through this component.
[ "Returns", "an", "object", "with", "properties", "that", "are", "relevant", "for", "the", "TextInput", "s", "textarea", "." ]
e0f561d6ad704b5e3d66a38752de29f938b065af
https://github.com/nikgraf/belle/blob/e0f561d6ad704b5e3d66a38752de29f938b065af/src/components/TextInput.js#L41-L48
15,377
irislib/iris-lib
dist/irisLib.js
isBuffer
function isBuffer(obj) { return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) }
javascript
function isBuffer(obj) { return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) }
[ "function", "isBuffer", "(", "obj", ")", "{", "return", "obj", "!=", "null", "&&", "(", "!", "!", "obj", ".", "_isBuffer", "||", "isFastBuffer", "(", "obj", ")", "||", "isSlowBuffer", "(", "obj", ")", ")", "}" ]
the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence The _isBuffer check is for Safari 5-7 support, because it's missing Object.prototype.constructor. Remove this eventually
[ "the", "following", "is", "from", "is", "-", "buffer", "also", "by", "Feross", "Aboukhadijeh", "and", "with", "same", "lisence", "The", "_isBuffer", "check", "is", "for", "Safari", "5", "-", "7", "support", "because", "it", "s", "missing", "Object", ".", "prototype", ".", "constructor", ".", "Remove", "this", "eventually" ]
6a170a49c0ef1ea06ebf8007a9af52e275b80f1d
https://github.com/irislib/iris-lib/blob/6a170a49c0ef1ea06ebf8007a9af52e275b80f1d/dist/irisLib.js#L4595-L4597
15,378
irislib/iris-lib
dist/irisLib.js
copyFromBuffer
function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; }
javascript
function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; }
[ "function", "copyFromBuffer", "(", "n", ",", "list", ")", "{", "var", "ret", "=", "Buffer", ".", "allocUnsafe", "(", "n", ")", ";", "var", "p", "=", "list", ".", "head", ";", "var", "c", "=", "1", ";", "p", ".", "data", ".", "copy", "(", "ret", ")", ";", "n", "-=", "p", ".", "data", ".", "length", ";", "while", "(", "p", "=", "p", ".", "next", ")", "{", "var", "buf", "=", "p", ".", "data", ";", "var", "nb", "=", "n", ">", "buf", ".", "length", "?", "buf", ".", "length", ":", "n", ";", "buf", ".", "copy", "(", "ret", ",", "ret", ".", "length", "-", "n", ",", "0", ",", "nb", ")", ";", "n", "-=", "nb", ";", "if", "(", "n", "===", "0", ")", "{", "if", "(", "nb", "===", "buf", ".", "length", ")", "{", "++", "c", ";", "if", "(", "p", ".", "next", ")", "list", ".", "head", "=", "p", ".", "next", ";", "else", "list", ".", "head", "=", "list", ".", "tail", "=", "null", ";", "}", "else", "{", "list", ".", "head", "=", "p", ";", "p", ".", "data", "=", "buf", ".", "slice", "(", "nb", ")", ";", "}", "break", ";", "}", "++", "c", ";", "}", "list", ".", "length", "-=", "c", ";", "return", "ret", ";", "}" ]
Copies a specified amount of bytes from the list of buffered data chunks. This function is designed to be inlinable, so please take care when making changes to the function body.
[ "Copies", "a", "specified", "amount", "of", "bytes", "from", "the", "list", "of", "buffered", "data", "chunks", ".", "This", "function", "is", "designed", "to", "be", "inlinable", "so", "please", "take", "care", "when", "making", "changes", "to", "the", "function", "body", "." ]
6a170a49c0ef1ea06ebf8007a9af52e275b80f1d
https://github.com/irislib/iris-lib/blob/6a170a49c0ef1ea06ebf8007a9af52e275b80f1d/dist/irisLib.js#L6956-L6981
15,379
irislib/iris-lib
dist/irisLib.js
Hash
function Hash (blockSize, finalSize) { this._block = Buffer$4.alloc(blockSize); this._finalSize = finalSize; this._blockSize = blockSize; this._len = 0; }
javascript
function Hash (blockSize, finalSize) { this._block = Buffer$4.alloc(blockSize); this._finalSize = finalSize; this._blockSize = blockSize; this._len = 0; }
[ "function", "Hash", "(", "blockSize", ",", "finalSize", ")", "{", "this", ".", "_block", "=", "Buffer$4", ".", "alloc", "(", "blockSize", ")", ";", "this", ".", "_finalSize", "=", "finalSize", ";", "this", ".", "_blockSize", "=", "blockSize", ";", "this", ".", "_len", "=", "0", ";", "}" ]
prototype class for hash functions
[ "prototype", "class", "for", "hash", "functions" ]
6a170a49c0ef1ea06ebf8007a9af52e275b80f1d
https://github.com/irislib/iris-lib/blob/6a170a49c0ef1ea06ebf8007a9af52e275b80f1d/dist/irisLib.js#L8173-L8178
15,380
irislib/iris-lib
dist/irisLib.js
write
function write(buffer, offs) { for (var i = 2; i < arguments.length; i++) { for (var j = 0; j < arguments[i].length; j++) { buffer[offs++] = arguments[i].charAt(j); } } }
javascript
function write(buffer, offs) { for (var i = 2; i < arguments.length; i++) { for (var j = 0; j < arguments[i].length; j++) { buffer[offs++] = arguments[i].charAt(j); } } }
[ "function", "write", "(", "buffer", ",", "offs", ")", "{", "for", "(", "var", "i", "=", "2", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "arguments", "[", "i", "]", ".", "length", ";", "j", "++", ")", "{", "buffer", "[", "offs", "++", "]", "=", "arguments", "[", "i", "]", ".", "charAt", "(", "j", ")", ";", "}", "}", "}" ]
helper functions for that ctx
[ "helper", "functions", "for", "that", "ctx" ]
6a170a49c0ef1ea06ebf8007a9af52e275b80f1d
https://github.com/irislib/iris-lib/blob/6a170a49c0ef1ea06ebf8007a9af52e275b80f1d/dist/irisLib.js#L9148-L9154
15,381
irislib/iris-lib
dist/irisLib.js
crc32
function crc32(png, offs, size) { var crc = -1; for (var i = 4; i < size-4; i += 1) { crc = _crc32[(crc ^ png[offs+i].charCodeAt(0)) & 0xff] ^ ((crc >> 8) & 0x00ffffff); } write(png, offs+size-4, byte4(crc ^ -1)); }
javascript
function crc32(png, offs, size) { var crc = -1; for (var i = 4; i < size-4; i += 1) { crc = _crc32[(crc ^ png[offs+i].charCodeAt(0)) & 0xff] ^ ((crc >> 8) & 0x00ffffff); } write(png, offs+size-4, byte4(crc ^ -1)); }
[ "function", "crc32", "(", "png", ",", "offs", ",", "size", ")", "{", "var", "crc", "=", "-", "1", ";", "for", "(", "var", "i", "=", "4", ";", "i", "<", "size", "-", "4", ";", "i", "+=", "1", ")", "{", "crc", "=", "_crc32", "[", "(", "crc", "^", "png", "[", "offs", "+", "i", "]", ".", "charCodeAt", "(", "0", ")", ")", "&", "0xff", "]", "^", "(", "(", "crc", ">>", "8", ")", "&", "0x00ffffff", ")", ";", "}", "write", "(", "png", ",", "offs", "+", "size", "-", "4", ",", "byte4", "(", "crc", "^", "-", "1", ")", ")", ";", "}" ]
compute crc32 of the PNG chunks
[ "compute", "crc32", "of", "the", "PNG", "chunks" ]
6a170a49c0ef1ea06ebf8007a9af52e275b80f1d
https://github.com/irislib/iris-lib/blob/6a170a49c0ef1ea06ebf8007a9af52e275b80f1d/dist/irisLib.js#L9322-L9328
15,382
irislib/iris-lib
dist/irisLib.js
searchText
async function searchText(node, callback, query, limit) { var cursor = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : ''; var desc = arguments[5]; var seen = {}; console.log('cursor', cursor, 'query', query, 'desc', desc); var q = desc ? { '<': cursor, '-': desc } : { '>': cursor, '-': desc }; node.get({ '.': q, '%': 20 * 1000 }).once().map().on(function (value, key) { console.log('searchText', value, key); if (key.indexOf(query) === 0) { if (typeof limit === 'number' && _Object$keys(seen).length >= limit) { return; } if (seen.hasOwnProperty(key)) { return; } if (value && _Object$keys(value).length > 1) { seen[key] = true; callback({ value: value, key: key }); } } }); }
javascript
async function searchText(node, callback, query, limit) { var cursor = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : ''; var desc = arguments[5]; var seen = {}; console.log('cursor', cursor, 'query', query, 'desc', desc); var q = desc ? { '<': cursor, '-': desc } : { '>': cursor, '-': desc }; node.get({ '.': q, '%': 20 * 1000 }).once().map().on(function (value, key) { console.log('searchText', value, key); if (key.indexOf(query) === 0) { if (typeof limit === 'number' && _Object$keys(seen).length >= limit) { return; } if (seen.hasOwnProperty(key)) { return; } if (value && _Object$keys(value).length > 1) { seen[key] = true; callback({ value: value, key: key }); } } }); }
[ "async", "function", "searchText", "(", "node", ",", "callback", ",", "query", ",", "limit", ")", "{", "var", "cursor", "=", "arguments", ".", "length", ">", "4", "&&", "arguments", "[", "4", "]", "!==", "undefined", "?", "arguments", "[", "4", "]", ":", "''", ";", "var", "desc", "=", "arguments", "[", "5", "]", ";", "var", "seen", "=", "{", "}", ";", "console", ".", "log", "(", "'cursor'", ",", "cursor", ",", "'query'", ",", "query", ",", "'desc'", ",", "desc", ")", ";", "var", "q", "=", "desc", "?", "{", "'<'", ":", "cursor", ",", "'-'", ":", "desc", "}", ":", "{", "'>'", ":", "cursor", ",", "'-'", ":", "desc", "}", ";", "node", ".", "get", "(", "{", "'.'", ":", "q", ",", "'%'", ":", "20", "*", "1000", "}", ")", ".", "once", "(", ")", ".", "map", "(", ")", ".", "on", "(", "function", "(", "value", ",", "key", ")", "{", "console", ".", "log", "(", "'searchText'", ",", "value", ",", "key", ")", ";", "if", "(", "key", ".", "indexOf", "(", "query", ")", "===", "0", ")", "{", "if", "(", "typeof", "limit", "===", "'number'", "&&", "_Object$keys", "(", "seen", ")", ".", "length", ">=", "limit", ")", "{", "return", ";", "}", "if", "(", "seen", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "return", ";", "}", "if", "(", "value", "&&", "_Object$keys", "(", "value", ")", ".", "length", ">", "1", ")", "{", "seen", "[", "key", "]", "=", "true", ";", "callback", "(", "{", "value", ":", "value", ",", "key", ":", "key", "}", ")", ";", "}", "}", "}", ")", ";", "}" ]
temp method for GUN search
[ "temp", "method", "for", "GUN", "search" ]
6a170a49c0ef1ea06ebf8007a9af52e275b80f1d
https://github.com/irislib/iris-lib/blob/6a170a49c0ef1ea06ebf8007a9af52e275b80f1d/dist/irisLib.js#L10842-L10864
15,383
Medium/medium-sdk-nodejs
lib/mediumClient.js
MediumClient
function MediumClient(options) { this._enforce(options, ['clientId', 'clientSecret']) this._clientId = options.clientId this._clientSecret = options.clientSecret this._accessToken = "" }
javascript
function MediumClient(options) { this._enforce(options, ['clientId', 'clientSecret']) this._clientId = options.clientId this._clientSecret = options.clientSecret this._accessToken = "" }
[ "function", "MediumClient", "(", "options", ")", "{", "this", ".", "_enforce", "(", "options", ",", "[", "'clientId'", ",", "'clientSecret'", "]", ")", "this", ".", "_clientId", "=", "options", ".", "clientId", "this", ".", "_clientSecret", "=", "options", ".", "clientSecret", "this", ".", "_accessToken", "=", "\"\"", "}" ]
The core client. @param {{ clientId: string, clientSecret: string }} options @constructor
[ "The", "core", "client", "." ]
63539084fb26f4c39f8c70f6baa599f866b38b9a
https://github.com/Medium/medium-sdk-nodejs/blob/63539084fb26f4c39f8c70f6baa599f866b38b9a/lib/mediumClient.js#L85-L90
15,384
microlinkhq/metascraper
bench/index.js
getResults
function getResults () { return getHtmls(URLS).then(htmls => { return getScrapersResults(SCRAPERS, URLS, htmls).then(results => results) }) }
javascript
function getResults () { return getHtmls(URLS).then(htmls => { return getScrapersResults(SCRAPERS, URLS, htmls).then(results => results) }) }
[ "function", "getResults", "(", ")", "{", "return", "getHtmls", "(", "URLS", ")", ".", "then", "(", "htmls", "=>", "{", "return", "getScrapersResults", "(", "SCRAPERS", ",", "URLS", ",", "htmls", ")", ".", "then", "(", "results", "=>", "results", ")", "}", ")", "}" ]
Get the metadata results. @return {Promise} results
[ "Get", "the", "metadata", "results", "." ]
0220c2a23351a97ba57f6d2a80c44da22f22b5f7
https://github.com/microlinkhq/metascraper/blob/0220c2a23351a97ba57f6d2a80c44da22f22b5f7/bench/index.js#L47-L51
15,385
microlinkhq/metascraper
bench/index.js
getScrapersResults
function getScrapersResults (SCRAPERS, urls, htmls) { return Promise.all( SCRAPERS.map(SCRAPER => { return getScraperResults(SCRAPER, urls, htmls).then(results => { return { name: SCRAPER.name, results: results } }) }) ) }
javascript
function getScrapersResults (SCRAPERS, urls, htmls) { return Promise.all( SCRAPERS.map(SCRAPER => { return getScraperResults(SCRAPER, urls, htmls).then(results => { return { name: SCRAPER.name, results: results } }) }) ) }
[ "function", "getScrapersResults", "(", "SCRAPERS", ",", "urls", ",", "htmls", ")", "{", "return", "Promise", ".", "all", "(", "SCRAPERS", ".", "map", "(", "SCRAPER", "=>", "{", "return", "getScraperResults", "(", "SCRAPER", ",", "urls", ",", "htmls", ")", ".", "then", "(", "results", "=>", "{", "return", "{", "name", ":", "SCRAPER", ".", "name", ",", "results", ":", "results", "}", "}", ")", "}", ")", ")", "}" ]
Get the metadata results from all `SCRAPERS` and `urls` and `htmls`. @param {Array} SCRAPERS @param {Array} urls @param {Array} htmls @return {Promise} results
[ "Get", "the", "metadata", "results", "from", "all", "SCRAPERS", "and", "urls", "and", "htmls", "." ]
0220c2a23351a97ba57f6d2a80c44da22f22b5f7
https://github.com/microlinkhq/metascraper/blob/0220c2a23351a97ba57f6d2a80c44da22f22b5f7/bench/index.js#L62-L73
15,386
microlinkhq/metascraper
bench/index.js
getScraperResults
function getScraperResults (SCRAPER, urls, htmls) { return Promise.all( urls.map((url, i) => { const html = htmls[i] const name = SCRAPER.name const Module = require(name) return SCRAPER.scrape(Module, url, html).then(metadata => { return SCRAPER.normalize(metadata) }) }) ) }
javascript
function getScraperResults (SCRAPER, urls, htmls) { return Promise.all( urls.map((url, i) => { const html = htmls[i] const name = SCRAPER.name const Module = require(name) return SCRAPER.scrape(Module, url, html).then(metadata => { return SCRAPER.normalize(metadata) }) }) ) }
[ "function", "getScraperResults", "(", "SCRAPER", ",", "urls", ",", "htmls", ")", "{", "return", "Promise", ".", "all", "(", "urls", ".", "map", "(", "(", "url", ",", "i", ")", "=>", "{", "const", "html", "=", "htmls", "[", "i", "]", "const", "name", "=", "SCRAPER", ".", "name", "const", "Module", "=", "require", "(", "name", ")", "return", "SCRAPER", ".", "scrape", "(", "Module", ",", "url", ",", "html", ")", ".", "then", "(", "metadata", "=>", "{", "return", "SCRAPER", ".", "normalize", "(", "metadata", ")", "}", ")", "}", ")", ")", "}" ]
Get metadata results from a single `SCRAPER` and `urls` and `htmls`. @param {Object} SCRAPER @param {Array} urls @param {Array} htmls @return {Promise} results
[ "Get", "metadata", "results", "from", "a", "single", "SCRAPER", "and", "urls", "and", "htmls", "." ]
0220c2a23351a97ba57f6d2a80c44da22f22b5f7
https://github.com/microlinkhq/metascraper/blob/0220c2a23351a97ba57f6d2a80c44da22f22b5f7/bench/index.js#L84-L95
15,387
microlinkhq/metascraper
bench/index.js
getHtmls
function getHtmls (urls) { return Promise.all(urls.map(url => got(url).then(res => res.body))) }
javascript
function getHtmls (urls) { return Promise.all(urls.map(url => got(url).then(res => res.body))) }
[ "function", "getHtmls", "(", "urls", ")", "{", "return", "Promise", ".", "all", "(", "urls", ".", "map", "(", "url", "=>", "got", "(", "url", ")", ".", "then", "(", "res", "=>", "res", ".", "body", ")", ")", ")", "}" ]
Get html from a list of `urls`. @param {Array} urls @return {Promise} htmls
[ "Get", "html", "from", "a", "list", "of", "urls", "." ]
0220c2a23351a97ba57f6d2a80c44da22f22b5f7
https://github.com/microlinkhq/metascraper/blob/0220c2a23351a97ba57f6d2a80c44da22f22b5f7/bench/index.js#L104-L106
15,388
jneen/parsimmon
src/parsimmon.js
union
function union(xs, ys) { var obj = {}; for (var i = 0; i < xs.length; i++) { obj[xs[i]] = true; } for (var j = 0; j < ys.length; j++) { obj[ys[j]] = true; } var keys = []; for (var k in obj) { if ({}.hasOwnProperty.call(obj, k)) { keys.push(k); } } keys.sort(); return keys; }
javascript
function union(xs, ys) { var obj = {}; for (var i = 0; i < xs.length; i++) { obj[xs[i]] = true; } for (var j = 0; j < ys.length; j++) { obj[ys[j]] = true; } var keys = []; for (var k in obj) { if ({}.hasOwnProperty.call(obj, k)) { keys.push(k); } } keys.sort(); return keys; }
[ "function", "union", "(", "xs", ",", "ys", ")", "{", "var", "obj", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "xs", ".", "length", ";", "i", "++", ")", "{", "obj", "[", "xs", "[", "i", "]", "]", "=", "true", ";", "}", "for", "(", "var", "j", "=", "0", ";", "j", "<", "ys", ".", "length", ";", "j", "++", ")", "{", "obj", "[", "ys", "[", "j", "]", "]", "=", "true", ";", "}", "var", "keys", "=", "[", "]", ";", "for", "(", "var", "k", "in", "obj", ")", "{", "if", "(", "{", "}", ".", "hasOwnProperty", ".", "call", "(", "obj", ",", "k", ")", ")", "{", "keys", ".", "push", "(", "k", ")", ";", "}", "}", "keys", ".", "sort", "(", ")", ";", "return", "keys", ";", "}" ]
Returns the sorted set union of two arrays of strings
[ "Returns", "the", "sorted", "set", "union", "of", "two", "arrays", "of", "strings" ]
f71a73882383013628cdd87017ae1617c765cf93
https://github.com/jneen/parsimmon/blob/f71a73882383013628cdd87017ae1617c765cf93/src/parsimmon.js#L379-L395
15,389
jneen/parsimmon
src/parsimmon.js
rangeFromIndexAndOffsets
function rangeFromIndexAndOffsets(i, before, after, length) { return { // Guard against the negative upper bound for lines included in the output. from: i - before > 0 ? i - before : 0, to: i + after > length ? length : i + after }; }
javascript
function rangeFromIndexAndOffsets(i, before, after, length) { return { // Guard against the negative upper bound for lines included in the output. from: i - before > 0 ? i - before : 0, to: i + after > length ? length : i + after }; }
[ "function", "rangeFromIndexAndOffsets", "(", "i", ",", "before", ",", "after", ",", "length", ")", "{", "return", "{", "// Guard against the negative upper bound for lines included in the output.", "from", ":", "i", "-", "before", ">", "0", "?", "i", "-", "before", ":", "0", ",", "to", ":", "i", "+", "after", ">", "length", "?", "length", ":", "i", "+", "after", "}", ";", "}" ]
Get a range of indexes including `i`-th element and `before` and `after` amount of elements from `arr`.
[ "Get", "a", "range", "of", "indexes", "including", "i", "-", "th", "element", "and", "before", "and", "after", "amount", "of", "elements", "from", "arr", "." ]
f71a73882383013628cdd87017ae1617c765cf93
https://github.com/jneen/parsimmon/blob/f71a73882383013628cdd87017ae1617c765cf93/src/parsimmon.js#L504-L510
15,390
jneen/parsimmon
examples/math.js
PREFIX
function PREFIX(operatorsParser, nextParser) { let parser = P.lazy(() => { return P.seq(operatorsParser, parser).or(nextParser); }); return parser; }
javascript
function PREFIX(operatorsParser, nextParser) { let parser = P.lazy(() => { return P.seq(operatorsParser, parser).or(nextParser); }); return parser; }
[ "function", "PREFIX", "(", "operatorsParser", ",", "nextParser", ")", "{", "let", "parser", "=", "P", ".", "lazy", "(", "(", ")", "=>", "{", "return", "P", ".", "seq", "(", "operatorsParser", ",", "parser", ")", ".", "or", "(", "nextParser", ")", ";", "}", ")", ";", "return", "parser", ";", "}" ]
Takes a parser for the prefix operator, and a parser for the base thing being parsed, and parses as many occurrences as possible of the prefix operator. Note that the parser is created using `P.lazy` because it's recursive. It's valid for there to be zero occurrences of the prefix operator.
[ "Takes", "a", "parser", "for", "the", "prefix", "operator", "and", "a", "parser", "for", "the", "base", "thing", "being", "parsed", "and", "parses", "as", "many", "occurrences", "as", "possible", "of", "the", "prefix", "operator", ".", "Note", "that", "the", "parser", "is", "created", "using", "P", ".", "lazy", "because", "it", "s", "recursive", ".", "It", "s", "valid", "for", "there", "to", "be", "zero", "occurrences", "of", "the", "prefix", "operator", "." ]
f71a73882383013628cdd87017ae1617c765cf93
https://github.com/jneen/parsimmon/blob/f71a73882383013628cdd87017ae1617c765cf93/examples/math.js#L43-L48
15,391
ngReact/ngReact
ngReact.js
findAttribute
function findAttribute(attrs, propName) { var index = Object.keys(attrs).filter(function (attr) { return attr.toLowerCase() === propName.toLowerCase(); })[0]; return attrs[index]; }
javascript
function findAttribute(attrs, propName) { var index = Object.keys(attrs).filter(function (attr) { return attr.toLowerCase() === propName.toLowerCase(); })[0]; return attrs[index]; }
[ "function", "findAttribute", "(", "attrs", ",", "propName", ")", "{", "var", "index", "=", "Object", ".", "keys", "(", "attrs", ")", ".", "filter", "(", "function", "(", "attr", ")", "{", "return", "attr", ".", "toLowerCase", "(", ")", "===", "propName", ".", "toLowerCase", "(", ")", ";", "}", ")", "[", "0", "]", ";", "return", "attrs", "[", "index", "]", ";", "}" ]
find the normalized attribute knowing that React props accept any type of capitalization
[ "find", "the", "normalized", "attribute", "knowing", "that", "React", "props", "accept", "any", "type", "of", "capitalization" ]
5f91c2e6bc976eb1aca7517adb448e4f07ff5d98
https://github.com/ngReact/ngReact/blob/5f91c2e6bc976eb1aca7517adb448e4f07ff5d98/ngReact.js#L162-L167
15,392
ngReact/ngReact
ngReact.js
function() { var scopeProps = {}, config = {}; props.forEach(function(prop) { var propName = getPropName(prop); scopeProps[propName] = scope.$eval(findAttribute(attrs, propName)); config[propName] = getPropConfig(prop); }); scopeProps = applyFunctions(scopeProps, scope, config); scopeProps = angular.extend({}, scopeProps, injectableProps); renderComponent(reactComponent, scopeProps, scope, elem); }
javascript
function() { var scopeProps = {}, config = {}; props.forEach(function(prop) { var propName = getPropName(prop); scopeProps[propName] = scope.$eval(findAttribute(attrs, propName)); config[propName] = getPropConfig(prop); }); scopeProps = applyFunctions(scopeProps, scope, config); scopeProps = angular.extend({}, scopeProps, injectableProps); renderComponent(reactComponent, scopeProps, scope, elem); }
[ "function", "(", ")", "{", "var", "scopeProps", "=", "{", "}", ",", "config", "=", "{", "}", ";", "props", ".", "forEach", "(", "function", "(", "prop", ")", "{", "var", "propName", "=", "getPropName", "(", "prop", ")", ";", "scopeProps", "[", "propName", "]", "=", "scope", ".", "$eval", "(", "findAttribute", "(", "attrs", ",", "propName", ")", ")", ";", "config", "[", "propName", "]", "=", "getPropConfig", "(", "prop", ")", ";", "}", ")", ";", "scopeProps", "=", "applyFunctions", "(", "scopeProps", ",", "scope", ",", "config", ")", ";", "scopeProps", "=", "angular", ".", "extend", "(", "{", "}", ",", "scopeProps", ",", "injectableProps", ")", ";", "renderComponent", "(", "reactComponent", ",", "scopeProps", ",", "scope", ",", "elem", ")", ";", "}" ]
for each of the properties, get their scope value and set it to scope.props
[ "for", "each", "of", "the", "properties", "get", "their", "scope", "value", "and", "set", "it", "to", "scope", ".", "props" ]
5f91c2e6bc976eb1aca7517adb448e4f07ff5d98
https://github.com/ngReact/ngReact/blob/5f91c2e6bc976eb1aca7517adb448e4f07ff5d98/ngReact.js#L275-L285
15,393
marcelduran/webpagetest-api
lib/helper.js
netLogParser
function netLogParser(data) { data = (data || '{}').toString(); if (data.slice(data.length - 3) === ',\r\n') { data = data.slice(0, data.length - 3) + ']}'; } return JSON.parse(data); }
javascript
function netLogParser(data) { data = (data || '{}').toString(); if (data.slice(data.length - 3) === ',\r\n') { data = data.slice(0, data.length - 3) + ']}'; } return JSON.parse(data); }
[ "function", "netLogParser", "(", "data", ")", "{", "data", "=", "(", "data", "||", "'{}'", ")", ".", "toString", "(", ")", ";", "if", "(", "data", ".", "slice", "(", "data", ".", "length", "-", "3", ")", "===", "',\\r\\n'", ")", "{", "data", "=", "data", ".", "slice", "(", "0", ",", "data", ".", "length", "-", "3", ")", "+", "']}'", ";", "}", "return", "JSON", ".", "parse", "(", "data", ")", ";", "}" ]
Net log has a buggy end of file, attempt to fix
[ "Net", "log", "has", "a", "buggy", "end", "of", "file", "attempt", "to", "fix" ]
9c4d4d89aa9637319bdc4d170211e19abafafda7
https://github.com/marcelduran/webpagetest-api/blob/9c4d4d89aa9637319bdc4d170211e19abafafda7/lib/helper.js#L121-L128
15,394
marcelduran/webpagetest-api
lib/helper.js
scriptToString
function scriptToString(data) { var script = []; data.forEach(function dataEach(step) { var key, value; if (typeof step === 'string') { script.push(step); } else if (typeof step === 'object') { key = [Object.keys(step)[0]]; value = step[key]; if (value !== undefined && value !== null && value !== '') { key = key.concat(value); } script.push(key.join(TAB)); } }); return script.join(NEWLINE); }
javascript
function scriptToString(data) { var script = []; data.forEach(function dataEach(step) { var key, value; if (typeof step === 'string') { script.push(step); } else if (typeof step === 'object') { key = [Object.keys(step)[0]]; value = step[key]; if (value !== undefined && value !== null && value !== '') { key = key.concat(value); } script.push(key.join(TAB)); } }); return script.join(NEWLINE); }
[ "function", "scriptToString", "(", "data", ")", "{", "var", "script", "=", "[", "]", ";", "data", ".", "forEach", "(", "function", "dataEach", "(", "step", ")", "{", "var", "key", ",", "value", ";", "if", "(", "typeof", "step", "===", "'string'", ")", "{", "script", ".", "push", "(", "step", ")", ";", "}", "else", "if", "(", "typeof", "step", "===", "'object'", ")", "{", "key", "=", "[", "Object", ".", "keys", "(", "step", ")", "[", "0", "]", "]", ";", "value", "=", "step", "[", "key", "]", ";", "if", "(", "value", "!==", "undefined", "&&", "value", "!==", "null", "&&", "value", "!==", "''", ")", "{", "key", "=", "key", ".", "concat", "(", "value", ")", ";", "}", "script", ".", "push", "(", "key", ".", "join", "(", "TAB", ")", ")", ";", "}", "}", ")", ";", "return", "script", ".", "join", "(", "NEWLINE", ")", ";", "}" ]
Convert script objects into formatted string
[ "Convert", "script", "objects", "into", "formatted", "string" ]
9c4d4d89aa9637319bdc4d170211e19abafafda7
https://github.com/marcelduran/webpagetest-api/blob/9c4d4d89aa9637319bdc4d170211e19abafafda7/lib/helper.js#L136-L155
15,395
marcelduran/webpagetest-api
lib/helper.js
dryRun
function dryRun(config, path) { path = url.parse(path, true); return { url: url.format({ protocol: config.protocol, hostname: config.hostname, port: (config.port !== 80 && config.port !== 443 ? config.port : undefined), pathname: path.pathname, query: path.query }) }; }
javascript
function dryRun(config, path) { path = url.parse(path, true); return { url: url.format({ protocol: config.protocol, hostname: config.hostname, port: (config.port !== 80 && config.port !== 443 ? config.port : undefined), pathname: path.pathname, query: path.query }) }; }
[ "function", "dryRun", "(", "config", ",", "path", ")", "{", "path", "=", "url", ".", "parse", "(", "path", ",", "true", ")", ";", "return", "{", "url", ":", "url", ".", "format", "(", "{", "protocol", ":", "config", ".", "protocol", ",", "hostname", ":", "config", ".", "hostname", ",", "port", ":", "(", "config", ".", "port", "!==", "80", "&&", "config", ".", "port", "!==", "443", "?", "config", ".", "port", ":", "undefined", ")", ",", "pathname", ":", "path", ".", "pathname", ",", "query", ":", "path", ".", "query", "}", ")", "}", ";", "}" ]
Build the RESTful API url call only
[ "Build", "the", "RESTful", "API", "url", "call", "only" ]
9c4d4d89aa9637319bdc4d170211e19abafafda7
https://github.com/marcelduran/webpagetest-api/blob/9c4d4d89aa9637319bdc4d170211e19abafafda7/lib/helper.js#L158-L171
15,396
marcelduran/webpagetest-api
lib/helper.js
normalizeServer
function normalizeServer(server) { // normalize hostname if (!reProtocol.test(server)) { server = 'http://' + server; } server = url.parse(server); return { protocol: server.protocol, hostname: server.hostname, auth: server.auth, pathname: server.pathname, port: parseInt(server.port, 10) || (server.protocol === 'https:' ? 443 : 80) }; }
javascript
function normalizeServer(server) { // normalize hostname if (!reProtocol.test(server)) { server = 'http://' + server; } server = url.parse(server); return { protocol: server.protocol, hostname: server.hostname, auth: server.auth, pathname: server.pathname, port: parseInt(server.port, 10) || (server.protocol === 'https:' ? 443 : 80) }; }
[ "function", "normalizeServer", "(", "server", ")", "{", "// normalize hostname", "if", "(", "!", "reProtocol", ".", "test", "(", "server", ")", ")", "{", "server", "=", "'http://'", "+", "server", ";", "}", "server", "=", "url", ".", "parse", "(", "server", ")", ";", "return", "{", "protocol", ":", "server", ".", "protocol", ",", "hostname", ":", "server", ".", "hostname", ",", "auth", ":", "server", ".", "auth", ",", "pathname", ":", "server", ".", "pathname", ",", "port", ":", "parseInt", "(", "server", ".", "port", ",", "10", ")", "||", "(", "server", ".", "protocol", "===", "'https:'", "?", "443", ":", "80", ")", "}", ";", "}" ]
Normalize server config
[ "Normalize", "server", "config" ]
9c4d4d89aa9637319bdc4d170211e19abafafda7
https://github.com/marcelduran/webpagetest-api/blob/9c4d4d89aa9637319bdc4d170211e19abafafda7/lib/helper.js#L174-L188
15,397
marcelduran/webpagetest-api
lib/helper.js
localhost
function localhost(local, defaultPort) { // edge case when hostname:port is not informed via cli if (local === undefined || local === 'true') { local = [defaultPort]; } else { local = local.toString().split(':'); } return { hostname: reIp.test(local[0]) || isNaN(parseInt(local[0], 10)) && local[0] ? local[0] : os.hostname(), port: parseInt(local[1] || (!reIp.test(local[0]) && local[0]), 10) || defaultPort }; }
javascript
function localhost(local, defaultPort) { // edge case when hostname:port is not informed via cli if (local === undefined || local === 'true') { local = [defaultPort]; } else { local = local.toString().split(':'); } return { hostname: reIp.test(local[0]) || isNaN(parseInt(local[0], 10)) && local[0] ? local[0] : os.hostname(), port: parseInt(local[1] || (!reIp.test(local[0]) && local[0]), 10) || defaultPort }; }
[ "function", "localhost", "(", "local", ",", "defaultPort", ")", "{", "// edge case when hostname:port is not informed via cli", "if", "(", "local", "===", "undefined", "||", "local", "===", "'true'", ")", "{", "local", "=", "[", "defaultPort", "]", ";", "}", "else", "{", "local", "=", "local", ".", "toString", "(", ")", ".", "split", "(", "':'", ")", ";", "}", "return", "{", "hostname", ":", "reIp", ".", "test", "(", "local", "[", "0", "]", ")", "||", "isNaN", "(", "parseInt", "(", "local", "[", "0", "]", ",", "10", ")", ")", "&&", "local", "[", "0", "]", "?", "local", "[", "0", "]", ":", "os", ".", "hostname", "(", ")", ",", "port", ":", "parseInt", "(", "local", "[", "1", "]", "||", "(", "!", "reIp", ".", "test", "(", "local", "[", "0", "]", ")", "&&", "local", "[", "0", "]", ")", ",", "10", ")", "||", "defaultPort", "}", ";", "}" ]
Normalize localhost and port
[ "Normalize", "localhost", "and", "port" ]
9c4d4d89aa9637319bdc4d170211e19abafafda7
https://github.com/marcelduran/webpagetest-api/blob/9c4d4d89aa9637319bdc4d170211e19abafafda7/lib/helper.js#L191-L205
15,398
marcelduran/webpagetest-api
lib/helper.js
setQuery
function setQuery(map, options, query) { query = query || {}; options = options || {}; map.options.forEach(function eachOpts(opt) { Object.keys(opt).forEach(function eachOpt(key) { var param = opt[key], name = param.name, value = options[name] || options[key]; if (value !== undefined && param.api) { if (param.array) { value = [].concat(value).join(' '); } query[param.api] = param.bool ? param.invert ? (value ? 0 : 1) : (value ? 1 : 0) : value; } }); }); return query; }
javascript
function setQuery(map, options, query) { query = query || {}; options = options || {}; map.options.forEach(function eachOpts(opt) { Object.keys(opt).forEach(function eachOpt(key) { var param = opt[key], name = param.name, value = options[name] || options[key]; if (value !== undefined && param.api) { if (param.array) { value = [].concat(value).join(' '); } query[param.api] = param.bool ? param.invert ? (value ? 0 : 1) : (value ? 1 : 0) : value; } }); }); return query; }
[ "function", "setQuery", "(", "map", ",", "options", ",", "query", ")", "{", "query", "=", "query", "||", "{", "}", ";", "options", "=", "options", "||", "{", "}", ";", "map", ".", "options", ".", "forEach", "(", "function", "eachOpts", "(", "opt", ")", "{", "Object", ".", "keys", "(", "opt", ")", ".", "forEach", "(", "function", "eachOpt", "(", "key", ")", "{", "var", "param", "=", "opt", "[", "key", "]", ",", "name", "=", "param", ".", "name", ",", "value", "=", "options", "[", "name", "]", "||", "options", "[", "key", "]", ";", "if", "(", "value", "!==", "undefined", "&&", "param", ".", "api", ")", "{", "if", "(", "param", ".", "array", ")", "{", "value", "=", "[", "]", ".", "concat", "(", "value", ")", ".", "join", "(", "' '", ")", ";", "}", "query", "[", "param", ".", "api", "]", "=", "param", ".", "bool", "?", "param", ".", "invert", "?", "(", "value", "?", "0", ":", "1", ")", ":", "(", "value", "?", "1", ":", "0", ")", ":", "value", ";", "}", "}", ")", ";", "}", ")", ";", "return", "query", ";", "}" ]
Set valid parameter in query
[ "Set", "valid", "parameter", "in", "query" ]
9c4d4d89aa9637319bdc4d170211e19abafafda7
https://github.com/marcelduran/webpagetest-api/blob/9c4d4d89aa9637319bdc4d170211e19abafafda7/lib/helper.js#L217-L238
15,399
marcelduran/webpagetest-api
lib/mapping.js
setOptions
function setOptions(command, query) { var count, opts; command = commands[command]; if (!command) { return; } opts = {}; count = Object.keys(query).length; [options.common].concat(command.options).some(function someTypes(options) { if (!options) { return; } Object.keys(options).some(function someOptions(key) { var valid = options[key].valid; if (key in query) { if (options[key].bool) { opts[options[key].name] = !reBool.test(query[key]); } else if (!valid || (valid && valid.test(query[key]))) { opts[options[key].name] = decodeURIComponent(query[key]); } count -= 1; } return count === 0; }); return count === 0; }); return opts; }
javascript
function setOptions(command, query) { var count, opts; command = commands[command]; if (!command) { return; } opts = {}; count = Object.keys(query).length; [options.common].concat(command.options).some(function someTypes(options) { if (!options) { return; } Object.keys(options).some(function someOptions(key) { var valid = options[key].valid; if (key in query) { if (options[key].bool) { opts[options[key].name] = !reBool.test(query[key]); } else if (!valid || (valid && valid.test(query[key]))) { opts[options[key].name] = decodeURIComponent(query[key]); } count -= 1; } return count === 0; }); return count === 0; }); return opts; }
[ "function", "setOptions", "(", "command", ",", "query", ")", "{", "var", "count", ",", "opts", ";", "command", "=", "commands", "[", "command", "]", ";", "if", "(", "!", "command", ")", "{", "return", ";", "}", "opts", "=", "{", "}", ";", "count", "=", "Object", ".", "keys", "(", "query", ")", ".", "length", ";", "[", "options", ".", "common", "]", ".", "concat", "(", "command", ".", "options", ")", ".", "some", "(", "function", "someTypes", "(", "options", ")", "{", "if", "(", "!", "options", ")", "{", "return", ";", "}", "Object", ".", "keys", "(", "options", ")", ".", "some", "(", "function", "someOptions", "(", "key", ")", "{", "var", "valid", "=", "options", "[", "key", "]", ".", "valid", ";", "if", "(", "key", "in", "query", ")", "{", "if", "(", "options", "[", "key", "]", ".", "bool", ")", "{", "opts", "[", "options", "[", "key", "]", ".", "name", "]", "=", "!", "reBool", ".", "test", "(", "query", "[", "key", "]", ")", ";", "}", "else", "if", "(", "!", "valid", "||", "(", "valid", "&&", "valid", ".", "test", "(", "query", "[", "key", "]", ")", ")", ")", "{", "opts", "[", "options", "[", "key", "]", ".", "name", "]", "=", "decodeURIComponent", "(", "query", "[", "key", "]", ")", ";", "}", "count", "-=", "1", ";", "}", "return", "count", "===", "0", ";", "}", ")", ";", "return", "count", "===", "0", ";", "}", ")", ";", "return", "opts", ";", "}" ]
set valid options only per command
[ "set", "valid", "options", "only", "per", "command" ]
9c4d4d89aa9637319bdc4d170211e19abafafda7
https://github.com/marcelduran/webpagetest-api/blob/9c4d4d89aa9637319bdc4d170211e19abafafda7/lib/mapping.js#L837-L871