_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q46300
train
function(map, origin) { this.writeDebug('inlineDirections',arguments); if (this.settings.inlineDirections !== true || typeof origin === 'undefined') { return; } var _this = this; // Open directions $(document).on('click.'+pluginName, '.' + _this.settings.locationList + ' li .loc-directions a', function (e) { e.preventDefault(); var locID = $(this).closest('li').attr('data-markerid'); _this.directionsRequest(origin, parseInt(locID), map); // Close directions $(document).on('click.'+pluginName, '.' + _this.settings.locationList + ' .bh-sl-close-icon', function () { _this.closeDirections(); }); }); }
javascript
{ "resource": "" }
q46301
train
function(map, markers) { this.writeDebug('visibleMarkersList',arguments); if (this.settings.visibleMarkersList !== true) { return; } var _this = this; // Add event listener to filter the list when the map is fully loaded google.maps.event.addListenerOnce(map, 'idle', function(){ _this.checkVisibleMarkers(markers, map); }); // Add event listener for center change google.maps.event.addListener(map, 'center_changed', function() { _this.checkVisibleMarkers(markers, map); }); // Add event listener for zoom change google.maps.event.addListener(map, 'zoom_changed', function() { _this.checkVisibleMarkers(markers, map); }); }
javascript
{ "resource": "" }
q46302
train
function (mappingObject) { this.writeDebug('mapping',arguments); var _this = this; var orig_lat, orig_lng, geocodeData, origin, originPoint, page; if (!this.isEmptyObject(mappingObject)) { orig_lat = mappingObject.lat; orig_lng = mappingObject.lng; geocodeData = mappingObject.geocodeResult; origin = mappingObject.origin; page = mappingObject.page; } // Set the initial page to zero if not set if ( _this.settings.pagination === true ) { if (typeof page === 'undefined' || originalOrigin !== addressInput ) { page = 0; } } // Data request if (typeof origin === 'undefined' && this.settings.nameSearch === true) { dataRequest = _this._getData(); } else { // Setup the origin point originPoint = new google.maps.LatLng(orig_lat, orig_lng); // If the origin hasn't changed use the existing data so we aren't making unneeded AJAX requests if ((typeof originalOrigin !== 'undefined') && (origin === originalOrigin) && (typeof originalData !== 'undefined')) { origin = originalOrigin; dataRequest = originalData; } else { // Do the data request - doing this in mapping so the lat/lng and address can be passed over and used if needed dataRequest = _this._getData(olat, olng, origin, geocodeData, mappingObject); } } // Check filters here to handle selected filtering after page reload if (_this.settings.taxonomyFilters !== null && _this.hasEmptyObjectVals(filters)) { _this.checkFilters(); } /** * Process the location data */ // Raw data if ( _this.settings.dataRaw !== null ) { _this.processData(mappingObject, originPoint, dataRequest, page); } // Remote data else { dataRequest.done(function (data) { _this.processData(mappingObject, originPoint, data, page); }); } }
javascript
{ "resource": "" }
q46303
calculateScrollDistribution
train
function calculateScrollDistribution(deltaX, deltaY, element, container, accumulator = []) { const scrollInformation = { element, scrollLeft: 0, scrollTop: 0 }; const scrollLeftMax = element.scrollWidth - element.clientWidth; const scrollTopMax = element.scrollHeight - element.clientHeight; const availableScroll = { deltaXNegative: -element.scrollLeft, deltaXPositive: scrollLeftMax - element.scrollLeft, deltaYNegative: -element.scrollTop, deltaYPositive: scrollTopMax - element.scrollTop }; const elementStyle = window.getComputedStyle(element); if (elementStyle.overflowX !== 'hidden') { // The `deltaX` can be larger than the available scroll for the element, thus overshooting. // The result of that is that it scrolls the element as far as possible. We don't need to // calculate exactly because we reduce the amount of desired scroll for the // parent elements by the correct amount below. scrollInformation.scrollLeft = element.scrollLeft + deltaX; if (deltaX > availableScroll.deltaXPositive) { deltaX = deltaX - availableScroll.deltaXPositive; } else if (deltaX < availableScroll.deltaXNegative) { deltaX = deltaX - availableScroll.deltaXNegative; } else { deltaX = 0; } } if (elementStyle.overflowY !== 'hidden') { scrollInformation.scrollTop = element.scrollTop + deltaY; if (deltaY > availableScroll.deltaYPositive) { deltaY = deltaY - availableScroll.deltaYPositive; } else if (deltaY < availableScroll.deltaYNegative) { deltaY = deltaY - availableScroll.deltaYNegative; } else { deltaY = 0; } } if (element !== container && (deltaX || deltaY)) { return calculateScrollDistribution(deltaX, deltaY, element.parentNode, container, accumulator.concat([scrollInformation])); } return accumulator.concat([scrollInformation]); }
javascript
{ "resource": "" }
q46304
dropdownIsValidParent
train
function dropdownIsValidParent(el, dropdownId) { let closestDropdown = closestContent(el); if (closestDropdown) { let trigger = document.querySelector(`[aria-owns=${closestDropdown.attributes.id.value}]`); let parentDropdown = closestContent(trigger); return parentDropdown && parentDropdown.attributes.id.value === dropdownId || dropdownIsValidParent(parentDropdown, dropdownId); } else { return false; } }
javascript
{ "resource": "" }
q46305
contentDisposition
train
function contentDisposition (filename, options) { var opts = options || {} // get type var type = opts.type || 'attachment' // get parameters var params = createparams(filename, opts.fallback) // format into string return format(new ContentDisposition(type, params)) }
javascript
{ "resource": "" }
q46306
getCSSText
train
function getCSSText(className) { if (typeof document.styleSheets != "object") return ""; if (document.styleSheets.length <= 0) return ""; var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules; for (var x = 0; x < classes.length; x++) { if (classes[x].selectorText == "." + className || classes[x].selectorText == "#" + className) { return ((classes[x].cssText) ? (classes[x].cssText) : (classes[x].style.cssText)); } } return ""; }
javascript
{ "resource": "" }
q46307
checkBrowser
train
function checkBrowser() { this.ver = navigator.appVersion this.dom = document.getElementById ? 1 : 0 this.ie5 = (this.ver.indexOf("MSIE 5") > -1 && this.dom) ? 1 : 0; this.ie4 = (document.all && !this.dom) ? 1 : 0; this.ns5 = (this.dom && parseInt(this.ver) >= 5) ? 1 : 0; this.ns4 = (document.layers && !this.dom) ? 1 : 0; this.bw = (this.ie5 || this.ie4 || this.ns4 || this.ns5) return this }
javascript
{ "resource": "" }
q46308
reverseData
train
function reverseData(data) { data.labels = data.labels.reverse(); for (var i = 0; i < data.datasets.length; i++) { for (var key in data.datasets[i]) { if (Array.isArray(data.datasets[i][key])) { data.datasets[i][key] = data.datasets[i][key].reverse(); } } } return data; }
javascript
{ "resource": "" }
q46309
drawMathLine
train
function drawMathLine(i,lineFct) { var line = 0; // check if the math function exists if (typeof eval(lineFct) == "function") { var parameter = {data:data,datasetNr: i}; line = window[lineFct](parameter); } if (!(typeof(line)=='undefined')) { ctx.strokeStyle= data.datasets[i].mathLineStrokeColor ? data.datasets[i].mathLineStrokeColor : config.defaultStrokeColor; ctx.lineWidth = config.datasetStrokeWidth; ctx.beginPath(); ctx.moveTo(yAxisPosX,yPos(i,0,line,false)); ctx.lineTo(yAxisPosX + msr.availableWidth,yPos(i,data.datasets[i].data.length-1,line,false)); ctx.stroke(); ctx.closePath(); } }
javascript
{ "resource": "" }
q46310
yPos
train
function yPos(dataSet, iteration, add,value) { value = value ? 1*data.datasets[dataSet].data[iteration] : 0; return xAxisPosY - calculateOffset(config.logarithmic, value+add, calculatedScale, scaleHop); }
javascript
{ "resource": "" }
q46311
populateLabels
train
function populateLabels(axis, config, labelTemplateString, labels, numberOfSteps, graphMin, graphMax, stepValue) { var logarithmic; if (axis == 2) { logarithmic = config.logarithmic2; fmtYLabel = config.fmtYLabel2; } else { logarithmic = config.logarithmic; fmtYLabel = config.fmtYLabel; } if (labelTemplateString) { //Fix floating point errors by setting to fixed the on the same decimal as the stepValue. if (!logarithmic) { // no logarithmic scale for (var i = 0; i < numberOfSteps + 1; i++) { labels.push(tmpl(labelTemplateString, { value: fmtChartJS(config, 1 * ((graphMin + (stepValue * i)).toFixed(getDecimalPlaces(stepValue))), fmtYLabel) })); } } else { // logarithmic scale 10,100,1000,... var value = graphMin; for (var i = 0; i < numberOfSteps + 1; i++) { labels.push(tmpl(labelTemplateString, { value: fmtChartJS(config, 1 * value.toFixed(getDecimalPlaces(value)), fmtYLabel) })); value *= 10; } } } }
javascript
{ "resource": "" }
q46312
train
function(allowImprecise) { var b = this.buffer, o = this.offset; // Running sum of octets, doing a 2's complement var negate = b[o] & 0x80, x = 0, carry = 1; for (var i = 7, m = 1; i >= 0; i--, m *= 256) { var v = b[o+i]; // 2's complement for negative numbers if (negate) { v = (v ^ 0xff) + carry; carry = v >> 8; v = v & 0xff; } x += v * m; } // Return Infinity if we've lost integer precision if (!allowImprecise && x >= Int64.MAX_INT) { return negate ? -Infinity : Infinity; } return negate ? -x : x; }
javascript
{ "resource": "" }
q46313
train
function(sep) { var out = new Array(8); var b = this.buffer, o = this.offset; for (var i = 0; i < 8; i++) { out[i] = _HEX[b[o+i]]; } return out.join(sep || ''); }
javascript
{ "resource": "" }
q46314
train
function(rawBuffer) { if (rawBuffer && this.offset === 0) return this.buffer; var out = new Buffer(8); this.buffer.copy(out, 0, this.offset, this.offset + 8); return out; }
javascript
{ "resource": "" }
q46315
train
function(other) { // If sign bits differ ... if ((this.buffer[this.offset] & 0x80) != (other.buffer[other.offset] & 0x80)) { return other.buffer[other.offset] - this.buffer[this.offset]; } // otherwise, compare bytes lexicographically for (var i = 0; i < 8; i++) { if (this.buffer[this.offset+i] !== other.buffer[other.offset+i]) { return this.buffer[this.offset+i] - other.buffer[other.offset+i]; } } return 0; }
javascript
{ "resource": "" }
q46316
_isValidCoreURI
train
function _isValidCoreURI(coreURI) { if (_isEmpty(coreURI) || !_isString(coreURI)) return false try { return isURL(coreURI, { protocols: ['https'], require_protocol: true, host_whitelist: [/^[a-z]\.chainpoint\.org$/] }) } catch (error) { return false } }
javascript
{ "resource": "" }
q46317
_isValidNodeURI
train
function _isValidNodeURI(nodeURI) { if (!_isString(nodeURI)) return false try { let isValidURI = isURL(nodeURI, { protocols: ['http', 'https'], require_protocol: true, host_blacklist: ['0.0.0.0'] }) let parsedURI = url.parse(nodeURI).hostname // Valid URI w/ IPv4 address? return isValidURI && isIP(parsedURI, 4) } catch (error) { return false } }
javascript
{ "resource": "" }
q46318
_isHex
train
function _isHex(value) { var hexRegex = /^[0-9a-f]{2,}$/i var isHex = hexRegex.test(value) && !(value.length % 2) return isHex }
javascript
{ "resource": "" }
q46319
_isValidProofHandle
train
function _isValidProofHandle(handle) { if ( !_isEmpty(handle) && _isObject(handle) && _has(handle, 'uri') && _has(handle, 'hashIdNode') ) { return true } }
javascript
{ "resource": "" }
q46320
_mapSubmitHashesRespToProofHandles
train
function _mapSubmitHashesRespToProofHandles(respArray) { if (!_isArray(respArray) && !respArray.length) throw new Error('_mapSubmitHashesRespToProofHandles arg must be an Array') let proofHandles = [] let groupIdList = [] if (respArray[0] && respArray[0].hashes) { _forEach(respArray[0].hashes, () => { groupIdList.push(uuidv1()) }) } _forEach(respArray, resp => { _forEach(resp.hashes, (hash, idx) => { let handle = {} handle.uri = resp.meta.submitted_to handle.hash = hash.hash handle.hashIdNode = hash.hash_id_node handle.groupId = groupIdList[idx] proofHandles.push(handle) }) }) return proofHandles }
javascript
{ "resource": "" }
q46321
_parseProofs
train
function _parseProofs(proofs) { if (!_isArray(proofs)) throw new Error('proofs arg must be an Array') if (_isEmpty(proofs)) throw new Error('proofs arg must be a non-empty Array') let parsedProofs = [] _forEach(proofs, proof => { if (_isObject(proof)) { // OBJECT parsedProofs.push(cpp.parse(proof)) } else if (isJSON(proof)) { // JSON-LD parsedProofs.push(cpp.parse(JSON.parse(proof))) } else if (isBase64(proof) || _isBuffer(proof) || _isHex(proof)) { // BINARY parsedProofs.push(cpp.parse(proof)) } else { throw new Error('unknown proof format') } }) return parsedProofs }
javascript
{ "resource": "" }
q46322
_flattenProofs
train
function _flattenProofs(parsedProofs) { if (!_isArray(parsedProofs)) throw new Error('parsedProofs arg must be an Array') if (_isEmpty(parsedProofs)) throw new Error('parsedProofs arg must be a non-empty Array') let flatProofAnchors = [] _forEach(parsedProofs, parsedProof => { let proofAnchors = _flattenProofBranches(parsedProof.branches) _forEach(proofAnchors, proofAnchor => { let flatProofAnchor = {} flatProofAnchor.hash = parsedProof.hash flatProofAnchor.hash_id_node = parsedProof.hash_id_node flatProofAnchor.hash_id_core = parsedProof.hash_id_core flatProofAnchor.hash_submitted_node_at = parsedProof.hash_submitted_node_at flatProofAnchor.hash_submitted_core_at = parsedProof.hash_submitted_core_at flatProofAnchor.branch = proofAnchor.branch flatProofAnchor.uri = proofAnchor.uri flatProofAnchor.type = proofAnchor.type flatProofAnchor.anchor_id = proofAnchor.anchor_id flatProofAnchor.expected_value = proofAnchor.expected_value flatProofAnchors.push(flatProofAnchor) }) }) return flatProofAnchors }
javascript
{ "resource": "" }
q46323
_flattenProofBranches
train
function _flattenProofBranches(proofBranchArray) { let flatProofAnchors = [] _forEach(proofBranchArray, proofBranch => { let anchors = proofBranch.anchors _forEach(anchors, anchor => { let flatAnchor = {} flatAnchor.branch = proofBranch.label || undefined flatAnchor.uri = anchor.uris[0] flatAnchor.type = anchor.type flatAnchor.anchor_id = anchor.anchor_id flatAnchor.expected_value = anchor.expected_value flatProofAnchors.push(flatAnchor) }) if (proofBranch.branches) { flatProofAnchors = flatProofAnchors.concat( _flattenProofBranches(proofBranch.branches) ) } }) return flatProofAnchors }
javascript
{ "resource": "" }
q46324
_flattenBtcBranches
train
function _flattenBtcBranches(proofs) { let flattenedBranches = [] _forEach(proofs, proof => { let btcAnchor = {} btcAnchor.hash_id_node = proof.hash_id_node if (proof.branches) { _forEach(proof.branches, branch => { // sub branches indicate other anchors // we want to find the sub-branch that anchors to btc if (branch.branches) { // get the raw tx from the btc_anchor_branch let btcBranch = branch.branches.find( element => element.label === 'btc_anchor_branch' ) btcAnchor.raw_btc_tx = btcBranch.rawTx // get the btc anchor let anchor = btcBranch.anchors.find(anchor => anchor.type === 'btc') // add expected_value (i.e. the merkle root of anchored block) btcAnchor.expected_value = anchor.expected_value // add anchor_id (i.e. the anchored block height) btcAnchor.anchor_id = anchor.anchor_id } }) } flattenedBranches.push(btcAnchor) }) return flattenedBranches }
javascript
{ "resource": "" }
q46325
_normalizeProofs
train
function _normalizeProofs(proofs) { // Validate proofs arg if (!_isArray(proofs)) throw new Error('proofs arg must be an Array') if (_isEmpty(proofs)) throw new Error('proofs arg must be a non-empty Array') // If any entry in the proofs Array is an Object, process // it assuming the same form as the output of getProofs(). return _map(proofs, proof => { if (_isObject(proof) && _has(proof, 'proof') && _isString(proof.proof)) { // Probably result of `submitProofs()` call. Extract proof String return proof.proof } else if ( _isObject(proof) && _has(proof, 'type') && proof.type === 'Chainpoint' ) { // Probably a JS Object Proof return proof } else if (_isString(proof) && (isJSON(proof) || isBase64(proof))) { // Probably a JSON String or Base64 encoded binary proof return proof } else { throw new Error( 'proofs arg Array has elements that are not Objects or Strings' ) } }) }
javascript
{ "resource": "" }
q46326
train
function () { var sheet = Foundation.stylesheet; if (typeof this.rule_idx !== 'undefined') { sheet.deleteRule(this.rule_idx); sheet.deleteRule(this.rule_idx); delete this.rule_idx; } }
javascript
{ "resource": "" }
q46327
guessAtomElementFromName
train
function guessAtomElementFromName(fourLetterName) { if (fourLetterName[0] !== ' ') { var trimmed = fourLetterName.trim(); if (trimmed.length === 4) { // look for first character in range A-Z or a-z and use that // for the element. var i = 0; var charCode = trimmed.charCodeAt(i); while (i < 4 && (charCode < 65 || charCode > 122 || (charCode > 90 && charCode < 97))) { ++i; charCode = trimmed.charCodeAt(i); } return trimmed[i]; } // when first character is not empty and length is smaller than 4, // assume that it's either a heavy atom (CA, etc), or a hydrogen // name with a numeric prefix. That's not always correct, though. var firstCharCode = trimmed.charCodeAt(0); if (firstCharCode >= 48 && firstCharCode <= 57) { // numeric prefix, so it's a hydrogen return trimmed[1]; } return trimmed.substr(0, 2); } return fourLetterName[1]; }
javascript
{ "resource": "" }
q46328
train
function(fromNumAndIns, toNumAndIns, ss) { // FIXME: when the chain numbers are completely ordered, perform binary // search to identify range of residues to assign secondary structure to. var from = rnumInsCodeHash(fromNumAndIns[0], fromNumAndIns[1]); var to = rnumInsCodeHash(toNumAndIns[0], toNumAndIns[1]); for (var i = 1; i < this._residues.length-1; ++i) { var res = this._residues[i]; // FIXME: we currently don't set the secondary structure of the last // residue of helices and sheets. that takes care of better transitions // between coils and helices. ideally, this should be done in the // cartoon renderer, NOT in this function. var combined = rnumInsCodeHash(res.num(), res.insCode()); if (combined < from || combined >= to) { continue; } res.setSS(ss); } }
javascript
{ "resource": "" }
q46329
train
function(chains) { var vertArrays = this.vertArrays(); var selectedArrays = []; var set = {}; for (var ci = 0; ci < chains.length; ++ci) { set[chains[ci]] = true; } for (var i = 0; i < vertArrays.length; ++i) { if (set[vertArrays[i].chain()] === true) { selectedArrays.push(vertArrays[i]); } } return selectedArrays; }
javascript
{ "resource": "" }
q46330
train
function(cam, shader, assembly) { var gens = assembly.generators(); for (var i = 0; i < gens.length; ++i) { var gen = gens[i]; var affectedVAs = this._vertArraysInvolving(gen.chains()); this._drawVertArrays(cam, shader, affectedVAs, gen.matrices()); } }
javascript
{ "resource": "" }
q46331
train
function(out) { if (!out) { out = vec3.create(); } vec3.add(out, self.atom_one.pos(), self.atom_two.pos()); vec3.scale(out, out, 0.5); return out; }
javascript
{ "resource": "" }
q46332
Cam
train
function Cam(gl) { this._projection = mat4.create(); this._camModelView = mat4.create(); this._modelView = mat4.create(); this._rotation = mat4.create(); this._translation = mat4.create(); this._near = 0.10; this._onCameraChangedListeners = []; this._far = 4000.0; this._fogNear = -5; this._fogFar = 50; this._fog = true; this._fovY = Math.PI * 45.0 / 180.0; this._fogColor = vec3.fromValues(1, 1, 1); this._outlineColor = vec3.fromValues(0.1, 0.1, 0.1); this._outlineWidth = 1.0; this._outlineEnabled = true; this._selectionColor = vec4.fromValues(0.1, 1.0, 0.1, 0.7); this._center = vec3.create(); this._zoom = 50; this._screenDoorTransparency = false; this._updateProjectionMat = true; this._updateModelViewMat = true; this._upsamplingFactor = 1; this._gl = gl; this._currentShader = null; this._stateId = 0; this.setViewportSize(gl.viewportWidth, gl.viewportHeight); }
javascript
{ "resource": "" }
q46333
train
function() { return[ vec3.fromValues(this._rotation[0], this._rotation[4], this._rotation[8]), vec3.fromValues(this._rotation[1], this._rotation[5], this._rotation[9]), vec3.fromValues(this._rotation[2], this._rotation[6], this._rotation[10]) ]; }
javascript
{ "resource": "" }
q46334
train
function(traces, vertsPerSlice, splineDetail) { var numVerts = 0; for (var i = 0; i < traces.length; ++i) { var traceVerts = ((traces[i].length() - 1) * splineDetail + 1) * vertsPerSlice; // in case there are more than 2^16 vertices for a single trace, we // need to manually split the trace in two and duplicate one of the // trace slices. Let's make room for some additional space... var splits = Math.ceil((traceVerts + 2)/65536); numVerts += traceVerts + (splits - 1) * vertsPerSlice; // triangles for capping the tube numVerts += 2; } return numVerts; }
javascript
{ "resource": "" }
q46335
train
function(out, axis, angle) { var sa = Math.sin(angle), ca = Math.cos(angle), x = axis[0], y = axis[1], z = axis[2], xx = x * x, xy = x * y, xz = x * z, yy = y * y, yz = y * z, zz = z * z; out[0] = xx + ca - xx * ca; out[1] = xy - ca * xy - sa * z; out[2] = xz - ca * xz + sa * y; out[3] = xy - ca * xy + sa * z; out[4] = yy + ca - ca * yy; out[5] = yz - ca * yz - sa * x; out[6] = xz - ca * xz - sa * y; out[7] = yz - ca * yz + sa * x; out[8] = zz + ca - ca * zz; return out; }
javascript
{ "resource": "" }
q46336
interpolateScalars
train
function interpolateScalars(values, num) { var out = new Float32Array(num*(values.length-1) + 1); var index = 0; var bf = 0.0, af = 0.0; var delta = 1/num; for (var i = 0; i < values.length-1; ++i) { bf = values[i]; af = values[i + 1]; for (var j = 0; j < num; ++j) { var t = delta * j; out[index+0] = bf*(1-t)+af*t; index+=1; } } out[index+0] = af; return out; }
javascript
{ "resource": "" }
q46337
ContinuousIdRange
train
function ContinuousIdRange(pool, start, end) { this._pool = pool; this._start = start; this._next = start; this._end = end; }
javascript
{ "resource": "" }
q46338
train
function() { if (!this._resize) { return; } this._resize = false; this._cam.setViewportSize(this._canvas.viewportWidth(), this._canvas.viewportHeight()); this._pickBuffer.resize(this._options.width, this._options.height); }
javascript
{ "resource": "" }
q46339
train
function(name, structure, opts) { opts = opts || {}; opts.forceTube = true; return this.cartoon(name, structure, opts); }
javascript
{ "resource": "" }
q46340
train
function(ms) { var axes = this._cam.mainAxes(); var intervals = [ new utils.Range(), new utils.Range(), new utils.Range() ]; this.forEach(function(obj) { if (!obj.visible()) { return; } obj.updateProjectionIntervals(axes[0], axes[1], axes[2], intervals[0], intervals[1], intervals[2]); }); this._fitToIntervals(axes, intervals, ms); }
javascript
{ "resource": "" }
q46341
train
function(enable) { if (enable === undefined) { return this._rockAndRoll !== null; } if (!!enable) { if (this._rockAndRoll === null) { this._rockAndRoll = anim.rockAndRoll(); this._animControl.add(this._rockAndRoll); this.requestRedraw(); } return true; } this._animControl.remove(this._rockAndRoll); this._rockAndRoll = null; this.requestRedraw(); return false; }
javascript
{ "resource": "" }
q46342
train
function(glob) { var newObjects = []; var regex = this._globToRegex(glob); for (var i = 0; i < this._objects.length; ++i) { var obj = this._objects[i]; if (!regex.test(obj.name())) { newObjects.push(obj); } else { obj.destroy(); } } this._objects = newObjects; }
javascript
{ "resource": "" }
q46343
LineChainData
train
function LineChainData(chain, gl, numVerts, float32Allocator) { VertexArray.call(this, gl, numVerts, float32Allocator); this._chain = chain; }
javascript
{ "resource": "" }
q46344
train
function(camera) { var time = Date.now(); this._animations = this._animations.filter(function(anim) { return !anim.step(camera, time); }); return this._animations.length > 0; }
javascript
{ "resource": "" }
q46345
train
function(width, height) { if (width === this._width && height === this._height) { return; } this._resize = true; this._width = width; this._height = height; }
javascript
{ "resource": "" }
q46346
LineGeom
train
function LineGeom(gl, float32Allocator) { BaseGeom.call(this, gl); this._vertArrays = []; this._float32Allocator = float32Allocator; this._lineWidth = 0.5; this._pointSize = 1.0; }
javascript
{ "resource": "" }
q46347
TraceVertexAssoc
train
function TraceVertexAssoc(structure, interpolation, callColoringBeginEnd) { this._structure = structure; this._assocs = []; this._callBeginEnd = callColoringBeginEnd; this._interpolation = interpolation || 1; this._perResidueColors = {}; }
javascript
{ "resource": "" }
q46348
train
function() { var center = this.center(); var radiusSquare = 0.0; this.eachAtom(function(atom) { radiusSquare = Math.max(radiusSquare, vec3.sqrDist(center, atom.pos())); }); return new geom.Sphere(center, Math.sqrt(radiusSquare)); }
javascript
{ "resource": "" }
q46349
train
function() { var chains = this.chains(); var traces = []; for (var i = 0; i < chains.length; ++i) { Array.prototype.push.apply(traces, chains[i].backboneTraces()); } return traces; }
javascript
{ "resource": "" }
q46350
train
function() { console.time('Mol.deriveConnectivity'); var thisStructure = this; var prevResidue = null; this.eachResidue(function(res) { var sqrDist; var atoms = res.atoms(); var numAtoms = atoms.length; for (var i = 0; i < numAtoms; i+=1) { var atomI = atoms[i]; var posI = atomI.pos(); var covalentI = covalentRadius(atomI.element()); for (var j = 0; j < i; j+=1) { var atomJ = atoms[j]; var covalentJ = covalentRadius(atomJ.element()); sqrDist = vec3.sqrDist(posI, atomJ.pos()); var lower = covalentI+covalentJ-0.30; var upper = covalentI+covalentJ+0.30; if (sqrDist < upper*upper && sqrDist > lower*lower) { thisStructure.connect(atomI, atomJ); } } } res._deduceType(); if (prevResidue !== null) { if (res.isAminoacid() && prevResidue.isAminoacid()) { connectPeptides(thisStructure, prevResidue, res); } if (res.isNucleotide() && prevResidue.isNucleotide()) { connectNucleotides(thisStructure, prevResidue, res); } } prevResidue = res; }); console.timeEnd('Mol.deriveConnectivity'); }
javascript
{ "resource": "" }
q46351
train
function(chain, recurse) { var chainView = new ChainView(this, chain.full()); this._chains.push(chainView); if (recurse) { var residues = chain.residues(); for (var i = 0; i< residues.length; ++i) { chainView.addResidue(residues[i], true); } } return chainView; }
javascript
{ "resource": "" }
q46352
_residuePredicates
train
function _residuePredicates(dict) { var predicates = []; if (dict.rname !== undefined) { predicates.push(function(r) { return r.name() === dict.rname; }); } if (dict.rnames !== undefined) { predicates.push(function(r) { var n = r.name(); for (var k = 0; k < dict.rnames.length; ++k) { if (n === dict.rnames[k]) { return true; } } return false; }); } if (dict.rnums !== undefined) { var num_set = {}; for (var i = 0; i < dict.rnums.length; ++i) { num_set[dict.rnums[i]] = true; } predicates.push(function(r) { var n = r.num(); return num_set[n] === true; }); } if (dict.rnum !== undefined) { predicates.push(function(r) { return r.num() === dict.rnum; }); } if (dict.rtype !== undefined) { predicates.push(function(r) { return r.ss() === dict.rtype; }); } return predicates; }
javascript
{ "resource": "" }
q46353
_filterResidues
train
function _filterResidues(chain, dict) { var residues = chain.residues(); if (dict.rnumRange) { residues = chain.residuesInRnumRange(dict.rnumRange[0], dict.rnumRange[1]); } var selResidues = [], i, e; if (dict.rindexRange !== undefined) { for (i = dict.rindexRange[0], e = Math.min(residues.length - 1, dict.rindexRange[1]); i <= e; ++i) { selResidues.push(residues[i]); } return selResidues; } if (dict.rindices) { if (dict.rindices.length !== undefined) { selResidues = []; for (i = 0; i < dict.rindices.length; ++i) { selResidues.push(residues[dict.rindices[i]]); } return selResidues; } } return residues; }
javascript
{ "resource": "" }
q46354
dictSelect
train
function dictSelect(structure, view, dict) { var residuePredicates = _residuePredicates(dict); var atomPredicates = _atomPredicates(dict); var chainPredicates = _chainPredicates(dict); if (dict.rindex) { dict.rindices = [dict.rindex]; } for (var ci = 0; ci < structure._chains.length; ++ci) { var chain = structure._chains[ci]; if (!fulfillsPredicates(chain, chainPredicates)) { continue; } var residues = _filterResidues(chain, dict); var chainView = null; for (var ri = 0; ri < residues.length; ++ri) { if (!fulfillsPredicates(residues[ri], residuePredicates)) { continue; } if (!chainView) { chainView = view.addChain(chain, false); } var residueView = null; var atoms = residues[ri].atoms(); for (var ai = 0; ai < atoms.length; ++ai) { if (!fulfillsPredicates(atoms[ai], atomPredicates)) { continue; } if (!residueView) { residueView = chainView.addResidue(residues[ri], false); } residueView.addAtom(atoms[ai]); } } } return view; }
javascript
{ "resource": "" }
q46355
completeTask
train
function completeTask() { if (o && _.isFunction(o.callback)) { o.callback(o.fontName, o.types, o.glyphs, o.hash); } allDone(); }
javascript
{ "resource": "" }
q46356
getHash
train
function getHash() { // Source SVG files contents o.files.forEach(function(file) { md5.update(fs.readFileSync(file, 'utf8')); }); // Options md5.update(JSON.stringify(o)); // grunt-webfont version var packageJson = require('../package.json'); md5.update(packageJson.version); // Templates if (o.template) { md5.update(fs.readFileSync(o.template, 'utf8')); } if (o.htmlDemoTemplate) { md5.update(fs.readFileSync(o.htmlDemoTemplate, 'utf8')); } return md5.digest('hex'); }
javascript
{ "resource": "" }
q46357
cleanOutputDir
train
function cleanOutputDir(done) { var htmlDemoFileMask = path.join(o.destCss, o.fontBaseName + '*.{css,html}'); var files = glob.sync(htmlDemoFileMask).concat(wf.generatedFontFiles(o)); async.forEach(files, function(file, next) { fs.unlink(file, next); }, done); }
javascript
{ "resource": "" }
q46358
generateFont
train
function generateFont(done) { var engine = require('./engines/' + o.engine); engine(o, function(result) { if (result === false) { // Font was not created, exit completeTask(); return; } if (result) { o = _.extend(o, result); } done(); }); }
javascript
{ "resource": "" }
q46359
generateWoff2Font
train
function generateWoff2Font(done) { if (!has(o.types, 'woff2')) { done(); return; } // Read TTF font var ttfFontPath = wf.getFontPath(o, 'ttf'); var ttfFont = fs.readFileSync(ttfFontPath); // Remove TTF font if not needed if (!has(o.types, 'ttf')) { fs.unlinkSync(ttfFontPath); } // Convert to WOFF2 var woffFont = ttf2woff2(ttfFont); // Save var woff2FontPath = wf.getFontPath(o, 'woff2'); fs.writeFile(woff2FontPath, woffFont, function() {done();}); }
javascript
{ "resource": "" }
q46360
readCodepointsFromFile
train
function readCodepointsFromFile(){ if (!o.codepointsFile) return {}; if (!fs.existsSync(o.codepointsFile)){ logger.verbose('Codepoints file not found'); return {}; } var buffer = fs.readFileSync(o.codepointsFile); return JSON.parse(buffer.toString()); }
javascript
{ "resource": "" }
q46361
saveCodepointsToFile
train
function saveCodepointsToFile(){ if (!o.codepointsFile) return; var codepointsToString = JSON.stringify(o.codepoints, null, 4); try { fs.writeFileSync(o.codepointsFile, codepointsToString); logger.verbose('Codepoints saved to file "' + o.codepointsFile + '".'); } catch (err) { logger.error(err.message); } }
javascript
{ "resource": "" }
q46362
generateDemoHtml
train
function generateDemoHtml(done) { if (!o.htmlDemo) { done(); return; } var context = prepareHtmlTemplateContext(); // Generate HTML var demoTemplate = readTemplate(o.htmlDemoTemplate, 'demo', '.html'); var demo = renderTemplate(demoTemplate, context); mkdirp(getDemoPath(), function(err) { if (err) { logger.log(err); return; } // Save file fs.writeFileSync(getDemoFilePath(), demo); done(); }); }
javascript
{ "resource": "" }
q46363
optionToArray
train
function optionToArray(val, defVal) { if (val === undefined) { val = defVal; } if (!val) { return []; } if (typeof val !== 'string') { return val; } return val.split(',').map(_.trim); }
javascript
{ "resource": "" }
q46364
normalizePath
train
function normalizePath(filepath) { if (!filepath.length) return filepath; // Make all slashes forward filepath = filepath.replace(/\\/g, '/'); // Make sure path ends with a slash if (!_s.endsWith(filepath, '/')) { filepath += '/'; } return filepath; }
javascript
{ "resource": "" }
q46365
readTemplate
train
function readTemplate(template, syntax, ext, optional) { var filename = template ? path.resolve(template.replace(path.extname(template), ext)) : path.join(__dirname, 'templates/' + syntax + ext) ; if (fs.existsSync(filename)) { return { filename: filename, template: fs.readFileSync(filename, 'utf8') }; } else if (!optional) { return grunt.fail.fatal('Cannot find template at path: ' + filename); } }
javascript
{ "resource": "" }
q46366
renderTemplate
train
function renderTemplate(template, context) { try { var func = _.template(template.template); return func(context); } catch (e) { grunt.fail.fatal('Error while rendering template ' + template.filename + ': ' + e.message); } }
javascript
{ "resource": "" }
q46367
getCssFilePath
train
function getCssFilePath(stylesheet) { var cssFilePrefix = option(wf.cssFilePrefixes, stylesheet); return path.join(option(o.destCssPaths, stylesheet), cssFilePrefix + o.fontBaseName + '.' + stylesheet); }
javascript
{ "resource": "" }
q46368
getDemoFilePath
train
function getDemoFilePath() { if (!o.htmlDemo) return null; var name = o.htmlDemoFilename || o.fontBaseName; return path.join(o.destHtml, name + '.html'); }
javascript
{ "resource": "" }
q46369
saveHash
train
function saveHash(name, target, hash) { var filepath = getHashPath(name, target); mkdirp.sync(path.dirname(filepath)); fs.writeFileSync(filepath, hash); }
javascript
{ "resource": "" }
q46370
_callAllFns
train
function _callAllFns(objWithFns, payload) { for (var id in objWithFns) { if (objWithFns.hasOwnProperty(id) && isFunction(objWithFns[id])) { objWithFns[id](payload); } } }
javascript
{ "resource": "" }
q46371
luigiClientInit
train
function luigiClientInit() { /** * Save context data every time navigation to a different node happens * @private */ function setContext(rawData) { for (var index = 0; index < defaultContextKeys.length; index++) { var key = defaultContextKeys[index]; try { if (typeof rawData[key] === 'string') { rawData[key] = JSON.parse(rawData[key]); } } catch (e) { console.info( 'unable to parse luigi context data for', key, rawData[key], e ); } } currentContext = rawData; } function setAuthData(eventPayload) { if (eventPayload) { authData = eventPayload; } } window.addEventListener('message', function messageListener(e) { if ('luigi.init' === e.data.msg) { setContext(e.data); setAuthData(e.data.authData); luigiInitialized = true; _callAllFns(_onInitFns, currentContext.context); } else if ('luigi.navigate' === e.data.msg) { setContext(e.data); if (!currentContext.internal.isNavigateBack) { window.location.replace(e.data.viewUrl); } // execute the context change listener if set by the microfrontend _callAllFns(_onContextUpdatedFns, currentContext.context); window.parent.postMessage( { msg: 'luigi.navigate.ok' }, '*' ); } else if ('luigi.auth.tokenIssued' === e.data.msg) { setAuthData(e.data.authData); } if ('luigi.navigation.pathExists.answer' === e.data.msg) { var data = e.data.data; pathExistsPromises[data.correlationId].resolveFn(data.pathExists); delete pathExistsPromises[data.correlationId]; } if ('luigi.ux.confirmationModal.hide' === e.data.msg) { const data = e.data.data; const promise = promises.confirmationModal; if (promise) { data.confirmed ? promise.resolveFn() : promise.rejectFn(); delete promises.confirmationModal; } } if ('luigi.ux.alert.hide' === e.data.msg) { const { id } = e.data; if (id && promises.alerts[id]) { promises.alerts[id].resolveFn(id); delete promises.alerts[id]; } } }); window.parent.postMessage( { msg: 'luigi.get-context' }, '*' ); }
javascript
{ "resource": "" }
q46372
setContext
train
function setContext(rawData) { for (var index = 0; index < defaultContextKeys.length; index++) { var key = defaultContextKeys[index]; try { if (typeof rawData[key] === 'string') { rawData[key] = JSON.parse(rawData[key]); } } catch (e) { console.info( 'unable to parse luigi context data for', key, rawData[key], e ); } } currentContext = rawData; }
javascript
{ "resource": "" }
q46373
addInitListener
train
function addInitListener(initFn) { var id = _getRandomId(); _onInitFns[id] = initFn; if (luigiInitialized && isFunction(initFn)) { initFn(currentContext.context); } return id; }
javascript
{ "resource": "" }
q46374
addContextUpdateListener
train
function addContextUpdateListener( contextUpdatedFn ) { var id = _getRandomId(); _onContextUpdatedFns[id] = contextUpdatedFn; if (luigiInitialized && isFunction(contextUpdatedFn)) { contextUpdatedFn(currentContext.context); } return id; }
javascript
{ "resource": "" }
q46375
fromClosestContext
train
function fromClosestContext() { var hasParentNavigationContext = currentContext.context.parentNavigationContexts.length > 0; if (hasParentNavigationContext) { options.fromContext = null; options.fromClosestContext = true; } else { console.error( 'Navigation not possible, no parent navigationContext found.' ); } return this; }
javascript
{ "resource": "" }
q46376
uxManager
train
function uxManager() { return { /** @lends uxManager */ /** * Adds a backdrop with a loading indicator for the micro front-end frame. This overrides the {@link navigation-configuration.md#nodes loadingIndicator.enabled} setting. */ showLoadingIndicator: function showLoadingIndicator() { window.parent.postMessage( { msg: 'luigi.show-loading-indicator' }, '*' ); }, /** * Removes the loading indicator. Use it after calling {@link #showLoadingIndicator showLoadingIndicator()} or to hide the indicator when you use the {@link navigation-configuration.md#nodes loadingIndicator.hideAutomatically: false} node configuration. */ hideLoadingIndicator: function hideLoadingIndicator() { window.parent.postMessage( { msg: 'luigi.hide-loading-indicator' }, '*' ); }, /** * Adds a backdrop to block the top and side navigation. It is based on the Fundamental UI Modal, which you can use in your micro front-end to achieve the same behavior. */ addBackdrop: function addBackdrop() { window.parent.postMessage( { msg: 'luigi.add-backdrop' }, '*' ); }, /** * Removes the backdrop. */ removeBackdrop: function removeBackdrop() { window.parent.postMessage( { msg: 'luigi.remove-backdrop' }, '*' ); }, /** * This method informs the main application that there are unsaved changes in the current view in the iframe. For example, that can be a view with form fields which were edited but not submitted. * @param {boolean} isDirty indicates if there are any unsaved changes on the current page or in the component */ setDirtyStatus: function setDirtyStatus(isDirty) { window.parent.postMessage( { msg: 'luigi.set-page-dirty', dirty: isDirty }, '*' ); }, /** * Shows a confirmation modal. * @param {Object} [settings] the settings the confirmation modal. If no value is provided for any of the fields, a default value is set for it * @param {string} [settings.header="Confirmation"] the content of the modal header * @param {string} [settings.body="Are you sure you want to do this?"] the content of the modal body * @param {string} [settings.buttonConfirm="Yes"] the label for the modal confirm button * @param {string} [settings.buttonDismiss="No"] the label for the modal dismiss button * @returns {promise} which is resolved when accepting the confirmation modal and rejected when dismissing it */ showConfirmationModal: function showConfirmationModal(settings) { window.parent.postMessage( { msg: 'luigi.ux.confirmationModal.show', data: { settings } }, '*' ); promises.confirmationModal = {}; promises.confirmationModal.promise = new Promise((resolve, reject) => { promises.confirmationModal.resolveFn = resolve; promises.confirmationModal.rejectFn = reject; }); return promises.confirmationModal.promise; }, /** * Shows an alert. * @param {Object} settings the settings for the alert * @param {string} settings.text the content of the alert. To add a link to the content, you have to set up the link in the `links` object. The key(s) in the `links` object must be used in the text to reference the links, wrapped in curly brackets with no spaces. If you don't specify any text, the alert is not displayed * @param {('info'|'success'|'warning'|'error')} [settings.type] sets the type of the alert * @param {Object} [settings.links] provides links data * @param {Object} settings.links.LINK_KEY object containing the data for a particular link. To properly render the link in the alert message refer to the description of the **settings.text** parameter * @param {string} settings.links.LINK_KEY.text text which replaces the link identifier in the alert content * @param {string} settings.links.LINK_KEY.url url to navigate when you click the link. Currently, only internal links are supported in the form of relative or absolute paths. * @param {number} settings.closeAfter (optional) time in milliseconds that tells Luigi when to close the Alert automatically. If not provided, the Alert will stay on until closed manually. It has to be greater than `100`. * @returns {promise} which is resolved when the alert is dismissed. * @example * import LuigiClient from '@kyma-project/luigi-client'; * const settings = { * text: Ut enim ad minim veniam, {goToHome} quis nostrud exercitation ullamco {relativePath} laboris nisi ut aliquip ex ea commodo consequat. * Duis aute irure dolor {goToOtherProject}, * type: 'info', * links: { * goToHome: { text: 'homepage', url: '/overview' }, * goToOtherProject: { text: 'other project', url: '/projects/pr2' }, * relativePath: { text: 'relative hide side nav', url: 'hideSideNav' } * }, * closeAfter: 3000 * } * LuigiClient * .uxManager() * .showAlert(settings) * .then(() => { * // Logic to execute when the alert is dismissed * }); */ showAlert: function showAlert(settings) { //generate random ID settings.id = crypto.randomBytes(4).toString('hex'); if (settings.closeAfter && settings.closeAfter < 100) { console.warn( `Message with id='${ settings.id }' has too small 'closeAfter' value. It needs to be at least 100ms.` ); settings.closeAfter = undefined; } window.parent.postMessage( { msg: 'luigi.ux.alert.show', data: { settings } }, '*' ); promises.alerts[settings.id] = {}; promises.alerts[settings.id].promise = new Promise(resolve => { promises.alerts[settings.id].resolveFn = resolve; }); return promises.alerts[settings.id].promise; } }; }
javascript
{ "resource": "" }
q46377
showConfirmationModal
train
function showConfirmationModal(settings) { window.parent.postMessage( { msg: 'luigi.ux.confirmationModal.show', data: { settings } }, '*' ); promises.confirmationModal = {}; promises.confirmationModal.promise = new Promise((resolve, reject) => { promises.confirmationModal.resolveFn = resolve; promises.confirmationModal.rejectFn = reject; }); return promises.confirmationModal.promise; }
javascript
{ "resource": "" }
q46378
train
function(startOptions) { if (!this._isCoverageEnabled()) { return; } attachMiddleware.serverMiddleware(startOptions.app, { configPath: this.project.configPath(), root: this.project.root, fileLookup: fileLookup }); }
javascript
{ "resource": "" }
q46379
train
function() { const dir = path.join(this.project.root, 'app'); let prefix = this.parent.isEmberCLIAddon() ? 'dummy' : this.parent.name(); return this._getIncludesForDir(dir, prefix); }
javascript
{ "resource": "" }
q46380
train
function() { let addon = this._findCoveredAddon(); if (addon) { const addonDir = path.join(this.project.root, 'addon'); const addonTestSupportDir = path.join(this.project.root, 'addon-test-support'); return concat( this._getIncludesForDir(addonDir, addon.name), this._getIncludesForDir(addonTestSupportDir, `${addon.name}/test-support`) ); } }
javascript
{ "resource": "" }
q46381
train
function(dir, prefix) { if (fs.existsSync(dir)) { let dirname = path.relative(this.project.root, dir); let globs = this.parentRegistry.extensionsForType('js').map((extension) => `**/*.${extension}`); return walkSync(dir, { directories: false, globs }).map(file => { let module = prefix + '/' + file.replace(EXT_RE, '.js'); this.fileLookup[module] = path.join(dirname, file); return module; }); } else { return []; } }
javascript
{ "resource": "" }
q46382
train
function() { var value = process.env[this._getConfig().coverageEnvVar] || false; if (value.toLowerCase) { value = value.toLowerCase(); } return ['true', true].indexOf(value) !== -1; }
javascript
{ "resource": "" }
q46383
config
train
function config(configPath) { var configDirName = path.dirname(configPath); var configFile = path.resolve(path.join(configDirName, 'coverage.js')); var defaultConfig = getDefaultConfig(); if (fs.existsSync(configFile)) { var projectConfig = require(configFile); return extend({}, defaultConfig, projectConfig); } return defaultConfig; }
javascript
{ "resource": "" }
q46384
resolveReferences
train
function resolveReferences() { var elementsById = context.elementsById; var references = context.references; var i, r; for (i = 0; (r = references[i]); i++) { var element = r.element; var reference = elementsById[r.id]; var property = getModdleDescriptor(element).propertiesByName[r.property]; if (!reference) { context.addWarning({ message: 'unresolved reference <' + r.id + '>', element: r.element, property: r.property, value: r.id }); } if (property.isMany) { var collection = element.get(property.name), idx = collection.indexOf(r); // we replace an existing place holder (idx != -1) or // append to the collection instead if (idx === -1) { idx = collection.length; } if (!reference) { // remove unresolvable reference collection.splice(idx, 1); } else { // add or update reference in collection collection[idx] = reference; } } else { element.set(property.name, reference); } } }
javascript
{ "resource": "" }
q46385
train
function() { if (common.isUndefined(SAVE_DIALOGUE)) { SAVE_DIALOGUE = new CenteredDiv(); SAVE_DIALOGUE.domElement.innerHTML = saveDialogueContents; } if (this.parent) { throw new Error("You can only call remember on a top level GUI."); } var _this = this; common.each(Array.prototype.slice.call(arguments), function(object) { if (_this.__rememberedObjects.length == 0) { addSaveMenu(_this); } if (_this.__rememberedObjects.indexOf(object) == -1) { _this.__rememberedObjects.push(object); } }); if (this.autoPlace) { // Set save row width setWidth(this, this.width); } }
javascript
{ "resource": "" }
q46386
addRow
train
function addRow(gui, dom, liBefore) { var li = document.createElement('li'); if (dom) li.appendChild(dom); if (liBefore) { gui.__ul.insertBefore(li, params.before); } else { gui.__ul.appendChild(li); } gui.onResize(); return li; }
javascript
{ "resource": "" }
q46387
update
train
function update (from, to, amount, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.new', params: { from, to, amount } }) return { handler: handlers.awaitingOffChainTx, state: { resolve, reject, sign } } } ) }) }
javascript
{ "resource": "" }
q46388
shutdown
train
function shutdown (sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.shutdown', params: {} }) return { handler: handlers.awaitingShutdownTx, state: { sign, resolve, reject } } } ) }) }
javascript
{ "resource": "" }
q46389
withdraw
train
function withdraw (amount, sign, { onOnChainTx, onOwnWithdrawLocked, onWithdrawLocked } = {}) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.withdraw', params: { amount } }) return { handler: handlers.awaitingWithdrawTx, state: { sign, resolve, reject, onOnChainTx, onOwnWithdrawLocked, onWithdrawLocked } } } ) }) }
javascript
{ "resource": "" }
q46390
deposit
train
function deposit (amount, sign, { onOnChainTx, onOwnDepositLocked, onDepositLocked } = {}) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.deposit', params: { amount } }) return { handler: handlers.awaitingDepositTx, state: { sign, resolve, reject, onOnChainTx, onOwnDepositLocked, onDepositLocked } } } ) }) }
javascript
{ "resource": "" }
q46391
createContract
train
function createContract ({ code, callData, deposit, vmVersion, abiVersion }, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.new_contract', params: { code, call_data: callData, deposit, vm_version: vmVersion, abi_version: abiVersion } }) return { handler: handlers.awaitingNewContractTx, state: { sign, resolve, reject } } } ) }) }
javascript
{ "resource": "" }
q46392
callContract
train
function callContract ({ amount, callData, contract, abiVersion }, sign) { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.update.call_contract', params: { amount, call_data: callData, contract, abi_version: abiVersion } }) return { handler: handlers.awaitingCallContractUpdateTx, state: { resolve, reject, sign } } } ) }) }
javascript
{ "resource": "" }
q46393
callContractStatic
train
async function callContractStatic ({ amount, callData, contract, abiVersion }) { return snakeToPascalObjKeys(await call(this, 'channels.dry_run.call_contract', { amount, call_data: callData, contract, abi_version: abiVersion })) }
javascript
{ "resource": "" }
q46394
getContractCall
train
async function getContractCall ({ caller, contract, round }) { return snakeToPascalObjKeys(await call(this, 'channels.get.contract_call', { caller, contract, round })) }
javascript
{ "resource": "" }
q46395
getContractState
train
async function getContractState (contract) { const result = await call(this, 'channels.get.contract', { pubkey: contract }) return snakeToPascalObjKeys({ ...result, contract: snakeToPascalObjKeys(result.contract) }) }
javascript
{ "resource": "" }
q46396
cleanContractCalls
train
function cleanContractCalls () { return new Promise((resolve, reject) => { enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.clean_contract_calls', params: {} }) return { handler: handlers.awaitingCallsPruned, state: { resolve, reject } } } ) }) }
javascript
{ "resource": "" }
q46397
sendMessage
train
function sendMessage (message, recipient) { let info = message if (typeof message === 'object') { info = JSON.stringify(message) } enqueueAction( this, (channel, state) => state.handler === handlers.channelOpen, (channel, state) => { send(channel, { jsonrpc: '2.0', method: 'channels.message', params: { info, to: recipient } }) return state } ) }
javascript
{ "resource": "" }
q46398
expandPath
train
function expandPath (path, replacements) { return R.toPairs(replacements).reduce((path, [key, value]) => path.replace(`{${key}}`, value), path) }
javascript
{ "resource": "" }
q46399
conform
train
function conform (value, spec, types) { return (conformTypes[conformDispatch(spec)] || (() => { throw Object.assign(Error('Unsupported type'), { spec }) }))(value, spec, types) }
javascript
{ "resource": "" }