_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q50200
signWithLocalPrivateKey
train
function signWithLocalPrivateKey(wallet_id, account, is_change, address_index, text_to_sign, handleSig){ var path = "m/44'/0'/" + account + "'/"+is_change+"/"+address_index; var privateKey = xPrivKey.derive(path).privateKey; var privKeyBuf = privateKey.bn.toBuffer({size:32}); // https://github.com/bitpay/bitcore-lib/issues/47 handleSig(ecdsaSig.sign(text_to_sign, privKeyBuf)); }
javascript
{ "resource": "" }
q50201
readSingleAddress
train
function readSingleAddress(conn, handleAddress){ readSingleWallet(conn, function(wallet_id){ conn.query("SELECT address FROM my_addresses WHERE wallet=?", [wallet_id], function(rows){ if (rows.length === 0) throw Error("no addresses"); if (rows.length > 1) throw Error("more than 1 address"); handleAddress(rows[0].address); }); }) }
javascript
{ "resource": "" }
q50202
readSingleWallet
train
function readSingleWallet(conn, handleWallet){ conn.query("SELECT wallet FROM wallets", function(rows){ if (rows.length === 0) throw Error("no wallets"); if (rows.length > 1) throw Error("more than 1 wallet"); handleWallet(rows[0].wallet); }); }
javascript
{ "resource": "" }
q50203
readMinerDeposit
train
function readMinerDeposit( sSuperNodeAddress, pfnCallback ) { readMinerAddress( sSuperNodeAddress, function( err, sMinerAddress ) { if ( err ) { return pfnCallback( err ); } // // query deposit // let nDeposit = 0; // ... return pfnCallback( null, nDeposit ); }); }
javascript
{ "resource": "" }
q50204
getSavingCallbacks
train
function getSavingCallbacks(callbacks){ return { ifError: callbacks.ifError, ifNotEnoughFunds: callbacks.ifNotEnoughFunds, ifOk: function(objJoint, private_payload, composer_unlock){ var objUnit = objJoint.unit; var unit = objUnit.unit; validation.validate(objJoint, { ifUnitError: function(err){ composer_unlock(); callbacks.ifError("Validation error: "+err); // throw Error("unexpected validation error: "+err); }, ifJointError: function(err){ throw Error("unexpected validation joint error: "+err); }, ifTransientError: function(err){ throw Error("unexpected validation transient error: "+err); }, ifNeedHashTree: function(){ throw Error("unexpected need hash tree"); }, ifNeedParentUnits: function(arrMissingUnits){ throw Error("unexpected dependencies: "+arrMissingUnits.join(", ")); }, ifOk: function(objValidationState, validation_unlock){ console.log("divisible asset OK "+objValidationState.sequence); if (objValidationState.sequence !== 'good'){ validation_unlock(); composer_unlock(); return callbacks.ifError("Divisible asset bad sequence "+objValidationState.sequence); } var bPrivate = !!private_payload; var objPrivateElement; var preCommitCallback = null; if (bPrivate){ preCommitCallback = function(conn, cb){ var payload_hash = objectHash.getBase64Hash(private_payload); var message_index = composer.getMessageIndexByPayloadHash(objUnit, payload_hash); objPrivateElement = { unit: unit, message_index: message_index, payload: private_payload }; validateAndSaveDivisiblePrivatePayment(conn, objPrivateElement, { ifError: function(err){ cb(err); }, ifOk: function(){ cb(); } }); }; } composer.postJointToLightVendorIfNecessaryAndSave( objJoint, function onLightError(err){ // light only console.log("failed to post divisible payment "+unit); validation_unlock(); composer_unlock(); callbacks.ifError(err); }, function save(){ writer.saveJoint( objJoint, objValidationState, preCommitCallback, function onDone(err){ console.log("saved unit "+unit, objPrivateElement); validation_unlock(); composer_unlock(); var arrChains = objPrivateElement ? [[objPrivateElement]] : null; // only one chain that consists of one element callbacks.ifOk(objJoint, arrChains, arrChains); } ); } ); } // ifOk validation }); // validate } }; }
javascript
{ "resource": "" }
q50205
pickDivisibleCoinsForAmount
train
function pickDivisibleCoinsForAmount(conn, objAsset, arrAddresses, last_ball_mci, amount, bMultiAuthored, onDone){ var asset = objAsset ? objAsset.asset : null; console.log("pick coins "+asset+" amount "+amount); var is_base = objAsset ? 0 : 1; var arrInputsWithProofs = []; var total_amount = 0; var required_amount = amount; // adds element to arrInputsWithProofs function addInput(input){ total_amount += input.amount; var objInputWithProof = {input: input}; if (objAsset && objAsset.is_private){ // for type=payment only var spend_proof = objectHash.getBase64Hash({ asset: asset, amount: input.amount, address: input.address, unit: input.unit, message_index: input.message_index, output_index: input.output_index, blinding: input.blinding }); var objSpendProof = {spend_proof: spend_proof}; if (bMultiAuthored) objSpendProof.address = input.address; objInputWithProof.spend_proof = objSpendProof; } if (!bMultiAuthored || !input.type) delete input.address; delete input.amount; delete input.blinding; arrInputsWithProofs.push(objInputWithProof); } // first, try to find a coin just bigger than the required amount function pickOneCoinJustBiggerAndContinue(){ if (amount === Infinity) return pickMultipleCoinsAndContinue(); var more = is_base ? '>' : '>='; conn.query( "SELECT unit, message_index, output_index, amount, blinding, address \n\ FROM outputs \n\ CROSS JOIN units USING(unit) \n\ WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 AND amount "+more+" ? \n\ AND is_stable=1 AND sequence='good' AND main_chain_index<=? \n\ ORDER BY amount LIMIT 1", [arrSpendableAddresses, amount+is_base*TRANSFER_INPUT_SIZE, last_ball_mci], function(rows){ if (rows.length === 1){ var input = rows[0]; // default type is "transfer" addInput(input); onDone(arrInputsWithProofs, total_amount); } else pickMultipleCoinsAndContinue(); } ); } // then, try to add smaller coins until we accumulate the target amount function pickMultipleCoinsAndContinue(){ conn.query( "SELECT unit, message_index, output_index, amount, address, blinding \n\ FROM outputs \n\ CROSS JOIN units USING(unit) \n\ WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 \n\ AND is_stable=1 AND sequence='good' AND main_chain_index<=? \n\ ORDER BY amount DESC", [arrSpendableAddresses, last_ball_mci], function(rows){ async.eachSeries( rows, function(row, cb){ var input = row; objectHash.cleanNulls(input); required_amount += is_base*TRANSFER_INPUT_SIZE; addInput(input); // if we allow equality, we might get 0 amount for change which is invalid var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount); bFound ? cb('found') : cb(); }, function(err){ if (err === 'found') onDone(arrInputsWithProofs, total_amount); else if (asset) issueAsset(); else{ // pow modi //addHeadersCommissionInputs(); finish(); } } ); } ); } // pow del // function addHeadersCommissionInputs(){ // addMcInputs("headers_commission", HEADERS_COMMISSION_INPUT_SIZE, // headers_commission.getMaxSpendableMciForLastBallMci(last_ball_mci), addWitnessingInputs); // } // function addWitnessingInputs(){ // addMcInputs("witnessing", WITNESSING_INPUT_SIZE, paid_witnessing.getMaxSpendableMciForLastBallMci(last_ball_mci), issueAsset); // } // function addMcInputs(type, input_size, max_mci, onStillNotEnough){ // async.eachSeries( // arrAddresses, // function(address, cb){ // var target_amount = required_amount + input_size + (bMultiAuthored ? ADDRESS_SIZE : 0) - total_amount; // mc_outputs.findMcIndexIntervalToTargetAmount(conn, type, address, max_mci, target_amount, { // ifNothing: cb, // ifFound: function(from_mc_index, to_mc_index, earnings, bSufficient){ // if (earnings === 0) // throw Error("earnings === 0"); // total_amount += earnings; // var input = { // type: type, // from_main_chain_index: from_mc_index, // to_main_chain_index: to_mc_index // }; // var full_input_size = input_size; // if (bMultiAuthored){ // full_input_size += ADDRESS_SIZE; // address length // input.address = address; // } // required_amount += full_input_size; // arrInputsWithProofs.push({input: input}); // (total_amount > required_amount) // ? cb("found") // break eachSeries // : cb(); // try next address // } // }); // }, // function(err){ // if (!err) // console.log(arrAddresses+" "+type+": got only "+total_amount+" out of required "+required_amount); // (err === "found") ? onDone(arrInputsWithProofs, total_amount) : onStillNotEnough(); // } // ); // } function issueAsset(){ if (!asset) return finish(); else{ if (amount === Infinity && !objAsset.cap) // don't try to create infinite issue return onDone(null); } console.log("will try to issue asset "+asset); // for issue, we use full list of addresses rather than spendable addresses if (objAsset.issued_by_definer_only && arrAddresses.indexOf(objAsset.definer_address) === -1) return finish(); var issuer_address = objAsset.issued_by_definer_only ? objAsset.definer_address : arrAddresses[0]; var issue_amount = objAsset.cap || (required_amount - total_amount) || 1; // 1 currency unit in case required_amount = total_amount function addIssueInput(serial_number){ total_amount += issue_amount; var input = { type: "issue", amount: issue_amount, serial_number: serial_number }; if (bMultiAuthored) input.address = issuer_address; var objInputWithProof = {input: input}; if (objAsset && objAsset.is_private){ var spend_proof = objectHash.getBase64Hash({ asset: asset, amount: issue_amount, denomination: 1, address: issuer_address, serial_number: serial_number }); var objSpendProof = {spend_proof: spend_proof}; if (bMultiAuthored) objSpendProof.address = input.address; objInputWithProof.spend_proof = objSpendProof; } arrInputsWithProofs.push(objInputWithProof); var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount); bFound ? onDone(arrInputsWithProofs, total_amount) : finish(); } if (objAsset.cap){ conn.query("SELECT 1 FROM inputs WHERE type='issue' AND asset=?", [asset], function(rows){ if (rows.length > 0) // already issued return finish(); addIssueInput(1); }); } else{ conn.query( "SELECT MAX(serial_number) AS max_serial_number FROM inputs WHERE type='issue' AND asset=? AND address=?", [asset, issuer_address], function(rows){ var max_serial_number = (rows.length === 0) ? 0 : rows[0].max_serial_number; addIssueInput(max_serial_number+1); } ); } } function finish(){ if (amount === Infinity && arrInputsWithProofs.length > 0) onDone(arrInputsWithProofs, total_amount); else onDone(null); } var arrSpendableAddresses = arrAddresses.concat(); // cloning if (objAsset && objAsset.auto_destroy){ var i = arrAddresses.indexOf(objAsset.definer_address); if (i>=0) arrSpendableAddresses.splice(i, 1); } if (arrSpendableAddresses.length > 0) pickOneCoinJustBiggerAndContinue(); else issueAsset(); }
javascript
{ "resource": "" }
q50206
composePowJoint
train
function composePowJoint(from_address, round_index, seed, deposit, solution, signer, callbacks){ var payload = {seed: seed, deposit:deposit, solution: solution}; var objMessage = { app: "pow_equihash", payload_location: "inline", payload_hash: objectHash.getBase64Hash(payload), payload: payload }; composeJoint({ paying_addresses: [from_address], outputs: [{address: from_address, amount: 0}], messages: [objMessage], round_index: round_index, pow_type: constants.POW_TYPE_POW_EQUHASH, signer: signer, callbacks: callbacks }); }
javascript
{ "resource": "" }
q50207
composeTrustMEJoint
train
function composeTrustMEJoint(from_address, round_index, signer, callbacks){ composeJoint({ paying_addresses: [from_address], outputs: [{address: from_address, amount: 0}], round_index: round_index, pow_type: constants.POW_TYPE_TRUSTME, signer: signer, callbacks: callbacks }); }
javascript
{ "resource": "" }
q50208
composeCoinbaseJoint
train
function composeCoinbaseJoint(from_address, coinbase_address, round_index, coinbase_amount, signer, callbacks){ var coinbase_foundation_amount = Math.floor(coinbase_amount*constants.FOUNDATION_RATIO); composeJoint({ paying_addresses: [from_address], outputs: [{address: coinbase_address, amount: 0}, {address: constants.FOUNDATION_ADDRESS, amount: coinbase_foundation_amount}], //inputs: [{type: "coinbase", amount: coinbase_amount, address: from_address}], inputs: [{type: "coinbase", amount: coinbase_amount}], round_index: round_index, input_amount: coinbase_amount, pow_type: constants.POW_TYPE_COIN_BASE, signer: signer, callbacks: callbacks }); }
javascript
{ "resource": "" }
q50209
connectToServer
train
function connectToServer( oOptions ) { let sUrl; let oWs; if ( 'object' !== typeof oOptions ) { throw new Error( 'call connectToServer with invalid oOptions' ); } if ( 'string' !== typeof oOptions.minerGateway || 0 === oOptions.minerGateway.length ) { throw new Error( 'call connectToServer with invalid oOptions.minerGateway' ); } if ( 'function' !== typeof oOptions.onOpen ) { throw new Error( 'call connectToServer with invalid oOptions.onOpen' ); } if ( 'function' !== typeof oOptions.onMessage ) { throw new Error( 'call connectToServer with invalid oOptions.onMessage' ); } if ( 'function' !== typeof oOptions.onError ) { throw new Error( 'call connectToServer with invalid oOptions.onError' ); } if ( 'function' !== typeof oOptions.onClose ) { throw new Error( 'call connectToServer with invalid oOptions.onClose' ); } // ... sUrl = oOptions.minerGateway; sUrl = sUrl.trim().toLowerCase(); oWs = new WebSocket( sUrl ); // // set max listeners for EventEmitter // oWs.on( 'open', () => { let oAnotherWsToTheSameServer; if ( ! oWs.url ) { throw new Error( "no url on ws" ); } // // browser implementation of Web Socket might add '/' // if ( oWs.url !== sUrl && oWs.url !== sUrl + "/" ) { throw new Error( `url is different: ${ oWs.url }` ); } // ... oAnotherWsToTheSameServer = _cacheGetHandleByUrl( sUrl ); if ( oAnotherWsToTheSameServer ) { // // duplicate driver. // May happen if we abondoned a driver attempt after timeout // but it still succeeded while we opened another driver // console.log( `already have a connection to ${ sUrl }, will keep the old one and close the duplicate` ); oWs.close( 1000, 'duplicate driver' ); // ... return oOptions.onOpen( null, oWs ); } // // almost done! // oWs.peer = sUrl; // peer oWs.host = _getHostByPeerUrl( sUrl ); // host oWs.bOutbound = true; // identify this driver as outbound driver oWs.last_ts = Date.now(); // record the last timestamp while we connected to this peer // ... console.log( `connected to ${ sUrl }, host ${ oWs.host }` ); // // cache new socket handle // _cacheAddHandle( oWs ); // ... return oOptions.onOpen( null, oWs ); }); oWs.on( 'message', ( sMessage ) => { oOptions.onMessage( oWs, sMessage ); }); oWs.on( 'close', () => { _cacheRemoveHandle( oWs ); oOptions.onClose( oWs, `socket was close` ); }); oWs.on( 'error', ( vError ) => { oOptions.onError( oWs, vError ); }); }
javascript
{ "resource": "" }
q50210
sendMessageOnce
train
function sendMessageOnce( oWs, sCommand, jsonMessage ) { // ... sendMessage( oWs, sCommand, jsonMessage ); // ... let nCheckInterval = setInterval( () => { if ( 0 === oWs.bufferedAmount ) { // Im' not busy anymore - set a flag or something like that clearInterval( nCheckInterval ); nCheckInterval = null; // close socket oWs.close( 1000, 'done' ); } }, 50 ); }
javascript
{ "resource": "" }
q50211
_cacheGetHandleByUrl
train
function _cacheGetHandleByUrl( sUrl ) { let oRet; let arrResult; if ( 'string' !== typeof sUrl || 0 === sUrl.length ) { return null; } // ... oRet = null; sUrl = sUrl.trim().toLowerCase(); arrResult = m_arrCacheOutboundPeers.filter( oSocket => oSocket.peer === sUrl ); if ( Array.isArray( arrResult ) && 1 === arrResult.length ) { oRet = arrResult[ 0 ]; } return oRet; }
javascript
{ "resource": "" }
q50212
_cacheAddHandle
train
function _cacheAddHandle( oSocket ) { if ( ! oSocket ) { return false; } // ... _cacheRemoveHandle( oSocket ); m_arrCacheOutboundPeers.push( oSocket ); return true; }
javascript
{ "resource": "" }
q50213
_cacheRemoveHandle
train
function _cacheRemoveHandle( oSocket ) { let bRet; let nIndex; if ( ! oSocket ) { return false; } // ... bRet = false; nIndex = m_arrCacheOutboundPeers.indexOf( oSocket ); if ( -1 !== nIndex ) { bRet = true; m_arrCacheOutboundPeers.splice( nIndex, 1 ); } return bRet; }
javascript
{ "resource": "" }
q50214
_getHostByPeerUrl
train
function _getHostByPeerUrl( sUrl ) { let arrMatches; // // this regex will match wss://xxx and ws://xxx // arrMatches = sUrl.match( /^wss?:\/\/(.*)$/i ); if ( Array.isArray( arrMatches ) && arrMatches.length >= 1 ) { sUrl = arrMatches[ 1 ]; } // ... arrMatches = sUrl.match( /^(.*?)[:\/]/ ); return ( Array.isArray( arrMatches ) && arrMatches.length >= 1 ) ? arrMatches[ 1 ] : sUrl; }
javascript
{ "resource": "" }
q50215
_getRemoteAddress
train
function _getRemoteAddress( oSocket ) { let sRet; if ( 'object' !== typeof oSocket ) { return null; } // ... sRet = oSocket.upgradeReq.connection.remoteAddress; if ( sRet ) { // // check for proxy // ONLY VALID FOR 127.0.0.1 and resources addresses // if ( oSocket.upgradeReq.headers[ 'x-real-ip' ] && _isValidResourceAddress( sRet ) ) { // we are behind a proxy sRet = oSocket.upgradeReq.headers[ 'x-real-ip' ]; } } return sRet; }
javascript
{ "resource": "" }
q50216
validateUnit
train
function validateUnit( objUnit, bRequireDefinitionOrChange, cb2 ) { let bFound = false; _async.eachSeries ( objUnit.authors, function( author, cb3 ) { let sAddress = author.address; if ( -1 === arrFoundTrustMEAuthors.indexOf( sAddress ) ) { // not a witness - skip it return cb3(); } // // the latest definition chash of the witness // let definition_chash = assocDefinitionChashes[ sAddress ]; if ( ! definition_chash ) { throw Error( "definition chash not known for address " + sAddress ); } if ( author.definition ) { // // do transaction for the first time // if ( _object_hash.getChash160( author.definition ) !== definition_chash ) { return cb3( "definition doesn't hash to the expected value" ); } assocDefinitions[ definition_chash ] = author.definition; bFound = true; } function handleAuthor() { // FIX _validation.validateAuthorSignaturesWithoutReferences ( author, objUnit, assocDefinitions[ definition_chash ], // definition JSON function( err ) { if ( err ) { return cb3( err ); } // // okay, definition is valid // for ( let i = 0; i < objUnit.messages.length; i++ ) { let message = objUnit.messages[ i ]; if ( 'address_definition_change' === message.app && ( message.payload.address === sAddress || 1 === objUnit.authors.length && objUnit.authors[ 0 ].address === sAddress ) ) { assocDefinitionChashes[ sAddress ] = message.payload.definition_chash; bFound = true; } } // ... cb3(); } ); } if ( assocDefinitions[ definition_chash ] ) { return handleAuthor(); } // // only an address with money // there is no transaction any more // _storage.readDefinition( _db, definition_chash, { ifFound : function( arrDefinition ) { assocDefinitions[ definition_chash ] = arrDefinition; handleAuthor(); }, ifDefinitionNotFound : function( sDefinitionCHash ) { throw Error( "definition " + definition_chash + " not found, address " + sAddress ); } }); }, function( err ) { if ( err ) { return cb2( err ); } if ( bRequireDefinitionOrChange && ! bFound ) { // // bRequireDefinitionOrChange always be false // so, you will never arrive here so far // return cb2( "neither definition nor change" ); } // ... cb2(); } ); // each authors }
javascript
{ "resource": "" }
q50217
isDepositDefinition
train
function isDepositDefinition(arrDefinition){ if (!validationUtils.isArrayOfLength(arrDefinition, 2)) return false; if (arrDefinition[0] !== 'or') return false; if (!validationUtils.isArrayOfLength(arrDefinition[1], 2)) return false; if (!validationUtils.isArrayOfLength(arrDefinition[1][0], 2)) return false; if (!validationUtils.isArrayOfLength(arrDefinition[1][1], 2)) return false; if (arrDefinition[1][0][1] !== constants.FOUNDATION_SAFE_ADDRESS) return false; if(!validationUtils.isValidAddress(arrDefinition[1][1][1])) return false; return true; }
javascript
{ "resource": "" }
q50218
hasInvalidUnitsFromHistory
train
function hasInvalidUnitsFromHistory(conn, address, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(address)) return cb("param address is null or empty string"); if(!validationUtils.isValidAddress(address)) return cb("param address is not a valid address"); conn.query( "SELECT address FROM units JOIN unit_authors USING(unit) \n\ WHERE is_stable=1 AND sequence!='good' AND address=?", [address], function(rows){ cb(null, rows.length > 0 ? true : false); } ); }
javascript
{ "resource": "" }
q50219
getBalanceOfDepositContract
train
function getBalanceOfDepositContract(conn, depositAddress, roundIndex, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(depositAddress)) return cb("param depositAddress is null or empty string"); if(!validationUtils.isValidAddress(depositAddress)) return cb("param depositAddress is not a valid address"); if(!validationUtils.isPositiveInteger(roundIndex)) return cb("param roundIndex is not a positive integer"); if(roundIndex === 1) return cb(null, 0); //WHERE src_unit=? AND src_message_index=? AND src_output_index=? \n\ round.getMaxMciByRoundIndex(conn, roundIndex-1, function(lastRoundMaxMci){ var sumBanlance = 0; conn.query("SELECT src_unit, src_message_index, src_output_index AS count \n\ FROM inputs JOIN units USING(unit) \n\ WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index>? AND address=?", [lastRoundMaxMci, depositAddress], function(rowsInputs) { conn.query("SELECT unit, is_spent, amount, message_index, output_index \n\ FROM outputs JOIN units USING(unit) \n\ WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index<=? AND address=?", [lastRoundMaxMci, depositAddress], function(rowsOutputs) { if (rowsOutputs.length === 0) return cb(null, 0); for (var i=0; i<rowsOutputs.length; i++) { if(rowsOutputs[i].is_spent === 0) { sumBanlance += rowsOutputs[i].amount; } else { if(rowsInputs.length > 0) { for (var j=0; j<rowsInputs.length; j++) { if(rowsInputs[j].src_unit === rowsOutputs[i].unit && rowsInputs[j].src_message_index === rowsOutputs[i].message_index && rowsInputs[j].src_output_index === rowsOutputs[i].output_index ){ sumBanlance += rowsOutputs[i].amount; } } } } } cb(null, sumBanlance); }); }); }); }
javascript
{ "resource": "" }
q50220
getBalanceOfAllDepositContract
train
function getBalanceOfAllDepositContract(conn, roundIndex, cb){ var conn = conn || db; if(!validationUtils.isPositiveInteger(roundIndex)) return cb("param roundIndex is not a positive integer"); round.getMaxMciByRoundIndex(conn, roundIndex, function(lastRoundMaxMci){ conn.query("SELECT deposit_address FROM supernode", function(rowsDepositAddress) { var arrDepositAddress = rowsDepositAddress.map(function(row){ return row.deposit_address; }); var strDepositAddress = arrDepositAddress.map(db.escape).join(', '); conn.query("SELECT sum(amount) AS sumBanlance \n\ FROM outputs JOIN units USING(unit) \n\ WHERE asset IS NULL AND sequence='good' AND is_stable=1 AND main_chain_index<=? \n\ AND address IN("+strDepositAddress+")", [lastRoundMaxMci], function(rowsOutputs) { if (rowsOutputs.length === 0) return cb(null, 0); cb(null, parseInt(rowsOutputs[0].sumBanlance)); }); }); }); }
javascript
{ "resource": "" }
q50221
getDepositAddressBySafeAddress
train
function getDepositAddressBySafeAddress(conn, safeAddress, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(safeAddress)) return cb("param safeAddress is null or empty string"); if(!validationUtils.isValidAddress(safeAddress)) return cb("param safeAddress is not a valid address"); const arrDefinition = [ 'or', [ ['address', constants.FOUNDATION_SAFE_ADDRESS], ['address', safeAddress], ] ]; const depositAddress = objectHash.getChash160(arrDefinition); conn.query("SELECT definition FROM shared_addresses WHERE shared_address = ?", [depositAddress], function(rows) { if (rows.length !== 1 ) return cb("deposit Address is not found when getDepositAddressBySafeAddress " + safeAddress); cb(null, depositAddress); }); }
javascript
{ "resource": "" }
q50222
getDepositAddressBySupernodeAddress
train
function getDepositAddressBySupernodeAddress(conn, supernodeAddress, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(supernodeAddress)) return cb("param supernodeAddress is null or empty string"); if(!validationUtils.isValidAddress(supernodeAddress)) return cb("param supernodeAddress is not a valid address"); conn.query("SELECT deposit_address FROM supernode WHERE address = ?", [supernodeAddress], function(rows) { if (rows.length !== 1 ) return cb("deposit address is not found when getDepositAddressBySupernodeAddress " + supernodeAddress); cb(null, rows[0].deposit_address); }); }
javascript
{ "resource": "" }
q50223
getSupernodeByDepositAddress
train
function getSupernodeByDepositAddress(conn, depositAddress, cb){ var conn = conn || db; if(!validationUtils.isNonemptyString(depositAddress)) return cb("param depostiAddress is null or empty string"); if(!validationUtils.isValidAddress(depositAddress)) return cb("param depostiAddress is not a valid address"); conn.query("SELECT address, safe_address FROM supernode WHERE deposit_address = ?", [depositAddress], function(rows) { if (rows.length !== 1 ) return cb("supernodeAddress is not found"); cb(null, rows); }); }
javascript
{ "resource": "" }
q50224
createDepositAddress
train
function createDepositAddress(my_address, callback) { var arrDefinition = [ 'or', [ ['address', constants.FOUNDATION_SAFE_ADDRESS], ['address', my_address], ] ]; var shared_address = objectHash.getChash160(arrDefinition) if(isDepositDefinition(arrDefinition)){ return callback.ifOk(shared_address) } else { return callback.ifError(JSON.stringify(arrDefinition) + ' is not a valid deposit definiton') } }
javascript
{ "resource": "" }
q50225
validateProposalJoint
train
function validateProposalJoint(objJoint, callbacks){ var objUnit = objJoint.unit; if (typeof objUnit !== "object" || objUnit === null) return callbacks.ifInvalid("no unit object"); console.log("\nvalidating joint identified by unit "+objJoint.unit.unit); if (!isStringOfLength(objUnit.unit, constants.HASH_LENGTH)) return callbacks.ifInvalid("wrong unit length"); // UnitError is linked to objUnit.unit, so we need to ensure objUnit.unit is true before we throw any UnitErrors if (objectHash.getProposalUnitHash(objUnit) !== objUnit.unit){ // console.log("888888888888888888888888--Proposal joint : " + JSON.stringify(objJoint)); return callbacks.ifInvalid("wrong proposal unit hash: "+objectHash.getProposalUnitHash(objUnit)+" != "+objUnit.unit); } if (hasFieldsExcept(objUnit, ["unit", "version", "alt" ,"round_index","pow_type","timestamp", "parent_units", "last_ball", "last_ball_unit", "messages", "hp"])) return callbacks.ifInvalid("unknown fields in nonserial unit"); if (objUnit.version !== constants.version) return callbacks.ifInvalid("wrong version"); if (objUnit.alt !== constants.alt) return callbacks.ifInvalid("wrong alt"); if (typeof objUnit.round_index !== "number") return callbacks.ifInvalid("no round index"); if (typeof objUnit.pow_type !== "number") return callbacks.ifInvalid("no pow_type type"); if (typeof objUnit.hp !== "number") return callbacks.ifInvalid("no hp type"); // pow_type type should be 2 for trustme if ( objUnit.pow_type !== constants.POW_TYPE_TRUSTME) return callbacks.ifInvalid("invalid unit type"); // unity round index should be in range of [1,4204800] if ( objUnit.round_index < 1 || objUnit.round_index > 4204800) return callbacks.ifInvalid("invalid unit round index"); if (!isNonemptyArray(objUnit.messages)) return callbacks.ifInvalid("missing or empty messages array"); // only one 'data_feed' message allowed in trust me units. if (objUnit.messages.length !== 1) return callbacks.ifInvalid("only one message allowed in proposal unit"); // Joint fields validation add last_ball_mci for only proposal joint, used for final trustme unit if (hasFieldsExcept(objJoint, ["unit", "proposer", "phase", "address","last_ball_mci", "idv","vp","isValid","sig"])) return callbacks.ifInvalid("unknown fields in joint unit " + json.stringify(objJoint)); if (typeof objJoint.phase !== "number" || objJoint.phase < 0 ) return callbacks.ifInvalid("joint phase invalid"); if(objJoint.proposer && objJoint.proposer.length !== 1) return callbacks.ifInvalid("multiple proposers are not allowed"); var conn = null; var objValidationState = { }; async.series( [ function(cb){ db.takeConnectionFromPool(function(new_conn){ conn = new_conn; conn.query("BEGIN", function(){cb();}); }); }, function(cb){ //validate roundIndex and hp (mci) to see if I am sync with proposer mci //if not, return -1 to let caller knows . round.getCurrentRoundIndex(conn, function(curRoundIndex){ if(objUnit.round_index < curRoundIndex) return cb("proposer's round_index is too old, curRoundIndex: " + curRoundIndex + " proposer round_index: " +objUnit.round_index ); if(objUnit.round_index > curRoundIndex) return cb({error_code: "unresolved_dependency", errorMessage:"propose round_index is ahead of me , curRoundIndex: " + curRoundIndex + " proposer round_index: " +objUnit.round_index }); storage.getMaxMci(conn,function(curMCI){ if(objUnit.hp < curMCI + 1) // recieve old proposal return cb("proposal hp is old, will discard it"); if(objUnit.hp > curMCI + 1 ) // propose mci is ahead of me return cb({error_code: "unresolved_dependency", errorMessage:"propose mci is ahead of me, will handle it once come up with it " }); cb(); }); }); }, function(cb){ validateParents(conn, objJoint, objValidationState, cb); }, // function(cb){ // profiler.stop('validation-parents'); // profiler.start(); // !objJoint.skiplist_units // ? cb() // : validateSkiplist(conn, objJoint.skiplist_units, cb); // }, function(cb){ // validate proposer ID byzantine.getCoordinators(conn, objUnit.hp, objJoint.phase, function(err, proposer, round_index, witnesses){ if(err) return cb("error occured when getCoordinators err:" + err); if(proposer !== objJoint.proposer[0].address) return cb("proposer incorrect,Expected: "+ proposer +" Actual :" + objJoint.proposer[0].address); if(round_index !== objUnit.round_index) return cb("proposer round_index incorrect ,Expected: "+ round_index +" Actual :" + objUnit.round_index); objValidationState.unit_hash_to_sign = objectHash.getProposalHashToSign(objUnit); //validate proposer signature validateProposer(conn, objJoint.proposer[0], objUnit, objValidationState, cb); }); }, function(cb){ // check timestamp is near to mine in data feed message validateDataFeedMessage(conn, objUnit.messages[0], objUnit, objValidationState, cb); }, ], function(err){ if(!err){ conn.query("COMMIT", function(){ conn.release(); callbacks.ifOk(); }); } else{ //Error occured here conn.query("ROLLBACK", function(){ conn.release(); if (typeof err === "object"){ if (err.error_code === "unresolved_dependency"){ console.log(err.errorMessage); callbacks.ifNeedWaiting(err.errorMessage); } else throw Error("unknown error code"); } else callbacks.ifInvalid(err); }); } } ); // async.series }
javascript
{ "resource": "" }
q50226
obtainMiningInput
train
function obtainMiningInput( oConn, uRoundIndex, pfnCallback ) { if ( ! oConn ) { throw new Error( `call obtainMiningInput with invalid oConn.` ); } if ( 'number' !== typeof uRoundIndex ) { throw new Error( `call obtainMiningInput with invalid nRoundIndex.` ); } if ( 'function' !== typeof pfnCallback ) { // arguments.callee.name throw new Error( `call obtainMiningInput with invalid pfnCallback.` ); } let sCurrentFirstTrustMEBall = null; let uCurrentBitsValue = null; let sCurrentPublicSeed = null; let sSuperNodeAuthorAddress = null; let sDepositAddress = null; let fDepositBalance = null; _async.series ([ function( pfnNext ) { // // author address of this super node // _super_node.readSingleAddress( oConn, function( sAddress ) { sSuperNodeAuthorAddress = sAddress; return pfnNext(); }); }, function( pfnNext ) { // // get deposit address by super-node address // _deposit.getDepositAddressBySupernodeAddress( oConn, sSuperNodeAuthorAddress, ( err, sAddress ) => { if ( err ) { return pfnNext( err ); } sDepositAddress = sAddress; return pfnNext(); }); }, function( pfnNext ) { // // get deposit amount by deposit address // _deposit.getBalanceOfDepositContract( oConn, sDepositAddress, uRoundIndex, ( err, fBanlance ) => { if ( err ) { return pfnNext( err ); } fDepositBalance = fBanlance; return pfnNext(); }); }, function( pfnNext ) { // // round (N) // obtain ball address of the first TrustME unit from current round // _round.queryFirstTrustMEBallOnMainChainByRoundIndex( oConn, uRoundIndex, function( err, sBall ) { if ( err ) { return pfnNext( err ); } sCurrentFirstTrustMEBall = sBall; return pfnNext(); }); }, function( pfnNext ) { // // round (N) // calculate public seed // _round.getRoundInfoByRoundIndex( oConn, uRoundIndex, function( round_index, min_wl, sSeed ) { sCurrentPublicSeed = sSeed; return pfnNext(); }); }, // function( pfnNext ) // { // // // // round (N) // // calculate bits value // // // _round.getDifficultydByRoundIndex( oConn, uRoundIndex, function( nBits ) // { // nCurrentBitsValue = nBits; // return pfnNext(); // }); // }, function( pfnNext ) { // // calculate bits value // calculateBitsValueByRoundIndexWithDeposit ( oConn, uRoundIndex, fDepositBalance, ( err, uSelfBits ) => { if ( err ) { return pfnCallback( err ); } // ... uCurrentBitsValue = uSelfBits; return pfnNext(); } ); } ], function( err ) { if ( err ) { return pfnCallback( err ); } let objInput = { roundIndex : uRoundIndex, firstTrustMEBall : sCurrentFirstTrustMEBall, bits : uCurrentBitsValue, deposit : fDepositBalance, publicSeed : sCurrentPublicSeed, superNodeAuthor : sSuperNodeAuthorAddress, }; pfnCallback( null, objInput ); }); return true; }
javascript
{ "resource": "" }
q50227
startMiningWithInputs
train
function startMiningWithInputs( oInput, pfnCallback ) { console.log( `>***< will start mining with inputs : ${ JSON.stringify( oInput ) }` ); if ( _bBrowser && ! _bWallet ) { throw new Error( 'I am not be able to run in a Web Browser.' ); } if ( 'object' !== typeof oInput ) { throw new Error( 'call startMiningWithInputs with invalid oInput' ); } if ( 'number' !== typeof oInput.roundIndex ) { throw new Error( 'call startMiningWithInputs with invalid oInput.roundIndex' ); } if ( 'string' !== typeof oInput.firstTrustMEBall || 44 !== oInput.firstTrustMEBall.length ) { throw new Error( 'call startMiningWithInputs with invalid oInput.firstTrustMEBall' ); } if ( 'number' !== typeof oInput.bits || oInput.bits < 0 ) { throw new Error( 'call startMiningWithInputs with invalid oInput.bits' ); } if ( 'string' !== typeof oInput.publicSeed || 0 === oInput.publicSeed.length ) { throw new Error( 'call startMiningWithInputs with invalid oInput.publicSeed' ); } if ( 'string' !== typeof oInput.superNodeAuthor || 0 === oInput.superNodeAuthor.length ) { throw new Error( 'call startMiningWithInputs with invalid oInput.superNodeAuthor' ); } if ( 'function' !== typeof pfnCallback ) { throw new Error( `call startMiningWithInputs with invalid pfnCallback.` ); } if ( _bDebugModel && ! _bUnitTestEnv ) { return _startMiningWithInputs_debug( oInput, pfnCallback ); } /** * start here */ let _oOptions = { bufInputHeader : _createMiningInputBufferFromObject( oInput ), bits : oInput.bits, calcTimes : ( 'number' === typeof oInput.calcTimes ? oInput.calcTimes : 30 ), maxLoop : ( 'number' === typeof oInput.maxLoop ? oInput.maxLoop : 1000000 ), }; console.log( `))) stopMining.` ); _pow_miner.stopMining(); console.log( `))) startMining with options : `, _oOptions ); _pow_miner.startMining( _oOptions, function( err, oData ) { let objSolution = null; if ( null === err ) { console.log( `))) startMining, callback data( ${ typeof oData } ) : `, oData ); if ( oData && 'object' === typeof oData ) { if ( oData.hasOwnProperty( 'win' ) && oData.win ) { console.log( `pow-solution :: WINNER WINNER, CHICKEN DINNER!`, oData ); objSolution = { round : oInput.roundIndex, selfBits : oInput.bits, publicSeed : oInput.publicSeed, nonce : oData.nonce, hash : oData.hashHex }; } else if ( oData.hasOwnProperty( 'gameOver' ) && oData.gameOver ) { err = `pow-solution :: game over!`; } else { err = `pow-solution :: unknown error!`; } } else { err = `pow-solution :: invalid data!`; } } // ... _event_bus.emit( 'pow_mined_gift', err, objSolution ); }); pfnCallback( null ); return true; }
javascript
{ "resource": "" }
q50228
calculatePublicSeedByRoundIndex
train
function calculatePublicSeedByRoundIndex( oConn, nRoundIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call calculatePublicSeedByRoundIndex with invalid oConn` ); } if ( 'number' !== typeof nRoundIndex ) { return pfnCallback( `call calculatePublicSeedByRoundIndex with invalid nRoundIndex` ); } if ( nRoundIndex <= 1 ) { // // round 1 // hard code // return pfnCallback( null, _blakejs.blake2sHex( _constants.GENESIS_UNIT ) ); } let sPreviousPublicSeed = null; let arrPrePreviousCoinBase = null; let sPreviousTrustMEBall = null; _async.series ([ function( pfnNext ) { // public seed queryPublicSeedByRoundIndex( oConn, nRoundIndex - 1, function( err, sSeed ) { if ( err ) { return pfnNext( err ); } if ( 'string' !== typeof sSeed || 0 === sSeed.length ) { return pfnNext( `calculatePublicSeedByRoundIndex got invalid sSeed.` ); } sPreviousPublicSeed = sSeed; return pfnNext(); } ); }, function( pfnNext ) { // coin base if ( 2 === nRoundIndex ) { arrPrePreviousCoinBase = []; return pfnNext(); } // ... _round.queryCoinBaseListByRoundIndex( oConn, nRoundIndex - 1, function( err, arrCoinBaseList ) { if ( err ) { return pfnNext( err ); } if ( ! Array.isArray( arrCoinBaseList ) ) { return pfnNext( 'empty coin base list' ); } if ( _constants.COUNT_WITNESSES !== arrCoinBaseList.length ) { return pfnNext( 'no enough coin base units.' ); } arrPrePreviousCoinBase = arrCoinBaseList; return pfnNext(); } ); }, function( pfnNext ) { // first ball _round.queryFirstTrustMEBallOnMainChainByRoundIndex( oConn, nRoundIndex - 1, function( err, sBall ) { if ( err ) { return pfnNext( err ); } if ( 'string' !== typeof sBall || 0 === sBall.length ) { return pfnNext( `calculatePublicSeedByRoundIndex got invalid sBall.` ); } sPreviousTrustMEBall = sBall; return pfnNext(); } ); } ], function( err ) { if ( err ) { return pfnCallback( err ); } // ... let sSource = "" + sPreviousPublicSeed + _crypto.createHash( 'sha512' ).update( JSON.stringify( arrPrePreviousCoinBase ), 'utf8' ).digest(); + _crypto.createHash( 'sha512' ).update( sPreviousTrustMEBall, 'utf8' ).digest(); pfnCallback( null, _blakejs.blake2sHex( sSource ) ); }); }
javascript
{ "resource": "" }
q50229
queryPublicSeedByRoundIndex
train
function queryPublicSeedByRoundIndex( oConn, nRoundIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call queryPublicSeedByRoundIndex with invalid oConn` ); } if ( 'number' !== typeof nRoundIndex || nRoundIndex <= 0 ) { return pfnCallback( `call queryPublicSeedByRoundIndex with invalid nRoundIndex` ); } oConn.query ( "SELECT seed \ FROM round \ WHERE round_index = ?", [ nRoundIndex ], function( arrRows ) { if ( 0 === arrRows.length ) { return pfnCallback( `seed not found.` ); } return pfnCallback( null, arrRows[ 0 ][ 'seed' ] ); } ); }
javascript
{ "resource": "" }
q50230
queryBitsValueByCycleIndex
train
function queryBitsValueByCycleIndex( oConn, uCycleIndex, pfnCallback ) { if ( ! oConn ) { return pfnCallback( `call queryBitsValueByCycleIndex with invalid oConn` ); } if ( 'number' !== typeof uCycleIndex || uCycleIndex <= 0 ) { return pfnCallback( `call queryBitsValueByCycleIndex with invalid uCycleIndex` ); } oConn.query ( "SELECT bits \ FROM round_cycle \ WHERE cycle_id = ?", [ _round.getCycleIdByRoundIndex( uCycleIndex ) ], function( arrRows ) { if ( 0 === arrRows.length ) { return pfnCallback( `bits not found in table [round_cycle].` ); } return pfnCallback( null, parseInt( arrRows[ 0 ][ 'bits' ] ) ); } ); }
javascript
{ "resource": "" }
q50231
_createMiningInputBufferFromObject
train
function _createMiningInputBufferFromObject( objInput ) { let objInputCpy; let sInput; let bufSha512; let bufMd5; let bufRmd160; let bufSha384; if ( 'object' !== typeof objInput ) { return null; } // ... objInputCpy = { roundIndex : objInput.roundIndex, firstTrustMEBall : objInput.firstTrustMEBall, bits : objInput.bits, publicSeed : objInput.publicSeed, superNodeAuthor : objInput.superNodeAuthor, }; sInput = JSON.stringify( objInputCpy ); bufSha512 = _crypto.createHash( 'sha512' ).update( sInput, 'utf8' ).digest(); bufMd5 = _crypto.createHash( 'md5' ).update( sInput, 'utf8' ).digest(); bufRmd160 = _crypto.createHash( 'rmd160' ).update( sInput, 'utf8' ).digest(); bufSha384 = _crypto.createHash( 'sha384' ).update( sInput, 'utf8' ).digest(); return Buffer.concat( [ bufSha512, bufMd5, bufRmd160, bufSha384 ], 140 ); }
javascript
{ "resource": "" }
q50232
_generateRandomInteger
train
function _generateRandomInteger( nMin, nMax ) { return Math.floor( Math.random() * ( nMax + 1 - nMin ) ) + nMin; }
javascript
{ "resource": "" }
q50233
blockHeaderFromRpc
train
function blockHeaderFromRpc (blockParams) { const blockHeader = new BlockHeader({ parentHash: blockParams.parentHash, uncleHash: blockParams.sha3Uncles, coinbase: blockParams.miner, stateRoot: blockParams.stateRoot, transactionsTrie: blockParams.transactionsRoot, receiptTrie: blockParams.receiptRoot || blockParams.receiptsRoot || ethUtil.SHA3_NULL, bloom: blockParams.logsBloom, difficulty: blockParams.difficulty, number: blockParams.number, gasLimit: blockParams.gasLimit, gasUsed: blockParams.gasUsed, timestamp: blockParams.timestamp, extraData: blockParams.extraData, mixHash: blockParams.mixHash, nonce: blockParams.nonce }) // override hash incase something was missing blockHeader.hash = function () { return ethUtil.toBuffer(blockParams.hash) } return blockHeader }
javascript
{ "resource": "" }
q50234
blockFromRpc
train
function blockFromRpc (blockParams, uncles) { uncles = uncles || [] const block = new Block({ transactions: [], uncleHeaders: [] }) block.header = blockHeaderFromRpc(blockParams) block.transactions = (blockParams.transactions || []).map(function (_txParams) { const txParams = normalizeTxParams(_txParams) // override from address const fromAddress = ethUtil.toBuffer(txParams.from) delete txParams.from const tx = new Transaction(txParams) tx._from = fromAddress tx.getSenderAddress = function () { return fromAddress } // override hash const txHash = ethUtil.toBuffer(txParams.hash) tx.hash = function () { return txHash } return tx }) block.uncleHeaders = uncles.map(function (uncleParams) { return blockHeaderFromRpc(uncleParams) }) return block }
javascript
{ "resource": "" }
q50235
train
function (cb3) { blockChain.getDetails(uncle.hash(), function (err, blockInfo) { // TODO: remove uncles from BC if (blockInfo && blockInfo.isUncle) { cb3(err || 'uncle already included') } else { cb3() } }) }
javascript
{ "resource": "" }
q50236
replacements
train
function replacements(document, original) { var modified = moment().format('YYYY-MM-DD'); var result = original; result = tagReplace(result, 'EOL', '\n'); result = tagReplace(result, 'ID', document.metadata.id); result = tagReplace(result, 'TITLE', document.metadata.title); result = tagReplace(result, 'SERIES', document.metadata.series); result = tagReplace(result, 'SEQUENCE', document.metadata.sequence); result = tagReplace(result, 'COPYRIGHT', document.metadata.copyright); result = tagReplace(result, 'LANGUAGE', document.metadata.language); result = tagReplace(result, 'FILEAS', document.metadata.fileAs); result = tagReplace(result, 'AUTHOR', document.metadata.author); result = tagReplace(result, 'PUBLISHER', document.metadata.publisher); result = tagReplace(result, 'DESCRIPTION', document.metadata.description); result = tagReplace(result, 'PUBLISHED', document.metadata.published); result = tagReplace(result, 'GENRE', document.metadata.genre); result = tagReplace(result, 'TAGS', document.metadata.tags); result = tagReplace(result, 'CONTENTS', document.metadata.contents); result = tagReplace(result, 'SOURCE', document.metadata.source); result = tagReplace(result, 'MODIFIED', modified); return result; }
javascript
{ "resource": "" }
q50237
getContainer
train
function getContainer(document) { var content = structuralFiles.getContainer(document); return replacements(document, replacements(document, content)); }
javascript
{ "resource": "" }
q50238
getNCX
train
function getNCX(document) { var content = structuralFiles.getNCX(document); return replacements(document, replacements(document, content)); }
javascript
{ "resource": "" }
q50239
getTOC
train
function getTOC(document) { var content = ""; if (document.generateContentsCallback) { var callbackContent = document.generateContentsCallback(document.filesForTOC); content = markupFiles.getContents(document, callbackContent); } else { content = markupFiles.getContents(document); } return replacements(document, replacements(document, content)); }
javascript
{ "resource": "" }
q50240
getCover
train
function getCover(document) { var content = markupFiles.getCover(); return replacements(document, replacements(document, content)); }
javascript
{ "resource": "" }
q50241
getCSS
train
function getCSS(document) { var content = document.CSS; return replacements(document, replacements(document, content)); }
javascript
{ "resource": "" }
q50242
getSection
train
function getSection(document, sectionNumber) { var content = markupFiles.getSection(document, sectionNumber); return replacements(document, replacements(document, content)); }
javascript
{ "resource": "" }
q50243
makeFolder
train
function makeFolder(path, cb) { if (cb) { fs.mkdir(path, function (err) { if (err && err.code != 'EEXIST') { throw err; } cb(); }); } }
javascript
{ "resource": "" }
q50244
train
function ( files ) { var me = this; files = files || [ ]; return me.normalizeEntries( files ).filter( function ( entry ) { return entry.changed; } ).map( function ( entry ) { return entry.key; } ); }
javascript
{ "resource": "" }
q50245
train
function ( files ) { files = files || [ ]; var me = this; var nEntries = files.map( function ( file ) { return me.getFileDescriptor( file ); } ); //normalizeEntries = nEntries; return nEntries; }
javascript
{ "resource": "" }
q50246
train
function ( noPrune ) { removeNotFoundFiles(); noPrune = typeof noPrune === 'undefined' ? true : noPrune; var entries = normalizedEntries; var keys = Object.keys( entries ); if ( keys.length === 0 ) { return; } var me = this; keys.forEach( function ( entryName ) { var cacheEntry = entries[ entryName ]; try { var meta = useChecksum ? me._getMetaForFileUsingCheckSum( cacheEntry ) : me._getMetaForFileUsingMtimeAndSize( cacheEntry ); cache.setKey( entryName, meta ); } catch (err) { // if the file does not exists we don't save it // other errors are just thrown if ( err.code !== 'ENOENT' ) { throw err; } } } ); cache.save( noPrune ); }
javascript
{ "resource": "" }
q50247
typeOf
train
function typeOf (value) { if (value === null) return 'null' var valueType = typeof value if (valueType === 'object') { valueType = value.constructor.name.toLowerCase() } return valueType }
javascript
{ "resource": "" }
q50248
parseKeyValue
train
function parseKeyValue (str, sep1, sep2) { var result = {} str.split(sep1).forEach(function (kv) { if (kv.length > 0) { kv = kv.split(sep2, 2) result[kv[0]] = parseValue(kv[1]) } }) return result }
javascript
{ "resource": "" }
q50249
smartParse
train
function smartParse (str, sep1, sep2) { sep1 = sep1 || ';' sep2 = sep2 || '=' if ((typeof str === 'string') && str.indexOf(sep1) >= 0) { if (str.indexOf(sep2) >= 0) { return parseKeyValue(str, sep1, sep2) } else { return str.split(sep1) } } return str }
javascript
{ "resource": "" }
q50250
getSeparators
train
function getSeparators (key) { let pattern = Object.keys(separators).find(p => minimatch(key, p)) const seps = separators[pattern] || defaultSeparators return seps.slice() // return a copy of the array }
javascript
{ "resource": "" }
q50251
deepSplitString
train
function deepSplitString (input, separators) { if (input === null || typeof input === 'undefined') { return input } if (separators.length === 0) { return input } const sep = separators.shift() let output = input if (typeof input === 'string') { output = splitString(input, sep) } else if (Array.isArray(input)) { output = input.map(i => splitString(i, sep)) } else if (typeof input === 'object') { output = {} Object.keys(input).forEach(key => { output[key] = splitString(input[key], sep) }) } if (separators.length > 0) { return deepSplitString(output, separators) } else { return output } }
javascript
{ "resource": "" }
q50252
workerProbe
train
function workerProbe () { Object.keys(cluster.workers).forEach(function (id) { cluster.workers[id].send(['trans']) }) }
javascript
{ "resource": "" }
q50253
train
function (priv) { if (utils.isString(priv) || Buffer.isBuffer(priv)) { this.privKey = priv.length === 32 ? priv : Buffer(priv, 'hex'); this.pubKey = null; this.address = null; } }
javascript
{ "resource": "" }
q50254
train
function () { if (utils.isNull(this.address)) { var pubKey = this.getPublicKey(); if (pubKey.length !== 64) { pubKey = cryptoUtils.secp256k1.publicKeyConvert(pubKey, false).slice(1); } // The uncompressed form consists of a 0x04 (in analogy to the DER OCTET STRING tag) plus // the concatenation of the binary representation of the X coordinate plus the binary // representation of the y coordinate of the public point. pubKey = Buffer.concat([cryptoUtils.toBuffer(4), pubKey]); // Only take the lower 160bits of the hash var content = cryptoUtils.sha3(pubKey); content = cryptoUtils.ripemd160(content); // content = AddressPrefix + NormalType + content(local address only use normal type) content = Buffer.concat([cryptoUtils.toBuffer(AddressPrefix), cryptoUtils.toBuffer(NormalType), content]); var checksum = cryptoUtils.sha3(content).slice(0, 4); this.address = Buffer.concat([content, checksum]); } return this.address; }
javascript
{ "resource": "" }
q50255
train
function (password, opts) { /*jshint maxcomplexity:17 */ opts = opts || {}; var salt = opts.salt || cryptoUtils.crypto.randomBytes(32); var iv = opts.iv || cryptoUtils.crypto.randomBytes(16); var derivedKey; var kdf = opts.kdf || 'scrypt'; var kdfparams = { dklen: opts.dklen || 32, salt: salt.toString('hex') }; if (kdf === 'pbkdf2') { kdfparams.c = opts.c || 262144; kdfparams.prf = 'hmac-sha256'; derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256'); } else if (kdf === 'scrypt') { kdfparams.n = opts.n || 4096; kdfparams.r = opts.r || 8; kdfparams.p = opts.p || 1; derivedKey = cryptoUtils.scrypt(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); } else { throw new Error('Unsupported kdf'); } var cipher = cryptoUtils.crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv); if (!cipher) { throw new Error('Unsupported cipher'); } var ciphertext = Buffer.concat([cipher.update(this.privKey), cipher.final()]); // var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex')])); // KeyVersion3 deprecated var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex'), iv, new Buffer(opts.cipher || 'aes-128-ctr')])); return { version: KeyCurrentVersion, id: cryptoUtils.uuid.v4({ random: opts.uuid || cryptoUtils.crypto.randomBytes(16) }), address: this.getAddressString(), crypto: { ciphertext: ciphertext.toString('hex'), cipherparams: { iv: iv.toString('hex') }, cipher: opts.cipher || 'aes-128-ctr', kdf: kdf, kdfparams: kdfparams, mac: mac.toString('hex'), machash: "sha3256" } }; }
javascript
{ "resource": "" }
q50256
train
function (input, password, nonStrict) { /*jshint maxcomplexity:10 */ var json = (typeof input === 'object') ? input : JSON.parse(nonStrict ? input.toLowerCase() : input); if (json.version !== KeyVersion3 && json.version !== KeyCurrentVersion) { throw new Error('Not supported wallet version'); } var derivedKey; var kdfparams; if (json.crypto.kdf === 'scrypt') { kdfparams = json.crypto.kdfparams; derivedKey = cryptoUtils.scrypt(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); } else if (json.crypto.kdf === 'pbkdf2') { kdfparams = json.crypto.kdfparams; if (kdfparams.prf !== 'hmac-sha256') { throw new Error('Unsupported parameters to PBKDF2'); } derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256'); } else { throw new Error('Unsupported key derivation scheme'); } var ciphertext = new Buffer(json.crypto.ciphertext, 'hex'); var mac; if (json.version === KeyCurrentVersion) { mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext, new Buffer(json.crypto.cipherparams.iv, 'hex'), new Buffer(json.crypto.cipher)])); } else { // KeyVersion3 mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext])); } if (mac.toString('hex') !== json.crypto.mac) { throw new Error('Key derivation failed - possibly wrong passphrase'); } var decipher = cryptoUtils.crypto.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), new Buffer(json.crypto.cipherparams.iv, 'hex')); var seed = Buffer.concat([decipher.update(ciphertext), decipher.final()]); while (seed.length < 32) { var nullBuff = new Buffer([0x00]); seed = Buffer.concat([nullBuff, seed]); } this.setPrivateKey(seed); return this; }
javascript
{ "resource": "" }
q50257
train
function (options) { if (arguments.length > 0) { options = utils.argumentsToObject(['chainID', 'from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract'], arguments); this.chainID = options.chainID; this.from = account.fromAddress(options.from); this.to = account.fromAddress(options.to); this.value = utils.toBigNumber(options.value); if(!this.value.isInteger()) throw new Error("Invalid value! The minimum unit is wei (1^-18nas)"); this.nonce = parseInt(options.nonce); // An error will be thrown is nonce is string. Error: "nonce: integer|Long expected" this.timestamp = Math.floor(new Date().getTime()/1000); this.contract = options.contract; this.gasPrice = utils.toBigNumber(options.gasPrice); this.gasLimit = utils.toBigNumber(options.gasLimit); this.data = parseContract(this.contract); if (this.gasPrice.lessThanOrEqualTo(0)) { this.gasPrice = new BigNumber(1000000); } if (this.gasLimit.lessThanOrEqualTo(0)) { this.gasLimit = new BigNumber(20000); } } this.signErrorMessage = "You should sign transaction before this operation."; }
javascript
{ "resource": "" }
q50258
train
function () { var Data = root.lookup("corepb.Data"); var err = Data.verify(this.data); if (err) { throw new Error(err); } var data = Data.create(this.data); var dataBuffer = Data.encode(data).finish(); var hash = cryptoUtils.sha3( this.from.getAddress(), this.to.getAddress(), cryptoUtils.padToBigEndian(this.value, 128), cryptoUtils.padToBigEndian(this.nonce, 64), cryptoUtils.padToBigEndian(this.timestamp, 64), dataBuffer, cryptoUtils.padToBigEndian(this.chainID, 32), cryptoUtils.padToBigEndian(this.gasPrice, 128), cryptoUtils.padToBigEndian(this.gasLimit, 128) ); return hash; }
javascript
{ "resource": "" }
q50259
train
function () { if (this.from.getPrivateKey() !== null) { this.hash = this.hashTransaction(); this.alg = SECP256K1; this.sign = cryptoUtils.sign(this.hash, this.from.getPrivateKey()); } else { throw new Error("transaction from address's private key is invalid"); } }
javascript
{ "resource": "" }
q50260
train
function() { return { chainID: this.chainID, from: this.from.getAddressString(), to: this.to.getAddressString(), value: utils.isBigNumber(this.value) ? this.value.toNumber() : this.value, nonce: this.nonce, gasPrice: utils.isBigNumber(this.gasPrice) ? this.gasPrice.toNumber() : this.gasPrice, gasLimit: utils.isBigNumber(this.gasLimit) ? this.gasLimit.toNumber() : this.gasLimit, contract: this.contract }; }
javascript
{ "resource": "" }
q50261
createHtmlDocument
train
function createHtmlDocument (message) { var body = escapeHtml(message) .replace(NEWLINE_REGEXP, '<br>') .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;') return '<!DOCTYPE html>\n' + '<html lang="en">\n' + '<head>\n' + '<meta charset="utf-8">\n' + '<title>Error</title>\n' + '</head>\n' + '<body>\n' + '<pre>' + body + '</pre>\n' + '</body>\n' + '</html>\n' }
javascript
{ "resource": "" }
q50262
finalhandler
train
function finalhandler (req, res, options) { var opts = options || {} // get environment var env = opts.env || process.env.NODE_ENV || 'development' // get error callback var onerror = opts.onerror return function (err) { var headers var msg var status // ignore 404 on in-flight response if (!err && headersSent(res)) { debug('cannot 404 after headers sent') return } // unhandled error if (err) { // respect status code from error status = getErrorStatusCode(err) if (status === undefined) { // fallback to status code on response status = getResponseStatusCode(res) } else { // respect headers from error headers = getErrorHeaders(err) } // get error message msg = getErrorMessage(err, status, env) } else { // not found status = 404 msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) } debug('default %s', status) // schedule onerror callback if (err && onerror) { defer(onerror, err, req, res) } // cannot actually respond if (headersSent(res)) { debug('cannot %d after headers sent', status) req.socket.destroy() return } // send response send(req, res, status, headers, msg) } }
javascript
{ "resource": "" }
q50263
getErrorHeaders
train
function getErrorHeaders (err) { if (!err.headers || typeof err.headers !== 'object') { return undefined } var headers = Object.create(null) var keys = Object.keys(err.headers) for (var i = 0; i < keys.length; i++) { var key = keys[i] headers[key] = err.headers[key] } return headers }
javascript
{ "resource": "" }
q50264
getErrorMessage
train
function getErrorMessage (err, status, env) { var msg if (env !== 'production') { // use err.stack, which typically includes err.message msg = err.stack // fallback to err.toString() when possible if (!msg && typeof err.toString === 'function') { msg = err.toString() } } return msg || statuses[status] }
javascript
{ "resource": "" }
q50265
getErrorStatusCode
train
function getErrorStatusCode (err) { // check err.status if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { return err.status } // check err.statusCode if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { return err.statusCode } return undefined }
javascript
{ "resource": "" }
q50266
getResponseStatusCode
train
function getResponseStatusCode (res) { var status = res.statusCode // default status code to 500 if outside valid range if (typeof status !== 'number' || status < 400 || status > 599) { status = 500 } return status }
javascript
{ "resource": "" }
q50267
setHeaders
train
function setHeaders (res, headers) { if (!headers) { return } var keys = Object.keys(headers) for (var i = 0; i < keys.length; i++) { var key = keys[i] res.setHeader(key, headers[key]) } }
javascript
{ "resource": "" }
q50268
Html5HlsJS
train
function Html5HlsJS(source, tech) { var options = tech.options_; var el = tech.el(); var duration = null; var hls = this.hls = new Hls(options.hlsjsConfig); /** * creates an error handler function * @returns {Function} */ function errorHandlerFactory() { var _recoverDecodingErrorDate = null; var _recoverAudioCodecErrorDate = null; return function() { var now = Date.now(); if (!_recoverDecodingErrorDate || (now - _recoverDecodingErrorDate) > 2000) { _recoverDecodingErrorDate = now; hls.recoverMediaError(); } else if (!_recoverAudioCodecErrorDate || (now - _recoverAudioCodecErrorDate) > 2000) { _recoverAudioCodecErrorDate = now; hls.swapAudioCodec(); hls.recoverMediaError(); } else { console.error('Error loading media: File could not be played'); } }; } // create separate error handlers for hlsjs and the video tag var hlsjsErrorHandler = errorHandlerFactory(); var videoTagErrorHandler = errorHandlerFactory(); // listen to error events coming from the video tag el.addEventListener('error', function(e) { var mediaError = e.currentTarget.error; if (mediaError.code === mediaError.MEDIA_ERR_DECODE) { videoTagErrorHandler(); } else { console.error('Error loading media: File could not be played'); } }); /** * Destroys the Hls instance */ this.dispose = function() { hls.destroy(); }; /** * returns the duration of the stream, or Infinity if live video * @returns {Infinity|number} */ this.duration = function() { return duration || el.duration || 0; }; // update live status on level load hls.on(Hls.Events.LEVEL_LOADED, function(event, data) { duration = data.details.live ? Infinity : data.details.totalduration; }); // try to recover on fatal errors hls.on(Hls.Events.ERROR, function(event, data) { if (data.fatal) { switch (data.type) { case Hls.ErrorTypes.NETWORK_ERROR: hls.startLoad(); break; case Hls.ErrorTypes.MEDIA_ERROR: hlsjsErrorHandler(); break; default: console.error('Error loading media: File could not be played'); break; } } }); Object.keys(Hls.Events).forEach(function(key) { var eventName = Hls.Events[key]; hls.on(eventName, function(event, data) { tech.trigger(eventName, data); }); }); // Intercept native TextTrack calls and route to video.js directly only // if native text tracks are not supported on this browser. if (!tech.featuresNativeTextTracks) { Object.defineProperty(el, 'textTracks', { value: tech.textTracks, writable: false }); el.addTextTrack = function() { return tech.addTextTrack.apply(tech, arguments); }; } // attach hlsjs to videotag hls.attachMedia(el); hls.loadSource(source.src); }
javascript
{ "resource": "" }
q50269
errorHandlerFactory
train
function errorHandlerFactory() { var _recoverDecodingErrorDate = null; var _recoverAudioCodecErrorDate = null; return function() { var now = Date.now(); if (!_recoverDecodingErrorDate || (now - _recoverDecodingErrorDate) > 2000) { _recoverDecodingErrorDate = now; hls.recoverMediaError(); } else if (!_recoverAudioCodecErrorDate || (now - _recoverAudioCodecErrorDate) > 2000) { _recoverAudioCodecErrorDate = now; hls.swapAudioCodec(); hls.recoverMediaError(); } else { console.error('Error loading media: File could not be played'); } }; }
javascript
{ "resource": "" }
q50270
train
function() { // Used to make sure the dropdown becomes focused (fixes IE issue) self.dropdown.trigger("focus", true); // The `click` handler logic will only be applied if the dropdown list is enabled if (!self.originalElem.disabled) { // Triggers the `click` event on the original select box self.triggerEvent("click"); if(!nativeMousedown && !customShowHideEvent) { self.toggle(); } } }
javascript
{ "resource": "" }
q50271
train
function(e) { // Stores the `keycode` value in a local variable var currentKey = self._keyMappings[e.keyCode], keydownMethod = self._keydownMethods()[currentKey]; if(keydownMethod) { keydownMethod(); if(self.options["keydownOpen"] && (currentKey === "up" || currentKey === "down")) { self.open(); } } if(keydownMethod && currentKey !== "tab") { e.preventDefault(); } }
javascript
{ "resource": "" }
q50272
train
function(e) { if (!self.originalElem.disabled) { // Sets the current key to the `keyCode` value if `charCode` does not exist. Used for cross // browser support since IE uses `keyCode` instead of `charCode`. var currentKey = e.charCode || e.keyCode, key = self._keyMappings[e.charCode || e.keyCode], // Converts unicode values to characters alphaNumericKey = String.fromCharCode(currentKey); // If the plugin options allow text searches if (self.search && (!key || (key && key === "space"))) { // Calls `search` and passes the character value of the user's text search self.search(alphaNumericKey, true, true); } if(key === "space") { e.preventDefault(); } } }
javascript
{ "resource": "" }
q50273
train
function() { // Removes the hover class from the previous drop down option self.listItems.not($(this)).removeAttr("data-active"); $(this).attr("data-active", ""); var listIsHidden = self.list.is(":hidden"); if((self.options["searchWhenHidden"] && listIsHidden) || self.options["aggressiveChange"] || (listIsHidden && self.options["selectWhenHidden"])) { self._update($(this)); } // Adds the focus CSS class to the currently focused dropdown list option $(this).addClass(focusClass); }
javascript
{ "resource": "" }
q50274
train
function() { if(nativeMousedown && !customShowHideEvent) { self._update($(this)); self.triggerEvent("option-mouseup"); // If the current drop down option is not disabled if ($(this).attr("data-disabled") === "false" && $(this).attr("data-preventclose") !== "true") { // Closes the drop down list self.close(); } } }
javascript
{ "resource": "" }
q50275
train
function() { // If the currently moused over drop down option is not disabled if($(this).attr("data-disabled") === "false") { self.listItems.removeAttr("data-active"); $(this).addClass(focusClass).attr("data-active", ""); // Sets the dropdown list indropdownidual options back to the default state and sets the focus CSS class on the currently hovered option self.listItems.not($(this)).removeClass(focusClass); $(this).addClass(focusClass); self.currentFocus = +$(this).attr("data-id"); } }
javascript
{ "resource": "" }
q50276
train
function(event, internal) { var currentOption, currentDataSelectedText; // If the user called the change method if(!internal) { currentOption = self.list.find('li[data-val="' + self.originalElem.value + '"]'); // If there is a dropdown option with the same value as the original select box element if(currentOption.length) { self.listItems.eq(self.currentFocus).removeClass(self.focusClass); self.currentFocus = +currentOption.attr("data-id"); } } currentOption = self.listItems.eq(self.currentFocus); currentDataSelectedText = currentOption.attr("data-selectedtext"); currentDataText = currentOption.attr("data-text"); currentText = currentDataText ? currentDataText: currentOption.find("a").text(); // Sets the new dropdown list text to the value of the current option self._setText(self.dropdownText, currentDataSelectedText || currentText); self.dropdownText.attr("data-val", self.originalElem.value); if(currentOption.find("i").attr("class")) { self.dropdownImage.attr("class", currentOption.find("i").attr("class")).addClass("selectboxit-default-icon"); self.dropdownImage.attr("style", currentOption.find("i").attr("style")); } // Triggers a custom changed event on the original select box self.triggerEvent("changed"); }
javascript
{ "resource": "" }
q50277
train
function() { var currentElem = self.list.find("li[data-val='" + self.dropdownText.attr("data-val") + "']"), activeElem; // If no current element can be found, then select the first drop down option if(!currentElem.length) { // Sets the default value of the dropdown list to the first option that is not disabled currentElem = self.listItems.not("[data-disabled=true]").first(); } self.currentFocus = +currentElem.attr("data-id"); activeElem = self.listItems.eq(self.currentFocus); self.dropdown.addClass(openClass). // Removes the focus class from the dropdown list and adds the library focus class for both the dropdown list and the currently selected dropdown list option removeClass(hoverClass).addClass(focusClass); self.listItems.removeClass(self.selectedClass). removeAttr("data-active").not(activeElem).removeClass(focusClass); activeElem.addClass(self.selectedClass).addClass(focusClass); if(self.options.hideCurrent) { activeElem.hide().promise().done(function () { self.listItems.show(); }); } }
javascript
{ "resource": "" }
q50278
compact
train
function compact(obj) { if ('object' != typeof obj) return obj; if (isArray(obj)) { var ret = []; for (var i in obj) { if (hasOwnProperty.call(obj, i)) { ret.push(obj[i]); } } return ret; } for (var key in obj) { obj[key] = compact(obj[key]); } return obj; }
javascript
{ "resource": "" }
q50279
parseObject
train
function parseObject(obj){ var ret = { base: {} }; forEach(objectKeys(obj), function(name){ merge(ret, name, obj[name]); }); return compact(ret.base); }
javascript
{ "resource": "" }
q50280
parseString
train
function parseString(str, options){ var ret = reduce(String(str).split(options.separator), function(ret, pair){ var eql = indexOf(pair, '=') , brace = lastBraceInKey(pair) , key = pair.substr(0, brace || eql) , val = pair.substr(brace || eql, pair.length) , val = val.substr(indexOf(val, '=') + 1, val.length); // ?foo if ('' == key) key = pair, val = ''; if ('' == key) return ret; return merge(ret, decode(key), decode(val)); }, { base: {} }).base; return compact(ret); }
javascript
{ "resource": "" }
q50281
bindMany
train
function bindMany($el, options, events) { var name, namespaced; for (name in events) { if (events.hasOwnProperty(name)) { namespaced = name.replace(/ |$/g, options.eventNamespace); $el.bind(namespaced, events[name]); } } }
javascript
{ "resource": "" }
q50282
bindUi
train
function bindUi($el, $target, options) { bindMany($el, options, { focus: function () { $target.addClass(options.focusClass); }, blur: function () { $target.removeClass(options.focusClass); $target.removeClass(options.activeClass); }, mouseenter: function () { $target.addClass(options.hoverClass); }, mouseleave: function () { $target.removeClass(options.hoverClass); $target.removeClass(options.activeClass); }, "mousedown touchbegin": function () { if (!$el.is(":disabled")) { $target.addClass(options.activeClass); } }, "mouseup touchend": function () { $target.removeClass(options.activeClass); } }); }
javascript
{ "resource": "" }
q50283
divSpanWrap
train
function divSpanWrap($el, $container, method) { switch (method) { case "after": // Result: <element /> <container /> $el.after($container); return $el.next(); case "before": // Result: <container /> <element /> $el.before($container); return $el.prev(); case "wrap": // Result: <container> <element /> </container> $el.wrap($container); return $el.parent(); } return null; }
javascript
{ "resource": "" }
q50284
highContrast
train
function highContrast() { var c, $div, el, rgb; // High contrast mode deals with white and black rgb = 'rgb(120,2,153)'; $div = $('<div style="width:0;height:0;color:' + rgb + '">'); $('body').append($div); el = $div.get(0); // $div.css() will get the style definition, not // the actually displaying style if (wind.getComputedStyle) { c = wind.getComputedStyle(el, '').color; } else { c = (el.currentStyle || el.style || {}).color; } $div.remove(); return c.replace(/ /g, '') !== rgb; }
javascript
{ "resource": "" }
q50285
setFilename
train
function setFilename($el, $filenameTag, options) { var filenames = $.map($el[0].files, function (file) {return file.name}).join(', '); if (filenames === "") { filenames = options.fileDefaultHtml; } else { filenames = filenames.split(/[\/\\]+/); filenames = filenames[(filenames.length - 1)]; } $filenameTag.text(filenames); }
javascript
{ "resource": "" }
q50286
swap
train
function swap($elements, newCss, callback) { var restore, item; restore = []; $elements.each(function () { var name; for (name in newCss) { if (Object.prototype.hasOwnProperty.call(newCss, name)) { restore.push({ el: this, name: name, old: this.style[name] }); this.style[name] = newCss[name]; } } }); callback(); while (restore.length) { item = restore.pop(); item.el.style[item.name] = item.old; } }
javascript
{ "resource": "" }
q50287
sizingInvisible
train
function sizingInvisible($el, callback) { var targets; // We wish to target ourselves and any parents as long as // they are not visible targets = $el.parents(); targets.push($el[0]); targets = targets.not(':visible'); swap(targets, { visibility: "hidden", display: "block", position: "absolute" }, callback); }
javascript
{ "resource": "" }
q50288
train
function (typeName) { switch (typeName) { case Constants.STRING_TYPE: return true; case Constants.NUMBER_TYPE: return true; case Constants.BOOLEAN_TYPE: return true; case Constants.DATE_TYPE: return true; case Constants.STRING_TYPE_LOWERCASE: return true; case Constants.NUMBER_TYPE_LOWERCASE: return true; case Constants.BOOLEAN_TYPE_LOWERCASE: return true; case Constants.DATE_TYPE_LOWERCASE: return true; default: return false; } }
javascript
{ "resource": "" }
q50289
train
function (metadata) { if (typeof metadata === 'string') { return getJsonPropertyDecorator({ name: metadata, required: false, access: exports.AccessType.BOTH }); } else { return getJsonPropertyDecorator(metadata); } }
javascript
{ "resource": "" }
q50290
train
function (instance, instanceKey, type, json, jsonKey) { var jsonObject = (jsonKey !== undefined) ? (json[jsonKey] || []) : json; var jsonArraySize = jsonObject.length; var conversionFunctionsList = []; var arrayInstance = []; instance[instanceKey] = arrayInstance; if (jsonArraySize > 0) { for (var i = 0; i < jsonArraySize; i++) { if (jsonObject[i]) { var typeName = getTypeNameFromInstance(type); if (!isSimpleType(typeName)) { var typeInstance = new type(); conversionFunctionsList.push({ functionName: Constants.OBJECT_TYPE, instance: typeInstance, json: jsonObject[i] }); arrayInstance.push(typeInstance); } else { arrayInstance.push(conversionFunctions[Constants.FROM_ARRAY](jsonObject[i], typeName)); } } } } return conversionFunctionsList; }
javascript
{ "resource": "" }
q50291
train
function (key, instance, serializer) { var value = serializer.serialize(instance); if (key !== undefined) { return "\"" + key + "\":" + value; } else { return value; } }
javascript
{ "resource": "" }
q50292
gulpCopy
train
function gulpCopy(destination, opts) { const throughOptions = { objectMode: true }; // Make sure a destination was verified if (typeof destination !== 'string') { throw new PluginError('gulp-copy', 'No valid destination specified'); } // Default options if (opts === undefined) { opts = opts || {}; } else if (typeof opts !== 'object' || opts === null) { throw new PluginError('gulp-copy', 'No valid options specified'); } return through(throughOptions, transform); /** * Transform method, copies the file to its new destination * @param {object} file * @param {string} encoding * @param {function} cb */ function transform(file, encoding, cb) { let rel = null; let fileDestination = null; if (file.isStream()) { cb(new PluginError('gulp-copy', 'Streaming not supported')); } if (file.isNull()) { cb(null, file); } else { rel = path.relative(file.cwd, file.path).replace(/\\/g, separator); // Strip path prefixes if (opts.prefix) { let p = opts.prefix; while (p-- > 0) { rel = rel.substring(rel.indexOf(separator) + 1); } } fileDestination = path.join(destination, rel); // Make sure destination exists if (!doesPathExist(fileDestination)) { createDestination(fileDestination.substr(0, fileDestination.lastIndexOf(separator))); } // Copy the file copyFile(file.path, fileDestination, function copyFileCallback(error) { if (error) { throw new PluginError('gulp-copy', `Could not copy file <${file.path}>: ${error.message}`); } // Update path for file so this path is used later on file.path = fileDestination; cb(null, file); }); } } }
javascript
{ "resource": "" }
q50293
createDestination
train
function createDestination(destination) { const folders = destination.split(separator); const pathParts = []; const l = folders.length; // for absolute paths if (folders[0] === '') { pathParts.push(separator); folders.shift(); } for (let i = 0; i < l; i++) { pathParts.push(folders[i]); if (folders[i] !== '' && !doesPathExist(pathParts.join(separator))) { try { fs.mkdirSync(pathParts.join(separator)); } catch (error) { throw new PluginError('gulp-copy', `Could not create destination <${destination}>: ${error.message}`); } } } }
javascript
{ "resource": "" }
q50294
doesPathExist
train
function doesPathExist(pathToVerify) { let pathExists = true; try { fs.accessSync(pathToVerify); } catch (error) { pathExists = false; } return pathExists; }
javascript
{ "resource": "" }
q50295
copyFile
train
function copyFile(source, target, copyCallback) { const readStream = fs.createReadStream(source); const writeStream = fs.createWriteStream(target); let done = false; readStream.on('error', copyDone); writeStream.on('error', copyDone); writeStream.on('close', function onWriteCb() { copyDone(null); }); readStream.pipe(writeStream); /** * Finish copying. Reports error when needed * @param [error] optional error */ function copyDone(error) { if (!done) { done = true; copyCallback(error); } } }
javascript
{ "resource": "" }
q50296
defaultOptions
train
function defaultOptions() { return { optimistic: false, directive: false, nodejsScope: false, impliedStrict: false, sourceType: "script", // one of ['script', 'module'] ecmaVersion: 5, childVisitorKeys: null, fallback: "iteration" }; }
javascript
{ "resource": "" }
q50297
updateDeeply
train
function updateDeeply(target, override) { /** * Is hash object * @param {Object} value - Test value * @returns {boolean} Result */ function isHashObject(value) { return typeof value === "object" && value instanceof Object && !(value instanceof Array) && !(value instanceof RegExp); } for (const key in override) { if (override.hasOwnProperty(key)) { const val = override[key]; if (isHashObject(val)) { if (isHashObject(target[key])) { updateDeeply(target[key], val); } else { target[key] = updateDeeply({}, val); } } else { target[key] = val; } } } return target; }
javascript
{ "resource": "" }
q50298
getDirContentMTime
train
function getDirContentMTime(dirPath, ignoredDirs, ignoredFiles){ let mtime if(fs.existsSync(dirPath)){ _ignoredDirs.push.apply(_ignoredDirs, ignoredDirs) _ignoredFiles.push.apply(_ignoredFiles, ignoredFiles) mtime = recursiveGetDirContentMTime(dirPath) } return mtime }
javascript
{ "resource": "" }
q50299
onClearBackend
train
function onClearBackend(projectInfo){ let backendProject = getBackendProjectObject(projectInfo) if(backendProject){ backendProject.name = '' setBackendProjectObject(backendProject, projectInfo) } }
javascript
{ "resource": "" }