_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q7100
step
train
function step(equation, symbolName) { const solveFunctions = [ // ensure the symbol is always on the left node EquationOperations.ensureSymbolInLeftNode, // get rid of denominators that have the symbol EquationOperations.removeSymbolFromDenominator, // remove the symbol from the right side EquationOperations.removeSymbolFromRightSide, // isolate the symbol on the left side EquationOperations.isolateSymbolOnLeftSide, ]; for (let i = 0; i < solveFunctions.length; i++) { const equationStatus = solveFunctions[i](equation, symbolName); if (equationStatus.hasChanged()) { return equationStatus; } } return EquationStatus.noChange(equation); }
javascript
{ "resource": "" }
q7101
addSimplificationSteps
train
function addSimplificationSteps(steps, equation, debug=false) { let oldEquation = equation.clone(); const leftSteps = simplifyExpressionNode(equation.leftNode, false); const leftSubSteps = []; for (let i = 0; i < leftSteps.length; i++) { const step = leftSteps[i]; leftSubSteps.push(EquationStatus.addLeftStep(equation, step)); } if (leftSubSteps.length === 1) { const step = leftSubSteps[0]; step.changeType = ChangeTypes.SIMPLIFY_LEFT_SIDE; if (debug) { logSteps(step); } steps.push(step); } else if (leftSubSteps.length > 1) { const lastStep = leftSubSteps[leftSubSteps.length - 1]; const finalEquation = EquationStatus.resetChangeGroups(lastStep.newEquation); // no change groups are set here - too much is changing for it to be useful const simplifyStatus = new EquationStatus( ChangeTypes.SIMPLIFY_LEFT_SIDE, oldEquation, finalEquation, leftSubSteps); if (debug) { logSteps(step); } steps.push(simplifyStatus); } // update `equation` to have the new simplified left node if (steps.length > 0) { equation = EquationStatus.resetChangeGroups( steps[steps.length - 1 ].newEquation); } // the updated equation from simplifing the left side is the old equation // (ie the "before" of the before and after) for simplifying the right side. oldEquation = equation.clone(); const rightSteps = simplifyExpressionNode(equation.rightNode, false); const rightSubSteps = []; for (let i = 0; i < rightSteps.length; i++) { const step = rightSteps[i]; rightSubSteps.push(EquationStatus.addRightStep(equation, step)); } if (rightSubSteps.length === 1) { const step = rightSubSteps[0]; step.changeType = ChangeTypes.SIMPLIFY_RIGHT_SIDE; if (debug) { logSteps(step); } steps.push(step); } else if (rightSubSteps.length > 1) { const lastStep = rightSubSteps[rightSubSteps.length - 1]; const finalEquation = EquationStatus.resetChangeGroups(lastStep.newEquation); // no change groups are set here - too much is changing for it to be useful const simplifyStatus = new EquationStatus( ChangeTypes.SIMPLIFY_RIGHT_SIDE, oldEquation, finalEquation, rightSubSteps); if (debug) { logSteps(simplifyStatus); } steps.push(simplifyStatus); } return steps; }
javascript
{ "resource": "" }
q7102
reduceZeroDividedByAnything
train
function reduceZeroDividedByAnything(node) { if (node.op !== '/') { return Node.Status.noChange(node); } if (node.args[0].value === '0') { const newNode = Node.Creator.constant(0); return Node.Status.nodeChanged( ChangeTypes.REDUCE_ZERO_NUMERATOR, node, newNode); } else { return Node.Status.noChange(node); } }
javascript
{ "resource": "" }
q7103
Register
train
function Register(client, path) { if (!(this instanceof Register)) return new Register(client); EventEmitter.call(this); this._client = client; this._path = path; // Register status. Supported 'unwatched' / 'pending' / 'watched'. this._status = 'unwatched'; this._watcher = this._watcher.bind(this); }
javascript
{ "resource": "" }
q7104
removeDivisionByOne
train
function removeDivisionByOne(node) { if (node.op !== '/') { return Node.Status.noChange(node); } const denominator = node.args[1]; if (!Node.Type.isConstant(denominator)) { return Node.Status.noChange(node); } let numerator = clone(node.args[0]); // if denominator is -1, we make the numerator negative if (parseFloat(denominator.value) === -1) { // If the numerator was an operation, wrap it in parens before adding - // to the front. // e.g. 2+3 / -1 ---> -(2+3) if (Node.Type.isOperator(numerator)) { numerator = Node.Creator.parenthesis(numerator); } const changeType = Negative.isNegative(numerator) ? ChangeTypes.RESOLVE_DOUBLE_MINUS : ChangeTypes.DIVISION_BY_NEGATIVE_ONE; numerator = Negative.negate(numerator); return Node.Status.nodeChanged(changeType, node, numerator); } else if (parseFloat(denominator.value) === 1) { return Node.Status.nodeChanged( ChangeTypes.DIVISION_BY_ONE, node, numerator); } else { return Node.Status.noChange(node); } }
javascript
{ "resource": "" }
q7105
train
function (wp) { var element = props.onRenderDisplayElement ? props.onRenderDisplayElement(wp) : null; if (element == null) { // Default the element element = props.displayElement ? React.createElement(props.displayElement, { cfg: wp.cfg }) : null; } // See if the element exists if (element) { // Render the element react_dom_1.render(React.createElement(Fabric_1.Fabric, null, element), wp.el); } }
javascript
{ "resource": "" }
q7106
train
function (wp) { var element = props.onRenderEditElement ? props.onRenderEditElement(wp) : null; if (element == null) { // Default the element element = props.editElement ? React.createElement(props.editElement, { cfg: wp.cfg, cfgElementId: props.cfgElementId }) : null; } // See if the element exists if (element) { // Render the element react_dom_1.render(React.createElement(Fabric_1.Fabric, null, element), wp.el); } }
javascript
{ "resource": "" }
q7107
stepThrough
train
function stepThrough(node, debug=false) { if (debug) { // eslint-disable-next-line console.log('\n\nSimplifying: ' + print(node, false, true)); } if(checks.hasUnsupportedNodes(node)) { return []; } let nodeStatus; const steps = []; const originalExpressionStr = print(node); const MAX_STEP_COUNT = 20; let iters = 0; // Now, step through the math expression until nothing changes nodeStatus = step(node); while (nodeStatus.hasChanged()) { if (debug) { logSteps(nodeStatus); } steps.push(removeUnnecessaryParensInStep(nodeStatus)); const nextNode = Status.resetChangeGroups(nodeStatus.newNode); nodeStatus = step(nextNode); if (iters++ === MAX_STEP_COUNT) { // eslint-disable-next-line console.error('Math error: Potential infinite loop for expression: ' + originalExpressionStr + ', returning no steps'); return []; } } return steps; }
javascript
{ "resource": "" }
q7108
step
train
function step(node) { let nodeStatus; node = flattenOperands(node); node = removeUnnecessaryParens(node, true); const simplificationTreeSearches = [ // Basic simplifications that we always try first e.g. (...)^0 => 1 basicsSearch, // Simplify any division chains so there's at most one division operation. // e.g. 2/x/6 -> 2/(x*6) e.g. 2/(x/6) => 2 * 6/x divisionSearch, // Adding fractions, cancelling out things in fractions fractionsSearch, // e.g. 2 + 2 => 4 arithmeticSearch, // e.g. addition: 2x + 4x^2 + x => 4x^2 + 3x // e.g. multiplication: 2x * x * x^2 => 2x^3 collectAndCombineSearch, // e.g. (2 + x) / 4 => 2/4 + x/4 breakUpNumeratorSearch, // e.g. 3/x * 2x/5 => (3 * 2x) / (x * 5) multiplyFractionsSearch, // e.g. (2x + 3)(x + 4) => 2x^2 + 11x + 12 distributeSearch, // e.g. abs(-4) => 4 functionsSearch, ]; for (let i = 0; i < simplificationTreeSearches.length; i++) { nodeStatus = simplificationTreeSearches[i](node); // Always update node, since there might be changes that didn't count as // a step. Remove unnecessary parens, in case one a step results in more // parens than needed. node = removeUnnecessaryParens(nodeStatus.newNode, true); if (nodeStatus.hasChanged()) { node = flattenOperands(node); nodeStatus.newNode = clone(node); return nodeStatus; } else { node = flattenOperands(node); } } return Node.Status.noChange(node); }
javascript
{ "resource": "" }
q7109
train
function(errOrMessage, result) { var err = (errOrMessage instanceof Error) ? errOrMessage : new Error(errOrMessage); result = result || {}; result.error = err; result.status = 'error'; err.result = result; return err; }
javascript
{ "resource": "" }
q7110
train
function(filepath, index) { index = index || 1; var params = this.get_path_info(filepath); params.index = index; var newpath = Handlebars.compile(this.config.sequential_template)(params); return (fs.existsSync(newpath)) ? this.get_sequential_filepath(filepath, index + 1) : newpath; }
javascript
{ "resource": "" }
q7111
sameOrigin
train
function sameOrigin(url) { let origin = `${location.protocol}//${location.hostname}`; if (location.port) { origin += `:${location.port}`; } return url && url.indexOf(origin) === 0; }
javascript
{ "resource": "" }
q7112
addLikeTerms
train
function addLikeTerms(node, polynomialOnly=false) { if (!Node.Type.isOperator(node)) { return Node.Status.noChange(node); } let status; if (!polynomialOnly) { status = evaluateConstantSum(node); if (status.hasChanged()) { return status; } } status = addLikePolynomialTerms(node); if (status.hasChanged()) { return status; } return Node.Status.noChange(node); }
javascript
{ "resource": "" }
q7113
simplify
train
function simplify(node, debug=false) { if(checks.hasUnsupportedNodes(node)) { return node; } const steps = stepThrough(node, debug); let simplifiedNode; if (steps.length > 0) { simplifiedNode = steps.pop().newNode; } else { // removing parens isn't counted as a step, so try it here simplifiedNode = removeUnnecessaryParens(flattenOperands(node), true); } // unflatten the node. return unflatten(simplifiedNode); }
javascript
{ "resource": "" }
q7114
get
train
function get(cb) { getRaw(function (err, num, muted) { timeouts.push(setTimeout(function () { cb(err, num, muted); }), 0); }); }
javascript
{ "resource": "" }
q7115
raiseLevel
train
function raiseLevel(edge) { var s = edge.s var t = edge.t //Update position in edge lists removeEdge(s, edge) removeEdge(t, edge) edge.level += 1 elist.insert(s.adjacent, edge) elist.insert(t.adjacent, edge) //Update flags for s if(s.euler.length <= edge.level) { s.euler.push(createEulerVertex(s)) } var es = s.euler[edge.level] es.setFlag(true) //Update flags for t if(t.euler.length <= edge.level) { t.euler.push(createEulerVertex(t)) } var et = t.euler[edge.level] et.setFlag(true) //Relink if necessary if(edge.euler) { edge.euler.push(es.link(et, edge)) } }
javascript
{ "resource": "" }
q7116
removeEdge
train
function removeEdge(vertex, edge) { var adj = vertex.adjacent var idx = elist.index(adj, edge) adj.splice(idx, 1) //Check if flag needs to be updated if(!((idx < adj.length && adj[idx].level === edge.level) || (idx > 0 && adj[idx-1].level === edge.level))) { vertex.euler[edge.level].setFlag(false) } }
javascript
{ "resource": "" }
q7117
link
train
function link(edge) { var es = edge.s.euler var et = edge.t.euler var euler = new Array(edge.level+1) for(var i=0; i<euler.length; ++i) { if(es.length <= i) { es.push(createEulerVertex(edge.s)) } if(et.length <= i) { et.push(createEulerVertex(edge.t)) } euler[i] = es[i].link(et[i], edge) } edge.euler = euler }
javascript
{ "resource": "" }
q7118
visit
train
function visit(node) { if(node.flag) { var v = node.value.value var adj = v.adjacent for(var ptr=elist.level(adj, level); ptr<adj.length && adj[ptr].level === level; ++ptr) { var e = adj[ptr] var es = e.s var et = e.t if(es.euler[level].path(et.euler[level])) { raiseLevel(e) ptr -= 1 } else { //Found the edge, relink components link(e) return true } } } if(node.left && node.left.flagAggregate) { if(visit(node.left)) { return true } } if(node.right && node.right.flagAggregate) { if(visit(node.right)) { return true } } return false }
javascript
{ "resource": "" }
q7119
removeMultiplicationByNegativeOne
train
function removeMultiplicationByNegativeOne(node) { if (node.op !== '*') { return Node.Status.noChange(node); } const minusOneIndex = node.args.findIndex(arg => { return Node.Type.isConstant(arg) && arg.value === '-1'; }); if (minusOneIndex < 0) { return Node.Status.noChange(node); } // We might merge/combine the negative one into another node. This stores // the index of that other node in the arg list. let nodeToCombineIndex; // If minus one is the last term, maybe combine with the term before if (minusOneIndex + 1 === node.args.length) { nodeToCombineIndex = minusOneIndex - 1; } else { nodeToCombineIndex = minusOneIndex + 1; } let nodeToCombine = node.args[nodeToCombineIndex]; // If it's a constant, the combining of those terms is handled elsewhere. if (Node.Type.isConstant(nodeToCombine)) { return Node.Status.noChange(node); } let newNode = clone(node); // Get rid of the -1 nodeToCombine = Negative.negate(clone(nodeToCombine)); // replace the node next to -1 and remove -1 newNode.args[nodeToCombineIndex] = nodeToCombine; newNode.args.splice(minusOneIndex, 1); // if there's only one operand left, move it up the tree if (newNode.args.length === 1) { newNode = newNode.args[0]; } return Node.Status.nodeChanged( ChangeTypes.REMOVE_MULTIPLYING_BY_NEGATIVE_ONE, node, newNode); }
javascript
{ "resource": "" }
q7120
isSymbolTerm
train
function isSymbolTerm(node, symbolName) { if (Node.PolynomialTerm.isPolynomialTerm(node)) { const polyTerm = new Node.PolynomialTerm(node); if (polyTerm.getSymbolName() === symbolName) { return true; } } return false; }
javascript
{ "resource": "" }
q7121
ZD
train
function ZD(conf) { if (!(this instanceof ZD)) return new ZD(conf); var config = ('string' === typeof conf) ? { conn: conf } : (conf || {}); this.dubbo = config.dubbo; this.client = zookeeper.createClient(config.conn, { sessionTimeout: config.sessionTimeout, spinDelay: config.spinDelay, retries: config.retries }); }
javascript
{ "resource": "" }
q7122
validateConfig
train
function validateConfig(config){ let errors = []; if( !config.key ){ errors.push('Missing config \'config.key\' - Undefined Trello Key'); } if( !config.token ){ errors.push('Missing config \'config.token\' - Undefined Trello Token'); } return errors; }
javascript
{ "resource": "" }
q7123
downloadFile
train
function downloadFile(url, outputPath) { const dir = path.dirname(outputPath); if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } return new Promise((resolve, reject) => { const file = fs.createWriteStream(outputPath); const sendReq = request.get(url); sendReq.pipe(file); sendReq .on("response", (response) => { if (response.statusCode !== 200) { fs.unlink(outputPath); const error = new Error("Response status code was " + response.statusCode + "."); console.trace(error); reject(error); } }) .on("error", (error) => { fs.unlink(outputPath); console.trace(error); reject(error); }); file .on("finish", () => { file.close(() => { resolve(); }); }) .on("error", (error) => { fs.unlink(outputPath); console.trace(error); reject(error); }); }); }
javascript
{ "resource": "" }
q7124
createProject
train
function createProject(zipFile) { return cocoonSDK.ProjectAPI.createFromZipUpload(zipFile) .catch((error) => { console.error("Project couldn't be created."); console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7125
updateConfig
train
function updateConfig(configXml, project) { return project.updateConfigXml(configXml) .catch((error) => { console.error("Project config with ID: " + project.id + " couldn't be updated."); console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7126
updateConfigWithId
train
function updateConfigWithId(configXml, projectId) { return fetchProject(projectId) .then((project) => { return updateConfig(configXml, project); }) .catch((error) => { console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7127
deleteProject
train
function deleteProject(project) { return project.delete() .catch((error) => { console.error("Project with ID: " + project.id + " couldn't be deleted."); console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7128
deleteProjectWithId
train
function deleteProjectWithId(projectId) { return fetchProject(projectId) .then(deleteProject) .catch((error) => { console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7129
createProjectWithConfig
train
function createProjectWithConfig(zipFile, configXml) { return createProject(zipFile) .then((project) => { return updateConfig(configXml, project) .then(() => { return project; }) .catch((errorFromUpdate) => { deleteProject(project) .then(() => { console.error("The project with ID: " + project.id + " was not created because it wasn't possible to upload the custom XML."); throw errorFromUpdate; }) .catch((errorFromDelete) => { console.error("The project with ID: " + project.id + " was created but it wasn't possible to upload the custom XML."); console.trace(errorFromDelete); throw errorFromDelete; }); }); }) .catch((error) => { console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7130
updateSource
train
function updateSource(zipFile, project) { return project.updateZip(zipFile) .catch((error) => { console.error("Project source with ID: " + project.id + " couldn't be updated."); console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7131
updateSourceWithId
train
function updateSourceWithId(zipFile, projectId) { return fetchProject(projectId) .then((project) => { return updateSource(zipFile, project); }) .catch((error) => { console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7132
compileProject
train
function compileProject(project) { return project.compile() .catch((error) => { console.error("Project " + project.name + " with ID: " + project.id + " couldn't be compiled."); console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7133
compileProjectWithId
train
function compileProjectWithId(projectId) { return fetchProject(projectId) .then(compileProject) .catch((error) => { console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7134
waitForCompletion
train
function waitForCompletion(project) { return new Promise((resolve, reject) => { let warned = false; project.refreshUntilCompleted((completed, error) => { if (!error) { if (completed) { if (warned) { readLine.clearLine(process.stdout); // clear "Waiting" line readLine.cursorTo(process.stdout, 0); // move cursor to beginning of line } resolve(); } else { if (!warned) { process.stdout.write("Waiting for " + project.name + " compilation to end "); warned = true; } process.stdout.write("."); } } else { reject(error); } }); }); }
javascript
{ "resource": "" }
q7135
downloadProjectCompilation
train
function downloadProjectCompilation(project, platform, outputDir) { return waitForCompletion(project) .then(() => { if (project.compilations[platform]) { if (project.compilations[platform].isReady()) { return downloadFile(project.compilations[platform].downloadLink, outputDir + "/" + project.name + "-" + platform + ".zip") .catch((error) => { console.error("Couldn't download " + platform + " compilation from project " + project.id + "."); console.trace(error); throw error; }); } else if (project.compilations[platform].isErred()) { console.error("Couldn't download " + platform + " compilation from " + project.name + " project: " + project.id + ". The compilation failed."); throw new Error("Compilation failed"); } else { console.error("Couldn't download " + platform + " compilation from " + project.name + " project: " + project.id + ". Status: " + project.compilations[platform].status + "."); throw new Error("Platform ignored"); } } else { console.error("Couldn't download " + platform + " compilation from " + project.name + " project: " + project.id + ". There was not a compilation issued for the platform."); throw new Error("No compilation available"); } }) .catch((error) => { console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7136
downloadProjectCompilationWithId
train
function downloadProjectCompilationWithId(projectId, platform, outputDir) { return fetchProject(projectId) .then((project) => { return downloadProjectCompilation(project, platform, outputDir); }) .catch((error) => { console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7137
downloadProjectCompilations
train
function downloadProjectCompilations(project, outputDir) { const promises = []; for (const platform in project.compilations) { if (!project.compilations.hasOwnProperty(platform)) { continue; } promises.push(downloadProjectCompilation(project, platform, outputDir).catch(() => { return undefined; })); } return Promise.all(promises); }
javascript
{ "resource": "" }
q7138
downloadProjectCompilationsWithId
train
function downloadProjectCompilationsWithId(projectId, outputDir) { return fetchProject(projectId) .then((project) => { return downloadProjectCompilations(project, outputDir); }) .catch((error) => { console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7139
checkProjectCompilationWithId
train
function checkProjectCompilationWithId(projectId, platform) { return fetchProject(projectId) .then((project) => { return checkProjectCompilation(project, platform); }) .catch((error) => { console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7140
checkProjectCompilations
train
function checkProjectCompilations(project) { return waitForCompletion(project) .then(() => { for (const platform in project.compilations) { if (!project.compilations.hasOwnProperty(platform)) { continue; } const compilation = project.compilations[platform]; if (compilation.isReady()) { console.info(compilation.platform + " compilation from " + project.name + " project: " + project.id + " is completed."); } else if (compilation.isErred()) { console.error(compilation.platform + " compilation from " + project.name + " project: " + project.id + " is erred."); console.error("ERROR LOG of the " + compilation.platform + " platform:"); console.error(compilation.error); } else { console.error(compilation.platform + " compilation from " + project.name + " project: " + project.id + " was ignored. Status: " + compilation.status + "."); } } return undefined; }) .catch((error) => { console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7141
checkProjectCompilationsWithId
train
function checkProjectCompilationsWithId(projectId) { return fetchProject(projectId) .then((project) => { return checkProjectCompilations(project); }) .catch((error) => { console.trace(error); throw error; }); }
javascript
{ "resource": "" }
q7142
getBase64
train
function getBase64 (file) { var reader = new FileReader(); reader.readAsDataURL(file); reader.onerror = function (error) { console.log('Error: ', error); }; return reader; }
javascript
{ "resource": "" }
q7143
train
function ( model, records, associations, sideload ) { sideload = sideload || false; var plural = Array.isArray( records ) ? true : false; var documentIdentifier = plural ? pluralize( model.globalId ) : model.globalId; //turn id into camelCase for ember documentIdentifier = camelCase(documentIdentifier); var json = {}; json[ documentIdentifier ] = plural ? [] : {}; if ( sideload ) { // prepare for sideloading forEach( associations, function ( assoc ) { var assocName; if (assoc.type === 'collection') { assocName = pluralize(camelCase(sails.models[assoc.collection].globalId)); } else { assocName = pluralize(camelCase(sails.models[assoc.model].globalId)); } // initialize jsoning object if ( !json.hasOwnProperty( assoc.alias ) ) { json[ assocName ] = []; } } ); } var prepareOneRecord = function ( record ) { // get rid of the record's prototype ( otherwise the .toJSON called in res.send would re-insert embedded records) record = create( {}, record.toJSON() ); forEach( associations, function ( assoc ) { var assocName; if (assoc.type === 'collection') { assocName = pluralize(camelCase(sails.models[assoc.collection].globalId)); } else { assocName = pluralize(camelCase(sails.models[assoc.model].globalId)); } if ( assoc.type === "collection" && record[ assoc.alias ] && record[ assoc.alias ].length > 0 ) { if ( sideload ) json[ assocName ] = json[ assocName ].concat( record[ assoc.alias ] ); record[ assoc.alias ] = pluck( record[ assoc.alias ], 'id' ); } if ( assoc.type === "model" && record[ assoc.alias ] ) { if ( sideload ) json[ assocName ] = json[ assocName ].concat( record[ assoc.alias ] ); record[ assoc.alias ] = record[ assoc.alias ].id; } } ); return record; }; // many or just one? if ( plural ) { forEach( records, function ( record ) { json[ documentIdentifier ] = json[ documentIdentifier ].concat( prepareOneRecord( record ) ); } ); } else { json[ documentIdentifier ] = prepareOneRecord( records ); } if ( sideload ) { // filter duplicates in sideloaded records forEach( json, function ( array, key ) { if ( !plural && key === documentIdentifier ) return; json[ key ] = uniq( array, function ( record ) { return record.id; } ); } ); } return json; }
javascript
{ "resource": "" }
q7144
resetKeepAlive
train
function resetKeepAlive() { if (keepAliveTimeoutId) { clearTimeout(keepAliveTimeoutId); } keepAliveTimeoutId = setTimeout(function () { exit.call(process, 1); }, keepAliveTimeout); }
javascript
{ "resource": "" }
q7145
fixEventPayload
train
function fixEventPayload(events) { return new Promise(function (resolve, reject) { events.forEach(function(event) { try { event.payload = JSON.parse(event.payload); } catch (e) { console.log('Could not parse payload'); return reject(new Error('Could not parse payload: ' + e.message)); } }); resolve(); }); }
javascript
{ "resource": "" }
q7146
getToken
train
function getToken(stripeCredentials) { return new Promise(function (resolve, reject) { var required = [ "stripe_secret", "credit_card_number", "credit_card_cvc", "credit_card_expiry_month", "credit_card_expiry_year" ]; if (stripeCredentials.stripe_api_key.indexOf("sk") === 0) { console.log("*** WARNING: using a secret stripe api key. ***"); } var stripe = require('stripe')(stripeCredentials.stripe_api_key); var card = { number: stripeCredentials.credit_card_number, exp_month: stripeCredentials.credit_card_expiry_month, exp_year: stripeCredentials.credit_card_expiry_year, cvc: stripeCredentials.credit_card_cvc }; stripe.tokens.create({ card: card }, (err, token) => { if (err) { reject(err); } else { resolve(token.id); } } ); }); }
javascript
{ "resource": "" }
q7147
functions
train
function functions(node) { if (!Node.Type.isFunction(node)) { return Node.Status.noChange(node); } for (let i = 0; i < FUNCTIONS.length; i++) { const nodeStatus = FUNCTIONS[i](node); if (nodeStatus.hasChanged()) { return nodeStatus; } } return Node.Status.noChange(node); }
javascript
{ "resource": "" }
q7148
removeExponentBaseOne
train
function removeExponentBaseOne(node) { if (node.op === '^' && // an exponent with checks.resolvesToConstant(node.args[1]) && // a power not a symbol and Node.Type.isConstant(node.args[0]) && // a constant base node.args[0].value === '1') { // of value 1 const newNode = clone(node.args[0]); return Node.Status.nodeChanged( ChangeTypes.REMOVE_EXPONENT_BASE_ONE, node, newNode); } return Node.Status.noChange(node); }
javascript
{ "resource": "" }
q7149
canRearrangeCoefficient
train
function canRearrangeCoefficient(node) { // implicit multiplication doesn't count as multiplication here, since it // represents a single term. if (node.op !== '*' || node.implicit) { return false; } if (node.args.length !== 2) { return false; } if (!Node.Type.isConstantOrConstantFraction(node.args[1])) { return false; } if (!Node.PolynomialTerm.isPolynomialTerm(node.args[0])) { return false; } const polyNode = new Node.PolynomialTerm(node.args[0]); return !polyNode.hasCoeff(); }
javascript
{ "resource": "" }
q7150
connect
train
function connect(params) { /** * @property server * @type {String} */ var server = ''; (function determineHost(controller) { var host = $ember.get(controller, 'host'), port = $ember.get(controller, 'port'), scheme = $ember.get(controller, 'secure') === true ? 'https' : 'http', path = $ember.get(controller, 'path') || ''; if (!host && !port) { return; } // Use the host to compile the connect string. server = !port ? `${scheme}://${host}/${path}` : `${scheme}://${host}:${port}/${path}`; })(this); // Create the host:port string for connecting, and then attempt to establish // a connection. var options = $ember.get(this, 'options') || {}, socket = $io(params ? params.namespace: server, $jq.extend(options, params || {})); socket.on('error', this.error); // Store a reference to the socket. this.set('socket', socket); /** * @on connect */ socket.on('connect', Ember.run.bind(this, this._listen)); }
javascript
{ "resource": "" }
q7151
emit
train
function emit(eventName, params) { //jshint unused:false var args = Array.prototype.slice.call(arguments), scope = $ember.get(this, 'socket'); scope.emit.apply(scope, args); }
javascript
{ "resource": "" }
q7152
_listen
train
function _listen() { var controllers = $ember.get(this, 'controllers'), getController = Ember.run.bind(this, this._getController), events = [], module = this, respond = function respond() { var eventData = Array.prototype.slice.call(arguments); module._update.call(module, this, eventData); }; controllers.forEach(function controllerIteration(controllerName) { // Fetch the controller if it's valid. var controller = getController(controllerName), eventNames = controller[this.NAMESPACE]; if (controller) { // Invoke the `connect` method if it has been defined on this controller. if (typeof controller[this.NAMESPACE] === 'object' && typeof controller[this.NAMESPACE].connect === 'function') { controller[this.NAMESPACE].connect.apply(controller); } // Iterate over each event defined in the controller's `sockets` hash, so that we can // keep an eye open for them. for (var eventName in eventNames) { if (eventNames.hasOwnProperty(eventName)) { if (events.indexOf(eventName) !== -1) { // Don't observe this event if we're already observing it. continue; } // Push the event so we don't listen for it twice. events.push(eventName); // Check to ensure the event was not previously registered due to a reconnect if (!(eventName in $ember.get(module, 'socket')._callbacks)) { // ...And finally we can register the event to listen for it. $ember.get(module, 'socket').on(eventName, respond.bind(eventName)); } } } } }, this); }
javascript
{ "resource": "" }
q7153
_getController
train
function _getController(name) { // Format the `name` to match what the lookup container is expecting, and then // we'll locate the controller from the `container`. name = `controller:${name}`; var controller = Ember.getOwner(this).lookup(name); if (!controller || (this.NAMESPACE in controller === false)) { // Don't do anything with this controller if it hasn't defined a `sockets` hash. return false; } return controller; }
javascript
{ "resource": "" }
q7154
Parameters
train
function Parameters(collection) { abstractions.Composite.call(this, utilities.types.PARAMETERS); // the parameters are immutable so the methods are included in the constructor const duplicator = new utilities.Duplicator(); const copy = duplicator.duplicateComponent(collection); this.getCollection = function() { return copy; }; this.toArray = function() { const array = copy.toArray(); return array; }; this.acceptVisitor = function(visitor) { visitor.visitParameters(this); }; this.getSize = function() { const size = copy.getSize(); return size; }; this.getParameter = function(key, index) { var value; index = index || 1; // default is the first parameter if (copy.getTypeId() === utilities.types.CATALOG) { value = copy.getValue(key); } else { value = copy.getItem(index); } return value; }; this.setParameter = function(key, value, index) { index = index || 1; // default is the first parameter if (copy.getTypeId() === utilities.types.CATALOG) { copy.setValue(key, value); } else { copy.setItem(index, value); } }; return this; }
javascript
{ "resource": "" }
q7155
Duration
train
function Duration(value, parameters) { abstractions.Element.call(this, utilities.types.DURATION, parameters); value = value || 0; // the default value value = moment.duration(value); // since this element is immutable the value must be read-only this.getValue = function() { return value; }; return this; }
javascript
{ "resource": "" }
q7156
select
train
function select(state) { const {notificationList, visibilityFilter, ...otherStateProperties} = state; return { //select the notification list from the state notificationList: selectNotifications(notificationList, visibilityFilter), visibilityFilter, ...otherStateProperties }; }
javascript
{ "resource": "" }
q7157
train
function () { var self = this; self.renderChildren.apply(self, arguments); // only sync child sub tree at root node // only sync child sub tree at root node if (self === self.get('tree')) { updateSubTreeStatus(self, self, -1, 0); } }
javascript
{ "resource": "" }
q7158
train
function () { var self = this; self.set('expanded', true); util.each(self.get('children'), function (c) { c.expandAll(); }); }
javascript
{ "resource": "" }
q7159
train
function () { var self = this; self.set('expanded', false); util.each(self.get('children'), function (c) { c.collapseAll(); }); }
javascript
{ "resource": "" }
q7160
getPreviousVisibleNode
train
function getPreviousVisibleNode(self) { var prev = self.prev(); if (!prev) { prev = self.get('parent'); } else { prev = getLastVisibleDescendant(prev); } return prev; }
javascript
{ "resource": "" }
q7161
getNextVisibleNode
train
function getNextVisibleNode(self) { var children = self.get('children'), n, parent; if (self.get('expanded') && children.length) { return children[0]; } // 没有展开或者根本没有儿子节点 // 深度遍历的下一个 // 没有展开或者根本没有儿子节点 // 深度遍历的下一个 n = self.next(); parent = self; while (!n && (parent = parent.get('parent'))) { n = parent.next(); } return n; }
javascript
{ "resource": "" }
q7162
writeFile
train
function writeFile(filename, content) { fs.writeFileSync(filename, JSON.stringify(content, null, 2)); }
javascript
{ "resource": "" }
q7163
preview
train
function preview(name, content) { console.log('======='); console.log('JSON SCHEMA PREVIEW BEGIN: ' + name); console.log('======='); console.log(JSON.stringify(content, null, 2)); console.log('======='); console.log('JSON SCHEMA PREVIEW END: ' + name); return Promise.resolve(); }
javascript
{ "resource": "" }
q7164
normalizeArray
train
function normalizeArray(parts, allowAboveRoot) { // level above root var up = 0, i = parts.length - 1, // splice costs a lot in ie // use new array instead newParts = [], last; for (; i >= 0; i--) { last = parts[i]; if (last !== '.') { if (last === '..') { up++; } else if (up) { up--; } else { newParts[newParts.length] = last; } } } // if allow above root, has to add .. if (allowAboveRoot) { for (; up--; up) { newParts[newParts.length] = '..'; } } newParts = newParts.reverse(); return newParts; }
javascript
{ "resource": "" }
q7165
train
function (path) { var result = path.match(splitPathRe) || [], root = result[1] || '', dir = result[2] || ''; if (!root && !dir) { // No dirname return '.'; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substring(0, dir.length - 1); } return root + dir; }
javascript
{ "resource": "" }
q7166
train
function () { var self = this, count = 0, _queryMap, k; parseQuery(self); _queryMap = self._queryMap; for (k in _queryMap) { if (S.isArray(_queryMap[k])) { count += _queryMap[k].length; } else { count++; } } return count; }
javascript
{ "resource": "" }
q7167
train
function (key) { var self = this, _queryMap; parseQuery(self); _queryMap = self._queryMap; if (key) { return key in _queryMap; } else { return !S.isEmptyObject(_queryMap); } }
javascript
{ "resource": "" }
q7168
train
function (key) { var self = this, _queryMap; parseQuery(self); _queryMap = self._queryMap; if (key) { return _queryMap[key]; } else { return _queryMap; } }
javascript
{ "resource": "" }
q7169
train
function (key, value) { var self = this, _queryMap; parseQuery(self); _queryMap = self._queryMap; if (typeof key === 'string') { self._queryMap[key] = value; } else { if (key instanceof Query) { key = key.get(); } S.each(key, function (v, k) { _queryMap[k] = v; }); } return self; }
javascript
{ "resource": "" }
q7170
train
function (key) { var self = this; parseQuery(self); if (key) { delete self._queryMap[key]; } else { self._queryMap = {}; } return self; }
javascript
{ "resource": "" }
q7171
train
function (serializeArray) { var self = this; parseQuery(self); return S.param(self._queryMap, undefined, undefined, serializeArray); }
javascript
{ "resource": "" }
q7172
train
function () { var uri = new Uri(), self = this; S.each(REG_INFO, function (index, key) { uri[key] = self[key]; }); uri.query = uri.query.clone(); return uri; }
javascript
{ "resource": "" }
q7173
train
function (module) { var factory = module.factory, exports; if (typeof factory === 'function') { // compatible and efficiency // KISSY.add(function(S,undefined){}) var require; if (module.requires && module.requires.length && module.cjs) { require = bind(module.require, module); } // 需要解开 index,相对路径 // 但是需要保留 alias,防止值不对应 //noinspection JSUnresolvedFunction exports = factory.apply(module, // KISSY.add(function(S){module.require}) lazy initialize (module.cjs ? [S, require, module.exports, module] : Utils.getModules(module.getRequiresWithAlias()))); if (exports !== undefined) { //noinspection JSUndefinedPropertyAssignment module.exports = exports; } } else { //noinspection JSUndefinedPropertyAssignment module.exports = factory; } module.status = ATTACHED; }
javascript
{ "resource": "" }
q7174
train
function (relativeName, fn) { relativeName = Utils.getModNamesAsArray(relativeName); return KISSY.use(Utils.normalDepModuleName(this.name, relativeName), fn); }
javascript
{ "resource": "" }
q7175
train
function () { var self = this, uri; if (!self.uri) { // path can be specified if (self.path) { uri = new S.Uri(self.path); } else { uri = S.Config.resolveModFn(self); } self.uri = uri; } return self.uri; }
javascript
{ "resource": "" }
q7176
train
function () { var self = this, requiresWithAlias = self.requiresWithAlias, requires = self.requires; if (!requires || requires.length === 0) { return requires || []; } else if (!requiresWithAlias) { self.requiresWithAlias = requiresWithAlias = Utils.normalizeModNamesWithAlias(requires, self.name); } return requiresWithAlias; }
javascript
{ "resource": "" }
q7177
train
function (moduleName, refName) { if (moduleName) { var moduleNames = Utils.unalias(Utils.normalizeModNamesWithAlias([moduleName], refName)); Utils.attachModsRecursively(moduleNames); return Utils.getModules(moduleNames)[1]; } }
javascript
{ "resource": "" }
q7178
Stack
train
function Stack(parameters) { parameters = parameters || new composites.Parameters(new Catalog()); if (!parameters.getParameter('$type')) parameters.setParameter('$type', '/bali/collections/Stack/v1'); abstractions.Collection.call(this, utilities.types.STACK, parameters); // the capacity and array are private attributes so methods that use it are // defined in the constructor var capacity = 1024; // default capacity if (parameters) { const value = parameters.getParameter('$capacity', 2); if (value) capacity = value.toNumber(); } const array = []; this.acceptVisitor = function(visitor) { visitor.visitStack(this); }; this.toArray = function() { return array.slice(); // copy the array }; this.getSize = function() { return array.length; }; this.addItem = function(item) { if (array.length < capacity) { item = this.convert(item); array.push(item); return true; } throw new utilities.Exception({ $module: '/bali/collections/Stack', $procedure: '$addItem', $exception: '$resourceLimit', $capacity: capacity, $text: '"The stack has reached its maximum capacity."' }); }; this.removeItem = function() { if (array.length > 0) { return array.pop(); } throw new utilities.Exception({ $module: '/bali/collections/Stack', $procedure: '$removeItem', $exception: '$emptyStack', $text: '"Attempted to remove an item from an empty stack."' }); }; this.getTop = function() { if (array.length > 0) { return array.peek(); } throw new utilities.Exception({ $module: '/bali/collections/Stack', $procedure: '$getTop', $exception: '$emptyStack', $text: '"Attempted to access an item on an empty stack."' }); }; this.deleteAll = function() { array.splice(0); }; return this; }
javascript
{ "resource": "" }
q7179
train
function(params) { var options = params ? corbel.utils.clone(params) : {}; var args = corbel.utils.extend(options, { url: this._buildUri(this.uri, this.id), method: corbel.request.method.GET, query: params ? corbel.utils.serializeParams(params) : null }); return this.request(args); }
javascript
{ "resource": "" }
q7180
train
function(data) { return this.request({ url: this._buildUri(this.uri), method: corbel.request.method.POST, data: data }). then(function(res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7181
train
function(params) { var args = params ? corbel.utils.clone(params) : {}; args.url = this._buildUri(this.uri + '/access'); args.method = corbel.request.method.GET; args.noRedirect = true; var that = this; return this.request(args). then(function(response) { return that.request({ noRetry: args.noRetry, method: corbel.request.method.POST, contentType: 'application/x-www-form-urlencoded; charset=UTF-8', data:response.data, url: response.headers.location }); }); }
javascript
{ "resource": "" }
q7182
train
function(data, cb) { if (corbel.Config.isNode) { // in node transform to stream cb(corbel.utils.toURLEncoded(data)); } else { // in browser transform to blob cb(corbel.utils.dataURItoBlob(data)); } }
javascript
{ "resource": "" }
q7183
train
function(response, resolver, callbackSuccess, callbackError) { //xhr = xhr.target || xhr || {}; var statusCode = xhrSuccessStatus[response.status] || response.status, statusType = Number(response.status.toString()[0]), promiseResponse; var data = response.response; var headers = corbel.utils.keysToLowerCase(response.headers); if (statusType <= 3 && !response.error) { if (response.response) { data = request.parse(response.response, response.responseType, response.dataType); } if (callbackSuccess) { callbackSuccess.call(this, data, statusCode, response.responseObject, headers); } promiseResponse = { data: data, status: statusCode, headers: headers }; promiseResponse[response.responseObjectType] = response.responseObject; resolver.resolve(promiseResponse); } else { var disconnected = response.error && response.status === 0; statusCode = disconnected ? 0 : statusCode; if (callbackError) { callbackError.call(this, response.error, statusCode, response.responseObject, headers); } if (response.response) { data = request.parse(response.response, response.responseType, response.dataType); } promiseResponse = { data: data, status: statusCode, error: response.error, headers: headers }; promiseResponse[response.responseObjectType] = response.responseObject; resolver.reject(promiseResponse); } }
javascript
{ "resource": "" }
q7184
train
function(params) { var that = this; return corbel.request.send(params, that.driver).then(function(response) { that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, 0); that.driver.config.set(corbel.Services._UNAUTHORIZED_NUM_RETRIES, 0); return response; }).catch(function(response) { // Force update if (response.status === corbel.Services._FORCE_UPDATE_STATUS_CODE && response.textStatus === corbel.Services._FORCE_UPDATE_TEXT) { var retries = that.driver.config.get(corbel.Services._FORCE_UPDATE_STATUS, 0); if (retries < corbel.Services._FORCE_UPDATE_MAX_RETRIES) { retries++; that.driver.config.set(corbel.Services._FORCE_UPDATE_STATUS, retries); that.driver.trigger('force:update', response); throw response; } else { throw response; } } else { throw response; } }); }
javascript
{ "resource": "" }
q7185
train
function(tokenObject) { var that = this; if (this.driver._refreshHandlerPromise) { return this.driver._refreshHandlerPromise; } if (tokenObject.refreshToken) { console.log('corbeljs:services:token:refresh'); this.driver._refreshHandlerPromise = this.driver.iam.token().refresh( tokenObject.refreshToken, this.driver.config.get(corbel.Iam.IAM_TOKEN_SCOPES, '') ); } else { console.log('corbeljs:services:token:create'); this.driver._refreshHandlerPromise = this.driver.iam.token().create(); } return this.driver._refreshHandlerPromise .then(function(response) { that.driver.trigger('token:refresh', response.data); that.driver._refreshHandlerPromise = null; return response; }).catch(function(err) { that.driver._refreshHandlerPromise = null; throw err; }); }
javascript
{ "resource": "" }
q7186
train
function(params) { var accessToken = params.accessToken ? params.accessToken : this.driver.config .get(corbel.Iam.IAM_TOKEN, {}).accessToken; if (accessToken && !params.headers.Authorization) { params.headers.Authorization = 'Bearer ' + accessToken; params.withCredentials = true; } else if (params.headers.Authorization) { params.withCredentials = true; } return params; }
javascript
{ "resource": "" }
q7187
train
function(responseObject) { var location = this._getLocationHeader(responseObject); return location ? location.substr(location.lastIndexOf('/') + 1) : undefined; }
javascript
{ "resource": "" }
q7188
train
function(responseObject) { responseObject = responseObject || {}; if (responseObject.xhr) { return responseObject.xhr.getResponseHeader('Location'); } else if (responseObject.response && responseObject.response.headers.location) { return responseObject.response.headers.location; } }
javascript
{ "resource": "" }
q7189
train
function(client) { console.log('iamInterface.client.create', client); return this.request({ url: this._buildUriWithDomain(this.uri), method: corbel.request.method.POST, data: client }).then(function(res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7190
train
function(client) { console.log('iamInterface.client.update', client); corbel.validate.value('clientId', this.clientId); return this.request({ url: this._buildUriWithDomain(this.uri + '/' + this.clientId), method: corbel.request.method.PUT, data: client }); }
javascript
{ "resource": "" }
q7191
train
function(domain) { console.log('iamInterface.domain.update', domain); return this.request({ url: this._buildUriWithDomain(this.uri), method: corbel.request.method.PUT, data: domain }); }
javascript
{ "resource": "" }
q7192
train
function(scope) { corbel.validate.failIfIsDefined(this.id, 'This function not allowed scope identifier'); console.log('iamInterface.scope.create', scope); return this.request({ url: this._buildUriWithDomain(this.uri), method: corbel.request.method.POST, data: scope }).then(function(res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7193
train
function(params) { params = params || {}; params.claims = params.claims || {}; if (params.jwt) { return params.jwt; } var secret = params.secret || this.driver.config.get('clientSecret'); params.claims.iss = params.claims.iss || this.driver.config.get('clientId'); params.claims.aud = params.claims.aud || this.driver.config.get('audience', corbel.Iam.AUD); params.claims.scope = params.claims.scope || this.driver.config.get('scopes', ''); return corbel.jwt.generate(params.claims, secret); }
javascript
{ "resource": "" }
q7194
train
function(refreshToken, scopes) { // console.log('iamInterface.token.refresh', refreshToken); // we need refresh token to refresh access token corbel.validate.isValue(refreshToken, 'Refresh access token request must contains refresh token'); // we need create default claims to refresh access token var params = { claims: { 'scope': scopes, 'refresh_token': refreshToken } }; var that = this; try { return this._doPostTokenRequest(this.uri, params) .then(function(response) { that.driver.config.set(corbel.Iam.IAM_TOKEN, response.data); return response; }); } catch (e) { console.log('error', e); return Promise.reject(e); } }
javascript
{ "resource": "" }
q7195
train
function() { console.log('iamInterface.user.get'); corbel.validate.value('id', this.id); return this._getUser(corbel.request.method.GET, this.uri, this.id); }
javascript
{ "resource": "" }
q7196
train
function(data, options) { console.log('iamInterface.user.update', data); corbel.validate.value('id', this.id); var args = corbel.utils.extend(options || {}, { url: this._buildUriWithDomain(this.uri, this.id), method: corbel.request.method.PUT, data: data }); return this.request(args); }
javascript
{ "resource": "" }
q7197
train
function(options) { var queryParams = ''; if (options && options.avoidNotification) { queryParams = '?avoidnotification=true'; } console.log('iamInterface.user.delete'); corbel.validate.value('id', this.id); return this.request({ url: this._buildUriWithDomain(this.uri, this.id) + queryParams, method: corbel.request.method.DELETE }); }
javascript
{ "resource": "" }
q7198
train
function(deviceId, data) { console.log('iamInterface.user.registerDevice'); corbel.validate.values(['id', 'deviceId'], { 'id': this.id, 'deviceId': deviceId }); return this.request({ url: this._buildUriWithDomain(this.uri, this.id) + '/device/' + deviceId, method: corbel.request.method.PUT, data: data }).then(function(res) { return corbel.Services.getLocationId(res); }); }
javascript
{ "resource": "" }
q7199
train
function(group) { console.log('iamInterface.user.deleteGroup'); corbel.validate.values(['id', 'group'], { 'id': this.id, 'group': group }); return this.request({ url: this._buildUriWithDomain(this.uri, this.id) + '/group/' + group, method: corbel.request.method.DELETE }); }
javascript
{ "resource": "" }