query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
Calls the willTransitionTo hook of all handlers in the given matches serially with the transition object and any params that apply to that handler. Calls callback(error) when finished. | function runTransitionToHooks(matches, transition, query, callback) {
var hooks = matches.map(function (match) {
return function () {
var handler = match.route.props.handler;
if (!transition.isAborted && handler.willTransitionTo)
handler.willTransitionTo(transition, match.params, query);
var promise = transition.promise;
delete transition.promise;
return promise;
};
});
runHooks(hooks, callback);
} | [
"function runTransitionFromHooks(matches, transition, callback) {\n\t var hooks = reversedArray(matches).map(function (match) {\n\t return function () {\n\t var handler = match.route.props.handler;\n\n\t if (!transition.isAborted && handler.willTransitionFrom)\n\t return handler.willTransitionFrom(transition, match.component);\n\n\t var promise = transition.promise;\n\t delete transition.promise;\n\n\t return promise;\n\t };\n\t });\n\n\t runHooks(hooks, callback);\n\t}",
"function setupStepTransitionListeners() {\n\t\t// TODO (mattflaschen, 2014-03-17): Temporary hack, until\n\t\t// there are tour-level transition listeners.\n\t\t// Will also change as mediawiki.libs.guiders module is refactored.\n\t\t/**\n\t\t * Checks for a transition after a minimal timeout\n\t\t *\n\t\t * @param {mw.guidedTour.TransitionEvent} transitionEvent event that triggered\n\t\t * the check\n\t\t */\n\t\tfunction transition( transitionEvent ) {\n\t\t\t// I found this timeout necessary when testing, probably to give the\n\t\t\t// browser queue a chance to do pending DOM rendering.\n\t\t\tsetTimeout( function () {\n\t\t\t\tvar currentStepInfo, currentStep, nextStep, tour;\n\n\t\t\t\tif ( guiders._currentGuiderID === null ) {\n\t\t\t\t\t// Ignore transitions if there is no active tour.\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tcurrentStepInfo = gt.parseTourId( guiders._currentGuiderID );\n\t\t\t\tif ( currentStepInfo === null ) {\n\t\t\t\t\tmw.log.warn( 'Invalid _currentGuiderID. Returning early' );\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\ttour = internal.definedTours[ currentStepInfo.name ];\n\t\t\t\tcurrentStep = tour.getStep( currentStepInfo.step );\n\t\t\t\tnextStep = currentStep.checkTransition( transitionEvent );\n\t\t\t\tif ( nextStep !== currentStep && nextStep !== null ) {\n\t\t\t\t\ttour.showStep( nextStep );\n\t\t\t\t}\n\n\t\t\t}, 0 );\n\t\t}\n\n\t\t// The next two are handled differently since they also require\n\t\t// settings an internal boolean.\n\t\t// TODO (mattflaschen, 2014-04-01): Hack pending tour-level listeners.\n\t\tmw.hook( 'postEdit' ).add( function () {\n\t\t\tvar transitionEvent = new gt.TransitionEvent();\n\t\t\ttransitionEvent.type = gt.TransitionEvent.MW_HOOK;\n\t\t\ttransitionEvent.hookName = 'postEdit';\n\t\t\ttransitionEvent.hookArguments = [];\n\n\t\t\tisPostEdit = true;\n\t\t\ttransition( transitionEvent );\n\t\t} );\n\t}",
"function runHooks(hooks, callback) {\n\t try {\n\t var promise = hooks.reduce(function (promise, hook) {\n\t // The first hook to use transition.wait makes the rest\n\t // of the transition async from that point forward.\n\t return promise ? promise.then(hook) : hook();\n\t }, null);\n\t } catch (error) {\n\t return callback(error); // Sync error.\n\t }\n\n\t if (promise) {\n\t // Use setTimeout to break the promise chain.\n\t promise.then(function () {\n\t setTimeout(callback);\n\t }, function (error) {\n\t setTimeout(function () {\n\t callback(error);\n\t });\n\t });\n\t } else {\n\t callback();\n\t }\n\t}",
"callAllCallbacks() {\n this.callbackSets.forEach((set) => {\n this.callCallbackSet(set);\n });\n }",
"listenToMatchingAction (matcher, handler, deferExecution) {\n this._actionListeners.push({matcher, handler, deferExecution});\n }",
"async function __handleFlowExecuteActions (flow, recUser, message) {\n\n\t// Execute all the actions in the order they are specified, and stop here if one of the actions redirects us.\n\tconst actions = flow.definition.actions;\n\tconst continueWithFlow = await this.executeActions(`flow`, flow.uri, actions, recUser, message);\n\n\tif (!continueWithFlow) {\n\t\tthrow new Error(`STOP_SUCCESSFULLY_COMPLETED`);\n\t}\n\n}",
"function multipleCallbacks (myObject, callback1, callback2){\n var myObject = {status: ['success', 'error']};\n var keyValue = Object.values(myObject.status);\n for (let i=0; i<keyValue.length; i++){\n if (keyValue[i] === 'success'){\n return callback1;\n } else return callback2;\n}\n}",
"switchNodes(searchFnNode, searchFnCur, e) {\n let node = this.getActiveNode();\n let inclusive = false;\n if (!node) {\n node = searchFnCur(this.cm.getCursor());\n if (!node) {\n // In the context of UP and DOWN key, this might mean the cursor is at the\n // top of bottom already, so we should do nothing\n return false;\n }\n inclusive = true;\n }\n const result = this.ast.getNextMatchingNode(\n searchFnNode, this.isNodeHidden, node, inclusive\n );\n if (result === null) {\n playSound(BEEP);\n return false;\n }\n this.activateNode(result, e);\n return true;\n }",
"function callbackTriggerTests(context) {\n it('should execute the provided callback when the keys that are entered match the key combination', function () {\n var e = $.Event(context.type, { keyCode: context.keyCode, ctrlKey: context.ctrlKey, shiftKey: context.shiftKey, altKey: context.altKey});\n context.element.trigger(e);\n expect(context.callback).toHaveBeenCalled();\n });\n it('should execute the provided callback when the keys that are entered match the key combination with a different dom implementation', function () {\n var e = $.Event(context.type, { which: context.keyCode, ctrlKey: context.ctrlKey, shiftKey: context.shiftKey, altKey: context.altKey});\n context.element.trigger(e);\n expect(context.callback).toHaveBeenCalled();\n });\n it('should not execute the provided callback when the keys that are entered match the key combination with an unknown dom implementation', function () {\n var e = $.Event(context.type, { unexpectedobject: context.keyCode, ctrlKey: context.ctrlKey, shiftKey: context.shiftKey, altKey: context.altKey});\n context.element.trigger(e);\n expect(context.callback).not.toHaveBeenCalled();\n });\n it('should not execute the provided callback when the keys that are entered do not match the key combination', function () {\n var e = $.Event(context.type, { keyCode: context.keyCode + 1, ctrlKey: context.ctrlKey, shiftKey: context.shiftKey, altKey: context.altKey});\n context.element.trigger(e);\n expect(context.callback).not.toHaveBeenCalled();\n });\n }",
"function chainTransition(e, e2, transitionClass) {\n\t\tvar transitionEnd = getTransitionEndPrefix(e);\n\n\t\te.addEventListener(transitionEnd, function() {\n\t\t\te2.classList.add(transitionClass);\n\n\t\t\tif(!inViewport(box[11])) {\n\t\t\t\te2.classList.remove(transitionClass);\n\t\t\t}\n\n\t\t});\n\t}",
"supportsTransition(panorama) {\n return false;\n }",
"function Transition() {}",
"transitionToState(oldStates, newState) {\n var _a, _b;\n if (oldStates.indexOf(this.connectivityState) === -1) {\n return false;\n }\n this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] +\n ' -> ' +\n connectivity_state_1.ConnectivityState[newState]);\n if (this.channelzEnabled) {\n this.channelzTrace.addTrace('CT_INFO', connectivity_state_1.ConnectivityState[this.connectivityState] +\n ' -> ' +\n connectivity_state_1.ConnectivityState[newState]);\n }\n const previousState = this.connectivityState;\n this.connectivityState = newState;\n switch (newState) {\n case connectivity_state_1.ConnectivityState.READY:\n this.stopBackoff();\n break;\n case connectivity_state_1.ConnectivityState.CONNECTING:\n this.startBackoff();\n this.startConnectingInternal();\n this.continueConnecting = false;\n break;\n case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE:\n if (this.channelzEnabled && this.transport) {\n this.childrenTracker.unrefChild(this.transport.getChannelzRef());\n }\n (_a = this.transport) === null || _a === void 0 ? void 0 : _a.shutdown();\n this.transport = null;\n /* If the backoff timer has already ended by the time we get to the\n * TRANSIENT_FAILURE state, we want to immediately transition out of\n * TRANSIENT_FAILURE as though the backoff timer is ending right now */\n if (!this.backoffTimeout.isRunning()) {\n process.nextTick(() => {\n this.handleBackoffTimer();\n });\n }\n break;\n case connectivity_state_1.ConnectivityState.IDLE:\n if (this.channelzEnabled && this.transport) {\n this.childrenTracker.unrefChild(this.transport.getChannelzRef());\n }\n (_b = this.transport) === null || _b === void 0 ? void 0 : _b.shutdown();\n this.transport = null;\n break;\n default:\n throw new Error(`Invalid state: unknown ConnectivityState ${newState}`);\n }\n for (const listener of this.stateListeners) {\n listener(this, previousState, newState, this.keepaliveTime);\n }\n return true;\n }",
"function parseTransition(gl, transitionJSON) {\n checkParameter(\"parseTransition\", gl, \"gl\");\n checkParameter(\"parseTransition\", transitionJSON, \"transitionJSON\");\n for (item in transitionJSON) {\n var value = transitionJSON[item];\n if (item === \"width\") {\n gl.canvas.width = value;\n gl.viewport(0, 0, value, gl.canvas.height);\n } else if (item === \"height\") {\n gl.canvas.height = value;\n gl.viewport(0, 0, gl.canvas.width, value);\n } else if (item === \"program\") {\n parseProgram(gl, value);\n } else if (item === \"uniform\") {\n parseUniforms(gl, value);\n } else if (item === \"buffer\") {\n parseBuffer(gl, value);\n } else if (item === \"vertex\") {\n parseVertex(gl, value);\n } else if (item === \"texture\") {\n parseTexture(gl, value);\n }\n }\n}",
"listenToAction(action, handler, deferExecution) {\n this.listenTo('action', action, handler, deferExecution);\n }",
"onTimeout(){\n\t\tthis.callback.apply(null, this.args)\n\t\tthis.continue()\n\t}",
"processMoveToStepResult(moveToStepResult, successfullyMovedCallback)\n\t\t{\n\t\t\tif (moveToStepResult === true)\n\t\t\t{\n\t\t\t\tsuccessfullyMovedCallback();\n\t\t\t}\n\n\t\t\tif (moveToStepResult && typeof moveToStepResult.then === 'function')\n\t\t\t{\n\t\t\t\tthis.isLoading = true;\n\n\t\t\t\tmoveToStepResult.then((result = {}) => {\n\t\t\t\t\tconst { finish = false, next = true } = result;\n\t\t\t\t\tthis.isLoading = false;\n\n\t\t\t\t\tif (finish)\n\t\t\t\t\t{\n\t\t\t\t\t\tthis.onFinish();\n\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!next)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tsuccessfullyMovedCallback();\n\t\t\t\t}).catch((e) => {\n\t\t\t\t\tconsole.error(e);\n\t\t\t\t\tthis.isLoading = false;\n\t\t\t\t\tthis.onFinish();\n\t\t\t\t});\n\t\t\t}\n\t\t}",
"transition(targetPosition, targetRotation) {\r\n this.transitionInfo = {\r\n targetPosition,\r\n targetRotation\r\n };\r\n\r\n // TWEEN\r\n const duration = 800;\r\n\r\n this.positionTween = new Tween(this.camera.position).easing(Easing.Cubic.Out).to({\r\n x: targetPosition.x,\r\n y: targetPosition.y,\r\n z: targetPosition.z\r\n }, duration).start();\r\n\r\n // NOTE: there's also nlerp (for performance maybe?)\r\n // http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/\r\n const startQuaternion = new Quaternion();\r\n startQuaternion.setFromEuler(this.camera.rotation);\r\n const endQuaternion = new Quaternion();\r\n endQuaternion.setFromEuler(targetRotation);\r\n let q = new Quaternion();\r\n this.rotationTween = new Tween({t: 0}).to({t: 1}, duration).easing(Easing.Cubic.Out).on('update', ({t}) =>{\r\n Quaternion.slerp(startQuaternion, endQuaternion, q, t);\r\n this.camera.quaternion.copy(q);\r\n }).start();\r\n }",
"function callback(callback){\n callback()\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if localStorage was last time updated today or not. | function isLastUpdateToday() {
if (localStorage.getItem('catalogLastUpdate') === null) {
return false;
} else if (new Date().getDate() !== new Date(localStorage.getItem('catalogLastUpdate')).getDate()) {
return false;
}
return true;
} | [
"function time_since_last_update()\r\n{\r\n var last_update = localStorage.getItem(\"last_update\"); // Last update time\r\n last_update = last_update ? last_update : 0; // 0 if not yet stored\r\n\r\n return current_time() - last_update;\r\n}",
"function checkRecentlyWatched() {\n if (localStorage.getItem(\"recentlyWatched\") == null) {\n recentlyWatched = [];\n localStorage.setItem(\"recentlyWatched\", JSON.stringify(recentlyWatched));\n } else {\n recentlyWatched = JSON.parse(localStorage.getItem(\"recentlyWatched\"));\n }\n }",
"function saveDate() {\n let lastDate = new Date();\n localStorage.lastDate = lastDate;\n}",
"checkToken() {\n if(localStorage.getItem(\"token_time\") != null) {\n if(new Date().getTime() - new Date(localStorage.getItem(\"token_time\")).getTime() > 60000) {\n localStorage.setItem(\"token_time\", (new Date()).toString());\n console.log(\"update token\");\n this.updateToken();\n }\n } else {\n localStorage.setItem(\"token_time\", (new Date()).toString());\n this.updateToken();\n }\n }",
"function didUpdateSinceLastCheck() {\n var chromeVersion = /Chrome\\/(\\d+)\\./.exec(navigator.userAgent);\n chromeVersion = chromeVersion && chromeVersion[1];\n if (!chromeVersion || localStorage.telemetryLastVersion === chromeVersion) {\n return false;\n }\n localStorage.telemetryLastVersion = chromeVersion;\n return true;\n }",
"function is_data_stale() {\n\treturn last + max_age < Date.now();\n}",
"showRecent() {\n const lastUpdate = this.props.course.updates.last_update;\n if (!lastUpdate) { return false; }\n return moment.utc(lastUpdate.end_time).add(7, 'days').isAfter(moment());\n }",
"function getLastViewed() {\n return sessionStorage.getItem('lastviewed');\n}",
"function checkOnline(lastCheckIn){\n var online = false;\n var dLast = new Date(lastCheckIn);\n var today = new Date(); \n today.setMinutes(today.getMinutes()-2);\n\n // Check if PI reported back within 90 seconds\n if(dLast > today){\n online = true;\n }\n return online;\n}",
"function checkLastModified(url){\n\txhraux = new XMLHttpRequest();\n\txhraux.open(\"GET\",url,false);\n\txhraux.send();\n\tvar lastMod = xhraux.getResponseHeader (\"Last-Modified\");\n\txhraux.abort();\n\tlastMode = new Date(lastMod);\n\treturn lastMode;\n}",
"function getDate() {\n var listDate = localStorage.getItem('listDate');\n var date = listDate.split(\",\");\n for (let i = 0; i < date.length; i++) {\n if (date[i] === localStorage.getItem('date')) {\n dataold = date[i - 1];\n $('.sincetot').text(\"Since \" + dataold);\n }\n }\n getOld(dataold);\n }",
"deviceStatusOffline(device) {\n\t\t\tconst difference = this.getTimeDifference(device.updated_at);\n\n\t\t\treturn (difference > 60);\n\t\t}",
"function timesOutdated(times){\r\n\tif (parseInt(times[times.length - 1]) < new Date().getTime() - 120000){\r\n\t\treturn true; // times outdated\r\n\t}\r\n\treturn false; // all good, go on..\r\n}",
"function expired() {\n return (this.token && this.token.expires_at && new Date(this.token.expires_at) < new Date());\n }",
"isUpdated(metadata) {\n const newTimestamp = moment.utc(metadata.updatedTimestamp).toDate();\n\n /* Normalize these to null, if undefined or empty. */\n const newETag = metadata.etag || null;\n const entryETag = this.get('etag') || null;\n\n return (newTimestamp > this.get('updatedTimestamp') ||\n newETag !== entryETag);\n }",
"flushHistory() {\n const currDate = new Date();\n for (let i = 0; i < this.history.length; i += 1) {\n const diff = (currDate - new Date(this.history[i].date));\n if (diff / (1000 * 3600 * 24 * 365) > 1) {\n this.history.splice(i, 1);\n }\n }\n localStorage.setItem('statsHistory', JSON.stringify(this.history));\n }",
"function checkDailyAvailable(timeSinceLastDaily) {\n const minHours = 18;\n if (!timeSinceLastDaily) return true;\n if (Date.now() - timeSinceLastDaily > minHours * 1000 * 60 * 60) return true;\n\n const timeUntilNextDaily = timeSinceLastDaily + minHours * 1000 * 60 * 60 - Date.now();\n return timeUntilNextDaily;\n}",
"setUserInactiveExpiresAt() {\n const value = new Date().getTime() + INACTIVE_OFFSET;\n\n if (Authenticator.getAccessToken() !== null) {\n localStorage.setItem(USER_INACTIVE_EXPIRES_AT, value);\n }\n }",
"function checkStorage() {\n var storage = JSON.parse(localStorage.getItem(\"dayPlanner\"));\n if (storage === undefined || storage === null || storage[0].currentDay !== displayCurrentDay) {\n storage = [];\n $.each(hourArr, function (i, value) {\n var generateObj = new Object();\n generateObj.currentDay = displayCurrentDay;\n generateObj.row = i;\n generateObj.text = \"\";\n storage.push(generateObj);\n localStorage.setItem(\"dayPlanner\", JSON.stringify(storage));\n });\n };\n localStorage.setItem(\"dayPlanner\", JSON.stringify(storage));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
game object storing stores current control and tool object selected by user and include array of stamps selected by user. | function gameObject(){
this.stamps = new Array();
var currentControl= null;
var currentTool = null;
var stampcount = 0;
this.addStamp = function(stampobj){
this.stamps[stampcount] = new stamp();
this.stamps[stampcount].shape = stampobj.shape;
this.stamps[stampcount].size = stampobj.size;
this.stamps[stampcount].shade = stampobj.shade;
++stampcount;
};
this.removeStamp = function(stampId){
for(var i = 0; i<this.stamps.length; i++){
if(stampId === this.stamps[i].shape){
delete this.stamps.slice(i, i+1);
}
}
}
} | [
"function saveToolRemember(toolname) {\n //var tool = getTool();\n //Number(sizemodifier.querySelector(\"[data-selected]\").id.replace(\"size\",\"\"));\n globals.toolRemember[toolname] = {\n \"sizemodifier\" : document.getElementById(\"sizemodifier\").querySelector(\"[data-selected]\").id,\n \"sizetext\" : document.getElementById(\"sizetext\").value, \n \"patternselect\" : document.getElementById(\"patternselect\").value\n };\n console.log(`Saved tool ${toolname}: `, globals.toolRemember[toolname]);\n}",
"function controls(){\nthis.mouse = new point(0,0);\n\nthis.x = false;\nthis.z = false;\n\nthis.w = false;\nthis.a = false;\nthis.s = false;\nthis.d = false;\n\nthis.up = false;\nthis.left = false;\nthis.bot = false;\nthis.right = false;\n\nthis.j = false;\n}",
"function assignTimestamp(){\n\tif (INTERSECTED && readOnly != 1) {\n\t\tif (INTERSECTED.name.dynamic==0) {\n\t\t\talert('Timestamp should be assigned to dynamic objects');\n\t\t\treturn;\n\t\t}\n\t\tif (INTERSECTED.name.dynamicIdx==-2) {\n\t\t\talert('Timestamp should be assigned to spline control objects');\n\t\t\treturn;\n\t\t}\n\t\tif (splineIsAutoBoxed[INTERSECTED.name.dynamicSeq]==1) {\n\t\t\talert('Timestamp cannot be modified after automatic boxes generated. ClearAutoBox at first for modification.');\n\t\t\treturn;\n\t\t}\n\t\tINTERSECTED.name.timestamp = shaderMaterial.uniforms.timestamp_center.value;\n\t\t//INTERSECTED.material.opacity = timestampOpacity;\n\t\tlabels_helper[currentIdx].material.color.setHex(WIREFRAME_COLOR[2]);\n \t\tdisplayMsg('status','Assign the current object with timestamp ' + shaderMaterial.uniforms.timestamp_center.value.toString());\n\t}\n}",
"createInteractionZones() {\n this.r3a1_graphics = this.add.graphics({fillStyle: {color: 0xFFFFFF, alpha: 0.0}});\n //this.graphicsTest = this.add.graphics({fillStyle: {color: 0x4F4F4F, alpha: 1.0}});\n //TOP ZONES\n //xpos ypos x y\n this.r3a1_increaseAssets = new Phaser.Geom.Rectangle(425,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseAssets);\n\n this.r3a1_decreaseAssets = new Phaser.Geom.Rectangle(425,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseAssets);\n\n this.r3a1_increaseLiabilities = new Phaser.Geom.Rectangle(525,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseLiabilities);\n\n this.r3a1_decreaseLiabilities = new Phaser.Geom.Rectangle(525,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseLiabilities);\n\n this.r3a1_increaseStock = new Phaser.Geom.Rectangle(625,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseStock);\n\n this.r3a1_decreaseStock = new Phaser.Geom.Rectangle(625,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseStock);\n\n this.r3a1_increaseRevenue = new Phaser.Geom.Rectangle(725,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseRevenue);\n\n this.r3a1_decreaseRevenue = new Phaser.Geom.Rectangle(725,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseRevenue);\n\n this.r3a1_increaseExpenses = new Phaser.Geom.Rectangle(825,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseExpenses);\n\n this.r3a1_decreaseExpenses = new Phaser.Geom.Rectangle(825,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseExpenses);\n\n this.r3a1_increaseDividend = new Phaser.Geom.Rectangle(925,300,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_increaseDividend);\n\n this.r3a1_decreaseDividend = new Phaser.Geom.Rectangle(925,500,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_decreaseDividend);\n\n //this.r3a1_holeInteract = new Phaser.Geom.Rectangle(1300, 400, 100, 100);\n //this.r3a1_graphics.fillRectShape(this.r3a1_holeInteract);\n\n this.r3a1_exitDoor_zone = new Phaser.Geom.Rectangle(113,320,100,100);\n this.r3a1_graphics.fillRectShape(this.r3a1_exitDoor_zone);\n }",
"makeThenRenderAGObject(obj_type, obj_left, obj_top) {\n let obj_buffer;\n let obj_buffer_ID;\n switch (obj_type) {\n case 'enemy':\n obj_buffer = new AGObject(\"AGgegner\", new Vector3((obj_left / this._scale), 1, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).tag = \"ENEMY\";\n getReferenceById(obj_buffer_ID).setSpeedSkalar(0);\n break;\n case 'wall':\n obj_buffer = new AGObject(\"Structure\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).tag = \"WALL\";\n break;\n case 'portal':\n obj_buffer = new AGPortal(\"Portal\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n break;\n case 'exit':\n obj_buffer = new AGRoomExit(\"Exit\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n break;\n case 'generic':\n obj_buffer = new AGObject(\"Generic\", new Vector3((obj_left / this._scale), 1.0, (obj_top / this._scale)), new Vector3(1, 0, 0), new Vector3(1, 1, 1));\n obj_buffer_ID = getIdByReference(obj_buffer);\n getReferenceById(obj_buffer_ID).collidable = false;\n getReferenceById(obj_buffer_ID).tag = \"GENERIC\";\n }\n getReferenceById(this._AGroomID).add(obj_buffer_ID);\n this.renderAGObject(obj_buffer_ID);\n\n this.refreshObjectSelect();\n this.listItems();\n this.listConditions();\n\n return obj_buffer_ID;\n }",
"function saveDesign(){\n\n var temp = { //this is common for all modules\n A: _this.A_slider.value()\n ,B: _this.B_slider.value()\n ,C: _this.C_slider.value()\n ,D: _this.D_slider.value()\n ,E: _this.E_slider.value()\n ,gearSize: _this.currentGearSize //number 1~4\n ,gearSize_R: _this.currentGearSize_R //R gear number 1~4\n ,servoAngle: _this.currentServoAngle //1:180, 2:cont\n ,mirroring: _this.currentPairing// True/False\n ,linekedTo: 'none'\n }\n\n switch (_this.currentModule) { //module specific informaion\n case 1: //OpenClose\n temp.module = 1\n break;\n case 3: //Flapping\n temp.module = 3 // <-- this is for user to see from mysketch\n temp.F = _this.F_slider.value()\n temp.X = _this.X_slider.value()\n temp.Y = _this.Y_slider.value()\n\n temp.driveGear = _this.currentDrivingGear\n break;\n case 5: //Walking\n temp.module = 5\n temp.F = _this.F_slider.value()\n temp.G = _this.G_slider.value()\n break;\n case 7: //planet\n temp.module = 7\n break;\n default:\n } // end of switch - case\n\n _this.mySavedSketch.push(temp)\n\n if(temp.module != 0){\n _this.selectParent.forEach(function(sel){\n if(temp.module == 5) //walking cannot be linked to any\n return\n var ii = _this.mySavedSketch.length-1\n sel.option('Module '+ ii)\n });\n }\n }",
"mouseInteraction() {\n\t\tvar that = this;\n\t\t\n\t\t// Get x,y coordinates of canvas where mouse pointer is\n\t\tvar getXandY = function (e) {\n\t\t\tvar x = e.clientX - that.ctx.canvas.getBoundingClientRect().left;\n\t\t\tvar y = e.clientY - that.ctx.canvas.getBoundingClientRect().top;\n\t\t\t\n\t\t\treturn { x: x, y: y };\n\t\t}\n\t\t\n\t\t// add mouse click event listener which selects and de-selects the store icon when clicked on directly\n\t\tthat.ctx.canvas.addEventListener(\"click\", function (e) {\n\t\t\tvar canvasCoordinates = getXandY(e);\n\t\t\tvar x = canvasCoordinates.x;\n\t\t\tvar y = canvasCoordinates.y;\n\t\t\tvar iconClickedOn = false;\n\t\t\t\n\t\t\t// go through store icon array to see if mouse cursor clicked on the box of a store icon\n\t\t\tfor (var i = 0; i < that.storeIcons.length; i++) {\n\t\t\t\tvar icon = that.storeIcons[i];\n\t\t\t\tvar topLeftX = icon.xCanvas * that.widthScale;\n\t\t\t\tvar topLeftY = icon.yCanvas * that.widthScale;\n\t\t\t\tvar iconWidth = icon.iconBoxWidth * that.widthScale;\n\t\t\t\tvar iconHeight = icon.iconBoxHeight * that.widthScale;\n\t\t\t\tif ( (x >= topLeftX && x <= topLeftX + iconWidth) && (y >= topLeftY && y <= topLeftY + iconHeight) ) {\n\t\t\t\t\ticonClickedOn = true;\n\t\t\t\t\tif (icon instanceof TowerIcon) {\n\t\t\t\t\t\tif (!icon.transparent) {\n\t\t\t\t\t\t\tif (!icon.selected) {\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tthat.turnOnIcon(icon);\n\t\t\t\t\t\t\t\tthat.selectedIcon = icon.getTowerType();\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tthat.level.placeTowerType = icon.towerType;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tthat.turnOffIcon(icon);\n\t\t\t\t\t\t\t\tthat.selectedIcon = \"none\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} \n\t\t\t\t\t} else if (icon instanceof StoreButton) {\n\t\t\t\t\t\tthat.gameEngine.entities.forEach(function (entity) {\n\t\t\t\t\t\t\tif (entity instanceof Tower && entity.selected) {\n\t\t\t\t\t\t\t\tswitch(icon.buttonName) {\n\t\t\t\t\t\t\t\t\tcase \"upgrade\":\n\t\t\t\t\t\t\t\t\t\tconsole.log(\"cost to upgrade: \", entity.upgradeCost);\n\t\t\t\t\t\t\t\t\t\tentity.upgrade();\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"sell\":\n\t\t\t\t\t\t\t\t\t\tentity.sell();\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\t\t\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\t// if mouse cursor clicked outside the boundaries of the map and not on a store icon, deselect the currently selected icon\t\t\n\t\t\tvar levelMapTopLeftX = that.level.xCanvas * that.widthScale;\n\t\t\tvar levelMapTopLeftY = that.level.yCanvas * that.widthScale;\n\t\t\tvar levelMapWidth = that.level.mapWidth * that.widthScale * that.level.drawScale;\n\t\t\tvar levelMapHeight = that.level.mapHeight * that.widthScale * that.level.drawScale;\n\t\t\tif ( !iconClickedOn && \n\t\t\t\t(x < levelMapTopLeftX || x > levelMapTopLeftX + levelMapWidth) \n\t\t\t\t|| (y < levelMapTopLeftY || y > levelMapTopLeftY + levelMapHeight) ) {\n\t\t\t\tthat.selectedIcon = \"none\";\n\t\t\t}\n\t\t\t\n\t\t\t// if mouse cursor selects a store icon while another icon is selected, then de-select the previous icon\n\t\t\tfor (var i = 0; i < that.storeIcons.length; i++) {\n\t\t\t\tvar icon = that.storeIcons[i];\n\t\t\t\tif (icon.isSelected() && icon.getTowerType() !== that.selectedIcon) \n\t\t\t\t\tthat.turnOffIcon(icon);\n\t\t\t}\n\t\t\t\n\t\t\t// if an icon is currently selected then turn on terrain grid map; otherwise turn the map off\n\t\t\tif (that.selectedIcon !== \"none\") {\n\t\t\t\tthat.level.showGridMap = true;\n\t\t\t} else {\n\t\t\t\tthat.level.showGridMap = false;\n\t\t\t}\n\t\t}, false);\n\t\t\n\t\t// add mouse move event listener which detects whether mouse cursor is over an icon or not\n\t\tthat.ctx.canvas.addEventListener(\"mousemove\", function (e) {\n\t\t\tvar canvasCoordinates = getXandY(e);\n\t\t\tvar x = canvasCoordinates.x;\n\t\t\tvar y = canvasCoordinates.y;\t\t\t\n\t\t\tfor (var i = 0; i < that.storeIcons.length; i++) {\t\n\t\t\t\tvar towerIcon = that.storeIcons[i];\n\t\t\t\tvar topLeftX = towerIcon.xCanvas * that.widthScale;\n\t\t\t\tvar topLeftY = towerIcon.yCanvas * that.widthScale;\n\t\t\t\tvar iconWidth = towerIcon.iconBoxWidth * that.widthScale;\n\t\t\t\tvar iconHeight = towerIcon.iconBoxHeight * that.widthScale;\t\t\t\t\n\t\t\t\tif ( (x >= topLeftX && x <= topLeftX + iconWidth) && (y >= topLeftY && y <= topLeftY + iconHeight) ) {\n\t\t\t\t\ttowerIcon.mouseover = true;\n\t\t\t\t} else {\n\t\t\t\t\ttowerIcon.mouseover = false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// that.gameEngine.entities.forEach(function (entity) {\n\t\t\t// \tif (entity instanceof Tower) {\n\t\t\t// \t\t// tower shoots enemy in shooting bounds\n\t\t\t// \t\tlet towerX = entity.x;\n\t\t\t// \t\tlet towerY = entity.y;\n\t\t\t// \t\tlet tileLength = that.level.getTilePixelImageSize();\n\t\t\t// \t\tif ( (x >= towerX - tileLength / 2 && x <= towerX + tileLength / 2) \n\t\t\t// \t\t\t&& (y >= towerY - tileLength / 2 && y <= towerY + tileLength / 2)) {\n\t\t\t// \t\t\tconsole.log(\"here\");\n\t\t\t// \t\t}\n\t\t\t// \t}\n\t\t\t// });\t\t\n\t\t}, false);\n\t\t\n\t}",
"function editorSelectObject() {\n\tvar cursorWorldPos = screenToSpace(cursor_x, cursor_y);\n\tvar toReturn = [1e1001, undefined];\n\tvar dist;\n\tfor (var p=0; p<game_map.statics.length; p++) {\n\t\tdist = Math.sqrt(Math.pow(cursorWorldPos[0] - game_map.statics[p].x, 2) + Math.pow(cursorWorldPos[1] - game_map.statics[p].y, 2));\n\t\tif (dist < toReturn[0]) {\n\t\t\ttoReturn[0] = dist;\n\t\t\tif (dist < game_map.statics[p].r) {\n\t\t\t\ttoReturn[1] = game_map.statics[p];\n\t\t\t\tp = game_map.statics.length;\n\t\t\t}\n\t\t}\n\t}\n\n\t//dynamic objects as well\n\tfor (var p=0; p<game_map.dynamics.length; p++) {\n\t\tdist = Math.sqrt(Math.pow(cursorWorldPos[0] - game_map.dynamics[p].x, 2) + Math.pow(cursorWorldPos[1] - game_map.dynamics[p].y, 2));\n\t\tif (dist < toReturn[0]) {\n\t\t\ttoReturn[0] = dist;\n\t\t\tif (dist < game_map.dynamics[p].r) {\n\t\t\t\ttoReturn[1] = game_map.dynamics[p];\n\t\t\t\tp = game_map.dynamics.length;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn toReturn;\n}",
"get tools() { return this.m_tools; }",
"function saveSelectionsInSlot() {\n\t\t// $log.log(preDebugMsg + \"saveSelectionsInSlot\");\n\t\tvar result = {};\n\t\tresult.selections = [];\n\t\tfor(var sel = 0; sel < selections.length; sel++) {\n\t\t\tresult.selections.push({'minX':selections[sel][0], 'maxX':selections[sel][1]});\n\t\t}\n\n\t\tinternalSelectionsInternallySetTo = result;\n\t\t$scope.set('InternalSelections', result);\n\t}",
"function saveGame(objButton){\n var fired_button = objButton.value;\n localStorage.setItem(\"datetime\", fired_button);\n}",
"static save_both (comp) {\n if (comp.object3D) {\n const kid = comp.object3D\n kid.isVisible = true\n const kids = kid.getChildren()\n for (let i = 0; i < kids.length; i++) {\n kids[i].setEnabled(true)\n }\n kids[kids.length - 1].isVisible = false\n\n var myser = BABYLON.SceneSerializer.SerializeMesh(comp.object3D, false, true)\n var jsonData = JSON.stringify(myser)\n\n // Component.doDownload('part.babylon', new Blob([jsonData], { type: 'octet/stream' }))\n return [new Blob([jsonData], { type: 'octet/stream' }), new Blob([jsonData], { type: 'octet/stream' })]\n }\n }",
"function store() {\n customs.push(custom); //stores custom arrays\n custom = {\n name: \"\",\n opt: [] //clears custom array to get new things\n };\n}",
"function BuildingMenuFunc (windowID : int) {\r\n \r\n var data:Database = GameObject.Find(\"Database\").GetComponent(\"Database\");\r\n \r\n // Added a scroll bar for when there are multiple buildings; need to find a way to disable the panning of the camera while scrolling\r\n scrollPosition = GUI.BeginScrollView (Rect (5,25,toolBarWidth - 25 , toolBarHeight - 50), scrollPosition, Rect (0, 0, toolBarWidth - 75, toolBarHeight + 75), false, true);\r\n \r\n for(var i =0; i<6; i++)\r\n {\r\n \tif(GUI.Button(Rect(5, 20 + (95*i), 90, 90), btnTextureArray[i]))\r\n \t{\r\n \t\tPlaceBuilding.changeBuilding = i;\r\n \t\tshowWindow = false;\r\n \t}\r\n\r\n\t\t\t//Debug.Log(\"Building: at index \" + i);\r\n\t\t\t//GUI.Label(Rect(100, 20 + (95*i), 200, 90 * i), buildingMenuStrings[i]);\r\n\t\t\t\r\n \tGUI.Label(Rect(100, 20 + (95*i), 200, 90), \tdata.buildings[i].buildingName \r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \"\\n\"\r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \"INPUT: \" + data.buildings[i].inputName\r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \" [\" + data.buildings[i].inputNum + \"]\"\r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \"\\n\"\r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \"OUTPUT: \" + data.buildings[i].outputName\r\n \t\t\t\t\t\t\t\t\t\t\t\t+ \" [\" + data.buildings[i].outputNum + \"]\");\r\n \t\t\t\t\t\t\t\t\t\t\t\r\n\r\n\t\t}\r\n\t\t\r\n\t\tGUI.EndScrollView ();\r\n}",
"function GameState (state) {\n // Storage class that is passed to all players at end of turn\n this.Players = [] ;//Ordered array of players in game\n this.Name = \"\" ;// Game name\n this.id = \"\";\n this.Started = false\n this.GameOwner = 0; //Index into players array of player that owns game\n this.CurrentPlayer = 0; //Index into players array of current player\n // History is array of TurnStates keeping a detailed history of each turn.\n // Note first TurnState is only interesting in terms of initial bag state and each\n //player's tray state\n this.History = [];\n if (state) {\n this.Players = state.Players\n this.Name = state.Name\n this.id = state.id\n this.Started = state.Started \n if (state.GameOwner) this.GameOwner = state.GameOwner;\n if (state.CurrentPlayer) this.CurrentPlayer = state.CurrentPlayer;\n if (state.History ){\n var history = []\n for(var i=0;i<state.History.length;i++){\n var bag = new Bag(true, state.History[i].Bag.letters)\n var boardState = new BoardState(state.History[i].BoardState.letters)\n var turn = null;\n if (state.History[i].Turn) {\n turn = new Turn(state.History[i].Turn.Type, state.History[i].Turn.LettersIn, state.History[i].Turn.LettersOut, \n state.History[i].Turn.TurnNumber, state.History[i].Turn.Player, state.History[i].Turn.NextPlayer)\n }\n var trayStates = [];\n for(var j=0;j<state.History[i].TrayStates.length;j++){ \n trayStates.push( new TrayState(state.History[i].TrayStates[j].player, state.History[i].TrayStates[j].letters, state.History[i].TrayStates[j].score));\n }\n history.push( new TurnState(bag, boardState, trayStates, state.History[i].End, turn))\n }\n this.History = history ;\n }\n }\n this.GetNextPlayer = function() {\n var next = this.CurrentPlayer +1;\n if (next >= this.Players.length){\n next =0;\n }\n return next;\n }\n this.GetPlayers = function(){\n return this.Players;\n }\n this.GetCurrentPlayerIndex = function(){\n return this.CurrentPlayer\n }\n this.GetNumberOfPlayers = function(){\n return this.Players.length;\n }\n this.IsPlayer = function(playerName){\n for (var i=0;i<Players.length;i++){\n if (playerName == Players[i]) return true;\n }\n return false;\n }\n this.GetBoardState = function(){\n var boardState = null;\n var lastTurn = this.GetLastTurn();\n if (lastTurn){\n boardState = lastTurn.GetBoardState();\n }\n return boardState;\n }\n this.CloneLastTurnState =function(){\n var last = this.GetLastTurnState();\n return last.Clone();\n }\n this.GetLastTurnState = function(){\n var lastTurnState = null;\n if (this.History.length >0 ) {\n lastTurnState = this.History[this.History.length-1]\n }\n return lastTurnState;\n }\n this.HasGameEnded = function(){\n var ended = false;\n var lastTurnState = this.GetLastTurnState();\n if (lastTurnState){\n ended = lastTurnState.End;\n }\n return ended;\n }\n \n this.GetLastTurn = function(){\n //Actually only gets last proper turn because there is no turn object in first turnState\n var lastTurn = null;\n if (this.History.length >=1 ) {\n lastTurn = this.History[this.History.length-1].Turn;\n }\n return lastTurn;\n }\n this.GetMyTrayState =function (playerName) {\n var trayState = null;\n if (this.History.length >=1 ) {\n var trays = this.History[this.History.length-1].GetTrayStates();\n if (trays) {\n for (var i=0;i<trays.length;i++){\n if (trays[i].GetPlayer() == playerName){\n trayState = trays[i]\n break;\n }\n }\n }\n }\n return trayState;\n }\n this.AddTurnState = function(turnState){\n this.History.push(turnState);\n }\n this.HasScores = function(){\n return (this.History.length > 0);\n }\n this.GetBagSize = function(){\n var count = 0;\n if (this.History.length >=1 )\n {\n count = this.History[this.History.length-1].GetBagSize();\n }\n return count;\n }\n this.GetPlayerScore = function (playerName){\n var lastTurnState = this.History[this.History.length-1];\n return lastTurnState.GetPlayerScore(playerName);\n }\n this.GetGameOwner = function(){\n return this.Players[ this.GameOwner];\n }\n this.RemoveLastState = function(){\n var lastTurnState = this.History.pop();\n var newLastTurn = this.GetLastTurn();\n if (newLastTurn){\n this.CurrentPlayer = newLastTurn.NextPlayer;\n }else{\n //This is same code at start game first player is first tray state\n this.SetCurrentPlayerByName(lastTurnState.GetTrayState(0).GetPlayer());\n }\n }\n this.SetCurrentPlayerByName = function(playerName){\n this.CurrentPlayer = 0\n for (var i=0;i<this.Players.length;i++){\n if (this.Players[i] == playerName){\n this.CurrentPlayer = i;\n break;\n }\n }\n }\n this.SetCurrentPlayer = function(index){\n this.CurrentPlayer = index; \n }\n this.GetCurrentPlayer = function(){\n var player = \"\";\n if (this.CurrentPlayer <= (this.Players.length -1) ){\n player = this.Players[this.CurrentPlayer];\n }\n return player\n }\n}",
"function createMissions() {\n rx = width * 0.5;\n ry = height * 0.5;\n rw = 700;\n rh = 750;\n\n //Frame, title and buttons of Mission Interface;\n push();\n missionFrame = new OnScreenFrame(\n rx,\n ry,\n rw,\n rh,\n false,\n Secondary,\n 15,\n ImageMissionInterfaceFrame\n );\n\n singleMissionsBtn = new Button(\n rx - rw / 2 + rw / 4,\n ry - rh / 2.6,\n 250,\n 50,\n \"Single Player Missions\",\n 0,\n 255,\n 15,\n 20,\n ftRetroGaming,\n Primary\n );\n\n multiMissionsBtn = new Button(\n rx + rw / 2 - rw / 4,\n ry - rh / 2.6,\n 250,\n 50,\n \"Collaborative Missions\",\n 0,\n 255,\n 15,\n 20,\n ftRetroGaming,\n Primary\n );\n\n missionExitBtn = new ExitButton(rx + rw / 2 - 42, ry - rh / 2 + 8, 30, 30);\n pop();\n\n //___________________________________________________________________\n //Mission boxes and Input;\n\n singlemission1 = new SoloMissionBox(\n rx,\n ry - rh / 4,\n rw - 50,\n rh / 7,\n singlemissionId,\n singlemissionName,\n singlemissionStory,\n singlemissionTime,\n singlemissionInputMoney,\n singlemissionInputPeople,\n singlemissionInputOre,\n singlemissionInputWater,\n singlemissionInputShips,\n singlemissionRewardMoney,\n singlemissionRewardPeople,\n singlemissionRewardOre,\n singlemissionRewardWater,\n singlemissionRank\n );\n singlemission2 = new SoloMissionBox(\n rx,\n ry - (rh / 4 - 100),\n rw - 50,\n rh / 7,\n singlemission2Id,\n singlemission2Name,\n singlemission2Story,\n singlemission2Time,\n singlemission2InputMoney,\n singlemission2InputPeople,\n singlemission2InputOre,\n singlemission2InputWater,\n singlemission2InputShips,\n singlemission2RewardMoney,\n singlemission2RewardPeople,\n singlemission2RewardOre,\n singlemission2RewardWater,\n singlemission2Rank\n );\n singlemission3 = new SoloMissionBox(\n rx,\n ry - (rh / 4 - 200),\n rw - 50,\n rh / 7,\n singlemission3Id,\n singlemission3Name,\n singlemission3Story,\n singlemission3Time,\n singlemission3InputMoney,\n singlemission3InputPeople,\n singlemission3InputOre,\n singlemission3InputWater,\n singlemission3InputShips,\n singlemission3RewardMoney,\n singlemission3RewardPeople,\n singlemission3RewardOre,\n singlemission3RewardWater,\n singlemission3Rank\n );\n singlemission4 = new SoloMissionBox(\n rx,\n ry - (rh / 4 - 300),\n rw - 50,\n rh / 7,\n singlemission4Id,\n singlemission4Name,\n singlemission4Story,\n singlemission4Time,\n singlemission4InputMoney,\n singlemission4InputPeople,\n singlemission4InputOre,\n singlemission4InputWater,\n singlemission4InputShips,\n singlemission4RewardMoney,\n singlemission4RewardPeople,\n singlemission4RewardOre,\n singlemission4RewardWater,\n singlemission4Rank\n );\n singlemission5 = new SoloMissionBox(\n rx,\n ry - (rh / 4 - 400),\n rw - 50,\n rh / 7,\n singlemission5Id,\n singlemission5Name,\n singlemission5Story,\n singlemission5Time,\n singlemission5InputMoney,\n singlemission5InputPeople,\n singlemission5InputOre,\n singlemission5InputWater,\n singlemission5InputShips,\n singlemission5RewardMoney,\n singlemission5RewardPeople,\n singlemission5RewardOre,\n singlemission5RewardWater,\n singlemission5Rank\n );\n\n singleMissionsArr = [\n singlemission1,\n singlemission2,\n singlemission3,\n singlemission4,\n singlemission5,\n ];\n\n //message to player, when missions have changed!\n if (previousMissions.length === 0) {\n } else if (previousMissions[0].missionId === singleMissionsArr[0].missionId) {\n } else if (previousMissions[0].missionId !== singleMissionsArr[0].missionId) {\n let message = { message: `Commander, a new Solo Mission is available!` };\n messages.push(message);\n soundMessageReceived.play();\n soundNewSMission.play();\n drawMessages();\n }\n\n //empty previousMissions again!\n previousMissions = [];\n\n //Disable accepted missions and assign runningMissions and openMissions with index of singleMissionsArr (this needs to stay on here, because otherwise it will create a bugg, whenver we are opening the missions interface again with a recently accepted mission --> it will not show then)\n runningSoloMissionsIndex = [];\n for (let i = 0; i < singleMissionsArr.length; i++) {\n for (let j = 0; j < runningSoloMissions.length; j++) {\n if (singleMissionsArr[i].missionId === runningSoloMissions[j]) {\n singleMissionsArr[i].acceptedMission();\n runningSoloMissionsIndex.push(i);\n }\n }\n }\n\n //assign openMissions array\n let dummyArray = [0, 1, 2, 3, 4];\n\n opensingleMissionsArr = dummyArray.filter(\n (el) => !runningSoloMissionsIndex.includes(el)\n );\n\n //print arrays\n console.log(\"open Missions Index \" + opensingleMissionsArr);\n console.log(\"runningSoloMissions Index \" + runningSoloMissionsIndex);\n console.log(\"running missions ID \" + runningSoloMissions);\n //console.log('Assigned missions '+singleMissionsArr.length);\n}",
"function givepts(target, context) {\r\n\r\n var viewer = context.username;\r\n //console.log(viewer);\r\n var pts = Math.floor((Math.random()+1 ) * 10);\r\n\r\n var i = 0;\r\n while (i <= viewerObj.length) {\r\n if (viewerObj[i] == viewer) {\r\n ptsObj[i] += pts;\r\n console.log(viewer + \" is already in array\");\r\n console.log(ptsObj[i]);\r\n break;\r\n }\r\n else if (i == viewerObj.length) {\r\n viewerObj.push(viewer);\r\n ptsObj.push(pts);\r\n coinObj.push(0);\r\n console.log(viewer + \" has been added to array\");\r\n console.log(ptsObj[i]);\r\n break;\r\n }\r\n i++;\r\n }\r\n\r\n sendMessage(target, context, context.username + ' got ' + pts + ' points. YAY!');\r\n}",
"addGame(opponent, teamPoints, opponentPoints) {\n const game = {\n opponent,\n teamPoints,\n opponentPoints\n }\n //pushes to an array\n this._games.push(game)\n }",
"saveSystemAndPlanets(sys) {\n for (let key in this.game.systems) {\n if (this.game.systems[key].img == sys.s.img) {\n this.game.systems[key] = sys.s;\n for (let j = 0; j < this.game.systems[key].planets.length; j++) {\n this.game.planets[this.game.systems[key].planets[j]] = sys.p[j];\n }\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method used to remove trailing zeros after decimal point. | removeTrailingZeros(amount) {
amount = amount.toString();
//console.log("Actual amount=>> ", amount);
let regEx1 = /^[0]+/; // remove zeros from start.
let regEx2 = /[0]+$/; // to check zeros after decimal point
let regEx3 = /[.]$/; // remove decimal point.
if (amount.indexOf(".") > -1) {
amount = amount.replace(regEx2, ""); // Remove trailing 0's
amount = amount.replace(regEx3, "");
//console.log("Remove trailings=>> ", amount);
}
return parseFloat(amount).toFixed(2);
} | [
"function removeLeadingZeros(value) {\n var i = 0;\n var lastLeadingZeroPos = -1;\n for (i = 0; i < value.length; i++) {\n if (value.charAt(i) === '0') {\n\tlastLeadingZeroPos = i;\n } else {\n\tbreak;\n }\n }\n var result = value.substring(lastLeadingZeroPos + 1);\n // Add zero before . back in\n if (result === \"\" || result.charAt(0) === '.') {\n result = '0' + result;\n }\n return result;\n }",
"function SysFmtRoundDecimal() {}",
"function formatNumber() {\n var n = 64.5;\n n.toFixed(0);\n return n;\n\n}",
"function toRep(str){\n\n str = str.toFixed(12);\n str = (str/1).toPrecision(14);\n\n while( (str[str.length-1] == '0' || str[str.length-1] == '.') && str.length > 1){\n str = str.substring(0, str.length-1);\n }\n\n\n return str;\n}",
"function getUnformattedNumber(number){\n \n // Remove anything but digits and decimal points\n \n number = number.toString().replace(/[^0-9.]/g, '');\n \n // Remove any decimal points after the first decimal point\n \n return number.substring(0, number.indexOf('.') + 1) + number.substring(number.indexOf('.') + 1).replace(/\\./g, '');\n \n}",
"function trailingZeros(mantissa){\n var zeros = 0;\n for (var i=mantissa.length-1; i>=0; i--){\n \tvar c = mantissa.charAt(i);\n if (c=='0'){\n zeros++;\n } else {\n return zeros;\n }\n }\n return zeros;\n}",
"function formatDecimal4(val, n) {\n n = n || 2;\n var str = \"\" + Math.round ( parseFloat(val) * Math.pow(10, n) );\n while (str.length <= n) {\n str = \"0\" + str;\n }\n var pt = str.length - n;\n return str.slice(0,pt) + \".\" + str.slice(pt);\n}",
"function truncate(_value)\n{\n if (_value < 0) return Math.ceil(_value)\n else return Math.floor(_value)\n}",
"function moveDecimalNF(val, left, places)\n{\n\tvar newVal = '';\n\t\n\tif (places == null) \n\t\tnewVal = this.moveDecimalAsString(val, left);\n\telse \n\t\tnewVal = this.moveDecimalAsString(val, left, places);\n\t\n\treturn parseFloat(newVal);\n}",
"function formatData(data, inc){\n \n if (Math.abs(data) < 1e-16){\n data = 0;\n }\n \n s = (Math.abs(data)).toPrecision(8).toString();\n \n var i;\n var len;\n if (s.search(\"\\\\.\") === -1){\n len = i = s.length;\n }\n else{\n for (i = s.length - 1; i >= 0; i--){\n if (s[i] != '0'){\n if (s[i] === '.'){\n }\n else{\n i++;\n }\n \n break\n }\n }\n \n len = s.length - (s.length - i - 1);\n }\n \n if (len > 10){\n return data.toExponential(5);\n }\n else{\n if (data >= 0){\n return s.substr(0, i)\n }\n else{\n return data.toPrecision(8).toString().substr(0, i + 1);\n }\n }\n}",
"function FormatNumber(srcStr, nAfterDot){\r\n\tvar srcStr,nAfterDot;\r\n\tvar resultStr,nTen;\r\n\tsrcStr = \"\"+srcStr+\"\";\r\n\tstrLen = srcStr.length;\r\n\tdotPos = srcStr.indexOf(\".\",0);\r\n\tif (dotPos == -1){\r\n\t\tresultStr = srcStr+\".\";\r\n\t\tfor (i=0;i<nAfterDot;i++){\r\n\t\t\tresultStr = resultStr+\"0\";\r\n\t\t}\r\n\t}else{\r\n\t\tif ((strLen - dotPos - 1) >= nAfterDot){\r\n\t\t\tnAfter = dotPos + nAfterDot + 1;\r\n\t\t\tnTen =1;\r\n\t\t\tfor(j=0;j<nAfterDot;j++){\r\n\t\t\t\tnTen = nTen*10;\r\n\t\t\t}\r\n\t\t\tresultStr = Math.round(parseFloat(srcStr)*nTen)/nTen;\r\n\t\t}else{\r\n\t\t\tresultStr = srcStr;\r\n\t\t\tfor (i=0;i<(nAfterDot - strLen + dotPos + 1);i++){\r\n\t\t\t\tresultStr = resultStr+\"0\";\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn resultStr;\r\n}",
"function formatDecimalOdds(odds) {\n\tlet updatedOdds = odds/1000;\n\treturn Number.parseFloat(updatedOdds).toFixed(2);\n}",
"function trimPeriods(str)\n {\n return str.replace(/^\\./, \"\").replace(/\\.$/, \"\");\n }",
"function formatDecimal3(val, n) {\n n = n || 2;\n var str = \"\" + Math.round ( parseFloat(val) * Math.pow(10, n) );\n while (str.length <= n) {\n str = \"0\" + str;\n }\n var pt = str.length - n;\n return str.slice(0,pt) + \".\" + str.slice(pt);\n}",
"function justNumberNF(val)\n{\n\tnewVal = val + '';\n\t\n\tvar isPercentage = false;\n\t\n\t// check for percentage\n\t// v1.5.0\n\tif (newVal.indexOf('%') != -1) \n\t{\n\t\tnewVal = newVal.replace(/\\%/g, '');\n\t\tisPercentage = true; // mark a flag\n\t}\n\t\t\n\t// Replace everything but digits - + ( ) e E\n\tvar re = new RegExp('[^\\\\' + this.inputDecimalValue + '\\\\d\\\\-\\\\+\\\\(\\\\)eE]', 'g');\t// v1.5.2\t\n\tnewVal = newVal.replace(re, '');\n\t// Replace the first decimal with a period and the rest with blank\n\t// The regular expression will only break if a special character\n\t// is used as the inputDecimalValue\n\t// e.g. \\ but not .\n\tvar tempRe = new RegExp('[' + this.inputDecimalValue + ']', 'g');\n\tvar treArray = tempRe.exec(newVal); // v1.5.2\n\tif (treArray != null) \n\t{\n\t var tempRight = newVal.substring(treArray.index + treArray[0].length); // v1.5.2\n\t\tnewVal = newVal.substring(0,treArray.index) + this.PERIOD + tempRight.replace(tempRe, ''); // v1.5.2\n\t}\n\t\n\t// If negative, get it in -n format\n\tif (newVal.charAt(newVal.length - 1) == this.DASH ) \n\t{\n\t\tnewVal = newVal.substring(0, newVal.length - 1);\n\t\tnewVal = '-' + newVal;\n\t}\n\telse if (newVal.charAt(0) == this.LEFT_PAREN\n\t && newVal.charAt(newVal.length - 1) == this.RIGHT_PAREN) \n\t{\n\t\tnewVal = newVal.substring(1, newVal.length - 1);\n\t\tnewVal = '-' + newVal;\n\t}\n\t\n\tnewVal = parseFloat(newVal);\n\t\n\tif (!isFinite(newVal)) \n\t\tnewVal = 0;\n\t\n\t// now that it's a number, adjust for percentage, if applicable.\n // example. if the number was formatted 24%, then move decimal left to get 0.24\n // v1.5.0 - updated v1.5.1\n if (isPercentage) \n \t\tnewVal = this.moveDecimalLeft(newVal, 2);\n\t\t\n\treturn newVal;\n}",
"function roundNumber(number,decimal_points) {\n if(!decimal_points) return Math.round(number);\n if(number == 0) {\n var decimals = \"\";\n for(var i=0;i<decimal_points;i++) decimals += \"0\";\n return \"0.\"+decimals;\n }\n\n var exponent = Math.pow(10,decimal_points);\n var num = Math.round((number * exponent)).toString();\n return num.slice(0,-1*decimal_points) + \".\" + num.slice(-1*decimal_points)\n}",
"function priceFormat6Dec(i) \n\t{\n\t\ti=noComma(i.toString());\n\t\tif(isNaN(i)) { i = 0.000000; }\n\t\tvar minus = '';\n\t\tif(i < 0) { minus = '-'; }\n\t\ti = Math.abs(i);\n\t\ti = parseInt((i + .0000005) * 1000000);\n\t\ti = i / 1000000;\n\t\ts = new String(i);\n\t\tif(s.indexOf('.') < 0) { s += '.000000'; }\n\t\tif(s.indexOf('.') == (s.length - 2)) { s += '00000'; }\n\t\tif(s.indexOf('.') == (s.length - 3)) { s += '0000'; }\n\t\tif(s.indexOf('.') == (s.length - 4)) { s += '000'; }\n\t\tif(s.indexOf('.') == (s.length - 5)) { s += '00'; }\n\t\tif(s.indexOf('.') == (s.length - 6)) { s += '0'; }\n\t\ts = minus + s;\n\t\treturn s;\n\t}",
"function currencyFormat(x) {\n return x.toString().replace(/\\B(?<!\\.\\d*)(?=(\\d{3})+(?!\\d))/g, \".\");\n}",
"function cut(value, prec){\n var precision = prec || 100000000;\n return Math.floor(value * precision) / precision;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add products to available product lists | function addProductLists(product){
productLists.push(product);
} | [
"addProducts() {\n document.querySelector('#product-list').innerHTML = '';\n document.querySelector('#update').innerHTML = '';\n Product.all.forEach(\n product => (document.querySelector('#product-list').innerHTML += product.renderProduct())\n );\n }",
"function appendProduct(product) {\n const listItem = document.createElement(\"li\");\n listItem.innerHTML = `\n <strong>ID:</strong> ${product.id}<br>\n <strong>Name:</strong> ${product.name}<br>\n <strong>Description:</strong> ${product.description}<br>\n <strong>Price:</strong> ${product.price}<br>\n <strong>Count:</strong> ${product.count}<br><br>\n `;\n productList.appendChild(listItem);\n }",
"function loadAllProductInShop() {\n Product.getProductLive({ SearchText: '' })\n .then(function (res) {\n $scope.products = res.data;\n });\n }",
"function addToMPO(product) {\n //Change state of the icon in the header\n iconMPO.classList.add('new');\n singleProducts.push(product);\n\n let input = document.querySelector(`.mijn-producten-label${product.id}`).querySelector('input');\n input.checked = true;\n input.classList.add('added');\n computeMPOProducts();\n updateCounter();\n}",
"onCustomProductAdd() {\n\t\tconst customProduct = new Product();\n\t\tthis.onProductAdd(customProduct);\n\t}",
"function refreshProductList() {\n loadProducts()\n .then(function (results) {\n vm.products = results;\n });\n }",
"function continueShopping() {\n getProducts();\n }",
"function addProduct({ name, price, qt, url }) {\n let newProduct = {\n id: lastID,\n name: name,\n price: price,\n qt: qt,\n url: url,\n };\n ref.push(newProduct);\n}",
"function selectProducts(product, addToListBtn) {\n changeState(addToListBtn)\n switch (addToListBtn.className) {\n case 'option addList active':\n product.selected = true;\n break;\n default:\n product.selected = false;\n }\n\n //Filter all the products that are selected and display a popup to the view\n let selectedProducts = Array.from(singleProducts.filter(product => product.selected === true));\n if (selectedProducts.length > 0) {\n addToListPopup.style.display = 'block';\n } else {\n addToListPopup.style.display = 'none';\n }\n updateCounter();\n}",
"AddProduct() {\n this.customerObj.products.push(this.productObj);\n this.productObj = new _CustomerApp_CustomerApp_CustomerModel__WEBPACK_IMPORTED_MODULE_0__[\"Product\"]();\n }",
"async addItem(product) {\n let exists = this.operationOnItemByProduct({product, operation: item => item.incrementCount()});\n if (!exists) {\n let items = _items.get(this);\n items.push(new Item(product));\n _items.set(this, items);\n }\n }",
"async function getProductList() {\n\n await fetch('http://52.26.193.201:3000/products/list')\n .then(response => response.json())\n .then(response => setProductList([...response]))\n }",
"function getProducts() {\n var params = getParams();\n params[\"categoryID\"] = $scope.categoryId;\n categoryApiService.getProductsByCategoryId(params).$promise.then(function(response) {\n var result = response.result || [];\n $scope.productsList = result;\n });\n }",
"function addSelectedItemToCart() {\n // TODO: suss out the item picked from the select list\n var product = document.getElementsById('items').value;\n // TODO: get the quantity\n var quantity = document.getElementById('quantity').value;\n // TODO: using those, add one item to the Cart\n cart.product = product;\n //cart.items.allProducts = product;\n //cart.product = value;\n //var numberOfProducts = cart.quantity++;\n //numberOfProducts = quantity;\n cart.quantity += quantity;\n}",
"productsDisplayEvent_productsShow(products) {\n console.log(`AmazonProductsController: ${products}`);\n $('#amazonProductFinderDisplayContainer').hide();\n $('#amazonProductsDisplayContainer').show();\n this.apd.productsDisplayEvent_showProducts(products);\n }",
"function displayProducts(products) {\n for (const product of products) {\n displayProduct(product);\n }\n}",
"function initProducts() {\n\tvar productListDiv = $('#productList');\n\n\tfor (var i = 0; i < productsPrices.length; i++) {\n\t\t// This is a div with the class 'product':\n\t\tvar productDiv = $('<div>');\n\t\tproductDiv.addClass('product');\n\n\t\t// This is the path of the image, ex:\n\t\t// \"images/Box1_$10.png\"\n\t\tvar imagePath = productsPrices[i];\n\n\t\t// This is the product name, ex:\n\t\t// \"Box1\"\n\t\tvar productName = productNameFromImagePath(imagePath);\n\n\t\t// This is the price of the product with the dollar sign, ex:\n\t\t// \"$10\"\n\t\tvar productPrice = '$' + productPriceFromImagePath(imagePath);\n\n\t\t// Preparing divs to be inserted into the product div:\n\n\t\tvar productImage = $('<img>');\n\t\tproductImage.attr('src', imagePath);\n\n\t\tvar cartDiv = $('<div>');\n\t\tcartDiv.addClass('cart');\n\t\tvar cartImage = $('<img>');\n\t\tcartImage.addClass('cartimg');\n\t\tcartImage.attr('src', 'images/cart.png');\n\t\tcartDiv.append(cartImage);\n\n\t\tvar priceDiv = $('<div>');\n\t\tpriceDiv.addClass('price')\n\t\tpriceDiv.text(productPrice);\n\n\t\t// Anonymous function is used here to store productName in its closure:\n\t\tvar addButton;\n\t\t(function() {\n\t\t\tvar _productName = productName;\n\t\t\taddButton = $('<button>');\n\t\t\taddButton.addClass('add');\n\t\t\taddButton.text('Add');\n\t\t\taddButton.click(function() {\n\t\t\t\taddToCart(_productName);\n\t\t\t});\n\t\t})();\n\n\t\t// Anonymous function is used here to store productName in its closure:\n\t\tvar removeButton;\n\t\t(function() {\n\t\t\tvar _productName = productName;\n\t\t\tremoveButton = $('<button>');\n\t\t\tremoveButton.addClass('remove');\n\t\t\tremoveButton.text('Remove');\n\t\t\tremoveButton.click(function() {\n\t\t\t\tremoveFromCart(_productName);\n\t\t\t});\n\t\t})();\n\n\t\tvar titleHeading = $('<h5>');\n\t\ttitleHeading.text(productName);\n\n\t\t// Insert all the divs and buttons created above to the product div:\n\t\tproductDiv.append(productImage);\n\t\tproductDiv.append(cartDiv);\n\t\tproductDiv.append(priceDiv);\n\t\tproductDiv.append(addButton);\n\t\tproductDiv.append(removeButton);\n\t\tproductDiv.append(titleHeading);\n\n\t\t// Insert this product div into the productList div:\n\t\tproductListDiv.append(productDiv);\n\t}\n}",
"function listProducts()\n{\n connection.query(\"SELECT * FROM products\", function(err, res)\n {\n if (err) throw err;\n console.log(\"You can select from these items\");\n for(i=0;i<res.length;i++)\n {\n console.log('Item ID ' + res[i].item_id + ' Product:' + res[i].product_name + ' Price: ' + res[i].price);\n }\n startOrder();\n })\n}",
"loadAvailableItems() {\n // Load the available items and parses the data\n var tempList = lf.getAvailableItems();\n tempList.then((value) => {\n // Get the items, their ids, and data\n var items = value.items;\n var ids = value.ids;\n var genNames = value.genNames;\n\n // Save the item information\n var temp = [];\n for (var i = 0; i < ids.length; i++) {\n temp.push({\n name: items[i],\n title: items[i],\n id: ids[i],\n genName: genNames[i]\n });\n }\n\n // Add the option to register a new item to the list\n temp.push({ name: NEW_ITEM, title: NEW_ITEM, id: -1 });\n\n availableItems = temp;\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ideate .findKey() [my solution]: testFunction added outside of _ object (above) | findKeyIdea (object, testFunction) {
let returnValue = ''
for (const key in object) {
if (testFunction(object[key])) {
returnValue = key
} else {
returnValue = undefined
}
}
return returnValue
} | [
"function keyLookup(key) {\n if (key == 'i') {\n return 73\n } else if (key == 'o') {\n return 79\n } else if (key == 'p') {\n return 80\n } else {\n return 'Error(keyLookup): No key match!'\n }\n}",
"function inputElem_add_byKey(e) {\n\t\n}",
"function findKey(record, predicate) {\n for (const a in record) {\n if (predicate(record[a]))\n return a;\n }\n return undefined;\n}",
"splitFunctionFromKey (theKey) {\n if (theKey !== null && theKey.indexOf('(') !== -1) { // Must be an aggregate or queryFunction\n let functionKeyPair = theKey.split('('); // Split function and property\n let functionAlias = functionKeyPair[0];\n let fieldName = functionKeyPair[1];\n\n let queryFunction = QueryFunctionEnum.getTypeFromAlias(functionAlias);\n\n log.log('splitFunctionFromKey queryFunction', functionAlias, queryFunction);\n\n if (queryFunction !== null) {\n this.queryFunction = queryFunction;\n this.key = fieldName.replace(')', ''); // Remove closing parenthesis from the key\n } else {\n log.error('Unrecognized function alias used by constraint - ' + functionAlias);\n }\n } else {\n log.info('In splitFunctionFromKey, set this.key = ', theKey);\n this.key = theKey;\n }\n }",
"function lookupExistingFunctionId(func) {\n var tokens = Object.keys(storedFunctionArguments);\n for (var i = 0, l = tokens.length; i < l; ++i) {\n var token = tokens[i];\n var functions = storedFunctionArguments[token];\n var functionIds = Object.keys(functions);\n for (var j = 0, k = functionIds.length; j < k; ++j) {\n var functionId = functionIds[j];\n if (functions[functionId] == func) return functionId;\n }\n }\n }",
"get(x)\n {\n let target=null\n if(x instanceof Hashable)\n {\n let i=this.evaluatePosition(x);\n if(this.#_arrayOfll[i].search(x)!=null)\n {\n target=this.#_arrayOfll[i].search(x);\n //break;\n }else\n {\n throw new Error(\"Element trying to 'get' does not exist!!\")\n }\n }\n else\n {\n throw new Error(\"'get(x):' Only takes a Hashable object as parameter\")\n }\n return target;\n }",
"findWhere(array, keyName, val) {\n return array.find((item) => {\n return item[keyName] == val;\n });\n }",
"search (arr, length, value, key, keyValue) {\n\n if (length) {\n\n /*\n * Third type of search\n */\n if (key && keyValue) {\n for (let object of arr) {\n \n if (_.get(object, [key], '') === value) {\n return _.get(object, [keyValue], 0);\n }\n\n }\n }\n /*\n * Second type of search\n */\n else if (key) {\n for (let object of arr) {\n \n if (_.get(object, [key], '') === value) {\n return object;\n }\n\n }\n }\n /*\n * First type of search\n */\n else {\n for (let i = 0; i < length; i++) {\n\n if (_.get(arr, [i], '') === value) {\n return i;\n }\n\n }\n }\n\n }\n\n return false;\n\n }",
"function filterFunction(obj, key, value){\n\tif(obj[key] === value) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}",
"function matchSearchFuncEngPlain (searchTerm) {\n return function(element) {\n if (element.definition == searchTerm) {\n return true;\n } else {\n return false;\n }\n }\n }",
"function isMethodAt(thing, key) {\n return thing && typeof thing[key] === 'function';\n}",
"kvMap( fn ){}",
"function mapKey(key) {\n if (key == 73) {\n return \"1\";\n } else if (key == 79) {\n return \"2\";\n } else if (key == 80) {\n return \"3\";\n } else {\n return 'Error(mapKey): No key match!'\n }\n}",
"function FILTER_KEY(key) {\n var string = %ToString(key);\n if (%HasProperty(this, string)) return string;\n return 0;\n}",
"checkForKey (futureLocation) {\n const isKeyType = this.board.getCell(futureLocation).getType()\n if (isKeyType === 'key') {\n this.keyGained = true\n return true\n } else {\n return false\n }\n }",
"get(key) {\n let index = this._hash(key);\n if (this.keyMap[index]) {\n for (let i = 0; i < this.keyMap[index].length; i++) {\n if (this.keyMap[index][i][0] === key) {\n return this.keyMap[index][i][1];\n }\n }\n }\n return undefined;\n }",
"add_keyup(func) {\n this.add_event(\"keyup\", func);\n }",
"function find_rule(rules, key_name, key_value) {\n\tvar matches = find_rules(rules, key_name, key_value);\n\tif (matches.length == 0) {\n\t\treturn null;\n\t} else {\n\t\treturn matches[0];\n\t}\n}",
"function partialMatchKey(a, b) {\n return partialDeepEqual(a, b);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set event handlers for autocomplete list | function setAutocompleteListHandlers(list){
// Handle clicking on an autocomplete list option
$(list).find('button').on('click', function(event){
selectAutocompleteOption(this);
});
// Handle clicking outside of time picker/field
$(document).on('mousedown', function(event){
if($(list).parent().has(event.target).length == 0){
$(list).hide();
}
});
} | [
"function setAutoComplete(arr) {\n searchInput.autocomplete({source: arr});\n}",
"function init() {\n var elementsArray = getAllElementsFromSelectos(inputAutocompleteSelector);\n //addEventsToElements(elementsArray, \"keydown\", disableChatOnPressReturn);\n\n for (var i = 0; i < elementsArray.length; i++) {\n addEvent(elementsArray[i], \"focus\", disableChat);\n addEvent(elementsArray[i], \"blur\", enableChat);\n }\n }",
"function setupClickListener(id, types) {\n var radioButton = document.getElementById(id);\n /*radioButton.addEventListener('click', function() {\n autocomplete.setTypes(types);\n });*/\n }",
"function customize_jquery_ui_autocomplete() {\n // Repalce @ to font awesome icon\n jquery_default().ui.autocomplete.prototype._renderItem = (\n $ul,\n { id, label }\n ) => {\n const $li = jquery_default()(eskape_default()`\n <li>\n <div>\n ${label} \n <i class=\"fa fa-globe\"></i>\n ${id}\n </div>\n </li>`)\n\n $ul.append($li)\n\n return $li\n }\n jquery_default().ui.autocomplete.prototype._resizeMenu = () => {\n // Prepend resize menu\n }\n } // CONCATENATED MODULE: ./src/lib/component/searchTerm.js",
"function handleAutoCompleteEntryClick(tag) {\n\t\t// Get all tag entries\n\t\tconst tags = ref.current.value.split(/\\s/);\n\t\t// Set the input text to the clicked tag name.\n\t\tref.current.value = [\n\t\t\t// Get the text content of the input, excluding the last word.\n\t\t\t...tags.slice(0, -1),\n\t\t\t// Append the tag name to the list of tags.\n\t\t\t(tags[tags.length - 1].match(/[^a-z0-9]/gi)?.[0] ?? \"\") + tag.name,\n\t\t\t// And a little spacey.\n\t\t\t\"\"\n\t\t].join(\" \");\n\n\t\t// Clear the auto complete entries.\n\t\tsetAutoCompleteEntries([]);\n\n\t\t// Wait for the next frame because JavaScript is shitting through the screen.\n\t\tsetImmediate(() => {\n\t\t\t// Set the selection index to the end of the list.\n\t\t\tref.current.selectionStart =\n\t\t\t\tref.current.selectionEnd = ref.current.value.length;\n\n\t\t\t// Focus the input field element.\n\t\t\tref.current.focus();\n\t\t});\n\t}",
"function suggestionClickListener() {\n $('li.tax-suggestion').click(function (e) {\n // Stop propagation so that this does not count as a body click (and thereby remove the list).\n //e.stopPropagation();\n $(this).parent().children().removeClass('selected');\n var value = $(this).addClass('selected').text();\n $(this).closest('.tax-wrapper').children('input.taxonomic').val(value);\n\n // Stop the suggestion function from triggering because the input changed.\n clearTimeout(sugTimeout);\n });\n }",
"registerEvents() {\n\t\t\tthis.container = this.getContainer();\n\t\t\tthis.registerListEvents();\n\t\t\tthis.registerForm();\n\t\t}",
"_listBoxChangeHandler(event) {\n const that = this;\n\n if ((that.dropDownAppendTo && that.dropDownAppendTo.length > 0) || that.enableShadowDOM) {\n that.$.fireEvent('change', event.detail);\n }\n\n that._applySelection(that.selectionMode, event.detail);\n }",
"#registerEventListeners() {\n this.#addOnFocusEventListener();\n this.#addOnHelpIconClickEventListener();\n }",
"function initDropdowns() {\n $('#question-button').on('click', dropdownHandler);\n $('#question-input').on('keyup', questionFilterFunction);\n $('#myPerson').on('keyup', peopleFilterFunction);\n}",
"onFocusAutosuggest(event) {\n event.target.select();\n }",
"onSuggestChange(event, o) {\n switch(o.method) {\n // this is necessary for the input to show each letter as its typed\n case 'type':\n this.setState({\n value: o.newValue\n });\n break;\n // one of the suggests was selected\n case 'click':\n let items = this.items;\n items.push({id: o.newValue.id, name: o.newValue.name});\n this.props.setModuleEditingPiece({items: items});\n // clear the input\n this.setState({\n value: ''\n });\n break;\n }\n }",
"function registerSearchableSelect() {\n\n}",
"function initAutocompleterTextfields()\n{\n\t$$('input.autocompleterTextfield').each(function(el){\n\t\tnew AutocompleterTextfield(el);\n\t});\n}",
"function initialAttendeeAutocomplete() {\n $('#attendeeName').autocomplete({\n source: function (request, response) {\n // Call api to get top 20 attendees\n $.ajax({\n url: '/api/attendees/top20',\n type: 'POST',\n contentType: 'application/JSON'\n })\n .done(function (data) {\n response($.map(data, function (item) {\n return item;\n }));\n })\n .fail(function () {\n // Show error\n });\n },\n select: function (event, ui) {\n event.preventDefault();\n $(this).val(ui.item.label);\n $('attendeeId').val(ui.item.value);\n // Check form\n checkAttendeeHourForm();\n }\n }); // autocomplete\n}",
"function ACListClick(e) {\r\n var ele = e.target;\r\n if(ele.tagName == \"STRONG\") ele = ele.parentNode;\r\n if(ele.tagName != \"LI\") return true;\r\n e.stopPropagation();\r\n changeSuggest();\r\n curPattern = \"\";\r\n completeFlag = 0;\r\n closeACList();\r\n }",
"function setSpecificListItemListener(listId, eventHandler){\n\t$(\"#\" + listId + \" li:not(:first)\").click(function(){\n\t\t$(\"#\" + listId + \" li\").removeClass(\"active\");\n\t\t$(this).addClass(\"active\");\n\t\teventHandler($(this),listId);\n\t});\n}",
"function init() {\n id(\"add\").addEventListener(\"click\", newList);\n }",
"setEventListeners() {\n this.on('edit',this.onEdit.bind(this));\n this.on('panelObjectAdded',this.onPanelObjectAdded.bind(this));\n this.on('panelObjectRemoved',this.onPanelObjectRemoved.bind(this));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replaces the placeholders a given format with the given parameters. | function replace(format, params) {
/*jslint unparam: true */
return format.replace(/\{([a-zA-Z]+)\}/g, function (s, key) {
return (typeof params[key] === 'undefined') ? '' : params[key];
});
} | [
"function ReplaceParams() {\n var result = arguments[0];\n for (var iArg = 1; iArg < arguments.length; iArg++) { // Start at second arg (first arg is the pattern)\n var pattern = new RegExp('%' + iArg + '\\\\w*%');\n result = result.replace(pattern, arguments[iArg]);\n }\n return result;\n}",
"function format(string, vars) {\n\tif (vars) {\n\t\tfor (var k in vars) {\n\t\t\tstring = string.replace(new RegExp('\\\\{' + k + '\\\\}', 'g'), vars[k]);\n\t\t}\n\t}\n\treturn string;\n}",
"function format(str, formats) {\n\tlet cachedFormats = formats;\n\n\tif (!Ember.isArray(cachedFormats) || arguments.length > 2) {\n\t\tcachedFormats = new Array(arguments.length - 1);\n\n\t\tfor (let i = 1, l = arguments.length; i < l; i++) {\n\t\t\tcachedFormats[i - 1] = arguments[i];\n\t\t}\n\t}\n\n\tlet idx = 0;\n\treturn str.replace(/%@([0-9]+)?/g, function(s, argIndex) {\n\t\targIndex = (argIndex) ? parseInt(argIndex, 10) - 1 : idx++;\n\t\ts = cachedFormats[argIndex];\n\t\treturn (s === null) ? '(null)' : (s === undefined) ? '' : Ember.inspect(s);\n\t});\n}",
"function fillPlaceholders(message, params) {\n return Function(...Object.keys(params), `return \\`${message}\\``)(...Object.values(params));\n}",
"function format(s) {\n var positional = undefined;\n if (arguments.length > 2) {\n positional = true;\n }\n var args = Array.apply(null, arguments).slice(1);\n var position = 0;\n\n var re = /%(\\(([\\w\\$]+)\\))?([^])?/g;\n function replacer(all, p, varname, formatchar) {\n var val;\n switch (formatchar) {\n case \"%\":\n return \"%\";\n case \"s\":\n if (varname == \"\") {\n positional = check(positional, true);\n if (args.length <= position) {\n throw Error(\"Not enough format arguments\");\n }\n val = args[position];\n position++;\n return String(val);\n }\n if (isInteger(varname)) {\n varname = Number(varname);\n positional = check(positional, true);\n if (args.length <= varname) {\n throw Error(\"Not enough arguments\");\n }\n return String(args[varname]);\n } \n positional = check(positional, false);\n if (args.length != 1) {\n throw Error(\"Named arguments require a single object.\");\n }\n return String(args[0][varname]);\n default:\n throw Error(\"Unexpected format char: \" + formatchar);\n }\n }\n return s.replace(re, replacer);\n}",
"function formatParameters() {\n if (!this.params) return '';\n return '(' + this.params.map(function (param) {\n return formatParameter(param);\n }).join(', ') + ')';\n}",
"function replacePlaceholders(quasisDoc, expressionDocs) {\n if (!expressionDocs || !expressionDocs.length) {\n return quasisDoc;\n }\n\n const expressions = expressionDocs.slice();\n let replaceCounter = 0;\n const newDoc = mapDoc$3(quasisDoc, doc => {\n if (!doc || !doc.parts || !doc.parts.length) {\n return doc;\n }\n\n let {\n parts\n } = doc;\n const atIndex = parts.indexOf(\"@\");\n const placeholderIndex = atIndex + 1;\n\n if (atIndex > -1 && typeof parts[placeholderIndex] === \"string\" && parts[placeholderIndex].startsWith(\"prettier-placeholder\")) {\n // If placeholder is split, join it\n const at = parts[atIndex];\n const placeholder = parts[placeholderIndex];\n const rest = parts.slice(placeholderIndex + 1);\n parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);\n }\n\n const atPlaceholderIndex = parts.findIndex(part => typeof part === \"string\" && part.startsWith(\"@prettier-placeholder\"));\n\n if (atPlaceholderIndex > -1) {\n const placeholder = parts[atPlaceholderIndex];\n const rest = parts.slice(atPlaceholderIndex + 1);\n const placeholderMatch = placeholder.match(/@prettier-placeholder-(.+)-id([\\s\\S]*)/);\n const placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:\n // animation: linear ${time}s ease-out;\n\n const suffix = placeholderMatch[2];\n const expression = expressions[placeholderID];\n replaceCounter++;\n parts = parts.slice(0, atPlaceholderIndex).concat([\"${\", expression, \"}\" + suffix]).concat(rest);\n }\n\n return Object.assign({}, doc, {\n parts\n });\n });\n return expressions.length === replaceCounter ? newDoc : null;\n }",
"function fill (template, data) {\n\n Object.keys(data).forEach(function (key) {\n var placeholder = \"{{\" + key + \"}}\";\n var value = data[key];\n\n while (template.indexOf(placeholder) !== -1) {\n template = template.replace(placeholder, value);\n }\n });\n\n return template;\n}",
"function replacePlaceholders(quasisDoc, expressionDocs) {\n if (!expressionDocs || !expressionDocs.length) {\n return quasisDoc;\n }\n\n const expressions = expressionDocs.slice();\n let replaceCounter = 0;\n const newDoc = mapDoc$1(quasisDoc, doc => {\n if (!doc || !doc.parts || !doc.parts.length) {\n return doc;\n }\n\n let {\n parts\n } = doc;\n const atIndex = parts.indexOf(\"@\");\n const placeholderIndex = atIndex + 1;\n\n if (atIndex > -1 && typeof parts[placeholderIndex] === \"string\" && parts[placeholderIndex].startsWith(\"prettier-placeholder\")) {\n // If placeholder is split, join it\n const at = parts[atIndex];\n const placeholder = parts[placeholderIndex];\n const rest = parts.slice(placeholderIndex + 1);\n parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);\n }\n\n const atPlaceholderIndex = parts.findIndex(part => typeof part === \"string\" && part.startsWith(\"@prettier-placeholder\"));\n\n if (atPlaceholderIndex > -1) {\n const placeholder = parts[atPlaceholderIndex];\n const rest = parts.slice(atPlaceholderIndex + 1);\n const placeholderMatch = placeholder.match(/@prettier-placeholder-(.+)-id([\\s\\S]*)/);\n const placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:\n // animation: linear ${time}s ease-out;\n\n const suffix = placeholderMatch[2];\n const expression = expressions[placeholderID];\n replaceCounter++;\n parts = parts.slice(0, atPlaceholderIndex).concat([\"${\", expression, \"}\" + suffix]).concat(rest);\n }\n\n return Object.assign({}, doc, {\n parts\n });\n });\n return expressions.length === replaceCounter ? newDoc : null;\n}",
"set possibleFormats(formats){this.hints.set(DecodeHintType$1.POSSIBLE_FORMATS,formats);}",
"function extUtils_replaceValuesInString(theStr, updatePatterns, paramObj)\n{\n var retVal = '';\n\n if (typeof theStr == \"string\" && theStr.length)\n {\n retVal = theStr;\n for (var i=0; i < updatePatterns.length; i++)\n {\n if (updatePatterns[i].pattern) //if there is a pattern\n {\n pattern = eval(updatePatterns[i].pattern);\n retVal = extUtils.safeReplaceBetweenSubExpressions(retVal, pattern, paramObj[updatePatterns[i].paramName]);\n }\n else\n {\n retVal = paramObj[updatePatterns[i].paramName]; //replace entire string\n }\n }\n }\n\n return retVal;\n}",
"function deleteFormat(format)\r\n{\r\n}",
"function _replacement() {\n if (!arguments[0]) return \"\";\n var i = 1, j = 0, $pattern;\n // loop through the patterns\n while ($pattern = _patterns[j++]) {\n // do we have a result?\n if (arguments[i]) {\n var $replacement = $pattern[$REPLACEMENT];\n switch (typeof $replacement) {\n case \"function\": return $replacement(arguments, i);\n case \"number\": return arguments[$replacement + i];\n }\n var $delete = (arguments[i].indexOf(self.escapeChar) == -1) ? \"\" :\n \"\\x01\" + arguments[i] + \"\\x01\";\n return $delete + $replacement;\n // skip over references to sub-expressions\n } else i += $pattern[$LENGTH];\n }\n }",
"swapPlaceholder(newText) {\n\n\t}",
"function makeReplaceFunction(values) {\n return function(match, id) {\n values.push(id);\n return '';\n };\n }",
"formatUrl(date) {\n return this.url.replace(/\\{\\{([^}]+)\\}\\}/, (_, fmt) => strftime(date, fmt))\n }",
"function __format(formatString, args) {\n if (formatString === null || formatString === undefined) return [\"\"];\n if (arguments.length == 1) return [formatString.toString()];\n\n if (typeof formatString != \"string\")\n formatString = formatString.toString();\n\n var pattern = /(.*?)%(.)(.*)/;\n var rest = formatString;\n var result = [];\n\n while (args.length) {\n var match = pattern.exec(rest);\n if (!match) break;\n\n var arg = args.shift();\n rest = match[3];\n result.push(match[1]);\n\n if (match[2] == '%') {\n result.push('%');\n args.unshift(arg);\n continue;\n }\n\n result.push(__formatted(arg, match[2]));\n }\n\n result.push(rest);\n\n var remainingArgs = [].slice.call(args);\n remainingArgs.unshift(result.join(''));\n return remainingArgs;\n }",
"replaceVariableNames(thisParameter, fileName, variableList) {\n let result = \"\";\n let fileContents = thisParameter.fileOpsUtil\n .getContentFromFile(fileName)\n .split(os.EOL);\n\n logger.info(\n \"Single File Converter: Replacing variable in file : \" + fileName\n );\n fileContents.forEach((line) => {\n for (let variable in variableList) {\n let indices = [];\n let tempLine = line;\n let indexCounter = 0;\n\n while (\n tempLine.indexOf(\n variableList[variable].split(\":\")[0].toString()\n ) > -1\n ) {\n let indexOfVariable = tempLine.indexOf(\n variableList[variable].split(\":\")[0].toString()\n );\n if (\n indexOfVariable > -1 &&\n (tempLine.charAt(indexOfVariable - 1).toString() ==\n \"$\" ||\n tempLine.charAt(indexOfVariable - 1).toString() ==\n \"{\")\n ) {\n indices.push(indexCounter + indexOfVariable);\n }\n indexCounter +=\n indexOfVariable +\n variableList[variable].split(\":\")[0].toString().length;\n tempLine = tempLine.substring(\n indexOfVariable +\n variableList[variable].split(\":\")[0].toString()\n .length,\n tempLine.length\n );\n }\n\n indices.forEach((index) => {\n if (\n index > -1 &&\n (line.charAt(index - 1).toString() == \"$\" ||\n line.charAt(index - 1).toString() == \"{\")\n ) {\n //line = line.replace((variableList[variable].split(\":\")[0]).toString(), (variableList[variable].split(\":\")[1]).toString());\n line =\n line.substring(0, index) +\n variableList[variable].split(\":\")[1].toString() +\n line.substring(\n index +\n variableList[variable]\n .split(\":\")[0]\n .toString().length,\n line.length\n );\n }\n });\n\n if (\n line.includes(\n \"export \" +\n variableList[variable].split(\":\")[0].toString()\n ) ||\n line.startsWith(\n \"EXPORT \" +\n variableList[variable].split(\":\")[0].toString()\n )\n ) {\n while (\n line.includes(\n variableList[variable].split(\":\")[0].toString()\n )\n ) {\n line = line.replace(\n variableList[variable].split(\":\")[0].toString(),\n variableList[variable].split(\":\")[1].toString()\n );\n }\n }\n }\n result += line + os.EOL;\n });\n\n fs.writeFileSync(fileName, result, \"utf8\", function (err) {\n if (err) {\n logger.error(err);\n } else {\n logger.info(\n \"Single File Converter: Successfully changed variable in file : \" +\n fileName\n );\n }\n });\n }",
"replaceTokens(tags, data) {\n tags.filter(t => t.text).forEach(tag => {\n const element = tag.element;\n const regex = /\\[([\\w\\s.-]+)\\]/g;\n let missingData = false;\n\n const replaced = tag.text.replace(regex, function(match, tokenName) {\n const value = data[tokenName];\n if (\n typeof value !== 'undefined' &&\n data[tokenName] !== null &&\n !(typeof value === 'number' && isNaN(value))\n ) {\n return value;\n } else {\n CD.log('missing replacement value for ' + tokenName);\n missingData = true;\n return '';\n }\n });\n\n if (missingData) {\n this.showFallbackText(tag);\n } else {\n tag.text = replaced;\n tag.element.innerHTML = replaced;\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts all components. label_struct is the result of running labelComponents and is reused if possible | function splitConnectedComponents(volume, label_struct) {
if(!label_struct) {
label_struct = labelConnectedComponents(volume);
}
var count = label_struct.count
, labels = label_struct.labels
, components = new Array(count);
for(var i=0; i<count; ++i) {
components[i] = new core.DynamicVolume();
}
for(var iter=core.beginStencil(volume, stencils.CROSS_STENCIL); iter.hasNext(); iter.next()) {
var idx = iter.ptrs[0];
var label = labels[idx];
var phase = volume.phases[idx];
var distance = volume.distances[idx];
if(label < 0) {
for(var i=1; i<7; ++i) {
if(labels[iter.ptrs[i]] >= 0) {
components[labels[iter.ptrs[i]]].push(iter.coord[0], iter.coord[1], iter.coord[2], distance, 0);
}
}
} else {
components[label].push(iter.coord[0], iter.coord[1], iter.coord[2], distance, phase);
}
}
for(var i=0; i<count; ++i) {
components[i] = repair.removeDuplicates(components[i]);
}
return components;
} | [
"labeled() {\n return getLabels(this.grid);\n }",
"generateLabels() {\n var filteredInstructions = [];\n var filteredIndex = 0;\n for (var i = 0; i < this.insns.length; ++i) {\n var lineNo = i + 1;\n var insn = this.insns[i];\n if (insn.indexOf('#') != -1) { // remove everything after a comment\n insn = insn.substring(0, insn.indexOf('#')).trim();\n }\n if (insn.charAt(insn.length-1) == ':') { // encounter a label which ends with a colon\n var label = insn.substring(0, insn.length-1);\n if (this.labels[label] !== undefined) {\n this.pushError(\"Found multiple instances of label: \" + label + \" [line \" + lineNo + \"]\");\n }\n if (label.charAt(0) >= '0' && label.charAt(0) <= '9') {\n this.pushError(\"Label name cannot start with a number: \" + label + \" [line \" + lineNo + \"]\");\n continue;\n }\n this.labels[label] = filteredIndex; // make label point to the line after it (also zero-index -> one-index)\n }\n else if (insn != '') { // ignore empty/comment lines\n filteredInstructions.push([insn, lineNo, insn]); // push instruction and line number for debugging purposes\n filteredIndex++;\n }\n }\n this.insns = filteredInstructions;\n }",
"function createFormControlLabels() {\n let sectionLabels = [\n 'arts', 'automobiles', 'books', 'business', 'fashion', 'food', 'health', 'home', 'insider', 'magazine', \n 'movies', 'ny region', 'obituaries', 'opinion', 'politics', 'real estate', 'science', 'sports', 'sunday review', \n 'technology', 'theater', 't-magazine', 'travel', 'upshot', 'us', 'world'\n ]\n\n const sectionValues = sectionLabels.map(section => {\n const sectionArr = section.split(' ');\n if (sectionArr.length > 1) {\n section = sectionArr.join('');\n console.log('joining section:', section);\n }\n return section;\n })\n\n /** capitalize each word in selction lables */\n sectionLabels = sectionLabels.map( section => {\n // debugger;\n section = section.split(' ');\n let updatedSection = section.map( item => {\n let firstLetter = item.charAt(0).toUpperCase();\n let remainder = item.slice(1);\n item = firstLetter + remainder;\n return item;\n })\n updatedSection = updatedSection.join(' ');\n return updatedSection;\n })\n\n /** Creating the form labels */\n const formLabels = sectionValues.map( (section, index) => (\n <FormControlLabel\n key={section}\n value={section}\n control={<Radio />}\n label={sectionLabels[index]}\n />\n ))\n\n return formLabels;\n }",
"getAllLabels() {\n return Object.keys(this.states)\n .map(n => this.states[n].edges.map(e => e.label).filter(l => l !== Label.E))\n .__dfajs_flatten()\n .__dfajs_uniqAsString();\n }",
"outChildComponents() {\n if(Array.isArray(this.props.loopedComponents)) {\n this.props.loopedComponents.forEach((component) => {\n if(Array.isArray(component.renderedComponents)) {\n Array.from(component.renderedComponents).forEach(comp => {\n comp.out();\n })\n component.renderedComponents = [];\n }\n })\n }\n if(typeof this.childsObj == \"object\") {\n Object.values(this.childsObj).map((component) => {\n component.out();\n })\n }\n }",
"GetMultipleComponentsInfo() {\n\n }",
"function buildLabels() {\n var shown = [];\n for (var n = 0; n < graphPath.nodes.length; n++) {\n // if type not placeholder, add to shown\n if (graphPath.nodes[n].type != \"placeholder\") {\n shown.push(graphPath.nodes[n].group);\n }\n }\n return shown;\n}",
"createLabelForFeature(feature) {\n //Return if labels are not desired for this area type\n if (!this.hasLabels) {\n return;\n }\n //Add arc label to label layer\n this.labelLayer.addLabelForFeature(feature);\n }",
"renderLabel(elements, label, side) {\n if (!label) return false;\n\n const { labelAppearance } = this.props;\n\n if (this.labelShouldWrapElement(side)) {\n elements.addOn(side, label);\n const labelClass = classNames(labelAppearance, `${side} wrapped`);\n // wrap in a <label> to get click behavior\n elements.wrap(\"label\", labelClass);\n // wrap in a span to avoid SUI rendering problem\n elements.wrap(\"span\");\n }\n else {\n const labelClass = classNames(\"ui\", labelAppearance, \"label\");\n const labelElement = elements.createWrapped(\"label\", labelClass, label);\n elements.addOn(side, labelElement);\n }\n return true;\n }",
"function group(label) {\n // parameter groups inside panels\n var $label = $(label),\n $description = $label.next('description');\n return {\n label: $label.text(),\n description: $description.text(),\n parameters: _.map($description.nextUntil('label'), param)\n };\n}",
"function CLC_Content_FindLabelText(target){\r\n var logicalLineage = CLC_GetLogicalLineage(target);\r\n var labelText = \"\";\r\n for (var i=0; i < logicalLineage.length; i++){\r\n if (logicalLineage[i].tagName && (logicalLineage[i].tagName.toLowerCase() == \"label\")){\r\n labelText = labelText + \" \" + logicalLineage[i].textContent;\r\n }\r\n }\r\n return labelText;\r\n }",
"function addLabelProperties()\n\t{\n\t\t//\tCollect all label elements in form, init vars\t\t\n\t\tif ( typeof f.getElementsByTagName == 'undefined' ) return;\n\t\tvar labels = f.getElementsByTagName( \"label\" );\n\t\tvar label, i = j = 0;\n\t\tvar elem;\n\n\t\t//\tLoop through labels retrieved\n\t\twhile ( label = labels[i++] )\n\t\t{\n\t\t\t//\tFor Opera 6\n\t\t\tif ( typeof label.htmlFor == 'undefined' ) return;\n\t\t\tif (typeof f.elements[label.htmlFor] == 'undefined') continue;\n\t\t\t\n\t\t\t//\tRetrieve element\n\t\t\telem = f.elements[label.htmlFor];\n\t\t\tif ( typeof elem == 'undefined' )\n\t\t\t{\t//\tNo element found for label\t\t\t\t\n\t\t\t\tself.devError( [label.htmlFor], 'noLabel' );\n\t\t\t}\n\t\t\telse if ( typeof elem.label != 'undefined' )\n\t\t\t{\t//\tlabel property already added\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse if ( typeof elem.length != 'undefined' && elem.length > 1 && elem.nodeName != 'SELECT' )\n\t\t\t{\t//\tFor arrayed elements\n\t\t\t\tfor ( j = 0; j < elem.length; j++ )\n\t\t\t\t{\n\t\t\t\t\telem.item( j ).label = label;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//\tRegular label\n\t\t\telem.label = label;\n\t\t}\n\t}",
"createShowSlotComponents() {\n let showSlots = [];\n for (var day in this.state.data) {\n let curDay = [];\n curDay.push(this.createLabelSlot(day));\n for (let i = 0; i < this.state.data[day].length; i++) {\n curDay.push(<ScheduleShowSlot {...this.state.data[day][i]}/>)\n }\n showSlots.push(curDay);\n }\n return showSlots;\n }",
"getLabel() { return this.labelP.innerText; }",
"visitLabel_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitLabel_name(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"getAllNodesWithLabel(label) {\n let task = session.run(`MATCH (N:${label}) RETURN N` ), records = [];\n return task.then(result => {\n result.records.forEach(record => records.push(createFlatProps(record.get('N').properties)));\n return records;\n })\n }",
"function TLabel(){}",
"_getFilterLabels(label, field)\r\n {\r\n var templateChoice = _.template($(this.options.templateFilterChoice).html());\r\n var templateInput = _.template($(this.options.templateFilterMultipleEnum).html());\r\n var labelCollection = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__GLOBAL_RESOURCELABEL_COLLECTION);\r\n var project = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__PROJECT_GET_ACTIVE);\r\n var project_resources = Radio.channel('rodan').request(RODAN_EVENTS.REQUEST__RESOURCES_CURRENT, {data: {project: project.id}});\r\n var labels = new Set();\r\n project_resources.each(function (resource) {\r\n resource.attributes.labels.forEach(function ({ url }) {\r\n labels.add(url);\r\n });\r\n });\r\n var filtered_collection = labelCollection.filter(function (resource) { return labels.has(resource.attributes.url); });\r\n var labelModels = filtered_collection.map((label) => {\r\n return {\r\n label: label.get('name'),\r\n value: label.get('uuid')\r\n };\r\n });\r\n var htmlChoice = templateChoice({label: label, field: field});\r\n var htmlInput = templateInput({label: label, field: field, values: labelModels});\r\n return {collectionItem: htmlChoice, input: htmlInput};\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the home score. | function setHomeScore(score) {
if(score >= 0) { // teams may not have a score below zero
snapshotState();
scoreBoard.homeScore = score;
var update = { homeScore: score };
socket.emit('boardUpdate', update);
}
} | [
"function updateScore() {\n\n}",
"function updateScore() {\n humanScoreSpan.innerHTML = humanScore;\n computerScoreSpan.innerHTML = computerScore;\n return;\n }",
"updateScore() {\n this.serverComm.updateScore(this.userId, this);\n }",
"set score(newScore) {\r\n score = newScore;\r\n _scoreChanged();\r\n }",
"setScore() {\n this.#gameScore += this.#rules[this.#gameLevel - 1].score\n document.dispatchEvent(this.#gameScoreEvent)\n }",
"function updateScore(){\n scoreText.setText(\"Score: \"+score);\n }",
"function updateScore() {\n\t\t\t// Score rule: pass level n in t seconds get ((100 * n) + (180 - t)) points \n\tlevelScore = (levelTime + 100) + Math.floor(levelTime * (currentLevel-1));\n\t// Set original \"levelScore\" to extraLevelScore for testing purpose\n\tfinalScore += levelScore + extraLevelScore;\t\t\n\t// Add finalTime\n\tfinalTime += startLevelTime - levelTime;\n}",
"set score(val) {\n this._score = val;\n console.log('score updated');\n emitter.emit(G.SCORE_UPDATED);\n }",
"updateScore(){\n this.score += 1;\n this.labelScore.text = this.score;\n }",
"function updateScore(elapsedTime){\r\n\t\tif(!myShip.getSpecs().hit && !myShip.getSpecs().invincible){\r\n\t\t\tvar oldCounter = Math.floor(updateScoreCounter);\r\n\t\t\tupdateScoreCounter += elapsedTime/1000;\r\n\t\t\tvar newCounter = Math.floor(updateScoreCounter);\r\n\r\n\t\t\tif(newCounter == oldCounter + 1){\r\n\t\t\t\taddToScore(10);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"function checkScore() {\n if (locArray[currentLocation].hasVisited === false) {\n locArray[currentLocation].hasVisited = true;\n score = score + 5; \n } else if (locArray[currentLocation].hasVisited === true) {\n score = score + 0; \n } \n }",
"function updateScoreOverlay() {\n let one = playerNetscore(team.getT1());\n write(t1Players, one);\n one = team.getT1();\n write(t1Score, one.points);\n\n let two = playerNetscore(team.getT2());\n write(t2Players, two);\n two = team.getT2();\n write(t2Score, two.points);\n}",
"function checkScore() {\n if (totalScoreNumber === currentGoalNumber && currentGoalNumber != 0) {\n wins++;\n $(\"#wins\").text(\"Wins: \" + wins);\n setNumbers();\n }\n else if (totalScoreNumber > currentGoalNumber) {\n losses++;\n $(\"#losses\").text(\"Losses: \" + losses);\n setNumbers();\n }\n }",
"function clearScore() {\n currentScore = 0;\n }",
"function updateScoreAndLives() {\r\n\tscoreSpan.innerHTML = score;\r\n\tlivesSpan.innerHTML = lives;\r\n\tresultScoreSpan.innerHTML = score;\r\n}",
"function updateHighScore(path, data) {\n var leaderRef = firebase.database().ref().child(\"highscores\");\n leaderRef.child(path).update(data);\n }",
"function displayScore() {\n // Make the score disappear when a game over happens\n if (state === \"GAMEOVER\") {\n return;\n }\n push();\n // Setting the aesthetics\n fill(255);\n textFont(neoFont);\n textSize(64);\n // Show the score at the bottom left of the screen\n textAlign(LEFT, BOTTOM);\n text(\"SCORE:\" + thief.preyEaten, 0, height);\n pop();\n}",
"function updateGameInfo() {\n\t\tvar $ = jewel.dom.$;\n\t\t$(\"#game-screen .score span\")[0].innerHTML = gameState.score;\n\t\t$(\"#game-screen .level span\")[0].innerHTML = gameState.level;\n\t}",
"function gameOver() {\n update($question, \"Game Over. You scored \" + score + \" points.\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Once Funder selection on homepage is made, run this function Be sure to rename all cta with unique IDs Update each unique ID with call to action text, replacing the text Funder mode is on! | function funderMode() {
//If the URL contains the word 'capacity', use these CTAs
if (window.location.pathname.match('capacity')) {
document.getElementById("capacityOne").innerHTML = '<div class="cta">Funder mode on!</div>';
document.getElementById("capacityTwo").innerHTML = '<div class="cta">Funder mode on!</div>';
}
//If the URL contains the word 'circular', use these CTAs
else if (window.location.pathname.match('circular')) {
document.getElementById("circularOne").innerHTML = '<div class="cta">Funder mode on!</div>';
document.getElementById("circularTwo").innerHTML = '<div class="cta">Funder mode on!</div>';
}
//If the URL contains the word 'cities', use these CTAs
else if (window.location.pathname.match('cities')) {
document.getElementById("citiesOne").innerHTML = '<div class="cta">Funder mode on!</div>';
document.getElementById("citiesTwo").innerHTML = '<div class="cta">Funder mode on!</div>';
}
//If the URL contains the word 'climate', use these CTAs
else if (window.location.pathname.match('climate')) {
document.getElementById("climateOne").innerHTML = '<div class="cta">Funder mode on!</div>';
document.getElementById("climateTwo").innerHTML = '<div class="cta">Funder mode on!</div>';
}
//If the URL contains the word 'health', use these CTAs
else if (window.location.pathname.match('health')) {
document.getElementById("healthOne").innerHTML = '<div class="cta">Funder mode on!</div>';
document.getElementById("healthTwo").innerHTML = '<div class="cta">Funder mode on!</div>';
}
//If the URL contains the word 'inclusive', use these CTAs
else if (window.location.pathname.match('inclusive')) {
document.getElementById("inclusiveOne").innerHTML = '<div class="cta">Funder mode on!</div>';
document.getElementById("inclusiveTwo").innerHTML = '<div class="cta">Funder mode on!</div>';
}
//If the URL contains the word 'leadership', use these CTAs
else if (window.location.pathname.match('leadership')) {
document.getElementById("leadershipOne").innerHTML = '<div class="cta">Funder mode on!</div>';
document.getElementById("leadershipTwo").innerHTML = '<div class="cta">Funder mode on!</div>';
}
//If the URL contains the word 'unprecedented', use these CTAs
else if (window.location.pathname.match('unprecedented')) {
document.getElementById("unprecedentedOne").innerHTML = '<div class="cta">Funder mode on!</div>';
document.getElementById("unprecedentedTwo").innerHTML = '<div class="cta">Funder mode on!</div>';
}
console.log("Funder mode on!");
} | [
"function fillActions() {\n\tvar actions = pref.getPref(\"actions\");\n\tfor (var id in actions) {\n\t\tactions[id].id = id;\n\t\tcreateAction(actions[id]);\n\t}\n\n\tlog.info(\"opt-action:\",\n\t\t\"Preferences page is filled with actions.\"\n\t);\n}",
"function iglooActions () {\n\t//we should have things like pageTitle, user and revid\n\t//here- and the current page\n}",
"function screenConfirmed(isConfirmed) { \n document.getElementById(\"selects\").innerHTML = \"\";\n if (isConfirmed === true){\n onAccessApproved(currentScreensharePickID);\n }\n togglePage();\n}",
"function rfqTabClicked()\n{\n\t$( \"#rfq_tab\" ).removeClass( 'tab_gray' );\n\t$( \"#rfq_tab\" ).addClass( 'tab_orange' );\n\t\n\t\n\t$( \"#quote_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#quote_tab\" ).addClass( 'tab_gray' );\n\t\n\t$( \"#po_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#po_tab\" ).addClass( 'tab_gray' );\n\t\n\t$( \"#invoice_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#invoice_tab\" ).addClass( 'tab_gray' );\n\t\n\tselectedTab = \"RFQ\";\n\t\n\t $(\"#transet_label_content\").val(rfqText);\n\t$(\"#transet_titile\").text(\"RFQ Terms and Conditions\");\n\t \n\t if(rfqText==\"\")\n\t{\n\t\t $(\"#no_tc\").show();\n\t\t $(\"#tc_content\").hide();\n\t }\n\t else\n\t {\n\t\t $(\"#tc_content\").show();\n\t\t $(\"#no_tc\").hide();\n\t\t \n\t }\n\t\n}",
"function poTabClicked()\n{\n\t$( \"#rfq_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#rfq_tab\" ).addClass( 'tab_gray' );\n\t\n\t$( \"#quote_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#quote_tab\" ).addClass( 'tab_gray' );\n\t\n\t$( \"#po_tab\" ).removeClass( 'tab_gray' );\n\t$( \"#po_tab\" ).addClass( 'tab_orange' );\n\t\n\t$( \"#invoice_tab\" ).removeClass( 'tab_orange' );\n\t$( \"#invoice_tab\" ).addClass( 'tab_gray' );\n\t\n\tselectedTab = \"PO\";\n\t\n\t $(\"#transet_label_content\").val(poText);\n\t $(\"#transet_titile\").text(\"PO Terms and Conditions\");\n\t\t\n\tif(poText==\"\")\n\t{\n\t\t$(\"#no_tc\").show();\n\t\t $(\"#tc_content\").hide();\n\t}\n\telse\n\t{\n\t\t$(\"#tc_content\").show(); \n\t\t $(\"#no_tc\").hide();\n\t}\n}",
"function C101_KinbakuClub_Fight_Click() {\n\tFightClick();\n}",
"function pageClick1(k) {\n\t$(k).parent().find(\"div\").removeClass(\"active\");\n\t$(k).addClass(\"active\");\n\t$(\"#flTitle\").text($(k).text());\n\tdocument.getElementById(\"con\").innerHTML = '<object type=\"text/html\" data=\"view\" width=\"100%\" height=\"100%\"></object>';\n}",
"function _showModifyTileMenu() {\n //topAppBar.winControl.hide();\n div_cockpits_bottomAppBar.winControl.hide();\n var item = lv_cockpits.winControl._selection.getItems()._value[0].data;\n item.idDashboard = CockpitHelper.currentDashboard.id;\n if (item.widgetType == CockpitHelper.TileType.Numerique) {\n RightMenu.showRightMenu(Pages.modifyKpiResumeStep, { \"tile\": item });\n }\n else if (item.widgetType == CockpitHelper.TileType.Exploration) {\n RightMenu.showRightMenu(Pages.modifyExploration, { \"tile\": item });\n }\n }",
"function SetSideMenuContentForFullAccountReconciliation(selectedPage,id)\r\n{\r\n var str ='';\r\n var temp = '<li>';\r\n var temp1 = '<li class=\"leftContentListNavSelected\">';\r\n\r\n if(selectedPage == 'entry')str += temp1;else str += temp;\r\n str += '<a href=\"..\\/acct_recon\\/entry.html\">Account recon issue manual entry<\\/a>';\r\n\tstr += '<\\/li>';\r\n\tif(selectedPage == 'import')str += temp1;else str += temp;\r\n\tstr += '<a href=\"..\\/acct_recon\\/import.html\">Account recon issue file import<\\/a>';\r\n\tstr += '<\\/li>';\r\n\tif(selectedPage == 'update')str += temp1;else str += temp;\r\n\tstr += '<a href=\"..\\/acct_recon\\/update.html\">Account recon update issue<\\/a>';\r\n\tstr += '<\\/li>';\r\n\tif(selectedPage == 'approval')str += temp1;else str += temp;\r\n\tstr += '<a href=\"..\\/acct_recon\\/issue_approval.html\">Account recon issue approval<\\/a>';\r\n\tstr += ' <\\/li>';\r\n\tif(selectedPage == 'statement')str += temp1;else str += temp;\r\n\tstr += '<a href=\"..\\/acct_recon\\/full_statement.html\">Account recon statement report<\\/a>';\r\n\tstr += ' <\\/li>';\r\n\tif(selectedPage == 'activity')str += temp1;else str += temp;\r\n\tstr += '<a href=\"..\\/acct_recon\\/full_activity.html\">Account recon activity report<\\/a>';\r\n\tstr += '<\\/li>';\r\n\thelpwriteContent(id,str);\r\n}",
"function confSelected(conf){\n\t\tvar selected = document.conferences[conf].checked;\n\t\tconferences[conf] = selected; \n\t\tif (currentAuthor != undefined){\n\t\t\tauthorClicked(currentAuthor);\n\t\t} else {\n\t\t\tresetSelector();\n\t\t}\n\t}",
"function performSelectedAction(){\r\n\tswitch(selectedAction){\r\n\tcase GameScreenActionType.mainmenu:\r\n\t\tperformQuit();\r\n\t\tbreak;\r\n\tcase GameScreenActionType.hints:\t\r\n\t\ttoggleHints();\r\n\t\tbreak;\r\n\tcase GameScreenActionType.difficulty:\r\n\t\tperformDifficultyAction();\r\n\t\tbreak;\r\n\tcase GameScreenActionType.gamestate:\r\n\t\t\r\n\t\tbreak;\r\n\t}\r\n}",
"function loggedOutQuicktabAlter(){\n\t\n\t\tif($(\"body\").hasClass(\"not-logged-in\")){\t\n\t\t\t$('.node-type-work-group .cop-quicktab .resources , .node-type-work-group .cop-quicktab .e-learning , .node-type-work-group .cop-quicktab .experts').wrapAll('<li class=\"wrapped-list\"> </li>');\t\t\t\n\t\t\tif( $('.not-logged-in.node-type-work-group .wrapped-list li').length > 0 ){\n\t\t\t\tif( $('.not-logged-in .cop-quicktab ul.quicktabs-tabs li.about').length > 0 ){ \n\t\t\t\t\t\t$('.not-logged-in .cop-quicktab ul.quicktabs-tabs li.about').after('<li class=\"knowledge\"><a>'+Drupal.t(\"Knowledge\")+'<div class=\"plus\">+</div><div class=\"minus\">-</div></a></li>');\n\t\t\t\t}\n\t\t\t\telse if( $('.not-logged-in.node-type-work-group .cop-quicktab ul.quicktabs-tabs li.about').length == 0 ){ \n\t\t\t\t\t\t$('.cop-quicktab ul.quicktabs-tabs li:first-child').before('<li class=\"knowledge\"><a>'+Drupal.t(\"Knowledge\")+'<div class=\"plus\">+</div><div class=\"minus\">-</div></a></li>');\n\t\t\t\t}\n\t\t\t}\t\t\n\t\t\t\n\t\t\tvar content = $('.cop-main-header').clone();\n\t\t\t$('.cop-main-header').remove();\n\t\t\t$('.cop-quicktab .tab-content .quicktabs-tabpage:first-child').before(content);\n\t\t\t//$('.customized-quicktab-menu .tab-content').before(content);\n\t\t\t\n\t\t}\n\t\t/*function for cop quicktab modification in logged out case French*/\n\t\tif(($(\"body\").hasClass(\"not-logged-in\")) && ($(\"body\").hasClass(\"i18n-fr\")) ){\t\n\t\t\t$('.node-type-work-group .cop-quicktab .portail, .node-type-work-group .cop-quicktab .trousses-à-outils, .node-type-work-group .cop-quicktab .ressources, .node-type-work-group .cop-quicktab .e-learning , .node-type-work-group .cop-quicktab .experts').wrapAll('<li class=\"wrapped-list\"> </li>');\t\t\t\n\t\t\tif( $('.not-logged-in.node-type-work-group .wrapped-list li').length > 0 ){\n\t\t\t\tif( $('.not-logged-in .cop-quicktab ul.quicktabs-tabs li.à-propos').length > 0 ){ \n\t\t\t\t\t\t$('.not-logged-in .cop-quicktab ul.quicktabs-tabs li.à-propos').after('<li class=\"knowledge\"><a>'+Drupal.t(\"Knowledge\")+'<div class=\"plus\">+</div><div class=\"minus\">-</div></a></li>');\n\t\t\t\t}\n\t\t\t\telse if( $('.not-logged-in.node-type-work-group .cop-quicktab ul.quicktabs-tabs li.à-propos').length == 0 ){ \n\t\t\t\t\t\t$('.cop-quicktab ul.quicktabs-tabs li:first-child').before('<li class=\"knowledge\"><a>'+Drupal.t(\"Knowledge\")+'<div class=\"plus\">+</div><div class=\"minus\">-</div></a></li>');\n\t\t\t\t}\n\t\t\t}\t\t\n\t\t\t\n\t\t\tvar content = $('.cop-main-header').clone();\n\t\t\t$('.cop-main-header').remove();\n\t\t\t$('.cop-quicktab .tab-content .quicktabs-tabpage:first-child').before(content);\t\n\t\t}\t\t\t\n\t}",
"function writeCategories() {\n for (i = 0; i < 4; i++) {\n var ranNum = makeUniqueRandom(selectCategory.length, uniqueCategory);\n var isDisabled = $(\"#categoryBtn-\" + i).attr(\"disabled\");\n if (!isDisabled) {\n $(\"#categoryBtn-\" + i).attr(\"value\", selectCategory[ranNum]);\n $(\"#categoryBtn-\" + i).text(selectCategory[ranNum]);\n }\n }\n removeUnderscores();\n }",
"function updateTextUI() {\n select('#result_hf').html(currentText);\n}",
"function ShareSelectedFactors(factor) {\n $(\".\" + factor).toggleClass(factor + \"_selected\");\n}",
"function loadFAQ() {\n\t\tvar itemID;\n\t\t//list of learneable items\n\t\tfor(var i=0;i<$(\".learn-list>li\").length;i++){\n\t\t\titemID=$(\".learn-list>li>.hint\").eq(i).attr(\"id\");\n\t\t\t$(\".learn-list>li>.hint\").eq(i).append(\"<a data-fav=\\\"#\"+itemID+\"\\\" class='favbtntest'>toggle favourite</a>\");\n\t\t}\t\n\t\t//this is the list of buttons for a predefined search\n\t\tfor(i=0;i<$(\".search-list>button\").length;i++){\n\t\t\t$(\".search-list>button\").eq(i).click(function() {\n\t\t\t\tvar searchText=($(this).text()===\"*\")?\"\":$(this).text();\n\t\t\t\t$(\".wb-fltr-inpt\").val(searchText)\n\t\t\t\tvar e = jQuery.Event(\"keyup\");\n\t\t\t\t//e.which = 50; // # Some key code value\n\t\t\t\t$(\".wb-fltr-inpt\").trigger(e);\n\n\t\t\t});\n\t\t}\n\t}",
"function on_piece_select()\n{\n\tupdate_editor();\n}",
"function switchMainTo(functId){\n \n if(!createFunct[functId] && functId != \"welcome_note\")\n return;\n $(\"#\"+activeMainId).hide();\n activeMainId=functId+\"_main\";\n if($(\"#\"+functId+\"_main\").length>0)\n $(\"#\"+functId+\"_main\").show();\n else\n createFunct[functId]();\n}",
"function showCorrectLogonPage() {\n if(initializeRewards.urlContainsFlowID()){\n changePageFn('#urlogon');\n } else if (isCustomerUsingToken(ccoTokenKey)) {\n changePageFn('#cco');\n }else if (isCustomerUsingToken(bbTokenKey)) {\n changePageFn('#bb');\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name: Jainam Shah Purpose: To get service user background data for a client Params: client_id | async getUserBackground(clientId) {
try {
const client = await Client.query()
.select(
'id',
'slug',
'service_user_weight',
'service_user_height',
'service_user_lastname',
'service_user_diet',
'service_user_physical_ability',
'service_user_eye_sight',
'service_user_hearing',
'service_user_lifting',
'service_user_lifting_specific',
'service_user_lower_left_leg_limb_mobility',
'service_user_lower_right_leg_limb_mobility',
'service_user_left_hand_mobility',
'service_user_right_hand_mobility',
'service_user_assisting_device',
)
.with('otherDevices')
.with('languages')
.with('selfCareAbilities')
.where('id', clientId)
.first();
return client;
} catch (error) {
Logger.info('Service getUserBackground Catch %s', error);
throw error;
}
} | [
"function getClientById(id){\n var count = users.length;\n var client = null;\n for(var i=0;i<count;i++){\n \n if(users[i].userId==id){\n client = users[i];\n break;\n }\n }\n return client;\n}",
"function getClient(id) {\n for (var i = 0; i < clients.length; i++) {\n if (clients[i].clientID == id) {\n return clients[i].clientName;\n }\n }\n}",
"function getServiceData (servicePath, cb) {\n self.serviceDiscovery.client.getClient().getData(servicePath, null, cb);\n }",
"function searchClientByID() {\n hideAllOptions();\n\n //Show the resources loading view\n $scope.loadingResources = true;\n\n //get user input from form\n var clientId = $scope.clientID;\n\n //if they don't chose a client, start over\n if (clientId === null || clientId === '' || typeof(clientId) === 'undefined') {\n checkClientInForms();\n return;\n }\n\n //array to store clients\n $scope.clients = [];\n\n $http.get('webapi/client/searchID/' + clientId)\n .then(function (response) {\n for (var client in response.data['clients']) {\n //loop through the response data and make clients\n $scope.clients.push(response.data['clients'][client]);\n }\n //hide the loading banner\n $scope.loadingResources = false;\n\n //show the clients to choose from\n $scope.clientList = true;\n\n }, function () {\n $scope.loadingResources = false;\n $scope.kitchenError = true;\n });\n }",
"static getClientNotification(entryId, type){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.type = type;\n\t\treturn new kaltura.RequestBuilder('notification', 'getClientNotification', kparams);\n\t}",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('emailingestionprofile', 'get', kparams);\n\t}",
"function load(req, res, next, userId) {\n Client.get(userId)\n .then((client) => {\n req.client = client;\n return next();\n })\n .catch(e => next(e));\n}",
"async function retrieveSiteSeal() {\n const subscriptionId =\n process.env[\"APPSERVICE_SUBSCRIPTION_ID\"] || \"34adfa4f-cedf-4dc0-ba29-b6d1a69ab345\";\n const resourceGroupName = process.env[\"APPSERVICE_RESOURCE_GROUP\"] || \"testrg123\";\n const certificateOrderName = \"SampleCertOrder\";\n const siteSealRequest = {\n lightTheme: true,\n locale: \"en-us\",\n };\n const credential = new DefaultAzureCredential();\n const client = new WebSiteManagementClient(credential, subscriptionId);\n const result = await client.appServiceCertificateOrders.retrieveSiteSeal(\n resourceGroupName,\n certificateOrderName,\n siteSealRequest\n );\n console.log(result);\n}",
"ListOfYourApiCredentials(applicationId, status) {\n let url = `/me/api/credential?`;\n const queryParams = new query_params_1.default();\n if (applicationId) {\n queryParams.set('applicationId', applicationId.toString());\n }\n if (status) {\n queryParams.set('status', status.toString());\n }\n return this.client.request('GET', url + queryParams.toString());\n }",
"function collectFacebookUser(userId){\n var emailAddress = document.getElementById('myVId').value;\n var phoneNumber = document.getElementById('phoneNumber').value;\n\n // Make a google user as a class\n FACEBOOKUSER.configure(userId, emailAddress, phoneNumber);\n\n console.log(FACEBOOKUSER.getId());\n console.log(FACEBOOKUSER.getEmail());\n console.log(FACEBOOKUSER.getMobile());\n\n pushToServer();\n}",
"onAddTetheredClient(tetheredClient) {\n super.onAddTetheredClient(tetheredClient);\n\n const client = tetheredClient.client;\n const myClient = tetheredClient.myClient;\n const incomingData = tetheredClient.incomingData;\n console.log(\"SharedRoom\", \"onAddMyClient\");\n }",
"static fromUserPoolClientId(scope, id, userPoolClientId) {\n class Import extends core_1.Resource {\n constructor() {\n super(...arguments);\n this.userPoolClientId = userPoolClientId;\n }\n get userPoolClientSecret() {\n throw new Error('UserPool Client Secret is not available for imported Clients');\n }\n }\n return new Import(scope, id);\n }",
"function getAdvertismentImagesService() {\n\tvar data = {};\n\n\tdata.store_id = Ti.App.Properties.getString(\"store_id\");\n\n\tTi.API.info('DATA ' + JSON.stringify(data));\n\n\tvar SERVICE_GET_ADVERTISMENT = Alloy.Globals.Constants.SERVICE_GET_ADVERTISMENT;\n\tif (Ti.Network.online) {\n\t\tAlloy.Globals.LoadingScreen.open();\n\t\tCommunicator.post(DOMAIN_URL + SERVICE_GET_ADVERTISMENT, getAdvertismentImagesCallback, data);\n\t} else {\n\t\tAlloy.Globals.Notifier.show(L(\"internat_connection_message\"));\n\t}\n}",
"async listByUserId (userId) {\n return this.dbConnection\n .query(\n `select distinct on (svc.id)\n svc.id, svc.name, svc.endpoint, svc.description, svc.created_at, svc.updated_at,\n upd.status, upd.created_at as status_created_at\n from services svc\n left join status_updates upd on upd.service_id = svc.id\n where svc.user_id = $1::uuid\n order by svc.id, upd.created_at desc;`,\n [userId]\n )\n }",
"function getUsername(clientId) {\n return userList[clientId].username;\n }",
"function getCustomerProfileExample() {\n oneapi.getCustomerProfile('me',function(isOk,oResponse) {\n if(!isOk) { // oResponse is DmApiError\n log(\"Error: Unable to get Customer profile:\" + oResponse.getErrorText()); \n } else { // oResponse is DmCustomerProfile\n log(\"Customer profile for <b>\" + oResponse.getAttr(\"username\",\"\") + '</b> :'); \n oResponse.forEachAttr(function(name,value) { // display all attributes of customer profile\n log(name + \" = \" + value);\n return true;\n }); \n log(\"Done.\");\n }\n });\n}",
"function GetUser() {\n\n\tvar client = new SpiderDocsClient(SpiderDocsConf);\n\n\tclient.GetUser('administrator', 'Welcome1')\n\t\n .then(function (user) {\n debugger;\n console.log(user);\n });\n}",
"function get_background_image()\n{\n\t//Get bg image\n \t$('#instagram-feed .slick-active:not(.loaded)').each(function()\n \t{\n\t var $bg = $(this).attr(\"data-background\");\n\t \t\n\t $(this).css('background-image','url(' + $bg + ')').addClass(\"loaded\");\t \n \t});\t\n}",
"getUserPresenceData(){\n callMsGraph(this.props.msalContext, graphConfig.presenceEndpoint, this.setPresenceInformation);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function for removeProductLocalStorage > remove from the local storage | function removeProductLocalStorage(productId) {
//get the local storage data
let productsInStorage = getProductsFromStorage();
//loop through the array to find the index to remove
productsInStorage.map(function (productInStorage, index) {
if (productInStorage.productId === productId) {
productsInStorage.splice(index, 1);
}
});
// add the rest of the array
localStorage.setItem("products", JSON.stringify(productsInStorage));
updateView();
} | [
"vaciarLocalStorage() {\n localStorage.clear();\n }",
"function removeCurrentUserIDFromLocalStorage() \r\n{\r\n localStorage.removeItem(\"currentUserID\");\r\n}",
"removeFromLocalStorage() {\n const artistsInStorage = localStorage.getItem(\"Artists\");\n let currentArray = [];\n if (artistsInStorage) {\n currentArray = JSON.parse(artistsInStorage);\n const index = this.indexContainingID(currentArray, this.props.info.id);\n if (index > -1) {\n currentArray.splice(index, 1);\n }\n }\n localStorage.removeItem(\"Artists\");\n localStorage.setItem(\"Artists\", JSON.stringify(currentArray));\n }",
"function removeProduct(dataMemory,removeObject) {\n if (dataMemory.getItem(removeObject) != null) {\n dataMemory.removeItem(removeObject);\n }\n}",
"function removeProduct(event) {\n const $target = $(event.currentTarget);\n const id = $target.data('product-id');\n const quantity = $target.data('product-count');\n server.removeFromCart(id)\n .then((data) => {\n mediator.publish('onCartUpdate', data);\n mediator.publish('onProductRemove', [{ id, quantity }]);\n });\n }",
"function editProductLocalStorage(productId, quantity) {\n //get the local storage data\n let productsInStorage = getProductsFromStorage();\n let quantityNew = quantity;\n let productToEdit;\n\n //loop through the array to find the index to remove\n productsInStorage.map(function (productInStorage, index) {\n if (productInStorage.productId === productId) {\n productToEdit = productInStorage;\n productToEdit.quantity = quantityNew;\n productsInStorage.splice(index, 1);\n }\n });\n\n productsInStorage.push(productToEdit);\n // add the rest of the array\n localStorage.setItem(\"products\", JSON.stringify(productsInStorage));\n updateView();\n}",
"function deleteFromMPO(product) {\n //Search for the index of the product in the array\n let index = singleProducts.indexOf(product);\n\n let input = document.querySelector(`.mijn-producten-label${product.id}`).querySelector('input');\n input.checked = false;\n input.classList.remove('added');\n //Remove product\n singleProducts.splice(index, 1)\n computeMPOProducts();\n updateCounter();\n}",
"function deleteFromList(list, product) {\n //Search for the index of the product in the array\n let index = list.products.indexOf(product);\n\n //Remove product\n list.products.splice(index, 1)\n let input = document.querySelector(`.mijn-producten-label${product.id}`).querySelector('input');\n input.checked = false;\n input.classList.remove('added'); \n calcLists();\n updateCounter();\n}",
"function storeRemoved(inputVal) {\n if(localStorage.getItem(\"removed\")){\n let localList = JSON.parse(localStorage.getItem(\"removed\"));\n localList[localList.length] = inputVal;\n localStorage.setItem(\"removed\", JSON.stringify(localList));\n } else {\n let localList = [];\n localList.push(inputVal);\n localStorage.setItem(\"removed\", JSON.stringify(localList));\n }\n storeAddedPro(inputVal);\n}",
"function removeList(elem) {\n\n //Get element/row number\n var elementNo = elem.parentNode.getAttribute(\"data\");\n\n //Check browser WebStorage support\n if (typeof(Storage) !== \"undefined\") {\n\n if(localStorage.getItem(\"lists\") != null) {\n\n // Retrieve local storage\n var lists = JSON.parse(localStorage.getItem(\"lists\"));\n\n lists.splice(elementNo, 1);\n\n localStorage.setItem(\"lists\", JSON.stringify(lists));\n //R\n location.reload();\n }\n\n } else {\n document.getElementById(\"result\").innerHTML = \"Sorry, your browser does not support Web Storage...\";\n }\n}",
"clearDataFromLocalStorage() {\n localStorage.db = [];\n }",
"function deleteQuoteLocalStorage() {\n console.log('delete')\n}",
"function activeFunctionDelete(dataMemory,dataParse,level) {\n let deleteObject = document.getElementsByClassName(deleteProductCartTarget);\n deleteObject[level].setAttribute(\"id\",\"\"+dataParse._id+\"\");\n deleteObject[level].addEventListener(\"click\", function() {\n removeProduct(dataMemory,deleteObject[level].getAttribute(\"id\"));\n location.reload();\n });\n}",
"function deleteStock() {\n rows = getSelectedRowBoxes();\n\n for (var i=rows.length - 1; i >= 0; i--) {\n var prodId = rows[i].parentNode.parentNode.id;\n delete products[prodId];\n products.splice(prodId, 1);\n }\n saveData();\n displayInventory();\n}",
"function removeFromCart(elem) {\n let favorites = JSON.parse(localStorage.getItem(favoritesKey));\n // get the text of the element to remove\n // this is used for string matching below\n let elemToRemove = JSON.stringify($(elem).parent().parent().html());\n if (favorites) {\n console.log(\"Searching localStorage for\\n\" + elemToRemove);\n // iterate over favorites\n const favoritesLength = favorites.length;\n for (let i = 0; i < favoritesLength; i++) {\n currentFav = JSON.stringify(favorites[i]);\n // check currentFav against element to remove\n if (currentFav == elemToRemove) {\n console.log(\"Found element to remove. Removing...\");\n favorites.splice(i, 1);\n localStorage.setItem(favoritesKey, JSON.stringify(favorites));\n // found the element, nothing left to do, break\n break;\n }\n }\n console.log(\"cart after removing element:\\n\"\n + JSON.parse(localStorage.getItem(favoritesKey)));\n }\n // if the cart was already empty, no action is required.\n // log a warning anyways\n else {\n console.warn(\"attempt to remove from empty cart. no further action needed.\")\n }\n}",
"function clearAllTasksFromLocalStorage() {\n\n localStorage.removeItem('tasks');\n\n \n}",
"function deleteTaskFromLocalStorage(task) {\r\n let LocalStorageTaskArray = getLocalStorage(\"task\");\r\n let taskTitle = document.getElementById(task).firstElementChild.innerHTML;\r\n let index = LocalStorageTaskArray.findIndex(obj => obj.name === taskTitle);\r\n LocalStorageTaskArray.splice(index, 1);\r\n setLocalStorage(\"task\", LocalStorageTaskArray);\r\n}",
"removeProducts() {\n var self = this;\n self.req.session.shoppingCart = [];\n return self.res.status(204).send();\n }",
"function removeFromPortfolio() { \n portfolioArr = JSON.parse(localStorage.getItem(\"stock\"));\n portfolioCash = localStorage.getItem(\"cash\");\n let quantity = parseInt(stockSaleInput.val());\n console.log(sellQuantityAvailable);\n console.log(quantity);\n\n if(sellQuantityAvailable < quantity){\n $(\"#errorMessageDiv\").text(\"Insufficient shares available.\")\n }\n else {\n let saleTotal = quantity * sellPrice;\n portfolioCash = parseFloat(portfolioCash) + saleTotal;\n localStorage.setItem(\"cash\", portfolioCash);\n for (i=0 ; i<portfolioArr.length; i++){\n if(sellStock === portfolioArr[i].name){\n portfolioArr[i].quantity -= quantity;\n }\n }\n stockArr = JSON.stringify(portfolioArr);\n localStorage.setItem(\"stock\", stockArr);\n $(\"#portfolioDisplayDiv\").empty();\n generatePortfolio();\n $(\"#modalSell\").modal('close');\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Listen to server calls on the appropriate port number add a ride to the database under all rides and ride queue | function addRide(req, res){
var body = '';
req.on('data', function (data) {
body += data;
if (body.length > 1e6) {
req.connection.destroy();
}
});
req.on('end', function () {
//parse and get all the information for the ride
var post = qs.parse(body);
var accom = post.accomodations;
var addr = post.address;
var id = post.id;
var pas = post.passengers;
var stat = post.status;
//get date
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
var hours = date.getHours();
var min = date.getMinutes();
//add ride to all rides collection
var docRef = database.collection('allRides/');
docRef.once("value").then(function(snapshot) {
//set all the information into one json
var data = {
Accomodations: accom,
Address: addr,
Data: hours + ":" + minutes + " " + month + "/" + day + "/" + year,
ID: id,
Passengers: pas,
status: stat
};
//creates new document with unique name and add the data for the ride
db.collection('allRides/').doc('ride' + id).set(data);
})
//add ride to ride queue with minimal info
var docRef = database.collection('rideQueue/');
docRef.once("value").then(function(snapshot) {
//create new document name number
rideNum = snapshot.numChildren()+1;
//set all the information into one json
var data = {
"ID": id,
"Queue Position": rideNum
};
//creates new document with unique name and add the data for the ride
db.collection('rideQueue/').doc('ride' + id).set(data);
})
res.end()
});
} | [
"function start() {\n test();\n var httpService = http.createServer(serve);\n httpService.listen(ports[0], '0.0.0.0');\n\n var options = {\n key: key,\n cert: cert\n };\n var httpsService = https.createServer(options, serve);\n httpsService.listen(ports[1], '0.0.0.0');\n\n var clients = clientService(httpsService);\n clients.onNewPos(updateEvents);\n\n printAddresses();\n}",
"_eventloop() {\n\n this.server\n // 'config_loaded' event is send by 'init' after succesfull\n // loading and parsing the AVR config file.\n // next action: open network connection.\n .on( \"config_loaded\", () => {\n this.configLoaded = true;\n this._openConnection();\n })\n\n // Network events all emitted by '_openConnection' depending\n // (except 'net_retry') on the received network events.\n // 'net_connect' -> new connection established\n // 'net_disconnect' -> Disconnection request from the AVR\n // 'net_error' -> Received net work errors.\n // 'net_timedout' -> Network connection to the AVR has a timeout.\n // 'net_retry' -> Try to connect again to the AVR.\n .on( \"net_connect\" , () => {\n // notify 'homey' part there is a connection\n // i.e make dev available\n\n this._getAVRStatusUpdate(); // get the status of the new AVR\n\n // Wait 2 sec before informing homey so the status of the AVR\n // can be collected.\n // Set hasNetworkConnection after the the wait time so the\n // above initial status requests don't cause events\n setTimeout( () => {\n this.hasNetworkConnection = true;\n this.conChn.emit(\"net_connected\", this.avrNum, this.avrName);\n }, 2000);\n })\n .on( \"net_disconnect\" ,() => {\n // notify 'homey' part connection is disconnected\n // i.e make dev unavailable\n this.conChn.emit(\"net_disconnected\", this.avrNum, this.avrName);\n this.server.emit(\"net_retry\"); // connect again.\n })\n .on(\"net_error\" , (err) => {\n // notify 'homey' part connection is disconnected\n // i.e make dev unavailable\n this.conChn.emit(\"net_error\", this.avrNum, this.avrName, err);\n this.server.emit(\"net_retry\"); // connect again.\n })\n .on(\"net_timed_out\", () => {\n // notify 'homey' part connection is disconnected\n // i.e make dev unavailable\n this.conChn.emit(\"net_timed_out\", this.avrNum, this.avrName);\n this.server.emit(\"net_retry\"); // connect again.\n })\n .on( \"net_retry\" , () => {\n // Don't start the action if a request to stop is received.\n // hasToStop will be set by 'disconnect' function.\n if ( this.hasToStop === false ) {\n setTimeout( () => {\n this._openConnection();\n }, TIME_TO_RETRY);\n }\n })\n // Disconnect request from user/Homey\n .on( \"req_disconnect\" , () => {\n this.hasToStop = true;\n this.socket.end();\n })\n\n // send buffer events.\n // 'send_command' event occurs when\n // 1) the send buffer is filled with a new command (_insertIntoSendBuffer)\n // 2) After a command is send to the AVR.\n // To check if the buffer is no empty. (_insertIntoSendBufferToAvr).\n\n .on( \"new_data\" , () => {\n // New commands are added to the send buffer.\n // start the send loop only once\n // will be reset as soon the send buffer runs out of new data.\n if ( this.isLoopRunning === false ) {\n this.isLoopRunning = true;\n this._checkSendBuffer(); // Send command to AVR.\n }\n })\n .on( \"check_buffer\" , () => {\n this._checkSendBuffer();\n })\n\n // catch uncaught exception to prevent runtime problems.\n .on(\"uncaughtException\", (err) => {\n this.conChn.emit(\"net_uncaught\", this.avrNum, this.avrName, err);\n });\n }",
"addServerToTracking(name, port, instanceId) {\n // Assign port to used list\n if (!this.inUsePorts.includes(port)) {\n this.inUsePorts.push(port);\n }\n // Clean out exited port if its there\n process.env.exitedProcessPorts = (typeof process.env.exitedProcessPorts ===\n 'string'\n ? process.env.exitedProcessPorts.split(',')\n : process.env.exitedProcessPorts\n )\n .map((port) => parseInt(port, 10))\n .filter((exitedPort) => typeof port === 'number' && exitedPort !== port);\n\n // Check that the server doesnt already exist\n if (Object.prototype.hasOwnProperty.call(this.serviceData, name)) {\n this.serviceData[name] = {\n ...this.serviceData[name],\n socketList: this.serviceData[name].socketList.concat(void 0),\n port: this.serviceData[name].port.concat(port),\n instanceId: this.serviceData[name].instanceId.concat(instanceId),\n process: this.serviceData[name].process.concat(void 0),\n connectionCount: this.serviceData[name].connectionCount.concat(0)\n };\n return true;\n }\n\n // Add the server to the tracking\n this.serviceData[name] = {\n instanceId: [instanceId],\n socketList: [void 0],\n status: false,\n error: false,\n port: [port],\n connectionCount: [0],\n process: [void 0]\n };\n\n // Return\n return true;\n }",
"function subscriber(port,url,conveyorName, robotName, workStationNumber) //subscribing the workstation servers to their cooresponding events\n{\n\t\n\tvar urlToSubscribe = [];\n\turlToSubscribe = getEventsToSubscribe(conveyorName, robotName, workStationNumber);\n\tvar destUrl = \"http://\" + url + \":\" + port + \"/\";\n\t\n\t//SUBSCRIBE to palletLoading,unloading, paperloading,unloading and drawEndExecution................\n\tfor(var i=0;i < urlToSubscribe.length; i++){\n\t\n\t\tvar sub_options =\n\t\t{\n\t\t\t\"method\": \"POST\",\n\t\t\tjson: true,\n\t\t\tbody: {\"destUrl\":destUrl}, //body for subscription as given in the instructions\n\t\t\turl: urlToSubscribe[i],\n\t\t\theaders:\n\t\t\t{\n\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t\"cache-control\": \"no-cache\"\n\t\t\t}\n\t\t};\t\t\n\t\t\t\n\t\tSendSubscriptionRequest(sub_options);\t\n\t\t\n\t}\n\t\n\t\n}",
"function listening_handler() {\n\tconsole.log(`Now Listening on Port ${port}`);\n}",
"sendQueuedRequests() {\n this._startTimer();\n }",
"function listen( client )\n{\n\tclient.emit('welcome' , \"You have established an connection\");\n\tclient.on('login' , serverCommands.VerifyLogin );\n\t\n\tclient.on('re_establish' , \n\t\tfunction( message ) {\n\t\tclientSocketTable[ message.user_name ] = this;\n\t\tconsole.log(\"re-established \" + message.user_name );\n\t});\n\tclient.on('tag_page_request' , serverCommands.serveTagPage );\n\tclient.on('create_login' , serverCommands.VerifyCreate );\n\tclient.on('buy_hash' , serverCommands.serveBuyHash );\n\tclient.on('sell_hash' , serverCommands.serveSellHash );\n\tclient.on('trending_request' , serverCommands.serveTrending );\n\tclient.on('my_investments_request' , serverCommands.serveMyTrending );\n\tclient.on('player_info_request' , serverCommands.servePlayerInfo);\n\tclient.on('leader_request' , serverCommands.serveLeaderBoard );\n client.on('search_username' , serverCommands.serveSearchUser );\n\tclient.on('search_user_email' , serverCommands.serveSearchEmail );\n}",
"run()\n {\n this.httpserver = http.createServer( ( req, res ) =>\n {\n /*\n Gather our body.\n */\n req.on( \"data\", ( chunk ) =>\n {\n if( !( \"collatedbody\" in this ) )\n {\n this.collatedbody = [];\n }\n this.collatedbody.push( chunk );\n } );\n\n req.on( \"end\", () =>\n {\n var urlparts = url.parse( req.url );\n /* Remove the leading '/' */\n var path = urlparts.path.substr( 1 );\n var pathparts = path.split( '/' );\n\n if( req.method in this.handlers && pathparts[ 0 ] in this.handlers[ req.method ] )\n {\n res.writeHead( 200, { \"Content-Length\": \"0\" } );\n this.handlers[ req.method ][ pathparts[ 0 ] ]( pathparts, req, res, Buffer.concat( this.collatedbody ).toString() );\n this.collatedbody = [];\n }\n else\n {\n console.log( \"Unknown method \" + req.method + \":\" + url );\n res.writeHead( 404, { \"Content-Length\": \"0\" } );\n }\n res.end();\n } );\n\n } );\n\n this.httpserver.listen( this.us.port, this.us.host, () =>\n {\n console.log( `Project Control Server is running on ${this.us.host} port ${this.us.port}` );\n } );\n }",
"function onListening() {\n var addr = server.address();\n var bind = typeof addr === 'string'\n ? 'pipe ' + addr\n : 'port ' + addr.port;\n debug('HTTP Listening on ' + bind);\n}",
"function startServer() {\n\troutes.setup(router); //Set the route\n\tapp.listen(port); //Passing port for the server\n\t\n\tconsole.log('\\n Server started \\n Mode: ' + env + ' \\n URL: localhost:' + port);\n}",
"start() {\n const PORT = process.env.PORT || this._config.port; // support heroku\n\n if (!this.isListening) {\n this[_server].listen(PORT, () => {\n this._log.debug(`Running on port ${PORT}`);\n });\n }\n }",
"listen() {\n console.log('--- Listening on localhost:8000 ---');\n this.server.listen(8000);\n }",
"function addServer(server) {\n\n\tvar\n\t\tself = this;\n\n\t// Add server to our list\n\tself._servers.push(server);\n\n\t// Wait for connections\n\tserver.on('connection',function(c){\n\t\tself._serverClients.push(self._newSClient(c));\n\t});\n\n}",
"start(port) {\n this.server.listen(port, 'localhost');\n }",
"function initServer() {\n var options = {\n dataAdapter: new DataAdapter(config.api),\n errorHandler: mw.errorHandler(),\n appData: config.rendrApp\n };\n server = rendr.createServer(app, options);\n}",
"startSocketServer() {\n // Create new socket.io server, listening on a specific path\n this.io = new Server(this.webServer, {\n path: SocketConfig.DEFAULT_PATH\n });\n\n // Setup handlers\n this.io.on('connect', (socket) => {\n logger.debug(`New socket (${socket.id}) connected to server`);\n\n socket.on('disconnect', (reason) => {\n logger.debug(`Socket (${socket.id}) disconnected`);\n });\n });\n }",
"function main() {\n var server = new grpc.Server();\n server.addService(grpc_proto.CrService.service, {insert: insert, get: get, getAll: getAll});\n server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), () => {\n server.start();\n });\n}",
"function runStatusQueryLoop() {\n setInterval(function() {\n queryServerForStatus().\n then(registerServerQuery);\n }, 100);\n}",
"function writeLivestockDatabaseAndServer(id, birthday, color, number, place, created, user, tagged, guid) {\n db.transaction(function (transaction) {\n var executeQuery =\n \"INSERT INTO livestock (id, birthday, color, number, place, created, user, tagged, guid) VALUES (?,?,?,?,?,?,?,?,?)\";\n transaction.executeSql(executeQuery, [id, birthday, color, number, place, created, user, tagged, guid],\n function (tx, result) {\n //if data is successfully stored in DB and Networkconnection is valid --> write Data to Server DB\n if (networkConnection == true) {\n RESTAddLivestock(birthday, color, number, place, created, email, guid)\n }\n },\n function (error) {\n alert('Error: ' + error.message + ' code: ' + error.code);\n });\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check to see if all values are below or equal the limit if they are return true example [1,2,3],3 return true | function smallEnough(a, limit){
// const isBelowThreshold = (currentValue) => currentValue < limit;
return a.every(currentValue => currentValue <= limit)
} | [
"hasReachedMaxLimit (list, maxLimit) {\n\t\treturn list && list.length === maxLimit;\n\t}",
"function check(min, max, target) {\n if (target > min && target < max) {\n return true;\n \n } else {\n \n return false;\n }\n}",
"function checkFieldEnumLength(field, limit)\n{\n\tsequences = field.value.split(\",\");\n\n\tfor (var i = 0; i < sequences.length; i++) \n\t{\n\t\tintervals = sequences[i].split(\"-\");\n\n\t\tfor (var j = 0; j < intervals.length; j++) \n\t\t{\n\t\t\tif (intervals[j].length > limit)\n\t\t\t{\n\t\t\t\talert(\"Il valore specificato eccede la lunghezza del campo\");\n\t\t\t\tfield.focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\t\t\t\n\t}\n\t\n\treturn true;\n}",
"function valueInBounds(v, [min, max]) {\n return v >= min && (max === undefined || v <= max);\n }",
"function boundary(N) {\n // if(N > 20 && N <= 100) {\n // return true\n // }\n // if(N === 400) {\n // return true\n // }\n // else {\n // return false;\n // }\n\n if ((N > 20 && N <= 100) || N === 400) {\n return true;\n } else {\n return false;\n }\n}",
"function arrayLessThan100(arr) {\n\treturn arr.reduce((x, i) => x + i) < 100;\n}",
"_checkRateLimit (ts: number, limit: number, rates: number[]) {\n rates.push(ts)\n let edge = rates.find((d) => ts - 1000 < d)\n if (edge) rates.splice(0, rates.indexOf(edge))\n return rates.length <= limit\n }",
"function passOrFail(array) {\n // let pass = false;\n // if (array >= 75) {\n // pass = true;\n // }\n let pass = array.map((x) => x >= 75);\n return pass;\n}",
"function controlloRangeNumeri(min, max, number) {\n var result = false;\n if (number >= min && number <= max) {\n result = true;\n }\n return result;\n }",
"function checkEvery(arr) {\n return arr.every(v => v % 3 == 0 )\n}",
"function areNumbersInRange(puzzle) {\n for (var i = 0; i < puzzle.length; i++) {\n if (puzzle[i] < 0 || puzzle[i] > 9) {\n return false;\n }\n }\n return true;\n }",
"static evalReadingLengthWithinLimit(dict, limit) {\n return (dict.ReadingSim.toString().length <= Number(limit));\n }",
"function validPickCount()\n {\n $scope.maxPicksReached1 = false;\n $scope.maxPicksReached2 = false;\n $scope.maxPicksReached3 = false;\n $scope.maxPicksReached4 = false;\n $scope.maxPicksReached5 = false;\n var returnVal = true;\n var valid = true;\n var hist = {};\n\n //check against max pick count\n $scope.displayedCollection.map(function (m)\n {\n m.ui_picks.map(function (a) {\n\n if (a.confidence_value == null)\n return;\n\n if (a.confidence_value in hist) {\n hist[a.confidence_value]++;\n if (hist[a.confidence_value] == $scope.detailsScope.detailsObject.max_pick_count) {\n\n switch (a.confidence_value) {\n case 1:\n $scope.maxPicksReached1 = true;\n break;\n case 2:\n $scope.maxPicksReached2 = true;\n break;\n case 3:\n $scope.maxPicksReached3 = true;\n break;\n case 4:\n $scope.maxPicksReached4 = true;\n break;\n case 5:\n $scope.maxPicksReached5 = true;\n break;\n }\n }\n\n if (hist[a.confidence_value] > $scope.detailsScope.detailsObject.max_pick_count) {\n returnVal = false;\n }\n\n }\n else {\n hist[a.confidence_value] = 1;\n } \n\n \n });\n });\n\n return returnVal;\n }",
"function checkDealerHits(){\n if(0 == dealerTotal[1]){\n if(17 > dealerTotal[0]){\n return true;\n }\n return false;\n }else{\n if(17 > dealerTotal[0] && 17 > dealerTotal[1]){\n return true;\n }\n } \n}",
"function between(i, min, max) {//check if int provided is within provided range. https://alvinalexander.com/java/java-method-integer-is-between-a-range\n if (i >= min && i <= max) {\n return true;\n } else {\n return false;\n }\n}",
"function checkForDecimal(arr) {\n return arr.length === new Set(arr).size;\n }",
"function checkRunOf3(arr) {\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tvar v = arr[i];\n\t\tif (i == 0 || v != lastVal)\n\t\t{\n\t\t\tvar run = 1;\n\t\t\tvar lastVal = v;\n\t\t}\n\t\telse\n\t\t{\n\t\t\trun++;\n\t\t\tif (run>=3) return true;\n\t\t}\n\t}\n\treturn false;\n}",
"function under50(num) {\n return num < 50;\n}",
"function checkRange(input) {\n //checks integer range values for min/max order\n if (input < 0) {\n return true;\n }\n //converts every input into a String\n let stringTest = input.toString();\n // Take their input and split it at the '-' (hyphen mark)\n // numbers variable will then look like this\n // numbers = ['value1', 'value2']\n let numbers = stringTest.split(\"-\");\n //removes empty strings in array (caused by edge case of negative min to max range ex: \"-100-300\")\n let filterednumbers = numbers.filter((item) => item);\n // parseFloat parses argument and returns floating point number, then point numbers are compared using the < (less than) mathematical symbol\n // Because we are using the < in the return, this will only return a true or false based off the values.\n return parseFloat(filterednumbers[0]) < parseFloat(filterednumbers[1]);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return node at given index return node at given index | getNodeAtIndex(index) {
//if index is not within list return null
if (index >= this.length || index < 0) return null;
//iterate through nodes until finding the one at index
let currentNode = this.head;
let currentIndex = 0;
while (currentIndex !== index) {
currentNode = currentNode.next;
currentIndex++;
}
return currentNode;
} | [
"getNode(index){\n\t\t//check in hidden nodes\n\t\tfor (var i = 0; i < this.hiddenNodes.length; i++){\n\t\t\tif (this.hiddenNodes[i].index == index){\n\t\t\t\treturn this.hiddenNodes[i]\n\t\t\t}\n\t\t}\n\n\t\t//check input nodes\n\t\tfor (var i = 0; i < this.inputNodes.length; i++){\n\t\t\tif (this.inputNodes[i].index == index){\n\t\t\t\treturn this.inputNodes[i]\n\t\t\t}\n\t\t}\n\n\t\t//check output nodes\n\t\tfor (var i = 0; i < this.outputNodes.length; i++){\n\t\t\tif (this.outputNodes[i].index == index){\n\t\t\t\treturn this.outputNodes[i]\n\t\t\t}\n\t\t}\n\n\t\t//not found\n\t\treturn -1\n\t}",
"get(index) {\n let foundNode = this._find(index);\n return foundNode ? foundNode.value : undefined;\n }",
"_getNode(idx) {\n let currentNode = this.head;\n let count = 0;\n\n while (currentNode !== null && count !== idx) {\n currentNode = currentNode.next;\n count++;\n }\n return currentNode;\n }",
"traverseToIndex(index) {\n let counter = 1;\n let currentNode = this.head;\n\n while (counter !== index) {\n currentNode = currentNode.next;\n counter++;\n }\n\n return currentNode;\n }",
"getAt(idx) {\n try {\n if (idx >= this.length || idx < 0) throw new Error('Index is invalid!');\n return this._getNode(idx).val;\n } catch (e) {\n console.warn(e);\n }\n }",
"get(index){\n // return the value of an element at given index\n return memory.get(index);\n }",
"function grabNode(id) {\n return nodesData[id];\n }",
"function findObject(index) {\n return repository[index];\n }",
"get(nodeId) {\n if (nodeId) {\n var node = this.db.database.get(nodeId)\n if (node.length === 1) {\n return node[0]\n }\n }\n }",
"getNode(name) {\n return this.nodes.find((n) => n.name === name) || null;\n }",
"child(root, index) {\n if (Text.isText(root)) {\n throw new Error(\"Cannot get the child of a text node: \".concat(JSON.stringify(root)));\n }\n\n var c = root.children[index];\n\n if (c == null) {\n throw new Error(\"Cannot get child at index `\".concat(index, \"` in node: \").concat(JSON.stringify(root)));\n }\n\n return c;\n }",
"function findNode(label, nodes){\n\tfor (var i = 0; i < nodes.length; i++){\n\t\t//console.log(nodes[i].label,label, nodes[i].label == label);\n\t\tif (nodes[i].label == label) {\n\t\t\treturn nodes[i];\n\t\t}\n\t} \n}",
"function _nodeIndex(node) {\n\t\t// \n\t\tif (!node.parentNode) return 0;\n\t\t// \n\t\tvar nodes = node.parentNode.childNodes,\n\t\t\tindex = 0;\n\t\t// \n\t\twhile (node != nodes[index]) ++index;\n\t\t// \n\t\treturn index;\n\t}",
"function getFilteredWordEntry(index)\n{\n\tvar nodes = filteredWordsContainer.childNodes;\n\treturn nodes[index];\n}",
"function get_xml_node(which_doc, which_id){\r\n\ttry {\r\n\t\treturn which_doc.getElementsByTagName(which_id)[0];\r\n\t}\r\n\tcatch(err) {\r\n\t\treturn null;\r\n\t}\r\n}",
"readDataByIndex(index) {\n return this.content[index];\n }",
"visitIndex_expr(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function getCloneElement(arr, index) {\n return Object.assign({}, arr[index]);\n}",
"findNode(number) {\n for (let layer = 0; layer < this.nodes.length; layer++) {\n for (let node = 0; node < this.nodes[layer].length; node++) {\n if (this.nodes[layer][node].number === number)\n return this.nodes[layer][node];\n }\n }\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get exist of end | getIsExistEnd() {
return this.state.schedule.find((item) => item.status == "end") ? true : false;
} | [
"eof() {\n return this.index >= this.tokens.length;\n }",
"function MarkerExist (dStart) : boolean {\n var fmarkerEnum = new Enumerator(Vegas.Project.Markers);\n while (!fmarkerEnum.atEnd()) {\n var fMyMarker = fmarkerEnum.item();\n var fMarkerStart = fMyMarker.Position.ToMilliseconds();\n if ( dStart == fMarkerStart ) {\n return 1;\n }\n fmarkerEnum.moveNext();\n } // End while fmarkerEnum\n return 0;\n}",
"end() {\n\t\treturn this.prog.length === 0;\n\t}",
"isEnd(editor, point, at) {\n var end = Editor.end(editor, at);\n return Point.equals(point, end);\n }",
"function isLastPage() {\n if (currPage + 1 == currMsg.msg.length)\n return true;\n return false;\n}",
"get isLastEntityConsumer () {\n if (this.entities.length > 0) {\n let lastEntity = this.entities[this.entities.length - 1];\n return lastEntity instanceof operators.FunctionCall ? true : !operators.isOperator(lastEntity);\n } else {\n return false;\n }\n }",
"isEOF() {\n return this._index >= this.input.length;\n }",
"has_next_frame() {\n if(this.frame_idx >= this.frames.length-1) return false;\n else return true;\n }",
"exists() {\n return this.element ? true : false;\n }",
"get end() {\n return this.endMarker;\n }",
"endsAt(path, another) {\n var i = path.length;\n var as = path.slice(0, i);\n var bs = another.slice(0, i);\n return Path.equals(as, bs);\n }",
"function matchLastItem(arr) {\n\tlet a = ''\n\tfor (let i = 0; i < arr.length - 1; i++) {\n\t\ta += arr[i];\n\t}\n\treturn a === arr[arr.length - 1];\n}",
"isLastRow(): boolean {\n return this.getRowIndex() === this.getHeight() - 1;\n }",
"function listHas(head, value){\n let result = false\n if (!head){\n result = `The list is empty`\n } else {\n while (head){\n if (head.val == value){\n result = true\n break\n }\n head = head.next\n }\n }\n return result\n}",
"function CheckUrlEnd(checkUrl){\r\n var path = window.location.pathname;\r\n var pathSplit = path.split(\"/\");\r\n var urlEnd = pathSplit[pathSplit.length - 1];\r\n\r\n if(urlEnd == checkUrl){\r\n return true;\r\n }\r\n\r\n return false;\r\n}",
"function last(){\n\tvar isi = \"saya beajar di rumah beajar\";\n\tconsole.log(isi.lastIndexOf(\"beajar\",5)); //nilai angka berfungsi sebagai startnya di index\n}",
"function startend(){\n\tvar aku = 'saya belajar di pasar';\n\tconsole.log(aku.startsWith(\"saya\"));\n\tconsole.log(aku.endsWith(\"di\"));\n\t}",
"checkStaffNum(id){\n for (let index = 0; index < this._staffNum.length; index++) {\n if (this._staffNum[index] == id) {\n return id;\n }\n\n }\n //this RETURN is ouside the for loop so the method does not return is the condition returns false\n return 0;\n \n }",
"async existsInDB() {\n let result = {\n dataValues: null\n };\n try {\n const tmpResult = await db.appModel.findOne({\n where: {\n appId: this.appId\n }\n });\n\n if (tmpResult) {\n result = tmpResult;\n this.setApp(result.dataValues);\n return true;\n }\n } catch (err) {\n new ErrorInfo({\n appId: this.appId,\n message: err.message,\n func: this.existsInDB.name,\n file: constants.SRC_FILES_NAMES.APP\n }).addToDB();\n }\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload ssh to github | async function uploadGitHubSSH(config) {
// Get root user path
let rootPath = Constants.rootUserPath();
// Log uploading public ssh key to github
Log.spacer();
Log.info('Uploading public SSH key to GitHub...');
// Get public key from file
let key = await Files.load(`${rootPath}.ssh/jarvis-github-${config.username}.pub`);
// Format data for curl request
let data = {
title: config.githubKeyTitle,
key: key
};
data = JSON.stringify(data);
// Upload
const { stdout, stderr } = await exec(`curl -u "${config.username}:${config.personalAccessToken}" --data '${data}' https://api.github.com/user/keys`);
// Check that the key was uploaded
if (stdout.includes("created_at")) {
Log.success('Uploaded public SSH key to GitHub');
// Convert the response to json so that we can get the id
let response = JSON.parse(stdout);
return response.id;
} else {
Log.error('Error uploading public SSH key to GitHub');
throw stdout;
}
} | [
"async function migrate() {\n\n github.authenticate({\n type: \"token\",\n token: settings.github.token\n });\n\n //\n // Sequentially transfer repo things\n //\n\n // transfer GitLab milestones to GitHub\n if (program.milestone) {\n await transferMilestones(settings.gitlab.projectId);\n }\n\n // transfer GitLab labels to GitHub\n if (program.label) {\n await transferLabels(settings.gitlab.projectId, true, settings.conversion.useLowerCaseLabels);\n }\n\n // Transfer issues with their comments; do this before transferring the merge requests\n if (program.issue) {\n await transferIssues(settings.github.owner, settings.github.repo, settings.gitlab.projectId);\n }\n\n if (program.mergerequest) {\n if (settings.mergeRequests.log) {\n // log merge requests\n await logMergeRequests(settings.gitlab.projectId, settings.mergeRequests.logFile);\n } else {\n await transferMergeRequests(settings.github.owner, settings.github.repo, settings.gitlab.projectId);\n }\n }\n\n console.log(\"\\n\\nTransfer complete!\\n\\n\");\n}",
"function updateGitRepo () {\n var cmd = 'git add ' + papersDir + '&& git commit -m \"Adding papers\" && git push';\n\n exec(cmd, function (error, stdout, stderr) {\n console.log(stdout);\n });\n}",
"async function migrate() {\n githubApi.authenticate({\n type: 'token',\n token: settings.github.token,\n });\n\n //\n // Sequentially transfer repo things\n //\n\n try {\n // transfer GitLab milestones to GitHub\n await transferMilestones();\n\n // transfer GitLab labels to GitHub\n await transferLabels(true, settings.conversion.useLowerCaseLabels);\n\n // Transfer issues with their comments; do this before transferring the merge requests\n await transferIssues();\n\n if (settings.mergeRequests.log) {\n // log merge requests\n await logMergeRequests(settings.mergeRequests.logFile);\n } else {\n await transferMergeRequests();\n }\n } catch (err) {\n console.error('Error during transfer:');\n console.error(err);\n }\n\n console.log('\\n\\nTransfer complete!\\n\\n');\n}",
"function upload(options, git_data) {\n\tvar rsync = new Rsync();\n\n\t// glob files\n\tglob(package_files, {\n\t\tabsolute: true\n\t}, function(error, files) {\n\t\tvar dest, path;\n\n\t\tif (error) throw error;\n\n\t\tconsole.log(chalk.green('Uploading ' + files.length + ' packages to ' + options.host + '...'));\n\n\t\tpath = options.path + '/' + options.package_name + '/' + git_data.branch + '/' + git_data.tag;\n\t\tdest = (options.user ? options.user + '@' : '') +\n\t\t\toptions.host + ':' + path;\n\n\t\trsync\n\t\t\t.flags('z')\n\t\t\t.set('rsync-path', 'mkdir -p ' + path + ' && rsync')\n\t\t\t.source(files)\n\t\t\t.destination(dest);\n\n\t\trsync.execute(function(error, code, cmd) {\n\t\t\tif (error) {\n\t\t\t\tconsole.error('Rsync error: ' + error.message + ' ' + cmd);\n\t\t\t\tprocess.exit(code);\n\t\t\t}\n\t\t});\n\t});\n}",
"async function addGitRemoteOrigin(config) {\n\n\t// Log adding remote origin\n\tLog.spacer();\n\tLog.info('Adding git remote origin...');\n\n\t// Add remote origin\n\tconst { stdout, stderr } = await exec(`git remote add origin https://github.com/${config.username}/${config.repo}.git`);\n\n\t// Check for errors\n\tif (stderr) {\n\t\tthrow stderr;\n\t} else {\n\t\tLog.success('Added git remote origin');\n\t}\n\n}",
"async function addNewSSHConfig(config) {\n\n\t// Get root user path\n\tlet rootPath = Constants.rootUserPath();\n\n\t// Create ssh folder\n\tawait createSSHFolder(rootPath);\n\n\t// Generate ssh keys\n\tawait generateSSHKeys(rootPath, config);\n\n\t// Update ssh config\n\tawait updateSSHConfig(rootPath, config);\n\n}",
"postV3ProjectsIdShare(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdShare(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"async function deleteGitHubSSH(config) {\n\n\t// Log deleting ssh key from github\n\tLog.spacer();\n\tLog.info('Deleting public SSH key from GitHub...');\n\n\t// Delete\n\tconst { stdout, stderr } = await exec(`curl -u \"${config.username}:${config.personalAccessToken}\" -X \"DELETE\" https://api.github.com/user/keys/${config.githubKeyId}`);\n\n\t// Check that the key was deleted\n\tif (stdout === '') {\n\t\tLog.success('Deleted public SSH key from GitHub');\n\t} else {\n\t\tLog.error('Error deleting public SSH key from GitHub');\n\t\tthrow stdout;\n\t}\n\n}",
"putV3ProjectsIdServicesPushover(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = 56;*/ // Number |\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.putV3ProjectsIdServicesPushover(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"putV3ProjectsIdRepositoryFiles(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The project I\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.putV3ProjectsIdRepositoryFiles(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"postV3ProjectsIdStatusesSha(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | The commit has\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdStatusesSha(incomingOptions.id, incomingOptions.sha, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdRepositoryCommitsShaComments(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | The commit's SH\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryCommitsShaComments(incomingOptions.id, incomingOptions.sha, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"putV3ProjectsIdServicesFlowdock(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = 56;*/ // Number |\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.putV3ProjectsIdServicesFlowdock(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"postV3ProjectsIdRepositoryCommitsShaCherryPick(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | A commit sha to be cherry picke\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryCommitsShaCherryPick(incomingOptions.id, incomingOptions.sha, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdUploads(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdUploads(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"putV3ProjectsIdRepositoryTagsTagNameRelease(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let tagName = \"tagName_example\";*/ // String | The name of the ta\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.putV3ProjectsIdRepositoryTagsTagNameRelease(incomingOptions.id, incomingOptions.tagName, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdIssuesIssueIdMove(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let issueId = 56;*/ // Number | The ID of a project issu\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdIssuesIssueIdMove(incomingOptions.id, incomingOptions.issueId, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"putV3ProjectsIdServicesMattermost(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = 56;*/ // Number |\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.putV3ProjectsIdServicesMattermost(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"postV3ProjectsForkId(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let opts = {\n 'UNKNOWN_BASE_TYPE': new Gitlab.UNKNOWN_BASE_TYPE() // UNKNOWN_BASE_TYPE | \n};*/\napiInstance.postV3ProjectsForkId(incomingOptions.id, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: setBranchComplete Sets a branch's isComplete property to true Parameters: branchInfo Object, with properties id, trigger, and isComplete Dependencies: , Returns: none Change Log: 2013.01.27ALP Initial version | function setBranchComplete(branchInfo) {
branchInfo.isComplete = true;
} | [
"function allBranchesComplete(bsp) {\n\tvar isComplete = true;\n\t// If all branches are required\n\tif (shell.branchStartPages.BSPReqArray[bsp]) {\n\t\tif (shell.branchStartPages.BSPArray[bsp] != undefined) {\n\t\t\tfor (var i=0, j = shell.branchStartPages.BSPArray[bsp].length; i<j; i++) {\n\t\t\t\t//console.log(\"branch \" + i + \" is complete? \" + \tshell.branchStartPages.BSPArray[bsp][i][2]);\n\t\t\t\tif (!shell.branchStartPages.BSPArray[bsp][i].isComplete) {\n\t\t\t\t\tisComplete = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\t}\n\treturn isComplete;\n}",
"function markGoalComplete() {\n\t\tprops.markGoalComplete(props.goalId);\n }",
"function storeNewBranch(id, trigger) {\n\tvar BSPArray = shell.branchStartPages.BSPArray[shell.currPageId];\n\tBSPArray[BSPArray.length] = new Object();\n\tBSPArray[BSPArray.length-1].id = id;\n\tBSPArray[BSPArray.length-1].trigger = trigger;\n\tBSPArray[BSPArray.length-1].isComplete = false;\n\t//console.log(BSPArray);\n}",
"function goToBranch(branchInfo) {\n\tloadPage(branchInfo.id);\n\tsetBranchComplete(branchInfo);\n\treturn false;\t\n}",
"function populateBranch()\n {\n var lstrDlrCode = document.forms[0].dealer.value;\n var lstrBlankFlag=arguments[0] ;\n // dealerBranch - a hidden combo\n comboDealerBranch = eval(document.forms[0].dealerBranch);\n comboBranch = eval(document.forms[0].branch);\n for(lintI=0; lintI < comboBranch.length; lintI++)\n {\n document.forms[0].branch.options[lintI] = null;\n lintI = -1;\n }\n\n //Enter default record\n if(lstrBlankFlag != null && lstrBlankFlag!=\"\" && lstrBlankFlag==\"YES\" ){\n document.forms[0].branch.options[document.forms[0].branch.options.length] = new Option(\" \", \"\");\n }else{\n document.forms[0].branch.options[document.forms[0].branch.options.length] = new Option(document.AppJsp.allLabel.value, \"\");\n }\n for(lintI=0; lintI < comboDealerBranch.length; lintI++)\n {\n var opt= document.forms[0].dealerBranch[lintI].text;\n var value= document.forms[0].dealerBranch[lintI].value;\n\n var lintPos = value.indexOf(\"~\");\n if (lintPos > -1)\n {\n var brcCode = value.substring(0, 2);\n var dlrCode = value.substring(3);\n if(dlrCode == lstrDlrCode || dlrCode == '')\n {\n with(document.forms[0].branch)\n {\n options[options.length] = new Option(opt, brcCode);\n }\n }\n }\n /*else\n {\n document.forms[0].branch.options[document.forms[0].branch.options.length] = new Option(document.AppJsp.allLabel.value, \"\");\n }*/\n }\n }",
"function launchBranchJourney() {\n var linkData = {\n campaign: \"campaign cannot be changed\",\n feature: \"feature cannot be changed\",\n channel: \"channel was changed by javascript\",\n stage: \"stage was changed by javascript\",\n tags: [\"tag was changed by javascript\"],\n data: {\n custom_bool: true,\n \"custom_int (todays date)\": Date.now(),\n \"custom_string (url)\": window.location.href,\n $journeys_icon_image_url:\n \"https://www.valorebooks.com/campus-life/wp-content/uploads/icon_340.png\",\n $journeys_button_get_no_app: \"changed!\",\n $journeys_button_get_has_app: \"changed!\",\n $journeys_description: \"Description reset by button click\",\n },\n };\n branch.setBranchViewData(linkData);\n //function to launch journey with flags to disable banner animations\n branch.track(\n \"pageview\",\n {},\n { disable_entry_animation: true, disable_exit_animation: true }\n );\n}",
"function bluesnapSetFieldStatus(tagId, status) {\n switch (tagId) {\n case 'ccn':\n isCardNumberComplete = status;\n\n case 'exp':\n isExpiryComplete = status;\n\n case 'cvv':\n isCVVComplete = status;\n }\n }",
"function addToBranch(branch, value, key = null, thenCallback = null) {\n let database = firebase.database();\n\n // Get a key for that object (for storing in\n // Firebase much like an ID I guess...?)\n if (key === null) {\n key = database.ref()\n .child(branch).push().key;\n }\n\n // Assign that object to a database entry thing\n let entry = {};\n entry[`/${branch}/` + key] = value;\n\n // And submit it to Firebase\n let result = database.ref().update(entry);\n console.log(`[INFO] Content added to '${branch}/${key}' branch: ${result}`);\n\n // If a then callback is specified, do it now\n result.then(thenCallback);\n}",
"markComponentAsComplete(component) {\n // Create a component_progress object for this component to indicate completion\n const path = APIRoutes.createComponentProgressPath(component.id)\n\n const componentParams = {\n component_progress: {\n component_id: component.id,\n student_id: getUser().id\n }\n }\n\n request.post(path, componentParams, (response) => {\n // Mark displayedComponent as complete\n const component = this.state.displayedComponent\n component.is_complete = true\n\n // Update displayedSubsection's components and current_component based on response\n const subsection = this.state.displayedSubsection\n subsection.components = response.components\n subsection.current_component = response.current_component\n\n const courseSidebar = this.state.courseSidebar\n const section = courseSidebar.sections[this.state.displayedSection.position - 1]\n\n // If displayedSubsection is complete, mark it and update the sidebar with the next current_subsection\n if (response.is_complete) {\n subsection.is_complete = true\n\n const nextSubsection = this.getNextSubsection(section, subsection)\n courseSidebar.current_subsection = nextSubsection\n }\n\n section.subsections[this.state.displayedSubsection.position - 1] = subsection\n courseSidebar.sections[this.state.displayedSection.position - 1] = section\n\n this.setState({\n displayedComponent: component,\n displayedSubsection: subsection,\n courseSidebar: courseSidebar,\n })\n\n }, (error) => {\n console.log(error)\n })\n }",
"async createOrUpdateBranchFromFileMap(fileMap, config) {\n const baseBranchRef = `heads/${config.baseBranchName}`;\n const branchRef = `heads/${config.branchName}`;\n const baseSha = await this.getBaseShaForNewBranch(baseBranchRef);\n const tree = await this.createTree(fileMap, baseSha);\n const commit = await this.api.git.createCommit({\n ...this.userInfo,\n message: config.message,\n tree: tree.sha,\n parents: [baseSha],\n });\n return this.updateOrCreateReference(commit.data.sha, branchRef);\n }",
"function completeAction(email, ref, completeButton) { \n\tif (completeButton.innerHTML == \"Complete\") {\n\t\tvar user = ref.child(email);\n\t\tuser.once(\"value\", function(snapshot) {\n\t\t\tvar endTime = calculateETA(0);\n\t\t\tvar ts = snapshot.val().timestamp\n\t\t\tuser.update({\"endTime\" : endTime});\n\t\t\tvar completed = firebase.database().ref().child(\"COMPLETED RIDES\");\n\t\t\tcompleted.child(email + \"_\" + ts).set({\n\t\t\t\temail: snapshot.val().email,\n\t\t\t\tend: snapshot.val().end,\n\t\t\t\tendTime: endTime,\n\t\t\t\teta: snapshot.val().eta,\n\t\t\t\tnumRiders: snapshot.val().numRiders,\n\t\t\t\tstart: snapshot.val().start,\n\t\t\t\ttime: snapshot.val().time,\n\t\t\t\ttimestamp: ts,\n\t\t\t\twaitTime: snapshot.val().waitTime,\n\t\t\t\tvehicle: snapshot.val().vehicle,\n\t\t\t});\n\t\t\tuser.remove();\n\t\t});\n\t} else {\n\t\tvar user = ref.child(email);\n\t\tuser.update({\"eta\" : \"update\"});\n\t\tuser.update({\"eta\" : \"Picked Up\", \"etaTimestamp\" : 0});\n\t}\n}",
"function gitBranch(args, repo) {\n if (args.length === 0) {\n return Object.keys(repo.branches).map((x) => {\n if (x === repo.activeBranch) {\n return `<li class=\"active\">${x}</li>`;\n }\n return `<li>${x}</li>`;\n }).reduce((p, c) => {\n return p.concat(c);\n }, `<div>Branches:</div><ul>`).concat(\"</ul>\");\n }\n\n if (args.length === 1) {\n if (args[0].startsWith(\"-\")) {\n if (args[0] === \"-vv\") {\n return Object.keys(repo.branches).map((x) => {\n if (x === repo.activeBranch) {\n return `<li class=\"active\">${x} [origin/${x}]</li>`;\n }\n return `<li>${x} [origin/${x}]</li>`;\n }).reduce((p, c) => {\n return p.concat(c);\n }, `<ul>`).concat(\"</ul>\");\n }\n } else {\n repo.createBranch(args[0]);\n return `Created Branch To ${args[0]}`;\n }\n }\n\n throw new Error(\"Unsupported Arguments\");\n}",
"function pollComplete(id, cb){\n var now = new Date\n \n Poll.findByIdAndUpdate(id, { active: false, dateCompleted: now }, function(err, poll){\n if (err) {\n if (cb) cb(err)\n return\n }\n console.log('Completed Poll: ' + poll);\n if (cb) cb(err)\n });\n}",
"function markGoalActive() {\n\t\tprops.markGoalActive(props.goalId);\n\t}",
"function parseBranch(branch_info,callback) {\n var branch_split_idx = branch_info.indexOf(BRANCH_MARKER);\n if(branch_split_idx === -1) {\n return callback(\"Log entry missing branch marker \"+BRANCH_MARKER+ \" on log entry \"+branch_info);\n }\n\n var branch_split = branch_info.substring(branch_split_idx + BRANCH_MARKER.length).trim();\n if(!branch_split) {\n return callback(branchParseFail(branch_info , \"No branch delimiter found\"));\n }\n var remote_split_idx = branch_split.indexOf(\"/\");\n if(remote_split_idx === -1) {\n return callback(branchParseFail(branch_info ,\"No remote branch split found\"));\n }\n\n var git_remote = branch_split.substring(0,remote_split_idx);\n var git_branch = branch_split.substring(remote_split_idx + 1);\n if(!git_remote || !git_branch) {\n return callback(branchParseFail(branch_info ,\"Unable to parse out remote and branch\"));\n }\n\n // Wrap up the parse info for easy consumption\n var branch = {\n git_remote:git_remote,\n git_branch:git_branch,\n branch_info:branch_info\n }\n\n callback(null,branch);\n}",
"get isCompleteUpdate() {\n // XXX: Bug 514040: _ums.isCompleteUpdate doesn't work at the moment\n if (this.activeUpdate.patchCount > 1) {\n var patch1 = this.activeUpdate.getPatchAt(0);\n var patch2 = this.activeUpdate.getPatchAt(1);\n\n return (patch1.URL == patch2.URL);\n } else {\n return (this.activeUpdate.getPatchAt(0).type == \"complete\");\n }\n }",
"function setBranchMarkers(branch) {\n const branchLatlng = new google.maps.LatLng(\n branch.latlng[0],\n branch.latlng[1],\n ); // eslint-disable-line no-undef\n const marker = new google.maps.Marker({\n // eslint-disable-line no-undef\n position: branchLatlng,\n icon: '/static/images/map-marker.png',\n });\n marker.setMap(branchMap);\n }",
"function toggleComplete(taskName) {\n var task = TaskListNamespace.taskList.tasks[taskName];\n var calendar = TaskListNamespace.cal;\n\n var p = new promise.Promise();\n task.completed = !task.completed;\n\n var req = {\n 'calendarId': calendar.id,\n 'eventId': task.id\n },\n ev = {\n 'summary': task.name,\n 'description': window.btoa(JSON.stringify(task)),\n 'start': { 'dateTime' : task.start },\n 'end': { 'dateTime' : task.end }\n };\n\n req.resource = ev;\n\n console.log('Send req to flip completed bit');\n gapi.client.calendar.events.update(req).execute(function(x) {\n console.log('Toggled completed bit');\n p.done(false, x);\n });\n\n return p;\n}",
"async complete(result = \"unknown\") {\n if (!PaymentCompleteEnum.includes(result)) {\n throw new TypeError(\"Invalid argument value: \" + result);\n }\n if (this[_complete]) {\n throw new DOMException(\"Response already completed\", \"InvalidStateError\");\n }\n this[_complete] = true;\n await paymentSheet.requestClose(result);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch input and store Username to local storage for personalizer + user validator | function storeName() {
const formWrapper = document.getElementById("personalizer");
const username = document
.querySelector('[name="username"]')
.value.trim()
.toUpperCase();
if (username === "") {
validationError('[name="username"]', formWrapper);
} else {
validationError('[name="username"]', formWrapper, false);
localStorage.setItem("username", username);
personalizer();
}
} | [
"function userData() {\n\n userName = $('#username').val()\n sessionStorage.setItem(\"userName\", userName)\n if ((fillUserName = null) || (fillUserName = \"\")) { //if player doesn't enter any username or saves username without entering anything\n sessionStorage.setItem(\"\", userName);\n }\n}",
"function getUsername() {\n let userName = document.getElementById('username_input_field').value;\n\n // if username supplied is invalid, alert user, and return null\n const validUsernameRegExp = new RegExp('^([a-zA-Z0-9_-]{3,16})$');\n if (!validUsernameRegExp.test(userName)) {\n alert('Your username can only contain alphanumeric, '\n + ' underscore, and hyphen characters (a-z A-Z 0-9 _ -). '\n + 'It should be at least 3 characters long.');\n return null;\n }\n\n // store username for next time\n setToLocalStorage(userNameKey, userName);\n\n return userName;\n}",
"function saveName() {\n\tlocalStorage.setItem('receivedName', userName)\n}",
"function save_user() {\n var user = document.getElementById(\"username\").value;\n //check that a username was inputted \n if (!user || (user.trim()).length == 0) {\n document.getElementById(\"username\").value = \"\";\n alert('No username specified.');\n return;\n }\n if (user.length>10){\n document.getElementById(\"username\").value = \"\";\n alert(\"Username exceeded 10 characters.\")\n return;\n }\n //if there is a username, save to chrome.storage\n chrome.storage.sync.set({\"user\": user}, function() {\n message('Username saved and updated.');\n });\n document.getElementById(\"username\").placeholder = \"Current Username: \" + user;\n document.getElementById(\"username\").value = \"\";\n }",
"function handleUsername() {\r\n\r\n // we extract the last.fm username from the form\r\n const username = document.forms.enterUsername.elements.username.value;\r\n\r\n // we first check if the username field is empty\r\n if (username === '') {\r\n alert('Please enter a last.fm username');\r\n // if not, we can begin the search\r\n } else {\r\n\r\n // we first remove the search settings form from the screen\r\n document.getElementById('enterUsername').style.display = 'none';\r\n\r\n // and now retrieve this user's last.fm friends' names\r\n getFriends(username);\r\n }\r\n}",
"function loadName() {\n const currentUser = localStorage.getItem(USER_LS);\n if (currentUser === null) {\n askForName();\n } else {\n paintGreeting(currentUser);\n }\n}",
"function makeUser(usernameInput) {\n const username = usernameInput.value;\n const UserObject = {\n name: username,\n wallet: 75,\n };\n\n return UserObject;\n\n}",
"function saveUsersName(text) {\n localStorage.setItem(USERS_LS, text);\n}",
"function onAddUsername() {\n if (self.usernameModel !== undefined) {\n //Add the username to the indexedDb database\n TransactionFactory.updateDataByKeyWithPromise(modelDatabaseObject, modelObjectStoreObject,\n modelIndecesObject, self.usernameModel)\n .then(function () {\n //Get the new list of users and repopulate the username dropdown\n Usernames.getAll(modelDatabaseObject, modelObjectStoreObject, modelIndecesObject).then(function (usernames) {\n var field;\n field = FormlyHelper.getFieldInFieldGroup(self.activeUsernameFields, 'userId');\n field.templateOptions.options = usernames;\n return usernames;\n });\n });\n }\n }",
"function loadLoginData () {\n let savedUsername = config.get('username')\n let savedPassword = config.get('password')\n let savedRememberUsername = config.get('rememberUsername')\n let savedRememberPassword = config.get('rememberPassword')\n\n document.querySelector('#login-remember-name').checked = savedRememberUsername\n document.querySelector('#login-remember-password').checked = savedRememberPassword\n\n if (savedUsername) {\n document.querySelector('#login-name').value = savedUsername\n }\n\n if (savedPassword) {\n document.querySelector('#login-password').value = decrypt(savedPassword)\n }\n}",
"function submitUsername() {\n\tvar newUsername = document.getElementById(\"newUsername\").value;\n\tvar newUsernameConfirm = document.getElementById(\"newUsernameConfirm\").value;\n\tvar validUsername = validateEmail(newUsername);\n\tvar db = app.database.read();\n\n\t// Format validation\n\tif (!validUsername) {\n\t\talert(\"Please enter an email of the format example@uw.edu or example@uwb.edu\");\n\t\treturn;\n\t}\n\t\n\t// Checking that they entered the same username both times\n\tif (newUsername != newUsernameConfirm) {\n\t\talert(\"Please make sure you typed the same username both times.\");\n\t\treturn;\n\t}\n\t\n\t// Checking that their new username doesn't belong to any other users\n\tif (accountExists(db, newUsername)) {\n\t\talert(\"An acount with this username already exists. Please choose a different username.\");\n\t\treturn;\n\t}\n\t\n\tvar currentUser = app.sessionDatabase.read();\n\tapp.search.changeUserEmail(currentUser.email, newUsername); // change permanent user email in local storage\n\tcurrentUser.email = newUsername; \n\tapp.sessionDatabase.write(currentUser); // change current user email in session storage\n\t\n\tdocument.getElementById(\"newUsername\").value = \"\";\n\tdocument.getElementById(\"newUsernameConfirm\").value = \"\";\n\t$('#usernameModal').modal('hide');\n\t\n\t//Refresh page to make new username appear in profile\n\tlocation.reload();\n}",
"function createNewInfo(){\n\tvar username = getInput(\"username\");\n\tvar password = getInput(\"password\");\n\tvar location = usernamesArray.length;\n\n\tif (username != \"\" && password != \"\"){\t\t\n\t\t//store the values\n\t\tusernamesArray[location] = username;\n\t\tpasswordsArray[location] = password;\n\t\t\n\t\t//wipe text fields and prompt login\n\t\twindow.alert(\"Information saved! PLease Login.\");\n\t\t\n\t\tdocument.getElementById(\"username\").value =\"\";\n\t\tdocument.getElementById(\"password\").value =\"\";\n\t\tsendLoginPost();\t\n\t}\n\t\n\telse {\n\t\twindow.alert(\"Please make sure all fields are filled correctly!\");\n\t}\n}",
"requestUsername() {\n var ui = SpreadsheetApp.getUi();\n var result = ui.prompt('Connect to ReadWorks', 'Please enter your ReadWorks username (email):', ui.ButtonSet.OK_CANCEL);\n var button = result.getSelectedButton();\n var text = result.getResponseText();\n if (button == ui.Button.CANCEL) {\n throw new Error('No username provided, cancelling assignment import.');\n } else if (button == ui.Button.CLOSE) {\n throw new Error('No username provided, cancelling assignment import.');\n }\n this.username = text;\n return this.username;\n }",
"function setupUser(loginScreenName) {\n if (userScreenName == null || userScreenName != loginScreenName)\n {\n userScreenName = loginScreenName;\n localStorage.setItem(\"user-screenname\",userScreenName);\n dbConnectionObject.set(userScreenName);\n setupChatRef();\n }\n}",
"function playerName() {\r\n var player = document.getElementById(\"player\").value;\r\n localStorage.setItem(\"playerName\", player);\r\n}",
"function promptUsername() {\n setInputFlow(submitUsername, true);\n\n print('Please enter your username in the box below');\n}",
"function addUserName () {\n let tag = document.querySelector('#player')\n let myHeadline = document.createElement('h2')\n myHeadline.innerText = 'Curently playing:'\n tag.appendChild(myHeadline)\n let button = document.querySelector('#player button')\n button.addEventListener('click', event => {\n let value = button.previousElementSibling.value\n if (value.length === 0) return\n window.localStorage.setItem('value', value)\n document.getElementById('playername').innerHTML = window.localStorage.getItem('value')\n event.stopPropagation()\n button.previousElementSibling.value = ''\n })\n}",
"function IndivisualLog() {\n\n \n var inFieldU = document.getElementById(\"in-userf\");\n var inFieldP = document.getElementById(\"in-passf\");\n \n var inLabelU = document.getElementById(\"in-user\");\n var inLabelP = document.getElementById(\"in-pass\");\nusernameRegex .exec(inFieldU);//regular expression\n const vaild=!!usernameRegex;\n if(!vaild){\nalert(\"user name is invaild\");\nreturn false\n }\n\n //if already shown from previous submit to hide it\n if (inLabelU.style.display === \"inline\" || \n inLabelP.style.display === \"inline\" \n \n \n ) {\n\n inLabelU.style.display = \"none\";\n inLabelP.style.display = \"none\";\n \n \n \n }\n if( inFieldU.value[0].match(RegexFirstchar) != null ){\n inLabelU.innerHTML=\"user name should not start with number or Literal Characters\";\n inLabelU.style.display=\"inline\"\n return false\n }\n\n \n }",
"function getUserToSearch(name = \"giusetega\"){\n var user = document.getElementById(\"username\").value;\n return (user == null || user == \"\") ? name : user;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
End of the "lgServerListLoad" Get server list with ajax | function lgServerListLoadAjax(URL, curIndex) {
$.ajax({
url: URL,
dataType: 'json',
success: function (data) {
hostFromURL()
localStorage.setItem("server_js", JSON.stringify(data));
lgServerListLoad(data["Servers"], svConfigComparisor(default_server_config["ServerConfig"], data["ServerConfig"]), ["serverList"]);
// After getting server data, start button services.
svButtonTrigger();
svButtonLoadSave(localStorage.SelectedServerID)
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
},
error: function (data) {
$(".server-list-group").html(JSON.stringify(data));
$(".serverSelectButton").html("ERR,Click more info");
if (data["status"] == 200) {
console.log('ERROR: ', "Json Parse Error");
$("#serverSelectLabel").html("Json Parse Error");
} else if (data["status"] == 404) {
console.log('ERROR: ', "Json not found");
$("#serverSelectLabel").html("Json not found in "+server_json_url);
} else {
$("#serverSelectLabel").html("Unknown error, for more details please look Developer Console 'F12' ");
console.log('Unknown error, here is more details: ', data);
}
}
});
} | [
"function getNodes() {\n \n $.ajax({\n url : window.helper.getAPIUrl(\"servers\"),\n method: \"GET\",\n crossDomain: true,\n success : function(list) {\n window.nodes = createMarkers(list, \"Node\");\n showMarkers(window.nodes);\n getClients(list);\n },\n error : function(request, error) {\n window.alert(\"Could not retrieve the data, see console for details.\");\n window.console.dir(error);\n }\n });\n \n// createMarkers(loadTestData());\n// createClients(loadTestData());\n}",
"function loadAppList() {\n //Start the loading indicator\n $('#pcs-applist-overlay').addClass('pcs-common-load-overlay');\n\n\t\t\t\t// clear all the old data\n\t\t\t\tself.startFormList.removeAll();\n\t\t\t\tself.processList = [];\n\t\t\t\tself.searchedStartFormList.removeAll();\n\n //trigger service to fetch data for appNameList\n services.getStartFormList().done(\n function(data) {\n self._populateStartFormListData(data);\n\n // Hide the loading indicator\n $('#pcs-applist-overlay').removeClass('pcs-common-load-overlay');\n\n\t\t\t\t\t\t$('#pcs-applist-error', self.rootElement).hide();\n }\n ).fail(\n function(jqXHR) {\n var msg = self.bundle.pcs.applist.load_error;\n\n if (jqXHR && jqXHR.status === 0) {\n msg = self.bundle.pcs.common.server_not_reachable;\n }\n\n if (jqXHR && jqXHR.status === 500) {\n msg = self.bundle.pcs.common.internal_server_err;\n } else if (jqXHR && jqXHR.status === 401) {\n // reset valid authInfo as the current auth is invalid\n msg = self.bundle.pcs.common.access_error_msg;\n }\n\n $('#pcs-applist-error', self.rootElement).show();\n $('#pcs-applist-error-msg', self.rootElement).text(msg);\n\n // Hide the loading indicator\n $('#pcs-applist-overlay').removeClass('pcs-common-load-overlay');\n }\n );\n\n //fetchDynamicProcess\n\t\t\t\tself.fetchDynamicProcess();\n }",
"function bindServerEvents(){\n $('a[attr-name]').on('click', function(event){\n var serverName = $(this).attr('attr-name');\n var cleanServerName = serverName.replace(/\\./g,'_');\n if ($('#server_'+cleanServerName).html()==\"\"){\n \n var url = 'http://localhost:8080/fullObject/zoneName/hostNamesByFabricWWN/'+serverName+'/';\n $.ajax({\n type: \"GET\",\n url: url,\n success: function(data){\n var resultHtml = '';\n for(var key in data){\n resultHtml+= '<li class=\"last\"><a href=# attr-servername=\"'+cleanServerName+'\" attr-deviceset=\"'+data[key]+'\">'+data[key]+'</a></li>';\n }\n $('#server_'+cleanServerName).html(resultHtml);\n bindDeviceSetEvents(serverName, cleanServerName);\n }\n });\n }\n $('#server_'+cleanServerName).toggle();\n slideOtherMenuLinks($(this));\n });\n }",
"loadDataStreamList() {\n this._dataStreamList = [];\n let servers = this.dataModelProxy.getUserConfig().getDashboardConfig().getServerList();\n let serverID = 0;\n for (let server in servers) {\n if (logging) console.log(\"Retrieving Datastreams from Server:\", servers[server].url);\n let sID = serverID;\n let cb = function(a) {\n this.dataStreamListAvailable(a, sID);\n };\n this.sensorThingsCommunications.getDataStreamList(servers[server].url, cb.bind(this));\n serverID++;\n }\n }",
"function serverListPopupTable(load,tab){\n\tif(globalDeviceType == \"Mobile\"){\n\t\t$(\"#configFooter\").hide();\n\t}\n\tglobalDeviceListLoad = \"\";\n\tglobalDeviceListLoad = load;\n\timgXPos = 152;\n\timgYPos = 24;\n\n\tglobalFlag = false;\n\tcheckLCArray=[]\n\tvar hasDevName = getHasDevNameOnArray();\n//\tvar url = \"/cgi-bin/Final/AutoCompleteCgiQuerry_withDb/querYCgi.fcgi\"\n\tif (tab == \"import\"){\n\t\tvar query = \"manual=server^user=\"+globalUserName+\"^domainname=\"+window['variable' + dynamicDomain[pageCanvas] ]+\"^zone=^imported=1^hostname=\"+hasDevName;\n\t}else{\n\t\tvar query = \"manual=server^user=\"+globalUserName+\"^domainname=\"+window['variable' + dynamicDomain[pageCanvas] ]+\"^zone=^imported=0^hostname=\"+hasDevName;\n\t}\n\tif(globalDeviceType == \"Mobile\"){\n loading('show');\n }\n//\tvar url = \"https://\"+CURRENT_IP+url;\n\tvar action = \"devicelist\";\n\t$.ajax({\n\t\turl: getURL(\"ConfigEditor\",\"JSON\"),\n\t\tdata: {\n\t\t\t\"action\":action,\n\t\t\t\"query\":query,\n\t\t},\n\t\tdataType: 'html',\n\t\tmethod: 'POST',\n\t\tproccessData: false,\n\t\tasync:false,\n\t\tsuccess: function(data) {\n\t\t\tif(globalDeviceType == \"Mobile\"){\n \t\tloading('hide');\n\t\t }\n\t\t\tdata = $.trim(data);\n\t\t\tif (data == \"nodevice\"){\n\t\t\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\t\t\tloading(\"hide\");\n\t\t\t\t\t$.mobile.changePage($('#configEditorPage'),{\n\t\t\t\t\t\t\t\ttransition: \"pop\"\n\t\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\talerts(\"No Available Device\");\n\t\t\t\t$( \"#configPopUp\" ).dialog('destroy');\n\t\t\t\treturn;\n\t\t\t}else if (data == \"databasetimeout\"){\n\t\t\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\t\t\tloading(\"hide\");\n\t\t\t\t}\n\t\t\t\talerts(\"Database Timeout\");\n\t\t\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\t\t\t$.mobile.changePage($('#configEditorPage'),{\n\t\t\t\t\t\t\ttransition: \"pop\"\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}else if (data == \"\"){\n\t\t\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\t\t\tloading(\"hide\");\n\t\t\t\t\t$.mobile.changePage($('#configEditorPage'),{\n\t\t\t\t\t\t\t\ttransition: \"pop\"\n\t\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\talerts(\"Database Timeout\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar condition = checkIfTabAvailable(data);\n\t\t\tif(globalDeviceType == \"Mobile\"){\n\t\t\t\tloading(\"hide\");\n\t\t\t\tappendToDeviceListTable(data,condition,load,tab);\n\t\t\t\tfilterManageDevice();\n\t\t\t}else{\n\t\t\t\tappendToDeviceListTable2(data,condition,load,tab);\n\t\t\t\tsearchBoxDevList();\n\t\t\t}\n\t\t\n\t\t}\n\t });\n\n}",
"function LoadOptions() {\n var xhttp = new XMLHttpRequest();\n xhttp.onreadystatechange = function () {\n if (this.readyState == 4 && this.status == 200) {\n var timeZones = JSON.parse(this.responseText);\n var select = document.getElementById(\"timeZoneSelect\");\n for (i = 0; i < timeZones.length; i++) {\n var listItem = document.createElement('option');\n listItem.value = timeZones[i]\n listItem.innerHTML = timeZones[i];\n select.appendChild(listItem);\n }\n }\n };\n xhttp.open(\"GET\", \"http://127.0.0.1:5000/api/getTimeZoneCollection\", true);\n xhttp.setRequestHeader(\"Content-type\", \"application/json\");\n xhttp.send();\n}",
"function xmlHttp_handle_ulist_populate(){\n\tif(xmlHttp.readyState == 4 && xmlHttp.status == 200){\n\t\tpopulate_list_from_xml(xmlHttp.responseText, 'user_list');\n\t\tcleanup();\n\t}\n}",
"function retrievePlayerGuild(){\n $('#create_guild').hide();\n $.ajax({\n\t type: \"GET\",\n\t url: \"/WebArenaGoupSI1-04-BE/Upgrade/retrievePlayersGuild\",\n contentType: \"application/json\",\n dataType: \"json\",\n success: function (data) { \n \n //populate HTML ul with list of guilds\n $(\"#guildTable\").empty();\n //$(\"#listAllGuilds\").children().remove();\n $(\"#guildTable\").append('<tr><td>' + data.Guild.name + '</td><td><button onclick=\"leave_guil();\">' + \"Leave Guild\" + '</button></td></tr>'); \n },\n\t error: function (error){\n\t }\n }); \n}",
"function loadVRoutersDropDown(urlPath) {\n $.ajax({\n url:urlPath,\n dataType:\"json\",\n success:function (response) {\n var vRouterNames = jsonPath(response, \"$..name\");\n var vRouterIPs = jsonPath(response, \"$..ip\");\n var results = [];\n for (i = 0; i < vRouterNames.length; i++) {\n results.push({\"name\":vRouterNames[i], \"value\":vRouterIPs[i]});\n }\n pingViewModel.set('vRoutersVN', results);\n kendo.bind($('#pingContainer'), pingViewModel);\n var vrdropdownlist = $(\"#ddListvRouter\").data(\"kendoDropDownList\");\n loadInterfacesDropDown('/api/admin/monitor/infrastructure/vrouter/interface?ip=' + vrdropdownlist.value());\n },\n error:function (message) {\n if (message.responseText) {\n showInfoWindow('Error: ' + message.responseText,'Error');\n } else {\n showInfoWindow('Request to get vRouters failed.','Error');\n }\n }\n });\n}",
"function loadAllDropDownListAtStart(){\n\t\t//load vào ddl customer\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/customer/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlCustomer').append($('<option>', {\n value: value.customercode,\n text: value.shortname\n }));\n \n //load bên edit\n $('#editFabricInformationDialog').find('#ddlCustomer').append($('<option>', {\n value: value.customercode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl fabric supplier\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/fabricSupplier/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlFabricSupplier').append($('<option>', {\n value: value.fabricsupcode,\n text: value.shortname\n }));\n \n //bên edit\n $('#editFabricInformationDialog').find('#ddlFabricSupplier').append($('<option>', {\n value: value.fabricsupcode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl chori agent\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/agent/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlChoriAgent').append($('<option>', {\n value: value.agentcode,\n text: value.shortname\n }));\n \n $('#editFabricInformationDialog').find('#ddlChoriAgent').append($('<option>', {\n value: value.agentcode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl factory\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/factory/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlFactory').append($('<option>', {\n value: value.factorycode,\n text: value.shortname\n }));\n \n $('#editFabricInformationDialog').find('#ddlFactory').append($('<option>', {\n value: value.factorycode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl width\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/width/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.width == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlWidth').append($('<option>', {\n value: value.widthcode,\n text: value.widthcode\n }));\n \n $('#editFabricInformationDialog').find('#ddlWidth').append($('<option>', {\n value: value.widthcode,\n text: value.widthcode\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show! 194');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl currency\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/currency/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlCurrency').append($('<option>', {\n value: value.currencycode,\n text: value.name\n }));\n \n $('#editFabricInformationDialog').find('#ddlCurrency').append($('<option>', {\n value: value.currencycode,\n text: value.name\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl Color\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/color/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDetailDialog').find('#ddlColor').append($('<option>', {\n value: value.colorcode,\n text: value.description\n }));\n \n $('#editFabricInformationDialog').find('#ddlColor').append($('<option>', {\n value: value.colorcode,\n text: value.description\n }));\n \n $('#addFabricInformationDetailEditVerDialog').find('#ddlColor').append($('<option>', {\n value: value.colorcode,\n text: value.description\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t}",
"function getBlogCollectionList()\n { \n $.ajax(\"/navbar/blogcollectionlist/checkout\", {\n method: \"get\",\n })\n .done(function (data)\n {\n var $blogCollectionList = $(\"#blog-colleciton-list\");\n for (var idx = 0; idx < data.length; idx++)\n {\n $blogCollectionList.append('<li><a href=/index?pageNum=1&blogCollectionId=' + data[idx]._id+ '>' + data[idx].title + '</a></li>');\n }\n \n })\n .fail(function (xhr, status)\n {\n \n });\n }",
"function ajaxChatContent() {\n $.ajax({\n url: CHAT_LIST_URL,\n data: \"chatversion=\" + chatVersion,\n dataType: 'json',\n timeout: 3000,\n success: function(data) {\n console.log(\"Server chat version: \" + data.version + \", Current chat version: \" + chatVersion);\n if (data.version !== chatVersion) {\n chatVersion = data.version;\n appendToChatArea(data.entries);\n }\n triggerAjaxChatContent();\n },\n error: function(error) {\n triggerAjaxChatContent();\n }\n });\n}",
"function labFetch(){\n\t\t$.ajax({url: currentUrl + '/getLabs', method: 'GET'}).done(function(data){\n\n\t\t\tfor(var i = 0; i < data.length; i++){\n\n\t\t\t\tvar li = $('<li class=\"list-group-item\" id=\"' + data[i]._id + 'li\">').html('Lab Name: ' + data[i].name);\n\t\t\t\tvar p= $('<p class=\"delMessage\">').html(' Delete Chat Lab');\n\t\t\t\tvar chatNum = $('<span class=\"badge\" data-toggle=\"tooltip\" title=\"# of messages in lab\">').html(data[i].chatLog.length);\n\t\t\t\tvar delGlyp = $('<span class=\"glyphicon glyphicon-trash delLab\" data-index=\"' + data[i]._id + '\" data-name=\"' + data[i].name + '\">');\n\n\t\t\t\tli.append(chatNum);\n\t\t\t\tp.prepend(delGlyp);\n\t\t\t\tli.append(p);\n\n\t\t\t\t$('#labList').append(li);\n\t\t\t}\n\n\t\t});\n\t}",
"function retrieveGuilds(){\n $('#create_guild').show();\n \n $.ajax({\n\t type: \"GET\",\n\t url: \"/WebArenaGoupSI1-04-BE/Upgrade/retrieveAllGuilds\",\n contentType: \"application/json\",\n dataType: \"json\",\n success: function (data) { \n $(\"#guildTable\").empty();\n //populate HTML ul with list of guilds\n $.each(data, function(key,value) {\n \n //$(\"#listAllGuilds\").children().remove();\n $(\"#guildTable\").append('<tr><td>' + value.Guild.name + '</td><td><button onclick=\"join_guil('+value.Guild.id+');\">' + \"Join Guild\" + '</button></td></tr>');\n }); \n },\n\t error: function (error){\n\t }\n }); \n}",
"function getOnlineUsers(){\n\tvar url = \"https://\"+CURRENT_IP+\"/cgi-bin/NFast_3-0/CGI/RESERVATIONMANAGER/FastConsoleCgi.py?action=getuseronline\";\n//\tvar url = getURL('Console', 'JSON')+action=getuseronline;\n\n\t$.ajax({\n\t\turl: url,\n\t\tdataType:'html',\n\t\tasync: false,\n\t\tsuccess: function(data){\n\t\t\tdata = $.trim(data);\n\t\t\tvar str = \"\";\n\t\t/*\tvar parser = new DOMParser();\n\t\t\tvar xmlDoc = parser.parseFromString(data, \"text/xml\");\n\t\t\tvar row = xmlDoc.getElementsByTagName(\"row\");*/\n\t\t\tdata = data.replace(/'/g,'\"');\n\t\t\tvar json = jQuery.parseJSON(data);\n\t\t\tif(json.data[0].row != undefined && json.data[0].row != null ){\n\t\t\t\tfor(var i = 0; i < json.data[0].row.length; i++){\n\t\t\t\t\tvar name = json.data[0].row[i].Name;\t\n\t\t\t\t\tstr += \"<li style='font-size:12px;list-style:none;cursor:pointer;text-align:left;margin-left:4px;' class='activeUser'><input type='checkbox' class='addtogroup' style='display:none;' value='\"+name+\"' />\"+name+\"</li>\"\n\t\t\t\t}\n\t\t\t\tif(globalDeviceType==\"Mobile\"){\n\t\t\t\t\t$('#listonline').html(str);\t\n\t\t\t\t}else{\n\t\t\t\t\t$('#onlineUser').empty().append(str);\n\t\t\t\t\t$(\"#user\").multiselect();\n\t\t\t\t}\n\t\t\t\t$(\".activeUser\").click(function(){\n\t\t\t\tglobalReciever=$(this).text();\n\t\t\t\t$(\"#receiverUserName\").html(globalReciever);\n\t\t\t});\t\n\t\t\t}\n\t\t}\n\t});\n}",
"function GetDataModuleAndMap() {\r\n var req = GetXmlHttp();\r\n req.onreadystatechange = function() { \r\n if (req.readyState == 4) { \r\n if(req.status == 200) {\r\n var json = JSON.parse(req.responseText);\r\n SetDataModuleAndMap(json);\r\n }\r\n else { notif(req.status ? req.statusText : 'Запрос не удался', 'Ошибка', 'warning'); return;}\r\n }\r\n }\r\n var json_string = JSON.stringify({'function':'get_list_module'});\r\n SendRequest(req, json_string);\r\n}",
"function loadRecentChanges(minchanges){\r\n\t$.ajax({\r\n\t type: \"GET\",\r\n\t url: wp_service_route_changes + \"?minchanges=\" + minchanges.toString(),\r\n\t dataType: \"json\",\r\n\t success: function (data) {\r\n\t \t$(\"#wait_recent_changes\").html(\"\");\r\n\t \t$(\"#recent_changes ul\").html(\"\");\r\n\t \t$(\"#recent_changes ul\").append(\"<li class='nav-header'>Recent Changes</li>\");\r\n\t \t$.each(data,function(i,changes){\r\n\t\t\t\tvar append_str = \"<li><a href='http://\" + changes.url + \"' target='_blank' >\" + changes.title + \" ( \" + changes.count + \" edits) \" +\"</a></li>\";\r\n\t \t\t\t$(\"#recent_changes ul\").append(append_str);\t \t\t\t\t \t\t\t\r\n\t \t});\r\n\t }\r\n\t});\t\r\n}",
"function loadMore() {\nvar jobid = $('#jobinfo').val();\nvar loadedSeqs = $('#speciessel > option').length - jsonOrgs[\"queryorgs\"].length; // amount of species loaded, minus user-submitted species\n//console.log(loadedSeqs);\n$.ajax({\n // Your server script to process the upload\n contentType: 'application/json',\n url: '/results/'+jobid+'/step2/orgs?start='+loadedSeqs,\n async: true,\n cache: false,\n contentType: false,\n processData: false,\n success: moreSeqsSuccess,\n error: moreSeqsError});\n}",
"function getAllItemsCallback(response){\n\t\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
======================================================================== 6. makeRunAdviseJob Create the modelXML and executes the Analytics Case job in the station. Unless a user selects a particular station from 'Configure And Run', priority is given to the secure local station. Else no affinity is set. If a secure station is used, submits a request to the station, with the job id to be claimed. ======================================================================== | function makeRunAdviseJob(adviseLaunchInfo) {
var resourceCredentials = adviseLaunchInfo.resourceCredentials,
eedURL = adviseLaunchInfo.eedURL,
eedTicket = adviseLaunchInfo.eedTicket,
decodeJobXML = htmlUnescape(adviseLaunchInfo.encodedJobXML),
runInfo = adviseLaunchInfo.runInfo,
affinity = null;
if(typeof adviseLaunchInfo.stationName !== 'undefined' && adviseLaunchInfo.stationName !== null
&& adviseLaunchInfo.stationName !== ''){
affinity = adviseLaunchInfo.stationName;
} else if (typeof adviseLaunchInfo.localStationName !== 'undefined' && adviseLaunchInfo.localStationName !== null
&& adviseLaunchInfo.localStationName !== ''){
affinity = adviseLaunchInfo.localStationName;
}
decodeJobXML = unescape(encodeURIComponent(decodeJobXML));
// Private Secure station takes precedence
if(adviseLaunchInfo.secureStation) {
// Set the affinity to localHost
affinity = "{localhost}";
// Set the HasLocalHost value to AppData
var appDataXML = UTILS.loadXml(decodeJobXML);
var lHostNode = appDataXML.getElementsByTagName('Application')[0].appendChild(
appDataXML.createElement('HasLocalHost'));
lHostNode.appendChild(appDataXML.createTextNode('true'));
decodeJobXML = UTILS.xmlToString(appDataXML);
}
showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_START_SERVANT'),
setStationNameToSplash(adviseLaunchInfo));
var proxyServerURL = adviseLaunchInfo.proxyServer;
if(typeof proxyServerURL === 'undefined' || proxyServerURL === null){
proxyServerURL = '';
}
if(proxyServerURL.indexOf('http') !== 0){
proxyServerURL = '';
}
var modelxml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<fiper_Model version=\"6.216.0\" majorFormat=\"1\" timestamp=\"6/5/14\" rootComponentId=\"812da46e-811e-11e2-ae82-e9ce6b18c519\">"
+ "<Properties modelId=\"6a53ba4c-811e-11e2-ae82-e9ce6b18c519\" modelName=\"AdviseServant\" modelVersion=\"6.216.0\" />"
+ "<Component id=\"812da46e-811e-11e2-ae82-e9ce6b18c519\" name=\"AdviseServant\" type=\"com.dassault_systemes.smacomponent.adviseservant\">";
// client
modelxml += "<Variable type=\"com.engineous.datatype.String\" id=\"bb27e8af-811e-11e2-ae82-e9ce6b18c519\" name=\"host\" role=\"Parameter\" structure=\"Scalar\" mode=\"Input\" dispName=\"host\" saveToDB=\"true\" parentId=\"812da46e-811e-11e2-ae82-e9ce6b18c519\">"
+ "<Value><![CDATA["+window.location.protocol+'//'+window.location.host+"]]></Value>"
+ "</Variable>";
// csrf
modelxml += "<Variable type=\"com.engineous.datatype.String\" id=\"bc27e8af-811e-11e2-ae82-e9ce6b18c519\" name=\"token\" role=\"Parameter\" structure=\"Scalar\" mode=\"Input\" dispName=\"token\" saveToDB=\"true\" parentId=\"812da46e-811e-11e2-ae82-e9ce6b18c519\">"
+ "<Value><![CDATA["+adviseLaunchInfo.token+"]]></Value>"
+ "</Variable>";
// if a local station was found or if user chose a station, assign affinity to the AdviseServant component
if(affinity){
modelxml = modelxml
+ "<Variable id=\"812da46e-811e-11e2-ae82-e9ce6b18c519:affinities\" name=\"affinities\" role=\"Property\" structure=\"Aggregate\" mode=\"Local\" parentId=\"812da46e-811e-11e2-ae82-e9ce6b18c519\">"
+ "<Variable type=\"com.engineous.datatype.String\" typeWrittenVersion=\"2.0.0\" id=\"812da46e-811e-11e2-ae82-e9ce6b18c519:Host\" name=\"Host\" role=\"Property\" structure=\"Scalar\" mode=\"Local\" parentId=\"812da46e-811e-11e2-ae82-e9ce6b18c519:affinities\">"
+ "<Value>"+affinity+"</Value>"
+ "</Variable>"
+ "</Variable>";
}
/**
* This variable sets tells the servant if the data should be
* saved and read in Essentials format.
*/
try {
var essOn = false;
if (localStorage.getItem('_ESSENTIALS_MODE_ON_') === true) {
essOn = true;
}
modelxml += "<Variable type=\"com.engineous.datatype.Bool\" id=\"be27e8af-811e-11e2-ae82-e9ce6b18c519\" name=\"_ESSENTIALS_MODE_ON_\" role=\"Parameter\" structure=\"Scalar\" mode=\"Input\" dispName=\"_ESSENTIALS_MODE_ON_\" saveToDB=\"true\" parentId=\"812da46e-811e-11e2-ae82-e9ce6b18c519\">"
+ "<Value>" + essOn + "</Value>"
+ "</Variable>";
} catch(ex){}
modelxml = modelxml
+ "</Component>"
+ "<Component id=\"6a5a22ed-811e-11e2-ae82-e9ce6b18c519\" name=\"Task1\" type=\"com.dassault_systemes.sma.adapter.Task\">" + "</Component>" + "</fiper_Model>";
// sd4: used to be "/execution/run/workflow"
var eedRunUrl = eedURL + '/execution/run';
jQuery.support.cors = true;
jQuery.ajax({
url : eedRunUrl,
type : "POST",
beforeSend : function(request) {
request.setRequestHeader("EEDTicket", eedTicket);
request.setRequestHeader("Credentials", "");
request.setRequestHeader("RunInfo", runInfo);
request.setRequestHeader("ApplicationData", decodeJobXML);
resourceCredentials = resourceCredentials.trim();
request.setRequestHeader("ResourceCredentials", resourceCredentials);
},
data : modelxml,
contentType : "text/plain",
success : function(returndata, status, xhr) {
var jobIdTxt = $simjq(returndata).find("JobID").text().trim();
adviseLaunchInfo.jobID = jobIdTxt;
if(adviseLaunchInfo.secureStation) {
showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_NOTIFY_SEC_STATION'));
jQuery.ajax({
url: adviseLaunchInfo.stationAccess+"/claim?jobids="+jobIdTxt,
type: "POST",
cache:false,
success: function (returndata, status, xhr) {
waitForServantStartup(adviseLaunchInfo);
},
error: function(jqXHR, textStatus, errorThrown){
console.error(textStatus);
console.error(errorThrown);
//waitForServantStartup(adviseLaunchInfo);
showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR'));
adviseGoBack(
adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR') + '<br\>' + err
);
}
});
} else {
waitForServantStartup(adviseLaunchInfo);
}
},
error : function(jqXHR, textStatus, err) {
showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR'));
adviseGoBack(
adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_EXEC_ERROR') + '<br\>' + err
);
}
});
} | [
"onModelRunClick () {\n const dgst = (this.useBaseRun && this.isCompletedRunCurrent) ? this.runCurrent?.RunDigest || '' : ''\n const wsName = (this.useWorkset && this.isReadonlyWorksetCurrent) ? this.worksetCurrent?.Name || '' : ''\n\n if (!dgst && !this.runOpts.csvDir) {\n if (!wsName) {\n this.$q.notify({ type: 'warning', message: this.$t('Please use input scenario or base model run or CSV files to specifiy input parameters') })\n return\n }\n if (wsName && this.isPartialWorkset()) {\n this.$q.notify({ type: 'warning', message: this.$t('Input scenario should include all parameters otherwise model run may fail') + ': ' + wsName })\n return\n }\n }\n // else do run the model\n this.doModelRun()\n }",
"async function validateTheSecurityAutomationModelBeforeCreateOrUpdate() {\n const subscriptionId =\n process.env[\"SECURITY_SUBSCRIPTION_ID\"] || \"a5caac9c-5c04-49af-b3d0-e204f40345d5\";\n const resourceGroupName = process.env[\"SECURITY_RESOURCE_GROUP\"] || \"exampleResourceGroup\";\n const automationName = \"exampleAutomation\";\n const automation = {\n description:\n \"An example of a security automation that triggers one LogicApp resource (myTest1) on any security assessment of type customAssessment\",\n actions: [\n {\n actionType: \"LogicApp\",\n logicAppResourceId:\n \"/subscriptions/e54a4a18-5b94-4f90-9471-bd3decad8a2e/resourceGroups/sample/providers/Microsoft.Logic/workflows/MyTest1\",\n uri: \"https://exampleTriggerUri1.com\",\n },\n ],\n isEnabled: true,\n location: \"Central US\",\n scopes: [\n {\n description:\n \"A description that helps to identify this scope - for example: security assessments that relate to the resource group myResourceGroup within the subscription a5caac9c-5c04-49af-b3d0-e204f40345d5\",\n scopePath:\n \"/subscriptions/a5caac9c-5c04-49af-b3d0-e204f40345d5/resourceGroups/myResourceGroup\",\n },\n ],\n sources: [\n {\n eventSource: \"Assessments\",\n ruleSets: [\n {\n rules: [\n {\n expectedValue: \"customAssessment\",\n operator: \"Equals\",\n propertyJPath: \"$.Entity.AssessmentType\",\n propertyType: \"String\",\n },\n ],\n },\n ],\n },\n ],\n tags: {},\n };\n const credential = new DefaultAzureCredential();\n const client = new SecurityCenter(credential, subscriptionId);\n const result = await client.automations.validate(resourceGroupName, automationName, automation);\n console.log(result);\n}",
"function tryTolaunchAdviseClient(adviseLaunchInfo, timer) {\n \n var jobIdTxt = adviseLaunchInfo.jobID;\n var eedURL = adviseLaunchInfo.eedURL;\n var eedTicket = adviseLaunchInfo.eedTicket;\n \n launchCount++;\n if (launchCount > launchLimit) {\n // sd4 - IR-297707-3DEXPERIENCER2015x - adding a confirmation message \n // to wait longer in order to allow downloading a large file\n createLaunchPopOver({\n 'message': adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_TIMER_XTND'),\n 'confirm-mode': true,\n 'ok-callback': function(){\n launchCount = 0;\n launchLimit = 150; // 5 minutes\n return;\n },\n 'close-callback': function(){\n clearInterval(timer);\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_TIMER_XTND'),\n setStationNameToSplash(adviseLaunchInfo));\n cancelJob(adviseLaunchInfo, adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_TIMEOUT'));\n }\n });\n }\n \n // Configure AJAX call to the EED for reading bulletin board messages\n var eedURLMonitor = eedURL + \"/job/\" + jobIdTxt + \"/monitor\";\n \n jQuery.support.cors = true;\n \n monitorForError(eedURLMonitor, eedTicket);\n \n // AJAX call to read EED bulletin board\n jQuery.ajax({\n url : eedURLMonitor,\n data : { 'Topic' : messageTopic,\n 'TimeStamp' : 0 },\n type : \"GET\",\n beforeSend : function(request) {\n request.setRequestHeader(\"EEDTicket\", eedTicket);\n request.setRequestHeader(\"Credentials\", \"\");\n },\n success : function(returndata, status, xhr){\n \n var adviseMessage = $simjq(returndata).find(\"Message\").text() || '';\n // sd4 - I keep getting this error when i try to launch \n var localTopic = $simjq(returndata).find(\"MessageList\").attr(\"topic\");\n if(localTopic && localTopic.length>4) {\n \tlocalTopic = localTopic.trim();\n }\n if (adviseMessage.length > 4) {\n // First message topic that we expect - before downloading the data\n // file on the servant (done by component BEFORE launching advise servant\n if (localTopic == \"ResultsServantDowloadingFile\") {\n \n showLoadingMessage(adviseLaunchInfo.translator.translate(adviseMessage) + \"...\",\n setStationNameToSplash(adviseLaunchInfo));\n \n // Next message topic that we expect - URL for advise - posted\n // after Advise servant is fully functional\n messageTopic = \"ResultsServantURL\";\n \n // Reset the timout to 30 mins - in case of downloading a very\n // large file over a slow network\n launchCount = 0;\n launchLimit = 900;\n jobRunning = true;\n }\n else {\n\t clearInterval(timer);\n\t \n\t // Retrieve the servant url(s)\n\t deriveServantURL(adviseLaunchInfo, adviseMessage);\n\t \n\t if ((adviseLaunchInfo['stationDisplayName']).length === 0){\n\t\n\t \t// The display name would be empty only if\n\t \t// affinity is not set and the station is not\n\t \t// a secure station.\n\t \t\n\t \tvar servantIP = '';\n\t \tif (adviseMessage.indexOf('http') === 0){\n\t \t\t// Unproxified url\n\t \t\tvar parser = document.createElement('a');\n\t parser.href = adviseMessage;\n\t servantIP = parser.hostname;\n\t \t} else {\n\t \t\t// Proxy exists, and the message format is\n\t \t\t// 192.178.106.25/8090/Advise\n\t \t\tservantIP = adviseMessage.split('/')[0];\n\t \t}\n\t \tif (servantIP.length > 0){\n\t \t\tfor(var i=0; i<adviseLaunchInfo.stationList.length; i++) {\n\t \t\tvar stationInfo = adviseLaunchInfo.stationList[i];\n\t \t\tif (servantIP ===\n\t \t\t\tstationInfo.GeneralInfo['@hostIP'].trim()){\n\t \t\t\tadviseLaunchInfo.stationIP = servantIP;\n\t \t\t\tadviseLaunchInfo.stationName = stationInfo['@name'];\n\t \t\t\tadviseLaunchInfo.stationDisplayName = stationInfo['@name'];\n\t \t\t}\n\t \t}\n\t \t\t\n\t \t\tif ((adviseLaunchInfo['stationDisplayName']).length === 0){\n\t \t\t\tadviseLaunchInfo.stationDisplayName = window.location.host\n\t \t\t}\n\t \t}\n\t }\n\t \n\t //startJobLogHeartbeat(jobIdTxt);\n\t \n\t var startWaitTimer = setInterval(function() {\n\t clearInterval(startWaitTimer);\n\t removeLoadingMessage();\n\t // FIXME: Why is the servant url set here ?\n\t // adviseLaunchInfo.servantURL = adviseMessage + '/';\n\t startApp(adviseLaunchInfo);\n\t }, 2000);\n }\n } else {\n \n var messageElem = $simjq(returndata).find(\"MonitoringMessages\");\n var status = messageElem.attr(\"status\");\n if (status == \"Running\" && !jobRunning) {\n // Reset the wait timer for the Executor to post the message\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_WAIT_FOR_SERVANT'),\n setStationNameToSplash(adviseLaunchInfo));\n \n launchCount = 0;\n jobRunning = true;\n } else if (status == \"Done\") {\n clearInterval(timer);\n \n // We don't need this message when the job is cancelled.\n if (! JOB_CANCELLED){\n var errorThrown = adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_ERROR');\n showLoadingMessage(errorThrown, setStationNameToSplash(adviseLaunchInfo));\n adviseGoBack(errorThrown);\n }\n }\n }\n }, // End of success callback\n error: function(jqXHR, textStatus, errorThrown){\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_STATUS_ERROR'));\n adviseGoBack(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_STATUS_ERROR') + '<br/>' +\n adviseLaunchInfo.translator.translate('LAUNCH_BB_ERROR'));\n return;\n }\n });\n}",
"function getRunningServant(caseID, adviseLaunchInfo) {\n \n var def = jQuery.Deferred(),\n clearStg = function(){\n delete localStorage['smaAnalyticsCase' + caseID];\n def.resolve(null);\n };\n\n if (typeof (Storage) !== 'undefined') {\n \n var currTime = Date.now();\n var previousSessionString = localStorage['smaAnalyticsCase' + caseID];\n \n if (previousSessionString && previousSessionString.length > 5) {\n \n var previousSession = JSON.parse(previousSessionString);\n var prevTime = previousSession.lastUpdateTime;\n var servantURL = previousSession.servantURL;\n adviseLaunchInfo['servantURL'] = servantURL;\n adviseLaunchInfo['caseID'] = caseID;\n \n $simjq.when(checkServantURLValidity(adviseLaunchInfo))\n .then(function(token){\n \n\t\t\t\t\tif (typeof token !== 'undefined' && token !== null && token.length > 0){\n createLaunchPopOver({\n 'message': adviseLaunchInfo.translator.translate('LAUNCH_EXISTING_SERVANT') ,\n 'header': adviseLaunchInfo.translator.translate('LAUNCH_RA_HEADER_EXS_SERVANT'),\n 'confirm-mode': true,\n 'close-label': adviseLaunchInfo.translator.translate('Cancel') ,\n 'ok-callback': function(){\n def.resolve({\n 'servantURL': servantURL,\n 'stationName': previousSession.stationName,\n 'stationIP' : previousSession.stationIP,\n 'token' : token });\n }.bind(this),\n \n 'close-callback': function(){\n \n var promise = jQuery.ajax({ url:servantURL + 'stop',\n crossDomain: true,\n data: { 't': Date.now() }\n })\n .done(clearStg)\n .fail(function(){\n console.error('Attempt to stop the running servant failed.');\n clearStg();\n });\n }.bind(this)\n });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclearStg();\n\t\t\t\t\t}\n }.bind(this));\n } else {\n clearStg();\n }\n } else {\n def.resolve(null);\n }\n return def;\n}",
"doneNewRunInit (ok, runStamp, submitStamp) {\n this.isInitRun = false\n this.loadWait = false\n\n if (!ok || !submitStamp) {\n this.$q.notify({ type: 'negative', message: this.$t('Server offline or model run failed to start') })\n return\n }\n\n // model wait in the queue\n if (!runStamp) {\n this.$q.notify({ type: 'info', message: this.$t('Model run wait in the queue' + ': ' + Mdf.fromUnderscoreTimeStamp(submitStamp)) })\n\n if (this.serverConfig.IsJobControl) {\n this.$emit('run-job-select', submitStamp) // show service state and job control page\n } else {\n this.$emit('run-log-select', submitStamp) // no job control: show run log page\n }\n } else {\n // else: model started\n this.$q.notify({ type: 'info', message: this.$t('Model run started' + ': ' + Mdf.fromUnderscoreTimeStamp(runStamp)) })\n this.$emit('run-list-refresh')\n this.$emit('run-log-select', runStamp)\n }\n }",
"function recordJob(website, id, method, job_id) {\n //Dev bypass, will not log jobs as no key found.\n if (setup.api_dev_mode === true) {\n return;\n }\n\n API.findById(id, function (err, info) {\n if (err || !info) {\n logger.warn(\"Failed to add job ID to API key, API key not found\");\n return;\n } else {\n //log job\n info.associated_job_ids.push(website + \"/\" + method + \"/\" + job_id);\n info.save();\n }\n });\n}",
"function startApp(adviseLaunchInfo) {\n \n $simjq.when(checkServantURLValidity(adviseLaunchInfo))\n .then(function(token){\n\t\t\tif (token.length > 0){\n \n if(!adviseLaunchInfo.noServant){\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_READING_DATA'),\n setStationNameToSplash(adviseLaunchInfo));\n }\n else{\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_LOAD_LITE'));\n }\n \n $simjq('#widgetframe').attr('src', \"../webapps/SMAAnalyticsUI/smaResultsAnalyticsLaunched.html\").load(function(){\n var widgetWindow = window.frames['widgetframe'];\n if(!widgetWindow.setServantFromParent) {\n widgetWindow = widgetWindow.contentWindow; // needed for FF\n }\n if(widgetWindow.setServantFromParent) {\n $simjq('.embeddedWidget').show();\n if(!adviseLaunchInfo.noServant){\n widgetWindow.setServantFromParent(adviseLaunchInfo);\n }\n } else {\n showLoadingMessage(adviseLaunchInfo.translator.translate('LAUNCH_PAGE_LOAD_ERROR'));\n adviseGoBack(adviseLaunchInfo.translator.translate('LAUNCH_PAGE_LOAD_ERROR'));\n }\n });\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tadviseGoBack(adviseLaunchInfo.translator.translate('LAUNCH_SERVANT_ERROR'));\n\t\t\t}\n\n });\n}",
"function createJobsForConstraint(constraint, index) {\n logger.debug(\"creating new jobs for: \" + constraint + \", index: \" + index);\n var dateUtil = org.forgerock.openidm.util.DateUtil.getDateUtil(),\n startDate = dateUtil.getStartOfInterval(constraint.duration),\n endDate = dateUtil.getEndOfInterval(constraint.duration),\n startExpression = dateUtil.getSchedulerExpression(startDate.plusSeconds(1)),\n endExpression = dateUtil.getSchedulerExpression(endDate.plusSeconds(1));\n \n var invokeScript = { \n \"script\" : { \n \"type\" : \"text/javascript\", \n \"source\" : \"require('roles/onSync-roles').syncUsersOfRoles(resourceName, object, object, null);\",\n \"globals\" : { \n \"object\" : newObject,\n \"resourceName\" : resourceName.toString()\n } \n } \n },\n startJob = {\n \"type\" : \"cron\",\n \"schedule\" : startExpression, \n \"misfirePolicy\" : \"doNothing\",\n \"persisted\" : true,\n \"invokeService\" : \"script\", \n \"invokeContext\" : invokeScript\n },\n endJob = {\n \"type\" : \"cron\",\n \"schedule\" : endExpression, \n \"misfirePolicy\" : \"doNothing\",\n \"persisted\" : true,\n \"invokeService\" : \"script\", \n \"invokeContext\" : invokeScript\n },\n startJobId = resourceName.toString().replace('/', '-') + \"-temporalConstraint-\" + index + \"-start\",\n endJobId = resourceName.toString().replace('/', '-') + \"-temporalConstraint-\" + index + \"-end\";\n\n if (startDate.isAfterNow()) {\n logger.debug(\"create startJob: \" + startJobId);\n openidm.create(\"scheduler\", startJobId, startJob);\n } else {\n logger.debug(\"Not creating start job, is in the past\");\n }\n if (endDate.isAfterNow()) {\n logger.debug(\"create endJob: \" + endJobId);\n openidm.create(\"scheduler\", endJobId, endJob);\n } else {\n logger.debug(\"Not creating end job, is in the past\");\n }\n return true;\n}",
"function C006_Isolation_Yuki_Run() {\n\tBuildInteraction(C006_Isolation_Yuki_CurrentStage);\n}",
"async forceRun() {\r\n var runJob = await this.saved_search.dispatch({force_dispatch: true, trigger_actions: true}, function(err) {\r\n if (err) {\r\n return err;\r\n }\r\n });\r\n\r\n if (!!runJob) {\r\n return runJob;\r\n }\r\n }",
"function run(context) {\n\n \"use strict\";\n\n // This holds a representation of the AFE model populated by parseAFEJson()\n var afeModel = {};\n\n var app = adsk.core.Application.get(), ui;\n if (app) {\n ui = app.userInterface;\n }\n\n var filename = \"\"; // Name of the file to import\n\n // Create the command definition.\n var createCommandDefinition = function() {\n var commandDefinitions = ui.commandDefinitions;\n var commandDefinitions = ui.commandDefinitions;\n\n // Be fault tolerant in case the command is already added...\n var cmDef = commandDefinitions.itemById('ForceEffectImport');\n if (!cmDef) {\n cmDef = commandDefinitions.addButtonDefinition('ForceEffectImport',\n 'ForceEffect Import',\n 'Import a ForceEffect or ForceEffect Motion document.',\n './resources'); // relative resource file path is specified\n }\n return cmDef;\n };\n\n // CommandCreated event handler.\n var onCommandCreated = function(args) {\n try {\n // Connect to the CommandExecuted event.\n var command = args.command;\n command.execute.add(onCommandExecuted);\n\n // Terminate the script when the command is destroyed\n command.destroy.add(function () { adsk.terminate(); });\n\n // Define the inputs.\n var inputs = command.commandInputs;\n\n var initValScale = adsk.core.ValueInput.createByReal(afeModel.Scale);\n inputs.addValueInput('scale', 'Scale', 'cm' , initValScale); // REVIEW: What about unitless values?\n\n var initValCompWidth = adsk.core.ValueInput.createByReal(afeModel.ComponentWidth);\n inputs.addValueInput('componentWidth', 'Component Width', 'cm' , initValCompWidth);\n\n inputs.addBoolValueInput('extrude', 'Extrude', true, \".\", true);\n\n var initValExtrudeDist = adsk.core.ValueInput.createByReal(afeModel.ExtrudeDist);\n inputs.addValueInput('extrudeHeight', 'Extrude Distance', 'cm' , initValExtrudeDist);\n\n var initValJointHoleDiam = adsk.core.ValueInput.createByReal(afeModel.JointHoleDiameter);\n inputs.addValueInput('jointHoleDiameter', 'Joint Hole Diameter', 'cm' , initValJointHoleDiam);\n }\n catch (e) {\n ui.messageBox('Failed to create command : ' + (e.description ? e.description : e));\n }\n };\n\n // CommandExecuted event handler.\n var onCommandExecuted = function(args) {\n try {\n\n // Extract input values\n var unitsMgr = app.activeProduct.unitsManager;\n var command = adsk.core.Command(args.firingEvent.sender);\n var inputs = command.commandInputs;\n\n var scaleInput, componentWidthInput, extrudeInput, extrudeHeightInput, jointHoleDiameterInput;\n\n // Problem with a problem - the inputs are empty at this point. We\n // need access to the inputs within a command during the execute.\n for (var n = 0; n < inputs.count; n++) {\n var input = inputs.item(n);\n if (input.id === 'scale') {\n scaleInput = adsk.core.ValueCommandInput(input);\n }\n else if (input.id === 'componentWidth') {\n componentWidthInput = adsk.core.ValueCommandInput(input);\n }\n else if (input.id === 'extrude') {\n extrudeInput = adsk.core.BoolValueCommandInput(input);\n }\n else if (input.id === 'extrudeHeight') {\n extrudeHeightInput = adsk.core.ValueCommandInput(input);\n }\n else if (input.id === 'jointHoleDiameter') {\n jointHoleDiameterInput = adsk.core.ValueCommandInput(input);\n }\n }\n\n if (!scaleInput || !componentWidthInput || !extrudeInput || !extrudeHeightInput || !jointHoleDiameterInput) {\n ui.messageBox(\"One of the inputs don't exist.\");\n return;\n }\n\n var scale = unitsMgr.evaluateExpression(scaleInput.expression, \"cm\");\n if (scale <= 0.0) {\n ui.messageBox(\"Invalid scale: must be > 0\");\n return;\n }\n\n afeModel.Scale = scale;\n\n var componentWidth = unitsMgr.evaluateExpression(componentWidthInput.expression, \"cm\");\n if (componentWidth <= 0.0) {\n ui.messageBox(\"Invalid component width: must be > 0\");\n return;\n }\n\n afeModel.ComponentWidth = componentWidth;\n\n var doExtrude = extrudeInput.value;\n\n var extrudeHeight = unitsMgr.evaluateExpression(extrudeHeightInput.expression, \"cm\");\n if (extrudeHeight <= 0.0) {\n ui.messageBox(\"Invalid extrude height: must be > 0\");\n return;\n }\n\n afeModel.ExtrudeHeight = extrudeHeight;\n\n var jointHoleDiameter = unitsMgr.evaluateExpression(jointHoleDiameterInput.expression, \"cm\");\n if (jointHoleDiameter <= 0.0) {\n ui.messageBox(\"Invalid joint hole diameter: must be > 0\");\n return;\n }\n\n afeModel.JointHoleDiameter = jointHoleDiameter;\n\n // Generate the drawing\n generateDrawing(afeModel, doExtrude);\n }\n catch (e) {\n ui.messageBox('Failed to import : ' + (e.description ? e.description : e));\n }\n };\n\n // Convert AFE value into centimeters\n function afeVal2cm(unit, value)\n {\n if (unit === \"ft\")\n return (value * 12 * 2.54); // ft -> in -> cm\n else if (unit == \"in\")\n return (value * 2.54); // in -> cm\n else if (unit == \"mm\")\n return (value / 10); // mm -> cm\n else if (unit == \"m\")\n return (value * 100); // meter -> cm\n else\n return (+value); // error?\n };\n\n // Return the Ids (keys) of a hashtable\n function hastableKeys(dict)\n {\n var ids = [];\n\n for (var id in dict)\n {\n if (dict.hasOwnProperty(id))\n ids.push(id);\n }\n\n return ids;\n };\n\n // Find the Joint's Point with a specified label\n function getJointPoint(joint, label)\n {\n if (!joint.Point.length)\n {\n if (joint.Point.Label === label)\n return joint.Point;\n }\n else // array\n {\n // Iterate over points\n for (var i = 0; i < joint.Point.length; ++i)\n {\n if (joint.Point[i].Label === label)\n return joint.Point[i];\n }\n }\n\n return null; // not found\n };\n\n // Rotate the X,Y point around the origin point.\n // Returns rotated point: {x,y}\n function rotatePoint(angleRadians, x, y, xOrigin, yOrigin)\n {\n return {\n\t\t x: Math.cos(angleRadians) * (x-xOrigin) - Math.sin(angleRadians) * (y-yOrigin) + xOrigin,\n\t\t y: Math.sin(angleRadians) * (x-xOrigin) + Math.cos(angleRadians) * (y-yOrigin) + yOrigin\n\t };\n };\n\n // Parses the AFE file and populates the afeModel object.\n function parseAFEFile(filename)\n {\n // The AFE Model object\n afeModel =\n {\n Title: \"\",\n Filename: filename,\n\n LengthUnit: \"ft\",\n\n // Hashtables (id -> elem)\n Joints: {},\n Components: {},\n Supports: {},\n\n // Will contain bounds of all elements\n Bounds:\n {\n xMin: Number.MAX_VALUE,\n yMin: Number.MAX_VALUE,\n xMax: Number.MIN_VALUE,\n yMax: Number.MIN_VALUE\n },\n\n // Min/Max line lengths\n LineLengths:\n {\n min: Number.MAX_VALUE,\n max: Number.MIN_VALUE,\n },\n\n // Amount to scale source model when creating Fusion model.\n Scale: 1.0,\n\n // Amount to extrude\n ExtrudeDist: app.activeProduct.unitsManager.evaluateExpression(\"0.3\", \"cm\"),\n\n // Set width of component bodies\n ComponentWidth: app.activeProduct.unitsManager.evaluateExpression(\"0.5\", \"cm\"),\n\n // Set diameter of joint holes\n JointHoleDiameter: app.activeProduct.unitsManager.evaluateExpression(\"1\", \"mm\")\n };\n\n // The current format of an AFE file comes in binary or text formats. The\n // text file contains an XML representation while the binary also contains\n // XML as well as other binary data.\n //\n // This parsing code determines which is which by looking at the first set\n // of values in the file. If they are text based then we assume it's a\n // text file. Otherwise, it's a binary. This is a hack but works for now.\n\n // Begin by reading in the buffer.\n var buffer = adsk.readFile(filename);\n if (!buffer) {\n ui.messageBox('Failed to open ' + filename);\n return null;\n }\n\n var bytes = new Uint8Array(buffer);\n if (bytes.byteLength < 20) {\n ui.messageBox('Invalid data file. Not enough data: ' + filename);\n return null;\n }\n\n // At the start of a binary version of the file is a header:\n //\n // 16 bytes (?)\n // 4 bytes (length of XML section)\n // XML section\n // Remainder of binary data\n //\n // Let's look at the first set of bytes to see if they are binary or text.\n // That will determine how we parse.\n var parseBinary = false;\n var asciiChars = /^[ -~\\t\\n\\r]+$/;\n for (var ii = 0; ii < 16; ++ii) {\n var ch = String.fromCharCode(bytes[ii]);\n if ( !asciiChars.test( ch ) ) {\n // non-ascii character\n parseBinary = true;\n break;\n }\n }\n\n var xmlBytes; // This will hold the XML to parse\n\n // This is a binary file\n if (parseBinary) {\n\n // Extract the XML section length from the header\n var xmlLength = (+bytes[16]) + (256 * bytes[17]);\n\n // Now extract the XML. Note, offset another 2 bytes later\n xmlBytes = bytes.subarray(20,xmlLength+20); // args = begin, end\n }\n else {\n xmlBytes = bytes; // XML text file so use all of it.\n }\n\n // Convert the model xml to a JSON string\n var xml = adsk.utf8ToString(xmlBytes);\n var jsonAFE = $.xml2json(xml);\n if (!jsonAFE) {\n ui.messageBox('Failed to convert file ' + filename);\n return null;\n }\n\n // Begin parsing - Extract settings from the file header.\n //\n // <File Schema=\"9\" Title=\"Diagram00014\" IsImperial=\"1\" UnitsVisible=\"1\" LengthUnit=\"ft\" AppType=\"afe\"\n // ForceUnit=\"lb\" MovieIsValid=\"0\" ScreenWidth=\"320\" ScreenHeight=\"524\" SimulationSpeed=\"35.000000\">\n if (jsonAFE.Title) {\n afeModel.Title = jsonAFE.Title;\n }\n\n if (afeModel.Title === \"\") {\n afeModel.Title = \"ForceEffect Import\";\n }\n\n if (jsonAFE.LengthUnit) {\n afeModel.LengthUnit = jsonAFE.LengthUnit;\n }\n\n // Parse the \"Elements\"\n if (jsonAFE.Elements && jsonAFE.Elements.Ided)\n {\n for (var iElem = 0; iElem < jsonAFE.Elements.Ided.length; ++iElem)\n {\n var elem = jsonAFE.Elements.Ided[iElem];\n if (!elem.TypeID) {\n continue;\n }\n\n if (elem.TypeID == \"Joint\")\n {\n // <Ided TypeID=\"Joint\" ObjectId=\"3\" Index=\"1\">\n afeModel.Joints[elem.ObjectId] = elem;\n }\n else if (elem.TypeID == \"Component\")\n {\n // <Ided TypeID=\"Component\" ObjectId=\"2\">\n afeModel.Components[elem.ObjectId] = elem;\n }\n else if (elem.TypeID == \"Support\")\n {\n // <Ided TypeID=\"Support\" ObjectId=\"1\">\n afeModel.Supports[elem.ObjectId] = elem;\n }\n }\n }\n\n // Iterate through the elements to calc bounding box.\n var idsComps = hastableKeys(afeModel.Components); // get Ids of components\n for (var i = 0; i < idsComps.length; ++i)\n {\n var idComp = idsComps[i];\n var comp = afeModel.Components[idComp];\n\n var startJoint = afeModel.Joints[comp.StartJoint.ObjId];\n var endJoint = afeModel.Joints[comp.EndJoint.ObjId];\n\n if (!startJoint || !endJoint)\n {\n console.log(\"Error: Unable to find start or end joint\");\n continue;\n }\n\n // Get the joint positions and convert to correct units\n var ptStart = getJointPoint(startJoint,\"Origin\");\n var ptEnd = getJointPoint(endJoint,\"Origin\");\n\n var xStart = afeVal2cm(afeModel.LengthUnit, ptStart.x);\n var yStart = afeVal2cm(afeModel.LengthUnit, ptStart.y);\n var xEnd = afeVal2cm(afeModel.LengthUnit, ptEnd.x);\n var yEnd = afeVal2cm(afeModel.LengthUnit, ptEnd.y);\n\n // Track bounds of all elements\n afeModel.Bounds.xMin = Math.min(afeModel.Bounds.xMin, Math.min(xStart,xEnd));\n afeModel.Bounds.yMin = Math.min(afeModel.Bounds.yMin, Math.min(yStart,yEnd));\n afeModel.Bounds.xMax = Math.max(afeModel.Bounds.xMax, Math.max(xStart,xEnd));\n afeModel.Bounds.yMax = Math.max(afeModel.Bounds.yMax, Math.max(yStart,yEnd));\n\n // Length of this line\n var lineLen = Math.sqrt((xEnd -= xStart) * xEnd + (yEnd -= yStart) * yEnd);\n if (lineLen < afeModel.LineLengths.min)\n afeModel.LineLengths.min = lineLen;\n if (lineLen > afeModel.LineLengths.max)\n afeModel.LineLengths.max = lineLen;\n }\n\n return afeModel;\n };\n\n // Generate the Fusion drawing from the ForceEffect model\n var generateDrawing = function(afeModel, doExtrude) {\n\n if (!afeModel)\n return;\n\n // Get the active design.\n var product = app.activeProduct;\n var design = adsk.fusion.Design(product);\n var title = afeModel.Title + '(' + afeModel.Filename + ')';\n if (!design) {\n ui.messageBox('No active Fusion design', title);\n adsk.terminate();\n return;\n }\n\n var rootComp = design.rootComponent;\n\n // Create a pair of new sketches.\n var sketches = rootComp.sketches;\n var xzPlane = rootComp.xZConstructionPlane;\n\n // This sketch contains the actual layout of the parts as defined in the\n // imported model. Additionally, part labels are added for reference by\n // the parts sketch.\n var sketchInstructions = sketches.add(xzPlane);\n sketchInstructions.name = \"Instructions\";\n\n // Begin adding INSTRUCTION geometry\n var sketchLines = sketchInstructions.sketchCurves.sketchLines;\n var sketchArcs = sketchInstructions.sketchCurves.sketchArcs;\n var sketchCircles = sketchInstructions.sketchCurves.sketchCircles;\n\n // Defer compute while sketch geometry added.\n sketchInstructions.isComputeDeferred = true;\n\n // The \"Components\" are lines that connect joints. Iterate over\n // these and create sketch lines.\n var idsComps = hastableKeys(afeModel.Components); // get Ids of components\n for (var iComp = 0; iComp < idsComps.length; ++iComp)\n {\n var comp = afeModel.Components[idsComps[iComp]];\n\n // Which joints are connected?\n var startJoint = afeModel.Joints[comp.StartJoint.ObjId];\n var endJoint = afeModel.Joints[comp.EndJoint.ObjId];\n\n if (!startJoint || !endJoint)\n {\n console.log(\"Error: Unable to find start or end joint for component\");\n continue;\n }\n\n // Get the joint positions and convert to correct units\n var ptStartSrc = getJointPoint(startJoint,\"Origin\");\n var ptEndSrc = getJointPoint(endJoint,\"Origin\");\n\n var xStart = afeVal2cm(afeModel.LengthUnit, ptStartSrc.x) * afeModel.Scale;\n var yStart = afeVal2cm(afeModel.LengthUnit, ptStartSrc.y) * afeModel.Scale;\n var xEnd = afeVal2cm(afeModel.LengthUnit, ptEndSrc.x) * afeModel.Scale;\n var yEnd = afeVal2cm(afeModel.LengthUnit, ptEndSrc.y) * afeModel.Scale;\n\n var ptStart = adsk.core.Point3D.create(xStart, yStart, 0);\n var ptEnd = adsk.core.Point3D.create(xEnd, yEnd, 0);\n\n // Create a line for this afe component\n var aLine = sketchLines.addByTwoPoints( ptStart, ptEnd );\n if (!aLine) {\n console.log(\"Error: Unable to create sketch geometry.\");\n }\n\n // TODO: Text not supported in API\n // Create a text element to mark this line\n }\n\n // Enable now that geometry has been added\n sketchInstructions.isComputeDeferred = false;\n\n if (doExtrude)\n {\n // This sketch contains the parts of the model placed in a line and\n // labeled to match those in the instructions.\n\n // Array of contruction planes for each part\n var sketchPartsArray = [];\n\n //var sketchParts = sketches.add(xzPlane);\n //sketchParts.name = \"Parts\";\n\n // this will contain circles for cutting holes in the parts\n var sketchPartsHoles = sketches.add(xzPlane);\n sketchPartsHoles.name = \"PartsHoles\";\n\n var sketchCirclesHoles = sketchPartsHoles.sketchCurves.sketchCircles;\n\n // Defer compute while sketch geometry added.\n sketchPartsHoles.isComputeDeferred = true;\n\n var extrudeDistPerSketch = afeModel.ExtrudeDist * 1.2;\n\n // The \"Components\" are lines that connect joints. Iterate over\n // these and create sketch lines.\n //var idsComps = hastableKeys(afeModel.Components); // get Ids of components\n for (var iComp = 0; iComp < idsComps.length; ++iComp)\n {\n var comp = afeModel.Components[idsComps[iComp]];\n\n // Which joints are connected?\n var startJoint = afeModel.Joints[comp.StartJoint.ObjId];\n var endJoint = afeModel.Joints[comp.EndJoint.ObjId];\n\n if (!startJoint || !endJoint)\n {\n console.log(\"Error: Unable to find start or end joint for component\");\n continue;\n }\n\n // Create the sketch plane and sketch for this part.\n // NOTE: We need 1 sketch plane per part so that we can keep them\n // from intersecting with each other when extruded and have them\n // sit in the same location as the instructions.\n var cpi = rootComp.constructionPlanes.createInput();\n cpi.setByOffset( xzPlane, adsk.core.ValueInput.createByReal(iComp * extrudeDistPerSketch) );\n var sketchPlane = rootComp.constructionPlanes.add( cpi );\n var sketchParts = sketches.add(sketchPlane);\n sketchPartsArray.push(sketchParts);\n sketchParts.name = \"Part - \" + iComp;\n\n // Begin adding PARTS geometry\n var sketchLines = sketchParts.sketchCurves.sketchLines;\n var sketchArcs = sketchParts.sketchCurves.sketchArcs;\n var sketchCircles = sketchParts.sketchCurves.sketchCircles;\n\n // Defer compute while sketch geometry added.\n sketchParts.isComputeDeferred = true;\n\n // Get the joint positions and convert to correct units\n var ptStartSrc = getJointPoint(startJoint,\"Origin\");\n var ptEndSrc = getJointPoint(endJoint,\"Origin\");\n\n var xStart = afeVal2cm(afeModel.LengthUnit, ptStartSrc.x) * afeModel.Scale;\n var yStart = afeVal2cm(afeModel.LengthUnit, ptStartSrc.y) * afeModel.Scale;\n var xEnd = afeVal2cm(afeModel.LengthUnit, ptEndSrc.x) * afeModel.Scale;\n var yEnd = afeVal2cm(afeModel.LengthUnit, ptEndSrc.y) * afeModel.Scale;\n\n var ptStart = adsk.core.Point3D.create(xStart, yStart, 0);\n var ptEnd = adsk.core.Point3D.create(xEnd, yEnd, 0);\n\n // Length of this line\n //var lineLen = Math.sqrt((xEnd -= xStart) * xEnd + (yEnd -= yStart) * yEnd);\n\n var halfWidth = afeModel.ComponentWidth / 2;\n\n // Calc the angle of the line\n var angleRadians = Math.atan2(yEnd-yStart,xEnd-xStart);\n\n var angle90InRadians = (90 * Math.PI/180);\n\n var ptEdgeOffset1 = rotatePoint(angleRadians + angle90InRadians, halfWidth, 0, 0, 0);\n var ptEdgeOffset2 = rotatePoint(angleRadians - angle90InRadians, halfWidth, 0, 0, 0);\n\n // Edge 1\n var edge1Start = adsk.core.Point3D.create(xStart+ptEdgeOffset1.x, yStart+ptEdgeOffset1.y, 0);\n var edge1End = adsk.core.Point3D.create(xEnd +ptEdgeOffset1.x, yEnd +ptEdgeOffset1.y, 0);\n var line1 = sketchLines.addByTwoPoints( edge1Start, edge1End );\n\n // Start arc\n var arc1 = sketchArcs.addByCenterStartSweep( ptStart, edge1Start, Math.PI );\n\n // Edge 2\n var edge2Start = adsk.core.Point3D.create(xStart+ptEdgeOffset2.x, yStart+ptEdgeOffset2.y, 0);\n var edge2End = adsk.core.Point3D.create(xEnd +ptEdgeOffset2.x, yEnd +ptEdgeOffset2.y, 0);\n\n var line2 = sketchLines.addByTwoPoints( edge2Start, edge2End );\n\n // End arc\n var arc2 = sketchArcs.addByCenterStartSweep( ptEnd, edge2End, Math.PI );\n\n // These are the cutting holes and go in the other sketch\n // Start hole\n var circle1 = sketchCirclesHoles.addByCenterRadius( ptStart, afeModel.JointHoleDiameter/2 );\n\n // End hole\n var circle2 = sketchCirclesHoles.addByCenterRadius( ptEnd, afeModel.JointHoleDiameter/2 );\n\n // TODO: Text not supported in API\n // Create a text element to mark this line. String should match the\n // one added in the instructions sketch.\n\n // Enable now that geometry has been added to this sketch\n sketchParts.isComputeDeferred = false;\n }\n\n // Enable now that geometry has been added\n sketchPartsHoles.isComputeDeferred = false;\n\n // Create the extrusion.\n var extrudes = rootComp.features.extrudeFeatures;\n\n // Keep track of timeline so we can group these operations\n var timelineStartIndex = design.timeline.count;\n\n for (var iSketchParts = 0; iSketchParts < sketchPartsArray.length; ++iSketchParts)\n {\n var sketchParts = sketchPartsArray[iSketchParts];\n\n for (var iProf = 0; iProf < sketchParts.profiles.count; ++iProf)\n {\n var prof = sketchParts.profiles.item(iProf);\n var extInput = extrudes.createInput(prof, adsk.fusion.FeatureOperations.NewBodyFeatureOperation);\n\n var distance = adsk.core.ValueInput.createByReal(afeModel.ExtrudeDist);\n extInput.setDistanceExtent(false, distance);\n var ext = extrudes.add(extInput);\n\n var fc = ext.faces.item(0);\n var bd = fc.body;\n bd.name = 'AFE Part - ' + iSketchParts+'.'+iProf;\n }\n }\n\n // Cut the holes\n for (var iProfHoles = 0; iProfHoles < sketchPartsHoles.profiles.count; ++iProfHoles)\n {\n var prof = sketchPartsHoles.profiles.item(iProfHoles);\n var extInput = extrudes.createInput(prof, adsk.fusion.FeatureOperations.CutFeatureOperation);\n\n var distance = adsk.core.ValueInput.createByReal((sketchPartsArray.length + 1) * extrudeDistPerSketch);\n extInput.setDistanceExtent(false, distance);\n var ext = extrudes.add(extInput);\n\n var fc = ext.faces.item(0);\n var bd = fc.body;\n bd.name = 'AFE Part - ' + iProf;\n }\n\n // Now group these operations in the timeline\n var timelineEndIndex = design.timeline.count - 1;\n if (timelineEndIndex > timelineStartIndex)\n design.timeline.timelineGroups.add(timelineStartIndex, timelineEndIndex);\n }\n\n // Now fit the view to show new items\n app.activeViewport.fit();\n };\n\n try {\n\n if (adsk.debug === true) {\n /*jslint debug: true*/\n debugger;\n /*jslint debug: false*/\n }\n\n // Prompt first for the name of the AFE file to import\n var dlg = ui.createFileDialog();\n dlg.title = 'Import ForceEffect File';\n dlg.filter = 'ForceEffect (*.afe);;ForceEffect Motion (*.afem);;All Files (*.*)';\n if (dlg.showOpen() !== adsk.core.DialogResults.DialogOK) {\n adsk.terminate();\n return;\n }\n\n filename = dlg.filename;\n\n // Parse the file\n afeModel = parseAFEFile(filename);\n\n if (afeModel) {\n // Create and run command\n var command = createCommandDefinition();\n var commandCreatedEvent = command.commandCreated;\n commandCreatedEvent.add(onCommandCreated);\n\n command.execute();\n }\n }\n catch (e) {\n if (ui) {\n ui.messageBox('Failed : ' + (e.description ? e.description : e));\n }\n\n adsk.terminate();\n }\n}",
"function setHTCReviewer(vbRec,vbSubs,vbOwner,k) {\t\t\t\n\tvar f3 = new Array();\n\tf3[0] = new nlobjSearchFilter('custrecord_spk_sr_ap_clerk_subsidiary',null,'anyof',vbSubs);\n\tf3[1] = new nlobjSearchFilter('isinactive',null,'is','F');\t\t\t\t\t\n\tvar col3 = new Array();\n\tcol3[0] = new nlobjSearchColumn('custrecord_spk_senior_apclerk_field');\n\tvar searchResult = nlapiSearchRecord('customrecord_spk_sr_ap_clerk_offshore',null,f3,col3);\n\tif(searchResult) {\n\t\tvar htcReviewerRec = searchResult[0];\n\t\tvar htcReviewer = htcReviewerRec.getValue('custrecord_spk_senior_apclerk_field');\n\t\tvar delegate_htcReviewer = getDelegateApprover(htcReviewer);\n\t\tnlapiLogExecution('DEBUG', 'HTC Reviewer', delegate_htcReviewer);\n\t\tvbRec.selectNewLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_seq', k);\n\t\tif(delegate_htcReviewer) {\n\t\t\tvbRec.setFieldValue('custbody_spk_inv_apvr',delegate_htcReviewer);\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr',delegate_htcReviewer);\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_delgtof',htcReviewer);\n\t\t}\n\t\telse {\n\t\t\tvar apclerk = vbRec.setFieldValue('custbody_spk_inv_apvr',htcReviewer);\n\t\t\tnlapiLogExecution('DEBUG', 'apclerk', apclerk);\n\t\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvr', htcReviewer);\n\t\t}\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apvrl','HTC Reviewer');\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_apmanager',nlapiGetUser());\n\t\tvbRec.setCurrentLineItemValue('recmachcustrecord_spk_apvmtx_tranno', 'custrecord_spk_apvmtx_invown',vbOwner);\n\t\tvbRec.commitLineItem('recmachcustrecord_spk_apvmtx_tranno');\n\t}\n}",
"function main() {\n\tconsole.log('Abacus iPad App Generator.');\n console.log('Create flat basic styled app from converted spreadhseet.');\n\tDU.displayTag();\n\n\tif(ops.version){\n\t\tprocess.exit();\n\t}\n\n\tif(!ops.repoPath){\n\t\tconsole.error('Missing argument: --repoPath');\n\t\tops.printHelp();\n\t\tprocess.exit(-2);\n\t}\n\n\tif(!ops.engine){\n\t\tconsole.error('Missing argument: --engine');\n\t\tops.printHelp();\n\t\tprocess.exit(-2);\n\t}\n\n\tif (ops.instance){\n\t\tconfig.instance = S(ops.instance).slugify().s;\n\t}\n\n\tif(ops.language){\n\t\tconfig.language = ops.language;\n\t}\n\n\tif(ops.noExtract){\n\t\tconfig.extractEngine = false;\n\t}\n\n\tif(ops.numeric){\n\t\tconfig.usePageNames = false;\n\t}\n\n\t// mandatory arguments\n\tconfig.repoPath = ops.repoPath;\n\tconfig.engineFile = ops.engine;\n\n\t// call extract, pass in config\n\tAG.generate(config);\n}",
"function monitorBulletinBoard(adviseLaunchInfo, waitLoop) {\n \n var mcsUrl = adviseLaunchInfo['mcsUrl'],\n launchInfoUrl = '../resources/slmservices/advise/getAnalyticsLaunchInfo?caseID='+adviseLaunchInfo.caseID;\n \n if(mcsUrl.length > 0){\n launchInfoUrl + '&mcsURI=' + encodeURIComponent(mcsUrl)\n }\n \n jQuery.ajax({ url : launchInfoUrl,\n cache: false,\n }) \n .done(function(newLaunchInfo) {\n if(!jQuery.isEmptyObject(newLaunchInfo)){\n \tadviseLaunchInfo.eedTicket = newLaunchInfo.eedTicket;\n }\n tryTolaunchAdviseClient(adviseLaunchInfo, waitLoop);\n })\n .fail(function() {\n tryTolaunchAdviseClient(adviseLaunchInfo, waitLoop);\n }\n );\n}",
"function testAddDSMapReceipient(){\n let _id = \"12345\";//Math.floor((Math.random() * 1000) + 1);\n let _args = ['hash1','recipientEid','5A989A9D6B'];\n let _enrollAttr = [{name:'typeOfUser',value:'Student'},{name:\"eID\",value:\"studentEid\"}];\n let _invAttr = ['typeOfUser','eID'];\n let req = {\n // Name (hash) required for invoke\n chaincodeID: basic.config.chaincodeID,\n // Function to trigger\n fcn: \"addRecepientToDSMap\",\n // Parameters for the invoke function\n args: _args,\n //pass explicit attributes to teh query\n attrs: _invAttr\n };\n basic.enrollAndRegisterUsers(\"testStd\",_enrollAttr)\n .then(user => {\n basic.invoke(user,req).then(res=> {console.log(res);\n // process.exit(0);\n }).catch(err =>{\n console.log(err);\n process.exit(1);\n });\n }).catch(err =>{\n console.log(err);\n });\n}",
"function startAgentARFinder() {\n\n // Get options ARFinder.\n var options = getOptionsSearchAcademicReferences();\n\n // Check config automatic references.\n if (options.autoAcademicReferences === true){\n //var watchEachSeconds = options.checkArticle * 1000;\n var watchEachSeconds = 4000;\n window.setInterval(agentSuggestAcademicReferences, watchEachSeconds);\n }\n\n}",
"function loadExecution(model, resource, jsonld) {\n model.execution.iri = resource['@id'];\n model.pipeline.iri = jsonld.getReference(resource,\n 'http://etl.linkedpipes.com/ontology/pipeline');\n var status = jsonld.getReference(resource,\n 'http://etl.linkedpipes.com/ontology/status');\n model.execution.status.iri = status;\n switch (status) {\n case 'http://etl.linkedpipes.com/resources/status/finished':\n case 'http://etl.linkedpipes.com/resources/status/failed':\n case 'http://etl.linkedpipes.com/resources/status/cancelled':\n model.execution.status.running = false;\n break;\n default:\n model.execution.status.running = true;\n break;\n }\n model.execution.deleteWorkingData = jsonld.getBoolean(resource,\n 'http://linkedpipes.com/ontology/deleteWorkingData');\n }",
"function runSolrXform(log, config, environment, vprRecord, callback) {\n var metricsObj = {\n 'subsystem': 'SOLR',\n 'action': 'transform',\n 'uid': vprRecord.uid,\n 'pid': vprRecord.pid,\n 'process': uuid.v4(),\n 'timer': 'start'\n };\n environment.metrics.debug('SOLR record transformation', metricsObj);\n\n // This gives us a hook so that we can test this better via Unit tests.\n //---------------------------------------------------------------------\n var solrXform;\n if (!environment.solrXform) {\n solrXform = require(global.VX_UTILS + 'solr-xform');\n } else {\n solrXform = environment.solrXform;\n }\n\n solrXform(vprRecord, log, config, function(error, result) {\n metricsObj.timer = 'stop';\n\n var errorMessage;\n if (error) {\n environment.metrics.debug('SOLR record transformation in error', metricsObj);\n errorMessage = util.format('solr-record-storage-handler.runSolrXform: SOLR xform returned error: %s', error);\n log.error(errorMessage);\n return callback(errorUtil.createTransient('Unable to store record in solr', errorMessage));\n }\n\n if (!result) {\n environment.metrics.debug('SOLR record transformation in error', metricsObj);\n errorMessage = util.format('solr-record-storage-handler.handle: SOLR xform returned null. There is no SOLR record to store. uid: %s', vprRecord.uid);\n log.error(errorMessage);\n return callback(errorUtil.createTransient('Unable to store record in solr', errorMessage));\n }\n\n environment.metrics.debug('SOLR record transformation', metricsObj);\n callback(null, result);\n });\n}",
"function submitAppointmentLocationAndTime(UpdateMode,laneId,appointmentId,appointmentTimeFrome,appointmentTimeTo,isEncryptResponse, encryptionPassword){\n\t\n\tvar bodyRequest = '<sch:submitAppointmentLocationAndTimeRequest>';\n\t\tbodyRequest += '<sch:isUpdateMode>' + UpdateMode + '</sch:isUpdateMode>';\n\t\tbodyRequest += '<sch:appointment>';\n\t\t\tbodyRequest += '<sch:tlnId>' + laneId + '</sch:tlnId>';\n\t\t\tbodyRequest += '<sch:aptId>' + appointmentId + '</sch:aptId>';\n\t\t\tbodyRequest += '<sch:appointmentTimeFrom>' + appointmentTimeFrome + '</sch:appointmentTimeFrom>';\n\t\t\tbodyRequest += '<sch:appointmentTimeTo>' + appointmentTimeTo + '</sch:appointmentTimeTo>';\t\n\t\tbodyRequest += '</sch:appointment>';\n\t\tbodyRequest += '</sch:submitAppointmentLocationAndTimeRequest>';\n\n\t\n\tvar request = getRequestString(bodyRequest);\n\n\tvar requestObj = buildBody([ request ], true);\n\tMFP.Logger.warn(\"submitAppointmentLocationAndTime request | \" + requestObj);\n\tvar result = invokeWebServiceString(requestObj, isEncryptResponse,\n\t\t\tencryptionPassword);\n\tMFP.Logger.warn(\"submitAppointmentLocationAndTime result | \" + result);\n\treturn result\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a graph of all walkable boxes that are connected to each other | function createBoxGraph() {
var graph = new Graph();
for (var y = 0; y < map.length; ++y) {
for (var x = 0; x < map[y].length; ++x) {
if (map[y][x] !== WALL) {
graph.addNode(keyFromCoordinates(x, y), [x, y]);
}
}
}
for (var y = 0; y < map.length; ++y) {
for (var x = 0; x < map[y].length; ++x) {
if (map[y][x] === WALL) {
continue;
}
// Add straight boxes as edges with weight 1
var straightBoxes = nearBoxes(x, y, COORD_MODE_STRAIGHT,
FILTER_MODE_NO_WALL);
for (var i = 0; i < straightBoxes.length; ++i) {
var otherX = straightBoxes[i][0],
otherY = straightBoxes[i][1];
graph.addEdge(keyFromCoordinates(x, y),
keyFromCoordinates(otherX, otherY), 1);
grid.connectBoxes(x, y, otherX, otherY,
options.connectColor);
}
var filterMode = FILTER_MODE_NO_WALL |
FILTER_MODE_DIAGONAL_NOT_NEAR_WALL;
// Diagonal boxes have 1.4 weight.
var diagonalBoxes = nearBoxes(x, y, COORD_MODE_DIAGONAL,
filterMode);
for (var i = 0; i < diagonalBoxes.length; ++i) {
var otherX = diagonalBoxes[i][0],
otherY = diagonalBoxes[i][1];
graph.addEdge(keyFromCoordinates(x, y),
keyFromCoordinates(otherX, otherY),
DIAGONAL_WEIGHT);
grid.connectBoxes(x, y, otherX, otherY, options.connectColor);
}
}
}
grid.draw();
return graph;
} | [
"function drawNodesAndEdges(sourceTurns, canvas, ctx, dotAlpha, glyphMap) {\n var i,\n conVats = {}, // storing last turn in proc order, [vat name] = sourceturns index\n conx, cony, //stores previous draw position for turn\n src, //source file from prev vat\n elementMap; //map information for prev element\n\n if (canvas.getContext) {\n list(sourceTurns, function(turn) {\n var edge, //stores edge\n target, //stores edge target node\n targetGlyph, //target information from map\n nodeGlyph, //stores node information from glyphMap\n edgeGlyph, //stores edge information from glyphMap\n alphaFlag, //used to count edge alphas \n endx, endy, //end x and y values for arcs\n sign, //used to establish draw direction\n str, //string variable\n diffbez, //diff angle for bezier curves\n sb, eb; //holds bezier control pts\n\n nodeGlyph = glyphMap.get(turn.trnNode);\n\n //bar for concurrency\n ctx.fillStyle = TURNBAR_COLOR\n + Math.max(1 - (2 * turn.trnConc.length / 10), 0) + ')';\n ctx.fillRect(nodeGlyph.x + 10, 10, \n turn.trnEdges.length * 10 + 20, 10);\n\n ctx.fillStyle = \"black\";\n ctx.font = \"8pt Helvetica\";\n ctx.textAlign = \"left\";\n ctx.textBaseline = \"top\";\n ctx.fillText('' + turn.trnConc.length, nodeGlyph.x, 9);\n\n //draw nodes\n ctx.beginPath();\n ctx.fillStyle = NODE_COLOR + nodeGlyph.alpha + ')';\n ctx.fillRect(nodeGlyph.x + 5, nodeGlyph.y + 5, 5, 5);\n\n //highlight picked nodes with halos\n if (nodeGlyph.hlight) {\n ctx.fillStyle = EDGE_COLOR + '.2)';\n ctx.fillRect(nodeGlyph.x, nodeGlyph.y, 15, 15);\n }\n\n //setting transparancy flag for turns, \n //so not entire turn is opaque if not all edges are shown\n alphaFlag = 0;\n for (i = 0; i < turn.trnEdges.length; i += 1) {\n if (glyphMap.get(turn.trnEdges[i]).alpha === 1) {\n alphaFlag = i;\n }\n }\n\n conx = nodeGlyph.x + 7.5;\n cony = nodeGlyph.y + 7.5;\n\n //used for bezier curves to leave and\n //enter nodes at various angle\n diffbez = 10;\n //drawing sent events\n for (i = 0; i < turn.trnEdges.length; i += 1) {\n edge = turn.trnEdges[i];\n edgeGlyph = glyphMap.get(edge);\n\n\n //solid black lines between edge nodes within a turn\n ctx.beginPath();\n //opaque for process order\n if (dotAlpha === 1 && edgeGlyph.alpha !== 1) {\n ctx.strokeStyle = NODE_COLOR + '1)';\n } else if (i < alphaFlag) {\n ctx.strokeStyle = NODE_COLOR + nodeGlyph.alpha + ')';\n } else {\n ctx.strokeStyle = NODE_COLOR + edgeGlyph.alpha + ')';\n }\n ctx.moveTo(conx, cony);\n ctx.lineTo(edgeGlyph.x + 7.5, edgeGlyph.y + 7.5);\n ctx.stroke();\n\n conx = edgeGlyph.x + 7.5;\n cony = edgeGlyph.y + 7.5;\n\n //draw edge nodes\n ctx.beginPath();\n ctx.fillStyle = EDGE_COLOR + edgeGlyph.alpha + ')';\n ctx.fillRect(edgeGlyph.x + 5, edgeGlyph.y + 5, 5, 5);\n\n // highlight picked edges with halo\n if (edgeGlyph.hlight) {\n ctx.fillStyle = EDGE_COLOR + '.2)';\n ctx.fillRect(edgeGlyph.x, edgeGlyph.y, 15, 15);\n }\n\n target = edge.getTarget();\n\n //connect sent edges with bezier curves or mark fulfilleds \n if (sourceTurns[target.name] !== void 0) {\n targetGlyph = glyphMap.get(sourceTurns[target.name].trnNode);\n \n endx = targetGlyph.x + 7.5;\n endy = targetGlyph.y + 7.5;\n\n sign = endy > (edgeGlyph.y + 7.5) ? 1 : -1;\n\n //if fulfilled, mark the node\n //str = new String();\n str = '' + edge.traceRecord.class;\n if (str.match(\"Fulfilled\") !== null) {\n ctx.fillStyle = FULFILLED_COLOR + edgeGlyph.alpha + ')';\n //draw triangle\n ctx.beginPath();\n ctx.moveTo(endx - 2.5, edgeGlyph.y + 7.5);\n ctx.lineTo(endx + 2.5, edgeGlyph.y + 7.5);\n ctx.lineTo(endx, edgeGlyph.y + 7.5 + 20 * sign); //endy\n ctx.closePath();\n ctx.fill();\n ctx.strokeStyle = FULFILLED_COLOR + edgeGlyph.alpha + ')';\n //connect tip of triangle with node\n ctx.moveTo(endx, edgeGlyph.y + 7.5 + 20 * sign);\n ctx.lineTo(endx, endy);\n ctx.stroke();\n } else { // if sent, draw bezier\n //help differentiate bezier curves\n sb = edgeGlyph.y + 7.5 - sign * diffbez;\n eb = endy + sign * diffbez;\n ctx.moveTo(edgeGlyph.x + 7.5, edgeGlyph.y + 7.5);\n ctx.bezierCurveTo(endx, sb, edgeGlyph.x + 7.5, eb, endx, endy);\n ctx.strokeStyle = EDGE_COLOR + edgeGlyph.alpha + ')';\n ctx.stroke();\n diffbez += 5;\n }\n }\n\n }\n\n //line connecting nodes between vats, process order\n if (conVats[turn.name] === void 0) {\n conVats[turn.name] = turn.trnNode.name;\n } else {\n src = sourceTurns[conVats[turn.name]];\n if (src.trnEdges.length > 0) {\n elementMap = glyphMap.get(src.trnEdges[src.trnEdges.length - 1]);\n } else {\n elementMap = glyphMap.get(src.trnNode);\n }\n\n ctx.beginPath();\n ctx.strokeStyle = NODE_COLOR + dotAlpha + ')';\n dottedLine(ctx, elementMap.x + 7.5, elementMap.y + 7.5, \n nodeGlyph.x + 7.5, nodeGlyph.y + 7.5);\n ctx.stroke();\n //holds last known turn for specific vat\n conVats[turn.name] = turn.trnNode.name; \n }\n\n });\n\n //weird draw bug, wont go away unless I draw something irrelevant last\n ctx.beginPath();\n ctx.moveTo(0, 0);\n ctx.lineTo(10, 0);\n ctx.stroke();\n\n }\n }//drawNodesAndEdges()",
"function renderChildAndPartnerLinks() {\n for (const [, persons] of generations)\n for (const person of persons) {\n const personBox = jQuery(\"#box-\" + person.id);\n if (person.children)\n for (const child of person.children)\n drawPath(personBox, jQuery(\"#box-\" + child.id), \"link-child\");\n if (person.partners)\n for (const partner of person.partners)\n drawPartnerPath(personBox, jQuery(\"#box-\" + partner.id));\n }\n}",
"function findAllSCC(net) {\n let graph = net.getGraph()\n let verticies = graph.verticies\n let edges = graph.edges\n let map = net.nodesMap\n let allStrong = new Set()\n let i = 0\n let stack = []\n let visited = new Map() // visited maps tag to object with info like index, lowindex and onstack\n\n function findSCC(current) {\n visited.set(current, {index: i, lowlink: i, onStack: true})\n i++\n stack.push(current)\n\n for (let edge of edges) {\n if (edge.from === current && map.has(edge.to)) {\n let from = edge.from // same as current\n let to = edge.to\n\n if (!visited.has(to)) {\n findSCC(to)\n visited.get(from).lowlink = Math.min(visited.get(from).lowlink, visited.get(to).lowlink)\n } else if (stack.includes(to)) {\n visited.get(from).lowlink = Math.min(visited.get(from).lowlink, visited.get(to).index)\n }\n }\n }\n\n if (visited.get(current).lowlink === visited.get(current).index) {\n let stronglyConnected = new Set()\n\n let w = stack[stack.length - 1]\n do {\n w = stack.pop()\n visited.get(w).onStack = false\n stronglyConnected.add(w)\n } while (w != current)\n\n allStrong.add(stronglyConnected)\n }\n }\n\n for (let v of verticies) {\n if (!visited.has(v)) {\n findSCC(v)\n }\n }\n\n return allStrong\n}",
"function checkGrid(grid) {\n var oldSpace = [];\n grid.forEach(function(ary) {\n ary.forEach(function(box) {\n\n //var banned = document.getElementById(box.id-1); //do not allow\n var north = document.getElementById(box.id-20);\n var northEast = document.getElementById(box.id-19);\n var northWest = document.getElementById(box.id-21);\n var east = document.getElementById(parseInt(box.id)+1);\n var west = document.getElementById(box.id-1);\n var south = document.getElementById(parseInt(box.id)+20);\n var southEast = document.getElementById(parseInt(box.id)+21);\n var southWest = document.getElementById(parseInt(box.id)+19);\n var boxConnect = 0;\n\n // if((box.id % 20 === 0 && box.checked === true) && banned.checked === true) {\n // console.log(box.id + \" \" + banned.id);\n // }\n if((box.checked === true && box.id > 19) && north.checked === true) {\n //console.log(\"North: \" + box.id + \" \" + north.id);\n boxConnect++;\n }\n if((box.checked === true && box.id > 19) && northEast.checked === true) {\n //console.log(\"Northeast: \" + box.id + \" \" + northEast.id);\n boxConnect+=2;\n }\n if((box.checked === true && box.id % 20 !== 0) && (box.id > 19 && northWest.checked === true)) {\n //console.log(\"Northwest: \" + box.id + \" \" + northWest.id);\n boxConnect+=2;\n }\n if((box.checked === true && (parseInt(box.id)+1)%20 !== 0) && east.checked === true) {\n //console.log(\"East: \" + box.id + \" \" + east.id);\n boxConnect++;\n }\n if(box.checked === true && west.checked === true && (box.id-1)%20 !== 19) {\n //console.log(\"West: \" + box.id + \" \" + west.id);\n boxConnect++;\n }\n if((box.checked === true && box.id < 380) && south.checked === true) {\n //console.log(\"South: \" + box.id + \" \" + south.id);\n boxConnect++;\n }\n if(box.checked === true && (box.id < 380) && southEast.checked === true) {\n //console.log(\"Southeast: \" + box.id + \" \" + southEast.id);\n boxConnect+=2;\n }\n if((box.checked === true && box.id < 380) && southWest.checked === true) {\n //console.log(\"Southwest: \" + box.id + \" \" + southWest.id);\n boxConnect+=2;\n }\n\n function ridSingles() {\n if(boxConnect < 2) {\n box.checked = false;\n }\n }\n\n //1.store old box.id in array\n //2.uncheck old position during random space move\n //3.check new position after random space move with new box.id\n // *******THIS IS THE PROBLEM*******\n function moveBoxes() {\n var spaces = [1, -1, 19, 20, 21, -19, -20, -21];\n var randNewSpace = Math.floor(Math.random()*spaces.length);\n if(box.checked === true && box.id < 400 || box.id > 0){\n box.id = parseInt(box.id)+ parseInt(spaces[randNewSpace]);\n //console.log(parseInt(box.id) + parseInt(spaces[randNewSpace]));\n box.id = parseInt(box.id);\n }\n else if(box.checked === true && box.id > 400 || box.id < 0){\n box.checked = false;\n }\n }\n\n setInterval(function() {\n ridSingles();\n moveBoxes();\n }, 1000);\n });\n //console.log(ary);\n });\n\n}",
"markedAllConnector() {\n\n\t\tlet lstMarkedInput = []\n\t\tlet lstMarkedOutput = []\n\n\t\tlstMarkedOutput = this.vertexMgmt.edgeMgmt.dataContainer.edge.filter(e => {\n\t\t\treturn e.source.prop.indexOf('title') == -1 && e.source.vertexId == this.id\n\t\t})\n\n\t\tlstMarkedInput = this.vertexMgmt.edgeMgmt.dataContainer.edge.filter(e => {\n\t\t\treturn e.target.prop.indexOf('title') == -1 && e.target.vertexId == this.id\n\t\t})\n\n\t\tlstMarkedInput.forEach(e => {\n\t\t\td3.select(`[prop=\"${e.target.prop}\"][type=\"I\"]`).classed('marked_connector', true)\n\t\t})\n\n\t\tlstMarkedOutput.forEach(e => {\n\t\t\td3.select(`[prop=\"${e.source.prop}\"][type=\"O\"]`).classed('marked_connector', true)\n\t\t})\n\t}",
"function removeAndStoreSelfLoops(graph) {\n\n var selfLoopEdges = [];\n var deepCopyElement,\n index;\n\n for (index = 0; index < graph.edges.length; index++) {\n if (graph.edges[index].from === graph.edges[index].to) {\n deepCopyElement = $.extend(true, [], graph.edges[index]);\n selfLoopEdges.push(deepCopyElement)\n graph.edges.splice(index, 1);\n index--;\n }\n };\n\n return selfLoopEdges;\n}",
"function createNeighbors() {\n\tfor(var i = 0; i < cells.length; i++) {\n\t\tfor(var j = 0; j < cells[i].length; j++) {\n\t\t\tif(j == cells[i].length - 1)\n\t\t\t\tcells[i][j].neighbors.push(-1);\n\t\t\telse\n\t\t\t\tcells[i][j].neighbors.push(cells[i][j+1]);\n\t\t\t\n\t\t\tif(i == cells.length - 1)\n\t\t\t\tcells[i][j].neighbors.push(-1);\n\t\t\telse\n\t\t\t\tcells[i][j].neighbors.push(cells[i+1][j]);\n\t\t\t\t\n\t\t\tif(j == 0)\n\t\t\t\tcells[i][j].neighbors.push(-1);\n\t\t\telse\n\t\t\t\tcells[i][j].neighbors.push(cells[i][j-1]);\n\t\t\t\t\n\t\t\tif(i == 0)\n\t\t\t\tcells[i][j].neighbors.push(-1);\n\t\t\telse\n\t\t\t\tcells[i][j].neighbors.push(cells[i-1][j]);\n\t\t}\n\t}\n}",
"function draw_connections(i, j, ni, nj, rad, arch) {\n for (let ii = 1; ii <= ni; ii++) {\n for (let jj = 1; jj <= nj; jj++) {\n \n let begin = neuron_pos(i, ii, arch);\n let end = neuron_pos(j, jj, arch);\n \n let r = p5.Vector.sub(end, begin);\n r.mult(rad / r.mag());\n \n begin.add(r);\n r.mult(1.2);\n end.sub(r);\n \n // Obtain color from real weights\n let curr_layer = nn[str(iteration[i])].weights[str(i)];\n let neuron_from = ii-1;\n let neuron_to = jj-1;\n let alpha = curr_layer[neuron_to][neuron_from];\n let scale = 200;\n draw_arrow(begin, end, alpha * scale);\n }\n }\n}",
"hasMoreThanOneTree() {\n let connections = this.getConnections();\n let roles = this.getRoles();\n let trees = [];\n\n\n let DFSUtil = (v, visited) => {\n // Mark the current node as visited\n visited.push(v);\n\n // Recur for all the vertices adjacent to this vertex\n let neighbors = [];\n connections.forEach(connection => {\n if (connection.source.node === v) {\n neighbors.push(connection.target.node);\n }\n if (connection.target.node === v) {\n neighbors.push(connection.source.node);\n }\n });\n neighbors.forEach(neighbor => {\n if (!visited.includes(neighbor)) {\n DFSUtil(neighbor, visited);\n }\n });\n };\n\n // Call the recursive helper function to print DFS traversal\n // starting from all vertices one by one\n let visited = [];\n for (let i = 0; i < roles.length; ++i) {\n let discovered = [];\n if (!visited.includes(roles[i].id)) {\n DFSUtil(roles[i].id, discovered);\n visited = visited.concat(discovered);\n trees.push(discovered);\n }\n }\n\n return trees.length > 1;\n }",
"function createBoard(n) {\n let i, j;\n let text = `<svg height=\"${n * 30}\" width=\"${n * 30}\">`;\n for (i = 0; i < n; i++) {\n text += `<line x1=\"${i * 30 + 15}\" y1=\"15\" x2=\"${i * 30 + 15}\" \ny2=\"${n * 30 - 15}\" style=\"stroke:rgb(0,0,0);stroke-width:2\" />`;\n text += `<line x1=\"15\" y1=\"${i * 30 + 15}\" x2=\"${n * 30 - 15}\" y2=\"${i * 30 + 15}\" style=\"stroke:rgb(0,0,0);stroke-width:2\" />`;\n }\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n let x = i * 30 + 15;\n let y = j * 30 + 15;\n text += `<g id=\"x${i}y${j}\">\n<circle cx=\"${x}\" cy=\"${y}\" r=\"15\" stroke=\"black\" stroke-opacity=\"0\" />\n<g class=\"marker\">\n<path d=\"M ${x-8} ${y-2} L ${x-2} ${y-2} L ${x-2} ${y-8} z\"></path>\n<path d=\"M ${x-8} ${y+2} L ${x-2} ${y+2} L ${x-2} ${y+8} z\"></path>\n<path d=\"M ${x+8} ${y-2} L ${x+2} ${y-2} L ${x+2} ${y-8} z\"></path>\n<path d=\"M ${x+8} ${y+2} L ${x+2} ${y+2} L ${x+2} ${y+8} z\"></path>\n</g>\n<text id=\"text-x${i}y${j}\" x=\"${i * 30 + 15}\" y=\"${j * 30 + 15}\"></text></g>`;\n }\n }\n text += '</svg>';\n document.getElementById('board').innerHTML = text;\n board = createBoardObject(n);\n}",
"calculateMeshOutlines() {\n for (\n let vertexIndex = 0;\n vertexIndex < this.verticies.length;\n vertexIndex++\n ) {\n if (!this.checkedVerticies[vertexIndex]) {\n let newOutlineVertex = this.getConnectedOutlineVertex(vertexIndex);\n if (newOutlineVertex !== -1) {\n this.checkedVerticies[vertexIndex] = true;\n\n const newOutline = [vertexIndex];\n this.outlines.push(newOutline);\n this.followOutline(newOutlineVertex, this.outlines.length - 1);\n this.outlines[this.outlines.length - 1].push(vertexIndex);\n }\n }\n }\n }",
"printComparison() {\n var g = this.getComparisonGraph();\n\n var printJourney = function(jid) {\n var edges = g.$('edge');\n edges.map(function(e){\n console.log(\"Edge: \", e.data());\n })\n\n g.$('node').map(function(n){\n console.log('Node: ', n.data());\n })\n }\n\n console.log(\"IN:\");\n printJourney('IN');\n }",
"async [_makeIdealGraph] (options) {\n /* Make sure that the ideal tree is build as the rest of\n * the algorithm depends on it.\n */\n const bitOpt = {\n ...options,\n complete: false,\n }\n await this.buildIdealTree(bitOpt)\n const idealTree = this.idealTree\n\n this.rootNode = {}\n const root = this.rootNode\n this.counter = 0\n\n // memoize to cache generating proxy Nodes\n this.externalProxyMemo = memoize(this.externalProxy.bind(this))\n this.workspaceProxyMemo = memoize(this.workspaceProxy.bind(this))\n\n root.external = []\n root.isProjectRoot = true\n root.localLocation = idealTree.location\n root.localPath = idealTree.path\n root.workspaces = await Promise.all(\n Array.from(idealTree.fsChildren.values(), this.workspaceProxyMemo))\n const processed = new Set()\n const queue = [idealTree, ...idealTree.fsChildren]\n while (queue.length !== 0) {\n const next = queue.pop()\n if (processed.has(next.location)) {\n continue\n }\n processed.add(next.location)\n next.edgesOut.forEach(e => {\n if (!e.to || (next.package.bundleDependencies || next.package.bundledDependencies || []).includes(e.to.name)) {\n return\n }\n queue.push(e.to)\n })\n if (!next.isProjectRoot && !next.isWorkspace) {\n root.external.push(await this.externalProxyMemo(next))\n }\n }\n\n await this.assignCommonProperties(idealTree, root)\n\n this.idealGraph = root\n }",
"function createConnections(data) {\n // This is a pretty simple algorithm, it connects\n // grid neighbours that are within 1 cell distance,\n // or lie on the same row or column as each other\n const set = new Set();\n for (let i = 0; i < data.length; i++) {\n for (let j = 0; j < data.length; j++) {\n if (i === j) continue;\n const a = data[i];\n const b = data[j];\n\n const collinear = a.row === b.row || a.column === b.column;\n const neighbour =\n Math.abs(a.row - b.row) <= 1 && Math.abs(a.column - b.column) <= 1;\n\n if (neighbour || collinear) {\n const key = [i, j].sort((a, b) => a - b).join(\":\");\n set.add(key);\n }\n }\n }\n\n // Return actual objects, not indices\n return [...set].map((n) => {\n return n\n .split(\":\")\n .map((n) => parseInt(n, 10))\n .map((i) => data[i]);\n });\n\n return connections;\n}",
"function makeTree(){\n console.log(tree);\n for (var i = 0; i < tree.length; i++) {\n // Get the branch, update and draw it\n tree[i].update();\n tree[i].render();\n \n\n if (tree[i].timeToBranch()) {\n\n if (tree.length < matPool.length+3) {\n \n angle = (floor(random(70, 50)));\n tree.push(tree[i].branch(angle)); // Add one going right, angle randomly between 50,30\n angle = (floor(random(-70, -50)));\n tree.push(tree[i].branch(angle));// add one going left, angle randomly\n angle = (floor(random(20, 40)));\n tree.push(tree[i].branch(angle)); // Add one going right, angle randomly between 50,30\n angle = (floor(random(-20, -40)));\n tree.push(tree[i].branch(angle)); // Add one going right, angle randomly between 50,30\n \n } else {\n\n for (var i = 0; i < matPool.length; i++) {\n //draw the flowers in the matepool\n var gen = matPool[i].getDNA();\n var x=tree[i].end.x;\n var y=tree[i].end.y;\n var f = new Flower(gen,x,y);\n f.set();\n f.display();\n //console.log(i + \" \" + x +\" \"+ y);\n \n }\n //if the tree is ready stop loop until button1 is pressed\n noLoop();\n }\n }\n }\n}",
"function branchingPoints (paths, to, port) {\n var toMap = _.keyBy(to, 'node')\n // the paths that do not go through a continuation node\n var branchingPaths = _(paths)\n .reject((path) => _.find(path, (p) => toMap[p.node]))\n .map((path) => _.reverse(path))\n .value()\n // the pathes to the continuations (without the continuation itself)\n var contPaths = _(paths)\n .filter((path) => _.find(path, (p) => toMap[p.node]))\n .map(_.partial(pathToSetOfNodes, _, toMap))\n .value()\n // all nodes that branch away from a continuation\n var branchings = _(branchingPaths)\n // every branching path can have only ONE branching node (and it is always the farthest)\n .map((path) => _.maxBy(_.map(contPaths, (rpath) => {\n var simPath = pathPrefixes(path, rpath)\n return { path: path[simPath.length], length: simPath.length }\n }), (p) => p.length))\n .compact()\n .map((p) => p.path)\n .uniqBy((b) => b.node + '_P_' + b.port)\n .map((branch) => ({ node: branch.edge.to, branchPort: branch.edge.inPort }))\n .value()\n return _(branchings)\n .groupBy((b) => b.node)\n .map((value, key) => {\n return { node: value[0].node, port, type: 'branching', branchPorts: _.map(value, (v) => v.branchPort) }\n })\n .value()\n}",
"function generatePaths(numberofNodes, nodes) {\n // console.log(numberofNodes);\n // console.log(nodes);\n // Init a map to represent a given node as the key and list of connected nodes as the value\n const pathMap = {};\n for (let i = 0; i < numberofNodes; i++) {\n pathMap[i] = [];\n }\n \n // Populate the pathMap with the connected nodes\n for (let i = 0; i < nodes.length; i++) {\n const [source, destination] = nodes[i].replace(' ', '').split(',');\n pathMap[source].push(destination); \n }\n \n // console.log(pathMap);\n \n // Recursively generate the paths\n\n // Recursive helper function\n function generateNodePath(root) {\n const paths = pathMap[root];\n // Base case\n if (paths.length === 0) return root;\n \n // Generate paths for all connected nodes\n for (let i = 0; i < paths.length; i++) {\n // TODO: This only returns the path for the first item completely.\n // Need to save the result and only return once all paths for each\n // node in the loop is generated.\n return root.toString() + '->' + generateNodePath(paths[i]);\n }\n }\n \n const pathMapKeys = Object.keys(pathMap);\n for (let i = 0; i < pathMapKeys.length; i++) {\n const path = generateNodePath(pathMapKeys[i]);\n console.log(path);\n }\n}",
"function drawConnections() {\n var boxes = $('#jsplumb-container .jsplumb-box');\n var numEffects = boxes.length - 2;\n\n if (numEffects > 0) {\n boxes.each(function (i, element) {\n if (element.id === 'inputbox') {\n jsPlumb.connect({\n source: 'inputbox',\n target: 'box-0',\n uuids: ['ep-right-0', 'ep-left-1']\n });\n } else if (element.id !== 'outputbox') {\n var j = parseInt(element.id.charAt(4)); // box-j\n if (j < numEffects - 1) {\n jsPlumb.connect({\n source: 'box-' + j,\n target: 'box-' + (j + 1),\n uuids: ['ep-right-' + (j + 1), 'ep-left-' + (j + 2)]\n });\n } else {\n jsPlumb.connect({\n source: 'box-' + j,\n target: 'outputbox',\n uuids: ['ep-right-' + (j + 1), 'ep-left-0']\n });\n }\n }\n });\n } else {\n jsPlumb.connect({\n source: 'inputbox',\n target: 'outputbox',\n uuids: ['ep-right-0', 'ep-left-0']\n })\n }\n}",
"function findCycles(net) {\n let SCCs = findAllSCC(net)\n let cycles = new Set()\n let map = net.nodesMap\n\n for (let set of SCCs) {\n if (set.size > 1) {\n cycles.add(set)\n } else {\n let tag = [...set][0]\n let node = map.get(tag)\n if (node.forwardsLink.has(tag)) {\n cycles.add(set)\n }\n }\n }\n\n return cycles\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public function `function`. Returns true if `data` is a function, false otherwise. | function isFunction (data) {
return typeof data === 'function';
} | [
"function ISFUNCTION(value) {\n return value && Object.prototype.toString.call(value) == '[object Function]';\n}",
"function isValidFunctionExpression(node) {\n if (node && node.type === 'FunctionExpression' && node.body) {\n return true;\n }\n return false;\n}",
"function isCallback(node) {\n return node && node.type === typescript_estree_1.AST_NODE_TYPES.TSFunctionType;\n }",
"isFunctionOrBreed(value) {\n doCheck(\n value.constructor.name === \"Function\" || value.constructor === BreedType,\n \"Attempt to call a non-function\"\n );\n }",
"function function_exists(function_name)\n{\n\tif (typeof function_name === 'string')\n\t\tfunction_name = this.window[function_name];\n\treturn typeof function_name === 'function';\n}",
"hasCallback() {}",
"function check(callback,input){\n try{\n return callback(input);\n }catch(error){\n return false;\n }\n}",
"function typeOfFunction(value) {\r\n const x = (typeof value);\r\n \r\n return \"The value of \" + value + \" is a type of : \" + x;\r\n}",
"function match (data, regex) {\n return string(data) && !!data.match(regex);\n }",
"inFunction(context, keyword) {\n doCheck(\n context.currentFunction !== null,\n `${keyword} can only be used in a function`\n );\n }",
"function instanceOf(obj, func) {\n if (typeof func === 'function' && obj instanceof func) {\n return true;\n } else {\n return cajita.inheritsFrom(obj, getFakeProtoOf(func));\n }\n }",
"function isArgUsedInFunc(fcallexpr, arg) {\r\n\r\n // First find the called function object\r\n //\r\n var ind = getFuncIdByName(CurModObj, fcallexpr.str);\r\n var fO = CurModObj.allFuncs[ind];\r\n\r\n var argpos = arg + 1; // in header, 0th arg is ReturnValue \r\n var gid = fO.allSteps[FuncHeaderStepId].allGridIds[argpos];\r\n\r\n // Go thru all steps of the function and see whether this grid is used\r\n //\r\n for (var s = FuncHeaderStepId + 1; s < fO.allSteps.length; s++) {\r\n\r\n var stepO = fO.allSteps[s];\r\n\r\n for (var g = 0; g < stepO.allGridIds.length; g++) {\r\n\r\n if (stepO.allGridIds[g] == gid)\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n}",
"function typeOf(obj) {\n var result = typeof obj;\n if (result !== 'object') { return result; }\n if (null === obj) { return result; }\n if (cajita.inheritsFrom(obj, DisfunctionPrototype)) { return 'function'; }\n if (cajita.isFrozen(obj) && typeof obj.call === 'function') {\n return 'function';\n }\n return result;\n }",
"function hasData(cell)\n{\n if (cell == null) return 0;\n return cell.length != 0;\n}",
"validateInput(data, callback) {\n const value = this.getInputFromData(data);\n const result = value === undefined\n || value === null\n || typeof value === 'string'\n || (typeof value === 'object' && (typeof value.first === 'string'\n || value.first === null\n || typeof value.last === 'string'\n || value.last === null));\n utils.defer(callback, result);\n }",
"function ISDATE(value) {\n return value && Object.prototype.toString.call(value) == '[object Date]';\n}",
"function isMap (data) {\n return Object.prototype.toString.call(data) === '[object Map]';\n }",
"static isFailedFuncTrigger(result) {\n if (CommonUtil.isDict(result)) {\n for (const fid in result) {\n const funcResult = result[fid];\n if (CommonUtil.isFailedFuncResultCode(funcResult.code)) {\n return true;\n }\n if (!CommonUtil.isEmpty(funcResult.op_results)) {\n for (const opResult of Object.values(funcResult.op_results)) {\n if (CommonUtil.isFailedTx(opResult.result)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }",
"function checkHandler(handler, functionName) {\n if (typeof handler !== 'function') throw new TypeError(functionName, 'requires a handler that is a function!');\n}",
"function isValidData(field, type, len) {\n\treturn typeof(field) == type && field.trim().length > len ? field : false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replaces the prompt() function. Takes a string of text to inform the user, a function to execute when the user submits it, and an optional regex for form input validation. | function modalPrompt(text, func, regEx) {
$("#custom-modal-header").text("Prompt");
$("#custom-modal-text").text(text);
var customContent = $("#custom-modal-content");
var form = $("<form>", { class: "modal-form", id: "custom-modal-form", method: "POST" });
// Input will only add a regex for validation if it's specified in the function call.
var formInput = $("<input>", { class: "modal-input", id: "custom-modal-input", pattern: regEx });
customContent.append(form);
form.append(formInput);
$("#custom-modal").css("display", "block");
form.on("submit", function (e) {
e.preventDefault();
var data = $("#custom-modal-input").val();
func(data);
closeModal(form);
})
} | [
"function promptUsername() {\n setInputFlow(submitUsername, true);\n\n print('Please enter your username in the box below');\n}",
"function TestInput() {\n //get text user provided for regex\n const regexText = RegExp(document.getElementById(\"regexText\").value);\n\n //get text user provided to test with\n const userText = document.getElementById(\"userText\").value;\n\n //test to see if the user test text can be handled by regex\n document.getElementById(\"checkMatch\").value = regexText.test(userText);\n}",
"prompt(text, callback) {\n let wrap = this.element.appendChild(document.createElement(\"div\"))\n wrap.textContent = text + \" \"\n let input = wrap.appendChild(document.createElement(\"input\"))\n input.addEventListener(\"keydown\", event => {\n if (event.keyCode == 13) {\n let replace = document.createElement(\"span\")\n replace.textContent = input.value\n wrap.replaceChild(replace, input)\n callback(input.value, replace)\n }\n })\n input.focus()\n }",
"function proc() {\n\tvar procedure = prompt(\"Enter Procedure Name\", document.getElementById('proc').innerHTML);\n\tif (procedure == \"\" || procedure == \" \" || procedure == null)\n\t\treturn;\n\telse\n\t\tdocument.getElementById('proc').innerHTML = procedure;\n}",
"function answer_regex(answer) {\n if (answer == null) {\n $('.answer').append('<p>Your regex returned null</p>');\n }else{\n $('.answer').append('<p>Your regex returned true</p>');\n }\n $('.answer').fadeIn();\n }",
"function updatePrompt(str) {\n prompt.text(str)\n}",
"function Simplification() {\r\n var regEx = document.getElementsByClassName(\"simpli\")[0].value;\r\n var text = document.getElementsByClassName(\"simpli\")[1].value;\r\n\r\n var re = new RegExp(regEx);\r\n\r\n var reponse = re.exec(text);\r\n document.getElementById(\"testSimpli\").value = reponse;\r\n\r\n}",
"function takeUserInput(value){\n if(value !== 'Submit' && value !== '<' && value !== 'C' && userInput.length < 4){\n userInput += value;\n print();\n }\n else{\n switch(value){\n case 'Submit': // if the submit button is pressed then call the isValid() function\n // to check whether the userInput is valid or not.\n tries--;\n isValid();\n break;\n case '<': // backspace statement.\n if(userInput.length > 0){\n userInput = userInput.substr(0, userInput.length -1); \n print();\n }\n break;\n case 'C': // delets all the userInput\n reset();\n }\n }\n\n function print(){ // prints the real time userInput value.\n userText.value = userInput;\n }\n\n } // end function registerInput();",
"function ValidateAndCompareInput()\r\n{\r\n\tvar strWild = $(\"wild\").value;\r\n\tvar strTame = $(\"tame\").value;\r\n\tvar strMessage = \"\";\r\n\t\r\n\t// Validation: Make sure we have two input strings.\r\n\tif ((typeof strWild == 'string' || strWild instanceof String) &&\r\n\t\t(typeof strTame == 'string' || strTame instanceof String))\r\n\t{\r\n\t\tlet bMatch = RegExWildCompare(strWild, strTame);\r\n\t\t\r\n\t\tif (bMatch)\r\n\t\t{\r\n\t\t\t$(\"result\").firstChild.nodeValue = \"Match.\";\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t$(\"result\").firstChild.nodeValue = \"No match.\";\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\t$(\"result\").firstChild.nodeValue = \"Please enter 'tame' and 'wild' text strings.\";\r\n\t}\r\n\t\r\n\treturn;\r\n}",
"_promptForEmail() {\n return this._prompt([\n {\n type: 'input',\n name: 'email',\n message: 'What is your email address?',\n validate: (input) => {\n return true; // @todo should be an email\n }\n }\n ])\n .then(({ email }) => {\n return email;\n });\n }",
"function commandTrigger() {\n var line = promptText;\n if (typeof config.commandValidate == 'function') {\n var ret = config.commandValidate(line);\n if (ret == true || ret == false) {\n if (ret) {\n handleCommand();\n }\n } else {\n commandResult(ret, \"jquery-console-message-error\");\n }\n } else {\n handleCommand();\n }\n }",
"function newPasswordPrompt(xcoord,ycoord,pw){\n\tif (verboseDebugging){\n\t\tconsole.log(\"we in new pw prompt nao\");\n\t\tconsole.log(\"pw is: \");\n\t\tconsole.log(pw);\n\t}\n\tmessageDiv.style.display = \"none\";\n\t//Gather prompt arguments and pass them along to handler.\n\tvar initCoords = {};\n\tinitCoords.xcoord = xcoord;\n\tinitCoords.ycoord = ycoord;\n\n\t//set up new prompt in HTML DOM. Make sure that defaults are reset.\n\tdisplayPassword(\"If you wish to set a new password, enter it and confirm.\\nIf you wish to keep the previous password, press Don't Change\\nIf you wish to keep the tile public, press Make Public\",\n\t\t\t\t\tcheckPasswordMatch,pw,initCoords);\n\n}",
"function initialPrompts() {\n userChoice = window.alert(\n \"Before generating your password, you must select some criteria for your password. Click ok to follow on to the next set of instructions.\"\n );\n userChoice = window.alert(\n \"In the upcoming pop-up, type what set of criteria you may want for your password. The options you may select are: 'capital: for capital letters; special: for special characters; number: for numbers in your password. Click ok to proceed to the typing prompt.'\"\n );\n userChoice = window.prompt(\n \"Type your criteria\",\n \"Capital; Number; Special\"\n );\n /* Converts users input to upper case to minimize input mistakes */\n userChoice = userChoice.toUpperCase();\n /* Prints out what the user has selected in the console for developer to check their choice! Helps to see if code is operational. */\n console.log(\n \"The user has selected \" +\n userChoice +\n \" as their criteria. End of initialPrompts function\"\n );\n\n if (!userChoice) {\n return;\n }\n\n selectCriteria();\n }",
"function journalEntry() {\r\n let journalEntry = prompt(` Okay ${userName} , Reflect on why you chose what you did. Describe how that rating makes you feel,why you chose that, how it makes you feel to have that rating, and plans for the upcoming days either change it or keep it the same! Please press the button under PRESS Here to log your answer !`, \" Please press the button under PRESS HERE after completing this entry!\");\r\n console.log(` You journal entry was: ${journalEntry}`);\r\n return journalEntry;\r\n // Enter in as much text as necessary about what you learned, how you felt, and plans for the upcoming days\r\n\r\n // what do I do with what I have here, \r\n}",
"function checkverifychar(formname,fieldname,message)\n{\n\tvar e=eval(\"document.\" + formname + \".\" + fieldname);\n\t//var alphaExp = new RegExp(\"[a-zA-Z\"+allowchar+\"]\", \"g\");\n\tvar validRegExp = /^[a-zA-Z]+$/\n\t//var alphaExp = new RegExp(\"[a-zA-Z]\", \"g\");\n\tvar isValid = validRegExp.test(e.value);\n\tif(!isValid)\n\t{\n\t\talert(message);\n\t\te.focus();\n\t\treturn false;\n\t}\n\treturn true;\n}",
"function showQuestion(){\n var lstrMessage = '';\n lstrMessageID = showQuestion.arguments[0];\n lobjField = showQuestion.arguments[1];\n lstrCaleeFunction = funcname(arguments.caller.callee);\n //Array to store Place Holder Replacement\n var larrMessage = new Array() ;\n var insertPosition ;\n var counter = 0 ;\n\n larrMessage = showQuestion.arguments[2];\n \n lstrMessage = getErrorMsg(lstrMessageID);\n \n if(larrMessage != null &&\n larrMessage.length > 0 ){\n\n while((insertPosition = lstrMessage.indexOf('#')) > -1){\n\n if(larrMessage[counter] == null ){\n larrMessage[counter] = \"\";\n }\n lstrMessage = lstrMessage.substring(0,insertPosition) +\n larrMessage[counter] +\n lstrMessage.substring(insertPosition+1,lstrMessage.length);\n counter++;\n }\n }\n\n //lstrFinalMsg = lstrMessageID + ' : ' + lstrMessage;\n lstrFinalMsg = lstrMessage;\n\n if(lobjField!=null){\n lobjField.focus();\n }\n var cnfUser = confirm(lstrFinalMsg);\n if( !cnfUser ) {\n isErrFlg = true;\n }\n if(cnfUser && lstrCaleeFunction == 'onLoad'){\n \tdisableButtons('2');\n }\n //End ADD BY SACHIN\n return cnfUser;\n}",
"function promptTeamName() {return inquirer.prompt([{name:\"teamName\" ,type:\"input\" ,message:\"TeamInfo: Team's Name?\" }]);}",
"function jsValidate(argForm, argInputField) {\n // If the user input needs to be checked for more characters then please add additional chrs\n // in the parentheses of search method. For e.g. to add \";\" change it to \".search(/[|~;]/)\".\n var textToValidate = eval(\"document.\"+argForm+\".\"+argInputField+\".value\");\n var searchResult = textToValidate.search(/[|~]/); \n if (searchResult != -1 ) {\n alert(\"<emxUtil:i18nScript localize='i18nId'>emxComponents.JSFunction.InvalidChars</emxUtil:i18nScript>\" +\n \"<emxUtil:i18nScript localize='i18nId'>emxComponents.JSFunction.InputAlert</emxUtil:i18nScript>\");\n eval(\"document.\"+argForm+\".\"+argInputField+\".focus()\");\n return false;\n }\n return true;\n }",
"function promptControl() {\n\tvar ballName = \"\";\n\tif (ball == 0) {\n\t\tballName = \"first\";\n\t} else if (ball == 1) {\n\t\tballName = \"second\";\n\t} else {\n\t\tballName = \"final\";\n\t}\n\n\t$scope.prompt = 'Frame ' + (frame + 1) + ', throw your ' + ballName + ' ball.'\n\tif (gameOver) {$scope.prompt = \"Game Over. Thanks for Playing.\"};\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copy this `HttpHeaderResponse`, overriding its contents with the given parameter hash. | clone(update = {}) {
// Perform a straightforward initialization of the new HttpHeaderResponse,
// overriding the current parameters with new ones if given.
return new HttpHeaderResponse({
headers: update.headers || this.headers,
status: update.status !== undefined ? update.status : this.status,
statusText: update.statusText || this.statusText,
url: update.url || this.url || undefined,
});
} | [
"copyHeaders(clientRes, serverRes) {\n Object.entries(clientRes.headers.raw()).forEach(([key, value]) => {\n if (key.toLowerCase() === \"location\") {\n //handle location redirects to hide microservice\n let newLocation = new URL(value[0]);\n newLocation.hostname = this.gatewayURL.hostname\n newLocation.port = this.gatewayURL.port\n console.log(\"replacing \"+value[0]+\" with \"+newLocation.href)\n value[0] = newLocation.href;\n }\n //console.log(key + \"->\" + value)\n serverRes.setHeader(key, value[0])\n });\n }",
"function TrackerSetHeader(\n Authorization = '',\n ppr = '',\n deltaId = '',\n deltamatic = '',\n channelId = '',\n appId = '',\n sessionId = ''\n ) {\n _HEADER = {\n Authorization: Authorization,\n UserAgent: `PPR|${ppr}, DL|${deltaId}, DLM|${deltamatic}`,\n channeId: channelId,\n appId: appId,\n sessId: sessionId\n }\n}",
"function cloneStatus( targetResponse, sourceResponse ) {\n return targetResponse.status( sourceResponse.statusCode );\n}",
"function setHeaderProp(name, value) {\n _HEADER[name] = value;\n}",
"setHeader(key, value) {\n this._headers[key] = value\n }",
"appendRobotHeaders()\n\t{\n\t\tconst xRobotsTag = this.currentResponse.headers[\"x-robots-tag\"];\n\n\t\t// @todo https://github.com/nodejs/node/issues/3591\n\t\tif (xRobotsTag != null)\n\t\t{\n\t\t\tthis.currentRobots.header(xRobotsTag);\n\t\t}\n\t}",
"copy() {\n return new $625ad1e1f4c43bc1$export$680ea196effce5f(this.hour, this.minute, this.second, this.millisecond);\n }",
"defaultHeaders(otherHeaders = {}) {\n\n let acceptHeaders = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n }\n\n return Object.assign({}, acceptHeaders, otherHeaders)\n }",
"function setHashKey(obj, h) {\n\t\tif (h) {\n\t\t\tobj.$$hashKey = h;\n\t\t}\n\t\telse {\n\t\t\tdelete obj.$$hashKey;\n\t\t}\n\t}",
"function cloneResponse(material) {\n return material_management_1.cloneMaterial(material);\n}",
"update() {\r\n this.updateHeader();\r\n }",
"clone() {\n let stats = {};\n this.forEachStat((name, value) => stats[name] = value)\n return new BirdStats(stats);\n }",
"static updatePaymentResponseStructure(response) {\n var authResp = response.payment.authentication;\n response.method = authResp.method;\n response.url = authResp.url;\n\n if (response.method == \"POST\") {\n response.params = Array();\n\n for (var key of Object.values(Object.keys(authResp.params))) {\n response.params[key] = authResp.params[key];\n }\n }\n\n delete response.payment;\n return response;\n }",
"function sha1Hmac(pass) {\n sjcl.misc.hmac.call(this, pass, sjcl.hash.sha1);\n }",
"function constructResponseHeaders(request, response) {\n\n //header array we'll eventually print, plus our own\n let finalHeaders = response.getHeaders();\n\n if (!finalHeaders) {\n finalHeaders = {}\n }\n\n finalHeaders = getSafeResponseHeaders(finalHeaders);\n \n //We look at all the request headers, and for each, we prepend x-fwd- and add them to the response headers array\n for (const [headerName, valuesForHeaderName] of Object.entries(request.getHeaders())) {\n var newHeaderName = 'x-fwd-' + headerName;\n finalHeaders[newHeaderName] = [];\n valuesForHeaderName.forEach((headerVal) => {\n finalHeaders[newHeaderName].push(headerVal);\n });\n }\n\n return finalHeaders;\n}",
"copy() {\n if (this.era) return new $625ad1e1f4c43bc1$export$ca871e8dbb80966f(this.calendar, this.era, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n else return new $625ad1e1f4c43bc1$export$ca871e8dbb80966f(this.calendar, this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);\n }",
"process_rendering_result_headers(arg_rendering_result_headers=[]/*, arg_credentials*/)\n\t{\n\t\tthis.debug('process_rendering_result_headers:rendering headers', arg_rendering_result_headers)\n\t\t\n\t\t// TODO\n\n\t\t// arg_rendering_result_headers.forEach(\n\t\t// \t(header)=>{\n\t\t// \t\tconst has_header = false // TODO\n\t\t// \t\t// const e = document.createElement(header)\n\t\t// \t\t// document.head.appendChild(e)// TODO\n\t\t// \t}\n\t\t// )\n\t}",
"function clone (buffer) {\r\n return copy(buffer, shallow(buffer));\r\n}",
"constructor() { \n \n UpdateExportSettingsS3Response.initialize(this);\n }",
"function prepareQuery(hash) {\n\t'use strict';\n\tds.historics.prepare({\n\t\t'hash': hash,\n\t\t'start': startTime,\n\t\t'end': endTime,\n\t\t'sources': 'twitter',\n\t\t'name': 'Example historic query'\n\t}, function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Prepared query: ' + response.id);\n\t\t\tcreateSubscription(response.id);\n\t\t}\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
connectes to a server with this IP (creates it in the list if it doesnt Exist) | function gameServerConnectForIP(serverIP, autoClickPlay = false) {
console.log("connecting to server of IP: " + serverIP);
//find if it exists
var serverObj = findGameServerObjForIP(serverIP);
//console.log("server for ip " + serverIP + " is " + findGameServerObjForIP(serverIP).name);
/*//create server DEF if it doesnt exist?
if(serverObj==null){
}*/
if (serverObj == null) {
console.log("No client server DEF exists for server IP " + serverIP);
addServerDef("Unknown server", serverIP, "Unknown servers");
}
gameServerConnect(serverObj, autoClickPlay);
} | [
"function addNewClient(socket) {\n //pushing each new client connection's id into an array of clientIDs -JT\n if (clientSockets.length < 1) {\n clientSockets.push(socket);\n clientCount++;\n } else {\n // Make sure not to store multiple clients with the same id\n var isMatch = false;\n for(i = 0; i < clientSockets.length; i++) {\n if (socket.id === clientSockets[i].id) {\n isMatch = true;\n // console.log(\"Socket already exists\");\n }\n }\n if (!isMatch) {\n clientSockets.push(socket);\n clientCount++;\n }\n }\n} // End addNewClient()",
"function addServer(server) {\n\n\tvar\n\t\tself = this;\n\n\t// Add server to our list\n\tself._servers.push(server);\n\n\t// Wait for connections\n\tserver.on('connection',function(c){\n\t\tself._serverClients.push(self._newSClient(c));\n\t});\n\n}",
"function isIPConnected(socket) {\n // Check if this sockets ip address is already exists in the clientSockets array\n for (i = 0; i < clientSockets.length; i++) {\n // socket.handshake.address returns the IP address\n if (socket.handshake.address === clientSockets[i].handshake.address) {\n return true;\n }\n }\n return false;\n} // End isIPConnected()",
"function replaceExistingClient(socket) {\n // console.log(\"[New client replacement]\");\n for(i = 0; i < clientSockets.length; i++) {\n // console.log(\"socket: \" + socket.handshake.address);\n // console.log(\"clientSockets [\" + i + \"]: \" + clientSockets[i].handshake.address);\n if (socket.handshake.address === clientSockets[i].handshake.address) {\n clientSockets[i] = socket;\n }\n }\n} // End replaceExistingClient()",
"function start() {\n test();\n var httpService = http.createServer(serve);\n httpService.listen(ports[0], '0.0.0.0');\n\n var options = {\n key: key,\n cert: cert\n };\n var httpsService = https.createServer(options, serve);\n httpsService.listen(ports[1], '0.0.0.0');\n\n var clients = clientService(httpsService);\n clients.onNewPos(updateEvents);\n\n printAddresses();\n}",
"function setupInterfaceList()\n{\n\tlet interfaces = os.networkInterfaces();\n\t\n\tif(interfaces)\n\t{\n\t\tfor(let interfaceName in interfaces)\n\t\t{\n\t\t\tinterfaces[interfaceName].forEach((addressInfo) =>\n\t\t\t{\n\t\t\t\tif(addressInfo.internal == false && addressInfo.family == 'IPv4' &&\n\t\t\t\t\t(!sockets.hasOwnProperty(interfaceName) || sockets[interfaceName].address().address != addressInfo.address))\n\t\t\t\t{\n\t\t\t\t\tlet socket = udp.createSocket({type: 'udp4', reuseAddr: true});\n\t\t\t\t\t\n\t\t\t\t\tsocket.on('message', handleDiscoveryResponse);\n\t\t\t\t\tsocket.on('error', (error) => {console.log('Socket error: ' + error)});\n\t\t\t\t\t\n\t\t\t\t\tsocket.on('listening', () =>\n\t\t\t\t\t{\n\t\t\t\t\t\tsocket.addMembership(multicastAddress, addressInfo.address);\n\t\t\t\t\t\tsocket.setMulticastTTL(128);\n\t\t\t\t\t});\n\t\t\t\t\t\n\t\t\t\t\t//Need to specify both port 0 (so it finds a free one) and the\n\t\t\t\t\t//interface address (so it listens on the current device's IP).\n\t\t\t\t\tsocket.bind(0, addressInfo.address);\n\t\t\t\t\t\n\t\t\t\t\tif(sockets.hasOwnProperty(interfaceName))\n\t\t\t\t\t{\n\t\t\t\t\t\tsockets[interfaceName].close();\n\t\t\t\t\t\tconsole.log('Updating interface ', interfaceName, ' with address ', addressInfo.address);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tconsole.log('Adding interface ', interfaceName, ' with address ', addressInfo.address);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tsockets[interfaceName] = socket;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\telse\n\t{\n\t\tconsole.log('Error getting network interfaces.');\n\t}\n}",
"function connect() {\n client.connect(function (_remote, conn) {\n self.remote = _remote; \n clearInterval(reconnectionTimer);\n conn.on('end', function(){\n //\n // Attempt reconnection\n //\n reconnectionTimer = setInterval(function(){\n connect();\n }, 3000)\n });\n self.emit('browser::ready');\n });\n }",
"function checkConnection(){\n\tdns.lookup('google.com',function(err) {\n\t\n \tif (err && err.code == \"ENOTFOUND\") {\n \t connected = 0;\n \t}\n\t\telse{\n\t\t\t\tconnected = 1;\n\t\t}\n\t});\n}",
"function showServerStarted() {\n var ifs = require('os').networkInterfaces();\n var currentIP = Object.keys(ifs)\n .map(x => [x, ifs[x].filter(x => x.family === 'IPv4')[0]])\n .filter(x => x[1])\n .map(x => x[1].address);\n\n dialog.showMessageBox({\n type: 'info',\n message: `Open http://${currentIP[1]}:3000/admin on another computer to control the cautions and warnings`,\n buttons: ['ok']\n });\n}",
"function register_proxy (uri, succeed, fail)\n{\n var options = url.parse(url.resolve(base, uri));\n \n test_host(options.hostname, \n function () {\n // local host so use local thing\n var thing = registry[options.href];\n \n if (thing)\n succeed(thing.thing);\n else // not yet created\n {\n console.log('waiting for ' + uri + ' to be created');\n record_handler(uri, succeed);\n }\n },\n function () {\n // remote host so find proxy\n console.log(options.hostname + \" is remote\");\n launch_proxy(options, succeed, fail);\n },\n function () {\n // unknown host name\n fail(\"server couldn't determine IP address for \" + options.hostname);\n });\n}",
"function addNewUser(socket, user){\n var findUsers = users.filter(function(us){\n if(us.email === user.email)\n return true;\n return false;\n });\n if(!findUsers.length){\n isNewUser = true;\n socket.email = user.email;\n socket.nickname = user.nickname;\n socket.avatar = user.avatar;\n socket.unique = getUnique(user.email);\n users.push(socket);\n io.sockets.emit('newUserConnect', {unique: getUnique(), nickname: user.nickname, avatar: user.avatar});\n }else{\n //User connect again.......\n }\n }",
"function addPeer(gun, ip, port) {\n //const oldPeers = gun.opt()['_'].opt.peers;\n return gun.opt({peers: [`http: *${ip}:${port}/gun`]}); // Should these be linked both ways?\n }",
"function initOSCserver() {\n\n //use the network IP as the OSC server.\n getNetworkIPs(function (error, ip) {\n if (!error) { \n //return first IP address only\n serverIP = (ip.constructor === Array)? ip[0] : ip;\n } else {\n if( process.env.NODE_ENV === 'development') {\n console.log('error:', error);\n }\n serverIP = '127.0.0.1';\n }\n\n //devel\n if( process.env.NODE_ENV === 'development') {\n console.log('#########################');\n console.log(\"OSC server IP is: \" + serverIP);\n }\n });\n}",
"_connect () {\n if (this._reconnectionInterval) {\n this._reconnectionInterval = clearInterval(this._reconnectionInterval)\n }\n\n if (this._connection && this.isConnected) {\n return\n }\n\n this._connection = new WebSocket(\n this._host + this._createQueryString()\n )\n\n this._connectionAttemps++\n this._listen()\n }",
"add(server) {\n let spec = server.spec;\n if (spec in this.collection) {\n // TODO Add error message area on page.\n console.error(sprintf(\"server '%s' already exists\", spec));\n return;\n }\n this.collection[spec] = server;\n }",
"listSockets() {\n var list = this.players.map(player => player.socketID);\n list.push(this.hostID);\n return list;\n }",
"function updateHosts(ip, host) {\n if (!hosts[ip] || hosts[ip].indexOf('*') != 0 && host != getHost(ip)) {\n\thosts[ip] = host;\n\tsaveHosts();\n\tconsole.log('Added host', ip + ':', host);\n }\n}",
"async function ipfsDefaultPeer() {\n await ipfs.swarm.connect(defaultPeer);\n }",
"addPeer() {\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace multiple constraints which upper bound or lower bound a param type with the lub or glb, respectively, of the concrete bound. | mergeConcreteBounds() {
let idmap = {};
let lower = {};
let upper = {};
let other = [];
for (let c of this.constraints.constraints) {
let a = c.lower;
let b = c.upper;
if (a.isParam()) idmap[a.id] = a;
if (b.isParam()) idmap[b.id] = b;
if (a.isParam() && b.isConcrete()) {
lower[a.id] = (a.id in lower) ? glb(lower[a.id], b) : b;
} else if (b.isParam() && a.isConcrete()) {
upper[b.id] = (b.id in upper) ? lub(upper[b.id], a) : a;
} else {
other.push(c);
}
}
if (lower.length === 0 && upper.length === 0) {
return null;
}
Object.keys(lower).forEach(id => other.push(new Constraint(idmap[id], lower[id])));
Object.keys(upper).forEach(id => other.push(new Constraint(upper[id], idmap[id])));
return new ConstraintSet(other);
} | [
"function geneBaseBounds(gn, min, max) {\n var gd = genedefs[gn];\n var gg = guigenes[gn];\n if (gd === undefined) return;\n if (gd.basemin === gd.min) {\n gd.min = min;\n gg.minEle.value = min;\n gg.sliderEle.min = min;\n }\n gd.basemin = min;\n if (gd.basemax === gd.max) {\n gd.max = max;\n gg.maxEle.value = max;\n gg.sliderEle.max = max;\n }\n gd.basemax = max;\n\n gg.deltaEle.value = gd.delta;\n gg.stepEle.value = gd.step;\n}",
"function toLatLngBounds(mixed) {\n var ne, sw;\n if (!mixed || mixed instanceof google.maps.LatLngBounds) {\n return mixed || null;\n }\n if ($.isArray(mixed)) {\n if (mixed.length == 2) {\n ne = toLatLng(mixed[0]);\n sw = toLatLng(mixed[1]);\n } else if (mixed.length == 4) {\n ne = toLatLng([mixed[0], mixed[1]]);\n sw = toLatLng([mixed[2], mixed[3]]);\n }\n } else {\n if ((\"ne\" in mixed) && (\"sw\" in mixed)) {\n ne = toLatLng(mixed.ne);\n sw = toLatLng(mixed.sw);\n } else if ((\"n\" in mixed) && (\"e\" in mixed) && (\"s\" in mixed) && (\"w\" in mixed)) {\n ne = toLatLng([mixed.n, mixed.e]);\n sw = toLatLng([mixed.s, mixed.w]);\n }\n }\n if (ne && sw) {\n return new google.maps.LatLngBounds(sw, ne);\n }\n return null;\n }",
"function geneBounds(gn, min, max) {\n var gd = genedefs[gn];\n if (gd === undefined) return;\n min = min !== undefined ? min : gd.basemin;\n max = max !== undefined ? max : gd.basemax;\n gd.min = min;\n gd.max = max;\n var gg = guigenes[gn];\n if (gg) {\n gg.minEle.value = min;\n gg.maxEle.value = max;\n gg.deltaEle.value = gd.delta;\n gg.stepEle.value = gd.step;\n gg.sliderEle.min = min;\n gg.sliderEle.max = max;\n }\n}",
"function unionBounds( a, b, target ) {\n\n\tlet aVal, bVal;\n\tfor ( let d = 0; d < 3; d ++ ) {\n\n\t\tconst d3 = d + 3;\n\n\t\t// set the minimum values\n\t\taVal = a[ d ];\n\t\tbVal = b[ d ];\n\t\ttarget[ d ] = aVal < bVal ? aVal : bVal;\n\n\t\t// set the max values\n\t\taVal = a[ d3 ];\n\t\tbVal = b[ d3 ];\n\t\ttarget[ d3 ] = aVal > bVal ? aVal : bVal;\n\n\t}\n\n}",
"function solveHomogeneous() {\n // No free variables - so we've got only trivial solution\n if(boundVariables.length == n)\n return null;\n\n // Get basis vectors corresponding to free variables\n var basis = [];\n for(var x = 0, i = 0; x < n; x++) {\n // Since boundVariables is strictly monotonic increasing sequence,\n // it is easy to get indices of free variables from it. (missing numbers)\n if(i >= boundVariables.length || boundVariables[i] != x) {\n var v = math.zeros(n, 1);\n v.set([x, 0], 1);\n\n basis.push(v);\n }\n\n else\n i++;\n }\n\n // Gauss backward substitution\n // Loop through rows corresponding to bound variables\n for(var row = boundVariables.length - 1; row >= 0; row--) {\n var x = boundVariables[row];\n var col = x;\n\n console.assert(math.equal(r.get([row, col]), 1), 'Pivot point must be 1');\n\n // Solve variable in each basis vector\n basis.map(function(v) {\n // We got a row:\n // 0 0 ... 0 1 A B C ... = 0, where 1 is in x column and A B C are in solved variables columns\n // so express bound variable x via solved variables\n\n // Multiply row by solved variables\n var value = math.multiply(\n r.subset(math.index(row, math.range(0, columns))),\n v.subset(math.index(math.range(0, n), 0))\n );\n\n // It seems value may turn out to be 1x1 matrix, so get rid of this wrap\n if(math.typeof(value) == 'Matrix')\n value = value.get([0, 0]);\n\n // Finally solve this variable\n v.set([x, 0], math.multiply(-1, value)); // Should be divided by 1 as well (pivot point)\n\n return v;\n });\n }\n\n return basis;\n }",
"function bound (n, min, max) {\n return Math.min(max, Math.max(min, n))\n}",
"function ParameterKliRelVlaga(parent, name, id, mval, bval) {\n Parameter.apply(this, [parent, name, id, mval, bval]);\n this.min = new Number(0);\n this.max = 100;\n}",
"function process_rigid_body_joints(obj) {\n\n // already processed\n if (has_constraint(obj))\n return;\n\n for (var i = 0; i < obj.physics_constraints.length; i++) {\n var cons = obj.physics_constraints[i];\n var targ = cons.target;\n var pivot_type = cons.pivot_type;\n\n if (!targ.physics)\n continue;\n\n var trans = get_rbj_trans(cons);\n var quat = get_rbj_quat(cons);\n\n var local = m_tsr.identity(_tsr_tmp);\n\n local = m_tsr.set_trans(trans, local);\n local = m_tsr.set_quat(quat, local);\n\n var world_a = m_tsr.multiply(obj.render.world_tsr, local, _tsr_tmp);\n\n var world_b_inv = m_tsr.invert(targ.render.world_tsr, _tsr_tmp2);\n\n var local_b = m_tsr.multiply(world_b_inv, world_a, world_b_inv);\n\n var local_b_tra = m_tsr.get_trans_view(local_b);\n var local_b_qua = m_tsr.get_quat_view(local_b);\n\n var limits = prepare_limits(cons);\n\n apply_constraint(pivot_type, obj, trans, quat, targ, local_b_tra,\n local_b_qua, limits, null, null);\n }\n}",
"visitReplace_type_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitBounds_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function changeAbr(player, min, max) {\n if (!player || !player.videoTracks[0]) {\n console.warn(\"No qualities yet available.\");\n }\n const allQualities = player.videoTracks[0].qualities;\n const qualities = [];\n if (!min && min !== 0 && !max && max !== 0) {\n console.warn(\"Not changing ABR ladder.\");\n } else {\n for (let i = 0; i < allQualities.length; i++) {\n const height = allQualities[i].height;\n if (!min && height <= max) {\n qualities.push(allQualities[i]);\n } else if (!max && height >= min) {\n qualities.push(allQualities[i]);\n } else if (height >= min && height <= max) {\n qualities.push(allQualities[i]);\n }\n }\n player.videoTracks[0].targetQuality = qualities;\n }\n}",
"function setupCommonRangeCheckingValidation(prototype, noun, nouns,\r\n\t\tminProperty, maxProperty, valueProperty, converter) {\r\n\tsetupCommonAndMaxLengthRangeCheckingValidation(prototype, noun, nouns,\r\n\t\tminProperty, maxProperty, valueProperty, converter, null);\r\n}",
"function constrain(n, min, max) {\n if (n < min) n = min;\n if (n > max) n = max;\n return n;\n}",
"function ReplaceParams() {\n var result = arguments[0];\n for (var iArg = 1; iArg < arguments.length; iArg++) { // Start at second arg (first arg is the pattern)\n var pattern = new RegExp('%' + iArg + '\\\\w*%');\n result = result.replace(pattern, arguments[iArg]);\n }\n return result;\n}",
"onItemBoundsModifiedNotification(bounds) {\n this._setBounds(bounds, false);\n }",
"function ServerBehavior_setParameters(mapNameToVals)\n{\n if (this.bInEditMode)\n {\n this.applyParameters = mapNameToVals;\n }\n else\n {\n this.parameters = mapNameToVals;\n }\n}",
"normalizeInputParameters() {\n if (this._max) this.handlePrecision(this._max);\n if (this._min) this.handlePrecision(this._min);\n if (this._step) this.handlePrecision(this._step);\n\n this._previousValue = this.value;\n }",
"function setRestrParameters(){\n\tvar panel = rplmClauseController.abRplmAddEditClausesAmntType;\n\tif(rplmClauseController.itemType == 'BUILDING'){\n\t\tpanel.addParameter('bl_restr', \"bl_amenity.bl_id = '\"+rplmClauseController.selectedId+\"'\");\n\t\tpanel.addParameter('pr_restr', \"prop_amenity.pr_id IN (SELECT pr_id FROM bl WHERE bl.bl_id = '\"+rplmClauseController.itemId+\"')\");\n\t}else{\n\t\tpanel.addParameter('bl_restr', \"bl_amenity.bl_id IN (SELECT bl_id FROM bl WHERE bl.pr_id = '\"+rplmClauseController.itemId+\"')\");\n\t\tpanel.addParameter('pr_restr', \" prop_amenity.pr_id = '\"+rplmClauseController.itemId+\"'\");\n\t}\t\n}",
"bounds(bounds) {\n this._edgeSegment.bounds(bounds);\n }",
"function replaceFuncArg(fcallexpr, pos, newExpr) {\r\n\r\n // find the function object of this function call\r\n //\r\n var ind = getFuncIdByName(CurModObj, fcallexpr.str);\r\n var fO = CurModObj.allFuncs[ind];\r\n //\r\n // find the gridObj corresponding to 'pos' in function header\r\n //\r\n var gidHead = fO.allSteps[FuncHeaderStepId].allGridIds[pos + 1];\r\n var gOhead = fO.allGrids[gidHead];\r\n\r\n // We ALWAYS check whether the newExpr and the grid in the function \r\n // prototype matches, when we do a replace.\r\n //\r\n if (newExpr.isScalarOrGridCell()) { // newExpr is scalar\r\n\r\n\r\n\tif (newExpr.isLetName()) {\r\n\r\n\t // if the new expression is a LetName, just check whether func arg\r\n\t // is scalar (because let is always sclar value)\r\n\t //\r\n\t if (gOhead.numDims > 0) {\r\n\t\talert(\"Existing argument in function header is not scalar\");\r\n\t\treturn false;\r\n\t }\r\n\t \r\n } else if (gOhead.numDims > 0) {\r\n\r\n // The function header has a non-scalar (i.e., a gridRef) arg\r\n //\r\n alert(\"Existing argument in function header is not scalar\");\r\n return false;\r\n\r\n } else if (gOhead.dataTypes[0] != findDataTypeOfScalarExpr(newExpr)) {\r\n\r\n // For a scalar grid, the data types must match. If not, the user\r\n // can change the function header (or use a different arg)\r\n //\r\n alert(\r\n \"Data Type mismatch. Use correct type arg OR change the \" +\r\n \" data type in function header\");\r\n\r\n return false;\r\n }\r\n\r\n } else { // newExpr is not scalar\r\n\r\n if (gOhead.numDims < 1) {\r\n\r\n alert(\"Existing argument in function header is scalar\");\r\n return false;\r\n }\r\n\r\n // TODO: Do other type checks here and return if not compatible.\r\n // E.g., (1) check \r\n\r\n\r\n\r\n }\r\n\r\n // We are here because the argument in function header and the newExr\r\n // match. So, we can safely replace the argument in the function call.\r\n // NO updates to the function header is made.\r\n //\r\n fcallexpr.exprArr.splice(pos, 1, newExpr);\r\n\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When taskId changed we should update the input | updateTaskIdInput() {
this.setState({taskIdInput: this.state.taskId});
} | [
"onTaskUpdated(task, updatedData) {\n const tasks = this.tasks.slice();\n const oldTask = tasks.splice(tasks.indexOf(task), 1, Object.assign({}, task, updatedData))[0];\n this.tasksUpdated.next(tasks);\n // Creating an activity log for the updated task\n this.activityService.logActivity(\n this.activitySubject.id,\n 'tasks',\n 'A task was updated',\n `The task \"${limitWithEllipsis(oldTask.title, 30)}\" was updated on #${this.activitySubject.document.data._id}.`\n );\n }",
"updateTask(e) {\n const taskValue = e.target.value;\n const keyForTask = Math.round(Math.random() * Math.floor(999999));\n\n const updatedTask = {};\n \n updatedTask[keyForTask] = taskValue; \n\n this.setState({\n [e.target.name]: updatedTask\n });\n\n }",
"function updateTask() {\n\t$('#tasks-list').on('keyup', '#taskBox-title', function(){ \n\t\tvar title = this.value;\n\t\tvar ref = this.getAttribute('data-ref');\n\t\tTaskManager.update(ref, title, null);\n\t});\n\n\t$('#tasks-list').on('keyup', '#taskBox-body', function(){ \n\t\tvar body = this.value;\n\t\tvar ref = this.getAttribute('data-ref');\n\n\t\tTaskManager.update(ref, null, body);\n\t});\n\n}",
"update(_task) {\n const { id, task, date, process } = _task\n let sql = `UPDATE tasks\n SET task = ?,\n date = ?,\n process = ?\n WHERE id = ?`;\n return this.dao.run(sql, [task, date, process, id])\n }",
"set task (value) {\n if (this._mem.work === undefined) {\n this._mem.work = {};\n }\n this._mem.work.task = value;\n }",
"taskUpdate(token, taskID, name, dueDate) {\n return fetch(`${this.url}/task/update`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n token: token,\n taskID: taskID,\n name: name,\n dueDate: dueDate\n })\n })\n }",
"function upDateTaskPhaseInLocalStorage(taskToUpdate, phase) {\r\n let LocalStorageTaskArray = getLocalStorage(\"task\");\r\n let taskTitle = document.getElementById(taskToUpdate).firstElementChild.innerHTML;\r\n let index = LocalStorageTaskArray.findIndex(obj => obj.name === taskTitle);\r\n LocalStorageTaskArray[index].phase = phase;\r\n setLocalStorage(\"task\", LocalStorageTaskArray);\r\n}",
"function findAndUpdateTask(taskID, nextTeamID) {\n\n for (var updateCounter = 0; updateCounter < this.tasksArray.length; updateCounter++) {\n var tempTask = this.tasksArray[updateCounter];\n if (tempTask.taskID == taskID) {\n //alert(nextTeamID + \" \" + taskID);\n if (tempTask.numberOfUnitsCompleted != tempTask.maximumEstimatedUnits) {\n if (tempTask.numberOfUnitsCompleted < tempTask.maximumEstimatedUnits) {\n tempTask.Increment();\n }\n } else {\n /*\n Not convinced the update of unitOfWorkCompleted should be happening here\n */\n this.unitOfWorkCompleted = this.unitOfWorkCompleted + tempTask.maximumEstimatedUnits;\n tempTask.numberOfUnitsCompleted = 0;\n // It is already done ... move to next team\n this.tasksArray.splice(updateCounter, 1);\n return tempTask;\n }\n }\n }\n\n return null;\n}",
"function SelectedProcessChanged(){\n \n GetCurrentProcessFromCombo();\n \n LoadTaskArray();\n \n _curSelectedTask = null;\n \n LoadSLDiagram();\n \n ShowTaskPanel(false);\n \n ShowProcessProperties();\n}",
"moveToTasksDone(task) {\n if (task !== \"\") {\n this.state.tasksDone.push(task);\n const index = this.state.toDoTasks.indexOf(task);\n this.state.toDoTasks.splice(index,1);\n this.setState({\n toDoTasks: this.state.toDoTasks,\n tasksDone: this.state.tasksDone\n })\n }\n }",
"function updateTaskById(id, { description, done }) {\n\tconst task = getTaskById(id);\n\tif (done !== undefined) {\n\t\ttask.done = !!done;\n\t}\n\tif (description) {\n\t\ttask.description = description;\n\t}\n\treturn task; //注:这里的思路与拆分前的有差异,这里是直接更改原task的属性,拆分前的版本是新建task再替换。\n}",
"function task_update_todoist(task_name, project_id, todoist_api_token) {\n todoist_api_token = todoist_api_token || 'a14f98a6b546b044dbb84bcd8eee47fbe3788671'\n return todoist_add_tasks_ajax(todoist_api_token, {\n \"content\": task_name,\n \"project_id\": project_id\n }, 'item_update')\n}",
"function updateTaskInfo(opt){\n var title = $('#task-title');\n var description = $('#task-description');\n var initDate = $('#task-init-date');\n var endDate = $('#task-end-date');\n var status = $('#task-status');\n var currentOpt = $(\"#\" + opt.id);\n\n var statusBadges = {\n 'New' : $('#status-new'),\n 'In progress' : $('#status-in-prog'),\n 'Waiting' : $('#status-freeze'),\n 'Closed' : $('#status-done')\n };\n\n //Set the task data\n title.text(currentOpt.data(\"tname\"));\n description.text(currentOpt.data(\"tdescrp\"));\n initDate.text( currentOpt.data(\"indate\") );\n endDate.text( currentOpt.data(\"endate\") );\n\n //Set the current status\n if(currentStatus != null){\n currentStatus.addClass(\"d-none\");\n }\n\n statusBadges[currentOpt.data(\"status\")].removeClass(\"d-none\");\n currentStatus = statusBadges[currentOpt.data(\"status\")];\n}",
"update(evnt) {\n evnt.preventDefault();\n let todoitem = this.state.todoitem;\n let field = evnt.target.name;\n todoitem[field] = evnt.target.value;\n this.setState({\n todoitem\n });\n }",
"function impact(task){\r\n\r\n }",
"function moveTask(index, task, value) {\n $scope.schedule[$scope.currentUserId].splice(index, 1);\n if (value == 1) {\n $scope.schedule[$scope.currentUserId].splice(index - 1, 0, task);\n } else {\n $scope.schedule[$scope.currentUserId].splice(index + 1, 0, task);\n }\n saveUserSchedule();\n }",
"function addTask() {\n let taskToSend = {\n task: $('#taskIn').val(),\n };\n\n saveTask(taskToSend);\n clearInputs();\n}",
"createTask(task) {\n this.state.todos.push({\n task,\n isCompleted: false\n });\n \n //set state with updated todos array\n this.setState({todos: this.state.todos})\n }",
"submitAnnotationEdit(){\n\t\t\t// let index = this.selected.props.index;\n\t\t\t// let theChannels = this.state.annotationObjects[this.selected.props.channel];\n\t\t\t// //update the annotation that is selected, by creating a new collection of annotations and modifying it\n\t\t\t// //this.state.annotationObjects[index].annotation = this.newAnnotationText\n\t\t\t//;\n\t\t\t// let newAnnotationObjects = Object.create(theChannel);\n\t\t\t// newAnnotationObjects[index].annotation = this.newAnnotationText\n\t\t\t//;\n\t\t\tlet newAnnotationMap = new annotationMap(this.state.annotationObjects).editAnnotation(this.selected.props.channels, this.selected.props.quote, this.annotation.value);\n\t\t\tthis.updateState({\n\t\t\t\tannotationObjects: newAnnotationMap,\n });\n\t\t\tthis.newAnnotationChannels = newAnnotationMap.keysAsArray();\n\t\t\tthis.prevOperation = this.operation;\n\t\t\tthis.operation = \"edit\";\n\t\t\tthis.switchAnnotationStyle();\n\t\t}",
"updateTodo() {\n this.todos[this.editTodo.index].text = this.editTodo.text;\n\n this.cancelTodo();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load purchase price history for the given part | function loadPurchasePriceHistoryTable(options={}) {
var part = options.part;
if (!part) {
console.error('No part provided to loadPurchasePriceHistoryTable');
return;
}
var table = options.table || $('#part-purchase-history-table');
var chartElement = options.chart || $('#part-purchase-history-chart');
var chart = null;
options.params = options.params || {};
options.params.base_part = part;
options.params.part_detail = true;
options.params.order_detail = true;
options.params.has_pricing = true;
// Purchase order must be 'COMPLETE'
options.params.order_status = {{ PurchaseOrderStatus.COMPLETE } | [
"function loadBomPricingChart(options={}) {\n\n var part = options.part;\n\n if (!part) {\n console.error('No part provided to loadBomPricingChart');\n return;\n }\n\n var table = options.table || $('#bom-pricing-table');\n var chartElement = options.table || $('#bom-pricing-chart');\n\n var chart = null;\n\n options.params = options.params || {};\n\n options.params.part = part;\n options.params.sub_part_detail = true;\n options.params.ordering = 'name';\n options.params.has_pricing = true;\n\n table.inventreeTable({\n url: '{% url \"api-bom-list\" %}',\n name: 'bompricingtable',\n queryParams: options.params,\n original: options.params,\n paginationVAlign: 'bottom',\n pageSize: 10,\n search: false,\n showColumns: false,\n formatNoMatches: function() {\n return '{% trans \"No BOM data available\" %}';\n },\n onLoadSuccess: function(data) {\n // Construct BOM pricing chart\n // Note here that we use stacked bars to denote \"min\" and \"max\" costs\n\n // Ignore any entries without pricing information\n data = data.filter((x) => x.pricing_min != null || x.pricing_max != null);\n\n // Sort in decreasing order of \"maximum price\"\n data = data.sort(function(a, b) {\n var pa = parseFloat(a.quantity * (a.pricing_max || a.pricing_min));\n var pb = parseFloat(b.quantity * (b.pricing_max || b.pricing_min));\n\n return pb - pa;\n });\n\n var graphLabels = Array.from(data, (x) => x.sub_part_detail.name);\n var minValues = Array.from(data, (x) => x.quantity * (x.pricing_min || x.pricing_max));\n var maxValues = Array.from(data, (x) => x.quantity * (x.pricing_max || x.pricing_min));\n\n if (chart) {\n chart.destroy();\n }\n\n // Generate colors\n var colors = Array.from(data, (x) => randomColor());\n\n chart = loadDoughnutChart(chartElement, {\n labels: graphLabels,\n datasets: [\n {\n label: '{% trans \"Maximum Price\" %}',\n data: maxValues,\n backgroundColor: colors,\n },\n {\n label: '{% trans \"Minimum Price\" %}',\n data: minValues,\n backgroundColor: colors,\n },\n ]\n });\n\n },\n columns: [\n {\n field: 'sub_part',\n title: '{% trans \"Part\" %}',\n sortable: true,\n formatter: function(value, row) {\n var url = `/part/${row.sub_part}/`;\n\n var part = row.sub_part_detail;\n\n return imageHoverIcon(part.thumbnail) + renderLink(part.full_name, url);\n },\n },\n {\n field: 'quantity',\n title: '{% trans \"Quantity\" %}',\n sortable: true,\n },\n {\n field: 'reference',\n title: '{% trans \"Reference\" %}',\n sortable: true,\n },\n {\n field: 'pricing',\n title: '{% trans \"Price Range\" %}',\n sortable: false,\n formatter: function(value, row) {\n var min_price = row.pricing_min;\n var max_price = row.pricing_max;\n\n if (min_price == null && max_price == null) {\n // No pricing information available at all\n return null;\n }\n\n // If pricing is the same, return single value\n if (min_price == max_price) {\n return formatCurrency(min_price * row.quantity);\n }\n\n var output = '';\n\n if (min_price != null) {\n output += formatCurrency(min_price * row.quantity);\n\n if (max_price != null) {\n output += ' - ';\n }\n }\n\n if (max_price != null) {\n output += formatCurrency(max_price * row.quantity);\n }\n\n return output;\n }\n }\n ]\n });\n}",
"function loadPartSupplierPricingTable(options={}) {\n\n var part = options.part;\n\n if (!part) {\n console.error('No part provided to loadPartSupplierPricingTable');\n return;\n }\n\n var table = options.table || $('#part-supplier-pricing-table');\n var chartElement = options.chart || $('#part-supplier-pricing-chart');\n\n var chart = null;\n\n options.params = options.params || {};\n\n options.params.base_part = part;\n options.params.supplier_detail = true;\n options.params.part_detail = true;\n\n table.inventreeTable({\n url: '{% url \"api-part-supplier-price-list\" %}',\n name: 'partsupplierprice',\n queryParams: options.params,\n original: options.params,\n paginationVAlign: 'bottom',\n pageSize: 10,\n pageList: null,\n search: false,\n showColumns: false,\n formatNoMatches: function() {\n return '{% trans \"No supplier pricing data available\" %}';\n },\n onLoadSuccess: function(data) {\n // Update supplier pricing chart\n\n // Only allow values with pricing information\n data = data.filter((x) => x.price != null);\n\n // Sort in increasing order of quantity\n data = data.sort((a, b) => (a.quantity - b.quantity));\n\n var graphLabels = Array.from(data, (x) => (`${x.part_detail.SKU} - {% trans \"Quantity\" %} ${x.quantity}`));\n var graphValues = Array.from(data, (x) => (x.price / x.part_detail.pack_quantity_native));\n\n if (chart) {\n chart.destroy();\n }\n\n chart = loadBarChart(chartElement, {\n labels: graphLabels,\n datasets: [\n {\n label: '{% trans \"Supplier Pricing\" %}',\n data: graphValues,\n backgroundColor: 'rgba(255, 206, 86, 0.2)',\n borderColor: 'rgb(255, 206, 86)',\n stepped: true,\n fill: true,\n }\n ]\n });\n },\n columns: [\n {\n field: 'supplier',\n title: '{% trans \"Supplier\" %}',\n formatter: function(value, row) {\n var html = '';\n\n html += imageHoverIcon(row.supplier_detail.image);\n html += renderLink(row.supplier_detail.name, `/company/${row.supplier}/`);\n\n return html;\n }\n },\n {\n field: 'sku',\n title: '{% trans \"SKU\" %}',\n sortable: true,\n formatter: function(value, row) {\n return renderLink(\n row.part_detail.SKU,\n `/supplier-part/${row.part}/`\n );\n }\n },\n {\n sortable: true,\n field: 'quantity',\n title: '{% trans \"Quantity\" %}',\n },\n {\n sortable: true,\n field: 'price',\n title: '{% trans \"Unit Price\" %}',\n formatter: function(value, row) {\n\n if (row.price == null) {\n return '-';\n }\n\n // Convert to unit pricing\n var unit_price = row.price / row.part_detail.pack_quantity_native;\n\n var html = formatCurrency(unit_price, {\n currency: row.price_currency\n });\n\n if (row.updated != null) {\n html += `<span class='badge badge-right rounded-pill bg-dark'>${renderDate(row.updated)}</span>`;\n }\n\n\n return html;\n }\n }\n ]\n });\n}",
"historicalOrderbook(symbol_id, time_start, time_end, limit, limit_levels) {\n const params = this._getParamString({\n time_start: time_start,\n time_end: time_end,\n limit: limit,\n limit_levels: limit_levels\n });\n return this._request(`/v1/orderbooks/${symbol_id}/history${params}`)\n }",
"onRecordLoad(event) {\n const record = event.detail && event.detail.records && event.detail.records[this.recordId];\n this.addRecordToCache(record);\n this.handleRecordFields(record);\n }",
"getHistoricalAccountData(address, startHeight, endHeight, increment) {\n return rxjs_1.of(\"historical/get?address=\" + address.plain() + \"&startHeight=\" + startHeight + \"&endHeight=\" + endHeight + \"&increment=\" + increment)\n .pipe(operators_1.flatMap((url) => requestPromise.get(this.nextHistoricalNode() + url, { json: true })), operators_1.retryWhen(this.replyWhenRequestError), operators_1.map((historicalAccountData) => {\n return historicalAccountData.data.map((accountHistoricalDataViewModelDTO) => {\n return AccountHistoricalInfo_1.AccountHistoricalInfo.createFromAccountHistoricalDataViewModelDTO(accountHistoricalDataViewModelDTO);\n });\n }));\n }",
"function loadProducts() {\n API.getProducts()\n .then(res => {\n setProducts(res.data);\n })\n .catch(err => console.log(err));\n API.getAverage()\n .then(res => {\n res.data[0] ?\n setAverage(res.data[0].average.toFixed(2)) :\n setAverage(0)\n })\n }",
"function fetchData() {\n client.subscribe(\"/fx/prices\", function (data) { //subscribing for updates\n rawData.push(JSON.parse(data.body)); //storing retrived data\n });\n}",
"function handle_bp_cart_hist(req, startTime, apiName) {\n this.req = req; this.startTime = startTime; this.apiName = apiName;\n}",
"function pullLivePriceData(url){\n var reqq = new XMLHttpRequest();\n reqq.open(\"GET\", url, false);\n reqq.send(null);\n var r = JSON.parse(reqq.response);\n return r;\n}",
"loadStocks() {\n stockService.get((err, data) => {\n if (err) return this.handleError(err);\n\n // the latest list of stocks on database\n const stocks = JSON.parse(data);\n\n // the list of stock symbols's currently on chart\n const chartedStockSymbols = this.stockChart.series.map((series) => {\n return series.name;\n });\n\n stocks.forEach((stock) => {\n // only get the pricing data of not-charted stock symbols\n if (chartedStockSymbols.indexOf(stock) == -1) {\n this.getStock(stock.symbol);\n }\n });\n\n this.stockSocket.start();\n });\n }",
"function fundsPrices() {\n loadTable();\n loadShowAll_btn();\n }",
"function displayHistory() {\r\n\tvar oLength = orderData.length;\r\n\tvar pLength = productData.length;\r\n\t//alert(pLength);\r\n\tvar oInfo = ''; //for adding new order\r\n\tvar n = 0;\r\n\tvar ohl = dom('orderHistoryList');\r\n\tvar tempID = 0;\r\n\tvar proName = '';\r\n\tvar iInfo = ''; //for adding new item in an existing order\r\n\tfor(var i=0;i<oLength;i++){\r\n\t\tif(tempID != orderData[i].order_id){\r\n\t\t\ttempID = orderData[i].order_id;\r\n\t\t\tfor(var t=0;t<pLength;t++){\r\n\t\t\t\tif(orderData[i].product_id == productData[t].product_id){\r\n\t\t\t\t\tproName = productData[t].productname;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tn = i+1;\r\n\t\t\toInfo = \r\n\t\t\t\t'<li class=\"order\" id=\"order_' + n + '\">' +\r\n\t\t\t\t\t'<span class=\"orderID\">' + orderData[i].order_id + '</span>' +\r\n\t\t\t\t\t'<span class=\"orderItems\">' +\r\n\t\t\t\t\t\t'<ul id=\"orderitem_' + tempID +'\">' +\r\n\t\t\t\t\t\t\t'<li>' +\r\n\t\t\t\t\t\t\t\t'<span class=\"itemName\">' + proName + '</span>' +\r\n\t\t\t\t\t\t\t\t'<span class=\"itemAmount\">' + orderData[i].amount + '</span>' +\r\n\t\t\t\t\t\t\t\t'<span class=\"itemTotalPrice\">' + orderData[i].totalprice + ' kr</span>' +\r\n\t\t\t\t\t\t\t'</li>' +\r\n\t\t\t\t\t\t'</ul>' +\r\n\t\t\t\t\t'</span>' +\r\n\t\t\t\t\t'<span class=\"orderTotalPrice\">' + orderData[i].orderprice + ' kr</span>' +\r\n\t\t\t\t\t'<span class=\"timeStamp\">' + orderData[i].timestamp + ' </span>' +\r\n\t\t\t\t\t'<button class=\"cancelOrder\" style=\"visibility:hidden\">Cancel</button>' +\r\n\t\t\t\t'</li>';\r\n\t\t\tohl.innerHTML += oInfo;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tvar itemID = 'orderitem_' + tempID;\r\n\t\t\tvar oi = dom(itemID);\r\n\t\t\tfor(var t=0;t<pLength;t++){\r\n\t\t\t\tif(orderData[i].product_id == productData[t].product_id){\r\n\t\t\t\t\tproName = productData[t].productname;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tiInfo =\r\n\t\t\t\t'<li>' +\r\n\t\t\t\t\t'<span class=\"itemName\">' + proName + '</span>' +\r\n\t\t\t\t\t'<span class=\"itemAmount\">' + orderData[i].amount + '</span>' +\r\n\t\t\t\t\t'<span class=\"itemTotalPrice\">' + orderData[i].totalprice + ' kr</span>' +\r\n\t\t\t\t'</li>';\r\n\t\t\toi.innerHTML += iInfo;\r\n\t\t}\r\n\t}\r\n}",
"function getExpenditureHistory ()\r\n{\r\n //First get the month\r\n var date = new Date();\r\n var currentMonth = date.getMonth();\r\n var currentYear = date.getYear();\r\n\r\n return Expenditure.filter(getAssetByMonth);\r\n}",
"function getRecordHistory(recordArr, dateArr) {\n try {\n const records = JSON.parse(localStorage.getItem(\"tbRecords\"));\n\n for (let i = 0; i < records.length; i++) {\n const currDateAsArr = records[i].Date.split(\"-\");\n const month = currDateAsArr[1];\n const day = currDateAsArr[2];\n dateArr[i] = month + \"/\" + day;\n recordArr[i] = parseFloat((\n Number.parseFloat(records[i].Hours) +\n Number.parseFloat(records[i].Minutes) / 60\n ).toFixed(2));\n }\n console.log(recordArr);\n } catch (e) {\n alert(\"Error retrieving information from storage.\");\n console.log(e);\n }\n}",
"getStock(stockSymbol) {\n stockService.data(stockSymbol, (err, data) => {\n if (err) return this.handleError(err);\n\n const stock = JSON.parse(data);\n let stockData = stock.data.reverse().map(info => {\n return [\n (new Date(info[0])).getTime(),\n info[1]\n ]\n });\n\n // update chart with new data\n this.addStockToChart(stockSymbol, stockData);\n\n this.addStockToStockTable(stock.company, stock.symbol);\n });\n }",
"refreshStockIssueHistoryTable() {\n if (this.selectedStockItem != null) {\n this.params = 'employee/' + \"0/\" + this.selectedStockItem.id;\n this.employeeStockIssueHistoryListComponent.loadData(this.params);\n }\n }",
"function getProductPrices()\n {\n $.getJSON(productPricesEndpoint, function (data) {\n prices = data;\n\n updateProductPrices();\n });\n }",
"function addToHistory (investment, price) {\n\n if(investment.holding){\n investment.success = true\n } else {\n investment.success = price > investment.price\n }\n\n investment.saleprice = price\n investment.btcprofit = (price * investment.amount) - (investment.price * investment.amount)\n\n log.sell(investment)\n history.push(investment)\n}",
"function fetchPartDetails(responseXML, astrPartNo){\n var lobjParts;\n var lobjPart;\n var lstrPartNo;\n var lstrPartName;\n var lstrFranchise;\n var lstrFormatMask;\n var lstrPrice;\n var lstrCost;\n var lstrMinCost;\n var lstrarrPartDtl = new Array(7);\n\n //Get the Parts node\n lobjParts = responseXML.getElementsByTagName(\"parts\")[0];\n //If there is no part in parts node\n if (lobjParts.childNodes.length <= 0) {\n // Passed Franchise Code\n lstrarrPartDtl[0] = '';\n // Part Franchise Mask\n lstrarrPartDtl[1] = '';\n // Part Name\n lstrarrPartDtl[2] = '';\n // Part Price\n lstrarrPartDtl[3] = '';\n //Part No with Franchise Code\n lstrarrPartDtl[4] = astrPartNo;\n // Part Cost\n lstrarrPartDtl[5] = '';\n // Min. Unit Cost\n lstrarrPartDtl[6] = '';\n }else{\n lobjPart = lobjParts.childNodes[0];\n if(lobjPart != null){\n lstrPartNo = lobjPart.getElementsByTagName(\"partNo\")[0].childNodes[0].nodeValue;\n lstrPartName = lobjPart.getElementsByTagName(\"partName\")[0].childNodes[0].nodeValue;\n lstrFranchise = lobjPart.getElementsByTagName(\"franchise\")[0].childNodes[0].nodeValue;\n lstrFormatMask = lobjPart.getElementsByTagName(\"formatMask\")[0].childNodes[0].nodeValue;\n lstrPrice = lobjPart.getElementsByTagName(\"unitPrice\")[0].childNodes[0].nodeValue;\n lstrCost = lobjPart.getElementsByTagName(\"unitCost\")[0].childNodes[0].nodeValue;\n lstrMinCost = lobjPart.getElementsByTagName(\"minUnitCost\")[0].childNodes[0].nodeValue;\n\n\n // Passed Franchise Code\n lstrarrPartDtl[0] = lstrFranchise;\n // Part Franchise Mask\n lstrarrPartDtl[1] = lstrFormatMask;\n // Part Name\n lstrarrPartDtl[2] = lstrPartName;\n // Part Price\n lstrarrPartDtl[3] = lstrPrice;\n //Part No with Franchise Code\n lstrarrPartDtl[4] = lstrFranchise + '-' + lstrPartNo;\n //Part Cost\n lstrarrPartDtl[5] = lstrCost;\n //Part Min. Cost\n lstrarrPartDtl[6] = lstrMinCost;\n }\n }\n return lstrarrPartDtl;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
count 'movestart' event registered in the map | function count_movestart_event(mIDX, e) {
var movestartEvents = app[mIDX].map._events["movestart"];
if (e) movestartEvents = e.target._events["movestart"];
if (!movestartEvents) return 0;
var count = 0;
$.each(movestartEvents, function(idx, row) {
var ctx = row['ctx'];
//console.log(mIDX, idx, ctx, e);
if (typeof ctx === 'string' && ctx.startsWith(mIDX)) count += 1;
});
return count;
} | [
"function count_moveend_event(mIDX, e) {\r\n\tvar moveendEvents = app[mIDX].map._events[\"moveend\"];\r\n\tif (e) moveendEvents = e.target._events[\"moveend\"];\r\n\tif (!moveendEvents) return 0;\r\n\tvar count = 0;\r\n\t$.each(moveendEvents, function(idx, row) {\r\n\t\tvar ctx = row['ctx'];\r\n\t\t//console.log(getNow(), mIDX, idx, ctx, e);\r\n\t\tif (typeof ctx === 'string' && ctx.startsWith(mIDX)) count += 1;\r\n\t});\r\n\treturn count;\r\n}",
"countEvents(events, mode) {\n\n if (!mode) return events.length;\n let count = 0;\n events.forEach(function(event) {\n if (event.mode === mode) count++;\n });\n if (mode === 'inquiry') count = count + this.unloadedInquiryCount;\n if (mode === 'showing') count = count + this.unloadedShowingCount;\n if (mode === 'message') count = count + this.unloadedMessageCount;\n if (mode === 'register') count = count + this.unloadedRegisterCount;\n if (mode === 'selling') count = count + this.unloadedSellingCount;\n\n if (this.state.filtering === mode) {\n count = count - this.loadedFilteredCount;\n }\n\n return count;\n }",
"function computeEquakeEvents(cavw, mapUsed){\r\n\tvar count = 0;\r\n\tvar vlat = earthquakes[cavw]['vlat'];\r\n\tvar vlon = earthquakes[cavw]['vlon'];\r\n\tvar total = 0;\r\n\tvar filtered = 0;\r\n\r\n\tfor(var i in earthquakes[cavw]){\r\n\t\tif (i == 'vlat' || i == 'vlon') continue;\r\n\t\ttotal++;\r\n\t\tif (earthquakes[cavw][i]['available'] == 1 || earthquakes[cavw][i]['available'] == 2){\r\n\t\t\tfiltered++;\r\n\t\t}\r\n\t}\r\n\tconsole.log(\"event computed total \" + total + \" and \" + filtered);\r\n\treturn [total, filtered];\r\n}",
"function countVisit(person) {\n let count = visitsCountMap.get(person) || 0;\n visitsCountMap.set(person, count + 1);\n console.log(visitsCountMap.get(person));\n}",
"count() {\n return Object.keys(this.locations).reduce(\n ((total, current) => total + Object.keys(this.locations[current]).length)\n , 0);\n }",
"function watchlistedMoviesObject(arr) {\n\n let movieCount = {}\n\n arr.map(movie => {\n\n if (movieCount[movie]) {\n movieCount[movie]++\n } else {\n movieCount[movie] = 1\n }\n })\n\n return movieCount\n\n}",
"function updateTipEventCount(tipObj){\n\t\n\t\t\tconsole.log(tipObj);\n\t\t\tconsole.log(tipObj._id + \" : \" + tipObj.isEvent);\n\t\t\t\n\t\t\tvar placeObj = {};\n\t\t\t\n\t\t\t\n\t\t\t//Get Current Tip Count\n\t\t\tvar promise = Kinvey.DataStore.find('places', tipObj._id , {\n\t\t\t\tsuccess: function(response) {\n\t\t\t\t\t\n\t\t\t\t\tconsole.log(response);\n\t\t\t\t\t\tplaceObj = response;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(tipObj.isEvent == \"true\"){\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t\tconsole.log(\"Event Count : \" + placeObj.eventCount++);\n\t\t\t\t\t\t\n\t\t\t\t\t\tplaceObj.eventCount = placeObj.eventCount++;\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t\tconsole.log(\"Tip Count : \" + placeObj.tipCount++);\n\t\t\t\t\t\tplaceObj.tipCount = placeObj.tipCount++;\n\t\t\t\t\t\tconsole.log(placeObj);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\t\n\n\tKinvey.DataStore.save('places', placeObj).then(function() {\n\t\t\tconsole.log(\"place event tip count updated\");\n\t\t\tconsole.log(placeObj);\n \t}, function(error) {\n \t\t doc.trigger('error', error);\n \t}).then(function() {\n\t\t \n\t\t \n\t\t});\t\n}",
"function trackMapGotoLastEventDate()\n{\n _resetCalandarDates();\n trackMapClickedUpdateAll();\n}",
"increment(){\n this.events[this.events.length] = Date.now();\n }",
"initCountMap() {\n this.countMap = [];\n this.props.pages.map(\n (section, index) => {\n if (section.elements === undefined) { return; }\n this.countMap.push({\n section: section.name,\n num: 0,\n totalSubSection: section.elements.length,\n });\n },\n );\n }",
"function countScores(){\n\tvar x=0;\n\tfor(var i in scoreBoardHistory){\n\t\tx++;\n\t}\n\treturn x;\n}",
"function getCountedObjects(){\n var counted = {};\n for (var i = 0; i < detections.length; i++){\n var lbl = detections[i].label;\n if (!counted[lbl]) counted[lbl] = 0;\n counted[lbl]++;\n }\n return counted;\n}",
"function buildTrackCounts() {\n interactionEvents.sort(function (a, b) {\n return (+a[config.timePointColumn]) - (+b[config.timePointColumn]);\n });\n for (let i = 0, eventCount = interactionEvents.length; i < eventCount; i++) {\n let event = interactionEvents[i];\n let proteinA = event[config.proteinAColumn];\n let proteinB = event[config.proteinBColumn];\n let timePoint = +event[config.timePointColumn];\n addTrackCount(proteinA, proteinB, timePoint);\n addTrackCount(proteinB, proteinA, timePoint);\n }\n\n if (config.removeDuplicateInteractions === \"true\") {\n removeDuplicateInteractions();\n }\n for (let protein in trackCounts) {\n removeSmallerTrackCounts(protein);\n }\n }",
"function addToCount() {\n totalButtonsPressed++;\n recentButtonsPressed++;\n}",
"function addPoo( quantity ) { _playerState[\"Statistics\"][\"TotalPooCollect\"] += quantity; }",
"function check_missing(){\n i=global_events.length;\n\n var layer_counts = {};\n while (i--) {\n if (global_events[i].fields.Layer){\n layer = global_events[i].fields.Layer\n label = global_events[i].fields.Label\n\n if(!layer_counts[layer]){\n layer_counts[layer] = {};\n }\n if(label){\n if(layer_counts[layer][label]){\n layer_counts[layer][label] = layer_counts[layer][label] +1;\n }\n else{\n layer_counts[layer][label] = 1;\n }\n }\n }\n }\n error_string ='';\n missing = 0;\n for (i in layer_counts){\n if (layer_counts[i].entry > layer_counts[i].exit){\n missing = 1;\n error_string = error_string.concat('Layer ',i,' is missing ',layer_counts[i].entry - layer_counts[i].exit,' exit events \\n');\n }\n }\n if (missing==1){\n alert(error_string);\n }\n else{\n alert('Seems OK. Check console for event counts');\n }\n console.log(layer_counts);\n\n}",
"function calcTotalDayAgain() {\n var eventCount = $this.find('.everyday .event-single').length;\n $this.find('.total-bar b').text(eventCount);\n $this.find('.events h3 span b').text($this.find('.events .event-single').length)\n }",
"getNumSongs(data) {\n let num = 0;\n data.sets.set.forEach((set) => num += set.song.length)\n return num;\n }",
"function hitCount() {\n if (archer1.health > 0 && archer2.health > 0) {\n if (archer1.damage > 0) {\n archer1.hits++\n }\n if (archer2.damage > 0) {\n archer2.hits++\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The database SQL request parameters for the request DELETE /categories/:id | function getDatabaseParameterDeleteCategory (params, query, body){
var parameters = {
where: { category_id: params.id },
};
return parameters;
} | [
"function checkRequestDeleteCategory (req, res, next) {\r\n\tvar params = {};\r\n\tif (!req.params.hasOwnProperty('id')) {\r\n\t\treturn next(apiErrors.GENERIC_ERROR_REQUEST_FORMAT_ERROR, req, res);\r\n\t}\r\n\tparams.id = req.params.id;\r\n\treturn {params: params, query: null, body: null};\r\n}",
"async Delete(info){\n if(\n info == undefined ||\n info.name == undefined ||\n info.company == undefined\n ) return {\n status: 400,\n msg: \"There is missing data\"\n };\n \n const results = await connection(\"jobVacancies\").where({\n name: `${info.name}`,\n company: `${info.company}`\n }).select(\"*\");\n\n if(results.length == 0)\n return {\n status: 401,\n msg: \"Unauthorized deletion\"\n };\n\n await connection(\"jobVacancies\").where({\n name: `${info.name}`,\n company: `${info.company}`\n })\n .delete();\n \n\n return {\n status: 200,\n msg: \"Deleted database vancancy\"\n };\n }",
"static deleteMealRequest(req, res) {\n const { requestid } = req.params;\n db.query(deleteRequest, [requestid]).then((del) => {\n res.status(200).json({\n success: true,\n message: 'the selected meal request is deleted successfully',\n del\n });\n }).catch((err) => {\n res.send(err.message);\n });\n }",
"delete(req, res) {\n Model.Company.destroy({\n where: {\n id: req.params.id\n }\n })\n .then(function (deletedRecords) {\n res.status(200).json(deletedRecords);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }",
"function getDatabaseParameterDeleteTeam (params, query, body){\r\n\tvar parameters = {\r\n\t\twhere: { team_id: params.id },\r\n\t};\r\n\treturn parameters;\r\n}",
"function getDatabaseParameterGetCategory (params, query, body){\r\n\tvar parameters = {\r\n\t\twhere: { category_id: params.id },\r\n\t\tattributes: { exclude: []},\r\n\t\tinclude: []\r\n\t};\r\n\treturn parameters;\r\n}",
"static async apiDeletePostit(req, res, next) {\n try {\n const postitId = req.query.id;\n console.log(postitId);\n const postitDelRes = await PostitsDAO.deletePostit(postitId);\n res.json({ status: \"Postit deleted successfully !\" });\n } catch (e) {\n res.status(500).json({ error: e.message });\n }\n }",
"delete(req, res) {\n Origin.destroy({\n where: {\n id: req.params.id\n }\n })\n .then(function (deletedRecords) {\n res.status(200).json(deletedRecords);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('flavorparams', 'delete', kparams);\n\t}",
"function apiDelete(req, res) {\n //console.log('DELETE /api/breed/:name');\n \n // delete the specified breed\n db.Breed.remove({'name': req.params.name}, function(err, lostSheep) {\n if (err) {\n res.status(404).send('could not remove that sheep');\n } else {\n res.json(lostSheep);\n }\n });\n}",
"function deleteYearSem(req , res , conn)\n{\n var body=req.body;\n body._id = ObjectId(body._id);\n conn.collection(\"yearsem\").deleteOne( {_id: body._id}, function( err, result ){\n if( err )\n {\n res.statusCode = 500;\n res.json({\"result\":err.message});\n }\n else\n {\n res.json({\"result\":\"deleted \" + result.deletedCount+ \" record \"});\n }\n } );\n \n}",
"deleteAction(req, res) {\n Robot.remove({ _id: req.params.id }, (err, robot) => {\n if (err)\n this.jsonResponse(res, 400, { 'error': err });\n\n this.jsonResponse(res, 204, { 'message': 'Deleted successfully!' });\n });\n }",
"delete(req, res) {\n const attributes = {\n purchaseId: req.params.purchaseId\n };\n\n PurchaseModel.delete(attributes)\n .then(result => {\n res.json(result);\n })\n .catch(err => {\n res.status(500).send('An unexpected error occurred.');\n console.error('An unexpected error occurred.', err);\n });\n }",
"function getDatabaseParameterPutCategory (params, query, body){\r\n\treturn body.category;\r\n}",
"deleteById(id) {\n return this.del(this.getBaseUrl() + '/' + id);\n }",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('thumbparams', 'delete', kparams);\n\t}",
"function getDatabaseParameterPostCategory (params, query, body){\r\n\treturn body.category;\r\n}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('caption_captionparams', 'delete', kparams);\n\t}",
"function removeFromCollection(movieId) {\n\n // fetch the Collection first.\n let collectionName = document.getElementById('searchFilterText').textContent;\n let collectionId = null;\n\n let url = \"http://localhost:3000/userCollections?name=\" + collectionName;\n\n // Fetch Collection details\n httpSync(url, (responseText) => {\n let response = JSON.parse(responseText);\n let index = response[0].movies.indexOf(parseInt(movieId));\n collectionId = response[0].id;\n if (index > -1) {\n response[0].movies.splice(index, 1);\n }\n\n //Update the DB\n var url = 'http://localhost:3000/userCollections/' + collectionId;\n\n // create a Post Request\n var json = JSON.stringify(response[0]);\n httpPostOrPut(url, 'PUT', json);\n\n }, 'GET', null);\n\n // Update the Store\n //store.dispatch(setActionFilter(ActionFilters.SHOW_MOVIE_REMOVED));\n currentAction = ActionFilters.MOVIE_REMOVED;\n store.dispatch(removeMovieFromCollectionStore(collectionId, movieId));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stops attacking the current entity. | stop() {
this.target = undefined;
// @ts-expect-error
const pathfinder = this.bot.pathfinder;
pathfinder.setGoal(null);
// @ts-expect-error
this.bot.emit('stoppedAttacking');
} | [
"stopShooting() {\n this.shooting = false;\n this.sentAddShooterPacket = false;\n\n var msg = {\n type: \"RemoveShooter\",\n entityType: \"Player\",\n };\n\n game.getNetwork.sendMessage(JSON.stringify(msg));\n }",
"break(){\n\t\tif(this.attackdelay > 0 || this.aimDir.equals(new vec2()))\n\t\t\treturn;\n\t\tthis._breakParticles();\n\t\tthis.attackdelay = 20;\n\t\tsfx_attack.play();\n\t\tvar c = this._getBreakBox();\n\t\tfor (var i = blocks.length - 1; i >= 0; i--) {\n\t\t\tif(box.testOverlap(blocks[i].col, c))\n\t\t\t\tbreakBlock(blocks[i]);\n\t\t}\n\t\tc = this._getSpitBox();\n\t\tfor(var i = enemies.length - 1; i >= 0; i--){\n\t\t\tif(box.testOverlap(enemies[i].getCol(), c)){\n\t\t\t\tsfx_hitenemy.play();\n\t\t\t\tenemies[i].vel = enemies[i].pos.minus(this.pos).normalized(10);\n\t\t\t\tenemies[i]._thinktimer = Math.random() * 20 + 30; // 30 - 50 ticks\n\t\t\t\tenemies[i].mov += Math.random(Math.PI / 2);\n\t\t\t\tenemies[i].seeking = false;\n\t\t\t\n\t\t\t\tthis.vel = this.aimDir.multiply(-this.speed);\n\t\t\t\tif(this.aimDir.y == 1)\n\t\t\t\t\tthis.vel.y -= 2;\n\t\t\t} \n\t\t}\n\t}",
"death () {\r\n this.body.velocity.x = 0\r\n this.dying = true\r\n this.events.onOutOfBounds.add(this.kill, this)\r\n this.game.camera.shake(0.005, 100)\r\n }",
"stop() {\n if (this.started) {\n this.keyboard.interceptKeys = false;\n this.cancelTickTimeout();\n this.started = false;\n }\n }",
"function hitEnemy (shot, enemy){\n shot.kill();\n enemy.kill();\n score += 5;\n }",
"function stopMoving(obj){\n obj.body.velocity.x=0;\n obj.body.velocity.y=0;\n obj.body.gravity.y = 0;\n obj.angle = 0;\n obj.body.angularVelocity=0;\n }",
"function stopGame(){\n\tresetGame();\n\tgoPage('result');\n}",
"endTurn() {\n let gameState = gameEngine.endTurn();\n if (gameState.isGameOver()) {\n GameScript.gameOver(gameState);\n } else {\n GameScript.newTurn(gameState);\n }\n }",
"_terminate() {\n console.log(\"terminate\");\n /*if (this.state !== or === ? GameStates.Terminating) {\n return; //error\n }*/\n\n this.state = GameStates.Terminating;\n clearTimeout(this.tick);\n this._clearTurn();\n this.destroy();\n }",
"function enemyHitsPlayer (player,bad) {\r\n \r\n bad.kill();\r\n\tkillPlayer();\r\n\r\n}",
"stopWalking() {\r\n this.isWalking = false;\r\n\r\n this.setStatus();\r\n this.statusWrapper.classList.remove('start');\r\n this.statusWrapper.classList.add('stop');\r\n }",
"function enemyPlayerCollision(player, enemy){\n enemy.kill();\n var live = lives.getFirstAlive();\n \n if (live){\n live.kill();\n }\n if (lives.countLiving()<1){\n endGame();\n }\n }",
"function stopSlideAction(objSlide){\n\t\t\n\t\tvar slideType = t.getSlideType(objSlide);\n\t\t\n\t\tswitch(slideType){\n\t\t\tdefault:\n\t\t\t\tg_objVideoPlayer.hide();\n\t\t\tbreak;\n\t\t}\n\t}",
"function stop() {\n testTransport.removeListener(\"close\", find);\n testTransport.close();\n }",
"abortTransaction() {\n\t\tthis.isTransacting = false;\n\t\tthis.restoreToPreviousState();\n\t}",
"attack() {\n this.attackLoop = setTimeout(this.attack.bind(this), this.attackRate);\n // Don't attack if no target is set.\n if (this.target === null) return;\n\n // Don't let them attack if a curse forbids it.\n if (this.curse !== null) {\n if (this.curse.onCharacterAttack() === false) {\n return;\n }\n }\n\n this.preAttack();\n\n // Stop attacking if the target is dead.\n if (this.target.hitPoints <= 0) {\n this.target = null;\n return;\n }\n\n this.attackFunction();\n }",
"function killPlayer()\r\n{\r\nnumberOfLives-=1;\r\nliveText.text = \"Lives: \" + numberOfLives;\r\nlive = lives.getFirstAlive();\r\n\r\n if (live)\r\n {\r\n live.kill();\r\n }\r\n\r\n // And create an explosion\r\n var explosion = explosions.getFirstExists(false);\r\n explosion.reset(player.body.x, player.body.y);\r\n explosion.play('kaboom', 30, false, true);\r\n\r\n // When the player dies\r\n if (lives.countLiving() < 1)\r\n {\r\n player.kill();\r\n\r\n stateText.text=\" GAME OVER \\n Click to restart\";\r\n stateText.visible = true;\r\n\r\n //the \"click to restart\" handler\r\n game.input.onTap.addOnce(restart,this);\r\n }\r\n}",
"stop() {\n dbg.log0('Stopping hosted_agents');\n this._started = false;\n //stop all running agents\n _.each(this._started_agents, (agent, node_name) => this._stop_agent(node_name));\n }",
"abortSession() {\n if (this.isRunning) {\n this.abort = true;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add resource to bundle as BundleEntry | addEntry(method, resource) {
let id = this.generateId();
// create entry array if still undefined
if (typeof this.entry === 'undefined') {
this.entry = [];
}
// check if id of resource is already set
if (typeof resource.id !== 'undefined') {
id = resource.id;
// check if there already is an entry with given id
if (this.idAlreadyExistsInBundle(id)) {
throw Error(`An entry with the id ${resource.id} already exists in bundle`);
}
}
else {
// Set relative id to entry
resource.id = id;
}
// adding bundle entry of resource with method and resource type
let bundleEntry = {
request: {
method: method,
url: resource.resourceType
},
resource: resource
};
this.entry.push(bundleEntry);
return bundleEntry;
} | [
"static addContent(entryId, resource){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.resource = resource;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'addContent', kparams);\n\t}",
"idAlreadyExistsInBundle(id) {\n for (let e of this.entry) {\n let resource = e.resource;\n if (resource['id'] === id)\n return true;\n }\n return false;\n }",
"add( asset ) {\n if ( asset instanceof Asset ) {\n this._assets.set( asset.id, asset );\n } else if ( asset instanceof Array ) {\n asset.forEach( this.add, this );\n } else {\n this.add( this.load( asset ) );\n }\n }",
"static addContent(entryId, resource = null){\n\t\tlet kparams = {};\n\t\tkparams.entryId = entryId;\n\t\tkparams.resource = resource;\n\t\treturn new kaltura.RequestBuilder('media', 'addContent', kparams);\n\t}",
"static add(entry){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\treturn new kaltura.RequestBuilder('externalmedia_externalmedia', 'add', kparams);\n\t}",
"_addResources(resources, forceUpdate = false) {\n for (const id in resources) {\n this.layerManager.resourceManager.add({\n resourceId: id,\n data: resources[id],\n forceUpdate\n });\n }\n }",
"function bundle(key) {\n\n // TODO: Use message handler mech. to get bundle from server\n // For now, a fake placeholder bundle\n\n var bun = {\n computer: 'Calcolatore',\n disk: 'Disco',\n monitor: 'Schermo',\n keyboard: 'Tastiera'\n };\n\n $log.warn('Using fake bundle', bun);\n return bun;\n }",
"static add(entry, type = null){\n\t\tlet kparams = {};\n\t\tkparams.entry = entry;\n\t\tkparams.type = type;\n\t\treturn new kaltura.RequestBuilder('baseentry', 'add', kparams);\n\t}",
"function loadBundle() {\n var bundleScript = document.createElement('SCRIPT');\n var bundleSrc = thisScript.getAttribute(\"bundle\") || (thisScript.src.replace('/dcp-client.js', '/dist/dcp-client-bundle.js'));\n var tmp;\n \n bundleScript.setAttribute('type', 'text/javascript');\n bundleScript.setAttribute('src', bundleSrc);\n bundleScript.setAttribute('id', '_dcp_client_bundle');\n bundleScript.setAttribute('dcp-env', 'vanilla-web');\n bundleScript.setAttribute('onerror', `alert('Error DCP-1002: Could not load dcp-client bundle from URL (\"${bundleSrc}\")')`);\n bundleScript.setAttribute('onload', thisScript.getAttribute('onload'));\n thisScript.removeAttribute('onload');\n bundleScript.setAttribute('onready', thisScript.getAttribute('onready'));\n thisScript.removeAttribute('onready');\n document.write(bundleScript.outerHTML);\n document.write(`<script>\n;(function bundleReadyIIFE() {\n let bundleScript = document.getElementById(\"_dcp_client_bundle\");\n let ready = bundleScript.getAttribute('onready');\n window.dcp = bundleScript.exports;\n\n /**\n * Transform instances of Address-like values into Addresses. Necessary since\n * the config can't access the Address class before the bundle is loaded.\n */\n window.dcp.wallet.Address.patchUp(dcpConfig);\n if (ready)\n window.setTimeout(function bundleReadyFire() { let indirectEval=eval; indirectEval(ready) }, 0);\n})();\n\n/**\n * The script tag is broken up on purpose, to avoid parsing errors by certain\n * browsers.\n */\n</scr` + `ipt>`);\n bundleScript = document.getElementById('_dcp_client_bundle');\n if (bundleScript)\n bundleScript.onerror = function(e) {\n console.error('Bundle load error:', e);\n bundleScript.removeAttribute('onready');\n };\n }",
"static addFromFlavorAsset(sourceFlavorAssetId, mediaEntry = null){\n\t\tlet kparams = {};\n\t\tkparams.sourceFlavorAssetId = sourceFlavorAssetId;\n\t\tkparams.mediaEntry = mediaEntry;\n\t\treturn new kaltura.RequestBuilder('media', 'addFromFlavorAsset', kparams);\n\t}",
"function ADLAuxiliaryResource()\r\n{\r\n}",
"function _createResource({domain, path, contentType, token, args}) {\n //Remove the path if we are running in function mode, so paths in original action work\n return post.func(args)({\n domain,\n token,\n path: '/resources',\n headers: {\n 'Content-Type': contentType\n },\n data: {}\n }).then(({response}) => {\n var id = response.headers.location.split('/')\n id = id[id.length-1]\n\n return put.func(args)({\n domain,\n path,\n token,\n headers: {\n 'Content-Type': contentType\n },\n data: {\n _id:'resources/'+id,\n _rev: '0-0'\n }\n });\n });\n}",
"function install(pluginBundle) {\n java.awt.Toolkit.getDefaultToolkit().beep();\n java.lang.System.out.println('install called for ' + pluginBundle.file.name);\n}",
"static add(fileAsset){\n\t\tlet kparams = {};\n\t\tkparams.fileAsset = fileAsset;\n\t\treturn new kaltura.RequestBuilder('fileasset', 'add', kparams);\n\t}",
"function addHashesToMedia(bundles, cb) {\n async.map(bundles, function (bundle, cbMapBundles) {\n async.map(bundle.media, function (media, cbMapMedia) {\n fs.readFile(media.path, function (err, imageData) {\n if (!err) {\n media.md5 = md5(imageData);\n }\n\n cbMapMedia(null, media);\n });\n }, function (ignoredError, media) {\n bundle.media = media;\n\n cbMapBundles(null, bundle);\n });\n }, cb);\n}",
"addEntry (state, args) {\n const cache = state.cache[args.property]\n const turn = state.turns[state.currentTurn]\n turn.push(args.entry)\n\n cache.turn = state.currentTurn\n cache.entryId = args.entry.entryId\n state.entryId++\n }",
"static add(userEntry){\n\t\tlet kparams = {};\n\t\tkparams.userEntry = userEntry;\n\t\treturn new kaltura.RequestBuilder('userentry', 'add', kparams);\n\t}",
"function startResourceUpdate(resource) {\n return { type: START_RESOURCE_UPDATE,\n resource: resource};\n}",
"function initializeNewItem(item) {\n item.assignedResource = resource1;\n console.log('A new item was created.');\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update to data dict | function updateData(){
dataDict.clear();
dataDict.setparse("NAMESPACES", JSON.stringify(namespaces));
dataDict.setparse("TRACKS", tracksDict.stringify());
updateDef();
} | [
"update ( data ) {\n if ( !this.deepEqual(data, this.data) ) {\n Object.assign(this.data, data);\n this.notify();\n }\n }",
"function updateData(){\n //Re draw the data\n drawDataOptions();\n\n //Fill in data element values when clicking on a data element in select box.\n $('.data-elements option').click( function(e){\n\n $('input.dataKey').attr('disabled','disabled');\n $('input.dataKey').val($(this).attr(\"dataKey\"));\n $('input.dataValue').val($(this).attr(\"dataValue\"));\n $('button.add-data').text(i18n.gettext('Edit Data'));\n e.stopPropagation();\n\n });\n }",
"update ( data ) {\n this.store.update(data);\n }",
"_setData() {\n this._global[this._namespace] = this._data;\n }",
"update(sessionDataUpdate) {\n if (sessionDataUpdate.isNoOp()) {\n return;\n }\n switch (sessionDataUpdate.mergeStrategy) {\n case SHALLOW_MERGE_STRATEGY:\n this.data = { ...this.data, ...sessionDataUpdate.data };\n break;\n case REPLACE_STRATEGY:\n this.data = sessionDataUpdate.data;\n break;\n }\n }",
"set(id, data) {\n let oldData = this.raw();\n oldData[id] = data;\n this._write(oldData);\n }",
"function updateData() {\n\tPapa.parse('/data/vatsim-data.txt', {\n\t\tdownload: true,\n\t\tdelimiter: ':',\n\t\tcomments: ';',\n\t\tfastMode: true,\n\t\tcomplete: parseData\n\t});\n}",
"function updateMap(data, canvas) {\n\t//TODO\n}",
"function dataUpdate() {\n if(filterData.length > 0) {\n data = [];\n filterData.map(row => {\n data.push({\n brand: row.Brand,\n values: [\n parseInt(row[\"BF_1 - Aided brand awareness\"].slice(0, -1)),\n parseInt(row[\"BF_2 - Brand consideration\"].slice(0, -1)),\n parseInt(row[\"BF_3 - Brand usage\"].slice(0, -1)),\n parseInt(row[\"BF_4 - Brand preference\"].slice(0, -1))\n ],\n variations: [\n row[\"AidedAwarenessVariation\"],\n row[\"ConsiderationVariation\"],\n row[\"UsageVariation\"],\n row[\"PreferenceVariation\"]\n ]\n });\n });\n\n rows = filterData.length;\n console.log(data);\n }\n }",
"setResourceData(state, {resource, data}) {\n _.forIn(data, (value, key) => {\n resource[key] = value\n })\n }",
"function update(hour, data) {\n planData[\"hour\" + hour] = data;\n localStorage.setItem(\"planData\", JSON.stringify(planData));\n }",
"function updateValuesFromFlash(data) {\n for (var i in data) {\n p[i] = data[i];\n // console.log(i, \" = \", this[i]);\n }\n }",
"reload(newData) {\n this.mapData = newData;\n console.log('New Dataset: ', this.mapData);\n console.log('Reloading the map using a new dataset');\n this.render();\n }",
"function applyData(object, data) {\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n object[key] = data[key];\n }\n }\n }",
"function updateDef(){\n\tinstDef.setparse(\"METADATA\", metaDict.stringify());\n\tinstDef.setparse(\"DATA\", dataDict.stringify());\n}",
"function updateDatapoints() {\n\t\t//remove all markers from the map in order to be able to do a refresh\n\t\tmarkers.clearLayers();\n\t\tmarkers_list = {};\n\t\t//for every datapoint\n\t\tbyId.top(Infinity).forEach(function(p, i) {\n\t\t\t//create a marker at that specific position\n\t\t\tvar marker = L.circleMarker([p.latitude,p.longitude]);\n\t\t\tmarker.setStyle({fillOpacity: 0.5,fillColor:'#0033ff'});\n\t\t\t//add the marker to the map\n\t\t\tmarkers.addLayer(marker);\n\t\t});\n\t}",
"function modifyData( newNeighbourhoodData ) {\n dataDict = [];\n\n if(newNeighbourhoodData) {\n for(var i = 0; i < newNeighbourhoodData.length; i++ ) {\n var regionData = newNeighbourhoodData[i];\n dataDict[regionData.neighborhood] = regionData;\n }\n } else {\n return dataDict;\n }\n return dataDict;\n}",
"updateMarkerData(markerData) {\n let currentData = cloneDeep(this.state.pluginData[\"Marker\"]);\n currentData[this.state.activeEntry] = markerData;\n this.updatePluginData(\"Marker\", currentData);\n }",
"function update(key, cfg) {\n data[key].config = cfg;\n setDateConfig(cfg, key);\n poller();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Abhaengigkeiten: ================ initOptions (PreInit): restoreMemoryByOpt: PreInit oldStorage getStoredCmds: restoreMemoryByOpt runStoredCmds: getStoredCmds loadOptions: PreInit startMemoryByOpt: storage oldStorage initScriptDB: startMemoryByOpt initOptions (Rest): PreInit __MYTEAM (initTeam): initOptions getMyTeam callback (getOptPrefix): initTeam renameOptions: getOptPrefix showOptions: startMemoryByOpt renameOptions updateScriptDB: startMemoryByOpt buildMenu: showOptions buildForm: showOptions Initialisiert die gesetzten Optionen und den Speicher und laedt die Optionen zum Start optConfig: Konfiguration der Optionen optSet: Platz fuer die gesetzten Optionen return Gefuelltes Objekt mit den gesetzten Optionen | function startOptions(optConfig, optSet = undefined, classification = undefined) {
optSet = initOptions(optConfig, optSet, true); // PreInit
// Memory Storage fuer vorherige Speicherung...
myOptMem = restoreMemoryByOpt(optSet.oldStorage);
// Zwischengespeicherte Befehle auslesen...
const __STOREDCMDS = getStoredCmds(myOptMem);
// ... ermittelte Befehle ausführen...
const __LOADEDCMDS = runStoredCmds(__STOREDCMDS, optSet, true); // BeforeLoad
loadOptions(optSet);
// Memory Storage fuer naechste Speicherung...
myOptMem = startMemoryByOpt(optSet.storage, optSet.oldStorage);
initScriptDB(optSet);
optSet = initOptions(optConfig, optSet, false); // Rest
if (classification !== undefined) {
// Classification mit optSet verknuepfen...
classification.optSet = optSet;
// Umbenennungen durchfuehren...
classification.renameOptions();
}
// ... ermittelte Befehle ausführen...
runStoredCmds(__LOADEDCMDS, optSet, false); // Rest
return optSet;
} | [
"function initOptions(optConfig, optSet = undefined, preInit = undefined) {\n let value;\n\n if (optSet === undefined) {\n optSet = { };\n }\n\n for (let opt in optConfig) {\n const __OPTCONFIG = optConfig[opt];\n const __PREINIT = getValue(__OPTCONFIG.PreInit, false);\n\n if ((preInit === undefined) || (__PREINIT === preInit)) {\n const __CONFIG = getSharedConfig(__OPTCONFIG);\n const __ALTACTION = getValue(__CONFIG.AltAction, __CONFIG.Action);\n // Gab es vorher einen Aufruf, der einen Stub-Eintrag erzeugt hat? Wurde ggfs. bereits geaendert...\n const __USESTUB = ((preInit === false) && __PREINIT);\n const __LOADED = (__USESTUB ? optSet[opt].Loaded : false);\n const __VALUE = (__USESTUB ? optSet[opt].Value : initOptValue(__CONFIG));\n\n optSet[opt] = {\n 'Config' : __CONFIG,\n 'Loaded' : __LOADED,\n 'Value' : __VALUE,\n 'SetValue' : __CONFIG.SetValue,\n 'Action' : initOptAction(__CONFIG.Action, opt, optSet),\n 'AltAction' : initOptAction(__ALTACTION, opt, optSet)\n };\n } else if (preInit) { // erstmal nur Stub\n optSet[opt] = {\n 'Config' : __OPTCONFIG,\n 'Loaded' : false,\n 'Value' : initOptValue(__OPTCONFIG)\n };\n }\n }\n\n return optSet;\n}",
"doPresetSelected (preset) {\n if (!preset || !preset?.opts) {\n this.$q.notify({ type: 'warning', message: this.$t('Invalid run options') })\n console.warn('Invalid run options:', preset)\n return\n }\n // merge preset with run options\n const ps = preset.opts\n\n this.runOpts.subCount = ps.subCount ?? this.runOpts.subCount\n if (this.runOpts.subCount < 1) {\n this.runOpts.subCount = 1\n }\n this.runOpts.threadCount = ps.threadCount ?? this.runOpts.threadCount\n if (this.runOpts.threadCount < 1) {\n this.runOpts.threadCount = 1\n }\n this.runOpts.progressPercent = ps.progressPercent ?? this.runOpts.progressPercent\n if (this.runOpts.progressPercent < 1) {\n this.runOpts.progressPercent = 1\n }\n this.runOpts.progressStep = ps.progressStep ?? this.runOpts.progressStep\n if (this.runOpts.progressStep < 0) {\n this.runOpts.progressStep = 0\n }\n this.runOpts.workDir = ps.workDir ?? this.runOpts.workDir\n this.runOpts.csvDir = ps.csvDir ?? this.runOpts.csvDir\n this.csvCodeId = ps.csvCodeId ?? this.csvCodeId\n if (this.enableIni) {\n this.runOpts.useIni = ps.useIni ?? this.runOpts.useIni\n if (this.enableIniAnyKey && this.runOpts.useIni) this.runOpts.iniAnyKey = ps.iniAnyKey ?? this.runOpts.iniAnyKey\n }\n this.runOpts.profile = ps.profile ?? this.runOpts.profile\n this.runOpts.sparseOutput = ps.sparseOutput ?? this.runOpts.sparseOutput\n this.runOpts.runTmpl = ps.runTmpl ?? this.runOpts.runTmpl\n this.runOpts.mpiNpCount = ps.mpiNpCount ?? this.runOpts.mpiNpCount\n if (this.runOpts.mpiNpCount < 0) {\n this.runOpts.mpiNpCount = 0\n }\n this.runOpts.mpiOnRoot = ps.mpiOnRoot ?? this.runOpts.mpiOnRoot\n this.runOpts.mpiUseJobs = this.serverConfig.IsJobControl && (ps.mpiUseJobs ?? (this.serverConfig.IsJobControl && this.runOpts.mpiNpCount > 0))\n this.runOpts.mpiTmpl = ps.mpiTmpl ?? this.runOpts.mpiTmpl\n\n // expand sections if preset options supplied with non-default values\n this.mpiOptsExpanded = (ps.mpiNpCount || 0) !== 0 || (ps.mpiTmpl || '') !== ''\n\n this.advOptsExpanded = (ps.threadCount || 0) > 1 ||\n (ps.workDir || '') !== '' ||\n (ps.csvDir || '') !== '' ||\n (ps.csvCodeId || 'enumCode') !== 'enumCode' ||\n !!ps.useIni ||\n !!ps.iniAnyKey ||\n (ps.profile || '') !== '' ||\n !!ps.sparseOutput ||\n (ps.runTmpl || '') !== ''\n\n this.$q.notify({\n type: 'info',\n message: preset?.descr || preset?.label || (this.$t('Using Run Options') + ': ' + preset?.name || '')\n })\n }",
"function createOptions(game) {\n // Data\n var music = game._music;\n var playerData = game._playerData;\n\n // Background\n fadeSceneIn(game, null, null, true);\n game.add.image(0, 0, 'game-bg').setOrigin(0, 0);\n\n\n // Menu sounds\n var sounds = {\n select: game.sound.add(\"menu-select\", { volume: 0.5 } ),\n accept: game.sound.add(\"menu-accept\", { volume: 0.5 } ),\n };\n\n // Title bar\n var bar = game.add.image(0, 0, \"top-bar\").setOrigin(0, 0);\n\n var nameStyle = { font: \"50px FrizQuadrata\", fill: \"#fff\", stroke: \"#000\", strokeThickness: 1 };\n var nameText = game.add.text(512, 40, \" Options \", nameStyle).setOrigin(0.5, 0.5);\n nameText.setShadow(2, 2, \"#000\", 2);\n\n\n // Portrait\n var masterImage = playerData.image;\n if (masterImage.indexOf(\" \") >= 0) {\n masterImage = masterImage.substr(0, masterImage.indexOf(\" \"));\n }\n var portrait = game.add.sprite(250, 0, masterImage).setOrigin(0.5, 0);\n\n\n // Back button\n backButton(game, sounds.select, () => {\n game.scene.start('GameMenuScene', { playerData: playerData, music: music });\n });\n\n\n // Options\n showOptions(game, sounds.select, playerData, music);\n}",
"loadOptions() {\n browser.storage.local.get(\"options\").then(res => {\n if (Object.getOwnPropertyNames(res).length != 0) {\n this.options = res.options;\n } else {\n this.options = DEFAULT_OPTIONS;\n }\n });\n }",
"function Scene_Workman_Options() {\n this.initialize.apply(this, arguments);\n}",
"function procHaupt() {\n const __TEAMPARAMS = getTeamParamsFromTable(getTable(1), __TEAMSEARCHHAUPT); // Link mit Team, Liga, Land...\n\n buildOptions(__OPTCONFIG, __OPTSET, {\n 'teamParams' : __TEAMPARAMS,\n 'hideMenu' : true\n });\n\n const __NEXTZAT = getZATNrFromCell(getRows(0)[2].cells[0]); // \"Der naechste ZAT ist ZAT xx und ...\"\n const __CURRZAT = __NEXTZAT - 1;\n const __DATAZAT = getOptValue(__OPTSET.datenZat);\n\n if (__CURRZAT >= 0) {\n console.log(\"Aktueller ZAT: \" + __CURRZAT);\n\n // Neuen aktuellen ZAT speichern...\n setOpt(__OPTSET.aktuellerZat, __CURRZAT, false);\n\n if (__CURRZAT !== __DATAZAT) {\n console.log(__DATAZAT + \" => \" + __CURRZAT);\n\n // ... und ZAT-bezogene Daten als veraltet markieren\n __TEAMCLASS.deleteOptions();\n\n // Neuen Daten-ZAT speichern...\n setOpt(__OPTSET.datenZat, __CURRZAT, false);\n }\n }\n}",
"function Workman_Options() {\n this.initialize.apply(this, arguments);\n}",
"function Options() {\n lces.types.component.call(this);\n \n var getPlayer = null;\n var getEpisodeLinks = null;\n var getEpisodeInfo = null;\n var getTrackerData = null;\n\n var infoCaption = true;\n\n var scaleMove = true;\n var scaleMoveConfig = true;\n var scaleMoveConfigUI = null;\n\n var shadingLevelUI = true;\n var shadingLevelConfig = true;\n var shadingLevelConfigUI = null;\n\n var generalConfigUI = null;\n\n var episodeTracker = true;\n var fullscreen = true;\n var mirrorPriority = true;\n var userModName = null;\n var aurTab = true;\n\n var defVideoWidth = 100;\n var defVideoHeight = 100;\n \n // Type utils\n function onlyBoolean(value) {\n if (typeof value === \"boolean\") {\n return true;\n } else {\n throw new TypeError(\"LightsOut: Options.\" + this.name + \" needs to be a boolean\");\n }\n }\n \n function onlyObject(value) {\n if (jSh.type(value) === \"object\") {\n return true;\n } else {\n throw new TypeError(\"LightsOut: Options.\" + this.name + \" needs to be a object\");\n }\n }\n \n function onlyFunction(value) {\n if (typeof value === \"function\") {\n return true;\n } else {\n throw new TypeError(\"LightsOut: Options.\" + this.name + \" needs to be a function\");\n }\n }\n \n function onlyPercent(value) {\n var num = jSh.numProp(value, null);\n \n if (num === null || num > 100 || num < 0) {\n throw new TypeError(\"LightsOut: Options.\" + this.name + \" needs to be a number from 0 to 100\");\n }\n \n return true;\n }\n \n // Conditions\n this.setState(\"getPlayer\", getPlayer);\n this.addStateCondition(\"getPlayer\", onlyFunction);\n \n this.setState(\"getEpisodeLinks\", getEpisodeLinks);\n this.addStateCondition(\"getEpisodeLinks\", onlyFunction);\n \n this.setState(\"infoCaption\", infoCaption);\n this.addStateCondition(\"infoCaption\", onlyBoolean);\n \n this.setState(\"getEpisodeInfo\", getEpisodeInfo);\n this.addStateCondition(\"getEpisodeInfo\", onlyFunction);\n \n this.setState(\"scaleMove\", scaleMove);\n this.addStateCondition(\"scaleMove\", onlyBoolean);\n \n this.setState(\"scaleMoveConfig\", scaleMoveConfig);\n this.addStateCondition(\"scaleMoveConfig\", onlyBoolean);\n \n this.setState(\"scaleMoveConfigUI\", scaleMoveConfigUI);\n this.addStateCondition(\"scaleMoveConfigUI\", onlyObject);\n \n this.setState(\"shadingLevelUI\", shadingLevelUI);\n this.addStateCondition(\"shadingLevelUI\", onlyBoolean);\n \n this.setState(\"shadingLevelConfig\", shadingLevelConfig);\n this.addStateCondition(\"shadingLevelConfig\", onlyBoolean);\n \n this.setState(\"shadingLevelConfigUI\", shadingLevelConfigUI);\n this.addStateCondition(\"shadingLevelConfigUI\", onlyObject);\n \n this.setState(\"generalConfigUI\", generalConfigUI);\n this.addStateCondition(\"generalConfigUI\", onlyObject);\n \n this.setState(\"episodeTracker\", episodeTracker);\n this.addStateCondition(\"episodeTracker\", onlyBoolean);\n \n this.setState(\"getTrackerData\", getTrackerData);\n this.addStateCondition(\"getTrackerData\", onlyFunction);\n \n this.setState(\"fullscreen\", fullscreen);\n this.addStateCondition(\"fullscreen\", onlyBoolean);\n \n this.setState(\"mirrorPriority\", mirrorPriority);\n this.addStateCondition(\"mirrorPriority\", onlyBoolean);\n \n this.setState(\"aurTab\", aurTab);\n this.addStateCondition(\"aurTab\", onlyBoolean);\n \n this.setState(\"userModName\", userModName);\n this.addStateCondition(\"userModName\", function(name) {\n if (typeof name === \"string\") {\n var exists = AUR.modProbe.exists(name);\n \n if (exists) {\n return true;\n } else {\n throw new ReferenceError(\"LightsOut: Options.userModName \\\"\" + name + \"\\\" module doesn't exist\");\n }\n } else {\n throw new TypeError(\"LightsOut: Options.userModName needs to be a string name of an existing AUR module\");\n }\n });\n \n this.setState(\"defVideoWidth\", defVideoWidth);\n this.addStateCondition(\"defVideoWidth\", onlyPercent);\n \n this.setState(\"defVideoHeight\", defVideoHeight);\n this.addStateCondition(\"defVideoHeight\", onlyPercent);\n}",
"function loadSolutionSelectData() {\n \"use strict\";\n createS_Option();\n}",
"setOptions(options) {\n this.options = Object.assign({\n labels: ['Vssue'],\n state: 'Vssue',\n prefix: '[Vssue]',\n admins: [],\n perPage: 10,\n proxy: (url) => `https://cors-anywhere.herokuapp.com/${url}`,\n issueContent: ({ url }) => url,\n autoCreateIssue: true,\n }, options);\n // check options\n const requiredOptions = [\n 'api',\n 'owner',\n 'repo',\n 'clientId',\n ];\n for (const opt of requiredOptions) {\n if (!this.options[opt]) {\n console.warn(`[Vssue] the option '${opt}' is required`);\n }\n }\n // set locale\n if (this.options.locale) {\n this.$i18n.locale = this.options.locale;\n }\n else {\n const locales = Object.keys(this.$i18n.messages);\n const navLangs = window.navigator.languages;\n this.$i18n.locale = navLangs.filter(item => locales.includes(item)).shift() || 'en';\n }\n }",
"get options() {\n if (typeof MI === 'undefined') {\n window.MI = { options: {} };\n }\n const { options } = MI;\n return options;\n }",
"function showOptions(optSet = undefined, optParams = { 'hideMenu' : false }) {\n updateScriptDB(optSet);\n\n if (! optParams.hideMenu) {\n buildMenu(optSet);\n }\n\n if ((optParams.menuAnchor !== undefined) && (myOptMem !== __OPTMEMINAKTIVE)) {\n buildForm(optParams.menuAnchor, optSet, optParams);\n }\n}",
"function handle_options(optionsArray) {\n var programName = [];\n var currentItem = optionsArray.shift();\n var defaults = amberc.createDefaultConfiguration();\n\n while (currentItem != null) {\n switch (currentItem) {\n case '-C':\n defaults.configFile = optionsArray.shift();\n break;\n case '-p':\n optionsArray.shift.split(',').forEach(function (pairString) {\n var mapping = pairString.split(':');\n defaults.paths[mapping[0]] = mapping[1];\n });\n break;\n case '-l':\n defaults.load.push.apply(defaults.load, optionsArray.shift().split(','));\n break;\n case '-g':\n defaults.jsGlobals.push.apply(defaults.jsGlobals, optionsArray.shift().split(','));\n break;\n case '-n':\n defaults.amdNamespace = optionsArray.shift();\n break;\n case '-D':\n defaults.outputDir = optionsArray.shift();\n break;\n case '-d':\n amber_dir = path.normalize(optionsArray.shift());\n break;\n case '-v':\n defaults.verbose = true;\n break;\n case '-h':\n case '--help':\n case '?':\n case '-?':\n print_usage_and_exit();\n break;\n default:\n defaults.stFiles.push(currentItem);\n break;\n }\n currentItem = optionsArray.shift();\n }\n\n if (1 < programName.length) {\n throw new Error('More than one name for ProgramName given: ' + programName);\n } else {\n defaults.program = programName[0];\n }\n return defaults;\n}",
"setOptions(options) {\n validation_1.CacheValidation.validateOptions(options);\n if (options.timeout)\n this.timeout = options.timeout;\n if (options.path) {\n this.basePath = options.path;\n fs_1.mkdirSync(this.path);\n }\n }",
"options(params) {\n if(!params) {\n return {\n provider: _currentProvider,\n customProvider: customProvider,\n depth: depth,\n weight: weight,\n spamSeed: spamSeed,\n message: message,\n tag: tag,\n numberOfTransfersInBundle: numberOfTransfersInBundle,\n isLoadBalancing: optionsProxy.isLoadBalancing\n }\n }\n if(params.hasOwnProperty(\"provider\")) {\n _currentProvider = params.provider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"customProvider\")) {\n customProvider = params.customProvider\n initializeIOTA()\n }\n if(params.hasOwnProperty(\"depth\")) { depth = params.depth }\n if(params.hasOwnProperty(\"weight\")) { weight = params.weight }\n if(params.hasOwnProperty(\"spamSeed\")) { spamSeed = params.spamSeed }\n if(params.hasOwnProperty(\"message\")) { message = params.message }\n if(params.hasOwnProperty(\"tag\")) { tag = params.tag }\n if(params.hasOwnProperty(\"numberOfTransfersInBundle\")) { numberOfTransfersInBundle = params.numberOfTransfersInBundle }\n if(params.hasOwnProperty(\"isLoadBalancing\")) { optionsProxy.isLoadBalancing = params.isLoadBalancing }\n if(params.hasOwnProperty(\"onlySpamHTTPS\")) { onlySpamHTTPS = params.onlySpamHTTPS }\n }",
"static vsamValidateOptions(options) {\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options, ZosFiles_messages_1.ZosFilesMessages.missingFilesCreateOptions.message);\n /* If our caller does not supply these options, we supply default values for them,\n * so they should exist at this point.\n */\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.dsorg, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"dsorg\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.alcunit, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"alcunit\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.primary, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"primary\");\n imperative_1.ImperativeExpect.toNotBeNullOrUndefined(options.secondary, ZosFiles_messages_1.ZosFilesMessages.missingVsamOption.message + \"secondary\");\n // validate specific options\n for (const option in options) {\n if (options.hasOwnProperty(option)) {\n switch (option) {\n case \"dsorg\":\n if (!ZosFiles_constants_1.ZosFilesConstants.VSAM_DSORG_CHOICES.includes(options.dsorg.toUpperCase())) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.invalidDsorgOption.message + options.dsorg\n });\n }\n break;\n case \"alcunit\":\n if (!ZosFiles_constants_1.ZosFilesConstants.VSAM_ALCUNIT_CHOICES.includes(options.alcunit.toUpperCase())) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.invalidAlcunitOption.message + options.alcunit\n });\n }\n break;\n case \"primary\":\n case \"secondary\":\n // Validate maximum allocation quantity\n if (options[option] > ZosFiles_constants_1.ZosFilesConstants.MAX_ALLOC_QUANTITY) {\n throw new imperative_1.ImperativeError({\n msg: ZosFiles_messages_1.ZosFilesMessages.maximumAllocationQuantityExceeded.message + \" \" +\n ZosFiles_messages_1.ZosFilesMessages.commonFor.message + \" '\" + option + \"' \" + ZosFiles_messages_1.ZosFilesMessages.commonWithValue.message +\n \" = \" + options[option] + \".\"\n });\n }\n break;\n case \"retainFor\":\n if (options[option] < ZosFiles_constants_1.ZosFilesConstants.MIN_RETAIN_DAYS ||\n options[option] > ZosFiles_constants_1.ZosFilesConstants.MAX_RETAIN_DAYS) {\n throw new imperative_1.ImperativeError({\n msg: imperative_1.TextUtils.formatMessage(ZosFiles_messages_1.ZosFilesMessages.valueOutOfBounds.message, {\n optionName: option,\n value: options[option],\n minValue: ZosFiles_constants_1.ZosFilesConstants.MIN_RETAIN_DAYS,\n maxValue: ZosFiles_constants_1.ZosFilesConstants.MAX_RETAIN_DAYS\n })\n });\n }\n break;\n case \"retainTo\":\n case \"volumes\":\n case \"storclass\":\n case \"mgntclass\":\n case \"dataclass\":\n case \"responseTimeout\":\n // no validation at this time\n break;\n default:\n throw new imperative_1.ImperativeError({ msg: ZosFiles_messages_1.ZosFilesMessages.invalidFilesCreateOption.message + option });\n } // end switch\n }\n } // end for\n }",
"function resetOptions(project, stack, parallel, engineAddr, monitorAddr, preview, organization) {\n const { settings } = state_1.getStore();\n monitor = undefined;\n engine = undefined;\n settings.monitor = undefined;\n settings.engine = undefined;\n settings.rpcDone = Promise.resolve();\n settings.featureSupport = {};\n // reset node specific environment variables in the process\n settings.options.project = project;\n settings.options.stack = stack;\n settings.options.dryRun = preview;\n settings.options.queryMode = isQueryMode();\n settings.options.parallel = parallel;\n settings.options.monitorAddr = monitorAddr;\n settings.options.engineAddr = engineAddr;\n settings.options.organization = organization;\n}",
"function initScriptDB(optSet) {\n const __INFO = GM_info;\n const __META = __INFO.script;\n\n //console.log(__INFO);\n\n __DBTOC.versions = getValue(JSON.parse(__DBMEM.getItem('__DBTOC.versions')), { });\n\n // Infos zu diesem Script...\n __DBMOD.name = __META.name;\n __DBMOD.version = __META.version;\n\n console.log(__DBMOD);\n\n // Zunaechst den alten Eintrag entfernen...\n __DBTOC.versions[__DBMOD.name] = undefined;\n\n // ... und die Daten der Fremdscripte laden...\n for (let module in __DBTOC.versions) {\n __DBDATA[module] = getValue(JSON.parse(__DBMEM.getItem('__DBDATA.' + module)), { });\n }\n}",
"resetCommandLineOptions () {\n this.setCommandLineOption(\"url\", undefined);\n this.setCommandLineOption(\"dir\", undefined);\n\n super.resetCommandLineOptions();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
tslint:enable Create a management canister actor. | function getManagementCanister(config) {
function transform(methodName, args, callConfig) {
const first = args[0];
let effectiveCanisterId = Principal.fromHex('');
if (first && typeof first === 'object' && first.canister_id) {
effectiveCanisterId = Principal.from(first.canister_id);
}
return { effectiveCanisterId };
}
return Actor.createActor(managementCanisterIdl, Object.assign(Object.assign(Object.assign({}, config), { canisterId: Principal.fromHex('') }), {
callTransform: transform,
queryTransform: transform,
}));
} | [
"async createManager() {\r\n let newManager = new Managers ({\r\n username: this.username,\r\n production: config.powerplant_production,\r\n powerPlantStatus: \"Running\"\r\n })\r\n\r\n await newManager.save(function(error){\r\n if (error) {\r\n console.log(error);\r\n return;\r\n } else {\r\n console.log(\"Manager added to database yey\")\r\n }\r\n });\r\n }",
"async function createManager() {\n const newManager = await new Manager();\n await newManager.getOfficeNumber();\n await manager.push(newManager);\n await generatorQs();\n}",
"addActor(scene, name, actor) {\n //console.log(`\\n@@@ narrative.addActor ${name} actor=${actor}:`);\n //console.dir(actor);\n //console.log(`addActor: et = ${devclock.getElapsedTime()}`);\n if (scene && actor && name && name.length > 0) {\n if (cast[name]) {\n narrative.removeActor(scene, name); //if replace actor with same name?\n }\n actor.name = name; // possible diagnostic use\n cast[name] = actor;\n //console.log(`addActor: et = ${devclock.getElapsedTime()}`);\n //prevent sglens and vrlens from becoming children of sgscene/vrscene\n //NOTE: if exp vrlens is child of vrscene vrcontrols FAIL!\n //NOTE: vrkeymap still works\n if (!/lens/.test(name)) {\n scene.add(actor);\n }\n //console.log(`n.addActor: scene.children.l = ${scene.children.length}`);\n //console.log(`n.addActor: cast size = ${Object.keys(cast).length}`);\n //console.log(`n.addActor: cast = ${Object.keys(cast)}`);\n }\n else {\n console.log(`n.addActor:FAILED to add actor ${actor} w. name ${name}!!`);\n }\n }",
"addViewingRole({initiator, target, day, role}) {\n const {viewingRole} = this.#status[initiator];\n viewingRole.push({target, day, role})\n this.#actions = [];\n }",
"spawn(mob){\r\n\r\n }",
"function MonsterManager() {\n Manager.call(this);\n}",
"SET_ACTIF_ADMINISTRATOR(state,payload){\n state.administrator = payload;\n }",
"constructor({ controllerMessenger, name, allowedActions, allowedEvents, }) {\n this.controllerMessenger = controllerMessenger;\n this.controllerName = name;\n this.allowedActions = allowedActions || null;\n this.allowedEvents = allowedEvents || null;\n }",
"function man(name) {\n this.name = name;\n this.isMortal = true; //All men are mortal\n}",
"function createMob() {\n var rand = Math.random();\n var tear = 1;\n if (rand < 0.5) {\n tear = 1;\n } else if (rand < 0.8) {\n tear = 2;\n } else if (rand < 0.95) {\n tear = 3;\n } else {\n tear = 4;\n }\n enemy = new Monster(LEVEL, tear);\n updateMob();\n}",
"init(actor) {\n this.host = actor\n }",
"spawning () {\n }",
"function init_pman() {\n\n var pman = new Pacman();\n pman.direction = LEFT;\n pman.x = 10;\n pman.y = 15;\n pman.lives = 3;\n\n actors[\"pman\"] = pman;\n pman.ref = $('<div>',{id:\"pman\",class:\"pman-left\"}).appendTo('#game-canvas');\n pman.draw();\n}",
"spawnEnemy() {\n // Pick a random x coordinate without set bounds\n // x will be between 25 and 425\n const x = (Math.random() * 360) + 40;\n\n // Casting X as a whole number to be used to pick a random enemy design\n let num = Math.round(x)\n\n // Creates the actual enemy object at the given position\n this.createEnemy(x, 0, num);\n\n // Set the spawn timer and time between spawns\n this.lastSpawned = this.now();\n\n if (this.score % 5 == 0)\n {\n this.spawnTime *= 0.95;\n }\n\n // Puts a hard limit on how small spawn time can get\n if (this.spawnTime < this.minSpawnTime) {\n this.spawnTime = this.minSpawnTime;\n }\n }",
"createAction(req, res) {\n let robot = new Robot();\n robot.name = req.body.name;\n\n robot.save((err) => {\n if (err)\n this.jsonResponse(res, 400, { 'error': err });\n\n this.jsonResponse(res, 201, { 'message': 'Robot created!' });\n });\n }",
"function createAdmin(callback) {\n AccessToken.destroyAll( function(err) {\n if (err) return callback(err);\n\n RoleMapping.destroyAll( function(err) {\n if (err) return callback(err);\n\n Roles.destroyAll( function(err) {\n if (err) return callback(err);\n\n Roles.create({\n name: 'admin'\n }, function(err, role) {\n if (err) return callback(err);\n //console.log('Created role:', role.name);\n\n role.principals.create({\n principalType: RoleMapping.USER,\n principalId: users.admin.username\n }, function(err, principal) {\n if (err) return callback(err);\n\n //console.log('Created principal:', principal.principalType);\n callback();\n });\n });\n });\n });\n });\n }",
"function C101_KinbakuClub_RopeGroup_NoActor() {\n\tActorLoad(\"\", \"ClubRoom1\");\n\tLeaveIcon = \"Wait\";\n}",
"createChannel() {\n\t\tlet depends = this.props.depends ? this.props.depends : {};\n\t\tvar channelObj = manager.create(depends);\n\n\t}",
"function spawnCreated(data) {\n // Handler for direct messages from child\n handlerCreate({\n name: 'helloHandler',\n channel: listenChannel,\n message: 'hello',\n ents: [data.ent]\n });\n\n // Let's talk back to the child\n directMessage({\n ent: data.ent,\n channel: listenChannel,\n message: 'hello',\n data: {\n channel: listenChannel,\n color: favoriteColor,\n number: favoriteNumber\n }\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
hideMouseReset event handler for mousemove to reset the hideMouse timer | function hideMouseReset()
{
if (hideMouseID === 0) { // Timer has fired and hid the cursor. Unhide it.
document.body.style.cursor = null;
hideMouseID = null; // null = cursor is visible
} else if (hideMouseID !== null) { // Timer hasn't fired yet. Remove it.
clearTimeout(hideMouseID);
hideMouseID = null; // null = cursor is visible
}
/* If still in slide mode, set a new timer; otherwise remove ourselves. */
if (slidemode) hideMouseID = setTimeout(hideMouse, hideMouseTime);
else document.removeEventListener('mousemove', hideMouseReset);
} | [
"function initHideMouse()\n{\n if (hideMouseTime === null) return;\n\n /* Add handler to restart the timer when the mouse moves. */\n document.addEventListener('mousemove', hideMouseReset);\n\n /* Remove old timer, unhide cursor if hidden, start new timer. */\n hideMouseReset();\n}",
"function hideMouse()\n{\n if (slidemode) document.body.style.cursor = 'none';\n hideMouseID = 0;\t\t// 0 = timer has fired, cursor is hidden\n}",
"function mouseIdleHandler() {\n mouse_id.style.display = \"block\";\n resetMouseTimeout(mouseIdleHandler)\n }",
"function mouseouthandler(event) {\n //console.log(\"the mouse is no longer over canvas:: \" + event.target.id);\n mouseIn = 'none';\n }",
"function mouseOut() {\n\tif (vid.paused === false) {\n controls.style.visibility = \"hidden\";\n seekslider.style.transform = \"translateY(30px)\";\n }\n}",
"function mouse_out_controls()\n{\n\t$(\".chalk_player .media_controls\").attr(\"data-mouse-in\",\"0\");\n}",
"imageMouseOutHandler() {\n clearInterval(this.triggerTime);\n }",
"stopTrackingMouse() {\n if (this._pointerWatch)\n this._pointerWatch.remove();\n\n this._pointerWatch = null;\n }",
"function mouseleave(e) {\n lastMousePos = {}\n coords.show()\n }",
"function resetHover() {\n hovering = false;\n startTimeout();\n }",
"function mouse_move_video()\n{\n\t$(\".chalk_player .media_controls\").addClass(\"media_show\");\n\tif($(\".chalk_player video\").attr(\"data-diy\")==\"1\")\n\t\t$(\".chalk_player .diy_wrapper .steps_container\").removeClass(\"hidden\");\n\tsetTimeout(function() {\n\t\tif($(\".chalk_player .media_controls\").attr(\"data-mouse-in\")==\"0\")\n\t\t\tif(Date.now()-$(\".chalk_player .media_controls\").attr(\"data-prev-hide\")>4000)\n\t\t\t{\n\t\t\t\t$(\".chalk_player .media_controls\").attr(\"data-prev-hide\",Date.now());\n\t\t\t\tmouse_out_video();\n\t\t\t}\n\t}, 4000);\n}",
"forceHide() {\n if (!this.$tip || !hasClass(this.$tip, ClassName.SHOW)) {\n /* istanbul ignore next */\n return;\n }\n // Disable while open listeners/watchers\n this.setWhileOpenListeners(false);\n // Clear any hover enter/leave event\n this.clearTimeout('hover');\n this.$hoverState = '';\n // Hide the tip\n this.hide(null, true);\n }",
"hideSystemCursor() {\n if (this._cursorTracker.set_keep_focus_while_hidden)\n this._cursorTracker.set_keep_focus_while_hidden(true);\n this._cursorTracker.set_pointer_visible(false);\n }",
"function OnTimeMouseDown(){\n\n \tg_bTimeUpdate = false;\n}",
"onPopupMouseLeave() {\n this.delaySetPopupVisible(false, this.props.delayHide);\n }",
"clearTechToolMousePos() {\r\n this.m_mousePushed_x = -1;\r\n this.m_mousePushed_y = -1;\r\n this.m_mouseMoving_x = -1;\r\n this.m_mouseMoving_y = -1;\r\n this.m_drawInf.setMousePos(0, 0);\r\n }",
"function mouseReleased(){\n\n shocked = false;\n\n}",
"function i2uiResizeSlaveonmousemove(e)\r\n{\r\n if (i2uiResizeSlavewhichEl == null)\r\n {\r\n event.returnValue = true;\r\n }\r\n else\r\n {\r\n event.returnValue = false;\r\n }\r\n}",
"function mouseDown(e) {\n // Here we changing isMoving from false to true, and depicting that now we are moving the mouse over the wheel\n setMoving(true);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clone left side, delete last child, and then copy to the right side | function deleteLast (theLeftSide) {
var theRightSide = document.getElementById("rightSide");
var leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);
} | [
"function delete_all_children() {\n var theRightSide = document.getElementById(\"rightSide\");\n var theLeftSide = document.getElementById(\"leftSide\");\n\n while (theRightSide.firstChild) {\n theRightSide.removeChild(theRightSide.firstChild)\n }\n while (theLeftSide.firstChild) {\n theLeftSide.removeChild(theLeftSide.firstChild)\n }\n}",
"pop() {\n if (this.currentNode.children.length > 0) return;\n\n let tmp = this.currentNode;\n this.previous();\n tmp.removeFromParent();\n }",
"function reference(node, clone)\n {\n clone.originalNode = node;\n \n node = node.firstChild;\n var child = clone.firstChild;\n \n while (node != null && child != null)\n {\n reference(node, child);\n node = node.nextSibling;\n child = child.nextSibling;\n }\n \n return clone;\n }",
"function swapChildren(root){\n var cR=root.children[0];\n var cL=root.children[1];\n root.children[0]=cL\n root.children[1]=cR;\n increaseSequence(cL,-cR.value);\n increaseSequence(cR,cL.value);\n }",
"function create_right_sibling(node)\n{\n if (node === null) \n {\n return;\n }\n \n var numberOfChildren = node.children.length;\n \n var queue = [];\n for (var i=0; i < numberOfChildren ; i++)\n {\n if (node.children[i].right === null && node.children[i+1])\n {\n node.children[i].right = node.children[i+1];\n queue.push(node.children[i]);\n }\n }\n \n for (var j=0; j < queue.length; j++)\n {\n create_right_sibling(queue[j]); \n }\n}",
"handleRightShiftUpdate($row){\n const node = $row.children(':last')\n node.detach();\n $row.prepend(node); \n }",
"shift() {\n if (!this.head) return undefined;\n let removed = this.head;\n if (this.length === 1) {\n this.head = null;\n this.tail = null;\n } else {\n this.head = removed.next;\n this.head.prev = null;\n removed.next = null;\n }\n\n // removed.next = null;\n this.length--;\n return removed;\n }",
"function split(node) {\r\n if (node.children.length === 0) { //Make sure this node has no children\r\n\r\n //Create or clone a new div\r\n let child1 = node.cloneNode();\r\n node.appendChild(child1);\r\n\r\n //Assign height and width values to them\r\n let dim = horv();\r\n child1.style.height = dim[0];\r\n child1.style.width = dim[1];\r\n\r\n //Assign random background color to them\r\n child1.style.backgroundColor = randColor();\r\n\r\n //Remove the class value\r\n child1.classList.remove('first');\r\n\r\n //Clone and copy the child div\r\n let child2 = child1.cloneNode();\r\n node.appendChild(child2);\r\n\r\n //Add event listeners to each\r\n listenClick(child1); //QUESTION - will an eventlistener get cloned? Nope.\r\n listenClick(child2);\r\n }\r\n}",
"cloneSubmenu() {\n if ( $('.menu > li.active .submenu').length ) {\n let $menuSub = $('.menu > li.active .submenu').clone();\n $menuSub.removeClass('animated fadeInUp');\n $('.submenu-placeholder').remove();\n $('.submenu-bar-inner').append($menuSub).addClass('not-empty');\n }\n }",
"function cleanClonePartData(children) {\n try {\n Object.keys(children[_constants_1.UI.CLONE_PARTS]).forEach(function (key, index) {\n if (index !== 0) {\n delete children[_constants_1.UI.CLONE_PARTS][key];\n }\n });\n var cloneKey_1 = Object.keys(children[_constants_1.UI.CLONE_PARTS])[0];\n var partsKey = children[_constants_1.UI.CLONE_PARTS][cloneKey_1][_constants_1.UI.PART] ? _constants_1.UI.PART : _constants_1.UI.PARTS;\n var clonePartsKey = children[_constants_1.UI.CLONE_PARTS][cloneKey_1][_constants_1.UI.PART] || children[_constants_1.UI.CLONE_PARTS][cloneKey_1][_constants_1.UI.PARTS]\n ? Object.keys(children[_constants_1.UI.CLONE_PARTS][cloneKey_1][partsKey])\n : [];\n // Loop over all of the subjects in the cloneParts array. There should only be one, but there may be a bug\n // causing there to be more than one. It shouldn't matter, though.\n clonePartsKey.forEach(function (part) {\n var _a;\n // Get the part itself. This should be the group, or the item inside of the multiple\n // Set the value to null for the part and update the base and parent value so it is a new set of parts instead of\n // tied to the original\n var cloneParts = children[_constants_1.UI.CLONE_PARTS][cloneKey_1][_constants_1.UI.PARTS];\n cloneParts[part] = __assign({}, cloneParts[part], (_a = {}, _a[_constants_1.UI.VALUE] = '', _a[_constants_1.UI.OLDVALUE] = '', _a));\n if (cloneParts[part][_constants_1.UI.PARTS]) {\n Object.keys(cloneParts[part][_constants_1.UI.PARTS]).forEach(function (subPartKey) {\n var _a;\n cloneParts[part][_constants_1.UI.PARTS][subPartKey] = __assign({}, cloneParts[part][_constants_1.UI.PARTS][subPartKey], (_a = {}, _a[_constants_1.UI.VALUE] = '', _a));\n // If an old value exists, delete it\n if (cloneParts[part][_constants_1.UI.PARTS][subPartKey][_constants_1.UI.OLDVALUE]) {\n delete cloneParts[part][_constants_1.UI.PARTS][subPartKey][_constants_1.UI.OLDVALUE];\n }\n });\n }\n });\n return children;\n }\n catch (error) {\n throw Error(error);\n }\n}",
"sendBackward(element) {\n return this.changeIndexTo(element, -1, true);\n\n if (index > 0) {\n var temp = this._children[index];\n this._children[index] = this._children[index - 1];\n this._children[index - 1] = temp;\n }\n }",
"function clearChildren() {\n while(board.firstChild) {\n board.removeChild(board.firstChild);\n }\n }",
"async addClonesToParent() {\n let parentComposition = this.openmct.composition.get(this.parent);\n await parentComposition.load();\n parentComposition.add(this.firstClone);\n\n return;\n }",
"sendToBack(element) {\n return this.changeIndexTo(element, 0, false);\n\n if (index > 0) {\n this._children.splice(index, 1);\n this._children.splice(0, 0, element);\n }\n }",
"balanceHtml() {\n\t\tif (!this.left && this.right) {\n\t\t\tthis.htmlRight = this.right.html;\n\t\t\tthis.setChildToNull(true);\n\t\t} else if (!this.right && this.left) {\n\t\t\tthis.htmlLeft = this.left.html;\n\t\t\tthis.setChildToNull(false);\n\t\t} else if (this.right && this.left) {\n\t\t\tthis.htmlLeft = this.left.html;\n\t\t\tthis.htmlRight = this.right.html;\n\t\t\tthis.setHtml();\n\t\t\tthis.updateRootHtml();\n\t\t} else {\n\t\t\tthis.htmlLeft = (\n\t\t\t\t<li className='null'>\n\t\t\t\t\t<div>null</div>\n\t\t\t\t</li>\n\t\t\t);\n\n\t\t\tthis.htmlRight = (\n\t\t\t\t<li className='null'>\n\t\t\t\t\t<div className='null'>null</div>\n\t\t\t\t</li>\n\t\t\t);\n\t\t\tthis.setHtml();\n\t\t\tthis.updateRootHtml();\n\t\t}\n\t}",
"addLeft(data){\n\t\tlet copyRoot = this.root;\n\t\twhile (this.root.left){\n\t\t\tthis.root = this.root.left;\n\t\t}\n\n\t\tthis.root.left = new TreeNode(data, this.root);\n\t\tthis.root = copyRoot;\n\t}",
"function doNavboxen() {\n\t\t\t// Move vertical-navbox into the right rail.\n\t\t\tvar $nbClone = $('.vertical-navbox').clone(true, true);\n\t\t\tif ($nbClone.length) {\n\t\t\t\t// Remove the old one.\n\t\t\t\t$('.vertical-navbox').remove();\n\t\t\t\t$('#wsidebar').append($nbClone);\n\t\t\t}\n\t\t}",
"delete(val) {\n debugger\n let currentNode = this.root;\n let found = false;\n let nodeToRemove;\n let parent = null;\n\n // find the node we want to remove\n while (!found) {\n if (currentNode === null || currentNode.val === null) {\n return 'the node was not found'\n }\n if (val === currentNode.val) {\n nodeToRemove = currentNode;\n found = true;\n } else if (val < currentNode.val) {\n parent = currentNode;\n currentNode = currentNode.left;\n } else {\n parent = currentNode;\n currentNode = currentNode.right;\n }\n }\n\n console.log(\"We found the node\");\n console.log('parent node', parent);\n\n // helper variable which returns true if the node we've removing is the left\n // child and false if it's right\n const nodeToRemoveIsParentsLeftChild = parent.left === nodeToRemove;\n\n // if nodeToRemove is a leaf node, remove it\n if (nodeToRemove.left === null && nodeToRemove.right === null) {\n if (nodeToRemoveIsParentsLeftChild) parent.left = null;\n else parent.right = null\n } else if (nodeToRemove.left !== null && nodeToRemove.right === null) {\n // only has a left child\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = nodeToRemove.left;\n } else {\n parent.right = nodeToRemove.left;\n }\n } else if (nodeToRemove.left === null && nodeToRemove.right !== null) {\n // only has a right child\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = nodeToRemove.right;\n } else {\n parent.right = nodeToRemove.right;\n }\n } else {\n // has 2 children\n const rightSubTree = nodeToRemove.right;\n const leftSubTree = nodeToRemove.left;\n // sets parent nodes respective child to the right sub tree\n if (nodeToRemoveIsParentsLeftChild) {\n parent.left = rightSubTree;\n } else {\n parent.right = rightSubTree;\n }\n\n // find the lowest free space on the left side of the right sub tree\n // and add the leftSubtree\n let currentLeftNode = rightSubTree;\n let currentLeftParent;\n let foundSpace = false;\n while (!foundSpace) {\n if (currentLeftNode === null) foundSpace = true;\n else {\n currentLeftParent = currentLeftNode;\n currentLeftNode = currentLeftNode.left;\n }\n }\n currentLeftParent.left = leftSubTree;\n return 'the node was successfully deleted'\n }\n }",
"function fill_missing_child_nodes_right_sibling(node)\n{\n if (node === null) \n {\n return;\n }\n \n var numberOfChildren = node.children.length;\n var lastNodeIndex = numberOfChildren - 1;\n \n if (lastNodeIndex >= 0)\n {\n if (node.children[lastNodeIndex].right === null)\n {\n node.children[lastNodeIndex].right = find_right_sibling(node);\n }\n for (var i=0; i < numberOfChildren; i++)\n {\n fill_missing_child_nodes_right_sibling(node.children[i]); \n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Submits login request to Internt Archive | static login() {
const doc = navigationDocument.documents[navigationDocument.documents.length - 1]
const e = doc.getElementsByTagName('textField').item(0)
const user = encodeURIComponent(e.getAttribute('data-username'))
const pass = encodeURIComponent(e.getFeature('Keyboard').text)
const dataString = `username=${user}&password=${pass}&remember=CHECKED&action=login&submit=Log+in`
$.post('https://archive.org/account/login.php', dataString, (xhr) => {
// https://developer.apple.com/documentation/tvmljs/xmlhttprequest
// TVA.alert(TVA.amp(dataString))
// TVA.alert(xhr.getAllResponseHeaders())
if (xhr.status !== 200) {
TVA.user = {}
TVA.alert(`server responded with non-success status: ${xhr.status}`)
return
}
// if (xhr.responseText.indexOf('Your browser does not appear to support cookies'))
// return TVA.alert('testcookie set/send problem')
// debugger
// return TVA.alert(TVA.amp(xhr.responseText).replace(/</g, '<').replace(/>/g, '>'))
TVA.set_user(TVA.last_week)
})
} | [
"login(username, password) {\r\n return this._call(\"post\", \"login\", { username, password });\r\n }",
"function signin(){\n var payload = {\n \"username\": username.value,\n \"password\": password.value\n };\n\n send_post_request(window.location.origin + '/api/rest-auth/login/', payload, function (data, status){\n\n if (status == 200 || status == 201){\n signin_message.innerHTML = \"Welcome, \" + username.value + \"!\";\n\n // Store token in browser\n sessionStorage.setItem(\"token\", data[\"key\"]);\n sessionStorage.setItem(\"username\", username.value);\n\n // go home\n location.href = window.location.origin\n\n }else{\n signin_message.innerHTML = \"Sign in Failed!\";\n\n }\n \n }, use_token=false)\n}",
"function login() {\n const OKTA_clientId = '0oa6fm8j4G1xfrthd4h6';\n const redirectUri = window.location.origin;\n\n const config = {\n logo: '//logo.clearbit.com/cdc.gov',\n language: 'en',\n features: {\n registration: false, // Enable self-service registration flow\n rememberMe: false, // Setting to false will remove the checkbox to save username\n router: true, // Leave this set to true for the API demo\n },\n el: \"#okta-login-container\",\n baseUrl: `https://hhs-prime.okta.com`,\n clientId: `${OKTA_clientId}`,\n redirectUri: redirectUri,\n authParams: {\n issuer: `https://hhs-prime.okta.com/oauth2/default`\n }\n };\n\n new OktaSignIn(config).showSignInToGetTokens({ scopes: ['openid', 'email', 'profile'] })\n .then(function (tokens) {\n const jwt = tokens.accessToken.value;\n window.sessionStorage.setItem('jwt', jwt);\n window.location.replace(`${window.location.origin}/daily-data/`);\n });\n}",
"login(params, callback){\n request(genRequestOptions({\n 'url' : 'https://apps.mypurecloud.com/api/v2/login',\n 'method' : 'POST',\n 'token' : null,\n 'data' : params\n }), function(error, response, body){\n if(error || response.statusCode !== 200){\n if(response.statusCode === 401)\n callback({'status' : 403, 'error' : body});\n else\n callback({'status' : response.statusCode, 'error' : body});\n }\n else{\n callback(null, body);\n }\n });\n }",
"async function login({ commit }, userData) {\n\t// one day ill implement snackbars with the auth state or use it in a component or footer\n\tcommit('auth_request')\n let response = await restApi\n\t\t.post('login', {\n\t\t\tusername: userData.username,\n\t\t\tpassword: userData.password,\n\t\t})\n\t\t.then((response) => {\n\t\t\t// we use the data we get back in the response object after the promise succeeds\n\t\t\t//you can change the data object props to match whatever your sever sends\n\t\t\tconst token = response.data.token\n\t\t\tconst user = response.data.username\n\t\t\t// storing jwt in localStorage. https cookie is safer place to store\n\t\t\tls.set('tokenKey', { token: token }) // using secure-ls to encrypt local storage\n\t\t\tls.set('userKey', { user: user })\n\t\t\taxios.defaults.headers.common['Authorization'] = 'Bearer ' + token\n\t\t\t// calling the mutation \"auth_success\" to change/update state.properties to the new values passed along in the second param\n\t\t\tcommit('auth_success', { token, user })\n\t\t})\n\t\t.catch((err) => {\n\t\t\tconsole.log('login error' + err)\n\t\t\tcommit('auth_error')\n\t\t\tls.remove('token')\n\t\t})\n return response\n}",
"function requestLogin() {\n\tlog('requesting');\n\tvar deferred = Q.defer();\n\n\tif (!code) {\n\t\tdeferred.reject('empty code');\n\t}\n\n\tvar data = querystring.stringify({\n\t\t'AjaxMethod': 'LOGIN',\n\t\t'Account': ACCOUNT.username,\n\t\t'Pwd': ACCOUNT.password,\n\t\t'ValidCode': code\n\t});\n\n\tvar options = {\n\t\thostname: HOST,\n\t\tport: 80,\n\t\tpath: URLS.login,\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\t'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n\t\t\t'Content-Length': data.length,\n\t\t\t'Cookie': COOKIE\n\t\t}\n\t};\n\n\tvar req = http.request(options, function(res) {\n\t\tvar content = '';\n\t\tres.setEncoding('utf8');\n\t\tres.on('data', function(chunk) {\n\t\t\tcontent += chunk;\n\t\t})\n\t\t.on('end', function() {\n\t\t\tlog('login message: ' + content);\n\t\t\tif (content.indexOf('true') !== -1) {\n\t\t\t\tdeferred.resolve();\n\t\t\t} else if (content.indexOf('验证码不符合!') != -1) {\n\t\t\t\tdeferred.reject('wrong validcode');\n\t\t\t} else {\n\t\t\t\tdeferred.reject('unknown error');\n\t\t\t}\n\t\t})\n\t});\n\n\treq.on('error', function(e) {\n\t\tdeferred.reject(e.message);\n\t})\n\n\treq.write(data);\n\treq.end();\n\n\treturn deferred.promise;\n}",
"function doLogin(username, password){\n\thideOrShow(\"register\", false);\n\n\tif(!username || !password)\n\t{\n\t\tusername = document.getElementById(\"loginName\").value.toLowerCase(); //Assign from user field.\n\t\tpassword = document.getElementById(\"loginPassword\").value; //Assign from pass field.\n\t}\n\n\tUSERNAME = username;\n\t//Create JSON body.\n\tlet body = {\n\t\t\"username\": username,\n\t\t\"password\": password\n\t}\n\n\t$.post(urlBase + \"api/login\", body)\n\t\t.done(function(data) {\n\t\t\tif(data.success === false){\n\t\t\t\talert(\"Could not login: \\n\" + data.message );\n\t\t\t}\n\t\t\telse{\n\t\t\t\tconsole.log(data);\n\t\t\t\tif(data.token)\n\t\t\t\t\tdocument.cookie = \"USER=\" + data.token;\n\t\t\t\t\tdocument.cookie = \"USERNAME=\" + username;\n\t\t\t\t\tdocument.cookie = \"PASSWORD=\" + password;\n\t\t\t\thideOrShow(\"Front Page\", false);\n\t\t\t\thideOrShow(\"contactPage\", true);\n\t\t\t\tgetContacts();\n\t\t\t}\n\n\t\t})\n\t\t.fail(function(err) {\n\t\t\tconsole.log(err);\n\t\t\talert(\"Failed to login\");\n\t\t})\n}",
"@action\n async login() {\n await this.auth.ensureLogin(this.selectedProvider);\n await this.storeCommunicator.fetchTypeIndexes(this.auth.webId);\n await this.profile.fetchProfileInfo();\n }",
"async login() {\n try {\n const { accountName, permission, publicKey } = await this.keycat.signin();\n return [\n new KeycatUser({\n accountName,\n permission,\n publicKey,\n keycat: this.keycat,\n chainId: this.selectedChainId,\n\n }),\n ];\n } catch (err) {\n throw new UALError(err.messsage, UALErrorType.Login, err);\n }\n }",
"function Authenticate() {\r\nconsole.log(\"authenticating user here..\");\r\ndojo.byId(\"divAppContainer\").style.display = \"block\";\r\n\r\n portal.signIn().then(function (loggedInUser) {\r\n //ShowProgressIndicator();\r\n portalUser = loggedInUser;\r\n dojo.byId(\"AddHeaderContentLogin\").innerHTML = portalUser.fullName;\r\n\t\tconsole.log(\"portalUser = \" + portalUser.fullName);\r\n sessionStorage.clear();\r\n\r\n // FindArcGISUserInGroup(configOptions.defaultExtent);\r\n var data = portalUser.credential;\r\n token = data.token;\r\n //tst for webmap in url to see if being passed from sharing link\r\n var chk = window.location.toString();\r\n var chk1 = chk.split(\"=\");\r\n if (chk.indexOf(\"webmap=\") != -1) {\r\n //need to get group info in login but don't run the searches to bring add content window to screen\r\n FindUsersGroupsNoSearch();\r\n\r\n CreateMapLayers(chk1[1], null);\r\n\r\n\r\n } else {\r\n\r\n FindUsersGroups();\r\n CloseAddContentsContainer();\r\n }\r\n });\r\n\r\n //prompt user for credentials for selected portal\r\n if (dojo.query(\".dijitDialogPaneContentArea\")[0]) {\r\n dojo.query(\".dijitDialogPaneContentArea\")[0].childNodes[0].innerHTML = \"Selected Portal: \" + dojo.query(\".labelEventNew1\", dojo.byId(\"tblPortalList\"))[0].innerHTML;\r\n \r\n\t var divPortal = dojo.create(\"div\");\r\n divPortal.innerHTML = \"Enter your Username and Password\";\r\n divPortal.style.marginTop = \"3px\";\r\n dojo.query(\".dijitDialogPaneContentArea\")[0].childNodes[1].appendChild(divPortal);\r\n }\r\n\r\n}",
"function LogClient ()\n{\n client.login (config.Token);\n}",
"loginCustomer(cemail, cpass) {\n return axios.post(CUSTOMER_API_BASE_URL + '/login/' + cemail + '/' + cpass);\n }",
"login (email, password) {\n assert.equal(typeof email, 'string', 'email must be string')\n assert.equal(typeof password, 'string', 'password must be string')\n const ctx = this\n return this._apiRequest('/user/login', 'POST', { email, password })\n .then(res => {\n ctx.api_access_key = res.api_access_key\n return res\n })\n }",
"onLogin() {}",
"function handleLogInSubmit() {\n $('body').on(\"submit\", \"#form-log-in\", (event) => {\n event.preventDefault();\n const credentials = {\n username: $('#username-txt').val(),\n password: $('#password-txt').val()\n }\n doUserLogIn({\n credentials,\n onSuccess: getAndDisplayIdeas,\n onError: err => {\n alert('Incorrect username or password. Please try again.');\n }\n });\n });\n}",
"authenticate() {\n this.set('hasResponseMessage', null);\n const {\n formatUsername,\n password,\n api,\n selectedEnvironemnt\n } = this.getProperties('formatUsername', 'password', 'api', 'selectedEnvironemnt');\n return this.get('session').authenticate('authenticator:application', formatUsername, password, api, selectedEnvironemnt)\n .catch(() => {\n this.set('hasResponseMessage', \"Invalid login. Please try again.\");\n });\n }",
"async function okCreateLogin() {\n if (userRole === \"Admin\"){\n let loginName = userNameInput.value + \"\";\n let loginPassword = passwordInput.value + \"\";\n let loginRole = loginRoleSelect.value + \"\";\n let response = await adminPOST({loginName, loginPassword, loginRole}, \"api/login/createLogin\");\n createLoginCloseModalAction();\n if (response !== undefined) {\n alert(\"Login blev ikke oprettet. \\n\" + response.body);\n }\n }\n}",
"function confirm_fedauth_login() {\n\n var acct = Rdbhost.account_number(),\n host = Rdbhost.host();\n\n var confProm = fetch('https://'+host+'/static/auth?uid='+acct,\n {mode: 'cors', method: 'get', credentials: 'include'});\n\n return confProm.then(function(d) {\n return d.json().then(function(body) {\n return { identifier: body.ident,\n issuer: body.issuer,\n key: body.key,\n status: body.status,\n idx: body.idx };\n })\n })\n .catch(function(e) {\n return { status: 'confirm-failed' };\n });\n }",
"function event_login(e) {\n ajax_login($('#email').val());\n e.preventDefault();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find by keyword & category | function findByKeywordAndCategory() {
getCateCacheByCategory()
.then(catecaches => {
// Check pagination
_findQuery = _pageNumber === undefined ? Dictionary.find({ 'keyword': { $regex: new RegExp(_keyword, "i") }, 'categoryid': { $in: catecaches } }).sort('keyword').limit(_pageSize)
: Dictionary.find({ 'keyword': { $regex: new RegExp(_keyword, "i") }, 'categoryid': { $in: catecaches } }).sort('keyword').skip((_pageNumber - 1) * _pageSize).limit(_pageSize);
var countQuery = Dictionary.count({ 'keyword': { $regex: new RegExp(_keyword, "i") }, 'categoryid': { $in: catecaches } });
// Execute the queries
executeCountQuery(countQuery)
.then(totalRecord => {
executeFindQuery(totalRecord);
})
.catch(err => {
logger.error("Error at function: DictionaryController.findAll->findByKeywordAndCategory", err);
return res.send({ code: 400, message: "Data not found!" });
})
})
.catch(err => {
logger.error("Error at function: DictionaryController.findAll->findByKeywordAndCategory", err);
return res.send({ code: 400, message: "Data not found!" });
})
} | [
"function searchObject(text) {\n allObjects.forEach((item) => {\n if (item.title.toLowerCase().includes(text)) {\n relatedObjects.push(item);\n } else if (item.keywords.toLowerCase().includes(text)) {\n relatedObjects.push(item);\n }\n })\n}",
"static findByCategory(searchCategory) {\r\n let results = []\r\n\r\n for (let event in all) {\r\n if (event.category.has(searchCategory)) {\r\n results.add(event);\r\n }\r\n }\r\n return results;\r\n }",
"function suggest(category, categories) {\n \t\n \t// fecth candidate suggestions from dictionary\n var candidates = categories[category.toLowerCase()];\n \n // format candidate suggestions according to category template\n if (isUpperCase(category)) {\n candidates = candidates.map(function(word) { return word.toUpperCase(); })\n } else if (isCapitalized(category)) {\n \tcandidates = candidates.map(function(word) { return capitalize(word); })\n }\n \n // return candidate suggestions\n return candidates;\n \n }",
"function displayItemsByNameAndCategory(searchString) {\n const filteredItems = CatalogItems.filter((item) => {\n return (\n item.name.toLowerCase().includes(searchString) ||\n item.category.toLowerCase().includes(searchString)\n );\n });\n\n //send items to be displayed\n displayItems(filteredItems);\n}",
"get _keywordQuery() {\n // The keyword is the first word in the search string, with the parameters\n // following it.\n let searchString = this._trimmedOriginalSearchString;\n let queryString = \"\";\n let queryIndex = searchString.indexOf(\" \");\n if (queryIndex != -1) {\n queryString = searchString.substring(queryIndex + 1);\n }\n // We need to escape the parameters as if they were the query in a URL\n queryString = encodeURIComponent(queryString).replace(/%20/g, \"+\");\n\n // The first word could be a keyword, so that's what we'll search.\n let keyword = this._searchTokens[0];\n\n return [\n SQL_KEYWORD_QUERY,\n {\n keyword: keyword,\n query_string: queryString,\n query_type: QUERYTYPE_KEYWORD\n }\n ];\n }",
"function search(foundArticles, searchedName) {\n matchedArticles = [];\n str = searchedName.replace(/\\s/g, '');\n if (str == \"\") {\n return matchedArticles;\n }\n foundArticles.forEach(function(article) {\n if (article.name.toLowerCase().includes(searchedName.toLowerCase())) {\n matchedArticles.push(article);\n }\n else if (article.author.toLowerCase().includes(searchedName.toLowerCase())) {\n matchedArticles.push(article);\n }\n else if (article.keywords.toLowerCase().includes(searchedName.toLowerCase())) {\n matchedArticles.push(article);\n }\n });\n return matchedArticles;\n}",
"search(text) {\n return this.addOption('search', text);\n }",
"function getCategoriesWithNameLike(req, res, mysql, context, complete) {\n\t\t//sanitize the input as well as include the % character\n\t\tvar query = \"SELECT id, name FROM categories WHERE name LIKE \" + mysql.pool.escape('%' + req.query.searchName + '%');\n\n\t\tmysql.pool.query(query, function (error, results, fields) {\n\t\t\tif (error) {\n\t\t\t\tres.write(JSON.stringify(error));\n\t\t\t\tres.end();\n\t\t\t}\n\t\t\tcontext.categories = results;\n\t\t\tcomplete();\n\t\t});\n\t}",
"find(type, group, instance) {\n\t\tif (Array.isArray(type)) {\n\t\t\t[type, group, instance] = type;\n\t\t} else if (typeof type === 'object') {\n\t\t\t({type, group, instance} = type);\n\t\t}\n\t\tlet query = {\n\t\t\ttype,\n\t\t\tgroup,\n\t\t\tinstance,\n\t\t};\n\n\t\tlet index = bsearch.eq(this.records, query, compare);\n\t\treturn index > -1 ? this.records[index] : null;\n\n\t}",
"function SearchForBookshelf(keyword, callback) {\n var bookshelfList = GetAllBookshelves();\n var result = [];\n\n for (x of bookshelfList) {\n var str = x.id.toLowerCase();\n if (str.indexOf(keyword.toLowerCase()) != -1) {\n result.push(x);\n }\n }\n\n return result;\n}",
"static find(x) {\n return this.data.filter(foodModel => foodModel.name.toLowerCase().includes(x.toLowerCase()));\n }",
"function containsCategory(collection, category) {\n $log.log(\"Checking if category \" + category + \" exists in\", collection);\n\n if(collection == null)\n return null;\n\n for(var i = 0; i < collection.length; i++) {\n if(collection[i] == category)\n return collection[i];\n }\n\n return null;\n }",
"static searchProductionLines(keywords) {\n let query = ProductionLine.query();\n query.where(\"name like '%\" + keywords + \"%'\");\n query.order(\"id\", true);\n\n return new Promise( (resolve, reject) => {\n ProductionLine.exec(query).then( list => {\n resolve(list);\n }).catch(error => {\n reject(error);\n });\n });\n }",
"function search1(searchTerm) {\n let docsWithTerm = []\n let reportsWithTerm = []\n let selectedReports = []\n docToRep = {}\n\n Object.keys(store.page).forEach(page => {\n if (page.body.includes(searchTerm) || page.footnote.includes(searchTerm)) {\n docsWithTerm.push(page.document_id)\n }\n })\n Object.keys(store.document).forEach(doc => {\n if (docsWithTerm.includes(doc.id) || doc.name.includes(searchTerm)) {\n reportsWithTerm.push(doc.report_id)\n }\n })\n Object.keys(store.report).forEach(rep => {\n if (reportsWithTerm.includes(rep.id) || rep.title.includes(searchTerm)) {\n selectedReports.push(rep.title)\n }\n })\n return selectedReports\n}",
"function search(searchString, titleSearchBool, tagsSearchBool, commentsSearchBool) {\r\n\tvar theTerms = splitSearchString(searchString);\r\n\tif (theTerms.length == 0) {\r\n\t\tvar allEntries = dataHandler.getAllEntries();\r\n\t\treturn allEntries;\r\n\t}\r\n\t\r\n\tvar positiveMatches = [];\r\n\tvar negativeMatches = [];\r\n\tvar finalMatches = [];\r\n\r\n\t\r\n\t// Get the first set of positive matches, corresponding to the first positive search term.\r\n\tvar termIndex = 0;\r\n\twhile((theTerms[termIndex].charAt(0) == \"-\") && (termIndex < theTerms.length)) termIndex++;\r\n\tif (termIndex < theTerms.length) {\r\n\t\tif (titleSearchBool) {\r\n\t\t\tpositiveMatches = positiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"title\"));\r\n\t\t}\r\n\t\tif (tagsSearchBool) {\r\n\t\t\tpositiveMatches = positiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"tag\"));\r\n\t\t}\r\n\t\tif (commentsSearchBool) {\r\n\t\t\tpositiveMatches = positiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"comment\"));\r\n\t\t}\r\n\t\tpositiveMatches = unique(positiveMatches);\r\n\t}\r\n\r\n\t\r\n\t// Now, loop over the rest of the positive terms, ANDing the resulting arrays with\r\n\t// our first results array.\r\n\tvar nextPositiveMatches = [];\r\n\tfor (termIndex = 1; termIndex < theTerms.length; termIndex++) {\r\n\t\tif (theTerms[termIndex].charAt(0) != \"-\") {\r\n\t\t\tif (titleSearchBool) {\r\n\t\t\t\tnextPositiveMatches = nextPositiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"title\"));\r\n\t\t\t}\r\n\t\t\tif (tagsSearchBool) {\r\n\t\t\t\tnextPositiveMatches = nextPositiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"tag\"));\r\n\t\t\t}\r\n\t\t\tif (commentsSearchBool) {\r\n\t\t\t\tnextPositiveMatches = nextPositiveMatches.concat(dataHandler.findEntries(theTerms[termIndex], \"comment\"));\r\n\t\t\t}\r\n\t\t\tnextPositiveMatches = unique(nextPositiveMatches);\r\n\t\t\tpositiveMatches = positiveMatches.intersection(nextPositiveMatches);\r\n\t\t\tif (positiveMatches == null)\r\n\t\t\t\treturn [];\r\n\t\t\tnextPositiveMatches = [];\r\n\t\t}\r\n\t}\r\n\t\r\n\t// Get negative matches.\r\n\tfor (termIndex = 0; termIndex < theTerms.length; termIndex++) {\r\n\t\tif (theTerms[termIndex].charAt(0) == \"-\") {\r\n\t\t\tif (titleSearchBool) {\r\n\t\t\t\tnegativeMatches = negativeMatches.concat(dataHandler.findEntries(theTerms[termIndex].substring(1), \"title\"));\r\n\t\t\t}\r\n\t\t\tif (tagsSearchBool) {\r\n\t\t\t\tnegativeMatches = negativeMatches.concat(dataHandler.findEntries(theTerms[termIndex].substring(1), \"tag\"));\r\n\t\t\t}\r\n\t\t\tif (commentsSearchBool) {\r\n\t\t\t\tnegativeMatches = negativeMatches.concat(dataHandler.findEntries(theTerms[termIndex].substring(1), \"comment\"));\r\n\t\t\t}\r\n\t\t\tnegativeMatches = unique(negativeMatches);\r\n\t\t}\r\n\t}\r\n\r\n\t// Subtract the negative matches from the positive matches; put the result\r\n\t// in finalMatches.\r\n\tvar foundNegativeMatch;\r\n\tfor (var posIndex = 0; posIndex < positiveMatches.length; posIndex++) {\r\n\t\tfoundNegativeMatch = false;\r\n\t\tfor (var negIndex = 0; negIndex < negativeMatches.length; negIndex++) {\r\n\t\t\tif (positiveMatches[posIndex].getId() == negativeMatches[negIndex].getId()) {\r\n\t\t\t\tfoundNegativeMatch = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!foundNegativeMatch) {\r\n\t\t\tfinalMatches.push(positiveMatches[posIndex]);\r\n\t\t}\r\n\t}\r\n\t\r\n\t// finalMatches should now have all final matches.\r\n\treturn finalMatches;\r\n}",
"function getDatabaseParameterPostCategory (params, query, body){\r\n\treturn body.category;\r\n}",
"function findResults(lines, keyword){\n arr = [];\n for (var i in lines){\n var terms = parseTerms(lines[i])[0][0];\n if (terms){\n if (terms.predicate != undefined){\n if (terms.predicate==\"result\"){\n try{\n if (keyword==\"tick\"){\n var keyword2 = terms.terms[0].predicate;\n }\n else{\n var keyword2 = terms.terms[0].terms[0].predicate;\n }\n\n if (keyword==keyword2){\n arr.push(lines[i].substring(6));\n }\n }catch(err){}\n }\n }\n }\n }\n return arr;\n }",
"function getRestaurantsBySearchTerm(keyword){\n var qualified = [];\n var returnObjects = [];\n if(keyword in searchIndex){\n qualified = searchIndex[keyword];\n }\n\n if(_ddebug){ console.log(qualified); }\n \n // fill out the restaurant objects, because qualified is only a list of qualifying ids\n if(qualified.length > 0){\n for(var i in qualified){\n returnObjects.push(getRestaurant(qualified[i]));\n }\n }\n return returnObjects;\n }",
"function findTagsByText(text) {\n\n return $http.get(URLS.BASE + URLS.TAGS + \"?text=\" + text)\n .then((responce) => {\n return responce.data;\n })\n .catch((error) => {\n console.log(error);\n return $q.reject(error);\n });\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
associates row metadata from the supplied message with this query object metadata used when parsing row results | handleRowDescription(msg) {
this._checkForMultirow()
this._result.addFields(msg.fields)
this._accumulateRows = this.callback || !this.listeners('row').length
} | [
"function insightFromRow (row) {\n return {\n id: row.iid,\n title: row.title,\n url: row.url,\n author: row.author,\n creator_id: row.creator_id,\n type: row.type,\n date: row.date,\n active: row.active,\n tags: row.tid ? [tagFromRow(row)] : []\n };\n}",
"getRowObject(i) {\n const row = this.rows[i];\n const obj = {};\n for (const i in this.fieldNames) {\n const fieldName = this.fieldNames[i];\n const fieldValue = row[i];\n obj[fieldName] = fieldValue;\n }\n return obj;\n }",
"function objectizeRowData(_row) {\r\n\tiobj = new Object();\r\n\tiobj.id = _row.getValue(_row.getAllColumns()[0].getName(),_row.getAllColumns()[0].getJoin()); //internal id\r\n\tiobj.cfrom = _row.getValue(_row.getAllColumns()[1].getName(),_row.getAllColumns()[1].getJoin()); //created from (Linked Trx)\r\n\tiobj.trxrectype = _row.getValue(_row.getAllColumns()[2].getName(),_row.getAllColumns()[2].getJoin()); //transaction record type\r\n\tiobj.trxshipstate = _row.getValue(_row.getAllColumns()[3].getName(),_row.getAllColumns()[3].getJoin()); //transaction shipping state\r\n\tiobj.cfromshipstate = _row.getValue(_row.getAllColumns()[4].getName(),_row.getAllColumns()[4].getJoin()); //created from shipping state\r\n\tiobj.cfromrectype = _row.getValue(_row.getAllColumns()[5].getName(),_row.getAllColumns()[5].getJoin()); //created from record type\r\n\tiobj.trxnumber = _row.getValue(_row.getAllColumns()[6].getName(),_row.getAllColumns()[6].getJoin()); //trx number\r\n}",
"function populateMetadataInternal() {\n \"use strict\";\n\n const table = document.getElementById(\"metadataInternal\");\n\n const url = getBaseURL();\n\n fetch(url).then(function (response) {\n if (response.ok) {\n return response.json();\n }\n throw new Error(\"Internal metadata request failed.\");\n }).then(function (data) {\n data.metadata_items.forEach(function (item) {\n tableAppendRow(table, [item.field.name, item.value]);\n });\n }).catch(function (e) {\n tableAppendRow(table, e.toString());\n });\n}",
"function addRowToSpreadsheet(message, file, originalFileName) {\r\n var config = getSpreadsheetLoggingConfig();\r\n\r\n if (config.activateSpreadsheetLogging == true) {\r\n\r\n var ss = SpreadsheetApp.openById(config.spreadsheetId);\r\n var sheet = ss.getSheetByName(config.sheetName);\r\n\r\n var nextRow = sheet.getLastRow() + 1;\r\n var cols = config.columns;\r\n\r\n var allInfo = getAllMailAttachmentInfo(message, file, originalFileName);\r\n\r\n for (let [keyword, obj] of Object.entries(allInfo)) {\r\n var cell = sheet.getRange(nextRow, obj.column);\r\n if (keyword == \"subject\") {\r\n if (cols.splitSubject.activated) {\r\n continue;\r\n } \r\n } else if (keyword == \"mailLink\") {\r\n cell.setFormula('=HYPERLINK(\"'+ obj.value +'\"; \"Open in Gmail\")');\r\n continue;\r\n\r\n } else if (keyword == \"fileLink\") {\r\n cell.setFormula('=HYPERLINK(\"'+ obj.value +'\"; \"Open in GDrive\")');\r\n continue;\r\n }\r\n cell.setValue(obj.value);\r\n }\r\n }\r\n}",
"extractMetadata(content) {\n const metadata = {};\n const both = this.splitHeader(content);\n\n // if no content returned, then that means there was no header, and both.header is the content\n if (!both.content) {\n if (!both.header) {\n return { metadata, rawContent: content };\n }\n return { metadata, rawContent: both.header };\n }\n\n // New line characters => to handle all operating systems.\n const lines = both.header.split(/\\r?\\n/);\n\n // Loop that add to metadata the current content of the fields of the header\n // Like the format:\n // id:\n // title:\n // original_id:\n for (let i = 0; i < lines.length - 1; ++i) {\n const keyvalue = lines[i].split(\":\");\n const key = keyvalue[0].trim();\n let value = keyvalue\n .slice(1)\n .join(\":\")\n .trim();\n try {\n value = JSON.parse(value);\n } catch (err) {\n // Ignore the error as it means it's not a JSON value.\n }\n metadata[key] = value;\n }\n return { metadata, rawContent: both.content };\n }",
"_open(rs) {\n this._resultSet = rs;\n\n // trigger the event listener that may have been added in _read() now that\n // the result set is ready\n this.emit('open');\n\n // emit a metadata event as a convenience to users\n this.emit('metadata', rs.metaData);\n }",
"function constructItemRow(rowObject) {\n // Convert to array.\n var rowDataToAppend = constructArrayFromObject(MERGED_SHEET_HEADERS, rowObject); \n // Add the formulas for columns that don't contain static data.\n rowDataToAppend[ORDER_FULFILLED_COLUMN_INDEX] = \" \";\n rowDataToAppend = addOrderDate(rowDataToAppend, rowObject); \n rowDataToAppend = addItemShippedFormula(rowDataToAppend, rowObject); \n rowDataToAppend = addItemTotalFormula(rowDataToAppend);\n rowDataToAppend = addStoreNameFormula(rowDataToAppend);\n // If there is a shipment present, add formulas.\n var orderItemId = rowObject.shipments_shipmentItems_orderItemId\n if (orderItemId != undefined && orderItemId != '') {\n rowDataToAppend = addShipmentFormulas(rowDataToAppend, rowObject);\n }\n // Row data is ready: write it to the array.\n return rowDataToAppend;\n}",
"function mergeMetaDataToCustomObject(customMetaDataObjectMap){\n\n $log.info('incoming customMetadataObject', customMetaDataObjectMap);\n\n var mergedCustomObject = {\n name: customMetaDataObjectMap.qualifiedName,\n label: customMetaDataObjectMap.customObject.label[0],\n pluralLabel: customMetaDataObjectMap.customObject.pluralLabel[0],\n fields:[],\n records:[]\n };\n\n\n for(var rKey in customMetaDataObjectMap.customMetaData){\n\n var record = {};\n record.name = rKey;\n record.description = customMetaDataObjectMap.customMetaData[rKey].description[0];\n record.label = customMetaDataObjectMap.customMetaData[rKey].label[0];\n record.values = [];\n for(var v=0; v < customMetaDataObjectMap.customMetaData[rKey].values.length; v++){\n\n var field = {};\n field.value = customMetaDataObjectMap.customMetaData[rKey].values[v].value[0];\n field.name = customMetaDataObjectMap.customMetaData[rKey].values[v].field[0];\n field.type = customMetaDataObjectMap.customObject.fields[v].type[0];\n\n record.values.push(field);\n\n }\n\n\n mergedCustomObject.records.push(record);\n\n }\n\n // merge the fields with the values of the custom metadata type\n // the custom object and metaData are paired by common fullname\n // both the fields and values arrays have matching order and length\n for(var f=0; f < customMetaDataObjectMap.customObject.fields.length; f++){\n\n var incomingField = customMetaDataObjectMap.customObject.fields[f];\n //var incomingValue = customMetaDataObjectMap.customMetaData.values[f];\n \n var field = {};\n field.fullName = incomingField.fullName[0];\n field.label = incomingField.label[0];\n if(typeof incomingField.length !== 'undefined'){ field.length = incomingField.length[0]; }\n //field.value = incomingValue.value[0];\n if(typeof incomingField.defaultValue !== 'undefined'){ field.defaultValue = incomingField.defaultValue[0]; }\n if(typeof incomingField.precision !== 'undefined'){ field.precision = incomingField.precision[0]; }\n if(typeof incomingField.scale !== 'undefined'){ field.scale = incomingField.scale[0]; }\n if(typeof incomingField.unique !== 'undefined'){ field.unique = incomingField.unique[0]; }\n if(typeof incomingField.required !== 'undefined'){ field.required = incomingField.required[0]; }\n if(typeof incomingField.externalId !== 'undefined'){ field.externalId = incomingField.externalId[0]; }\n field.type = incomingField.type[0];\n\n mergedCustomObject.fields.push(field);\n\n }\n\n // this defines the existing list of custom objects.\n existingCustomMetadataObjects.push(mergedCustomObject);\n\n if (existingCustomMetadataObjects.length === Object.keys(cmToCustomObjectMapper).length) {\n\n resolveHelper(existingCustomMetadataObjects)\n $log.info('existingCustomMetadataObjects',existingCustomMetadataObjects );\n\n }\n\n }",
"attachMetadata(recipe, metadataResponse) {\n recipe.watched = metadataResponse.watched.includes(recipe.id);\n recipe.saved = metadataResponse.favs.includes(recipe.id);\n recipe.addedToMeal = metadataResponse.meal.includes(recipe.id);\n\n return recipe;\n }",
"static retransmitMessage(message){\n MetaManager.getEntity(message.entity).executeCommand({ command: message.cmd, value: message.arg}, true);\n }",
"parseFetchedResult(data) {\n const {bodyDataKey, footerDataKey} = this.props\n if (check.object(data)) {\n if (data[bodyDataKey]) this.setState({tableBodyData: data[bodyDataKey]})\n if (data[footerDataKey]) this.setState({tableFooterData: data[footerDataKey]})\n } else if (check.array(data)) {\n this.setState({tableBodyData: data})\n } else {\n throw new Error('Invalid data format')\n }\n }",
"function processMessage(msg){\n let outputMessage = {};\n\n if (!msg){\n errLog(\"No message to process.\");\n return;\n }\n\n outputMessage.routingKey = msg.fields.routingKey;\n outputMessage.id = msg.properties.appId;\n outputMessage.content = msg.content;\n outputMessage.timestamp = msg.properties.timestamp;\n outputMessage.length = msg.content.length;\n\n return outputMessage;\n}",
"function identifiersMessage(message) {\n this.titleType = message.titleType;\n this.title = message.title;\n this.bodyType = message.bodyType;\n this.body = message.body;\n this.nextType = message.nextType;\n this.nextTag = message.nextTag;\n this.next = message.next;\n folder = message.href.match(/https?:\\/\\/(www.)?([^\\/]*)/)[2] + \"/\"; // matches the part between www. and the first /\n sendMessage({\n command: \"fetchChapter\",\n titleType: this.titleType,\n title: this.title,\n bodyType: this.bodyType,\n body: this.body\n });\n}",
"function buildInfoTable(rows) {\n var itable = { \n rows: rows,\n dataShape: {\n fieldDefinitions: {\n value: {aspects: {}, baseType: \"STRING\", name: \"value\" }, \n pressed: {aspects: {}, baseType: \"BOOLEAN\", name: \"pressed\" }\n }\n }\n }; \n return itable;\n }",
"fillHeaderRow(headerRowNumber, rowData) {\n for (let [i, value] of rowData.entries()) {\n this.tableBodyNode.appendChild(this.createTableDiv('header ' + headerRowNumber, this.keys[i], value, 'string', this.columnFormats[i] + ' tableHeaderDiv'))\n }\n }",
"function addRow(record, index, allItems)\n {\n addRecordToJSONSearch(record,panelNumber)\n }",
"function addMetaData(container, callback) {\n $('[data-id]', container).each(function (i, row) {\n var $item, model, id, data;\n\n $item = $(row);\n model = $item.attr('data-class');\n id = $item.attr('data-id');\n\n if (metaData && metaData[model] && metaData[model][id]) {\n data = metaData[model][id];\n appendMetaData(row, model, id, data);\n }\n });\n\n if (callback) {\n callback();\n }\n }",
"updateMessage(props) {\n Common.assertPlainObject(props);\n const model = this.application.getModel();\n const message = model.getMessageById(props.id);\n if (message) {\n for (const k of Object.keys(props)) {\n if (k !== 'id') {\n message[k] = props[k];\n }\n }\n }\n this.forceUpdate();\n this.application.renderDiagram();\n }",
"function addRow(row, tableRef, drug) {\n\tlet i, j;\n\tlet occs, ptr, text;\n\tlet newRow;\n\tlet mentioned, mentions;\n\tlet year;\n\n\t// Skip header row\n\tif (row[0] == \"cord_uid\") {\n\t\treturn;\n\t}\n\t\n\t// Check if row contains the search query\n\toccs = findOccurrences(row, drug);\n\t\n\tif (occs.length != 0) {\n\t\n\t\t// Create new row\n\t\tnewRow = tableRef.insertRow();\n\t\t// Add the elements one by one\n\t\tfor (j = 0; j < vCols.length; j++) {\n\t\t\t// Pointer to the wanted columns\n\t\t\tptr = vCols[j];\n\t\t\t// Cases for year storing & author name formatting\n\t\t\t// If on \"Publish Date\" column, Store year for chart\n\t\t\tif (ptr == 9) {\n\t\t\t\ttext = String(row[ptr]);\n\t\t\t\tyear = String(row[ptr]).split('-')[0] - 2000;\n\t\t\t\tif (year >= 0) {\n\t\t\t\t\tyears[year] += 1;\n\t\t\t\t}\n\t\t\t// If on \"Authors\" column, format the text accoringly\n\t\t\t} else if (ptr == 10) {\n\t\t\t\ttext = formatAuthors(String(row[ptr]), ptr);\n\t\t\t// Otherwise, simply get the text\n\t\t\t} else {\n\t\t\t\ttext = String(row[ptr]);\n\t\t\t}\n\t\t\t// Insert the new element to the row\n\t\t\tinsertCell(j, newRow, text);\n\t\t}\n\n\t\t// Initialize the variables covering the number of occurences of our query\n\t\t// and the locations where it was found\n\t\tmentioned = \"\";\n\t\tmentions = \"\";\n\t\t// Go through the occurrences array, sum up and sort the occurences\n\t\tfor (i = 0; i < occs.length; i++) {\n\t\t\tif (occs[i] > 0) {\n\t\t\t\t// extra check to add separator if required\n\t\t\t\tif (mentioned.length > 0) mentioned += \"; \";\n\t\t\t\t// Add the section on the string\n\t\t\t\tmentioned += cNames[i];\n\t\t\t\tif (mentions.length > 0) mentions += \"; \";\n\t\t\t\t// Add the # of occurrences on the string\n\t\t\t\tmentions += String(occs[i]);\n\t\t\t}\n\t\t}\n\t\t// Insert the occurence details on the row\n\t\tinsertCell(j, newRow, mentioned);\n\t\tj++\n\t\tinsertCell(j, newRow, mentions);\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
promise used for popups and resolutions via ohledger messages. | function setupNewPromise(){console.assert(!resolve,'oh-popup promise being set but already set when calling setupNewPromise(..)');return new Promise(function(rs,rj){resolve=rs;reject=rj;});}// make popup visible to be hidden with makePopupHidden | [
"function showpopup(msg_id, process_name, top_value) {\n GetFullDetailMessage(msg_id, process_name);\n}",
"function popup (message) {\n $('.pop').show().css('display', 'flex')\n $('.message').html(message)\n }",
"function popupPVAsWindow_onload(e)\n{\n\t// set flag\n\tasPopupWindow = true;\n\n\t// initialise fields\n\tgblPromptTitle = window.opener.gblPromptTitle;\n\tgblPromptFieldId = window.opener.gblPromptFieldId;\n\tgblPromptId = window.opener.gblPromptId;\n\tgblPromptDecode = window.opener.gblPromptDecode;\n\tgblPromptSecurity = window.opener.gblPromptSecurity;\n\tgblPromptFile = window.opener.gblPromptFile;\n\tgblPromptKeys = window.opener.gblPromptKeys;\n\tgblReturnFieldNames = window.opener.gblReturnFieldNames;\n\tgblReturnFieldLabels = window.opener.gblReturnFieldLabels;\n\tgblReturnFieldPositions = window.opener.gblReturnFieldPositions;\n\tgblReturnFieldLengths = window.opener.gblReturnFieldLengths;\n\tgblBackStart = window.opener.gblBackStart;\n\tgblBackLength = window.opener.gblBackLength;\n\tgblDataFields = window.opener.gblDataFields;\n\tgblDbFields = window.opener.gblDbFields;\n\tgblReturnFieldHdrPos = window.opener.gblReturnFieldHdrPos;\n\tgblMaxResults = window.opener.gblMaxResults;\n\t\n\tgetNewPVList(gblPromptTitle,gblPromptFieldId,gblPromptId,gblPromptDecode,gblPromptSecurity,gblPromptFile,gblPromptKeys,\n\t\t\t\t\t\tgblReturnFieldNames,gblReturnFieldLabels,gblReturnFieldPositions,gblReturnFieldLengths,\n\t\t\t\t\t\tgblBackStart,gblBackLength,\n\t\t\t\t\t\tgblDataFields,gblDbFields,gblReturnFieldHdrPos,\n\t\t\t\t\t\ttrue,gblMaxResults\n\t\t\t\t\t\t);\n\t\n}",
"handlePostPromptUI_() {\n if (!this.postPromptUI_) {\n return;\n }\n\n this.notificationUiManager_.onQueueEmpty(() => {\n this.vsync_.mutate(() => {\n this.postPromptUI_.show(false);\n // Will need to scheduleLayout for postPromptUI\n // upon request for using AMP component.\n });\n });\n\n this.notificationUiManager_.onQueueNotEmpty(() => {\n this.vsync_.mutate(() => {\n this.postPromptUI_.hide();\n });\n });\n }",
"function popupFindItem(ui) {\n\n v_global.event.type = ui.type;\n v_global.event.object = ui.object;\n v_global.event.row = ui.row;\n v_global.event.element = ui.element;\n\n switch (ui.element) {\n case \"emp_nm\":\n case \"manager1_nm\":\n case \"manager2_nm\":\n case \"manager3_nm\":\n case \"manager4_nm\": \n {\n var args = { type: \"PAGE\", page: \"DLG_EMPLOYEE\", title: \"사원 선택\"\n \t, width: 700, height: 450, locate: [\"center\", \"top\"], open: true\n };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"DLG_EMPLOYEE\",\n param: { ID: gw_com_api.v_Stream.msg_selectEmployee }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n case \"dept_nm\":\n {\n var args = { type: \"PAGE\", page: \"DLG_TEAM\", title: \"부서 선택\", width: 500, height: 450, open: true };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"DLG_TEAM\",\n param: { ID: gw_com_api.v_Stream.msg_selectTeam }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n case \"supp_nm\":\n {\n var args = { type: \"PAGE\", page: \"w_find_supplier\", title: \"협력사 선택\", width: 500, height: 450, open: true };\n if (gw_com_module.dialoguePrepare(args) == false) {\n var args = { page: \"w_find_supplier\",\n param: { ID: gw_com_api.v_Stream.msg_selectedSupplier }\n };\n gw_com_module.dialogueOpen(args);\n }\n } break;\n default: return;\n }\n}",
"getDialogMessage() {\n let message = \"<strong>\" + this.messageHeader + \"</strong></br>\";\n let innerMessage = isDefined(this.onMakeDialogMessage)\n ? this.onMakeDialogMessage()\n : \"\";\n if (innerMessage !== \"\") {\n message += innerMessage + \"</br>\";\n }\n if (this.pointEntities.entities.values.length > 0) {\n message +=\n \"<i>\" + i18next.t(\"models.userDrawing.clickToAddAnotherPoint\") + \"</i>\";\n }\n else {\n message +=\n \"<i>\" + i18next.t(\"models.userDrawing.clickToAddFirstPoint\") + \"</i>\";\n }\n // htmlToReactParser will fail if html doesn't have only one root element.\n return \"<div>\" + message + \"</div>\";\n }",
"function loadPopupInDialogBox(popupUrl, popupTitle){\r\n\r\n\t\tpopup_Div = document.getElementById(\"gauth-light-box\");\r\n\t \r\n\t\tpopup_Div.innerHTML = \"<a class='button' id='liteBoxClose' href='#' onclick='hideLightBox();return false;'><span>X</span></a>\";\r\n\t\t\r\n\t\tvar popup_source;\r\n\t\tvar host = getGAuthHost();\r\n\t\t\r\n\t\tpopup_source = host + popupUrl;\r\n\t \r\n consoleInfo(\"gauth-widget.js LoadPopupInDialogBox(): popup_source: \" + popup_source);\r\n\r\n\t if (document.getElementById('popup-iframe-id')){\r\n\t \tpurge(document.getElementById('popup-iframe-id'));\r\n\t \tpopup_Div.removeChild(document.getElementById('popup-iframe-id'));\r\n\t\t}\r\n\t\r\n\t //append iframe\r\n\t appendPopupIFrame(popup_Div, popup_source, popupTitle);\r\n\t}",
"function waitForWithholdMsgInjectorModal() {\n\tif ($('#'+modalID+'_response .markItUpEditor').length > 0) {\n\t\tconsole.log(\"GBAT: Form for \" + modalID + \" is ready, continuing...\");\n\t\thookWithholdMsgInjectorUI();\n\t\tn = 0;\n\t} else {\n\t\tif (n < 50) {\n\t\t\tsetTimeout(waitForWithholdMsgInjectorModal, 100);\n\t\t\tn++;\n\t\t} else {\n\t\t\tconsole.warn(\"GBAT: Form for \" + modalID + \" failed after waiting 5 seconds, aborting...\");\n\t\t\tn = 0;\n\t\t}\n\t}\n}",
"function lpDialog() {\n\tSpreadsheetApp.getUi().showModalDialog(\n\t\tgenerateDialog('Views/lpDialogPage.html'),\n\t\t'Select GMail Label to Pull Data From:'\n\t);\n}",
"function loadReceivedMessage() {\n return new Promise(function (resolve, reject) {\n socket.onmessage = function(e) {\n const returnedMessage = [protoFile.build(\"SignatureResponse\").decode(e.data), aggKey];\n\n resolve(returnedMessage);\n };\n\n socket.onerror = function (e) {\n reject(e);\n };\n });\n }",
"function createLaunchPopOver (options){\n \n if (typeof options === 'undefined' ||\n options === null){\n return;\n }\n \n var message = options['message'],\n trace = options['trace'],\n isConfirm = options['confirm-mode'] || false,\n okLabel = options['ok-label'] || 'Ok',\n okCallBack = options['ok-callback'],\n closeLabel = options['close-label'] || 'Close',\n closeCallBack = options['close-callback'],\n header = options['header'] || 'Results Analytics';\n \n var raSplash = document.querySelector('.sim-ui-advise-splash-background') || null;\n \n document.querySelector('.sim-ui-errpop-header').textContent = header;\n \n if(isConfirm)\n document.querySelector('#sim-ui-errpop-ok').classList.remove('sim-ui-errpop-noshow');\n else\n document.querySelector('#sim-ui-errpop-ok').classList.add('sim-ui-errpop-noshow');\n if (okLabel.length > 0)\n $simjq('#sim-ui-errpop-ok').text(okLabel);\n if (okLabel.length > 0)\n $simjq('#sim-ui-errpop-close').text(closeLabel);\n if (typeof message !== 'undefined' &&\n message !== null &&\n message.length > 0){\n $simjq('#sim-ui-errpop-msgcard').html(message);\n }\n else {\n if(typeof closeCallBack === 'function')\n closeCallBack();\n return;\n }\n if (typeof trace !== 'undefined' &&\n trace !== null &&\n trace.length > 0){\n $simjq('#sim-ui-errpop-tracecard').text(trace);\n }\n \n $simjq('#sim-ui-errpop-close,#sim-ui-errpop-ok').bind('click',\n function(){\n var id = $simjq(this).attr('id');\n if(id === 'sim-ui-errpop-ok'){\n if(typeof okCallBack === 'function')\n okCallBack();\n }\n if(id === 'sim-ui-errpop-close'){\n if(typeof closeCallBack === 'function')\n closeCallBack();\n }\n document.querySelector('.sim-ui-errpop-veil').classList.add('sim-ui-errpop-noshow');\n if(raSplash)\n raSplash.classList.remove('sim-ui-errpop-noshow');\n return;\n });\n\n if(raSplash)\n raSplash.classList.add('sim-ui-errpop-noshow');\n document.querySelector('.sim-ui-errpop-veil').classList.remove('sim-ui-errpop-noshow');\n}",
"function displayGetFreeRequests(callbackWhenLoaded){\n referralLink = \"https://www.synchronise.io/?referral=\"+Synchronise.User.current().id;\n var modal = new Modal();\n modal.title(\"Free requests\");\n var string = \"<div class='col-lg-6'><legend>Invite your friends <img src='/images/emojiFriend.png' style='height: 20px;'/></legend><h4 style='text-align:center'>10,000 requests</h4>Get <b>10,000</b> requests everytime a friends signup. There is no limit on the amount of friend you can invite.<div style='text-align:center; margin-top: 10px'><a class='btn btn-block btn-social shareOnMessenger' style='background: white; box-shadow: none; border: 1px solid darkgray'><span class='fa'><img src='/images/messenger.png' style='width: 30px; height: 30px'/></span> Send via Messenger</a><a href='https://twitter.com/intent/tweet?text=Stop reinventing the wheel! Reusable cloud components are there.&url=\" + referralLink + \"&hashtags=cloud,app&via=synchroniseio' class='btn btn-block btn-social btn-twitter' style='border: 0px; box-shadow: none;'><span class='fa fa-twitter'></span> Post a Tweet</a><input type='text' class='form-control' value='\" + referralLink + \"'></div></div>\";\n string+= \"<div class='col-lg-6'><legend>Add a payment method <img src='/images/emojiPaymentMethod.png' style='width: 25px'/></legend><h4 style='text-align:center'>20,000 requests</h4>Add a payment method and we'll give you an extra <b>20,000</b> requests and you <b>won't</b> be charged, ever, until you decide to switch to a payed plan. <br/><br/>Why? When you save a payment method you give us a strong sign that you believe in our platform and that means a lot to us. This is our way of saying thank you for your support. <div style='text-align:center; margin-top: 10px'><a class='btn btn-primary' href='/billing?tab=paymentMethods'>Add payment method</a></div></div>\";\n\n modal.content(string);\n modal.show();\n callbackWhenLoaded();\n }",
"function dynPopup(title,message,cbObject,cbAfterOpen,cbAfterClose)\n{\n//Display dynamically a popup dialogbox without having to insert template in all pages\n//Content of the dynamic popup can be text only or Full html - we reuse here the markup from current appibuddy Dialog (see dialogContent class in htmls)\n// with a new css class dynpopupContent derived from dialogContent see custom.css\n// main difference is that dynpopupContent is visible by default and display absolute instead of fixed\n\n\nvar content=[\n '<div class=\"dynpopupContent\">',\n ' <div class=\"dialogHeader\" >',\n ' <div>',\n ' <div class=\"dhLeft\" onclick= \"$(\\'#DynPopupPushNotif\\').popup(\\'close\\')\"><img src=\"' + app.rootFullPath + 'img/gr_close.png\" style=\"width:20px; height:20px\" /></div>',\n ' <div class=\"dhRight\"><img src=\"' + app.rootFullPath + 'img/gr_greenbuddy.png\" style=\"width:30px; height:40px\" /></div>',\n ' <div class=\"dhMid\"><span id =\"lblAlertTitle\">' + title + '</span></div>',\n ' </div>',\n ' </div>',\n ' <div class=\"dialogBody\" >',\n ' <div class=\"dbContent\">',\n ' <span id =\"lblAlertMsg\">' + message,\n ' </span>',\n ' </div>',\n ' <div class=\"dbButton center-wrapper\">',\n ' <div >',\n ' <div>',\n ' <a class=\"ui-btn\" style=\"background-color: #f2f2f2\" href=\"#\" data-role=\"button\" data-rel=\"back\"> OK</a>',\n ' </div>',\n ' </div>',\n ' </div>',\n ' </div>',\n '</div>'].join('\\n');\n\n if (!cbObject) //null cbObject passed then we could use directly the callback function \n cbObject = {\n popupafteropen: cbAfterOpen,\n popupafterclose: cbAfterClose\n };\n if ( ! (\"beforeposition\" in cbObject)) //providing default beforeposition callback\n {\n cbObject.beforeposition = function(event, ui)\n {\n var w = $(event.target).attr(\"width\");\n var h = $(event.target).attr(\"height\");\n debuglog('beforeposition w:' + w + ' h:' + h);\n $(event.target).attr(\"width\", \"280px\");\n };\n }\n $.dynamic_popup({\n content: content,\n popupId: \"DynPopupPushNotif\",\n 'data-transition': 'none', //was 'flow'\n 'data-position-to': 'window', //Centered on window can also be any other selector suche #divid\n 'dismissible' : false //modal dialog no click outside see http://api.jquerymobile.com/popup/#option-dismissible\n }).bind(cbObject);\n//Default dynamic+popup parameter\n// $.dynamic_popup({\n// content: '',\n// popupId: 'popup' + $activePage.attr('id'),\n// 'data-theme': 'a',\n// 'data-overlay-theme': 'none',\n// 'data-position-to': 'window',\n// 'data-rel': 'back',\n// 'data-dismissible': true,\n// 'data-transition': 'none',\n// 'data-arrow': false\n//});\n}",
"onDialogLoadedNotification() {\n this._refresh();\n }",
"function newServerPop() {\n\taddEvent2History(\"SideBar Server > NewServer\"); //add event to history\n\tvar h = $(window).height() - 100;\n\t$( \"#newserverPopup\" ).dialog({\n\t\tmodal: true,\n\t\tautoResize:true,\n\t\twidth: \"auto\",\n\t\tcloseOnEscape: false\n\t});\n\t$( \"#newserverPopup\" ).empty().load('pages/ConfigEditor/NewServer.html',function(){\n\t\t$('span.ui-dialog-title').text(\"ADD NEW SERVER\");\n\t\t$('.ui-dialog-title').css({'margin-left':'14px','margin-top':'7px','text-align':'center'});\n\t\tsetTimeout(function(){\n\t\t\tnewDevice('device');\t\n\t\t}, 1000);\n\t\t$(document).on(\"change\", \"#dropdowntypeServer\", function(){\n\t\t\tif($(\"#dropdowntypeServer option:selected\").val()==\"Manual\"){\n\t\t\t\t$(\"#serverMainDiv\").hide();\n\t\t\t\t$(\".manualServerClass\").show();\n\t\t\t}else{\n\t\t\t\tAutoDType=\"Server\";\n\t\t\t\t$(\"#serverMainDiv\").show();\n\t\t\t\t$(\".manualServerClass\").hide();\n\t\t\t\tserverValidation();\n\t\t\t\tchangeServerManuType();\n\t\t\t\tsetAutoDVariable();\n\t\t\t\t$('#addNewTestTDomainOpt').html(autoDDomainOptions);\n\t\t\t}\n\t\t});\n\t\t$(\".deviceInfoHideAndShow\").hide();\n\t\tgetMapPartnerPortInfo();\n\t\tnewDeviceAvailableDom();\n\t\tnewDevAttribute();\n\t\t$(\".ui-dialog\").position({\n\t\t my: \"top\",\n\t\t at: \"top\",\n\t\t of: window\n\t\t});\n\t});\n\n}",
"function showEmailWishListDialog() {\n var successMsg = _L('Your Wish List has been emailed.');\n var wishListName = (_.isFunction(getWishListNameFromPListArray) ? getWishListNameFromPListArray(cCProductLists.where({\n id : selectedWishListId\n })) : '');\n if (wishListName != '') {\n successMsg = String.format(_L('Your Wish List %s has been emailed.'), wishListName);\n }\n Alloy.Dialog.showCustomDialog({\n controllerPath : 'checkout/cart/emailCollectorDialog',\n cancelEvent : 'email_collector_dialog:dismiss',\n continueEvent : 'email_collector_dialog:continue',\n options : {\n emailData : {\n productListId : selectedWishListId,\n senderEmail : currentCustomer.getEmail(),\n senderName : currentCustomer.getFullName()\n },\n successNotifyMessage : successMsg,\n failNotifyMessage : _L('Your email failed to be sent. Please try again later.')\n }\n }).focus();\n\n}",
"function portTablePopUp(){\n\t$( \"#testToolPopUp\" ).dialog({\n\t\tmodal: true,\n\t\tautoResize:true,\n\t\twidth: \"auto\",\n\t\tmaxHeight: 500\n\t});\n\t$( \"#testToolPopUp\" ).load('pages/ConfigEditor/PortTestTool.html',function(){\n\t\t//deviceListPopupTable('deviceMenu','local');\n\t\t$('#PortTitle').text(HostName);\t\n\t\tsetTimeout(function(){\n\t\t\tPortTestToolTable();\n\t\t},100);\n\n\t\t$(\".ui-dialog\").position({\n\t\t my: \"center\",\n\t\t at: \"center\",\n\t\t of: window\n\t\t});\n\t});\n}",
"sendPublication(key, content){\n let commObj = this;\n return commObj.registerPromise\n .then(() => commObj.announcementExchangePromise)\n .then(() => sendMessage(commObj, commObj.announcementChannel, commObj.pubsubExchange, key, content))\n .catch(function(err){\n errLog(\"sendPublication function not available. \" + err);\n return Promise.reject(err);\n });;\n }",
"get mainPopupSet()\n {\n return this.chromeDocument.getElementById(\"mainPopupSet\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
["a", 1, 2, 3] 9. Oddities The oddities function takes an array as an argument and returns a new array containing every other element from the input array. The values in the returned array are the first (index 0), third, fifth, and so on, elements of the input array. The program below uses the array returned by oddities as part of a comparison. Can you explain the results of these comparisons? | function oddities(array) {
var oddElements = [];
var i;
for (i = 0; i < array.length; i += 2) {
oddElements.push(array[i]);
}
return oddElements;
} | [
"function odds(arr) {\n oddArr = [];\n each(arr, function(element) {\n if (element % 2 !==0) {\n oddArr.push(element);\n };\n });\n return oddArr;\n}",
"function evenIndexedOddNumbers(arr) {\n var output = [];\n each(arr, function(e, i) {\n if ((e % 2 !== 0) && (i % 2 === 0)) {\n output.push(e)\n }\n })\n return output;\n}",
"function odds(arr) {\n return filter(arr, function(elem) {\n // remember to RETURN the filter function\n return elem % 2 !== 0;\n });\n}",
"function arrayOfOdds (arr){\n var arr = [];\n for(var i = 0; i <= 50; i++){\n if(i % 2 !== 0){\n arr.push(i);\n }\n }\n return arr;\n}",
"function doubleOddNumbers(arr) {\n let oddNumsArr = arr.filter(function(num){\n return num%2 === 1\n })\n let oddNumsDoubledArr = oddNumsArr.map(function(num){\n return num * 2\n })\n return oddNumsDoubledArr\n}",
"function arrayodd() {\n var oddarray = [];\n for (var i = 1; i <= 50; i = i + 2) {\n oddarray.push(i);\n }\n return oddarray;\n}",
"function evenOddPartition(arr) {\n\tconst evens = []\n\tconst odds = []\n\tarr.filter(int => int % 2 === 0 ? evens.push(int) : odds.push(int))\n\treturn [evens, odds]\n}",
"function filterOddElements(arr) {\n\t// input/parameter --> array\n\t// EDGE CASE:\n\t//if the array has no odd elements\n\tif (arr.length === 0) {\n\t\t// return []\n\t\treturn [];\n\t}\n\t// create a result variable --> empty array\n\tconst oddArr = [];\n\t// iterate through the array\n\tfor (let i = 0; i < arr.length; i++) {\n\t\t// if element of array are not divisble by two --> odd\n\t\tif (arr[i] % 2 !== 0) {\n\t\t\t// push elements inside array\n\t\t\toddArr.push(arr[i]);\n\t\t}\n\t}\n\t//return the odd array\n\treturn oddArr;\n}",
"function processOddNums (arr) {\n // let finalIndex = arr.length -1;\n // let result = [];\n // for (let i = finalIndex; i > 0; i--) {\n // if (i % 2 !== 0) {\n // let num = 2 * arr[i];\n // result.push(num)\n // }\n // }\n // console.log(result.join(\" \"));\n\n console.log(\n (arr.filter((el, index) => index % 2 != 0))\n .map(e => e = 2 * e)\n .reverse()\n .join(\" \"))\n}",
"function pickIt(arr){\n var odd=[],even=[];\n \n for(let i = 0; i < arr.length; i++) {\n if(arr[i] % 2 === 0) even.push(arr[i])\n else odd.push(arr[i])\n }\n\n return [odd,even];\n}",
"function makeEven(array) {\n //tulislah code kalian disini!\n\n var result = [];\n if (array.length % 2 === 0) {\n for (i = 0; i < array.length; i++) {\n if (i === 1 || i === array.length-2) {\n continue;\n } else {\n result.push(array[i]);\n }\n }\n } else {\n for (i = 0; i < array.length; i++) {\n if (i === Math.round(array.length/2)-1) {\n continue;\n } else {\n result.push(array[i]);\n }\n }\n }\n return result;\n\n}",
"function isPerfectlyOdd(arr){\n if(arr.length === 0){\n return false;\n } \nfor(let i =1; i<arr.length; i +=2){\n console.log(i);\n if(arr[i] % 2 === 0){\n // console.log(arr[i]);\n return false;\n }\n\n}\nreturn true;\n }",
"function evensAndOdds(arr) {\n var evens = 0;\n var odds = 0;\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 === 0) {\n odds = 0;\n evens++;\n if (evens === 3) {\n console.log(\"Even more so!\");\n evens = 0;\n }\n } else {\n evens = 0;\n odds ++;\n if (odds === 3) {\n console.log(\"That's odd!\")\n odds = 0;\n }\n }\n }\n}",
"function iqTest(numbers) {\n const inputArray = numbers.split(' ');\n const even = [];\n const odd = []\n\n inputArray.map((elm) => elm % 2 == 0 ? even.push(elm) : odd.push(elm));\n\n return inputArray.indexOf(even.length > odd.length ? odd[0] : even[0]) + 1;\n}",
"function evenOddTransform(arr, n) {\n\tfor (let i = 0; i < n; i++) {\n\t\tfor (let j = 0; j < arr.length; j++) {\n\t\t\tif (arr[j] % 2 !== 0) {\n\t\t\t\tarr[j] += 2;\n\t\t\t} else if (arr[j] % 2 === 0) {\n\t\t\t\tarr[j] -= 2;\n\t\t\t}\n\t\t}\n\t}\n\treturn arr;\n}",
"function oddMultLength(arr) {\n const oddFilter = arr.filter(item => item % 2 !== 0);\n const newArr = oddFilter.map(item => item * oddFilter.length);\n console.log(newArr);\n}",
"function oddProduct(arr) {\n\tlet a = 1;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tif (arr[i] % 2 === 1) {\n\t\t\ta *= arr[i];\n\t\t}\n\t}\n\treturn a;\n}",
"function isPerfectlyOdd(arr) {\n let sum = 0;\n for (let i = 1; i < arr.length; i += 2) {\n sum += arr[i];\n\n }\n if (sum % 2 !== 0) {\n return true;\n }\n return false;\n\n}",
"function oddeven(arr) {\n\treturn arr.filter(x => x % 2 === 0).length * 2 < arr.length;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PLANS Load spatialized plan into the scene. | function load3DPlan(obj) {
if(plans.getByName(obj.info.content)) return;
var plan = new DV3D.Plan('data/' + obj.file.path + obj.file.content, 'data/' + obj.info.materialMapPath + obj.info.materialMap, obj.info.scale);
plan.onComplete = function () {
animate();
};
scene.add(plan);
plan.name = obj.info.content;
plan.userData.name = obj.info.materialName;
plan.userData.source = obj.source;
plan.userData.type = 'plan';
var entry = new DV3D.PlanEntry(plan);
plan.entry = entry;
plans.add(entry);
console.log('Plan', plan);
} | [
"function loadTasksMatrix() {\n loadAllTasks();\n loadMatrixArea();\n assignTaskToBox();\n}",
"function loadPlanet ( planetData, scene, progressCallback, resolve, reject ) {\n\n texLoader.load( planetData.path, function ( texture ) {\n\n console.log('in texLoader, typeof planet.geometry:' + typeof planetData.geometry);\n\n if ( isString( planetData.geometry ) ) { // path to mesh file\n\n modLoader.load( planetData.geometry, function ( obj ) {\n\n planetData.geometry = obj.children[ 0 ].geometry;\n\n planetData.material.map = texture;\n\n //planetData.geometry.scale( 10, 10, 10 ); // might need later\n\n planetData.geometry.center(); // center model within bounding box\n\n planetData.mesh = new THREE.Mesh( planetData.geometry, planetData.material );\n\n planetData.mesh.position.set( 0, 0, 0 );\n\n planetData.geometry.applyMatrix( planetData.translation );\n\n planetData.group.add( planetData.mesh );\n\n planetData.mesh.name = planetData.name;\n\n // Planet mesh stored for picking (can't pick Rings, Stars, Galaxy)\n\n gazeObjects.push( planetData.mesh );\n\n // create a visible ring for the planetary orbit\n\n planetData.orbit = createRing( 50, 50, planetData.distance - 0.25, planetData.distance + 0.25,\n\n new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true, opacity: 0.2 } ),\n\n new THREE.Vector3( 0, 0, 0 ), // position\n\n new THREE.Vector3( Math.PI / 2, 0, 0 ) // rotation\n\n );\n\n scene.add( planetData.orbit );\n\n // Resolve the Promise if our texture loaded successfully\n\n if( texture instanceof THREE.Texture) {\n\n resolve( planetData );\n\n } else {\n\n reject( planetData );\n\n }\n\n } ); // End of mesh loaded by program\n\n } else { // Use THREE.Sphere primitive\n\n planetData.geometry.applyMatrix( planetData.translation );\n\n planetData.material.map = texture;\n\n planetData.mesh = new THREE.Mesh( planetData.geometry, planetData.material );\n\n planetData.group.add( planetData.mesh );\n\n planetData.mesh.name = planetData.name;\n\n // Planet mesh stored for picking (can't pick Rings, Stars, Galaxy)\n\n gazeObjects.push( planetData.mesh );\n\n if( texture instanceof THREE.Texture ) {\n\n resolve( planetData );\n\n } else {\n\n reject( planetData );\n }\n\n } // End of THREE.Sphere load\n\n\n // compute the number of loads\n\n numLoads++;\n\n // progressCallback used bind() to keep global scope inside this object\n\n console.log( 'numloads:' + numLoads + ' totalLoads:' + totalLoads);\n\n if ( progressCallback ) {\n\n var loaded = parseInt( 100 * numLoads / totalLoads );\n\n progressCallback( loaded / 2, planetData.name, 50 );\n\n }\n\n },\n\n function ( xhr ) { // Report loading progress\n\n console.log(planetData.name + ' ' + parseInt(xhr.loaded / xhr.total * 100) + '% loaded');\n\n if ( progressCallback ) {\n\n var loaded = parseInt( 100 * numLoads / totalLoads );\n\n progressCallback( loaded / 2, planetData.name, 50 );\n\n }\n },\n\n function ( xhr ) { // Report loading error.\n\n reject( new Error ('domui.loadPlanet() error:' + xhr + ' An error occurred loading while loading' + planetData.path));\n\n }\n\n ); // end of texLoader\n\n }",
"function loadProject() {\n\t\t/*\n\t\t//use temp project stubs here \n\t\tvar project = project1;\n\t\tfor (var i = 0; i <= project.tasks.length - 1; i++) { \n\t\t\taddTableRow(project.tasks[i]);\n\t\t\tgenerateTaskDetailsModal(project.tasks[i]);\t\n\t\t};\n\t\t*/\n\t\tgenerateLeftTable();\n\t\tgenerateRightDayTable();\n\t\tgenerateRightWeekTable();\n\t\tgenerateRightMonthTable();\n\t\tgenerateRightQuarterTable();\n\t}",
"function createPlanCircle() {\r\n planCircle = loadCircle(\"#total-plan-completion\");\r\n}",
"function load_next_planet() {\n gamer.planet.type = gamer.next.type;\n gamer.planet.assigned = false;\n gamer.planet.removed = false;\n gamer.planet.checked = false;\n gamer.planet.x = gamer.x;\n gamer.planet.y = gamer.y;\n\n var sun = random(1,100);\n if(sun <= 3) {\n gamer.next.type = planet_types.sun;\n } else if(gamer.available_planets <= 5) {\n var types = [];\n for(var j = 0; j < map.rows; j++) {\n for(var i = 0; i < map.columns; i++) {\n var planet = map.planets[i][j];\n if(planet.type >= planet_types.mercury\n && planet.type <= planet_types.saturn\n && !planet.removed\n && !planet.assigned) {\n types.push(planet.type);\n }\n }\n }\n gamer.next.type = types[Math.floor(Math.random() * types.length)];\n } else {\n gamer.next.type = random(1,6);\n }\n }",
"function loadDashboard() {\n loadReservations();\n loadTables();\n }",
"function load_planets_image() {\n planets_image.source = new Image();\n planets_image.source.src = 'assets/img/planets.png';\n planets_image.source.onload = function() {\n planets_image.loaded = true;\n };\n }",
"function startPlan(plan, args) {\n var base = plan ? plan.base || basePlan : basePlan;\n plan = plan || base;\n var timeout = plan.timeout || base.timeout;\n if (timeout) {\n delete args.timeoutError;\n args.timeout = setTimeout(function () {\n var error = new TimeoutError('Time exceeded ' + timeout + 'ms.');\n finishPlan(plan, [error], null, args);\n args.timeoutError = error;\n }, timeout);\n }\n}",
"function loadCameraParaSingle(dir, filename, index, mode, len, visible) { \n\tvar poses;\n\tvar poseName = dir + filename + '_' + mode + '.txt';\n\tjQuery.get(poseName, function(data) \n\t{\n\t\tvar d = data; \n\t\td = d.replace(/\\s+/g,' ').trim(); \n\t\tposes = d.split(\" \");\n\n\t\tvar matrixInitial = new THREE.Matrix4();\n\t\t\n\t\tfor (var c in poses) {\n\t\t\tif (c < 16) {\n\t\t\t\tmatrixInitial.elements[c] = poses[c];\n\t\t\t}\n\t\t\telse break;\n\t\t}\n\n\t\t// also parse the plane paras\n\t\t// Ax + By + Cz + 1 = 0\n\t\tvar planePara = new THREE.Vector3(parseFloat(poses[16]), parseFloat(poses[17]), \n\t\t\tparseFloat(poses[18]));\n\n\n\t\t// take transpose beause of data streaming order\n\t\tmatrixInitial.transpose();\n\t\tvar m = matrixInitial;\n\t\tvar g = sequence.groundTrans.clone();\n\t\tg.multiply(m);\n\n\t\tif (mode == 0) {\n\t\t\tcamPoses.poseP[filename] = g;\n\n\t\t\tvar vituralCam = setupVirtualCameras(g);\n\t\t\t\t\n\t\t\tvituralCam.vCamera.name = 'p'+filename;\n\t\t\tvituralCam.wireFrame.name = 'p' + filename;\n\n\t\t\tif (typeof visible == 'undefined') {\n\t\t\t\tvituralCam.vCamera.visible = controlHandler.showCam;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tvituralCam.vCamera.visible = visible;\n\t\t\t}\n\t\t\tvituralCam.wireFrame.visible = false;\n\n\t\t\tcamGroup.wireFrame.push(vituralCam.wireFrame);\n\t\t\tcamGroup.vCamera.push(vituralCam.vCamera);\n\n\t\t\tscene3D.add(vituralCam.wireFrame);\n\t\t\tscene3D.add(vituralCam.vCamera);\n\n\n\t\t\t// also load the ground info\n\t\t\tcamPoses.poseGround[filename] = planePara;\n\n\t\t\t/*********For debugging purpose*************/\n\t\t\tvar region = new THREE.Mesh(new THREE.CircleGeometry( 5, 32 ), \n\t\t\t\tnew THREE.MeshBasicMaterial( {color: 0xffff00, transparent: true, opacity: 0.5, \n\t\t\t\t\t\t\t\t\t\t\t side: THREE.DoubleSide}));\n\t\t\t// position\n\t\t\tvar intersection = planeInterset(planePara, vituralCam.vCamera.position, planePara);\n\t\t\tregion.position.set(intersection.x, \n\t\t\t\t\t\t\t\tintersection.y, \n\t\t\t\t\t\t\t\tintersection.z);\n\t\t\tregion.visible = false;\n\t\t\tregion.name = 'p'+filename;\n\t\t\t// rotation\n\t\t\tregion.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), \n\t\t\t\t\t\t\t\t\t\t\t\tnew THREE.Vector3(planePara.x/planePara.length(), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t planePara.y/planePara.length(), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t planePara.z/planePara.length()));\n\t\t\tcamGroup.localPlane.push(region);\n\t\t\tscene3D.add(region);\t\n\t\t\t/*********For debugging purpose**************/\n\n\t\t\tnumPoses ++;\n\n\t\t\t// check if load finished\n\t\t\tif (numPoses == len) {\n\t\t\t\t// if so, compute the height for ground and sky\n\t\t\t\tcomputeRange();\n\t\t\t}\n\n\t\t}\n\n\t\telse if (mode == 2) {\n\t\t\tcamPoses.poseF1[filename] = g;\n\n\t\t\t// configure sideview cameras\n\t\t\tvar sideCam = setupSideviewCameras(g, 'left');\n\t\t\tsideCam.vCamera.name = 'l'+filename;\n\t\t\tsideCam.wireFrame.name = 'l'+filename;\n\n\t\t\tif (typeof visible == 'undefined') {\n\t\t\t\tsideCam.vCamera.visible = controlHandler.showCam;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsideCam.vCamera.visible = visible;\n\t\t\t}\n\t\t\tsideCam.wireFrame.visible = false;\n\n\t\t\tcamGroup.wireFrame.push(sideCam.wireFrame);\n\t\t\tcamGroup.vCamera.push(sideCam.vCamera);\n\t\t\t\n\t\t\tscene3D.add(sideCam.wireFrame);\n\t\t\tscene3D.add(sideCam.vCamera);\n\t\t}\n\n\t\telse if (mode == 3) {\n\n\t\t\tcamPoses.poseF2[filename] = g;\n\n\t\t\t// configure sideview cameras\n\t\t\tvar sideCam = setupSideviewCameras(g, 'right');\n\t\t\tsideCam.vCamera.name = 'r'+filename;\n\t\t\tsideCam.wireFrame.name = 'r'+filename;\n\n\t\t\tif (typeof visible == 'undefined') {\n\t\t\t\tsideCam.vCamera.visible = controlHandler.showCam;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsideCam.vCamera.visible = visible;\n\t\t\t}\n\t\t\tsideCam.wireFrame.visible = false;\n\n\t\t\tcamGroup.wireFrame.push(sideCam.wireFrame);\n\t\t\tcamGroup.vCamera.push(sideCam.vCamera);\n\t\t\t\n\t\t\tscene3D.add(sideCam.wireFrame);\n\t\t\tscene3D.add(sideCam.vCamera);\n\t\t}\n\n\t\tif (index == 0) {\n\t\t\t\n\t\t\tif (mode == 0) {\n\n\t\t\t\tcurrPersCam = vituralCam.wireFrame;\n\t\t\t\tcurrPersCam.visible = true;\n\n\t\t\t\tcameraProjection.cameraP = new THREE.PerspectiveCamera( FOV, width_p/width_h, NEAR, FAR);\n\t\t\t\tconfigCameraProj(g, cameraProjection.cameraP, frame.frame_perspective, INTRINSIC.f);\n\n\t\t\t\tobjController.controlCube2D = new THREE.TransformControls( cameraProjection.cameraP, renderer.domElement, views['view2D'], false, enableAdvanceControl);\n\t\t\t\tobjController.controlCube2D.addEventListener( 'change', render );\n\t\t\t\tscene2D.add( objController.controlCube2D );\n\n\t\t\t\tobjController.controlCube2D.enabled = false;\n\t\t\t\tobjController.controlCube2D.setSize(objController.controlCube2D.size*30);\t\n\n\t\t\t\t// place the axis to the origin\n\t\t\t\torigin = new THREE.Vector3(g.elements[12], g.elements[13], g.elements[14]);\n\t\t\t\t//axisHelper.position.copy(origin); \n\n\t\t\t\t// we also need to estimate the camera angle of the first perspective camera\n\t\t\t\tsceneRotation.x = g.elements[8];\n\t\t\t\tsceneRotation.y = g.elements[9];\n\t\t\t\tsceneRotation.z = g.elements[10];\t\t\n\t\t\t}\n\n\t\t\telse if (mode == 2) {\n\t\t\t\tcameraProjection.cameraF1 = new THREE.PerspectiveCamera( FOV, width_fishseye/width_h, NEAR, FAR);\n\t\t\t\tconfigCameraProj(g, cameraProjection.cameraF1, frame.frame_fisheye, INTRINSIC.fVirtual);\n\n\t\t\t\t// setup controller\n\t\t\t\tobjController.controlCubeFish1= new THREE.TransformControls( cameraProjection.cameraF1, renderer.domElement, views['view2D_left'], false, enableAdvanceControl);\n\t\t\t\tobjController.controlCubeFish1.addEventListener( 'change', render );\n\t\t\t\tscene2D.add( objController.controlCubeFish1 );\n\n\t\t\t\tobjController.controlCubeFish1.enabled = false;\n\t\t\t\tobjController.controlCubeFish1.setSize(objController.controlCubeFish1.size*30);\t\n\n\t\t\t\tobjController.controlCubeFish1.setHandlerSize (300/INTRINSIC.fVirtual);\n\t\t\t}\n\n\t\t\telse if (mode == 3) {\n\t\t\t\tcameraProjection.cameraF2 = new THREE.PerspectiveCamera( FOV, width_fishseye/width_h, NEAR, FAR);\n\t\t\t\tconfigCameraProj(g, cameraProjection.cameraF2, frame.frame_fisheye, INTRINSIC.fVirtual);\n\t\t\t\tsideCam.wireFrame.visible = true;\n\n\t\t\t\tcamSide = 'right';\n\t\t\t\tcurrSideCam = sideCam.wireFrame;\n\n\t\t\t\t// setup controller\n\t\t\t\tobjController.controlCubeFish2 = new THREE.TransformControls( cameraProjection.cameraF2, renderer.domElement, views['view2D_left'], false, enableAdvanceControl);\n\t\t\t\tobjController.controlCubeFish2.addEventListener( 'change', render );\n\t\t\t\tscene2D.add( objController.controlCubeFish2 );\n\n\t\t\t\tobjController.controlCubeFish2.enabled = false;\n\t\t\t\tobjController.controlCubeFish2.setSize(objController.controlCubeFish2.size*30);\t\n\n\t\t\t\tobjController.controlCubeFish2.setHandlerSize (300/INTRINSIC.fVirtual);\n\t\t\t}\n\t\t}\n\t})\n}",
"executePlan(...data) {\n return new Promise((resolve, reject) => {\n // If we don't have a plan yet, calling this function is premature\n if (!this.plan) throw new Error(NO_PLAN);\n\n const inputPlaceholders = this.plan.getInputPlaceholders();\n const argsLength = inputPlaceholders.length,\n opsLength = this.plan.operations.length;\n\n // If the number of arguments supplied does not match the number of arguments required...\n if (data.length !== argsLength)\n throw new Error(NOT_ENOUGH_ARGS(data.length, argsLength));\n\n // If we have already completed the plan, there's no need to execute\n if (this.lastUnfinishedOperation === opsLength)\n throw new Error(PLAN_ALREADY_COMPLETED(this.plan.name, this.plan.id));\n\n // For each argument supplied, store them in this.objects\n data.forEach((datum, i) => {\n this.objects[inputPlaceholders[i].id] = datum;\n });\n\n // Add state tensors to objects\n if (this.plan.state && this.plan.state.tensors) {\n this.plan.state.tensors.forEach((tensor, i) => {\n this.objects[tensor.id] = tensor;\n });\n }\n\n let finished = true;\n\n // Execute the plan\n for (let i = this.lastUnfinishedOperation; i < opsLength; i++) {\n // The current operation\n const currentOp = this.plan.operations[i];\n\n // The result of the current operation\n const result = currentOp.execute(this.objects, this.logger);\n\n // Place the result of the current operation into this.objects at the 0th item in returnIds\n if (result) {\n if (currentOp.returnIds.length > 0) {\n this.objects[currentOp.returnIds[0]] = result;\n } else if (currentOp.returnPlaceholders.length > 0) {\n this.objects[currentOp.returnPlaceholders[0].id] = result;\n }\n } else {\n finished = false;\n this.lastUnfinishedOperation = i;\n\n break;\n }\n }\n\n if (finished) {\n // Set the lastUnfinishedOperation as the number of operations (meaning, we've already executed the plan successfully)\n this.lastUnfinishedOperation = opsLength;\n\n // Resolve all of the requested resultId's as specific by the plan\n const resolvedResultingTensors = [];\n const outputPlaceholders = this.plan.getOutputPlaceholders();\n outputPlaceholders.forEach(placeholder => {\n resolvedResultingTensors.push({\n id: placeholder.id,\n value: this.objects[placeholder.id]\n });\n });\n\n // Return them to the worker\n resolve(resolvedResultingTensors);\n } else {\n // If the plan wasn't finished, notify the worker that they may try again once they have the appropriate information\n reject(\n 'There is not enough information to execute this plan, but we have saved your progress!'\n );\n }\n });\n }",
"function savePreSetPlans()\r\n{\r\nlocalStorage.setItem(\"planUP\"+1,JSON.stringify(planUP)); \r\nlocalStorage.setItem(\"planUM\"+1,JSON.stringify(planUM)); \r\nlocalStorage.setItem(\"planUR\"+1,JSON.stringify(planUR)); \r\nlocalStorage.setItem(\"planHP\"+1,JSON.stringify(planHP)); \r\nlocalStorage.setItem(\"planHM\"+1,JSON.stringify(planHM)); \r\nlocalStorage.setItem(\"planHR\"+1,JSON.stringify(planHR)); \r\nlocalStorage.setItem(\"planOP\"+1,JSON.stringify(planOP)); \r\nlocalStorage.setItem(\"planOM\"+1,JSON.stringify(planOM)); \r\nlocalStorage.setItem(\"planOR\"+1,JSON.stringify(planOR)); \r\nlocalStorage.setItem(\"planBP\"+1,JSON.stringify(planBP)); \r\nlocalStorage.setItem(\"planBM\"+1,JSON.stringify(planBM)); \r\nlocalStorage.setItem(\"planBR\"+1,JSON.stringify(planBR)); \r\n}",
"createPlan() {\n // reset plan\n this._plan.length = 0;\n // reset update plan\n this._updatePlan.length = 0;\n // recalculate total duration time\n this._calcTotalTime();\n\n // frame size (60fps)\n const step = 16;\n\n const { delay, duration } = this._props;\n // current time\n let time = delay;\n\n let periodStart;\n\n while (time <= this._totalTime) {\n const prevPeriod = this._getPeriod(time - step);\n const period = this._getPeriod(time);\n const nextPeriod = this._getPeriod(time + step);\n const prevFrame = this._plan[this._plan.length-1];\n\n let frameSnapshot = 0;\n\n if (period === 'delay') {\n this._plan.push(frameSnapshot);\n time += step;\n periodStart = undefined;\n continue;\n }\n\n // catch the start of `update` period\n if (periodStart === undefined) {\n this._o.isIt && console.log('yep', time, period);\n periodStart = time;\n }\n // calculate current progress\n this._updatePlan.push((time - periodStart) / duration);\n\n // onUpdate\n frameSnapshot = frameSnapshot | (1 << 3);\n\n const isPrevFrame = prevFrame !== undefined;\n\n if (!isPrevFrame) {\n // onStart\n frameSnapshot = frameSnapshot | (1 << 1);\n }\n\n const isPrevDelay = prevPeriod === 'delay';\n // onRepeatStart\n if (!isPrevFrame || isPrevDelay || prevPeriod === period - 1) {\n frameSnapshot = frameSnapshot | (1 << 2);\n }\n\n // onRepeatComplete\n if (nextPeriod === 'delay' || nextPeriod === period + 1) {\n frameSnapshot = frameSnapshot | (1 << 4);\n }\n\n this._plan.push(frameSnapshot);\n\n time += step;\n }\n\n // onComplete\n const lastIndex = this._plan.length - 1;\n this._plan[lastIndex] = this._plan[lastIndex] | (1 << 5);\n if (this._props.isReverse) {\n this.reverse();\n }\n\n this._o.isIt && console.log(this._plan.length);\n\n // the first one should be always 0\n // this._updatePlan[0] = 0;\n // the last one should be always 1\n // this._updatePlan[this._updatePlan.length-1] = 1;\n\n return this._plan;\n }",
"function load() {\n _data_id = m_data.load(FIRST_SCENE, load_cb, preloader_cb);\n}",
"function loadActivities() {\n clearCanvas();\n nodesArray = [];\n loadedStory.activities.forEach((a) => {\n addActivityNode(a);\n });\n \n //After we created all nodes we create all outputs and make the connections\n loadedStory.activities.forEach((a, index) => {\n setNodeOutputs(a, nodesArray[index]);\n });\n}",
"function simulatePlan(){\n simulation();\n}",
"static GetPlanes(transform) {\n const frustumPlanes = [];\n for (let index = 0; index < 6; index++) {\n frustumPlanes.push(new Plane_1.Plane(0.0, 0.0, 0.0, 0.0));\n }\n Frustum.GetPlanesToRef(transform, frustumPlanes);\n return frustumPlanes;\n }",
"LoadScene()\n {\n\n if ( this.__loaded )\n {\n console.error( \"Unable to load scene, already loaded \" )\n return;\n }\n\n this.LocalSceneObjects.forEach( element => {\n\n let _constructor = element[0];\n let _serializedCallback = element[1];\n \n let obj = this.Create( _constructor, GameObject.COMPONENT_INIT_MODES.NO_SYNC );\n _serializedCallback( obj );\n\n } );\n\n this.__loaded = true;\n }",
"async load(callback) {\n this.loadingStart(this.name);\n\n var promises = [];\n if ( this.file ) {\n var scenePromise = VRSPACEUI.assetLoader.loadAsset( this.baseUrl+this.file,\n // onSuccess:\n (url, container, info ) => {\n this.sceneMeshes = container.meshes;\n this.container = container;\n \n // Adds all elements to the scene\n var mesh = container.createRootMesh();\n mesh.name = this.name;\n container.addAllToScene();\n \n this.loaded( this.file, mesh );\n \n },\n // onError:\n exception => this.loadFailed( exception ),\n // onProgress:\n evt => this.loadProgress(evt, this.name)\n );\n promises.push(scenePromise);\n }\n \n if ( this.objectsFile ) {\n var response = await fetch(this.baseUrl+this.objectsFile);\n var json = response.json();\n this.worldObjects = JSON.parse(json);\n }\n \n if ( this.worldObjects ) {\n this.sceneMeshes = [];\n for ( var url in this.worldObjects ) {\n var instances = this.worldObjects[url].instances;\n if ( !url.startsWith(\"/\") ) {\n // relative url, make it relative to world script path\n url = this.baseUrl+url;\n }\n instances.forEach( (instance) => {\n var objPromise = VRSPACEUI.assetLoader.loadAsset(url,\n // callback \n (loadedUrl, container,info,instances)=>{\n if ( instances ) {\n var mesh = obj.instantiatedEntries.rootNodes[0];\n // CHECKME: untested\n var children = mesh.getChildMeshes();\n this.sceneMeshes.push(...children);\n } else {\n // Adds all elements to the scene\n var mesh = container.createRootMesh();\n var pos = loadedUrl.lastIndexOf('/');\n if ( pos >= 0 ) {\n mesh.name = loadedUrl.substring(pos+1);\n }\n container.addAllToScene();\n this.sceneMeshes.push(...container.meshes);\n }\n if ( instance.position ) {\n mesh.position = new BABYLON.Vector3(instance.position.x, instance.position.y, instance.position.z);\n }\n if ( instance.rotation ) {\n mesh.rotation = new BABYLON.Vector3(instance.rotation.x, instance.rotation.y, instance.rotation.z);\n }\n if ( instance.scale ) {\n mesh.scaling = new BABYLON.Vector3(instance.scale.x, instance.scale.y, instance.scale.z);\n }\n this.loaded( loadedUrl, mesh );\n },\n // onError:\n exception => this.loadFailed( exception ),\n // onProgress:\n evt => this.loadProgress(evt, url)\n );\n promises.push(objPromise);\n });\n }\n }\n \n Promise.all(promises).then(() => {\n VRSPACEUI.log(\"World loaded\");\n this.loadingStop(this.name);\n this.collisions(this.collisionsEnabled);\n if ( callback ) {\n callback(this);\n }\n });\n \n return this;\n }",
"function updateLineplans() {\n $.ajax(\"/lineplans\")\n .done(function (data) {\n line_routes = data;\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
init grid size horizontal get height param | function initSizeParamsHor(){
var arrThumbs = g_objInner.children(".ug-thumb-wrapper");
var firstThumb = jQuery(arrThumbs[0]);
var thumbsRealHeight = firstThumb.outerHeight();
//set grid size
var gridWidth = g_temp.gridWidth;
var gridHeight = g_options.grid_num_rows * thumbsRealHeight + (g_options.grid_num_rows-1) * g_options.grid_space_between_rows;
g_temp.gridHeight = gridHeight;
g_functions.setElementSize(g_objGrid, gridWidth, gridHeight);
//set inner size (as grid size, will be corrected after placing thumbs
g_functions.setElementSize(g_objInner, gridWidth, gridHeight);
//set initial inner size params
g_temp.innerWidth = gridWidth;
g_temp.innerHeight = gridHeight;
} | [
"function makeGrid() {\n\n\tcreateGrid($('#inputHeight').val(),$('#inputWidth').val());\n}",
"gridCellSize() {\n return (gridCellSizePercent * canvasWidth) / 100;\n }",
"function makeGrid() {\n\tlet cellSize = 0;\n\tif ($(window).width() < $(window).height()) {\n\t\tcellSize = $(window).width()*0.8*(1/(level + 0.5));\n\t} else {\n\t\tcellSize = $(window).height()*0.8*(1/(level + 0.5));\n\t}\n\tmakeRows(cellSize);\n\tfillRows(cellSize);\n}",
"get gridResolutionY() {}",
"function newGrid (newSize) {\n $('.row').remove();\n createGrid(newSize);\n // $('.column').outerHeight(oldSize*oldPixel/newSize);\n // $('.column').outerWidth(oldSize*oldPixel/newSize);\n}",
"function initGrid(canvas, color, size) {\n\t// calculate where the grid lines should be placed\n\tcomputeLineLocations(size, canvas.width, Columns);\n\tcomputeLineLocations(size, canvas.height, Rows);\n\t\n\t// draw the lines on the canvas\n\tdrawLines(canvas, Columns, color, \"vertical\");\n\tdrawLines(canvas, Rows, color, \"horizontal\");\n}",
"configure(width, height)\n {\n // use the width passed by the user\n // but check the height, each team should have at least 200 px of space\n this.width = width\n let len = Object.keys(this.teams).length;\n if (len * 200 > height)\n {\n this.height = len * 200 + 100;\n }\n else\n {\n this.height = height;\n }\n\n this.app.renderer.autoResize = true;\n this.app.renderer.resize(this.width, this.height);\n }",
"function createGrid() {\n for (let i = 0; i < width * height; i++) {\n const cell = document.createElement('div')\n grid.appendChild(cell)\n cells.push(cell)\n }\n for (let i = 2; i < 22; i++) {\n rowArray.push(cells.slice(i * 10, ((i * 10) + 10)))\n }\n for (let i = 0; i < 20; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('top')\n }\n for (let i = 10; i < 20; i++) {\n cells[i].classList.remove('top')\n cells[i].classList.add('topline')\n }\n for (let i = 220; i < 230; i++) {\n cells[i].classList.remove('div')\n cells[i].classList.add('bottom')\n }\n }",
"function createGrid(x) {\n\tfor (var rows=0; rows<x; rows++) {\n\t\tfor (var columns=0; columns<x; columns++) {\n\t\t\t$(\"#container\").append(\"<div class='grid'></div>\");\n\t\t};\n\t};\n\t$(\".grid\").width(960/x);\n\t$(\".grid\").height(960/x);\n}",
"function changeGridSize() {\n value = sizeSlider.value;\n container.innerHTML = \"\";\n makeRows(value, value);\n displayGridSlider.innerHTML = value.toString() + \"x\" + value.toString();\n}",
"set requestedHeight(value) {}",
"function changeGridSize(){\r\n let cellsToDelete = Array.prototype.slice.apply(document.querySelectorAll('.cell'))\r\n cellsToDelete.forEach((cell) => {gridContainer.removeChild(cell)})\r\n\r\n let gridValue = gridSize.value\r\n console.log(gridValue,\"GV\")\r\n createGrid(gridValue)\r\n}",
"calculateLayoutSizes() {\n const gridItemsRenderData = this.grid.getItemsRenderData();\n this.layoutSizes =\n Object.keys(gridItemsRenderData)\n .reduce((acc, cur) => (Object.assign(Object.assign({}, acc), { [cur]: [gridItemsRenderData[cur].width, gridItemsRenderData[cur].height] })), {});\n }",
"function setDefaultGrid() {\n setGridSize(16);\n fillGrid(16);\n}",
"function setValueGrid(startRow, startCol, w, h, val) {\n for (var i = startRow; i < startRow + h; i++) {\n for (var j = startCol; j < startCol + w; j++) {\n grid[i][j] = val;\n }\n }\n}",
"constructor(row, col, size) {\n this.size = size\n this.row = row\n this.col = col\n }",
"function layoutGrid(gridContainer, columns, rows){\n\tgridContainer.style.display = 'grid';\n\t//gridContainer.style.gridTemplateColumns = `repeat(${columns},${100/columns}%)`;\n\t//gridContainer.style.gridTemplateRows = `repeat(${rows}, ${100/rows}%)`;\n\tgridContainer.style.gridTemplateColumns = `repeat(${columns}, 1fr)`;\n\tgridContainer.style.gridTemplateRows = `repeat(${rows}, 1fr)`;\n\treturn;\n}",
"function create8X8 () {\n for (i=0;i<64;i++){\n var newSquare = \"<li id=\"+parseInt(i)+\"></li>\";\n $(\".grid\").append(newSquare);\n }\n $tileArray = $(\"li\");\n row_length = Math.sqrt($tileArray.length); \n $tileArray.css(\"height\", \"10%\").css(\"width\", \"10%\");\n }",
"function setTileSizes() {\n $tileList = mainDiv.find(selector);\n for (var i = 0; i < $tileList.length; i++) {\n var size = $tileList.eq(i).attr(\"data-size\");\n var wdt = tileRatio * baseWH * tileSize[size].w-margin;\n var hgh = baseWH * tileSize[size].h-margin;\n $tileList.eq(i).css({\"width\": wdt, \"height\": hgh}).addClass('w' + tileSize[size].w + ' ' + 'h' + tileSize[size].h);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the foldable region containing the given line, if one exists | function foldableContainer(view, lineBlock) {
// Look backwards through line blocks until we find a foldable region that
// intersects with the line
for (let line = lineBlock; ; ) {
let foldableRegion = foldable(view.state, line.from, line.to)
if (foldableRegion && foldableRegion.to > lineBlock.from)
return foldableRegion
if (!line.from) return null
line = view.lineBlockAt(line.from - 1)
}
} | [
"function _foldLine(cm, line) {\n var marks = cm.findMarksAt(CodeMirror.Pos(line + 1, 0)), i;\n if (marks && marks.some(function (m) { return m.__isFold; })) {\n return;\n } else {\n foldFunc(cm, line);\n }\n }",
"function foldable(state, lineStart, lineEnd) {\n for (let service of state.facet(foldService)) {\n let result = service(state, lineStart, lineEnd)\n if (result) return result\n }\n return syntaxFolding(state, lineStart, lineEnd)\n }",
"function lineNo(line) {\n if (line.parent == null) { return null }\n var cur = line.parent, no = indexOf(cur.lines, line);\n for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {\n for (var i = 0;; ++i) {\n if (chunk.children[i] == cur) { break }\n no += chunk.children[i].chunkSize();\n }\n }\n return no + cur.first\n }",
"function hasBreakpoint(ctx, line) {\n let { cm } = ctx;\n // In some rare occasions CodeMirror might not be properly initialized yet, so\n // return an exceptional value in that case.\n if (cm.lineInfo(line) === null) {\n return null;\n }\n let markers = cm.lineInfo(line).gutterMarkers;\n\n return markers != null &&\n markers.breakpoints &&\n markers.breakpoints.classList.contains(\"breakpoint\");\n}",
"function findMatchingLine(lines, re, startIndex) {\n re = new RegExp(re);\n if (!startIndex) startIndex = 0;\n\n var found = false, index;\n\n for (index = startIndex; index < lines.length; index++) {\n if (re.test(lines[index])) {\n found = true;\n break;\n }\n }\n\n return found ? index : -1;\n}",
"function locate_line(elt) {\n var found\n var initlen = elt.textContent.length\n var textlen = 0\n var count = 10000\n var wentup = false\n\n while (count > 0 && elt) {\n count = count - 1\n // console.log(\"at\", elt)\n if (elt.nodeType == 3) {\n textlen += textContentLength(elt)\n } else if (found = atLineStart(elt)) {\n break;\n } else if (!wentup) {\n textlen += textContentLength(elt)\n }\n wentup = false\n var next = elt.previousSibling\n if (!next) {\n next = elt.parentNode\n wentup = true\n if (!next || next == elt) {\n break\n }\n }\n elt = next\n }\n if (found) {\n var minCol = textlen - initlen + 1\n var maxCol = textlen + 1\n return [found, minCol, maxCol, elt]\n } else {\n return\n }\n}",
"function getTopVisibleLine(editor) {\n if (!editor[\"visibleRanges\"].length) {\n return undefined;\n }\n const firstVisiblePosition = editor[\"visibleRanges\"][0].start;\n const lineNumber = firstVisiblePosition.line;\n const line = editor.document.lineAt(lineNumber);\n const progress = firstVisiblePosition.character / (line.text.length + 2);\n return lineNumber + progress;\n}",
"function SearchJumpToLine(CodeMirror) {\n function dialog(cm, text, shortText, deflt, f) {\n if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});\n else f(prompt(shortText, deflt));\n }\n\n function getJumpDialog(cm) {\n return cm.phrase(\"Jump to line:\") + ' <input type=\"text\" style=\"width: 10em\" class=\"CodeMirror-search-field\"/> <span style=\"color: #888\" class=\"CodeMirror-search-hint\">' + cm.phrase(\"(Use line:column or scroll% syntax)\") + '</span>';\n }\n\n function interpretLine(cm, string) {\n var num = Number(string);\n if (/^[-+]/.test(string)) return cm.getCursor().line + num\n else return num - 1\n }\n\n CodeMirror.commands.jumpToLine = function(cm) {\n var cur = cm.getCursor();\n dialog(cm, getJumpDialog(cm), cm.phrase(\"Jump to line:\"), (cur.line + 1) + \":\" + cur.ch, function(posStr) {\n if (!posStr) return;\n\n var match;\n if (match = /^\\s*([\\+\\-]?\\d+)\\s*\\:\\s*(\\d+)\\s*$/.exec(posStr)) {\n cm.setCursor(interpretLine(cm, match[1]), Number(match[2]));\n } else if (match = /^\\s*([\\+\\-]?\\d+(\\.\\d+)?)\\%\\s*/.exec(posStr)) {\n var line = Math.round(cm.lineCount() * Number(match[1]) / 100);\n if (/^[-+]/.test(match[1])) line = cur.line + line + 1;\n cm.setCursor(line - 1, cur.ch);\n } else if (match = /^\\s*\\:?\\s*([\\+\\-]?\\d+)\\s*/.exec(posStr)) {\n cm.setCursor(interpretLine(cm, match[1]), cur.ch);\n }\n });\n };\n\n CodeMirror.keyMap[\"default\"][\"Alt-G\"] = \"jumpToLine\";\n }",
"function findSnappedLocation(lineLocation){\n\tvar finalLocation=lineLocation;\n\tvar listSize=globalPlList.size;\n\tfor(var i=1;i<=listSize;i++){\n\t\tvar line = globalPlList.get(i.toString());\n\t\tif(line!=undefined){\n\t\t\tvar startPath=line.getPath().getAt(0);\n\t\t\tvar endPath=line.getPath().getAt(1);\n\t\t\tvar tempCircleStart=new google.maps.Circle({\n\t\t\t\tcenter: startPath,\n\t\t\t\tradius: 10\n\t\t\t});\t\n\t\t\tvar tempCircleEnd=new google.maps.Circle({\n\t\t\t\tcenter: endPath,\n\t\t\t\tradius: 10,\n\t\t\t});\t\n\t\t\tvar isStartPath = google.maps.Circle.prototype.contains(lineLocation, tempCircleStart);\n\t\t\tvar isEndPath = google.maps.Circle.prototype.contains(lineLocation, tempCircleEnd);\n\t\t\tif(isStartPath){\n\t\t\t\tfinalLocation=startPath;\n\t\t\t\treturn finalLocation;\n\t\t\t}\n\t\t\telse if(isEndPath){\n\t\t\t\tfinalLocation=endPath;\n\t\t\t\treturn finalLocation;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tlistSize++; //To increase the size if a number is missing from id seq like 1,2,4,5,7 . Here Ids 3 and 6 are missing\n\t\t}\n\t}\n\treturn finalLocation;\n}",
"function region(n) {\n if (n == regions[n]) return n;\n var r = region(regions[n])\n regions[n] = r\n return r\n }",
"lineIndent(line) {\n var _a;\n let override = (_a = this.options) === null || _a === void 0 ? void 0 : _a.overrideIndentation;\n if (override) {\n let overriden = override(line.from);\n if (overriden > -1)\n return overriden;\n }\n let text = line.slice(0, Math.min(100, line.length));\n return this.countColumn(text, text.search(/\\S/));\n }",
"function getFolds(lines, level, offset) {\n var folds = Object.create(null);\n var currentFold = null;\n var key, l, line;\n\n // Iterate in lines\n for (l = 0; l < lines.length; l++) {\n line = lines[l];\n\n // If line is not indented it can be an object key or a key: value pair\n if (line.substr(0, TAB_SIZE) !== tab) {\n key = line.trim();\n\n // Cover the case that key is quoted. Example: \"/user/{userId}\":\n if ((key[0] === '\"') && (key[key.length - 2] === '\"') && (key[key.length - 1] === ':')) {\n key = key.substring(1, key.length - 2) + ':';\n }\n\n // If colon is not the last character it's not an object key\n if (!key || key.lastIndexOf(':') !== key.length - 1) {\n continue;\n }\n\n // Omit colon character\n if (key[key.length - 1] === ':') {\n key = key.substring(0, key.length - 1);\n }\n\n // If there is no current fold in progress initiate one\n if (currentFold === null) {\n currentFold = {\n start: l + offset,\n folded: false,\n end: null\n };\n folds[key] = currentFold;\n\n // else, add middle folds recessively and close current fold in progress\n } else {\n addSubFoldsAndEnd(lines, l, currentFold, level, offset);\n\n currentFold = {\n start: l + offset,\n end: null\n };\n folds[key] = currentFold;\n }\n }\n }\n\n // In case there is a current fold in progress finish it\n addSubFoldsAndEnd(lines, l, currentFold, level, offset);\n\n return folds;\n }",
"function FindStartBracket(currentLineNum) {\r\n\tvar match = -1;\r\n\r\n\tdo {\r\n\t\tvar currentLine = RemoveQuoted(Editor.Lines[currentLineNum]); // remove stuff in quotes\r\n\t\tif (RegexMatch(currentLine, \"{\", true) != \"\") {\r\n\t\t\tmatch = currentLineNum;\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tcurrentLineNum++;\r\n\t} while (currentLineNum != Editor.LineCount);\r\n\r\n\treturn match;\r\n\r\n}",
"function hiliteEmlLine(docObj, line) {\n var bgColor;\n if (top.HiliteCodeStatus)\n bgColor = \"#66CCFF\";\n else\n bgColor = \"#E8D152\";\n // unhighlight\n if (typeof docObj.HiliteLine != \"undefined\") {\n\ttrObj = docObj.getElementById(\"LN_\"+docObj.HiliteLine);\n\tif (trObj != null) {\n\t trObj.style.backgroundColor = \"\";\t\t\t\n\t}\n }\t\n // hilighlight\n trObj = docObj.getElementById(\"LN_\"+line);\n if (trObj != null) {\n\ttrObj.style.backgroundColor = bgColor;\n\tdocObj.HiliteLine = line;\n }\n}",
"lookForString(line) {\n line = this.trim(line);\n if(line.indexOf('constructor(') >= 0){console.log('line = ' + line);}\n if(line.indexOf('pragma ') >= 0){\n return 'pragma';\n }else if(line.indexOf('contract ') >= 0){\n return 'contract';\n }else if(line.indexOf('function ') >=0\n || line.indexOf('constructor') >= 0\n){\n return 'function';\n }else {\n return null;\n }\n}",
"function regionFromUrl(url) {\n var matches = url.match(/\\#l(\\d+)(?:-(\\d+))?/i);\n if (!matches) { return; }\n return orderedRegion(matches[1], matches[2] && Number(matches[2]));\n }",
"findInsertIndexInLine(char, line) {\n let left = 0;\n let right = line.length - 1;\n let mid, compareNum;\n\n if (line.length === 0 || char.compareTo(line[left]) < 0) {\n return left;\n } else if (char.compareTo(line[right]) > 0) {\n return this.struct.length;\n }\n\n while (left + 1 < right) {\n mid = Math.floor(left + (right - left) / 2);\n compareNum = char.compareTo(line[mid]);\n\n if (compareNum === 0) {\n return mid;\n } else if (compareNum > 0) {\n left = mid;\n } else {\n right = mid;\n }\n }\n\n if (char.compareTo(line[left]) === 0) {\n return left;\n } else {\n return right;\n }\n }",
"#checkLineBeforeBio(line) {\n if (line.startsWith('----')) {\n this.#messages.styleMessages.push('Horizontal rule before Biography');\n this.#style.bioHasStyleIssues = true;\n this.#headingBeforeBiography = true;\n } else {\n if (line.startsWith(Biography.#HEADING_START)) {\n if (!this.#headingBeforeBiography) {\n this.#style.bioHasStyleIssues = true;\n this.#headingBeforeBiography = true;\n this.#messages.styleMessages.push('Heading or subheading before Biography');\n }\n } else {\n // See https://www.wikitree.com/wiki/Help:Recommended_Tags\n // this might be too aggressive\n if ((line.startsWith('[[')) && (line.endsWith(']]'))) {\n this.#unexpectedLines.push(line);\n }\n if ((line.includes('through the import of')) ||\n (line.includes('collaborative work-in-progress'))) {\n this.#unexpectedLines.push(line);\n }\n }\n }\n }",
"detectRegion(stage, regionToFind) {\n if (!stage.srcCtx) {\n return null;\n }\n\n const srcData = stage.srcCtx.getImageData(0, 0, stage.srcSize.w, stage.srcSize.h);\n\n let x, y;\n\n // First find optical bounds\n // This works by taking an alpha value histogram and finding two maxima to determine\n // low and high alphas.\n let alphaHistogram = [];\n for (x = 0; x < stage.srcSize.w; x++) {\n for (y = 0; y < stage.srcSize.h; y++) {\n let alpha = srcData.data[(y * stage.srcSize.w + x) * 4 + 3];\n alphaHistogram[alpha] = alphaHistogram[alpha] ? alphaHistogram[alpha] + 1 : 1;\n }\n }\n\n let max1 = 0, max1Freq = 0, max2 = 0, max2Freq = 0;\n for (let i = 0; i < 256; i++) {\n if (alphaHistogram[i] > max1Freq) {\n max2 = max1;\n max2Freq = max1Freq;\n max1 = i;\n max1Freq = alphaHistogram[i];\n } else if (alphaHistogram[i] > max2Freq) {\n max2 = i;\n max2Freq = alphaHistogram[i];\n }\n }\n\n let alphaMin = (max1 < max2) ? max1 : max2;\n let alphaMax = (max1 > max2) ? max1 : max2;\n\n const ALPHA_THRESHOLD = 5;\n\n var opticalBoundsRect = {l:-1, r:-1, t:-1, b:-1};\n\n // Find left optical bound\n obrLeft:\n for (x = 0; x < stage.srcSize.w; x++) {\n for (y = 0; y < stage.srcSize.h; y++) {\n var alpha = srcData.data[(y * stage.srcSize.w + x) * 4 + 3];\n if (alpha >= alphaMax - ALPHA_THRESHOLD) {\n opticalBoundsRect.l = x;\n break obrLeft;\n }\n }\n }\n // Find right optical bound\n obrRight:\n for (x = stage.srcSize.w - 1; x >= 0; x--) {\n for (y = 0; y < stage.srcSize.h; y++) {\n var alpha = srcData.data[(y * stage.srcSize.w + x) * 4 + 3];\n if (alpha >= alphaMax - ALPHA_THRESHOLD) {\n opticalBoundsRect.r = x;\n break obrRight;\n }\n }\n }\n // Find top optical bound\n obrTop:\n for (y = 0; y < stage.srcSize.h; y++) {\n for (x = 0; x < stage.srcSize.w; x++) {\n var alpha = srcData.data[(y * stage.srcSize.w + x) * 4 + 3];\n if (alpha >= alphaMax - ALPHA_THRESHOLD) {\n opticalBoundsRect.t = y;\n break obrTop;\n }\n }\n }\n // Find bottom optical bound\n obrBottom:\n for (y = stage.srcSize.h - 1; y >= 0; y--) {\n for (x = 0; x < stage.srcSize.w; x++) {\n let alpha = srcData.data[(y * stage.srcSize.w + x) * 4 + 3];\n if (alpha >= alphaMax - ALPHA_THRESHOLD) {\n opticalBoundsRect.b = y;\n break obrBottom;\n }\n }\n }\n\n let returnRect;\n\n if (opticalBoundsRect.l >= 0 && opticalBoundsRect.r > opticalBoundsRect.l\n && opticalBoundsRect.t >= 0 && opticalBoundsRect.b > opticalBoundsRect.t) {\n let rect = {\n x: opticalBoundsRect.l,\n y: opticalBoundsRect.t,\n w: opticalBoundsRect.r - opticalBoundsRect.l + 1,\n h: opticalBoundsRect.b - opticalBoundsRect.t + 1\n };\n\n if (regionToFind == 'opticalbounds' || regionToFind == 'padding') {\n return rect;\n }\n }\n\n // Next find stretch regions. Only use them if they're within the optical bounds\n if (regionToFind == 'stretch') {\n let newStretchRect = Object.assign({}, stage.stretchRect);\n\n const summer = new Summer();\n let sums = [];\n for (y = 0; y < stage.srcSize.h; y++) {\n // Compute row\n summer.reset();\n for (let x = 0; x < stage.srcSize.w; x++) {\n summer.addNext(getPixel_(stage, srcData, x, y));\n }\n sums.push(summer.compute());\n }\n\n let ranges = getEqualRanges_(sums);\n for (let i = 0; i < ranges.length; i++) {\n let range = ranges[i];\n let passesThreshold = false;\n // Check if this row has a minimum alpha\n for (x = 0; x < stage.srcSize.w; x++) {\n let alpha = srcData.data[(range.start * stage.srcSize.w + x) * 4 + 3];\n if (alpha >= alphaMax - ALPHA_THRESHOLD) {\n passesThreshold = true;\n break;\n }\n }\n if (passesThreshold) {\n newStretchRect.y = range.start;\n newStretchRect.h = range.length;\n if (range.length >= 4) {\n // inset a bit to prevent scaling artifacts\n newStretchRect.y++;\n newStretchRect.h -= 2;\n }\n break;\n }\n }\n\n summer.reset();\n sums = [];\n for (x = 0; x < stage.srcSize.w; x++) {\n // Compute column\n summer.reset();\n for (y = 0; y < stage.srcSize.h; y++) {\n summer.addNext(getPixel_(stage, srcData, x, y));\n }\n sums.push(summer.compute());\n }\n\n ranges = getEqualRanges_(sums);\n for (let i = 0; i < ranges.length; i++) {\n let range = ranges[i];\n let passesThreshold = false;\n // Check if this column has a minimum alpha\n for (y = 0; y < stage.srcSize.h; y++) {\n let alpha = srcData.data[(y * stage.srcSize.w + range.start) * 4 + 3];\n if (alpha >= alphaMax - ALPHA_THRESHOLD) {\n passesThreshold = true;\n break;\n }\n }\n\n if (passesThreshold) {\n newStretchRect.x = range.start;\n newStretchRect.w = range.length;\n if (range.length >= 4) {\n // inset a bit to prevent scaling artifacts\n newStretchRect.x++;\n newStretchRect.w -= 2;\n }\n break;\n }\n }\n\n return newStretchRect;\n }\n\n return null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Callback function for the IAM creation which should have 3 params coming in. | function finishedCreatingCallback(err, usersForCloudFormation, IAMuserPassword, groupName) {
if(err) {
cloudformationsender.sendResponse(theEvent, theContext, "FAILED", {});
}
else {
cloudformationsender.sendResponse(theEvent, theContext, "SUCCESS", {
"IamPassword": IAMuserPassword,
"Users": usersForCloudFormation,
"IamGroup": groupName
});
}
} | [
"async createApiKey (obj, args, context) {\n try {\n return {\n key: await WIKI.models.apiKeys.createNewKey(args),\n responseResult: graphHelper.generateSuccess('API Key created successfully')\n }\n } catch (err) {\n return graphHelper.generateError(err)\n }\n }",
"function create(accessKeyId, secretAccessKey) {\n config.accessKeyId = accessKeyId;\n config.secretAccessKey = secretAccessKey;\n\n AWS.config.update(config);\n AWS.config.region = window.AWS_EC2_REGION;\n AWS.config.apiVersions = {\n cloudwatch: '2010-08-01',\n sqs: '2012-11-05'\n };\n\n cloudWatch = new AWS.CloudWatch();\n autoScaling = new AWS.AutoScaling();\n sqs = new AWS.SQS();\n }",
"function AM_policy_create(amServer, policyData){\n\t\n\tvar result = {};\n\tvar ssoToken = amServer.ssoToken;\n\t\n\trestCall = {};\n\trestCall.url = constructAmUri(amServer) + \"/json/realms/\" + amServer.policyRealm + \"/policies?_action=create\";\n\n\trestCall.headers = { \"contentType\" \t : \"application/json\", \n\t\t\t \"Accept-API-Version\" : \"protocol=1.0\",\n\t\t\t \"iPlanetDirectoryPro\" : ssoToken};\n\trestCall.body = JSON.stringify(policyData);\n\trestCall.method = \"POST\";\n\n\texecuteRest(restCall);\n\n\treturn;\n\t\n}",
"function NewSignature(cred , sk , Nym , RNym , ipk , Disclosure , msg , rhIndex , cri , rng ) {\n \n /*\n // Validate inputs\n\tif cred == nil || sk == nil || Nym == nil || RNym == nil || ipk == nil || rng == nil || cri == nil {\n\t\treturn nil, errors.Errorf(\"cannot create idemix signature: received nil input\")\n\t}\n\n\tif rhIndex < 0 || rhIndex >= len(ipk.AttributeNames) || len(Disclosure) != len(ipk.AttributeNames) {\n\t\treturn nil, errors.Errorf(\"cannot create idemix signature: received invalid input\")\n\t}\n\n\tif cri.RevocationAlg != int32(ALG_NO_REVOCATION) && Disclosure[rhIndex] == 1 {\n\t\treturn nil, errors.Errorf(\"Attribute %d is disclosed but also used as revocation handle attribute, which should remain hidden.\", rhIndex)\n\t}\n*/\n\n\t// locate the indices of the attributes to hide and sample randomness for them\n\tHiddenIndices = hiddenIndices(Disclosure)\n\n\t// Generate required randomness r_1, r_2\n\tlet r1 = RandModOrder(rng)\n\tlet r2 = RandModOrder(rng)\n\t// Set r_3 as \\frac{1}{r_1}\n let r3 = new FP256BN.BIG(r1)\n\n\tr3.invmodp(GroupOrder)\n\n\t// Sample a nonce\n\tlet Nonce = RandModOrder(rng)\n\n\t// Parse credential\n\tlet A = cred.A\n\tlet B = cred.B\n let E = cred.E\n let S = cred.S\n\n\t// Randomize credential\n\n\t// Compute A' as A^{r_!}\n\tlet APrime = FP256BN.PAIR.G1mul(A, r1)\n\n\t// Compute ABar as A'^{-e} b^{r1}\n let ABar = FP256BN.PAIR.G1mul(B, r1)\n\tABar.sub(FP256BN.PAIR.G1mul(APrime, E))\n\n\t// Compute B' as b^{r1} / h_r^{r2}, where h_r is h_r\n\tlet BPrime = FP256BN.PAIR.G1mul(B, r1)\n\tlet HRand = ipk.HRand\n\t// Parse h_{sk} from ipk\n\tlet HSk = ipk.HSk\n\n\tBPrime.sub(FP256BN.PAIR.G1mul(HRand, r2))\n\n\t// Compute s' as s - r_2 \\cdot r_3\n\tlet sPrime = Modsub(S, FP256BN.BIG.modmul(r2, r3, GroupOrder), GroupOrder)\n\n\t// The rest of this function constructs the non-interactive zero knowledge proof\n\t// that links the signature, the non-disclosed attributes and the nym.\n\n\t// Sample the randomness used to compute the commitment values (aka t-values) for the ZKP\n\tlet rSk = RandModOrder(rng)\n\tlet re = RandModOrder(rng)\n\tlet rR2 = RandModOrder(rng)\n\tlet rR3 = RandModOrder(rng)\n\tlet rSPrime = RandModOrder(rng)\n\tlet rRNym = RandModOrder(rng)\n\n let rAttrs = new Array(HiddenIndices.length)\n HiddenIndices.forEach(\n (value,i) => {\n rAttrs[i] = RandModOrder(rng)\n }\n )\n\n/*\n\t// First compute the non-revocation proof.\n\t// The challenge of the ZKP needs to depend on it, as well.\n\tprover, err = getNonRevocationProver(RevocationAlgorithm(cri.RevocationAlg))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnonRevokedProofHashData, err = prover.getFSContribution(\n\t\tFP256BN.FromBytes(cred.Attrs[rhIndex]),\n\t\trAttrs[sort.SearchInts(HiddenIndices, rhIndex)],\n\t\tcri,\n\t\trng,\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to compute non-revoked proof\")\n\t}\n*/\n\t// Step 1: First message (t-values)\n\n\t// t1 is related to knowledge of the credential (recall, it is a BBS+ signature)\n let t1 = APrime.mul2(re, HRand, rR2) // A'^{r_E} . h_r^{r_{r2}}\n\n\t// t2: is related to knowledge of the non-disclosed attributes that signed in (A,B,S,E)\n\tlet t2 = FP256BN.PAIR.G1mul(HRand, rSPrime) // h_r^{r_{s'}}\n t2.add(BPrime.mul2(rR3, HSk, rSk)) // B'^{r_{r3}} \\cdot h_{sk}^{r_{sk}}\n\n for (i = 0; i < Math.floor(HiddenIndices.length/2); i++){\n\t\tt2.add(\n\t\t\t// \\cdot h_{2 \\cdot i}^{r_{attrs,i}\n\t\t\tipk.HAttrs[HiddenIndices[2*i]].mul2(\n\t\t\t\trAttrs[2*i],\n\t\t\t\tipk.HAttrs[HiddenIndices[2*i+1]],\n\t\t\t\trAttrs[2*i+1],\n\t\t\t),\n\t\t)\n\t}\n\tif (HiddenIndices.length % 2 != 0 ){\n\t\tt2.add(FP256BN.PAIR.G1mul(ipk.HAttrs[HiddenIndices[HiddenIndices.length-1]], rAttrs[HiddenIndices.length-1]))\n\t}\n\n\t// t3 is related to the knowledge of the secrets behind the pseudonym, which is also signed in (A,B,S,E)\n \tlet t3 = HSk.mul2(rSk, HRand, rRNym) // h_{sk}^{r_{sk}} \\cdot h_r^{r_{rnym}}\n //let t3 = Mul2(HSk,rSk, HRand, rRNym)\n\n\t// Step 2: Compute the Fiat-Shamir hash, forming the challenge of the ZKP.\n\n\t// Compute the Fiat-Shamir hash, forming the challenge of the ZKP.\n\t// proofData is the data being hashed, it consists of:\n\t// the signature label\n\t// 7 elements of G1 each taking 2*FieldBytes+1 bytes\n // one bigint (hash of the issuer public key) of length FieldBytes\n \n\n\n\t// disclosed attributes\n\t// message being signed\n\t// the amount of bytes needed for the nonrevocation proof\n\t//let proofData = new ArrayBuffer( signLabel.lenght+7*(2*FieldBytes+1)+FieldBytes+Disclosure.length+msg.length+ProofBytes[RevocationAlgorithm(cri.RevocationAlg)])\n\tlet proofData = new ArrayBuffer( signLabel.length+7*(2*FieldBytes+1)+FieldBytes+Disclosure.length+msg.length)\n let v = new Uint8Array(proofData);\n let index = 0\n\tindex = appendBytesString(v, index, signLabel)\n index = appendBytesG1(proofData, index, t1)\n\tindex = appendBytesG1(proofData, index, t2)\n\tindex = appendBytesG1(proofData, index, t3)\n\tindex = appendBytesG1(proofData, index, APrime)\n\tindex = appendBytesG1(proofData, index, ABar)\n\tindex = appendBytesG1(proofData, index, BPrime)\n\tindex = appendBytesG1(proofData, index, Nym)\n //index = appendBytes(proofData, index, nonRevokedProofHashData)\n v.set(BigToBytes(ipk.Hash),index);\n\tindex = index + FieldBytes\n v.set(Buffer.from(Disclosure),index);\n\tindex = index + Disclosure.length\n v.set(msg,index);\n\tlet c = HashModOrder(v)\n\n\t// add the previous hash and the nonce and hash again to compute a second hash (C value) \n index = 0\n proofData = proofData.slice(0,2*FieldBytes);\n let v2 = new Uint8Array(proofData);\n\n\tindex = appendBytesBig(proofData, index, c)\n\tindex = appendBytesBig(proofData, index, Nonce)\n\n ProofC = HashModOrder(v2)\n\n // Step 3: reply to the challenge message (s-values)\n ProofSSk = Modadd(rSk, FP256BN.BIG.modmul(ProofC, sk, GroupOrder), GroupOrder) // s_sk = rSK + C . sk\n\n ProofSE = Modsub(re, FP256BN.BIG.modmul(ProofC, E, GroupOrder), GroupOrder) // s_e = re + C . E\n ProofSR2 = Modadd(rR2, FP256BN.BIG.modmul(ProofC, r2, GroupOrder), GroupOrder) // s_r2 = rR2 + C . r2\n\n\n\tlet ProofSR3 = Modsub(rR3, FP256BN.BIG.modmul(ProofC, r3, GroupOrder), GroupOrder) // s_r3 = rR3 + C \\cdot r3\n\tlet ProofSSPrime = Modadd(rSPrime, FP256BN.BIG.modmul(ProofC, sPrime, GroupOrder), GroupOrder) // s_S' = rSPrime + C \\cdot sPrime\n\tlet ProofSRNym = Modadd(rRNym, FP256BN.BIG.modmul(ProofC, RNym, GroupOrder), GroupOrder) // s_RNym = rRNym + C \\cdot RNym\n let ProofSAttrs = new Array(HiddenIndices.length)\n\n\n /*\n\tfor i, j = range HiddenIndices {\n\t\tProofSAttrs[i] = BigToBytes(\n\t\t\t// s_attrsi = rAttrsi + C \\cdot cred.Attrs[j]\n\t\t\tModadd(rAttrs[i], FP256BN.Modmul(ProofC, cred.Attrs[j], GroupOrder), GroupOrder),\n\t\t)\n }*/\n\n HiddenIndices.forEach(\n (j,i) => {\n // s_attrsi = rAttrsi + C \\cdot cred.Attrs[j]\n ProofSAttrs[i] = Modadd(rAttrs[i], FP256BN.BIG.modmul(ProofC, cred.Attrs[j], GroupOrder), GroupOrder); \n }\n )\n // Compute the revocation part\n /*\n\tnonRevokedProof, err = prover.getNonRevokedProof(ProofC)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n*/\n\n\t// We are done. Return signature\n\treturn {\n\t\t\tAPrime: APrime,\n\t\t\tABar: ABar,\n\t\t\tBPrime: BPrime,\n\t\t\tProofC: ProofC,\n\t\t\tProofSSk: ProofSSk,\n\t\t\tProofSE: ProofSE,\n\t\t\tProofSR2: ProofSR2,\n\t\t\tProofSR3: ProofSR3,\n\t\t\tProofSSPrime: ProofSSPrime,\n\t\t\tProofSAttrs: ProofSAttrs,\n\t\t\tNonce: Nonce,\n\t\t\tNym: Nym,\n\t\t\tProofSRNym: ProofSRNym,\n\t//\t\tRevocationEpochPk: cri.EpochPk,\n\t//\t\tRevocationPkSig: cri.EpochPkSig,\n\t//\t\tEpoch: cri.Epoch,\n // NonRevocationProof: nonRevokedProof\n }\n}",
"createAccount()\n {\n account = this.web3.eth.accounts.create();\n\n vaultData.account_list.push(account)\n\n this.selectAccount( account.address )\n\n this.saveVaultData( vaultData )\n\n }",
"function createBucket(bucketName, _callback){\n\n storage\n .createBucket(bucketName, {\n location: 'us-central1',\n storageClass: 'Regional',\n })\n .then(results => {\n console.log(`Bucket ${bucketName} created`);\n _callback(bucketName);\n })\n\n .catch(err => {\n console.error('ERROR:', err);\n });\n}",
"async function accountsCreateOrUpdate() {\n const subscriptionId =\n process.env[\"NETAPP_SUBSCRIPTION_ID\"] || \"D633CC2E-722B-4AE1-B636-BBD9E4C60ED9\";\n const resourceGroupName = process.env[\"NETAPP_RESOURCE_GROUP\"] || \"myRG\";\n const accountName = \"account1\";\n const body = { location: \"eastus\" };\n const credential = new DefaultAzureCredential();\n const client = new NetAppManagementClient(credential, subscriptionId);\n const result = await client.accounts.beginCreateOrUpdateAndWait(\n resourceGroupName,\n accountName,\n body\n );\n console.log(result);\n}",
"function workOrderCreate() {\n // Define the data object and include the needed parameters.\n // Make the Create API call and assign a callback function.\n}",
"handleAddAttribute(params) {\n this.applicant = params[1];\n this.applicant[params[2]] = params[0];\n this.applicant[`${params[2]}File`] = params[3];\n }",
"static createInvoiceItem(invoice_id, user_id, role, advanced_price=0) {\n return axios.post(\n liabilities_url + 'invoice_items/',\n {\n invoice_id: invoice_id,\n user_id: user_id,\n role: role,\n advanced_price: advanced_price,\n }\n );\n }",
"function createS3(){\n\treturn s3.createBucket({\n\t\tBucket: CONFIG.s3_image_bucket,\n\t}).promise().catch(err => {\n\t\tif (err.code !== \"BucketAlreadyOwnedByYou\") throw err\n\t})\n}",
"newAuthorisedCapability (holder, id, type, location, sphere, validFrom, validTo) {\n const subject = {\n id: 'did:caelum:' + this.did + '#issued-' + (id || 0),\n capability: {\n type: type || 'member',\n sphere: (['over18', 'oidc'].includes(type) ? 'personal' : 'professional')\n }\n }\n if (location) subject.capability.location = location\n const credential = {\n '@context': [\n 'https://www.w3.org/2018/credentials/v1',\n 'https://caelumapp.com/context/v1'\n ],\n id: 'did:caelum:' + this.did + '#issued',\n type: ['VerifiableCredential', 'AuthorisedCapability'],\n issuer: 'did:caelum:' + this.did,\n holder: holder,\n issuanceDate: new Date().toISOString(),\n credentialSubject: subject\n }\n return credential\n }",
"async createVoter(ctx, args) {\n\n args = JSON.parse(args);\n\n //create a new voter\n let newVoter = await new Voter(ctx, args.voterId, args.registrarId, args.firstName, args.lastName);\n\n //update state with new voter\n await ctx.stub.putState(newVoter.voterId, Buffer.from(JSON.stringify(newVoter)));\n\n //query state for elections\n let currElections = JSON.parse(await this.queryByObjectType(ctx, 'election'));\n\n if (currElections.length === 0) {\n let response = { error: 'no elections. Run the init() function first.' };\n return response;\n }\n\n //get the election that is created in the init function\n let currElection = currElections[0];\n\n let votableItems = JSON.parse(await this.queryByObjectType(ctx, 'votableItem'));\n\n //generate ballot with the given votableItems\n await this.generateBallot(ctx, votableItems, currElection, newVoter);\n\n let response = { message: `voter with voterId ${newVoter.voterId} is updated in the world state` };\n return response;\n }",
"constructor(accessKey, secretKey, region, bucket, callback) {\n\t\tthis._s3 = null;\n\t\tthis._bucket = bucket;\n\t\tlet scriptTag = document.createElement('script');\n\t\tscriptTag.src = 'aws-sdk.min.js';\n\t\tscriptTag.onload = function () {\n\t\t\tAWS.config.update({\n\t\t\t\taccessKeyId: accessKey,\n\t\t\t\tsecretAccessKey: secretKey,\n\t\t\t\tregion: region\n\t\t\t});\n\t\t\tthis._s3 = new AWS.S3();\n\t\t\tcallback();\n\t\t}.bind(this);\n\t\tdocument.body.appendChild(scriptTag);\n\t}",
"function saveVegOrder(agent){\n let dbVegWrite = new aws.DynamoDB.DocumentClient();\n //console.log(\"Coming in saveVegOrder\");\n var number = makeID(3);\n\n var id = number;\n const order = \"Veg Pizza\";\n const pizzaSize = agent.parameters.pizzaSize;\n const crustType = agent.parameters.crustType;\n const pizzaToppings = agent.parameters.pizzaToppings;\n \n \n let save = function(){\n var input = {\n \"orderId\" : id,\n \"pizzaType\" : `${order}`,\n \"pizzaSize\" : `${pizzaSize}`,\n \"crustType\" : `${crustType}`,\n \"pizzaToppings\" : `${pizzaToppings}`\n };\n var parameters = {\n TableName: \"OrderDetailsTable\",\n Item: input\n };\n dbVegWrite.put(parameters,function(err,data){\n if(err){\n console.log(\"Error is two:\",JSON.stringify(err,null,2));\n }else{console.log(\"success\");}\n });\n };\n save();\n\n }",
"async create(attrs) {\r\n // {email: '', password:''} this is what we assume attrs is\r\n attrs.id = this.randomId();\r\n const salt = crypto.randomBytes(8).toString('hex');\r\n const buf = await scrypt(attrs.password, salt, 64);\r\n //salt + attrs.password\r\n const records = await this.getAll() //gets existing users\r\n const record = {\r\n ...attrs,\r\n password: `${buf.toString('hex')}.${salt}`\r\n } // the fullstop splits the hashed pw from the salt\r\n records.push(record); // pushes new user into our records\r\n await this.writeAll(records);\r\n\r\n return record; // returns object with user ID, plus hash and salted pw\r\n }",
"function idbCreate_attributes(){\r\n\tvar request = db.setVersion('1');\r\n\trequest.onerror = function(e){log(\"Error: IndexedDB create attributes\");};\r\n\trequest.onsuccess = function(e) {\r\n\t\tif (!db.objectStoreNames.contains('attributes')) {\r\n\t\t\ttry {\r\n\t\t\t\tdb.createObjectStore('attributes', {keyPath: 'id'});\r\n\t\t\t\tvar key = '__default_attributes__';\r\n\t\t\t\t$.ajax({\r\n\t\t\t\t\turl:'bin/xml_to_json.php',\r\n\t\t\t\t\ttype:'POST',\r\n\t\t\t\t\tdataType:'json',\r\n\t\t\t\t\tdata:{filename:'attributes.xml'},\r\n\t\t\t\t\tsuccess:function(d){\r\n\t\t\t\t\t\tM3D.DB.setAttributes({name:key, value:d.attributes});\r\n\t\t\t\t\t},\r\n\t\t\t\t\terror:function(){\r\n\t\t\t\t\t\talert('Could not load Models attributes! A server error has occured!');\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\tlog(\"Object store attributes created\");\r\n\t\t\t} catch (err) {\r\n\t\t\t\tlog(\"Error: IndexedDB create attributes\");\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tlog(\"Object store attributes already exists\");\r\n\t\t}\r\n\t}\r\n}",
"function initializeNewItem(item) {\n item.assignedResource = resource1;\n console.log('A new item was created.');\n }",
"function AddInstancetag(tagData, callback) {\n //tagData is of the\n //type {compType:Ec2/Elb/S3 , tag:[{Key:\"Component\",Value:\"sda\"}] ,identifer:identifier }\n\n if (tagData.compType === 'Ec2') {\n var params = {\n Resources: [tagData.identifier],\n Tags: tagData.tag\n };\n ec2.createTags(params, function (err, data) {\n if (err) {\n console.log(err, err.stack);\n callback(err);\n } // an error occurred\n else {\n console.log(data);\n callback(false, data);\n } // successful response\n });\n } else {\n if (tagData.compType === 'Elb') {\n // callback(false,tagData.tag);\n // return false;\n var params = {\n LoadBalancerNames: [tagData.identifier],\n Tags: tagData.tag\n };\n elb.addTags(params, function (err, data) {\n if (err) {\n console.log(err, err.stack);\n callback(err);\n } // an error occurred\n else {\n console.log(data);\n callback(false, data);\n } // successful response\n });\n } else {\n if (tagData.compType === 'S3') {\n var params = {\n Bucket: tagData.identifier,\n Tagging: {\n TagSet: tagData.tag\n }\n };\n s3.putBucketTagging(params, function (err, data) {\n if (err) {\n console.log(err, err.stack);\n callback(err);\n } // an error occurred\n else {\n console.log(data);\n callback(false, data);\n } // successful response\n });\n } else {\n console.log(\"Shouldnt be here :: InstanceService line 448 :: Maybe compType was not \\\n Ec2/Elb/S3 \");\n }\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes the range of an animation | function AnimationRange(/**The name of the animation range**/name,/**The starting frame of the animation */from,/**The ending frame of the animation*/to){this.name=name;this.from=from;this.to=to;} | [
"setRanges() {\r\n\t\tthis.ranges.x = d3.scaleTime()\r\n\t\t\t.range([0, this.dimensions.width - this.margins.x]);\r\n\r\n\t\tthis.ranges.y = d3.scaleLinear()\r\n\t\t\t.range([this.dimensions.height - (2 * this.margins.y), 0]);\r\n\t}",
"init() {\n\t\tconst agents = this.m.getAgents();\n\t\tfor (let i = 0; i < agents.length; i++) {\n\t\t\tthis.setPosition(agents[i].name, i, generatePosition(this.m.mapManager.borders) );\n\t\t}\n\t}",
"initialize(options) {\n if (this.pages.length == 0) {\n console.error('VerticalPageCarousel requires a pages array.');\n return;\n }\n\n if (!this.getPageDefByKey(options.step)) { // don't know what they're doing\n options.step = this.pages[0].key;\n }\n this.currentDef = this.getPageDefByKey(options.step);\n\n // A counter for distinguishing unique region ids\n this.regionIndex = 0;\n\n // A variable for keeping track of the new region \"in play\" and being animated into existence\n this.newRegion = null;\n }",
"function Range() {\n\tthis.minCells = 2 // Can operate on a minimum of 2 cells\n\tthis.maxCells = 4 // Can operate on a maximum of 4 cells\n\tthis.symbol = 'range'\n}",
"setStartPosition() {\n this.position = [Math.floor(pixelAmount / 2), Math.floor(pixelAmount / 2)];\n }",
"reset(){\n this.setSpeed();\n this.setStartPosition();\n }",
"function CellRange() {\r\n this.p0 = new Vec2d();\r\n this.p1 = new Vec2d();\r\n this.reset();\r\n}",
"startRandomAnimation() {\n this.clearPrevious();\n try {\n let n = this.getN();\n let parameterObject = this.generateParameter(n);\n this.startAnimation(parameterObject);\n } catch (e) {\n\n }\n }",
"constructor(paramToTween, startVal, endVal, time) {\r\n this.param = paramToTween;\r\n this.startVal = startVal;\r\n this.endVal = endVal;\r\n this.time = time;\r\n this.elapsedTime = 0;\r\n }",
"function initializeLesson() {\r\n lesson11.init();\r\n animate();\r\n}",
"constructor (period, delay, width, start_pos_X, start_pos_Y, end_pos_X, end_pos_Y) {\n\t\tthis.period = period;\n\t\tthis.delay = delay;\n\t\tthis.width = width;\n\t\tthis.start_pos = [];\n\t\tthis.start_pos[0] = start_pos_X;\n\t\tthis.start_pos[1] = start_pos_Y;\n\t\tthis.end_pos = [];\n\t\tthis.end_pos[0] = end_pos_X;\n\t\tthis.end_pos[1] = end_pos_Y;\n\n\t\tthis.curr_start_pos = [];\n\t\tthis.curr_end_pos = [];\n\n\t\tvar time = new Date();\n\t\tthis.initialize_time = time.getTime();\n\t\tthis.start_time = -1;\n\t}",
"componentDidMount(){\r\n\t\tlet t1 = gsap.timeline({repeat: 0, delay: 0, repeatDelay: 1});\r\n\t\tt1.from('#photoSlider', {\r\n\t\t\tduration: 1,\r\n\t\t\ty: -500,\r\n\t\t\tease: 'power1'\r\n\t\t});\r\n\t}",
"initZoomOut()\n {\n this.animStyle = Target.ANIM_ZOOM_OUT;\n }",
"constructor() {\n this.current_position = -1;\n this.playerDiceRoll = -1;\n this.i = 0;\n }",
"reset() {\n this.animatedValues = object.clone(this.initialProps);\n }",
"function setSliderMinMaxDates(range) {\n $scope.layoutEndTimeMS = range.max;\n $scope.layoutStartTimeMS = range.min;\n $scope.currentDate = range.min;\n $scope.layoutCurTimeMS = range.min;\n }",
"init(){\n this.speedX=0;\n this.speedY=-this.maxSpeed;\n this.speedZ=0;\n\n // these two components are used to know speed in the new coordinates after a rotation\n this.speedXAfterRotate=0;\n this.speedZAfterRotate=0;\n\n let now = (new Date).getTime();\n this.lastUpdate=now;\n }",
"moveToStart() { \n\n TweenMax.fromTo('#ball', this.time,\n { \n scale: 0 \n },\n { \n scale: 1,\n delay: this.time * ((this.steps - 3) - 1.5), \n onComplete: () => {\n this.balltween.play();\n }\n });\n\n this.timeline.add(\n TweenMax.fromTo('#sticks', this.time * this.steps, { x: this.screen / this.scale }, { x: 0, ease: Power0.easeNone})\n );\n }",
"initDistTime () {\n this.eachDatum((x, y, status) => {\n const beta = this._ellipse.betaPoint(x, y) // { radians, ratio, rate, dist, time }\n this.set(x, y, new Location(beta.dist, beta.time, Unvisited, Unvisited))\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mobile Menu End Mobile Admin Dashboard Open | function openAdminDashboard() {
var oad1 = document.getElementById("mob-admin-dash");
oad1.classList.add("in");
var oad2 = document.getElementById("close-admin-overlay");
oad2.classList.add("in");
} | [
"listenAdminHomeLink() {\n editor.clearMenus();\n editor.showPrimaryMenu();\n event.preventDefault();\n }",
"function sgny_mobil_menu(){\n\t$('#mobil_menu').slimmenu({\n\t\tresizeWidth: '800',\n\t\tcollapserTitle: '',\n\t\tanimSpeed: 'medium',\n\t\teasingEffect: null,\n\t\tindentChildren: false,\n\t\tchildrenIndenter: ' ',\n\t\texpandIcon: '<i class=\"fa fa-angle-down\"></i>',\n\t\tcollapseIcon: '<i class=\"fa fa-angle-up\"></i>'\n\t});\n\n\t$(\"#mobil_menu li.menu-item-has-children > a\").on(\"click\",function(){\n\t\t$(this).next(\".sub-toggle\").trigger(\"click\");\n\t});\n}",
"function openMobileDropdown( link ){\n\t\t//console.log(link);\n\n\t\tvar item = link.parent('.has-sub-menu');\n\n\t\tif( $(item).hasClass('closed') ){\n\t\t\t$(link).removeClass('mobile-closed').addClass('mobile-open');\n\t\t\t$(item).removeClass('closed').addClass('open');\t\n\t\t\t$('body').removeClass('mobile-dropdown-off').addClass('mobile-dropdown-on');\n\t\t}\n\n\t}",
"function closeMobileMenu() {\n navMenuMobile.style.maxHeight = null;\n navMenuMobile.style.pointerEvents = 'none';\n bodyOverlay.style.opacity = 0;\n document.querySelector('body').style.overflow = 'unset';\n bodyOverlay.style.pointerEvents = 'none';\n navTriangle.style.display = 'none';\n}",
"function onOpen() \n{\n SpreadsheetApp.getUi()\n .createMenu('Custom Menu')\n .addItem('Open Export Sidebar', 'showSidebar')\n .addToUi();\n}",
"function _showModifyTileMenu() {\n //topAppBar.winControl.hide();\n div_cockpits_bottomAppBar.winControl.hide();\n var item = lv_cockpits.winControl._selection.getItems()._value[0].data;\n item.idDashboard = CockpitHelper.currentDashboard.id;\n if (item.widgetType == CockpitHelper.TileType.Numerique) {\n RightMenu.showRightMenu(Pages.modifyKpiResumeStep, { \"tile\": item });\n }\n else if (item.widgetType == CockpitHelper.TileType.Exploration) {\n RightMenu.showRightMenu(Pages.modifyExploration, { \"tile\": item });\n }\n }",
"function expandMoMenu() {\n $(\".headBot\").css({\"overflow\": \"visible\"}); \n $(\".expandMenu\").addClass(\"switchButtonIconOther\");\n $(\".menu\").addClass(\"mobileMenu\");\n mobileMenuState = true;\n }",
"function openMenu1() {\n setColor({ color1: '#0e80c0' });\n setMenu({ menu1: true });\n\n\n }",
"toggleMobileMenu() {\n this.setState({ showMobileMenu: !this.state.showMobileMenu });\n }",
"function openMobileNavbar() {\n\n $('.mobile-navbar').removeClass('hidden');\n /* Hide burger icon */\n $('#openMobileNavbar').addClass('hidden');\n\n /* Show close button */\n $('#closeMobileNavbar').removeClass('hidden');\n\n}",
"function showSideBarMenu(testtoolFlag,deviceFlag,serverFlag,connectivityFlag){\n\tif(userInformation[0].userLevel != \"Administrator\" && globalDeviceType != \"Mobile\"){\n\t\tvar sideStr = \"\";\n\t\tif(!testtoolFlag){\n\t\t\t$('#testToolIn').hide();\n\t\t}\n\t\tif(!deviceFlag){\n\t\t\t$('#deviceIn').hide();\n\t\t}\n\t\tif(!serverFlag){\n\t\t\t$('#serverIn').hide();\n\t\t}\n\t\tif(!connectivityFlag){\n\t\t\t$('#connectivityIn').hide();\n\t\t}\n\t}\n}",
"function initDesktopMenu() {\n\t\tif(window.desktopCapable) {\n\t\t\tcurScrollTop = window.pageYOffset;\n\t\t\tif(window.responsiveState !== 'mobile' && $active.length) {\n\t\t\t\twindow.requestAnimationFrame(function () {\n\t\t\t\t\treturn setIndicator($active[0]);\n\t\t\t\t});\n\t\t\t}\n $window.smartresize(function(){\n setIndicator($active[0])\n });\n\t\t}\n\t\tonPageLoad();\n\t}",
"function NovVerticalToggleMobile() {\n $('.header-4 .verticalmenu .toggle-nav').on('click', function(e) {\n if ($('.verticalmenu-content').hasClass('show')) {\n $('.verticalmenu-content').removeClass('show');\n $(this).removeClass('act');\n } else {\n if ($('.verticalmenu-content').hasClass('active')) {\n $('.verticalmenu-content').removeClass('active');\n $(this).removeClass('act');\n } else {\n $('.verticalmenu-content').addClass('active');\n $(this).addClass('act');\n }\n }\n $('.verticalmenu-content').hasClass('active') ? ( $('.verticalmenu-content').removeClass('active').removeClass('show'), $(this).removeClass('act') ) : ( $('.verticalmenu-content').addClass('active').removeClass('show'), $(this).addClass('act') );\n e.stopPropagation();\n });\n $(document).on('click', function(vl) {\n if ($(vl.target).is('.verticalmenu-content')==false) {\n $('.verticalmenu-content').removeClass('active');\n $('.verticalmenu .toggle-nav').removeClass('act');\n }\n });\n}",
"function cbase_adjust_admin_tools() {\n var side = $(\"#admin-toolbar .admin-blocks, #admin-toolbar .admin-toggle\");\n\n if (side.length > 0) {\n // If the admin menu is to be rendered on this page, listen for it to be\n // added then adjust the sidebar.\n if (Drupal.settings.admin_menu) {\n toplisten = setInterval(function() {\n var menu = $(\"#admin-menu\");\n\n // If the menu has loaded, slide the sidebar and stop the itterations.\n if (menu.length > 0) {\n side.animate({'top': menu.inScrollView('top')});\n clearInterval(toplisten);\n }\n }, 250);\n }\n\n $(window).scroll(function() {\n var menu = $(\"#admin-menu\");\n if (menu.length > 0) {\n side.css({'top': menu.inScrollView('top')});\n }\n });\n }\n }",
"async closeMenu() {\n const closeMenuLocator = await this.components.menuCloseButton()\n await closeMenuLocator.click()\n }",
"function loadAdminMenu() {\n\tvar adminMenu;\n\tadminMenu = '<div id=\"AdminMenuWrap\">';\n\t\tadminMenu += '<ul id=\"AdminMenu\">';\n\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com\"><i class=\"fa fa-lg fa-fw fa-home\"></i>Frontpage</a></li>';\n\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/wikis/1835\"><i class=\"fa fa-lg fa-fw fa-book\"></i>Rules</a></li>';\n\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/wikis/16\"><i class=\"fa fa-lg fa-fw fa-users\"></i>Contacts</a></li>';\n\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/wikis/cats/1\"><i class=\"fa fa-lg fa-fw fa-briefcase\"></i>ModDocs</a></li>';\n\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/admin/modlog\"><i class=\"fa fa-lg fa-fw fa-binoculars\"></i>ModLog</a></li>';\n\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/admin/flaggedsubs\"><i class=\"fa fa-lg fa-fw fa-flag\"></i>Flagged Submissions</a></li>';\n\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/admin/withheld\"><i class=\"fa fa-lg fa-fw fa-legal\"></i>Withheld Submissions</a></li>';\n\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/admin/catmod\"><i class=\"fa fa-lg fa-fw fa-folder-open\"></i>Pending Categories</a></li>';\n\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/support\"><i class=\"fa fa-lg fa-fw fa-support\"></i>Support Tickets</a></li>';\n\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/bugs\"><i class=\"fa fa-lg fa-fw fa-bug\"></i>Bug Reports</a></li>';\n\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/ideas\"><i class=\"fa fa-lg fa-fw fa-lightbulb-o\"></i>Suggested Ideas</a></li>';\n\t\t\tadminMenu += '<li class=\"SubMenuHeader\"><i class=\"fa fa-lg fa-fw fa-comments\"></i>Forums<i class=\"fa fa-lg fa-fw fa-angle-right\"></i>';\n\t\t\tadminMenu += '<ul class=\"SubMenu\">';\n\t\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/game/threads/cats/3563\"><i class=\"fa fa-lg fa-fw fa-commenting\"></i>AdminTalk</a></li>';\n\t\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/game/threads/cats/783\"><i class=\"fa fa-lg fa-fw fa-commenting\"></i>ModTalk</a></li>';\n\t\t\tadminMenu += '</ul></li>';\n\t\t\tadminMenu += '<li class=\"SubMenuHeader\"><i class=\"fa fa-lg fa-fw fa-wrench\"></i>Tools<i class=\"fa fa-lg fa-fw fa-angle-right\"></i>';\n\t\t\tadminMenu += '<ul class=\"SubMenu\">';\n\t\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/admin/bananabank\"><i class=\"fa fa-lg fa-fw fa-bank\"></i>BananaBank</a></li>';\n\t\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/admin/recordselector\"><i class=\"fa fa-lg fa-fw fa-server\"></i>RecordSelector</a></li>';\n\t\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/admin/reportmaker\"><i class=\"fa fa-lg fa-fw fa-file-text-o\"></i>ReportMaker</a></li>';\n\t\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/admin/ipsearch\"><i class=\"fa fa-lg fa-fw fa-terminal\"></i>IP Search</a></li>';\n\t\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/ip-blocks\"><i class=\"fa fa-lg fa-fw fa-terminal\"></i>IP Blocker</a></li>';\n\t\t\tadminMenu += '</ul></li>';\n\t\t\tadminMenu += '<li class=\"SubMenuHeader\"><i class=\"fa fa-lg fa-fw fa-bullhorn\"></i>Promotional<i class=\"fa fa-lg fa-fw fa-angle-right\"></i>';\n\t\t\tadminMenu += '<ul class=\"SubMenu\">';\n\t\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/contest-winners\"><i class=\"fa fa-lg fa-fw fa-trophy\"></i>Contest Winners</a></li>';\n\t\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/features\"><i class=\"fa fa-lg fa-fw fa-tv\"></i>Features</a></li>';\n\t\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/newsletters\"><i class=\"fa fa-lg fa-fw fa-newspaper-o\"></i>Newsletters</a></li>';\n\t\t\tadminMenu += '</ul></li>';\n\t\t\tadminMenu += '<li class=\"SubMenuHeader\"><i class=\"fa fa-lg fa-fw fa-info-circle\"></i>GB Admin Toolbox<i class=\"fa fa-lg fa-fw fa-angle-right\"></i>';\n\t\t\tadminMenu += '<ul class=\"SubMenu\">';\n\t\t\t\tadminMenu += '<li><a href=\"https://github.com/yogensia/gb-toolbox#readme\"><i class=\"fa fa-lg fa-fw fa-file-text-o\"></i>Readme</a></li>';\n\t\t\t\tadminMenu += '<li><a href=\"https://github.com/yogensia/gb-toolbox#changelog\"><i class=\"fa fa-lg fa-fw fa-gear\"></i>Changelog</a></li>';\n\t\t\t\tadminMenu += '<li><a href=\"https://github.com/yogensia/gb-toolbox/issues\"><i class=\"fa fa-lg fa-fw fa-exclamation-circle\"></i>Known Issues / TODO</a></li>';\n\t\t\t\tadminMenu += '<li><a href=\"https://gamebanana.com/threads/198550\"><i class=\"fa fa-lg fa-fw fa-envelope\"></i>Send Feedback</a></li>';\n\t\t\t\tadminMenu += '<li class=\"AdminMenuHeader\"><i class=\"fa fa-lg fa-fw fa-check\"></i>Version '+GAT_VERSION+'</li>';\n\t\t\tadminMenu += '</ul></li>';\n\t\tadminMenu += '</ul>';\n\tadminMenu += '</div>';\n\t$(\"#Wrapper\").append(adminMenu);\n}",
"function _showAddTileMenu() {\n topAppBar.winControl.hide();\n div_cockpits_bottomAppBar.winControl.hide();\n RightMenu.showRightMenu(Pages.formatTileStep, null);\n }",
"function backToLoseMenu() {\n changeVisibility(\"menu\");\n changeVisibility(\"loseScreen\");\n} // backToLoseMenu",
"function backToWinMenu() {\n changeVisibility(\"menu\");\n changeVisibility(\"winScreen\");\n} // backToWinMenu",
"function showLoggedInMenu(){\n\t\t$('#signup, #login').hide();\n\t\t$('#logout').show();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a tonic and a chord list expressed with roman numeral notation returns the progression expressed with leadsheet chords symbols notation | function fromRomanNumerals(tonic, chords) {
const romanNumerals = chords.map(romanNumeral);
return romanNumerals.map(rn => transpose(tonic, interval(rn)) + rn.chordType);
} | [
"function toRomanNumerals(tonic, chords) {\n return chords.map(chord => {\n const [note, chordType] = tokenize(chord);\n const intervalName = distance(tonic, note);\n const roman = romanNumeral(interval(intervalName));\n return roman.name + chordType;\n });\n}",
"function immediateRenderChord(MIDINumbers, duration = \"\"){\n\tmusicalElements = \"[\";\n\tfor(var i = 0; i < MIDINumbers.length; i++){\n\t\tmusicalElements += MIDINotes.MIDINoteToABCNote(MIDINumbers[i]) + duration + \" \";\n\t}\n\tmusicalElements += \"]\";\n\t\n\trenderNotation();\n}",
"function getChord() {\n //get all playing keys\n var keys = document.querySelectorAll(\".key.playing\");\n\n //if less than 2 keys there is no chord, return blank\n if (keys.length < 2) {\n return \"\";\n }\n\n //get bass note (lowest playing note)\n var bass = keys[0].dataset.note;\n //get indicies of currently playing notes\n var indicies = [];\n for (i = 0; i < keys.length; i++) {\n indicies.push(keys[i].dataset.pos);\n }\n\n //test every note as a potential root in order\n for (i = 0; i < keys.length; i++) {\n //set current root to test\n var root = i;\n\n //get intervals of all notes from root; stored as a set\n let intervals = new Set();\n for (j = 0; j < indicies.length; j++) {\n //get interval between root and current note\n //if current note is < root shift it an octave up for calculations\n if ((indicies[j] % 12) < (indicies[root] % 12)) {\n var interval = Math.abs(((indicies[j] % 12) + 12) - (indicies[root] % 12));\n }\n else {\n var interval = Math.abs((indicies[j] % 12) - (indicies[root] % 12));\n }\n //mudolo to remove compound intervals\n interval = interval % 12;\n //add interval to set of intervals\n intervals.add(interval);\n }\n\n //loop through every chord in the chord db\n for (j = 0; j < chords.length; j++) {\n //if match found return chord\n if (chordEq(chords[j].intervals, intervals)) {\n //add root note and notation to chord display\n var chord = keys[root].dataset.note + chords[j].notation;\n //if bass note is different from the root add it\n if (bass != keys[root].dataset.note) {\n chord += \"\\\\\" + bass;\n }\n\n return chord\n }\n }\n }\n \n //nothing found; return blank\n return \"\";\n}",
"function printChords(inp){\n var result = [\"\",\"\"]; //output lines\n var str = inp; //local copy of input for modifying\n var offset = 0; //offset caused by pasting the last chord (e.g. Esus2 shifts the following E 5 characters over)\n\n while(str.indexOf(\"[\") != -1){\n //all chords are of the format [chord], find it by finding [ and ]\n var leftBrace = str.indexOf(\"[\");\n var rightBrace = str.indexOf(\"]\");\n\n //take the lyrics from start to [\n result[0] += str.substring(0,leftBrace);\n\n //pad spaces to where the chord belongs on the chord line\n for(i = offset; i < leftBrace; i++)\n result[1] += \" \";\n if(leftBrace < offset) result[1] += \" \"; //if no padding was added (two chords in a row), add a space\n\n //get the chord from between the braces\n result[1] += str.substring(leftBrace+1, rightBrace);\n offset = rightBrace-leftBrace;\n\n //str = remainder of string after ]\n str = str.substring(rightBrace+1, 999).trim();\n }\n result[0] += str;\n console.log(result[1] .green);\n console.log(result[0] .yellow);\n}",
"function getBasicChord(chord) {\n\tchordNotes = [1, 5, 8, 10];\n\treturn chordNotes.map(rel => getIntervalNote(chord + chordData.baseOctave, rel));\n}",
"function jtabChord (token) {\n\n this.scale = jtab.WesternScale;\n this.baseNotes = this.scale.BaseNotes;\n this.baseChords = jtab.Chords;\n this.chordArray = null;\n this.isValid = false;\n\n this.fullChordName = token;\n this.isCustom = ( this.fullChordName.match( /\\%/ ) != null )\n this.isCaged = ( this.fullChordName.match( /\\:/ ) != null )\n\n\n if (this.isCaged) {\n var parts = this.fullChordName.split(':');\n this.chordName = parts[0];\n this.cagedPos = parts[1];\n } else if (this.isCustom){\n var parts = this.fullChordName.match( /\\[(.+?)\\]/ );\n if(parts){\n this.chordName = parts[1];\n } else {\n this.chordName = '';\n }\n } else {\n this.chordName = this.fullChordName;\n this.cagedPos = 1;\n }\n this.rootExt = this.chordName.replace(/^[A-G#b]{1,2}/,'');\n this.rootNote = this.chordName.substr(0, this.chordName.length - this.rootExt.length);\n var baseNoteInfo = this.baseNotes[this.rootNote];\n if (baseNoteInfo) {\n this.baseName = baseNoteInfo[0] + this.rootExt;\n this.cagedBaseShape = baseNoteInfo[1];\n this.cagedBaseFret = baseNoteInfo[2];\n } else {\n this.cagedBaseShape = '';\n this.cagedBaseFret = 0;\n }\n if ( ( this.isCaged ) && ( this.cagedPos > 1 ) ) {\n this.setCagedChordArray();\n } else if (this.isCustom){\n this.setCustomChordArray();\n } else {\n this.setChordArray(this.baseName);\n }\n}",
"drawSequence() {\n\n // chords which are used in the sequence (in the correct order!)\n this.chords = ['C', 'F', 'G', 'Am'];\n\n // get the current sequence\n this.sequence = this.musicMenu.getSequence();\n\n this.chordTexts = [];\n let chord;\n\n // draw each chord of the sequence\n for (let i in this.sequence) {\n\n chord = this.add.text(this.xStart + i * this.distance, this.yPosition, this.chords[this.sequence[i]], this.styles.get(7)).setOrigin(0.5);\n this.chordTexts.push(chord);\n\n }\n\n }",
"printPascal2 ( n) {\n for (let line = 1; line <= n; line++)\n {\n let C = 1; // used to represent C(line, i)\n\n let str = \" \";\n for (let i = 1; i <= line; i++)\n {\n str += C + \" \";\n // The first value in a line is always 1\n C = C * (line - i) / i;\n }\n console.log(str);\n }\n }",
"function romanToInteger(string) {\n let count = 0;\n\n for (i = 0; i < string.length; i++) {\n console.log(\"i, string[i], count\",i,string[i],count)\n if (string[i] === \"I\") {\n if (string[i+1] === \"V\") {\n count+= 4;\n i++;\n }\n else if(string[i+1] === \"X\") {\n count+=9;\n i++;\n } else {\n count+=1;\n }\n }\n\n else if (string[i] === \"V\") {\n count+= 5;\n }\n\n else if (string[i] === \"X\") {\n if (string[i+1] === \"L\") {\n count+= 40;\n i++;\n }\n if (string[i+1] === \"C\") {\n count+= 90;\n i++;\n } else {\n count+= 10;\n }\n }\n\n else if (string[i] === \"L\") {\n count+= 50;\n }\n\n else if (string[i] === \"C\") {\n if (string[i+1] === \"D\") {\n count+= 400;\n i++;\n }\n else if (string[i+1] === \"M\") {\n count+= 900;\n i++;\n } else {\n count+= 100;\n }\n }\n\n else if (string[i] === \"D\") {\n count+= 500;\n }\n\n else if (string[i] === \"M\") {\n count+= 1000;\n }\n \n }\n return count;\n }",
"function Identify_Chord_Seventh(a, b, c, d) {\n\t// (M3, m3 Chords)\n\n\t\tif (Identify_Interval(a, b) === \"M3\"){\n\t\t\tif (Identify_Interval(b, c) === \"m3\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"m3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = d;\n\t\t\t\t\treturn (a + \" Major Minor 7th\")}\t\n\t\t\t\tif (Identify_Interval(c, d) === \"M3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = d;\n\t\t\t\t\treturn (a + \" Major 7th\")\t}\n\t\t\t\tif (Identify_Interval(c, d) === \"M2\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = c;\n\t\t\t\t\treturn (d + \" Minor 7th (First Inversion)\")}\n\t\t\t}\n\t\t}\n\t\t\t\n\t// (M3, m2 Chords)\t\n\t\tif (Identify_Interval(a, b) === \"M3\"){\n\t\t\tif (Identify_Interval(b, c) === \"m2\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"m3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = b;\n\t\t\t\t\treturn (c + \" Minor Major 7th (Second Inversion)\")}\t\t\n\t\t\t\tif (Identify_Interval(c, d) === \"M3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = b;\n\t\t\t\t\treturn (c + \" Major 7th (Second Inversion)\")}\t\n\t\t\t}\n\t\t}\n\n\t// (M3, Misc. Chords)\n\t\tif (Identify_Interval(a, b) === \"M3\"){\n\t\t\tif (Identify_Interval(b, c) === \"M2\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"m3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = b;\n\t\t\t\t\treturn (c + \" Half Diminished 7th (Second Inversion)\")}\n\t\t\t\t}\n\t\t\tif (Identify_Interval(b, c) === \"M3\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"m2\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = c;\n\t\t\t\t\treturn (d + \" Minor Major 7th (First Inversion)\")}\n\t\t\t\t}\n\t\t}\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t// (m3, M3 Chords)\n\t\tif (Identify_Interval(a, b) === \"m3\"){\n\t\t\tif (Identify_Interval(b, c) === \"M3\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"m3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = d;\n\t\t\t\t\treturn (a + \" Minor 7\")}\n\t\t\t\tif (Identify_Interval(c, d) === \"M3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = d;\n\t\t\t\t\treturn (a + \" Minor Major 7\")}\n\t\t\t\tif (Identify_Interval(c, d) === \"m2\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = c;\n\t\t\t\t\treturn (d + \" Major 7th (First Inversion)\")}\n\t\t\t\tif (Identify_Interval(c, d) === \"M2\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = c;\n\t\t\t\t\treturn (d + \" Half Diminished 7th (First Inversion)\")}\n\t\t\t}\n\t\t}\n\n\t// (m3, m3 Chords)\n\t\tif (Identify_Interval(a, b) === \"m3\"){\n\t\t\tif (Identify_Interval(b, c) === \"m3\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"M2\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = c;\n\t\t\t\t\treturn (d + \" Major Minor 7th (First Inversion)\")}\n\t\t\t\tif (Identify_Interval(c, d) === \"m3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = d;\n\t\t\t\t\treturn (a + \" Fully Diminished 7th\")}\n\t\t\t\tif (Identify_Interval(c, d) === \"Augmented 2nd\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = c;\n\t\t\t\t\treturn (d + \" Fully Diminished 7th (First Inversion)\")}\n\t\t\t\tif (Identify_Interval(c, d) === \"M3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = d;\n\t\t\t\t\treturn (a + \" Half Diminished 7th\")}\n\t\t\t}\n\t\t}\t\t\t\n\n\t// (m3, M2 Chords)\n\t\tif (Identify_Interval(a, b) === \"m3\"){\n\t\t\tif (Identify_Interval(b, c) === \"M2\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"M3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = b;\n\t\t\t\t\treturn (c + \" Major Minor 7th (Second Inversion)\")}\n\t\t\t\tif (Identify_Interval(c, d) === \"m3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = b;\n\t\t\t\t\treturn (c + \" Minor 7th (Second Inversion)\")}\n\t\t\t}\n\t\t}\n\n\t// (The Sole Diminished Chord)\n\t\tif (Identify_Interval(a, b) === \"m3\"){\n\t\t\tif (Identify_Interval(b, c) === \"Augmented 2nd\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"m3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = a;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = b;\n\t\t\t\t\treturn (c + \" Fully Diminished 7th (Second Inversion)\")}\n\t\t\t}\n\t\t}\n\n\t// (M2, m3 Chords)\n\t\tif (Identify_Interval(a, b) === \"M2\"){\n\t\t\tif (Identify_Interval(b, c) === \"m3\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"M3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = a;\n\t\t\t\t\treturn (b + \" Minor 7th (Third Inversion)\")}\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\tif (Identify_Interval(c, d) === \"m3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = a;\n\t\t\t\t\treturn (b + \" Half Diminished 7th (Third Inversion)\")}\n\t\t\t}\n\t\t}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t// (M2 Chord)\n\t\tif (Identify_Interval(a, b) === \"M2\"){\n\t\t\tif (Identify_Interval(b, c) === \"M3\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"m3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = a;\n\t\t\t\t\treturn (b + \" Major Minor 7th (Third Inversion)\")}\n\t\t\t}\n\t\t}\n\n\t// (m2 Chord)\n\t\tif (Identify_Interval(a, b) === \"m2\"){\n\t\t\tif (Identify_Interval(b, c) === \"M3\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"m3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = a;\n\t\t\t\t\treturn (b + \" Major 7th (Third Inversion)\")}\n\t\t\t}\n\t\t\tif (Identify_Interval(b, c) === \"m3\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"M3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = a;\n\t\t\t\t\treturn (b + \" Minor Major 7th (Third Inversion)\")}\n\t\t\t}\n\t\t}\t\t\t\t\t\t\t\t\t\t\n\t\tif (Identify_Interval(a, b) === \"Augmented 2nd\"){\n\t\t\tif (Identify_Interval(b, c) === \"m3\"){\n\t\t\t\tif (Identify_Interval(c, d) === \"m3\"){\n\t\t\t\t\tdocument.getElementById(\"root\").innerHTML = b;\n\t\t\t\t\tdocument.getElementById(\"third\").innerHTML = c;\n\t\t\t\t\tdocument.getElementById(\"fifth\").innerHTML = d;\n\t\t\t\t\tdocument.getElementById(\"seventh\").innerHTML = a;\n\t\t\t\t\treturn (b + \" Fully Diminished 7th (Third Inversion)\")}\n\t\t\t}\n\t\t}\n\t}",
"function displayChord(el) {\n // first, clear the diagram that involves toggling so we can reuse functions\n clearDiagram();\n\n pressedDownStrings = getByValue(chordMap, el.innerHTML).split(',');\n\n for(let i = 0; i < pressedDownStrings.length; ++i) {\n pressedDownStrings[i] = parseInt(pressedDownStrings[i]);\n }\n\n\n for(let i = 1; i <= 6; ++i) {\n if(pressedDownStrings[i] == -1) {\n // set closed string to closed\n toggleStringClosed(document.getElementById(\"string-\"+i));\n }\n // if it's an open chord do nothing\n else if(pressedDownStrings[i] != 0) {\n let id = pressedDownStrings[i]+'-'+i;\n toggleClick(document.getElementById(pressedDownStrings[i]+'-'+i));\n }\n }\n\n // really setting the barre :)\n if(pressedDownStrings[0] != 0) {\n let barreInput = document.getElementById(\"barre-input\");\n barreInput.value = pressedDownStrings[0];\n\n doBarreGraphic(barreInput);\n }\n}",
"function findCadence(chords) {\n\tif (chords[chords.length - 2] === \"V\" && chords[chords.length - 1] === \"I\") {\n\t\treturn \"perfect\";\n\t} else if (chords[chords.length - 2] === \"IV\" && chords[chords.length - 1] === \"I\") {\n\t\treturn \"plagal\";\n\t} else if (chords[chords.length - 2] === \"V\" && chords[chords.length - 1] !== \"I\") {\n\t\treturn \"interrupted\";\n\t} else if (chords[chords.length - 1] === \"V\") {\n\t\treturn \"imperfect\";\n\t} else return \"no cadence\";\n}",
"function DrawChord(trips){\n\tvar streetnames = []\n\tfor (var i = 0; i < trips.length; i++) {\n\t\tfor (var j = 0; j < trips[i].streetnames.length; j++) {\n\t\t\tstreetnames.push(trips[i].streetnames[j]);\n\t\t}\n\t}\n\t\n\tvar myConfig = {\n\t\t\"type\": \"chord\",\n\t\tplot:{\n\t\t\tanimation:{\n\t\t\t effect: 4,\n\t\t\t method: 0,\n\t\t\t sequence: 1\n\t\t\t}\n\t\t},\n\t\t\"options\": {\n\t\t \"radius\": \"90%\"\n\t\t},\n\t\t\"plotarea\": {\n\t\t \"margin\": \"dynamic\"\n\t\t},\n\t\t\"series\": [{\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Street Names\"\n\t\t}, {\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Average Speed\"\n\t\t}, {\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Distance\"\n\t\t}, {\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Duration\"\n\t\t}]\n\t };\n\t \n\t zingchart.render({\n\t\tid: 'myChart',\n\t\tdata: myConfig,\n\t\theight: \"100%\",\n\t\twidth: \"100%\",\n\t });\n}",
"function getSimpleChord(chord, inversion, numBaseNotes, numBright, numDark, isSparse) {\n\tchordNotes = [chord + chordData.baseOctave];\n\n\tif (isSparse) {\n\t\t// slice to remove notes below inversion\n\t\tsliceStart = 1;\n\t\tif (inversion > 2) {\n\t\t\tsliceStart = 2;\n\t\t}\n\n\t\tbasicNotes = chordData.basicChordNotes.slice(sliceStart, chordData.basicChordNotes.length);\n\t\tchordNotes = basicNotes.sort(() => 0.5 - Math.random()).slice(0, numBaseNotes);\n\t\tchordNotes = chordNotes.concat([chordData.inversions[inversion - 1]]);\n\t} else {\n\t\tchordNotes = chordData.basicChordNotes.slice(0, numBaseNotes);\n\t}\n\n\tbrightNotes = chordData.colorNotes.bright;\n\tdarkNotes = chordData.colorNotes.dark;\n\n\t// should be encapsulated within dark / bright notes...\n\t// replace tritones with major seconds (F-B to F-G)\n\t// replace root minor seconds with major fourths (B-C to B-E) (E-F to E-A)\n\trootNote = chord.match(/[A-Z]+/g)[0];\n\tdebugMusic(rootNote + chordData.baseOctave);\n\tfor (var i = 0; i < darkNotes.length; i++) {\n\t\tdarkNote = getIntervalNote(rootNote + chordData.baseOctave, darkNotes[i]).match(/[A-Z#b]+/g)[0];\n\t\tinterval = getSemitoneInterval(rootNote, darkNote);\n\t\tswitch (interval) {\n\t\t\tcase 1:\n\t\t\t\tdarkNotes[i] = 4;\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\tdarkNotes[i] = 2;\n\t\t}\n\t}\n\tfor (var i = 0; i < brightNotes.length; i++) {\n\t\tbrightNote = getIntervalNote(rootNote + chordData.baseOctave, brightNotes[i]).match(/[A-Z#b]+/g)[0];\n\t\tinterval = getSemitoneInterval(rootNote, brightNote);\n\n\t\tswitch (interval) {\n\t\t\tcase 1:\n\t\t\t\tbrightNotes[i] = 11;\n\t\t\t\tbreak;\n\t\t\tcase 6:\n\t\t\t\tbrightNotes[i] = 9;\n\t\t}\n\t}\n\n\tif (isMinor(chord)) {\n\t\t// for (var i = 0; i < darkNotes.length; i++) {\n\t\t// \tif (darkNotes[i] == 2) {\n\t\t// \t\tdarkNotes[i] = 4;\n\t\t// \t}\n\t\t// }\n\t\tfor (var i = 0; i < brightNotes.length; i++) {\n\t\t\tif (brightNotes[i] == 13) {\n\t\t\t\tbrightNotes[i] = 11;\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\tchordNotes = chordNotes.concat(brightNotes.sort(() => 0.5 - Math.random()).slice(0, numBright));\n\tchordNotes = chordNotes.concat(darkNotes.sort(() => 0.5 - Math.random()).slice(0, numDark));\n\n\tchordNotes = chordNotes.sort((a, b) => a - b);\n\treturn chordNotes.map(rel => getIntervalNote(rootNote + chordData.baseOctave, rel));\n}",
"function romanNumeralReduction(str) {\n // code goes here\n return str;\n}",
"function pinyinToneNumToMark( str )\n{\n\tvar strArray = str.split(\" \");\n\tvar retStr = \"\";\n\tfor( var i=0; i<strArray.length; i++)\n\t{\n\t\tretStr = retStr + placeTonePerWord(strArray[i]);\n\t\tif ( i<(strArray.length - 1) )\n\t\t{\n\t\t\tretStr = retStr + \" \";\n\t\t}\n\t}\n\treturn( retStr );\n}",
"function checkIfChord() {\n let chordName = chordMap[pressedDownStrings.toString()];\n\n if(chordName) {\n let ch = chordName.charAt(0);\n let isVowel = (ch == 'A' || ch == 'E');\n ch = (isVowel ? 'n' : '');\n document.getElementById('chordText').innerHTML = `This is a${ch} ${chordName}`;\n\n }\n else\n document.getElementById('chordText').innerHTML = \"I don't know this chord\";\n}",
"function translate(codonString = '') {\n const TO_AMINO_ACID = {\n AUG: 'Methionine',\n UUU: 'Phenylalanine',\n UUC: 'Phenylalanine',\n UUA: 'Leucine',\n UUG: 'Leucine',\n UCU: 'Serine',\n UCC: 'Serine',\n UCA: 'Serine',\n UCG: 'Serine',\n UAU: 'Tyrosine',\n UAC: 'Tyrosine',\n UGU: 'Cysteine',\n UGC: 'Cysteine',\n UGG: 'Tryptophan',\n UAA: 'STOP',\n UAG: 'STOP',\n UGA: 'STOP',\n }\n\n let res = [];\n\n for (let idx = 0; idx < codonString.length; idx += 3) {\n let codon = codonString.slice(idx, idx + 3);\n \n console.log(codon);\n let acid = TO_AMINO_ACID[codon];\n\n if (!acid) throw new Error(\"Invalid codon\");\n if (acid === 'STOP') return res;\n \n res.push(acid);\n }\n\n return res;\n}",
"function mouseoverChord(d,i) {\n\t\t//Decrease opacity to all\n\t\tsvg.selectAll(\"path.chord\")\n\t\t\t.transition()\n\t\t\t.style(\"opacity\", 0.1);\n\t\t//Show hovered over chord with full opacity\n\t\td3.select(this)\n\t\t\t.transition()\n\t\t\t.style(\"opacity\", 1);\n\t\t//correct log\n\t\t//console.log(\"i: \" + d.source.index);\n\t\t//Define and show the tooltip over the mouse location\n\t\t$(this).popover({\n\t\t\t//placement: 'auto top',\n\t\t\ttitle: function() {return names[d.source.index];},\n\t\t\tplacement: 'auto',\n\t\t\tcontainer: 'body',\n\t\t\tanimation: false,\n\t\t\tfollowMouse: true,\n\t\t\ttrigger: 'click',\n\t\t\thtml : true,\n\t\t\tcontent: function() {\n\t\t\treturn \"<p style='font-size: 11px; text-align: center;'><span style='font-weight:900'>\" + names[d.target.index] + \"</span> is embedded in \" + \"<span style='font-weight:900'>\" + names[d.source.index] + \"</span><span style='font-weight:900'></span></p>\"; }\n\t\t});\n\t\t$(this).popover('show');\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a numeric value from a string containing a rank | function getValueOfRank(rank) {
let value = ranks[rank.toLowerCase()];
if (value) {
return value;
}
return -1;
} | [
"function getRankingFromIntent(intent) {\n\n var rankingSlot = intent.slots.Ranking;\n\n if (!rankingSlot || !rankingSlot.value) {\n return 0;\n } else {\n\n return rankingSlot.value;\n }\n}",
"function parseNum(){\n var pattern = /[0-9]+/;\n //If the we have set text to be the game map string, then we execute the following code.\n if(text){\n //This sets result to be either null (if the pattern was not found), or a string of \n // what we are looking for. It parses text, looking for pattern. And returns the \n // either a string, or null. Pattern tells exec that it wants to take the first \n // sequence of numbers from text that appear, and ignore everything else. In the \n // case of the default Frupal map, the first sequence of numbers that appear is \"25\". \n // Thus, result would contain: \"25\"\n var result = pattern.exec(text);\n //This takes text - which is the game map string - and takes a substring of it\n // and stores that substring back to text. The substring it takes starts at position\n // (index of where result first starts to appear in text offset by the length of result)\n // and continues to the length of the whole game map string. Thus, effectively, anything\n // that was written in \"text\" before result appears, and result itself get discarded from\n // the game map string.\n text = text.slice(result.index + result[0].length, text.length);\n //This Parses result to an integer (because result is an integer in string form right now)\n // and then returns it.\n return parseInt(result);\n }\n}",
"function regularizeRank(rank) {\n return ((31 - rank) / 30 * 100).toFixed(1);\n}",
"function loadRank() {\n let resolvedRankString = [];\n let rowRankString = getCookie('rank');\n if (rowRankString) {\n rowRankString = rowRankString.split('&')\n for (let pairs of rowRankString) {\n pairs = pairs.split('@');\n resolvedRankString.push(pairs);\n }\n rank = resolvedRankString;\n }\n}",
"function extUtils_getWeightNum(weight)\n{\n if (typeof weight == \"string\")\n {\n var pos = weight.indexOf(\"+\");\n weight = parseInt((pos > 0)? weight.substring(pos+1) : weight);\n }\n\n return weight;\n}",
"function toNumber(isRow = true, str = \"\") {\n\n // do nothing if invalid input\n if(str.length == 0) return;\n\n if(isRow) {\n return rows.indexOf(str) + 1;\n }\n\n return cols.indexOf(str) + 1;\n\n}",
"function findRank(team, stat){\n var rank = 30 - (vis.ranks[stat].findIndex(function(e) {\n return e.TEAM == team;\n }))\n\n return rank\n }",
"function get_quantity(searchstring, itemname){\n if(!isArray(searchstring)){searchstring = searchstring.split(\" \")}//should already be processed by replacesynonyms\n for(var searchindex = 0; searchindex<searchstring.length; searchindex++){\n if(isNumeric( searchstring[searchindex] )){\n if(itemname.indexOf( searchstring[searchindex] ) == -1) {//make sure the number isn't part of the item name\n return searchindex;\n }\n }\n }\n return -1;\n}",
"function marketCapToNum(mcString) {\r\n if (!mcString) {\n return;\n }\r\n const suffix = mcString.charAt(mcString.length-1);\r\n let mcNum;\r\n switch(suffix) {\r\n // billions\r\n case \"B\":\r\n mcNum = Number(mcString.replace(\"B\", \"\")) * 1000000000;\r\n break;\r\n // millions\r\n case \"M\":\r\n mcNum = Number(mcString.replace(\"M\", \"\")) * 1000000;\r\n break;\r\n // < 1 million, no suffix, remove commas\r\n default:\r\n mcNum = Number(mcString.replace(\",\", \"\"));\r\n }\r\n return mcNum;\r\n }",
"function getNumericalPart(s) {\n return parseFloat(s); //apparently I don't actually need to remove the % (or anything else) from the string before I do the conversion\n}",
"function parseSeasonNum(link) {\n return parseInt(link.split(\"no\")[1].split(\"-\")[0]);\n}",
"get rank(): string {\n if (!this.cachedRank) {\n this.cachedRank = Config.cardRanks[this.id % Config.cardRanks.length];\n }\n\n return this.cachedRank;\n }",
"setRank(rank)\n\t{\n\t\tswitch (rank)\n\t\t{\n\t\tcase'2':\n\t\tcase'3':\n\t\tcase'4':\n\t\tcase'5':\n\t\tcase'6':\n\t\tcase'7':\n\t\tcase'8':\n\t\tcase'9':\n\t\tcase'J':\n\t\tcase'Q':\n\t\tcase'K':\n\t\tcase'A':\n\t\tcase'j':\n\t\tcase'q':\n\t\tcase'k':\n\t\tcase'a':\n\t\tcase't':\n\t\tcase'T':\n\t\t\tthis.rank = rank.toUpperCase();\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcerr(\"invalid rank: \" + rank);\n\t\t\tbreak;\n\t\t}\n\t}",
"async _strToInt(topEmployeeName, topEmployee) {\n let salesArr = topEmployeeName.split(\" \")\n let sales = salesArr[0]\n let num = salesArr[2]\n let number = parseInt(num, 10)\n console.log(`${topEmployee}: ${sales} ${number}`)\n logger.info(`${topEmployee}: ${sales} ${number}`)\n return number \n }",
"function getZATNrFromCell(cell) {\r\n const __TEXT = cell.textContent.split(' ');\r\n let ZATNr = 0;\r\n\r\n for (let i = 1; (ZATNr === 0) && (i < __TEXT.length); i++) {\r\n if (__TEXT[i - 1] === \"ZAT\") {\r\n if (__TEXT[i] !== \"ist\") {\r\n ZATNr = parseInt(__TEXT[i], 10);\r\n }\r\n }\r\n }\r\n return ZATNr;\r\n}",
"rank(word){cov_25grm4ggn6.f[6]++;cov_25grm4ggn6.s[27]++;if(!word){cov_25grm4ggn6.b[10][0]++;cov_25grm4ggn6.s[28]++;return 0;}else{cov_25grm4ggn6.b[10][1]++;}cov_25grm4ggn6.s[29]++;if(!word.length){cov_25grm4ggn6.b[11][0]++;cov_25grm4ggn6.s[30]++;return 0;}else{cov_25grm4ggn6.b[11][1]++;}cov_25grm4ggn6.s[31]++;if(!this.max){cov_25grm4ggn6.b[12][0]++;cov_25grm4ggn6.s[32]++;return 0;}else{cov_25grm4ggn6.b[12][1]++;}cov_25grm4ggn6.s[33]++;if(!this.maxLength){cov_25grm4ggn6.b[13][0]++;cov_25grm4ggn6.s[34]++;return 0;}else{cov_25grm4ggn6.b[13][1]++;}cov_25grm4ggn6.s[35]++;if(!this.count[word]){cov_25grm4ggn6.b[14][0]++;cov_25grm4ggn6.s[36]++;return 0;}else{cov_25grm4ggn6.b[14][1]++;}cov_25grm4ggn6.s[37]++;word=word.toString().toLowerCase();//normalize word length weighting\nlet weight=(cov_25grm4ggn6.s[38]++,word.length/this.maxLength);cov_25grm4ggn6.s[39]++;return weight*(this.count[word]/this.max);}",
"function get (str) {\n if (registers.hasOwnProperty(str))\n return Number(registers[str]);\n else if (str === \"$zero\")\n return 0;\n else\n output(\"Error getting register \" + str + \" on Line \" + line, 'e');\n}",
"function myParseInt(str) {\n\n var newString= str.replace(/ /g, '');\n var isFloat=newString.indexOf('.') != -1\n var isValidNumber=!isNaN(newString);\n var hasLetters=(newString.match(/[a-z]/i));\n var specialCharacters=!(/[~`!#$%\\^&*+=\\-\\[\\]\\\\';,/{}|\\\\\":<>\\?]/g.test(newString));\n \n if (isValidNumber && !isFloat && !hasLetters && specialCharacters){\n // Convert to number the string\n return Number(newString);\n }else{\n return \"NaN\";\n }\n}",
"function findLastNumber(str) {\n for (let i = str.length - 1; i >= 0; --i) {\n const code = str.charCodeAt(i);\n if (code >= _ZERO && code <= _NINE) {\n return i;\n }\n }\n return -1;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function sends backupdata chunk to Queue | function sendBackupDataToQueue(data,params){
var sqs = new AWS.SQS();
var boxParams = {
MessageBody: JSON.stringify(data),
QueueUrl: semusiConfig.DataBackupQueueList[backupQueueIndex],
DelaySeconds: 0
};
sqs.sendMessage(boxParams, function (err, data) {
if (err) {
console.log(err);
mail.sendAlertNotification("Alert: SQS failure.","Could not write backup data to sqs");
try{
fs.writeFile(semusiConfig.SQSFailureLog+"/"+common.getCurrentEpochTime(), data, function(err) {
if(err) {
return console.log(err);
}
});
}
catch(e){
console.log('SQSFailureLog catch error:'+JSON.stringify(e));
}
//common.returnMessage(params, 200, 'false');
//return true;
}
else {
//common.returnMessage(params, 200, 'true');
//return true;
}
});
//Change the queueindex so that next itme gets inserted to the next queue.
if(backupQueueIndex == semusiConfig.BackupQueueLength-1){
backupQueueIndex = 0;
}
else{
backupQueueIndex++;
}
} | [
"_wipeChunkedMessageQueue ( ) {\n\n this.chunkedPutMessagesAwaitingCompletion = [];\n }",
"function onQueue(data) {\n\tif (\"Error\" in data) {\n\t\tonError(data.Error);\n\t} else if (\"Value\" in data) {\n\t\tqueueSize = data.Value.length;\n\t\t$(\"#current-queue>tbody\").empty();\n\t\tfor (i = currentTrack; i < data.Value.length; i++) {\n\t\t\twriteTrackRow(data.Value[i], i + 1);\n\t\t}\n\t\tfor (i = 0; i < currentTrack; i++) {\n\t\t\twriteTrackRow(data.Value[i], i + 1);\n\t\t}\n\t}\n}",
"function send_chunk_data_fom_pos(uuid, data){\r\n \r\n let pos = data[\"position\"];\r\n let x = pos[\"x\"];\r\n let y = pos[\"y\"];\r\n\r\n get_chunk_at_pos(x, y, function(chunks){\r\n let data_to_send = {\r\n \"cmd\" : \"chunk_data\",\r\n \"data\" : {\r\n \"chunks\" : chunks\r\n }\r\n }\r\n send_message(uuid, data_to_send);\r\n });\r\n}",
"sendOneCopyShard(port, host, shards, manifest){\n let shardIdx = 0\n let orgShardId = shards[shardIdx];\n let copyIdx = 0\n let client = this.connect(port, host)\n\n client.on('data', (data) => {\n let serverResponse = JSON.parse(data).messageType\n // console.log(\"Processing shard number: \" + (shardIdx+1));\n if (shardIdx >= shards.length - 1){\n client.end();\n } else if (serverResponse === \"SUCCESS\" && shardIdx < shards.length - 1) {\n shardIdx += 1;\n orgShardId = shards[shardIdx];\n // console.log(\"Processing shard: \" + manifest[orgShardId][copyIdx]);\n let message = {\n messageType: \"STORE_FILE\",\n fileName: manifest[orgShardId][copyIdx],\n fileContent: fs.readFileSync(`./shards/${orgShardId}`)\n }\n client.write(JSON.stringify(message))\n }\n })\n\n let message = {\n messageType: \"STORE_FILE\",\n fileName: manifest[orgShardId][copyIdx],\n fileContent: fs.readFileSync(`./shards/${orgShardId}`)\n }\n \n client.write(JSON.stringify(message))\n \n }",
"flush(callback) {\n\n var callQueue = this._callQueue;\n var uploadQueue = this._uploadQueue;\n\n var waitUpload = () => {\n if (uploadQueue.idle()) {\n return callback();\n }\n\n uploadQueue.drain = () => {\n uploadQueue.drain = null;\n\n callback();\n }\n }\n\n if (callQueue.idle()) {\n return waitUpload();\n }\n callQueue.drain = () => {\n callQueue.drain = null;\n\n waitUpload();\n }\n }",
"function batchUpload() {\n var queueName = dijit.byId('vl-queue-name').getValue();\n currentType = dijit.byId('vl-record-type').getValue();\n\n var handleProcessSpool = function() {\n if( \n vlUploadQueueImportNoMatch.checked || \n vlUploadQueueAutoOverlayExact.checked || \n vlUploadQueueAutoOverlay1Match.checked) {\n\n vlImportRecordQueue(\n currentType, \n currentQueueId, \n function() {\n retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);\n }\n );\n } else {\n retrieveQueuedRecords(currentType, currentQueueId, handleRetrieveRecords);\n }\n }\n\n var handleUploadMARC = function(key) {\n dojo.style(dojo.byId('vl-upload-status-processing'), 'display', 'block');\n processSpool(key, currentQueueId, currentType, handleProcessSpool);\n };\n\n var handleCreateQueue = function(queue) {\n currentQueueId = queue.id();\n uploadMARC(handleUploadMARC);\n };\n \n if(vlUploadQueueSelector.getValue() && !queueName) {\n currentQueueId = vlUploadQueueSelector.getValue();\n uploadMARC(handleUploadMARC);\n } else {\n createQueue(queueName, currentType, handleCreateQueue, vlUploadQueueHoldingsImportProfile.attr('value'));\n }\n}",
"function tasks_queue() {\r\n let q_data = new Queue(1);\r\n q_data.push(4);\r\n q_data.push(8);\r\n q_data.push(9);\r\n q_data.push(19);\r\n\r\n q_data.parse_llist();\r\n let out = q_data.pop();\r\n let out1 = q_data.pop();\r\n let out2 = q_data.pop();\r\n let out3 = q_data.pop();\r\n console.log(\r\n \" queue gotten out \",\r\n out.value,\r\n out1.value,\r\n out2.value,\r\n out3.value\r\n );\r\n q_data.push(100);\r\n // q_data.pop();\r\n\r\n console.log(\"queueu peeking out \", q_data.peek(), q_data.is_empty());\r\n q_data.parse_llist();\r\n }",
"insertInQueue(msg,onComplete){\r\n assert.equal(typeof msg,'object','msg must be an object');\r\n assert.equal(typeof onComplete,'function','onComplete must be a function');\r\n let th = this;\r\n console.log(MODULE_NAME + ': insert new msg');\r\n this.queueMgr.insertInQueue(\r\n FATUS_QUEUE_NAME,\r\n msg,\r\n function onDone(e,v){\r\n th.addWorker();\r\n onComplete(e,v);\r\n }\r\n );\r\n }",
"function FileQueue() {\n size = 0;\n}",
"function getAllBackupProgress() {\n var backupids = [];\n var progressbars = $('.progress').find('.progress-bar').not('.complete');\n\n progressbars.each(function() {\n backupids.push((this.id).substring(0, 32));\n });\n\n if (backupids.length > 0) {\n ajax.call([{\n // Get the backup progress via webservice.\n methodname: 'core_backup_get_async_backup_progress',\n args: {\n 'backupids': backupids,\n 'contextid': contextid\n },\n }], true, true, false, timeout)[0].done(function(response) {\n updateProgressAll(response);\n checkdelay = checkdelayoriginal;\n allbackupintervalid = updateInterval(allbackupintervalid, getAllBackupProgress, checkdelayoriginal);\n }).fail(function() {\n checkdelay = checkdelay * checkdelaymultipler;\n allbackupintervalid = updateInterval(allbackupintervalid, getAllBackupProgress, checkdelay);\n });\n } else {\n clearInterval(allbackupintervalid); // No more progress bars to update, stop checking.\n }\n }",
"_checkSendBuffer() {\n\n this._d(`${this.insertIndex} / ${this.deleteIndex}.`);\n\n if ( this.insertIndex === this.deleteIndex ) {\n\n // end buffer is 'empty' => nothing to do then wait till's flled again.\n this.isLoopRunning = false ;\n this._d(\"Send loop temp stopped - empty send buffer.\");\n } else {\n if ( this.sendAr[ this.deleteIndex ] === \"\" ) {\n\n // If the command to be send if empty consider it as\n // empty buffer and exit the data send loop.\n this.isLoopRunning = false ;\n this._d(\"Sendbuffer entry empty (stopping send loop)!.\");\n } else {\n let data = this.sendAr[ this.deleteIndex ];\n this.sendAr[ this.deleteIndex ] = \"\"; // clear used buffer.\n this.deleteIndex++;\n\n if ( this.deleteIndex >= this.MAXINDEX ) {\n this.deleteIndex = 0;\n }\n this._d(`Setting deleteIndex to ${this.deleteIndex}.`);\n\n this._sendToAvr( data );\n }\n }\n }",
"function jsonq_send()\n\t{\n\t\tif (jsonq_uid > 0 && typeof jsonq_queue['u'+(jsonq_uid-1)] == 'object')\n\t\t{\n\t\t\tvar jobs_to_send = {};\n\t\t\tvar something_to_send = false;\n\t\t\tfor(var uid in jsonq_queue)\n\t\t\t{\n\t\t\t\tvar job = jsonq_queue[uid];\n\n\t\t\t\tif (job.menuaction == 'send') continue;\t// already send to server\n\n\t\t\t\t// if job has a callbeforesend callback, call it to allow it to modify pararmeters\n\t\t\t\tif (typeof job.callbeforesend == 'function')\n\t\t\t\t{\n\t\t\t\t\tjob.callbeforesend.call(job.sender, job.parameters);\n\t\t\t\t}\n\t\t\t\tjobs_to_send[uid] = {\n\t\t\t\t\tmenuaction: job.menuaction,\n\t\t\t\t\tparameters: job.parameters\n\t\t\t\t};\n\t\t\t\tjob.menuaction = 'send';\n\t\t\t\tjob.parameters = null;\n\t\t\t\tsomething_to_send = true;\n\t\t\t}\n\t\t\tif (something_to_send)\n\t\t\t{\n\t\t\t\t// TODO: Passing this to the \"home\" application looks quite ugly\n\t\t\t\tvar request = egw.json('home.queue', jobs_to_send, jsonq_callback, this);\n\t\t\t\trequest.sendRequest(true);\n\t\t\t}\n\t\t}\n\t}",
"function getBackupProgress() {\n ajax.call([{\n // Get the backup progress via webservice.\n methodname: 'core_backup_get_async_backup_progress',\n args: {\n 'backupids': [backupid],\n 'contextid': contextid\n },\n }], true, true, false, timeout)[0].done(function(response) {\n // We have the progress now update the UI.\n updateProgress(response[0]);\n checkdelay = checkdelayoriginal;\n backupintervalid = updateInterval(backupintervalid, getBackupProgress, checkdelayoriginal);\n }).fail(function() {\n checkdelay = checkdelay * checkdelaymultipler;\n backupintervalid = updateInterval(backupintervalid, getBackupProgress, checkdelay);\n });\n }",
"_sendRequestFromQueue () {\n while (this[ _requestQueue ].length > 0) {\n const request = this[ _requestQueue ].shift()\n this._sendRequest(request)\n }\n }",
"saveChunk() {\n console.log(\"Saving Chunk for \" + this.name + \" @ \" + this.path + \"/fullLog.json\");\n\n // Load the Full Log.\n let fullLogRaw = fs.readFileSync(this.path + \"/fullLog.json\");\n let fullLog = JSON.parse(fullLogRaw);\n\n // Push the Current Chunk.\n fullLog.push(this.currentChunk);\n\n // Clear the Current Chunk.\n this.currentChunk = [];\n let logJSON = JSON.stringify(fullLog, null, 2);\n\n // Write the New Full Log.\n fs.writeFileSync(this.path + \"/fullLog.json\", logJSON);\n this.currentChunkIndex++;\n }",
"flushMessageBuffer() {\n console.debug('flush' + this);\n const adapter = this;\n const socket = this.get('socket');\n if (adapter.messageBuffer.length > 0 && socket) {\n if (socket.readyState === 1) {\n let batch = { batch: [] };\n adapter.messageBuffer.forEach(function (payload) {\n batch.batch.push(payload);\n });\n adapter.messageBuffer = [];\n socket.send(JSON.stringify(batch));\n\n // readyState > 1 means that WS is closing/closed, so we reject promises\n // to avoid indefinitely wait for WS to be opened again (maybe TODO)\n }\n if (socket.readyState > 1) {\n adapter.messageBuffer.forEach((message) => {\n const promise_spec = adapter.promises.get(message.uuid);\n promise_spec.error({ message: 'Cannot send message - WebSocket closed' });\n });\n }\n }\n }",
"function progressPatient(queue) {\n setShow('send');\n }",
"async function saveHistoryFile (transferData: TransferData) {\n let data = JSON.parse(storage.getItem('data'))\n let transfers = data[HISTORY_FOLDER_NAME][HISTORY_FILE_NAME]\n let id = transferData.transferId ? transferData.transferId : transferData.receivingId\n if (!id) throw new Error('Missing id in transferData')\n if (transfers) {\n transfers[id] = {\n ...transfers[id],\n ...transferData\n }\n } else {\n transfers = {\n [id]: transferData\n }\n }\n\n // update the send file with new content\n data[HISTORY_FOLDER_NAME][HISTORY_FILE_NAME] = transfers\n storage.setItem('data', JSON.stringify(data))\n}",
"function flushBuffer(cb) {\n crate.Insert(table_name).data(buf).run(function(err, res) {\n\t\tif(cb) {\n\t\t\tcb()\n\t\t}\n if (err) {\n console.log(\"Failed to insert :(\", err)\n return\n }\n console.log(\"Inserted sucessfuly.\")\n });\n\n console.log(\"Inserting \", buf.length, \" documents to the database, current pos:\", total)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the two numbers are within the given tolerance of each other. This is useful to correct for floating point precision issues, less useful for integers. | function approxEqual(a, b, tolerance) {
if (tolerance === void 0) {
tolerance = 0.00001;
}
return Math.abs(a - b) <= tolerance;
} | [
"function testTolerance(value, test, tolerance) {\n if (Math.abs(value - test) < tolerance) {\n return true;\n } else {\n return false;\n }\n }",
"static WithinEpsilon(a, b, epsilon = 1.401298e-45) {\n const num = a - b;\n return -epsilon <= num && num <= epsilon;\n }",
"function isCloseToZero (num, tolerance = t) {\n return Math.abs(num) <= tolerance;\n}",
"function checkAnswer(inputAnswer, correctAnswer, tolerance){\n var lowerLimit = correctAnswer - tolerance; \n var upperLimit = correctAnswer + tolerance; \n if(inputAnswer >= lowerLimit && inputAnswer <= upperLimit){\n return true;\n }else{\n return false;\n } \n }",
"pointsEqual(p1, p2) {\n return GeoPlus.distance(p1, p2) <= this.tolerance;\n }",
"function near(a,b) {\n var diff1 = 100 - a;\n var diff2 = 100 - b;\n if(diff1 === diff2) {\n console.log(a, \"is the nearest to 100\");\n }\n else\n {\n (diff1 < diff2) ? console.log(a, \"is the nearest to 100\") : console.log(b, \"is the nearest to 100\"); \n }\n}",
"function isNear(val, target, threshold) {\n return Math.abs(val - target) <= threshold;\n}",
"function approximately(x, y, delta) {\n if (delta === undefined)\n delta = 1e-9;\n return Math.abs(x - y) < delta;\n }",
"function isBetween(a, b, c){\n var crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y);\n if (Math.abs(crossproduct) > 0.2) {return false;}\n var dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y);\n if (dotproduct < 0) {return false;}\n var squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y);\n return (dotproduct <= squaredlengthba);\n}",
"function pixelEq (p1, p2) {\n const epsilon = 0.002;\n for (let i = 0; i < 3; ++i) {\n if (Math.abs(p1[i] - p2[i]) > epsilon) {\n return false;\n }\n }\n return true;\n}",
"function temp(temp1, temp2){\n\tif((temp1 < 0 && temp2 > 100) || (temp1 > 100 && temp2 < 0)){\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}",
"function lessThan100(num1, num2) {\r\n if (num1 + num2 < 100) { return true }\r\n return false\r\n}",
"function approximatelyEqual(path1, path2) {\n // convert to numbers and letters\n const path1Items = pathToItems(path1);\n const path2Items = pathToItems(path2);\n const epsilon = 0.001;\n\n if (path1Items.length !== path2Items.length) {\n return false;\n }\n\n for (let i = 0; i< path1Items.length; i++) {\n if (typeof path1Items[i] === 'string' && path1Items[i] !== path2Items[i]) {\n return false;\n }\n\n // otherwise it's a number, check if approximately equal\n if (Math.abs(path1Items[i] - path2Items[i]) > epsilon) {\n return false;\n }\n }\n\n return true;\n}",
"function closeEnough(a, b) {\n function close(c, d){ return Math.abs(c - d) < 0.01; }\n return close(a.red, b.red) && close(a.green, b.green) && close(a.blue, b.blue);\n}",
"function dist(distance, x1, y1, x2, y2) {\n if(Math.abs(x1-x2) === distance && y1 === y2 || x1 === x2 && Math.abs(y1-y2) === distance) {\n return true;\n }\n else {\n return false;\n }\n \n}",
"function checkNumbers(a, b) {\n if (a === 50 || b === 50 || a + b === 50) return true;\n}",
"function checkBalance(creep, tolerance) {\n \n for(var i = 0; i < containerIDs.length; ++i) {\n var container = Game.getObjectById(containerIDs[i]); \n if(_.sum(container.energy) < _.sum(container.energyCapacity) - energyLimit) {\n containerEnergy[i]=_.sum(container.energy);\n }\n }\n \n lowest=containerEnergy[i];\n for(var i = 0; i < containerEnergy.length; ++i) {\n if(lowest < containerEnergy[i]) {\n lowest = containerEnergy[i];\n }\n }\n \n //if the lowerst is more than tolerance (20%) lower than the average of containers\n if(lowest <= ((tolerance/100) * (_.sum(containerEnergy)/containerEnergy.length))) {\n return true;\n } else {\n return false;\n }\n}",
"isCircleTooClose(x1,y1,x2,y2){\n // if(Math.abs(x1-x2)<50 && Math.abs(y1-y2)<50)\n // return true;\n // return false; \n\n var distance = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));\n if(distance<90)\n return true;\n return false;\n \n }",
"static AreClose(quat0, quat1) {\n const dot = Quaternion.Dot(quat0, quat1);\n return dot >= 0;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the outermost matching node before a given position. | function findNodeBefore(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
var max
;(function c(node, st, override) {
if (node.start > pos) { return }
var type = override || node.type;
if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))
{ max = new Found(node, st); }
baseVisitor[type](node, st, c);
})(node, state);
return max
} | [
"matchBefore(expr) {\n let line = this.state.doc.lineAt(this.pos)\n let start = Math.max(line.from, this.pos - 250)\n let str = line.text.slice(start - line.from, this.pos - line.from)\n let found = str.search(ensureAnchor(expr, false))\n return found < 0\n ? null\n : { from: start + found, to: this.pos, text: str.slice(found) }\n }",
"matchBefore(expr) {\n let line = this.state.doc.lineAt(this.pos);\n let start = Math.max(line.from, this.pos - 250);\n let str = line.slice(start - line.from, this.pos - line.from);\n let found = str.search(ensureAnchor(expr, false));\n return found < 0 ? null : { from: start + found, to: this.pos, text: str.slice(found) };\n }",
"getPrev(pos) {\n if (pos.character === 0 && pos.line === 0)\n throw new Error(\"Attempt to get position before (0,0)!\");\n return this.document.positionAt(this.document.offsetAt(pos) - 1);\n }",
"function preceding( jq, expr ) {\n\tvar found;\n\t$(jq).parents().each(function() {\n\t\t// Check the parent and then it's preceding siblings\n\t\tfound = self(this, expr) || prevSiblings(this, expr);\n\t\treturn !found;\n\t});\n\treturn found;\n}",
"function findForward(node, callback) {\n if (callback(node))\n return node;\n for (var i=0; i < node.children.length; i++) {\n foundNode = findForward(node.children[i], callback);\n if (foundNode)\n return foundNode;\n }\n return null;\n}",
"function getLeftmost( start ) {\n \n var p = start,\n leftmost = start;\n do {\n \n if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;\n p = p.next;\n \n } while ( p !== start );\n \n return leftmost;\n \n }",
"function nextLeft(v){var children=v.children;return children?children[0]:v.t;} // This function works analogously to nextLeft.",
"walkBackWhile(startingPosition, condition) {\n let currentPos = startingPosition;\n let currentChar = this.getChar(currentPos);\n while (condition(currentChar)) {\n currentPos = this.getPrev(currentPos);\n currentChar = this.getChar(currentPos);\n if (currentPos.line === 0 && currentPos.character === 0)\n break;\n }\n return currentPos;\n }",
"function findPrev(item) {\n var currNode = this.head;\n while (currNode.next.element != item && currNode.next.element != \"head\") {\n currNode = currNode.next;\n }\n if (currNode.next.element == item) {\n return currNode;\n }\n return -1;\n }",
"nodeOffset(blockOffset, isFocusOffset) {\n isFocusOffset = isFocusOffset || false;\n const nodes = this.textNodes();\n\n for (let i = 0, j = nodes.length; i < j; i++) {\n const len = nodes[i].length;\n const nodeOffset = isFocusOffset ? blockOffset-len-1 : blockOffset-len;\n if (nodeOffset < 0) {\n return {'node': nodes[i], 'offset': blockOffset };\n } else {\n blockOffset -= len;\n }\n }\n\n // no text node found, default to the first node\n if (this.node && this.node.firstChild) {\n return {'node': this.node.firstChild, 'offset': 0};\n }\n return {};\n }",
"isPreceding(node) {\n var nodePos, thisPos;\n nodePos = this.treePosition(node);\n thisPos = this.treePosition(this);\n if (nodePos === -1 || thisPos === -1) {\n return false;\n } else {\n return nodePos < thisPos;\n }\n }",
"function assert_previous_nodes(aNodeType, aStart, aNum) {\n let node = aStart;\n for (let i = 0; i < aNum; ++i) {\n node = node.previousSibling;\n if (node.localName != aNodeType)\n throw new Error(\"The node should be preceded by \" + aNum + \" nodes of \" +\n \"type \" + aNodeType);\n }\n return node;\n}",
"getInorderSuccessor(node) {\n if(node == null || node.left == null)\n return node;\n return this.getInorderSuccessor(node.left);\n }",
"function findPrev(ctx, query) {\n doSearch(ctx, true, query);\n}",
"tokenBefore(types) {\n let token = this.state.tree.resolve(this.pos, -1);\n while (token && types.indexOf(token.name) < 0)\n token = token.parent;\n return token ? { from: token.from, to: this.pos,\n text: this.state.sliceDoc(token.from, this.pos),\n type: token.type } : null;\n }",
"tokenBefore(types) {\n let token = this.state.tree.resolve(this.pos, -1);\n while (token && types.indexOf(token.name) < 0)\n token = token.parent;\n return token ? { from: token.start, to: this.pos,\n text: this.state.sliceDoc(token.start, this.pos),\n type: token.type } : null;\n }",
"function lensForCurrentMinElement(tree) {\n\tif (isEmpty(tree)) {\n\t\treturn null;\n\t} else if (isEmpty(tree.left)) {\n\t\treturn R.identity;\n\t} else {\n\t\treturn R.compose(\n\t\t\tlenses.leftChild,\n\t\t\tR.defaultTo(\n\t\t\t\tR.identity,\n\t\t\t\tlensForCurrentMinElement(tree.left)));\n\t}\n}",
"function extUtils_getOffsetsAfterBubblingUpTree(currNode)\n{\n\n // special case for dynamic elements\n if (currNode.parentNode && extUtils.isPartOfLockedContent(currNode) &&\n extUtils.isOKToBubbleThroughTag(currNode.parentNode.tagName)) {\n currNode = currNode.parentNode;\n }\n\n // climb up to top character style -- otherwise selection could be unbalanced\n while (currNode.parentNode && currNode.parentNode.childNodes.length == 1 &&\n extUtils.isOKToBubbleThroughTag(currNode.parentNode.tagName)) {\n currNode = currNode.parentNode;\n }\n\n return dwscripts.getNodeOffsets(currNode);\n}",
"function FIND(find_text) {\n var within_text = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];\n var position = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2];\n\n\n // Find the position of the text\n position = within_text.indexOf(find_text, position - 1);\n\n // If found return the position as base 1.\n return position === -1 ? error$2.value : position + 1;\n}",
"function findNearestNodeEl(el) {\n while (el !== document.body && !el.classList.contains('blocks-node')) {\n el = el.parentNode;\n }\n return el === document.body? null : el;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getOutputActivations Gets output activations of an image label as onehot Float32Array | function getOutputActivations(mnistData, sampleId) {
const l = getImageLabel(mnistData, sampleId);
const oa = new Float32Array(10);
oa[l] = 1.0;
return oa;
} | [
"function getInputActivations({ imageWidth, imageHeight, imagesBuffer }, sampleId) {\n // size of input\n const sizeOfInput = imageWidth * imageHeight;\n // our result array\n const inputActivations = new Float32Array(sizeOfInput);\n // for each pixel in the image\n for (let r = 0; r < imageHeight; ++r) {\n for (let c = 0; c < imageWidth; ++c) {\n inputActivations[r * imageWidth + c] =\n imagesBuffer.getUint8(sampleId * sizeOfInput + r * imageWidth + c) / 256.0;\n }\n }\n return inputActivations;\n }",
"output(inputArr) {\n\n let inputs = (this.hiddensOutputs.singleColumnMatrix(inputArr)); //turn the vision array into a 1xN Matrix\n let Biased = inputs.Bias(); //Applies a level of bias to the array to encourage acting\n\n let WeightedHiddenInputs = this.hiddensInputs.dot(inputs); //Runs the biased input matrix through the first matrix\n\n let WeightedHiddenOutputs = WeightedHiddenInputs.activate(); //Runs the 1 generation matrix through the sigmoid function (which represents learning curves)\n\n let WeightedHiddenOutputsBias = WeightedHiddenOutputs.Bias(); //Adds a level of bias to the 1 generation matrix to encourage acting\n\n let HI2 = this.hiddenshiddens.dot(WeightedHiddenOutputsBias); //Runs the 1 generation matrix through the second matrix \n\n let HO2 = HI2.activate(); //Runs the 2 generation matrix through the sigmoid function learning curve\n let HOB2 = HO2.Bias(); //Adds a level of bias to the 2 generation matrix to encourage acting\n\n let OutIn = this.hiddensOutputs.dot(HOB2); // runs the 2 generation matrix through the third matrix\n\n let Out = OutIn.activate(); //runs the 3 generation matrix through the sigmoid learning curve\n\n return Out.toArray(); //outputs the 3 generation learning matrix to an array to be returned to the ship.\n }",
"annual_outputs(state) {\n return state.annual_outputs;\n }",
"function predict(input) {\n return dl.tidy(() => {\n\n const hidden = input.matMul(weights).add(biases).relu();\n const hidden2 = hidden.matMul(weights2).add(biases2).relu();\n const out = hidden2.matMul(outWeights).add(outBias).sigmoid().as1D();\n\n return out;\n });\n}",
"getInputWeights() {\n return this._inputLayer.reduce(\n (acc, neuron) => acc.concat(neuron.getWeights()),\n []);\n }",
"outputs() {\n return this.stack.outputs();\n }",
"function use_nueral_net_before_storing(networky,array_to_predict_20) {\n\t var prediction; \nprediction = networky.activate(array_to_predict_20)\n//console.log( prediction);\nreturn prediction;\n}",
"function getOutputs (gate, state) {\n return gate.outputs.map((pin) => state.outputs[pin.id])\n}",
"function getTrainingModeLabel(x)\n{\n\tswitch(x)\n\t{\n\t\tcase TRAININGOFF:\n\t\treturn TRAININGOFF_ID;\n\t\tbreak;\n\t\t\n\t\tcase TRAININGON:\n\t\treturn TRAININGON_ID;\n\t\tbreak;\n\t}\n}",
"async function draw_prediction(batch, predictions, labels,num_of_pics,start_index){\r\n\tvar guess_accuracy=0;\r\n\tvar drawing_place = document.getElementById(\"show_predictions\");\r\n\tvar tot_accuracy = document.createElement(\"h5\");\r\n\ttot_accuracy.setAttribute(\"id\",\"tot_accuracy\");\r\n\ttot_accuracy.setAttribute(\"align\",\"center\");\r\n\tdrawing_place.appendChild(tot_accuracy);\r\n\tvar row1;\r\n\tvar row2;\r\n\tfor(let i=0;i<num_of_pics; i++){\r\n\t\tvar string_row1 = \"row1\" + (i%5);\r\n\t\tvar string_row2 = \"row2\" + (i%5);\r\n\t\tif(i%5 == 0){\r\n\t\t\trow1 = document.createElement(\"div\");\r\n\t\t\trow1.setAttribute(\"class\",\"row\");\r\n\t\t\trow1.setAttribute(\"id\",string_row1);\t\r\n\t\t\trow2 = document.createElement(\"div\");\r\n\t\t\trow2.setAttribute(\"class\",\"row\");\r\n\t\t\trow2.setAttribute(\"id\",string_row2);\t\t\t\t\r\n\t\t}\r\n\t\t//get data of the relevant image and put it on a canvas element\r\n\t\tvar tf2pic=batch.xs.reshape([1000,32,32,3]).slice([i+start_index,0,0,0],[1,32,32,3]).reshape([32,32,3]);\r\n\t\tvar c = document.createElement(\"canvas\");\r\n\t\tc.setAttribute(\"width\",\"32\");\r\n\t\tc.setAttribute(\"height\",\"32\");\r\n\t\tconst imgRequest=tf.toPixels(tf2pic,c);\r\n\t\tconst [imgResponse]=await Promise.all([imgRequest]);\r\n\t\t\r\n\t\t//get the label and print it's correctness\r\n\t\tvar guess = document.createElement(\"p\");\r\n\t\tvar string1 = get_type(Number(predictions[i+start_index]));\r\n\t\tvar string2 = \"(\" + get_type(Number(labels[i+start_index]));\r\n\t\tif(string1 == \"\" || string2 == \"(\"){ //if an error was occured:\r\n\t\t\tconsole.log(\"there was a problem with some of the input data\");\r\n\t\t\treturn;\r\n\t\t}\r\n\t\telse if(predictions[i+start_index]==labels[i+start_index]){//if the guess was correct\r\n\t\t\tguess_accuracy++;\r\n\t\t\tstring2+= \") - correct\";\r\n\t\t\tguess.setAttribute(\"style\",\"color:#007000\");\r\n\t\t}\r\n\t\telse{//if the guess wasn't correct\r\n\t\t\tstring2+= \") - incorrect\";\r\n\t\t\tguess.setAttribute(\"style\",\"color:#e60000\");\r\n\t\t}\r\n\t\tvar guess_text = document.createTextNode(string1+string2);\r\n\t\tguess.appendChild(guess_text);\r\n\t\tcol1 = document.createElement(\"div\");\r\n\t\tcol1.setAttribute(\"class\",\"col\");\r\n\t\tcol2 = document.createElement(\"div\");\r\n\t\tcol2.setAttribute(\"class\",\"col\");\t\t\t\r\n\t\tcol1.appendChild(guess);\r\n\t\tcol2.appendChild(c);\r\n\t\trow1.appendChild(col1);\r\n\t\trow2.appendChild(col2);\r\n\t\tif((i+1)%5 == 0){\r\n\t\t\tdrawing_place.appendChild(row1);\r\n\t\t\tdrawing_place.appendChild(row2);\r\n\t\t}\r\n\t}\r\n\tfor(let i = num_of_pics; i< 1000 ; i++){\r\n\t\tif(predictions[i+start_index]==labels[i+start_index]){//if the guess was correct\r\n\t\t\tguess_accuracy++;\r\n\t\t}\r\n\t}\r\n\tdocument.getElementById(\"tot_accuracy\").innerHTML = \"Accuracy: \"+(guess_accuracy/1000)+\"%, 50 pictures for example:\"\r\n}",
"clearAllInputsOutputLayer(){\n for(var i = 0; i < neuralNet.layers[2].neurons.length; i++){\n neuralNet.layers[2].neurons[i].receivedInputs = [];\n neuralNet.layers[2].neurons[i].receivedWeights = [];\n }\n }",
"function predictionCallback(resp) {\n if ('error' in resp) {\n\tconsole.log(resp['error']);\n }\n console.log('prediction callback!');\n console.log(resp);\n document.getElementById('tag_category').innerHTML=resp['outputLabel'];\n}",
"_createIndexMap() {\n if (this.poolIndexMap) {\n return;\n }\n\n let [inputRows, inputCols, inputChannels] = this.inputShape;\n const rowIndices = new Tensor([], [inputRows, inputCols]);\n let index = 0;\n for (let i = 0; i < inputRows; i++) {\n for (let j = 0; j < inputCols; j++) {\n rowIndices.tensor.set(i, j, index);\n index += 1;\n }\n }\n\n // padding\n if (this.padding === 'SAME' || Array.isArray(this.padding)) {\n const [paddingRowBefore, paddingRowAfter, paddingColBefore, paddingColAfter] = this.inputPadding;\n inputRows = inputRows + paddingRowBefore + paddingRowAfter;\n inputCols = inputCols + paddingColBefore + paddingColAfter;\n const _rowIndices = new Tensor([], [inputRows, inputCols]);\n ops.assigns(_rowIndices.tensor, -1);\n ops.assign(\n _rowIndices.tensor\n .hi(this.inputShape[0] + paddingRowBefore, this.inputShape[1] + paddingColBefore)\n .lo(paddingRowBefore, paddingColBefore),\n rowIndices.tensor\n );\n rowIndices.tensor = _rowIndices.tensor;\n }\n\n const [nbRow, nbCol] = this.kernelShape;\n const outputRows = this.outputShape[0];\n const outputCols = this.outputShape[1];\n\n this.poolIndexMap = new Tensor([], [outputRows * outputCols, nbRow * nbCol], Int32Array);\n\n const patchRow = new Tensor([], [nbRow, nbCol]);\n let offset = 0;\n for (let i = 0, limit = inputRows - nbRow; i <= limit; i += this.strides[0]) {\n for (let j = 0, limit = inputCols - nbCol; j <= limit; j += this.strides[1]) {\n ops.assign(patchRow.tensor, rowIndices.tensor.hi(i + nbRow, j + nbCol).lo(i, j));\n this.poolIndexMap.tensor.data.set(patchRow.tensor.data, offset);\n offset += nbRow * nbCol;\n }\n }\n this.poolIndexMap.createGLTexture({ type: '2d', format: 'int', supportSliceTexture: true });\n }",
"dispatchSignalForward(){\n\n this.clearAllInputsOutputLayer();\n\n //console.log('Output layer inputs after clearing by hidden layer');\n // console.log(neuralNet.layers[2].neurons);\n // console.log(neuralNet.layers[2].neurons);\n\n for(var i = 0; i < this.neurons.length; i++){\n this.neurons[i].dispatchSignalForward();\n }\n }",
"feedForward(inputs) {\n // Reset the inputs/weights from the last training round.\n [...this._inputLayer, ...this._hiddenLayer, ...this._outputLayer]\n .forEach(n => n.reset());\n\n // Set the new inputs (not including bias).\n for (let i = 0; i < this._inputLayer.length - 1; ++i)\n this._inputLayer[i].pushInput(inputs[i]);\n\n // Feed the inputs forward to the hidden layer.\n this._inputLayer.forEach(n => n.feedForward());\n\n // Update the outputs for each hidden neuron (excluding bias).\n for (let i = 0; i < this._hiddenLayer.length - 1; ++i)\n this._hiddenLayer[i].updateOutput();\n\n // Feed the hidden outputs forward to the output layer.\n for (let i = 0; i < this._hiddenLayer.length; ++i)\n this._hiddenLayer[i].feedForward();\n\n // Update the outputs.\n this._outputLayer.forEach(n => n.updateOutput());\n\n // Store the new outputs.\n this._outputs = this._outputLayer.map(n => n.getOutput());\n\n return this.getOutputs();\n }",
"activation(z) {\n return 1 * z;\n }",
"getOutput() {\n\t\treturn this.myOutput;\n\t}",
"function getColormap() {\n var map = [];\n var index = [];\n\n for (var i = 0; i < netsize; i++) {\n index[network[i][3]] = i;\n }var k = 0;\n for (var l = 0; l < netsize; l++) {\n var j = index[l];\n map[k++] = network[j][0];\n map[k++] = network[j][1];\n map[k++] = network[j][2];\n }\n return map;\n }",
"getHiddenWeights() {\n return this._hiddenLayer.reduce(\n (acc, neuron) => acc.concat(neuron.getWeights()),\n []);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets dynamic load balancer. | _setLoadBalancer () {
if (!this[ _options ] || !this[ _options ].loadbalancer) {
return
}
this[ _loadBalancer ] = _loadDynamicComponent(this[ _options ].loadbalancer)
} | [
"function LoadBalancer(props) {\n return __assign({ Type: 'AWS::ElasticLoadBalancing::LoadBalancer' }, props);\n }",
"function updateLoadBalRouting(configid, proxyport){\n\n\tvar query = {'configid' : configid};\n\tvar update ={ $set : { 'proxyurl': \"localhost:\" + proxyport, 'status':true } };\n\n\tLoadbalanceConfig.update(query, update, function(err, num){\n\t\tif(err)\n\t\t\tthrow err;\n\t\tconsole.log( (err === null) ? { msg: 'updated' } : { msg: err });\n\t});\n}",
"function setBannerImage() {\n if (!document.styleSheets) return;\n if (AVAILABLE_BANNERS < 2) return;\n\n var imageIndex = bannerImageIndex == null ? 1 :\n parseInt(bannerImageIndex);\n if (imageIndex < 0 || imageIndex > AVAILABLE_BANNERS)\n imageIndex = 1;\n\n var rules = new Array();\n if (document.styleSheets[STYLESHEET_INDEX].cssRules)\n rules = document.styleSheets[STYLESHEET_INDEX].cssRules;\n else\n rules = document.styleSheets[STYLESHEET_INDEX].rules;\n rules[0].style.backgroundImage =\n \"url(http://visualvm.java.net/images/main_background_\" + imageIndex + \".jpg)\";\n\n setCookie(BANNER_IMAGE_INDEX, ++imageIndex + '');\n}",
"set gw( gw )\n {\n this.gateways.push( gw );\n }",
"function tell(){\n stickyLoadBalancer.tellBalancer(balancer, own);\n}",
"function setBxSlider() {\r\n $('.bxslider.catalog').bxSlider({\r\n mode: 'fade',\r\n pagerCustom: '#bx-pager',\r\n preloadImages: 'visible',\r\n pager: true,\r\n speed: 500,\r\n controls: true,\r\n adaptiveHeight: true,\r\n adaptiveHeightSpeed: 500,\r\n nextText: \"\",\r\n prevText: \"\",\r\n onSliderLoad: function($elemIndex){\r\n setImageSliderControls(null, $elemIndex);\r\n Baralaye.Template.VAlign();\r\n },\r\n onSlideBefore: function($elem){\r\n Baralaye.Template.VAlign($elem);\r\n },\r\n onSlideAfter: function($elem){\r\n setImageSliderControls($elem, null);\r\n }\r\n });\r\n }",
"async _createApplicationLoadBalancer(environment, appElbName, subnetIds, scheme, securityGroupIds) {\n let params = {\n Name: appElbName, /* required */\n Subnets: subnetIds,\n Scheme: scheme,\n SecurityGroups: securityGroupIds,\n Tags: [\n { Key: 'Environment', Value: environment },\n { Key: 'Created', Value: moment().format() }\n ]\n };\n\n this.logMessage(`Creating Application Load Balancer. [Name: ${appElbName}]`);\n const albResult = await this._awsElbv2Client.createLoadBalancer(params).promise();\n\n if(albResult && albResult.LoadBalancers && albResult.LoadBalancers.length > 0) {\n return albResult.LoadBalancers[0].LoadBalancerArn;\n } else {\n return '';\n }\n }",
"setFallback(handler) {\n const fallbackGroup = new RouteGroup_1.default(constants_1.ROUTES_FALLBACK);\n fallbackGroup.match(null, handler);\n this.fallback = fallbackGroup;\n }",
"function setProxyUrl(url) {\n proxyUrl = url;\n }",
"setVillage(village) {\r\n this.village = village;\r\n }",
"async function createsOrUpdatesAnAvailabilityGroupListenerUsingLoadBalancerThisIsUsedForVMSPresentInSingleSubnet() {\n const subscriptionId =\n process.env[\"SQLVIRTUALMACHINE_SUBSCRIPTION_ID\"] || \"00000000-1111-2222-3333-444444444444\";\n const resourceGroupName = process.env[\"SQLVIRTUALMACHINE_RESOURCE_GROUP\"] || \"testrg\";\n const sqlVirtualMachineGroupName = \"testvmgroup\";\n const availabilityGroupListenerName = \"agl-test\";\n const parameters = {\n availabilityGroupName: \"ag-test\",\n loadBalancerConfigurations: [\n {\n loadBalancerResourceId:\n \"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.Network/loadBalancers/lb-test\",\n privateIpAddress: {\n ipAddress: \"10.1.0.112\",\n subnetResourceId:\n \"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/default\",\n },\n probePort: 59983,\n sqlVirtualMachineInstances: [\n \"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/testvm2\",\n \"/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/testrg/providers/Microsoft.SqlVirtualMachine/sqlVirtualMachines/testvm3\",\n ],\n },\n ],\n port: 1433,\n };\n const credential = new DefaultAzureCredential();\n const client = new SqlVirtualMachineManagementClient(credential, subscriptionId);\n const result = await client.availabilityGroupListeners.beginCreateOrUpdateAndWait(\n resourceGroupName,\n sqlVirtualMachineGroupName,\n availabilityGroupListenerName,\n parameters\n );\n console.log(result);\n}",
"set BatchingStatic(value) {}",
"setPath(basDerivationPath) {\n this._baseDerivationPath = basDerivationPath;\n }",
"setGDP(gdp){\n this.gdp = gdp\n }",
"set shard(value) {\n this._options.shard = value;\n\n // shard setting changed so let's schedule a new keep-alive check if connected\n if (this._oneSuccessfulConnect) {\n this._maybeStartWSKeepAlive();\n }\n }",
"function set_broadband(){\nsetCookie('broadband',\"true\",cookie_time,\"/\")\n location.reload(false) ;\n}",
"function ServerBehavior_setFamily(family)\n{\n this.family = family;\n}",
"set LightmapStatic(value) {}",
"function setFrontBrake(isOn) {\n bicycle.frontBrake = true;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a SigningRequest instance configured for this link. | async createRequest(args, transport) {
const t = transport || this.transport;
// generate unique callback url
let request = await esr.SigningRequest.create({
...args,
chainId: this.chainId,
broadcast: false,
callback: {
url: this.createCallbackUrl(),
background: true,
},
}, this.requestOptions);
if (t.prepare) {
request = await t.prepare(request);
}
return request;
} | [
"function newRequest(data){\n var request = createNewRequestContainer(data.requestId);\n createNewRequestInfo(request, data);\n }",
"async function makeRequest(web3, req, defaultRequest, chainId, forwarderInstance) {\n var _a;\n const filledRequest = {\n request: Object.assign(Object.assign({}, defaultRequest.request), req.request),\n relayData: Object.assign(Object.assign({}, defaultRequest.relayData), req.relayData)\n };\n // unless explicitly set, read nonce from network.\n if (((_a = filledRequest.request.nonce) !== null && _a !== void 0 ? _a : '0') === '0') {\n filledRequest.request.nonce = (await forwarderInstance.getNonce(filledRequest.request.from)).toString();\n }\n const sig = await Utils_1.getEip712Signature(web3, new TypedRequestData_1.default(chainId, filledRequest.relayData.forwarder, filledRequest));\n return {\n req: filledRequest,\n sig\n };\n}",
"function newItemRequest(endpoint, payload) {\n var request = baseRequest;\n request.url = endpoint;\n request.type = \"POST\";\n request.contentType = \"application/json;odata=verbose\";\n request.headers = {\n \"ACCEPT\": \"application/json;odata=verbose\",\n \"X-RequestDigest\": $(\"#__REQUESTDIGEST\").val()\n };\n request.data = payload;\n return request;\n }",
"function initializeRequest(api, url, method, body) {\n var options = {\n \"method\": method,\n \"uri\": url,\n \"body\": body,\n \"headers\": {}\n }, dsAuthHeader = JSON.stringify({ // DocuSign authorization header\n \"Username\": api.config.tcConfig.docusign.username,\n \"Password\": api.config.tcConfig.docusign.password,\n \"IntegratorKey\": api.config.tcConfig.docusign.integratorKey\n });\n options.headers[\"X-DocuSign-Authentication\"] = dsAuthHeader;\n\n return options;\n}",
"getNotificationRequest() {\n let operation = {\n 'api': 'GetBucketNotification',\n 'method': 'GET',\n 'uri': '/<bucket-name>?notification',\n 'params': {\n },\n 'headers': {\n 'Host': this.properties.zone + '.' + this.config.host,\n },\n 'elements': {\n },\n 'properties': this.properties,\n 'body': undefined\n };\n this.getNotificationValidate(operation);\n return new Request(this.config, operation).build();\n }",
"function eventToSentryRequest(event, api) {\n // since JS has no Object.prototype.pop()\n var _a = event.tags || {}, samplingMethod = _a.__sentry_samplingMethod, sampleRate = _a.__sentry_sampleRate, otherTags = Object(tslib__WEBPACK_IMPORTED_MODULE_0__[\"__rest\"])(_a, [\"__sentry_samplingMethod\", \"__sentry_sampleRate\"]);\n event.tags = otherTags;\n var useEnvelope = event.type === 'transaction';\n var req = {\n body: JSON.stringify(event),\n type: event.type || 'event',\n url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth(),\n };\n // https://develop.sentry.dev/sdk/envelopes/\n // Since we don't need to manipulate envelopes nor store them, there is no\n // exported concept of an Envelope with operations including serialization and\n // deserialization. Instead, we only implement a minimal subset of the spec to\n // serialize events inline here.\n if (useEnvelope) {\n var envelopeHeaders = JSON.stringify({\n event_id: event.event_id,\n sent_at: new Date().toISOString(),\n });\n var itemHeaders = JSON.stringify({\n type: event.type,\n // TODO: Right now, sampleRate may or may not be defined (it won't be in the cases of inheritance and\n // explicitly-set sampling decisions). Are we good with that?\n sample_rates: [{ id: samplingMethod, rate: sampleRate }],\n });\n // The trailing newline is optional. We intentionally don't send it to avoid\n // sending unnecessary bytes.\n //\n // const envelope = `${envelopeHeaders}\\n${itemHeaders}\\n${req.body}\\n`;\n var envelope = envelopeHeaders + \"\\n\" + itemHeaders + \"\\n\" + req.body;\n req.body = envelope;\n }\n return req;\n}",
"function get_signed_request(file, ifLast){\n\t\tvar username;\n\t\tif(document.getElementById('username') != null){\n\t\t\tusername = document.getElementById('username').value;\n\t\t}\n\t\telse{\n\t\t\tusername = 'username';\n\t\t}\n\t\t\n\t var xhr = new XMLHttpRequest();\n\t xhr.open(\"GET\", \"/sign_s3?file_name=\"+file.name+\"&file_type=\"+file.type+\"&username=\"+username);\n\t xhr.onreadystatechange = function(){\n\t if(xhr.readyState === 4){\n\t if(xhr.status === 200){\n\t var response = JSON.parse(xhr.responseText);\n\t upload_file(file, response.signed_request, response.url, ifLast);\n\t }\n\t else{\n\t alert(\"Could not get signed URL.\");\n\t }\n\t }\n\t };\n\t xhr.send();\n\t}",
"static from(signerEntry, xrplNetwork) {\n var _a, _b, _c;\n const account = (_b = (_a = signerEntry.getAccount()) === null || _a === void 0 ? void 0 : _a.getValue()) === null || _b === void 0 ? void 0 : _b.getAddress();\n if (!account) {\n throw new __1.XrpError(__1.XrpErrorType.MalformedProtobuf, 'SignerEntry protobuf does not contain `account` field.');\n }\n const accountXAddress = xrp_utils_1.default.encodeXAddress(account, undefined, xrplNetwork == xpring_common_js_1.XrplNetwork.Test || xrplNetwork == xpring_common_js_1.XrplNetwork.Dev);\n if (!accountXAddress) {\n throw new __1.XrpError(__1.XrpErrorType.MalformedProtobuf, 'Cannot construct XAddress from SignerEntry protobuf `account` field.');\n }\n const signerWeight = (_c = signerEntry.getSignerWeight()) === null || _c === void 0 ? void 0 : _c.getValue();\n if (signerWeight === undefined) {\n throw new __1.XrpError(__1.XrpErrorType.MalformedProtobuf, 'SignerEntry protobuf does not contain `signerWeight` field.');\n }\n return new XrpSignerEntry(accountXAddress, signerWeight);\n }",
"async _makeManagementRequest(request, options = {}) {\n const retryOptions = options.retryOptions || {};\n try {\n const abortSignal = options && options.abortSignal;\n const sendOperationPromise = async () => {\n let count = 0;\n const retryTimeoutInMs = getRetryAttemptTimeoutInMs(options.retryOptions);\n let timeTakenByInit = 0;\n if (!this._isMgmtRequestResponseLinkOpen()) {\n logger.verbose(\"[%s] Acquiring lock to get the management req res link.\", this._context.connectionId);\n const initOperationStartTime = Date.now();\n try {\n await defaultCancellableLock.acquire(this.managementLock, () => {\n const acquireLockEndTime = Date.now();\n const timeoutInMs = retryTimeoutInMs - (acquireLockEndTime - initOperationStartTime);\n return this._init({ abortSignal, timeoutInMs });\n }, { abortSignal, timeoutInMs: retryTimeoutInMs });\n }\n catch (err) {\n const translatedError = translate(err);\n logger.warning(\"[%s] An error occurred while creating the management link %s: %s\", this._context.connectionId, this.name, `${translatedError === null || translatedError === void 0 ? void 0 : translatedError.name}: ${translatedError === null || translatedError === void 0 ? void 0 : translatedError.message}`);\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n timeTakenByInit = Date.now() - initOperationStartTime;\n }\n const remainingOperationTimeoutInMs = retryTimeoutInMs - timeTakenByInit;\n const sendRequestOptions = {\n abortSignal: options.abortSignal,\n requestName: options.requestName,\n timeoutInMs: remainingOperationTimeoutInMs\n };\n count++;\n if (count !== 1) {\n // Generate a new message_id every time after the first attempt\n request.message_id = generate_uuid();\n }\n else if (!request.message_id) {\n // Set the message_id in the first attempt only if it is not set\n request.message_id = generate_uuid();\n }\n return this._mgmtReqResLink.sendRequest(request, sendRequestOptions);\n };\n const config = Object.defineProperties({\n operation: sendOperationPromise,\n operationType: RetryOperationType.management,\n abortSignal: abortSignal,\n retryOptions: retryOptions\n }, {\n connectionId: {\n enumerable: true,\n get: () => {\n return this._context.connectionId;\n }\n }\n });\n return (await retry(config)).body;\n }\n catch (err) {\n const translatedError = translate(err);\n logger.warning(\"[%s] An error occurred during send on management request-response link with address '%s': %s\", this._context.connectionId, this.address, `${translatedError === null || translatedError === void 0 ? void 0 : translatedError.name}: ${translatedError === null || translatedError === void 0 ? void 0 : translatedError.message}`);\n logErrorStackTrace(translatedError);\n throw translatedError;\n }\n }",
"getPolicyRequest() {\n let operation = {\n 'api': 'GetBucketPolicy',\n 'method': 'GET',\n 'uri': '/<bucket-name>?policy',\n 'params': {\n },\n 'headers': {\n 'Host': this.properties.zone + '.' + this.config.host,\n },\n 'elements': {\n },\n 'properties': this.properties,\n 'body': undefined\n };\n this.getPolicyValidate(operation);\n return new Request(this.config, operation).build();\n }",
"buildPaymentRequest(cart) {\n // Supported payment instruments\n const supportedInstruments = [{\n supportedMethods: (PAYMENT_METHODS)\n }];\n\n // Payment options\n const paymentOptions = {\n requestShipping: true,\n requestPayerEmail: true,\n requestPayerPhone: true\n };\n\n let shippingOptions = [];\n let selectedOption = null;\n\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n\n // Initialize\n let request = new window.PaymentRequest(supportedInstruments, details, paymentOptions);\n\n // When user selects a shipping address, add shipping options to match\n request.addEventListener('shippingaddresschange', e => {\n e.updateWith(_ => {\n // Get the shipping options and select the least expensive\n shippingOptions = this.optionsForCountry(request.shippingAddress.country);\n selectedOption = shippingOptions[0].id;\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n return Promise.resolve(details);\n });\n });\n\n // When user selects a shipping option, update cost, etc. to match\n request.addEventListener('shippingoptionchange', e => {\n e.updateWith(_ => {\n selectedOption = request.shippingOption;\n let details = this.buildPaymentDetails(cart, shippingOptions, selectedOption);\n return Promise.resolve(details);\n });\n });\n\n return request;\n }",
"function NewCredRequest(sk , IssuerNonce , ipk , rng ) {\n\t// Set Nym as h_{sk}^{sk}\n\tlet HSk = ipk.HSk\n\tlet Nym = HSk.mul(sk)\n\n\t// generate a zero-knowledge proof of knowledge (ZK PoK) of the secret key\n\n\t// Sample the randomness needed for the proof\n\tlet rSk = RandModOrder(rng)\n\n\t// Step 1: First message (t-values)\n\tlet t = HSk.mul(rSk) // t = h_{sk}^{r_{sk}}, cover Nym\n\n\t// Step 2: Compute the Fiat-Shamir hash, forming the challenge of the ZKP.\n\t// proofData is the data being hashed, it consists of:\n\t// the credential request label\n\t// 3 elements of G1 each taking 2*FieldBytes+1 bytes\n\t// hash of the issuer public key of length FieldBytes\n // issuer nonce of length FieldBytes\n \n let proofData = new ArrayBuffer(credRequestLabel.length+3*(2*FieldBytes+1)+2*FieldBytes);\n let v = new Uint8Array(proofData);\n\tlet index = 0\n\n\tindex = appendBytesString(v, index, credRequestLabel)\n\tindex = appendBytesG1(proofData, index, t)\n\tindex = appendBytesG1(proofData, index, HSk)\n\tindex = appendBytesG1(proofData, index, Nym)\n index = appendBytes(v, index, IssuerNonce)\n v.set(BigToBytes(ipk.Hash),index)\n\tlet proofC = HashModOrder(v)\n\n\t// Step 3: reply to the challenge message (s-values)\n\tlet proofS = Modadd(FP256BN.BIG.modmul(proofC, sk, GroupOrder), rSk, GroupOrder) // s = r_{sk} + C \\cdot sk\n\n\t// Done\n\treturn {\n\t\tNym: Nym,\n\t\tIssuerNonce: IssuerNonce,\n\t\tProofC: proofC,\n ProofS: proofS\n }\n}",
"function attachToken(request) {\r\n var token = getToken();\r\n if (token) {\r\n request.headers = request.headers || {};\r\n request.headers['x-access-token'] = token;\r\n }\r\n return request;\r\n }",
"static fromSigningProfileAttributes(scope, id, attrs) {\n try {\n jsiiDeprecationWarnings.aws_cdk_lib_aws_signer_SigningProfileAttributes(attrs);\n }\n catch (error) {\n if (process.env.JSII_DEBUG !== \"1\" && error.name === \"DeprecationError\") {\n Error.captureStackTrace(error, this.fromSigningProfileAttributes);\n }\n throw error;\n }\n class Import extends core_1.Resource {\n constructor(signingProfileArn, signingProfileProfileVersionArn) {\n super(scope, id);\n this.signingProfileName = attrs.signingProfileName;\n this.signingProfileVersion = attrs.signingProfileVersion;\n this.signingProfileArn = signingProfileArn;\n this.signingProfileVersionArn = signingProfileProfileVersionArn;\n }\n }\n const signingProfileArn = core_1.Stack.of(scope).formatArn({\n service: 'signer',\n resource: '',\n resourceName: `/signing-profiles/${attrs.signingProfileName}`,\n });\n const SigningProfileVersionArn = core_1.Stack.of(scope).formatArn({\n service: 'signer',\n resource: '',\n resourceName: `/signing-profiles/${attrs.signingProfileName}/${attrs.signingProfileVersion}`,\n });\n return new Import(signingProfileArn, SigningProfileVersionArn);\n }",
"function GenericRequest() {}",
"function methodRequest(method) {\n return (uri, headers, body) => {\n const init = {\n body,\n headers: Object.assign({}, DefaultHeaders, headers),\n method\n };\n const url = env.get('mavenlinkApiHostName') + uri;\n return signedFetch.then(fetch => fetch(url, init)).then(responseHandler);\n };\n }",
"sign(privateKey) {\n // encrypts the private key calling getNodePrivateKey on Wallet instance\n const cert = wallet.getNodePrivateKey(this.from, privateKey);\n /*\n createSign creates and returns a Sign object that uses the given algorithm(SHA256).\n .update updates the hash content with the given data which are the signed with cert in hex base.\n */\n const signature = createSign('SHA256').update(this.hash()).sign(cert, 'hex');\n // creates a transaction updating the hash and adding the signature\n return new Transaction({...this, signature});\n }",
"static signatureCond(from: BvmAddr): SignatureCond {\n return {\n type: 'signature',\n from,\n };\n }",
"constructor() { \n \n MozuAppDevContractsProvisionTenantRequest.initialize(this);\n }",
"function sign(key, req, options, cb) {\n if(options.wrap_ssl) return sign_cmd(key, req, options, cb);\n\n pkey = pkey || require('ursa').coercePrivateKey;\n var signature = pkey(key).privateEncrypt(req, 'utf8', 'base64');\n\n return cb(null, signature);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort the linked list using bubble sort algorithm in ascending order | bubbleSort() {
let firstNode, secondNode;
firstNode = this.head;
while (firstNode !== null) {
secondNode = this.head;
while (secondNode !== null) {
if (firstNode.value < secondNode.value) {
let temp = secondNode.value;
secondNode.value = firstNode.value;
firstNode.value = temp;
}
secondNode = secondNode.next;
}
firstNode = firstNode.next;
}
return this;
} | [
"function bubbleSort(arr) {\n\n}",
"function nodeArraySort(to_sort) \n{\n var sorted = false; \n while (!sorted) \n {\n\t sorted = true;\n for (var i=0; i<to_sort.length-1; i++) \n {\n if (compareNode(to_sort[i], to_sort[i+1])) \n {\n \tsorted = false;\n tmp_var = to_sort[i];\n to_sort[i] = to_sort[i+1];\n to_sort[i+1] = tmp_var;\n }\n }\n }\n return to_sort;\n}",
"function bubbleSort2() {\n var i1, i2, j1, j2;\n var copy = numbers.slice(0);\n var len = copy.length;\n var tmp;\n var startTime = performance.now();\n var newStart = 0;\n var newEnd = len - 1;\n var swapCount1 = 0;\n var swapCount2 = 0;\n var totalSwaps = 0;\n var totalIterations = 0;\n do {\n var end = newEnd;\n var start = newStart;\n swapCount1 = 0;\n swapCount2 = 0;\n for (i1 = start, j2 = end; i1 < end; i1++, j2--) {\n var i2 = i1 + 1;\n var j1 = j2 - 1;\n if (copy[i1] > copy[i2]) {\n tmp = copy[i1];\n copy[i1] = copy[i2];\n copy[i2] = tmp;\n newEnd = i1;\n swapCount1++;\n }\n if (copy[j1] > copy[j2]) {\n tmp = copy[j2];\n copy[j2] = copy[j1];\n copy[j1] = tmp;\n newStart = j2;\n swapCount2++;\n }\n totalIterations++;\n }\n swapCount = swapCount1 + swapCount2;\n totalSwaps += swapCount;\n } while(swapCount > 1);\n console.log('Optimized: totalSwaps=' + totalSwaps + ' totalIterations=' + totalIterations);\n var endTime = performance.now();\n var time = endTime - startTime;\n var result = copy.join(' ');\n $('#bubbleSort2').text(result);\n $('#bubbleSortTime2').text(time);\n return result;\n}",
"function order(list) {\n let number = 0;\n for (let i = 0; i <= list.length; i++) {\n for (let j = 0; j < list.length; j++) {\n if (list[j] > list[j + 1]) {\n number = list[j];\n console.log(number);\n list[j] = list[j + 1];\n console.log(list[j]);\n list[j + 1] = number;\n console.log(list[j + 1], number);\n }\n }\n }\n return list;\n}",
"function bubbleSort3() {\n var i1, i2, j1, j2;\n var copy = numbers.slice(0);\n var len = copy.length;\n var tmp;\n var startTime = performance.now();\n var newStart = 0;\n var newEnd = len - 1;\n var swapCount1 = 0;\n var swapCount2 = 0;\n var totalSwaps = 0;\n var totalIterations = 0;\n do {\n var end = newEnd;\n var start = newStart;\n swapCount1 = 0;\n swapCount2 = 0;\n for (i1 = start; i1 < end; i1++) {\n var i2 = i1 + 1;\n if (copy[i1] > copy[i2]) {\n tmp = copy[i1];\n copy[i1] = copy[i2];\n copy[i2] = tmp;\n newEnd = i1;\n swapCount1++;\n }\n }\n for (j2 = end; j2 > start; j2--) {\n var j1 = j2 - 1;\n if (copy[j1] > copy[j2]) {\n tmp = copy[j2];\n copy[j2] = copy[j1];\n copy[j1] = tmp;\n newStart = j2;\n swapCount2++;\n }\n totalIterations++;\n }\n swapCount = swapCount1 + swapCount2;\n totalSwaps += swapCount;\n } while(swapCount > 1);\n console.log('Cocktail Shaker: totalSwaps=' + totalSwaps + ' totalIterations=' + totalIterations);\n var endTime = performance.now();\n var time = endTime - startTime;\n var result = copy.join(' ');\n $('#bubbleSort3').text(result);\n $('#bubbleSortTime3').text(time);\n return result;\n}",
"function sortLists() {\n\t\t// Loop all ul, and for each list do initial sort\n\t\tvar ul = $(\".subpageListContainer ul\");\n\t\t$.each(ul, function() {\n\t\t\tsortList($(this), false);\n\t\t});\n\t}",
"sortBookmark() {\n let bookmarks = this.props.bookmarks.slice();\n if (this.state.sortby === 'addTime') {\n bookmarks.sort((a,b) => {\n return compareTime(a.addTime, b.addTime) ? 1 : -1;\n });\n return bookmarks;\n } else {\n bookmarks.sort((a,b) => {\n return ( a.currentChapterOrder > b.currentChapterOrder) ? 1 :\n (((a.currentChapterOrder === b.currentChapterOrder) &&\n ( a.scrollTop / a.scrollHeight > b.scrollTop / b.scrollHeight)) ? 1 :\n (( compareTime(a.addTime, b.addTime)) ? 1 : -1)); \n });\n return bookmarks;\n }\n }",
"function insertSort(arr) {\n var len = arr.length\n\n for(let i = 1; i < len; i++) {\n let j = i, temp = arr[i]\n while(j > 0 && arr[j - 1] > temp) {\n arr[j] = arr[j - 1]\n j--\n }\n arr[j] = temp\n }\n}",
"function sortNotes(){\n notesList.sort(function(a,b)\n {\n if(a.date < b.date)\n return 1;\n if(a.date > b.date)\n return -1;\n if(a.date == b.date)\n {\n if(a.id < b.id)\n return 1;\n if(a.id > b.id)\n return -1;\n }\n return 0;\n })\n console.log(\"posortowane\");\n}",
"function sortSubmenu(e) {\n\t\t\tconst inputEl = $editShortcutDialog.find('input[name=subreddit]').get(0);\n\t\t\tconst currStr = inputEl.value;\n\t\t\t// sort ASC\n\t\t\tconst ascArr = currStr.split('+');\n\t\t\tascArr.sort();\n\t\t\tconst ascStr = ascArr.join('+');\n\t\t\t// sort DESC\n\t\t\tconst descArr = ascArr;\n\t\t\tdescArr.reverse();\n\t\t\tconst descStr = descArr.join('+');\n\t\t\tlet btnTxt;\n\t\t\tif (e.target.type === 'submit') {\n\t\t\t\t// if sorted ASC, sort DESC. If unsorted or sorted DESC, sort ASC\n\t\t\t\tinputEl.value = currStr === ascStr ? descStr : ascStr;\n\t\t\t\tbtnTxt = currStr === ascStr ? 'A-Z' : 'Z-A';\n\t\t\t} else {\n\t\t\t\tbtnTxt = currStr === ascStr ? 'Z-A' : 'A-Z';\n\t\t\t}\n\t\t\t(0, _vendor.$)('#sortButton').text(btnTxt);\n\t\t}",
"function sortOpenList(){\n openList.sort(function(a,b){\n // Sort the list so that the item with the lowest F value goes to the end of the list\n return b.f - a.f;\n });\n}",
"mergesort(start, chainLength) {\n // YOUR CODE HERE\n }",
"visitSort_or_nosort(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function cycleSortPriority() {\r\n // We subtract 2 from sortTypes.length so we skip over sortHidden\r\n if (currentSortType == sortTypes.length - 2 || currentSortType == HIDDEN_SORT_TYPE) {\r\n currentSortType = 0;\r\n } else {\r\n currentSortType++;\r\n }\r\n sortTypes[currentSortType]();\r\n }",
"function sortFromHigh(items) {\n\t\"use strict\";\n\tvar temp;\n\tfor (var i = 0; i < items.length - 1; i++) {\n\t\tfor (var j = 0; j < items.length - 1 - i; j++) {\n\t\t\tvar p1 = parseInt(items[j].getElementsByTagName(\"price\")[0].childNodes[0].nodeValue.substring(3));\n\t\t\tvar p2 = parseInt(items[j + 1].getElementsByTagName(\"price\")[0].childNodes[0].nodeValue.substring(3));\n\t\t\tif (p1 <= p2) {\n\t\t\t\ttemp = items[j];\n\t\t\t\titems[j] = items[j + 1];\n\t\t\t\titems[j + 1] = temp;\n\t\t\t}\n\t\t}\n\t}\n\treturn items;\n}",
"insertionSort() {\r\n // eslint-disable-next-line\r\n if (this.disabled == false) this.animate(sortingAlgos.insertionSort(this.state.array), this.state.animationSpeed);\r\n\r\n }",
"function insertionSort(arr, arr_size) {\n // There should be atleast 1 elements \n if (arr_size < 1) {\n console.log(\" Invalid Input \");\n return;\n } else if (arr_size === 1) {\n console.log(\" Insertion Sort = \" + arr);\n return;\n }\n for (let i = 1; i < arr.length; i++) {\n const temp = arr[i];\n let j = i - 1;\n //Left Part[] Right Part[12, 35, 1, 10, 37, 1]\n // while loop chalega jab tak ki A[i] chota hua back array elemets se \n //Left Part[12] Right Part[35, 1, 10, 37, 1]\n // shuruat me A[j] {j=0} will be 12 and A[i] {i=1} will be 35 so no needt to replace \n //Left Part[12,35] Right Part[1, 10, 37, 1]\n // second me A[j] will be 12,35 {j= 0 to 1} and A[i] {i=2} will be 1 so \n //1. needt to replace 35 with 1 \n //2. again 1 with 12 \n while (j >= 0 && arr[j] > temp) {\n arr[j + 1] = arr[j]\n j--;\n }\n arr[j + 1] = temp;\n }\n console.log(\"The Insertion Sort = \" + arr + \"\\n\");\n}",
"sortAttack(items) {\n\n items.sort(function(a, b){\n\n if(a.atck < b.atck){ \n \n return -1;\n }\n if(a.atck > b.atck) {\n \n return 1;\n }\n return 0;\n })\n \n return items;\n \n }",
"function docEdits_sortWeights()\n{\n //var msg=\"presort -------------\\n\";\n //for (i=0; i<docEdits.editList.length; i++) {\n // msg += i+\":\" +docEdits.editList[i].weight+\"=\"+docEdits.editList[i].text+\"\\n\";\n //}\n //alert(msg);\n\n //shift-sort algorithm. Keeps same-weight chunks together\n for (var i=0; i < docEdits.editList.length-1; i++)\n {\n for (var j=i+1; j < docEdits.editList.length; j++)\n {\n var aType = docEdits.editList[i].weightType;\n var bType = docEdits.editList[j].weightType;\n\n var a = docEdits.editList[i].weightNum;\n var b = docEdits.editList[j].weightNum;\n\n if ((aType == bType && a != null && b != null && a > b)\n || (aType == \"belowHTML\" && bType==\"aboveHTML\"))\n {\n var temp = docEdits.editList[j];\n for (var k=j; k>i; k--)\n {\n docEdits.editList[k] = docEdits.editList[k-1];\n }\n docEdits.editList[i] = temp;\n }\n }\n }\n\n //var msg=\"After pre sort:\\n\";\n //for (i=0; i<docEdits.editList.length; i++) {\n // msg += i+\":\" +docEdits.editList[i].weight+\"=\"+docEdits.editList[i].text+\"\\n\";\n //}\n //alert(msg);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function is called when "Add New Sticky" button is clicked (see index.html) create a new Note object, set id, timestamp, position, and zindex properties; insert into database using saveAsNew() defined in its prototype | function newNote () {
var note = new Note();
note.id = ++highestId;
note.timestamp = new Date().getTime();
note.left = Math.round(Math.random() * 400) + 'px';
note.top = Math.round(Math.random() * 500) + 'px';
note.zIndex = ++highestZ;
note.saveAsNew();
} | [
"function Note() {\n\tvar self = this;\n\t\n\t// create main div for the sticky\n\tvar stickyDiv = document.createElement('div');\n\tstickyDiv.className = 'note';\n\t\n\t// see prototype definition\n\tstickyDiv.addEventListener('mousedown', function(e) { \n\t\treturn self.onMouseDown(e)\n\t}, false\t);\n\t\n\t// see prototype definition\n\tstickyDiv.addEventListener('click', function() {\n\t\treturn self.onNoteClick()\n\t}, false\t);\n\t\n\tself.note = stickyDiv;\n\t\n\t// create a div for the close button & append to main div\n\tvar closeBtn = document.createElement('div');\n\tcloseBtn.className = 'closebutton';\n\tcloseBtn.addEventListener('click',\tfunction(event) {\n\t\treturn self.close(event)\n\t}, false\t);\n\tstickyDiv.appendChild(closeBtn);\n\t\n\t// create a div for the edit field & append to main div\n\tvar edit = document.createElement('div');\n\tedit.className = 'edit';\n\tedit.setAttribute('contenteditable', true);\n\tedit.addEventListener('keyup', function() {\n\t\treturn self.onKeyUp()\n\t}, \tfalse);\n\tstickyDiv.appendChild(edit);\n\tself.editField = edit;\n\t\n\t// create a div for the timestamp & append to main div\n\tvar ts = document.createElement('div');\n\tts.className = 'timestamp';\n\tts.addEventListener('mousedown', function(e) {\n\t\treturn self.onMouseDown(e)\n\t}, false);\n\tstickyDiv.appendChild(ts);\n\tself.lastModified = ts;\n\t\n\tdocument.body.appendChild(stickyDiv);\n\treturn self;\n}",
"function addNote(){\n\t\t// get the span element that hode the number of notes\n\t\tcurCounter = $(this).parent().prev();\n\n\t\t// get the article id \n\t\tvar articleId = $(this).data('article-id');\n\n\t\t// store the article id in save button's data attr \n\t\t$('#btn-save-note').data('article-id', articleId);\n\t\t$('textarea').val('');\n\n\t\t// get the notes for this article\n\t\t$.get('api/article/' + articleId, function(data){\n\t\t\t// if there are notes create the list of notes\n\t\t\tif(data){\n\t\t\t\tcreateList(data.note);\n\t\t\t}\n\t\t});\n\n\t\t// show the modal box\n\t\t$('#modal-note').modal();\n\t}",
"createNote(){\n let note = Text.createNote(this.activeColor);\n this.canvas.add(note);\n this.notifyCanvasChange(note.id, \"added\");\n }",
"function addNote(e) {\n let addTxt = document.getElementById(\"addTxt\");\n let addTitle = document.getElementById(\"addTitle\");\n let notes = localStorage.getItem(\"notes\");\n if (notes == null) {\n notesObject = [];\n } else {\n notesObject = JSON.parse(notes);\n }\n let myObj = {\n title: addTitle.value,\n text: addTxt.value\n }\n notesObject.push(myObj);\n localStorage.setItem(\"notes\", JSON.stringify(notesObject));\n addTxt.value = \"\";\n addTitle.value = \"\";\n showNotes();\n}",
"function renderNotes(){\n $('#new-note-btn').show();\n $(\"#new-note-hr\").show();\n $(\"#note-index-container\").css('height', '');\n clearNotesDisplay(\"notes\");\n raw_notes.forEach(function(note){\n $(\".note-index\").append('<div class=\"note-tile btn btn-block transition-quick\" data-id=' + note[\"id\"] + '>' + trimTitle(note[\"title\"], titleDisplayLen) + '</div>');\n });\n addTileListener();\n}",
"function create (post_title, post_content) {\n var postData = {title: post_title, content: post_content};\n \n // send POST request to server to create new note on API \n $.post('/api/posts', postData, function(data) {\n var newPost = data;\n render(newPost);\n });\n }",
"async saveNote(note){\n const index = this.notes.findIndex(({ id }) => note.id === id )\n if (index === -1) {\n note.id = uuid()\n this.update(notes => notes.push(note))\n } else {\n this.update(notes => notes.splice(index, 1, note))\n }\n\n return note\n }",
"function createNotes() {\n\t\tvar notesEl = document.createElement('div'), notesElContent = '';\n\t\tnotesEl.className = 'notes';\n\t\tfor(var i = 0; i < totalNotes; ++i) {\n\t\t\t// we have 6 different types of symbols (icon--note1, icon--note2 ... icon--note6)\n\t\t\tvar j = (i + 1) - 8 * Math.floor(i/6);\n\t\t\tnotesElContent += '<div class=\"note icon icon--note' + j + '\"></div>';\n\t\t}\n\t\tnotesEl.innerHTML = notesElContent;\n\t\tshzEl.insertBefore(notesEl, shzEl.firstChild)\n\n\t\t// reference to the notes elements\n\t\tnotes = [].slice.call(notesEl.querySelectorAll('.note'));\n\t}",
"function createNoteObject(writebackContext, clinicalObjectUid, callback) {\n var noteObject = {};\n noteObject.patientUid = writebackContext.model.patientUid;\n noteObject.authorUid = writebackContext.model.authorUid;\n noteObject.domain = 'ehmp-note';\n noteObject.subDomain = 'noteObject';\n noteObject.visit = writebackContext.model.visit;\n noteObject.ehmpState = 'active';\n noteObject.referenceId = null;\n var noteObjectData = {};\n noteObjectData.sourceUid = clinicalObjectUid;\n noteObjectData.problemRelationship = '';\n noteObjectData.annotation = '';\n if (writebackContext.model.data) {\n if (writebackContext.model.data.problemRelationship) {\n noteObjectData.problemRelationship = writebackContext.model.data.problemRelationship;\n }\n if (writebackContext.model.data.annotation) {\n noteObjectData.annotation = writebackContext.model.data.annotation;\n }\n noteObjectData.madlib = writebackContext.model.data.madlib;\n }\n noteObject.data = noteObjectData;\n pjds.create(writebackContext.logger, writebackContext.appConfig, noteObject, function(err, response) {\n if (err) {\n return callback(err);\n }\n writebackContext.logger.debug({\n noteObject: response\n }, 'new note object');\n return callback(null, response.headers.location);\n });\n}",
"pushNoteCoord(x, y, speed) {\n this.allNotes.push(new Note (this.noteTexture, x, y, speed))\n this.active.push(true);\n }",
"function editNote(){\n\t\n\tvar moment = require('alloy/moment');\n\t\n\tvar note= myNotes.get(idNote);\n\tnote.set({\n\t\t\"noteTitle\": $.noteTitle.value,\n\t\t\"noteDescription\": $.noteDescription.value,\n\t\t\"date\": moment().format()\n\t}).save();\n\t\n\tvar toast = Ti.UI.createNotification({\n\t\t \t\t\t \tmessage:\"Note has been succesfully saved\",\n\t\t \t\t\tduration: Ti.UI.NOTIFICATION_DURATION_SHORT\n\t\t\t\t\t\t});\n\t\t\t\t\t\t\n\t\t\t\ttoast.show();\n\tAlloy.Collections.note.fetch();\n\t\n $.detailnote.close();\n\t\t\n}",
"function addNotes(note){\n\t\tconsole.log(JSON.stringify(note));\n\t\t//ignore already received notes\n\t\t// if(note.time <= info.time) return;\n\t\t/*use built in html5 audio player to play sounds*/\n\t\tnewElem = `<div>\n\t \t${new Date(note.time).toLocaleString()}\n\t \t<audio id=\"${note.path}\"\" controls>\n\t\t\t <source src=\"${note.path}\" type=\"audio/wav\">\n\t\t\t\tYour browser does not support the audio element.\n\t\t\t</audio>\n\t\t\tlistened: ${note.users.length}, received: ${note.receivers.length}\n\t\t\t</div>`;\n\t $(\"#messages\").append(newElem);\n\t /*update last received timestamp*/\n\t // if(note.time > info.lastTime){\n\t // \tinfo.lastTime = note.time;\n\t // }\n}",
"function set_note_button_callback() {\n songList.name = song_title_box.value;\n if ( !(songList.notes.length == 0) ) {\n var n = note_production_label.note;\n \n alert(songList.notes[songList.length - 1]);\n commandStack.execute(new SetNoteCommand(new Note(n.pitch, n.length),\n songList));\n drawSongArea();\n saveSong(songList);\n }\n}",
"function save () {\n\n\tvar title = postTitle.value;\n\tvar content = postContent.value;\n\tvar savedPost = { \"title\": title, \"content\": content };\n\n\tsaving = setInterval( saveItemToLocalStorage, 5000, savedPost, 'savedPost' );\n\n}",
"function send_notes_to_db() {\n let new_note = document.querySelector('textarea'); // reference to the textarea in the modal form\n db.collection(\"schedule_notes\").add({ // saves the timestamp and the contents of the textarea\n timestamp: last_day_picked,\n message: new_note.value\n })\n}",
"function testNewNote() {\n document.getElementById(\"result\").innerHTML += \"Test NoteList // NoteList newNote function creates and stores new note model:\";\n let noteList = new NoteList();\n let text = \"Checkmate 1-2 1-2!!\";\n console.log(`NotesDB before newNOte function: ${noteList.allNotes()}`)\n noteList.newNote(text);\n console.log(`NotesDB first array value: ${noteList.notesDb[0]}`)\n test.isEqual(noteList.notesDb[0].content === text);\n}",
"function createTodo() {\n // get the string value of input todo\n var newTodo = $('#newTodo').val();\n\n pushToTodos(newTodo);\n\n displayTodoItems(todos);\n\n storeTodos();\n\n // empty the input feild\n $('#newTodo').val('');\n }",
"function renderNote(note, notesDiv) {\n const noteDiv = document.createElement(\"div\");\n noteDiv.classList.add(\"note\");\n noteDiv.setAttribute(\"data-id\", note.id)\n notesDiv.appendChild(noteDiv);\n\n // Retrieve data\n const title = note.title;\n const desc = note.desc;\n const date = note.date;\n const time = note.time;\n const priority = note.priority;\n\n // Create DOM elements for data\n\n // Title\n const noteTitle = document.createElement(\"p\");\n noteTitle.classList.add(\"note-title\");\n noteTitle.innerHTML = title;\n noteDiv.appendChild(noteTitle);\n\n if(new Date().toISOString().split(\"T\")[0] <= date) {\n // Add clock fa icon showing how much time until the note's date!\n const clockIcon = document.createElement(\"div\");\n noteTitle.appendChild(clockIcon);\n clockIcon.classList.add(\"fas\", \"fa-clock\");\n clockIcon.innerHTML = \"\"\n clockIcon.style.color = getColorByPriority(priority);\n clockIcon.style.fontSize = \"22px;\"\n }\n\n \n // Hidden div containing rest of the info about this note\n const noteInfo = document.createElement(\"div\");\n noteInfo.classList.add(\"note-info\")\n noteInfo.style.display = \"none\";\n noteDiv.appendChild(noteInfo);\n\n // Description\n const noteDescDiv = document.createElement(\"div\");\n noteDescDiv.classList.add(\"note-desc-div\");\n const noteDesc = document.createElement(\"p\");\n noteDescDiv.appendChild(noteDesc);\n noteDesc.classList.add(\"note-desc\");\n noteDesc.innerHTML = desc;\n noteInfo.appendChild(noteDescDiv);\n\n // Date\n if(date !== \"\") {\n const notedate = document.createElement(\"p\");\n notedate.classList.add(\"note-date\");\n notedate.innerHTML = date;\n noteInfo.appendChild(notedate);\n }\n\n // Time\n if(time !== \"\") {\n const noteTime = document.createElement(\"p\");\n noteTime.classList.add(\"note-time\");\n noteTime.innerHTML = time;\n noteInfo.appendChild(noteTime);\n }\n\n // Edit button at the bottom\n const editBtn = document.createElement(\"btn\")\n noteInfo.appendChild(editBtn);\n editBtn.classList.add(\"btn\", \"btn-sm\", \"btn-danger\", \"btn-outline-white\")\n editBtn.innerHTML = \"Edit Note\";\n\n // Add event listener to that button\n\n editBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n\n const noteDiv = e.target.parentElement.parentElement;\n // const noteId = noteDiv.getAttribute(\"data-id\");\n\n // Remove note's child elements\n Array.from(noteDiv.children).forEach(child => {\n child.remove()\n })\n\n // And render edit form in place of it\n renderEditNote(noteDiv, title, desc, date, time, priority);\n\n })\n \n\n // Toggle between showing noteInfo when clicking on a note (WITH FADE ANIMATION)\n noteDiv.addEventListener(\"click\", () => {\n if(noteInfo.style.display !== \"block\") {\n\n noteInfo.style.opacity = 0;\n noteInfo.style.display = \"block\";\n setTimeout(() => {\n noteInfo.style.opacity = 1;\n }, 100)\n } else {\n noteInfo.style.opacity = 0;\n setTimeout(() => {\n noteInfo.style.display = \"none\"; \n }, 500)\n }\n })\n\n \n // Set note's background color according to priority!\n const divColor = getColorByPriority(priority);\n noteDiv.style.cssText = `background-color: ${divColor}`;\n\n // Add delete button for note!\n const deleteNote = document.createElement(\"div\");\n deleteNote.classList.add(\"delete-note\", \"fas\", \"fa-times\");\n noteDiv.appendChild(deleteNote);\n\n // Add event listener for the button!\n deleteNote.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n if (confirm(\"Are you sure you want to delete this note? This action cannot be undone!\")) {\n const note = e.target.parentElement;\n const notes = e.target.parentElement.parentElement;\n\n const projectId = notes.getAttribute(\"data-id\");\n const noteId = note.getAttribute(\"data-id\");\n\n\n db.collection('Users')\n .doc(auth.currentUser.uid)\n .collection(\"Projects\")\n .doc(projectId)\n .collection(\"Notes\")\n .doc(noteId)\n .delete()\n .then(() => {\n location.reload();\n });\n \n }\n });\n \n }",
"function insert_trips(trip_id){\n INS_TRIPS = true;\n var opt_rte;\n var locations;\n var flexbus_id;\n var home;\n var html_data = $('#infoWindow').html(); \n console.log(trip_id);\n console.log(READY_TO_INS_TRIPS);\n var trip_ids;\n trip_ids = JSON.stringify(trip_id);\n console.log(trip_ids);\n $('#infoWindow').html('Current Time is ' + seconds + ' seconds.<br>' + html_data); \n console.log('Inserting trips at time ' + seconds);\n $.ajaxSetup({async:true});\n $.post('/insert_trip/', {\"second\":seconds, \"trip_ids\":trip_ids},\n\t function(data){\n\t seconds = seconds + 1; // finished with inserting passengers, increment by one second\n\t INS_TRIPS = false;\n\t }\n\t );\n return;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks the message display to see who's turn it is and changes it to the other player. changes the color of the message to make it clearer which player's turn it is. is called in the checkAnswer function to execute when the user submits and answer. | function switchTurn() {
if (turn === "player 2") {
turn = "player 1";
setMessage(turn + "'s turn");
document.getElementById("playerTurn").style.color ="hotpink";
} else {
turn = "player 2";
setMessage(turn + "'s turn");
document.getElementById("playerTurn").style.color ="gold";
}
} | [
"function setMessage(){\n message.textContent = `${tempInput.value} is equal to ` + result + ` Degrees ` + type;\n message.style.color = 'initial';\n}",
"function check() {\n // Determine milliseconds elapsed since the color was loaded\n var milliseconds_taken = Date.now() - time_at_load;\n\n // Calculate the percents that the user was off\n var percents = {\n red: (Math.abs(color.red - guess.red)/255)*100,\n green: (Math.abs(color.green - guess.green)/255)*100,\n blue: (Math.abs(color.blue - guess.blue)/255)*100\n };\n\n // Calculate the average (overall) percent off\n var percent_off = (percents.red + percents.green + percents.blue)/3;\n\n // Calculate the turn's score\n var turn_score = ((15 - settings.difficulty - percent_off) /\n (15 - settings.difficulty)) *\n (15000 - milliseconds_taken);\n\n // If positive, round to 2 decimals. If negative, set to 0.\n turn_score = (turn_score > 0) ? (Math.round(turn_score*100)/100) : 0;\n\n // Add the score for the turn to the running total\n total_score += turn_score;\n\t\ttotal_score = (Math.round(total_score*100)/100)\n\n\t\t// decrease the turn count\n turns_remaining--;\n\n\t\t// check if no turns remain\n if(turns_remaining > 0) {\n newColor();\n\n // Display the current statistics\n $('#result').html(\"Last Score: \" + turn_score +\n \"; Total Score: \" + total_score +\n \"; Turns Left: \" + turns_remaining);\n\n } else {\n // create a new div element to display game over info for the user\n // wrapped in a div for easy removing on game reset\n var gameOver = $('<div>').attr('id', 'gameOver');\n\n // Add a header to denote game over\n gameOver.append($(\"<h2>\").text(\"Game Over!\"));\n\n // Show the final score from the game\n gameOver.append($(\"<p>\").text(\"Final Score: \" + total_score));\n\n\t\t\t// Create the input for players to input a name for their high score\n var playerNameInput = $('<input>').attr('placeholder', 'Your name');\n\n\t\t\t// Add the input to the page with an ID for easy value access\n gameOver.append(playerNameInput.attr('id', 'hsName'));\n\n\t\t\t// Create a submit button to send the score to the high scores array\n var submit = $('<button>').text(\"Submit High Score!\");\n submit = submit.attr(\"type\", \"button\").attr(\"id\",\"hsSubmit\");\n\n\t\t\t// Show the button\n gameOver.append(submit.click(submitHighscore));\n\n\t\t\t// Create a try again buton to allow users to restart the game over\n\t\t\tvar againButton = $(\"<button>\").text(\"Try Again!\");\n\n\t\t\t// Show the button\n gameOver.append(againButton.attr(\"type\", \"button\").click(reset));\n\n\t\t\t// Hide the game so they can't keep playing\n gameElement.children().hide();\n\n\t\t\t// Add the game over elements\n gameElement.append(gameOver);\n }\n }",
"function matchMessageBoardColorTo(riskLevel) {\r\n if (riskLevel === \"lowRisk\") {\r\n document.getElementById(\"display-message\").style.backgroundColor = '#62b1f5';\r\n }\r\n if (riskLevel === \"mediumRisk\") {\r\n document.getElementById(\"display-message\").style.backgroundColor = '#ffff82';\r\n }\r\n if (riskLevel === \"highRisk\") {\r\n document.getElementById(\"display-message\").style.backgroundColor = '#f56262';\r\n }\r\n\r\n}",
"function change_result_panel_color(correct_answer, user_choice, result_panel) {\n if (correct_answer === user_choice) {\n result_panel.find('span').css('background-color', '#5cb85c');\n result_panel.find('span').css('color', '#fff');\n result_panel.find('span').css('border-color', '#4cae4c');\n }\n else {\n result_panel.find('span').css('background-color', '#d9534f');\n result_panel.find('span').css('color', '#fff');\n result_panel.find('span').css('border-color', '#d43f3a');\n }\n}",
"function playerTurn() {\n setMessage(turn + \"'s turn\");\n }",
"function checkWinner() {\n if (player1Score === 20) {\n setMessage(\"player 1 wins\");\n document.getElementById(\"ci1a\").disabled = true;\n document.getElementById(\"ci1b\").disabled = true;\n document.getElementById(\"ci1c\").disabled = true;\n document.getElementById(\"ci1d\").disabled = true;\n document.getElementById(\"ci2a\").disabled = true;\n document.getElementById(\"ci2b\").disabled = true;\n document.getElementById(\"ci2c\").disabled = true;\n document.getElementById(\"ci2d\").disabled = true;\n playAgain();\n } else if (player2Score === 20) {\n setMessage(\"player 2 wins\");\n document.getElementById(\"ci1a\").disabled = true;\n document.getElementById(\"ci1b\").disabled = true;\n document.getElementById(\"ci1c\").disabled = true;\n document.getElementById(\"ci1d\").disabled = true;\n document.getElementById(\"ci2a\").disabled = true;\n document.getElementById(\"ci2b\").disabled = true;\n document.getElementById(\"ci2c\").disabled = true;\n document.getElementById(\"ci2d\").disabled = true;\n playAgain();\n }\n }",
"function updateDifficultyText() {\r\n if (difficulty === 0) {\r\n $($difficulty).text('Easy');\r\n updateScorecardColor('Easy');\r\n $diffButton.removeClass('challening');\r\n $diffButton.removeClass('impossible');\r\n $diffButton.addClass('easy');\r\n $titleBar.removeClass('challening');\r\n $titleBar.removeClass('impossible');\r\n $titleBar.addClass('easy');\r\n\r\n } else if (difficulty === 1) {\r\n $($difficulty).text('Challenging');\r\n updateScorecardColor('Challenging');\r\n $diffButton.removeClass('easy');\r\n $diffButton.removeClass('impossible');\r\n $diffButton.addClass('challening');\r\n $titleBar.removeClass('easy');\r\n $titleBar.removeClass('impossible');\r\n $titleBar.addClass('challening');\r\n\r\n } else if (difficulty === 2) {\r\n $($difficulty).text('Impossible');\r\n updateScorecardColor('Impossible');\r\n $diffButton.removeClass('easy');\r\n $diffButton.removeClass('challening');\r\n $diffButton.addClass('impossible');\r\n $titleBar.removeClass('easy');\r\n $titleBar.removeClass('challening');\r\n $titleBar.addClass('impossible');\r\n }\r\n console.log(difficulty);\r\n }",
"function updateColor() {\n if( userScore > compScore ) {\n //Player is winning\n table.style.border = \"5px solid #38d020\"\n } else if ( compScore > userScore ) {\n //Computer is winnning\n table.style.border = \"5px solid #d21f1f\"\n } else {\n //If there is a draw\n table.style.border = \"5px solid #363636\"\n }\n}",
"function checkAnswerAndReset(colorChosen) {\n if (colorChosen === validColor) {\n setCorrectAnswers(correctAnswers + 1);\n }\n startNewGame(false);\n }",
"function showAnswer(gameWon) {\n\n var codeLabel = document.getElementById('code');\n // codeLabel.innerHTML = '<strong>' + answer.value + '</strong>';\n codeLabel.innerHTML = answer.value;\n if (gameWon) {\n // add success class to code label\n codeLabel.classList.add('success');\n } else {\n // add lost failure class\n codeLabel.classList.add('failure');\n }\n}",
"function checkAnswer(currIndex) {\r\n if (userClickedPattern[currIndex] === gamePattern[currIndex]) {\r\n\r\n // If userClickedPattern = gamePattern entirely, then go to next sequence.\r\n\r\n if (userClickedPattern.length === gamePattern.length) {\r\n userClickedPattern = [];\r\n\r\n setTimeout(function() {\r\n nextInSequence();\r\n }, 1000);\r\n }\r\n }\r\n\r\n // Game Over - If user's color choice does not match matching index color of gamePattern, reset level, userClickedPattern, and gamePattern.\r\n\r\n else {\r\n $(\"h1\").text(\"Game Over, Press Any Key to Restart\");\r\n\r\n playSound(\"wrong\");\r\n animate(\"body\", 200, \"game-over\");\r\n\r\n level = 0;\r\n userClickedPattern = [];\r\n gamePattern = [];\r\n }\r\n}",
"function change_text( player, target_hit )\n{\n\tfor (var i = 0; i < board_sections.length; i++) \n\t{\n\t\tvar section_text = $(board_sections[i]).text();\n\t\tif (target_hit == section_text) \n\t\t{\n\t\t\tif (player.marker == 'X') \n\t\t\t{\n\t\t\t\t$(board_sections[i]).css('color', '#91c46b');\n\t\t\t\t$(board_sections[i]).text('X');\n\n\t\t\t}\n\t\t\telse if (player.marker == 'O')\n\t\t\t{\n\t\t\t\t$(board_sections[i]).css('color', '#d9534f');\n\t\t\t\t$(board_sections[i]).text('O');\n\t\t\t}\n\t\t}\n\t}\n\tcheck_game( player );\n}",
"function correctGuess() {\n score += wrongAnswersLeft;\n if (score > hScore) {\n hScore = score;\n }\n setCorrectScreen(wrongAnswersLeft);\n }",
"function buttonClickPlayerTwo() {\n if($(this).hasClass(\"correct\")){\n $(\".correct\").css(\"background-color\", \"#00FF00\");\n correctAudio.play();\n p2Score = p2Score + 10;\n $(\"#score2\").html(\"Score: \" + p2Score);\n }\n else if ($(this).hasClass(\"incorrect\")) {\n $(this).css(\"background-color\", \"#FF0000\");\n incorrectAudio.play();\n }\n $(answerBtns2).off(\"click\");\n }",
"function toggleWin(winner, name, screen)\n{\n const message = screen.querySelector('.message');\n const winnerName = screen.querySelector('.winner');\n //color of the winner's name depends on who won\n const color = (winner === 'x') ? 205 : 0;\n\n //changes to win screen\n switchScreen(screen);\n\n //activates the win screen of the given winner\n screen.classList.add(`screen-win-${winner}`);\n //changes win message accordingly\n message.textContent = (winner === 't') ? ('It\\'s a Cat!') : ('Winner');\n //sets winner name's text and color for display\n winnerName.textContent = name.toUpperCase();\n winnerName.style.color = `rgba(${color}, ${color}, ${color}, 0.3)`\n}",
"function processBotAnswer(answer) {\n if (answer === allQuestions[currentQuestionIndex].correctAnswer) {\n $(\"#answer-response\").html(\"An opponent answered first: \" + allQuestions[currentQuestionIndex].correctAnswer);\n $(\"#answer-response\").removeClass(\"hide\");\n finishQuestion();\n }\n}",
"function producePrompt(message, promptLocation, color)\n{\n\tdocument.getElementById(promptLocation).innerHTML = message; \n\tdocument.getElementById(promptLocation).style.color = color; \n}",
"gameOver(result) {\n document.getElementById('overlay').style.display = '';\n if (result === 'win') {\n document.getElementById('game-over-message').className = 'win';\n document.getElementById('game-over-message').innerHTML = `<br><i>Wow, you reached 88 miles per hour!</i> 🏎️💨 <p>Nailed it! The phrase was \"${this.activePhrase.phrase.toUpperCase()}\"!</p>`;\n document.getElementById('btn__reset').textContent = 'Go back to the future & try again?';\n } else {\n document.getElementById('game-over-message').className = 'lose';\n document.getElementById('game-over-message').innerHTML = `<br><i>Think, McFly, think!</i> 😖💭 <p>Better luck next time! The phrase was \"${this.activePhrase.phrase.toUpperCase()}\".</p>`;\n document.getElementById('btn__reset').textContent = 'Go back in time & try again?';\n }\n this.resetGame();\n }",
"draw_ready_message() {\r\n\r\n if (this.game_data.message_count > 0) {\r\n\r\n this.data.game.set_text_font('30pt Impact');\r\n this.data.game.set_text_color('#ffffff');\r\n //this.data.game.text_write(self.game_data.message, 200, 444); \r\n this.data.game.text_write('Ready!', 330, 414); \r\n this.game_data.message_count --;\r\n \r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Awake(): Called by Unity when the script has loaded. We use this function to initialise our link to the Lerpz GameObject. | function Awake()
{
//levelGoal.GetComponent(MeshCollider).isTrigger = false;
playerLink = GameObject.FindGameObjectWithTag("Player");
if(!playerLink)
Debug.Log("Could not get link to Lerpz");
} | [
"function init() {\n \"use strict\";\n \n var game = new Phaser.Game(384, 640, Phaser.AUTO);\n game.state.add('splashscreen', splashScreen);\n game.state.add('screen1', screen1);\n game.state.add('detailscreen1', detailScreen1);\n game.state.add('detailscreen2', detailScreen2);\n game.state.add('detailscreen3', detailScreen3);\n\n document.addEventListener('deviceready', onDeviceReady.bind(this), false);\n\n function onDeviceReady() { \n game.state.start('splashscreen');\n };\n\n \n}",
"_init() {\n try {\n if (!fs.existsSync(LINKS_DIR)) {\n fs.mkdirSync(LINKS_DIR);\n }\n this.links = require(LINKS_PATH);\n\n for (const key in this.links) {\n if (this.links.hasOwnProperty(key)) {\n const url = this.links[key].url;\n\n if (!this._urls[url]) {\n this._urls[url] = key;\n }\n }\n }\n }\n catch (e) {\n pino.error('Could not load links: ' + e.message);\n }\n }",
"setup() {\n this.player.setup();\n }",
"function init(liliPads)\r\n\t{\r\n\t\tthis.liliPads = liliPads;\r\n\t\tthis.lifeBar.init();\r\n\t}",
"init() {\n\t\t'use strict';\n\t\tthis.createRenderer();\n\t\tthis.createScene();\n\n\t\tthis.clock = new THREE.Clock;\n this.clock.start();\n\n\n\t\twindow.addEventListener(\"keydown\", KeyDown);\n window.addEventListener(\"keyup\", KeyUp);\n\t}",
"createLamp(x, y, z) {\n\t\t'use strict';\n\t\tvar lamp = new Lamp(x, y, z);\n\n\t\tlamp.createLampBase();\n\t\tlamp.createLampBulbSupport();\n\t\tlamp.createLampBulb();\n\t\tlamp.createLampAbajour();\n\t\tthis.scene.add(lamp);\n\t\treturn lamp;\n\t}",
"init() {\n\t\tdocument.body.append(this.view);\n\t\tthis.functions.load();\n\t\tthis.Loader.load(async (loader, resources) => {\n\t\t\tlet i = 0;\n\t\t\tfor (const [name, value] of Object.entries(resources)) {\n\t\t\t\tif (loader.rorkeResources[i].options) {\n\t\t\t\t\tconst urls = await this.Loader.splitSpritesheetIntoTiles(\n\t\t\t\t\t\tvalue.data,\n\t\t\t\t\t\tloader.rorkeResources[i].options,\n\t\t\t\t\t);\n\t\t\t\t\tconst textures = urls.map(tile => Texture.from(tile));\n\t\t\t\t\tthis.spritesheets.set(name, {\n\t\t\t\t\t\ttexture: value.texture,\n\t\t\t\t\t\toptions: loader.rorkeResources[i].options,\n\t\t\t\t\t\ttiles: urls,\n\t\t\t\t\t\ttextures,\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tthis.textures.set(name, value.texture);\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tthis.runCreate();\n\t\t});\n\t}",
"function Awake ()\n{\n\trigidbody.freezeRotation = true;\n}",
"function initObjectOrientation() {\n\n config.cube.position = {\n x: -config.cube.dimensions.width / 2,\n y: 3,\n z: 0\n };\n config.bouncingSphere.position = {\n x: 20,\n y: config.bouncingSphere.dimensions.diameter / 2,\n z: 2\n };\n config.archingSphere.position = {\n x: (config.cube.position.x - config.bouncingSphere.position.x) / 2,\n y: config.bouncingSphere.position.y,\n z: 0\n };\n config.pointLightSphere.position = {\n x: 3,\n y: config.pointLightSphere.dimensions.diameter, // raised above plane by 1/2 diameter length\n z: 3\n };\n}",
"LoadScene()\n {\n\n if ( this.__loaded )\n {\n console.error( \"Unable to load scene, already loaded \" )\n return;\n }\n\n this.LocalSceneObjects.forEach( element => {\n\n let _constructor = element[0];\n let _serializedCallback = element[1];\n \n let obj = this.Create( _constructor, GameObject.COMPONENT_INIT_MODES.NO_SYNC );\n _serializedCallback( obj );\n\n } );\n\n this.__loaded = true;\n }",
"function init() {\n\tcamera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10000);\n\tcamera.position.z = 700;\n\tcamera.up.set(0, 0, 1);\n\n\tconsole.log(\"initialisation\", camera)\n\n\tscene = new THREE.Scene();\n\n\tcreateMap();\n\n\trenderer = new THREE.WebGLRenderer({\n antialias: true,\n logarithmicDepthBuffer: false,\n });\n\trenderer.setSize(window.innerWidth, window.innerHeight);\n\tdocument.body.appendChild(renderer.domElement);\n\n\t// Define orbitControls and their initial state\n\tcontrols = new THREE.OrbitControls(camera, renderer.domElement);\n\n\tcontrols.saveState()\n}",
"function Start () {\n PartLoader.PreloadParts();\n\tvar part1 = PartLoader.LoadPart(\"Cockpit1\");\n\tvar part2 = PartLoader.LoadPart(\"Engine1\");\n\t//var part3 = PartLoader.LoadPart(\"Engine1\");\n\t//var part4 = PartLoader.LoadPart(\"Engine1\");\n\t//var part5 = PartLoader.LoadPart(\"Engine1\");\n\tpart1.transform.parent = transform;\n\tpart2.transform.parent = transform;\n\t//part3.transform.parent = transform;\n\t//part4.transform.parent = transform;\n\t//part5.transform.parent = transform;\n\tvar ship : ShipBehavior = GetComponent(\"ShipBehavior\") as ShipBehavior;\n\tship.Initialize();\n\t(part1.GetComponent(PartBehavior) as PartBehavior).ConnectToHardpoint((part2.GetComponent(PartBehavior) as PartBehavior),0,0);\n\t//(part3.GetComponent(\"PartBehavior\") as PartBehavior).ConnectToHardpoint((part2.GetComponent(\"PartBehavior\") as PartBehavior),1,2);\n\t//(part4.GetComponent(\"PartBehavior\") as PartBehavior).ConnectToHardpoint((part2.GetComponent(\"PartBehavior\") as PartBehavior),2,1);\n\t//(part5.GetComponent(\"PartBehavior\") as PartBehavior).ConnectToHardpoint((part2.GetComponent(\"PartBehavior\") as PartBehavior),3,4);\n\t\n}",
"function parallax_init()\n{\n\t//Nucleo do widget (não mecha)\n\tparallax_Box = document.createElement(\"div\");\n\tparallax_Box.id = \"parallaxContainer\";\n\tdocument.body.insertBefore(parallax_Box, document.body.firstChild);\n\n\tparallax_Layer0 = $(parallax_Box);\n\t\n\tparallax_custom_init();\n\t\n\t//Ajustes finais\n\t$(window).scroll(parallax_run);\n\t$(window).resize(parallax_size);\n\tparallax_size(null);\n\tparallax_run(null);\n}",
"init(){\n this.speedX=0;\n this.speedY=-this.maxSpeed;\n this.speedZ=0;\n\n // these two components are used to know speed in the new coordinates after a rotation\n this.speedXAfterRotate=0;\n this.speedZAfterRotate=0;\n\n let now = (new Date).getTime();\n this.lastUpdate=now;\n }",
"function initLunr() {\n\n\t\t\t// First retrieve the index file\n\t\t\t$.getJSON(\"/js/lunr/PagesIndex.json\")\n\t\t\t\t.done((index) => {\n\t\t\t\t\tpagesIndex = index;\n\n\t\t\t\t\t// Set up lunrjs by declaring the fields we use\n\t\t\t\t\t// Also provide their boost level for the ranking\n\t\t\t\t\tlunrIndex = lunr(function() {\n\t\t\t\t\t\tthis.field(\"title\", {\n\t\t\t\t\t\t\tboost: 10\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.field(\"content\", {\n\t\t\t\t\t\t\tboost: 5\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.field(\"category\");\n\n\t\t\t\t\t\t// ref is the result item identifier (I chose the page URL)\n\t\t\t\t\t\tthis.ref(\"href\");\n\t\t\t\t\t});\n\n\t\t\t\t\tpagesIndex.map(pageMapper).forEach((page) => {\n\t\t\t\t\t\tlunrIndex.add(page);\n\t\t\t\t\t});\n\t\t\t\t})\n\t\t\t\t.fail((jqxhr, textStatus, error) => {\n\t\t\t\t\tvar err = textStatus + \", \" + error;\n\t\t\t\t\tconsole.error(\"Error getting Hugo index file:\", err);\n\t\t\t\t});\n\t\t}",
"function init(){\n homeScreen.createHomePage();\n beaverEvents.addModel(beaverApp);\n beaverEvents.addModel(beaverRelations);\n beaverEvents.getViewState(homeScreen);\n beaverEvents.getViewState(profileView);\n beaverEvents.activeView = homeScreen.name;\n beaverEvents.viewState.homeScreen.showMapButton();\n // Display beavers\n beaverEvents.displayBeavers();\n // beaverEvents.getGeoLocation();\n homeScreenHandlers.setupEvents();\n}",
"function initializeLesson() {\r\n lesson11.init();\r\n animate();\r\n}",
"function createPortal() {\n var portal = createSprite(350, 250);\n portal.setAnimation(\"lollipop_red_1\");\n portal.scale = 0.7;\n portal.rotationSpeed = -5;\n //portal.debug = true;\n portal.setCollider(\"circle\");\n return portal;\n}",
"function initializePlayer(){\n let scale = scalePlayer(mode);\n playerHP = 100;\n playerFuel = 100;\n carsPassed = 0;\n //Player start position\n player = createSprite(playerX,playerY, \n carW / scale, carH / scale);\n player.addImage('start', p00);\n player.addImage('dmg01', p01);\n player.addImage('dmg02', p02);\n player.addImage('dmg03', p03);\n player.addImage('dmg04', p04);\n player.addImage('dmg05', p05);\n player.changeImage('start');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete Flavor Params by ID. | static deleteAction(id){
let kparams = {};
kparams.id = id;
return new kaltura.RequestBuilder('flavorparams', 'delete', kparams);
} | [
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('flavorasset', 'delete', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('thumbparams', 'delete', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('caption_captionparams', 'delete', kparams);\n\t}",
"deleteById(id) {\n return this.del(this.getBaseUrl() + '/' + id);\n }",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('fileasset', 'delete', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_distributionprofile', 'delete', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('cuepoint_cuepoint', 'delete', kparams);\n\t}",
"async destroy ({ params, request, response }) {\n const tarefa = await Tarefa.findOrFail(params.id);\n await tarefa.delete();\n }",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('responseprofile', 'delete', kparams);\n\t}",
"static get(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('flavorparamsoutput', 'get', kparams);\n\t}",
"static update(id, flavorParams){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\tkparams.flavorParams = flavorParams;\n\t\treturn new kaltura.RequestBuilder('flavorparams', 'update', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('contentdistribution_genericdistributionprovideraction', 'delete', kparams);\n\t}",
"destroy(id) {\n return db.none(`\n DELETE FROM parks\n WHERE id = $1`, id);\n }",
"function getDatabaseParameterDeleteCategory (params, query, body){\r\n\tvar parameters = {\r\n\t\twhere: { category_id: params.id },\r\n\t};\r\n\treturn parameters;\r\n}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('emailingestionprofile', 'delete', kparams);\n\t}",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('conversionprofile', 'delete', kparams);\n\t}",
"static deleteAction(drmPolicyId){\n\t\tlet kparams = {};\n\t\tkparams.drmPolicyId = drmPolicyId;\n\t\treturn new kaltura.RequestBuilder('drm_drmpolicy', 'delete', kparams);\n\t}",
"delete(req, res) {\n Origin.destroy({\n where: {\n id: req.params.id\n }\n })\n .then(function (deletedRecords) {\n res.status(200).json(deletedRecords);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }",
"static deleteAction(id){\n\t\tlet kparams = {};\n\t\tkparams.id = id;\n\t\treturn new kaltura.RequestBuilder('accesscontrolprofile', 'delete', kparams);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function returns a json object containing the heart rate data of all users There is an optional parameter range that specifies a range of data wanted: EX: 1d, 1w, 1m | async function heartRateAllPeriod(req, res) {
if(userList.length === 0) {
return res.status(400).send("There are not any available Users. Please add a user")
}
try{
const tableData = await heartRateFetch.fetchAllHeartRatesPeriod(userList, req.query.range)
res.json(tableData)
} catch(error) {
res.status(400).json({ status: "error", msg:`${error.msg}` })
}
} | [
"async function heartRateAllDate(req, res) {\n const startDate = req.query.start\n const endDate = req.query.end\n\n // See if any parts of the body are undefined\n if(startDate === undefined || endDate === undefined) {\n return res.status(400).json({ status: \"error\", msg: \"The start, end date, or user was not supplied.\" })\n }\n\n try {\n const tableData = await heartRateFetch.fetchAllHeartRateRange(userList, startDate, endDate)\n return res.json(tableData)\n } catch(error) {\n return res.status(400).json({ status: \"error\", msg:`${error.msg}` })\n }\n}",
"function handleHeartRateNotifications(event) {\n // In Chrome 50+, a DataView is returned instead of an ArrayBuffer.\n let value = event.target.value;\n value = value.buffer ? value : new DataView(value);\n let id = event.target.service.device.id;\n let timestamp = new Date().getTime();\n let flags = value.getUint8(0);\n let rate16Bits = flags & 0x1;\n let result = {};\n let index = 1;\n if (rate16Bits) {\n result.heartRate = value.getUint16(index, /*littleEndian=*/true);\n index += 2;\n } else {\n result.heartRate = value.getUint8(index);\n index += 1;\n }\n\n heartRateText.innerHTML = 'HR: ' + result.heartRate + ' bpm';\n heartRateValues.push(result.heartRate);\n\n if (result.heartRate > maxHRVal) {\n maxHRVal = result.heartRate;\n }\n if (result.heartRate < minHRVal) {\n minHRVal = result.heartRate;\n }\n let heartRateRange = maxHRVal - minHRVal;\n var heartRatePlotValues = heartRateValues.map(function(element) {\n return (element - minHRVal)/heartRateRange;\n });\n\n\n if (heartRateValues.length > 45) {\n heartRateValues.shift();\n }\n\n drawWaves(heartRatePlotValues, heartRateCanvas, 1, 60, 70);\n}",
"function startHR() {\nheartRateArray = new Array();\nwindow.webapis.motion.start(\"HRM\", function onSuccess(hrmInfo) {\n if (hrmInfo.heartRate > 0) \n HR = hrmInfo.heartRate;\n});\n//sendingInterval = setInterval(sendHR, 5000);\nsendingInterval = setInterval(makeJsonHR, 5000);\n}",
"function getMetricsData() {\n //select Average Page View\n data.avgPageView = $('#card_metrics > section.engagement > div.flex > div:nth-child(1) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Average Time On Site\n data.avgTimeOnSite = $('#card_metrics > section.engagement > div.flex > div:nth-child(2) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Bounce Rate\n data.bounceRate = $('#card_metrics > section.engagement > div.flex > div:nth-child(3) > p.small.data').text().replace(/\\s\\s+/g, '').split(' ')[0];\n\n //select Search Traffic Percent\n data.searchTrafficPercent = $('#card_mini_competitors > section.group > div:nth-child(2) > div.ThirdFull.ProgressNumberBar > span').text();\n\n //select Overall Rank\n data.overallRank = $('#card_rank > section.rank > div.rank-global > div:nth-child(1) > div:nth-child(2) > p.big.data').text().replace(/\\s+/g, ''); //.replace(/,/g, '');\n\n }",
"function getAllThreats() {\n baseRequest.get(\"threats\", function(err, res, body){\n if (err) {\n console.log(err);\n } else if (!err && res.statusCode == 200) {\n let info = JSON.parse(body);\n let data = info.data;\n data.forEach(t => {\n let disp = new table();\n disp.push(\n { 'Domain': t.agentdomain },\n { 'Client': t.siteName },\n { 'Agent': t.agentComputerName },\n { 'Description': t.description },\n { 'File': t.fileDisplayName },\n { 'Path': t.filePath },\n { 'Resolved?': t.resolved },\n { 'Agent ID': t.agentId }\n )\n console.log(disp.toString());\n })\n console.log(data[0].agentId);\n } else {\n console.log(\"HTTP Status Code: \" + res.statusCode);\n console.log(body);\n }\n })\n}",
"function dataDayTemp(){\napp.get('/api/statisticsByDay/Temp', (req, res)=>{\n let sql = \"SELECT * FROM SensorTemp WHERE Date = '\"+valueDate+\"';SELECT MAX(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"';SELECT MIN(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"';SELECT SUM(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"' AND Temp>32;SELECT SUM(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"' AND Temp<18;SELECT SUM(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"' AND Temp BETWEEN 18 AND 32;SELECT AVG(Temp) FROM SensorTemp WHERE Date = '\"+valueDate+\"'\";\n con.query(sql, (err, result, fields)=>{\n if (err) throw err;\n res.json(result);\n });\n})\n}",
"function getAvailableMetrics() {\n\t$.ajax({ \n\t\ttype: \"get\",\n\t\turl: \"restAPI/agents/\"+window.params.agentID+\"/availableMetrics\",\n\t\tbeforeSend: function(req) {\n\t\t\treq.setRequestHeader(\"Accept\", \"application/json\");\n\t\t},\n\t\tcontentType: \"application/json\",\n\t\tdataType: \"json\",\n\t\tsuccess: populateMetrics\n\t});\n}",
"static async getAllRates() {\n return new Promise((resolve, reject) => {\n oxr.latest(function() {\n // You can now use `oxr.rates`, `oxr.base` and `oxr.timestamp`\n let data = {\n rates: oxr.rates,\n base: oxr.base,\n timestamp: oxr.timestamp\n };\n return resolve(data);\n });\n });\n }",
"function CookiesEachHour(min, max, avg) {\n var customerNumArray = [];\n for (let index = 0; index < hour.length; index++) {\n customerNumArray.push(Math.floor(getRandomNum(min, max) * avg));\n\n }\n return customerNumArray;\n}",
"function rate_limit_return(request){\n $.getJSON(options.twitter_rate_limit_url,function(data){\n console.log(\"-------------------------------------------------------\");\n console.log(\"RATE LIMIT STATUS\");\n console.log(\" User Timeline Limit: \"+ data.resources.statuses['/statuses/user_timeline'].limit);\n console.log(\" User Timeline Remaining: \"+ data.resources.statuses['/statuses/user_timeline'].remaining);\n console.log(\" ----- \");\n console.log(\" Search Tweets Limit: \"+ data.resources.search['/search/tweets'].limit);\n console.log(\" Search Tweets Remaining: \"+ data.resources.search['/search/tweets'].remaining);\n console.log(\"-------------------------------------------------------\");\n });\n }",
"function dataMonthTemp(){\napp.get('/api/statisticsByMonth/Temp', (req, res)=>{\n let sql = \"SELECT * FROM SensorTemp WHERE MONTH(Date) = MONTH('\"+valueDate+\"');SELECT MAX(Temp) FROM SensorTemp WHERE MONTH(Date) = MONTH('\"+valueDate+\"');SELECT MIN(Temp) FROM SensorTemp WHERE MONTH(Date) = MONTH('\"+valueDate+\"');SELECT SUM(Temp) FROM SensorTemp WHERE MONTH(Date) = MONTH('\"+valueDate+\"') AND Temp>32;SELECT SUM(Temp) FROM SensorTemp WHERE MONTH(Date) = MONTH('\"+valueDate+\"') AND Temp<18;SELECT SUM(Temp) FROM SensorTemp WHERE MONTH(Date) = MONTH('\"+valueDate+\"') AND Temp BETWEEN 18 AND 32;SELECT AVG(Temp) FROM SensorTemp WHERE MONTH(Date) = MONTH('\"+valueDate+\"')\";\n con.query(sql, (err, result, fields)=>{\n if (err) throw err;\n res.json(result);\n console.log(result)\n });\n})\n}",
"static getList(username){\n let list = getBMListFromFile(DEFAULT_FILE_PATH).concat(getBMListFromFile(FILE_PATH)); //list = Default + Published beatmaps\n return list.map(item => {\n const data = Beatmap.getBeatmapFromList(item.beatmapID);\n let highscore = 0;\n if(username !== \"null\")\n highscore = User.getHighscore(username, data.beatmapID);\n return {\n beatmapID: data.beatmapID,\n musicTitle: data.musicTitle,\n musicArtist: data.musicArtist,\n musicDuration: data.musicDuration,\n creator: data.creator,\n difficulty: data.difficulty,\n leaderboard: data.leaderboard,\n highscore: highscore ? highscore : 0,\n isActive: data.isActive\n }\n });\n }",
"function getResponseTimes() {\n return {\n 'foia:ResponseTimeMedianDaysValue': { '$t': 0 },\n 'foia:ResponseTimeAverageDaysValue': { '$t': 0 },\n 'foia:ResponseTimeLowestDaysValue': { '$t': 0 },\n 'foia:ResponseTimeHighestDaysValue': { '$t': 0 },\n }\n}",
"function readEmployeeRate() {\n\n fs.readFile(\"employee-rates.txt\", \"utf8\", function (err, data) {\n if (err) {\n return console.log(err);\n }\n data = JSON.parse(data)\n \n\n for (var i = 0; i < data.length; i++) {\n if (parseFloat(data[i])) {\nemployeeRateArr.push(new employeeRate(data[i]).name,data[i].rate);\n }\n }\n\n\n data.forEach(element => {\n employeeRateArr.push(element)\n console.log(employeeRateArr)\n });\n // console.log(\"these are the choices \" + data[i]);\n });\n\n}",
"function loadTweetData() {\n T.get(\"friends/list\", { screen_name: userName, count: 5 }, function(\n err,\n data,\n response\n ) {\n if (err) {\n // console.log(err);\n throw err;\n } else {\n myFriends = data.users;\n // console.log(data.users);\n }\n });\n\n T.get(\"direct_messages/sent\", { count: 5 }, function(err, data, response) {\n if (err) {\n console.log(err);\n } else {\n myChats = data;\n // console.log(data);\n }\n });\n\n T.get(\"statuses/user_timeline\", { screen_name: userName, count: 5 }, function(\n err,\n data,\n response\n ) {\n if (err) {\n console.log(err);\n } else {\n myTweets = data;\n // console.log(data);\n }\n });\n}",
"function getprices() {\n\trequest(c.URL, function(error, res, body) {\n\t\tif (!error && res.statusCode == 200) {\n\n\t\t\tvar prices = {};\n\t\t\tvar result = JSON.parse(body);\n\n\t\t\tprices.btcusd = result.btc_usd;\n\t\t\tprices.btceur = result.btc_eur;\n\t\t\tprices.ltcusd = result.ltc_usd;\n\t\t\tprices.ltceur = result.ltc_eur;\n\t\t\tprices.ethusd = result.eth_usd;\n\n\t\t\tvar json = JSON.stringify(prices);\n\t\t\tfs.writeFile('./src/prices.json', json, function(err) {\n\t\t\t\tif (err) throw err;\n\t\t\t});\n\n\t\t\t// loop indefinitely\n\t\t\tsetTimeout(function(){getprices()}, 60000);\n\t\t}\n\t});\n}",
"function getDataCoinbase()\n {\n $.ajax({\n url: \"https://api.gdax.com/products/btc-usd/candles/\",\n success: function(data)\n {\n var data = {\n last: $(\"#tableData\").attr(\"data-usd-coinbase\"),\n volume: data[0][5],\n high : data[0][2],\n low : data[0][1]\n };\n\n $.ajax({\n url: \"serverCoinbase\",\n method: \"GET\",\n data: \"dataCoinbase=\" + JSON.stringify(data),\n success: function(){}\n });\n }\n })\n }",
"async function fetchHistoricalRates() {\n var pastDays = [];\n for (var i = 1; i <= 7; i++) {\n var d = new Date();\n d.setDate(d.getDate() - i);\n pastDays.push( d.toISOString().slice(0, 10) );\n }\n setPassSevenDay(pastDays);\n // console.log(passSevenDates);\n var newExchangeRateHist = new Array(7);\n for (i = 0; i < 7; i++) {\n const response = await axios.get(`https://openexchangerates.org/api/historical/${pastDays[i]}.json?app_id=${appId}`)\n if (response && response.data) {\n newExchangeRateHist[i] = response.data.rates;\n } else {\n console.log(`error! can't get the exchange rate info of ${i+1} day before`)\n }\n }\n setExchangeRatesHist(newExchangeRateHist);\n // console.log(newExchangeRateHist)\n }",
"function getData() {\n // let toDate = e;\n // console.log(toDate.target.value)\n console.log(to.onchange)\n\n\n axios.get(`http://api.coindesk.com/v1/bpi/historical/close.json?start=${fromDateValue}&end=${toDateValue}`)\n .then(res => {\n let labels = Object.keys(res.data.bpi)\n let values = Object.values(res.data.bpi)\n printChart(res.data, labels, values)\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
helper to check if filepath refers to a file that userland is not allowed to edit directly | function assertUnprotectedFilePath (filepath) {
if (filepath === '/' + DAT_MANIFEST_FILENAME) {
throw new ProtectedFileNotWritableError()
}
} | [
"validateFilePath(file) {\n try {\n if (fs.existsSync(file)) {\n return;\n } else {\n // File wasn't found, but we didn't get an error\n console.error('Provided file path was not valid or not found. Please try again.');\n process.exit(1);\n }\n } catch (error) {\n console.error('Provided file path was not valid or not found. Please try again.');\n process.exit(1);\n }\n }",
"function preventFileActivity()\n{\n\treturn true;\n}",
"isValid() {\n try {\n fs.accessSync(CONFIG_FILE_PATH, fs.constants.R_OK | fs.constants.W_OK);\n return true;\n } catch (err) {\n return false;\n }\n }",
"function validateFileName(fname,path) {\n\tif ( fname == \"\" ) {\n return 1;\n } else {\n var isinvalid = 0;\n if (/^disk[0-2]|disk$/.test(path) == true || /^slot[0-1]$/.test(path) == true || /^NVRAM$/.test(path) == true || /^bootflash$/.test(path) == true || /^flash[0-1]|flash$/.test(path) == true) {\n if (/^[a-z|A-Z|0-9][0-9|a-z|\\-|\\_|A-Z|\\.]+$/.test(fname) == false) {\n if (/^[\\/][0-9|a-z|\\-|\\_|A-Z|\\.]+$/.test(fname) == false) {\n isinvalid = 1;\n }\n }\n } else if (/^[a-z|A-Z|0-9][0-9|a-z|\\-|\\_|A-Z|\\.]+$/.test(fname) == false) {\n isinvalid = 1;\n }\n return isinvalid;\n }\n}",
"function isPathUnderDesign(path)\n{\n if(path.length == 0)\n {\n return false;\n }\n\n if(path[1] == 'Design')\n {\n return true;\n }\n else\n {\n return false;\n }\n}",
"function isInSrcDir(_filepath){\n var filepathRelativeToSrcDir = path.relative( srcDir, path.resolve(config.base,_filepath) );\n if( filepathRelativeToSrcDir.substr(0,2) !== '..' ) { // file is in srcDir\n return filepathRelativeToSrcDir;\n }\n return false;\n }",
"function statSafe (path, requestedPermissions, callback) {\n fs.stat(path, function (err, stat) {\n onSafeStat(err, stat, requestedPermissions, callback)\n })\n }",
"isScriptFile(filePath) {\n return ['.js', '.json'].includes(path_1.extname(filePath));\n }",
"function check_file_exist(file){\n\tvar http = new XMLHttpRequest();\n\thttp.open('HEAD',file,false);\n\thttp.send();\n\treturn http.status == 404;\n}",
"function inRelativePath(filePath) {\n return filePath.startsWith(withSlash);\n }",
"function external(path) {\n return (\n !path.startsWith('.') && // Paths that doesn't start with a '.' (e.g. './agile.ts')\n !path.startsWith(packageRoot) // Paths that doesn't start with the package root path (e.g. 'path/to/package/agile.ts')\n );\n}",
"function validatePath(path) {\n if (path === \"\") {\n return validationError($('#file-chooser').parent().parent().children(\".error\"), i18n.EMPTY_PATH)\n } else if (!path.includes(\".specifz\")) {\n return validationError($('#file-chooser').parent().parent().children(\".error\"), i18n.NO_SPECIFZ_FILE)\n } else {\n return hideError($('#file-chooser').parent().parent().children(\".error\"))\n }\n }",
"function checkFile(el,allowed) {\n\tvar suffix = $(el).val().split(\".\")[$(el).val().split(\".\").length-1].toUpperCase();\n\tif (!(allowed.indexOf(suffix) !== -1)) {\n\t\talert(\"File type not allowed,\\nAllowed files: *.\"+allowed.join(\",*.\"));\n\t\t$(el).val(\"\");\n\t}\n}",
"function isAbsolute(path) {\n return __WEBPACK_IMPORTED_MODULE_0__platform_js__[\"g\" /* isWindows */] ?\n isAbsolute_win32(path) :\n isAbsolute_posix(path);\n}",
"function _shouldIgnore(pattern /*: Function | RegExp*/, filename /*: string*/) {\n if (typeof pattern === \"function\") {\n return pattern(filename);\n } else {\n return pattern.test(filename);\n }\n}",
"fileExists() {\n return fs.pathExists(this.location);\n }",
"function validatePath(path) {\n if ( path == \"\" ) {\n return 1;\n\t} else if (/^disk[0-2]|disk$/.test(path) == true || /^slot[0-1]$/.test(path) == true || /^NVRAM$/.test(path) == true || /^bootflash$/.test(path) == true || /^flash[0-1]|flash$/.test(path) == true) {\n return 0;\n } else {\n var pathArr = path.split(\"\\/\");\n var isinvalid = 0;\n for (var x = 0 ; x < pathArr.length; x++) {\n if (/^[a-z|A-Z][0-9|a-z|\\-|\\_|A-Z|\\.]+$/.test(pathArr[x]) == false) {\n isinvalid = 1;\n }\n }\n return isinvalid;\n }\n}",
"function isUNC(path) {\n if (!__WEBPACK_IMPORTED_MODULE_0__platform_js__[\"g\" /* isWindows */]) {\n // UNC is a windows concept\n return false;\n }\n if (!path || path.length < 5) {\n // at least \\\\a\\b\n return false;\n }\n var code = path.charCodeAt(0);\n if (code !== 92 /* Backslash */) {\n return false;\n }\n code = path.charCodeAt(1);\n if (code !== 92 /* Backslash */) {\n return false;\n }\n var pos = 2;\n var start = pos;\n for (; pos < path.length; pos++) {\n code = path.charCodeAt(pos);\n if (code === 92 /* Backslash */) {\n break;\n }\n }\n if (start === pos) {\n return false;\n }\n code = path.charCodeAt(pos + 1);\n if (isNaN(code) || code === 92 /* Backslash */) {\n return false;\n }\n return true;\n}",
"static validateTopologyFile(file) {\n\n const allowedExtensions = ['.yml', '.yaml', '.json', '.js'];\n const exists = fs.existsSync(file);\n if (!exists) {\n throw new Error('File does not exist', file);\n }\n\n const ext = path.extname(file);\n if (allowedExtensions.indexOf(ext) === -1) {\n throw new Error('Can only be either a .yml, .yaml, .json or .js file', file);\n }\n }",
"canLoad(url) {\n return !!(this.files.has(url) ||\n this.fallbackLoader && this.fallbackLoader.canLoad(url));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to active on corbeil icon delete action one product Parameters: dataMemory => storage interface that contains the data from the browser cache in which all the products added to the cart are located dataParse => parsed data corresponding to a product of products list from the listproductorder function level => if object to create is in same parent value is 0 else value is a variable | function activeFunctionDelete(dataMemory,dataParse,level) {
let deleteObject = document.getElementsByClassName(deleteProductCartTarget);
deleteObject[level].setAttribute("id",""+dataParse._id+"");
deleteObject[level].addEventListener("click", function() {
removeProduct(dataMemory,deleteObject[level].getAttribute("id"));
location.reload();
});
} | [
"function listProductOrder(dataMemory) {\n const tab = [\"imageUrl\",\"name\",\"lenses\",\"price\",\"delete\"];\n var cost = 0;\n for (let i = 0 ; i < dataMemory.length; i++) {\n let memoryDataParse = JSON.parse(dataMemory.getItem(dataMemory.key(i)));\n createObject(listProductOrderTarget,\"tr\",listProductOrderProductTarget,null,0);\n for (let j = 0 ; j < tab.length; j++) {\n for (const key in memoryDataParse) {\n if (key == tab[j]) {\n switch (key) {\n case \"imageUrl\":\n createObject(listProductOrderProductTarget,\"td\",imageProductCartTarget,\"<img src=\\\"\"+memoryDataParse[key]+\"\\\" alt=\\\"product view\\\">\",i);\n break;\n case \"name\":\n createObject(listProductOrderProductTarget,\"td\",nameProductCartTarget,memoryDataParse[key],i);\n break;\n case \"lenses\":\n createObject(listProductOrderProductTarget,\"td\",lensesProductCartTarget,\"Personnalisation: \"+ memoryDataParse[key],i);\n break;\n case \"price\":\n createObject(listProductOrderProductTarget,\"td\",priceProductCartTarget,memoryDataParse[key]/100+\"€\",i);\n cost += memoryDataParse[key]/100;\n break;\n }\n }\n }\n if (tab[j] == \"delete\") {\n createObject(listProductOrderProductTarget,\"td\",deleteProductCartTarget,\"<img src=\\\"../Images/corbeille.png\\\" alt=\\\"product to delete icon\\\">\",i);\n activeFunctionDelete(orderStorage,memoryDataParse,i);\n }\n }\n } \n createObject(productOrderCostTarget,\"tr\",labelProductOrderCostTarget,\"<td>Coût total de la commande: </td><td>\"+cost+\" €</td>\" ,0);\n}",
"function removeProduct(dataMemory,removeObject) {\n if (dataMemory.getItem(removeObject) != null) {\n dataMemory.removeItem(removeObject);\n }\n}",
"function deleteFromMPO(product) {\n //Search for the index of the product in the array\n let index = singleProducts.indexOf(product);\n\n let input = document.querySelector(`.mijn-producten-label${product.id}`).querySelector('input');\n input.checked = false;\n input.classList.remove('added');\n //Remove product\n singleProducts.splice(index, 1)\n computeMPOProducts();\n updateCounter();\n}",
"function basketDeleteOne(id){\n var cartData = getCartData();\n delete cartData[id];\n setCartData(cartData);\n getTotal();\n if(window.location.href==location.protocol+'//'+document.domain+\"/checkout\"){\n openBasket();\n }\n return false;\n }",
"function listProductOrder(data) {\n const tab = [\"imageUrl\",\"name\",\"lenses\",\"price\"];\n var cost = 0;\n for (let i = 0 ; i < data.products.length; i++) {\n createObject(listProductOrderTarget,\"tr\",listProductOrderProductTarget,null,0);\n const product = data.products[i];\n for (let j = 0 ; j < tab.length; j++) {\n for (let key in product) {\n if (key == tab[j]) {\n switch (key) {\n case \"imageUrl\":\n createObject(listProductOrderProductTarget,\"td\",imageProductResumTarget,\"<img src=\\\"\"+product[key]+\"\\\" alt=\\\"product view\\\">\",i);\n break;\n case \"name\":\n createObject(listProductOrderProductTarget,\"td\",nameProductResumTarget,product[key],i);\n break;\n case \"lenses\":\n createObject(listProductOrderProductTarget,\"td\",lensesProductResumTarget,\"Possibilités offertes: \"+ product[key],i);\n break;\n case \"price\":\n createObject(listProductOrderProductTarget,\"td\",priceProductResumTarget,product[key]/100+\"€\",i);\n cost += product[key]/100;\n break;\n }\n } \n } \n }\n }\n createObject(productOrderCostTarget,\"tr\",labelProductOrderCostTarget,\"<td>Coût total de la commande: </td><td>\"+cost+\" €</td>\" ,0);\n}",
"function deleteFromList(list, product) {\n //Search for the index of the product in the array\n let index = list.products.indexOf(product);\n\n //Remove product\n list.products.splice(index, 1)\n let input = document.querySelector(`.mijn-producten-label${product.id}`).querySelector('input');\n input.checked = false;\n input.classList.remove('added'); \n calcLists();\n updateCounter();\n}",
"function deleteBought(product, boughtBtn) {\n let itemWrapper = Array.from(allLists.querySelectorAll('.itemWrapper')).filter(elem => elem.getAttribute('id') === product.id)[0];\n let boughtPrice = allLists.querySelector('.boughtPrice');\n product.bought = false;\n product.boughtPrice = 0;\n boughtPrice.innerHTML = `€ ${product.boughtPrice}`;\n itemWrapper.style.border = 'none';\n boughtPrice.style.display = 'none';\n changeState(boughtBtn);\n}",
"function deleteStock() {\n rows = getSelectedRowBoxes();\n\n for (var i=rows.length - 1; i >= 0; i--) {\n var prodId = rows[i].parentNode.parentNode.id;\n delete products[prodId];\n products.splice(prodId, 1);\n }\n saveData();\n displayInventory();\n}",
"function deletePriceAlert(product) {\n //Search for the alert button \n try{\n let alertBtn = Array.from(popover.querySelectorAll('.setAlert')).filter(alert => alert.getAttribute('id') === product.id)[0];\n changeState(alertBtn);\n }catch{\n //nothing\n }\n\n //Set price alert to false\n product.priceAlert = false;\n let index = allPriceAlerts.indexOf(product);\n allPriceAlerts.splice(index, 1);\n calcPriceAlerts();\n}",
"function setItems(product) {\r\n //8 console.log(\"inside of set Items function\");\r\n //8 console.log(\"my prodcut function is\", product);\r\n //8 this will print inside of my set item function, you will see my product is with the name of the product you clicked on\r\n\r\n //8.3 when ever we click on the set item function. this will check if it exist already some items or not\r\n //8.3 the item you want to get product incart in local sotrage to check if it exist and see if something in our local storage\r\n //8.3 if we are trying to get something from our local storage we type this console.log(\"My cartitems are\", cartitems);\r\n //8.3 this will print in console my cart item are with the name,price.. of the item\r\n //8.3 this is in a json foramt\r\n let cartItems = localStorage.getItem('productsInCart');\r\n //8.4 this is what to pass in from json into javascript object\r\n //8.4 we are updating this json\r\n cartItems = JSON.parse(cartItems);\r\n //8.5 if cart item is equal to null this means something is already in our cart/localstorage\r\n //8.5 then we going to do a check\r\n if (cartItems != null) {\r\n\r\n if (cartItems[product.tag] == undefined) {\r\n //8.7 this is to update my cart item what ever in my local sotrage \r\n cartItems = {\r\n //8.7 grab what ever from my cart items before and then using the rest operator from js\r\n ...cartItems,\r\n //8.7 and then add this new product \r\n [product.tag]: product\r\n }\r\n }\r\n //8.7 this is to incrase 1 is already in there\r\n cartItems[product.tag].inCart += 1;\r\n } else {\r\n //8.1 this is the first time you going to click \r\n product.inCart = 1;\r\n cartItems = {\r\n //8.6 setting the product in cart to be 1\r\n [product.tag]: product\r\n }\r\n }\r\n //8.2 we dont want to pass javascript object. we use JSON.stringify to pass as json object on local sotrage. \r\n //8.2 it will show the name, price ... with incart 1.\r\n localStorage.setItem(\"productsInCart\", JSON.stringify(cartItems));\r\n}",
"function removeCustomCartDishItem(data){\n $.getJSON(\"/restaurace/removeCustomItem\", data, function(dish){\n actualizeCalculationsAfterItemRemoved(dish);\n });\n }",
"function itemQuantity() {\n let increase = document.querySelectorAll(\"i.fa-plus\");\n let decrease = document.querySelectorAll(\"i.fa-minus\");\n let currentQuantity = 0;\n let currentProduct = \"\";\n\n let foodItems = localStorage.getItem(\"foodsInCart\");\n foodItems = JSON.parse(foodItems);\n\n for (let i = 0; i < increase.length; i++) {\n increase[i].addEventListener(\"click\", () => {\n currentQuantity =\n increase[i].parentElement.querySelector(\"span\").textContent;\n\n currentProduct = increase[\n i\n ].parentElement.parentElement.previousElementSibling.textContent\n .trim()\n .toLowerCase()\n .replace(/ /g, \"_\");\n\n foodItems[currentProduct].inCart += 1;\n cartCounter(foodItems[currentProduct]);\n totalCost(foodItems[currentProduct]);\n localStorage.setItem(\"foodsInCart\", JSON.stringify(foodItems));\n cartContent();\n });\n }\n\n for (let i = 0; i < decrease.length; i++) {\n decrease[i].addEventListener(\"click\", () => {\n currentQuantity =\n decrease[i].parentElement.querySelector(\"span\").textContent;\n\n currentProduct = decrease[\n i\n ].parentElement.parentElement.previousElementSibling.textContent\n .trim()\n .toLowerCase()\n .replace(/ /g, \"_\");\n\n if (foodItems[currentProduct].inCart > 1) {\n foodItems[currentProduct].inCart -= 1;\n cartCounter(foodItems[currentProduct], \"decrease\");\n totalCost(foodItems[currentProduct], \"decrease\");\n localStorage.setItem(\"foodsInCart\", JSON.stringify(foodItems));\n cartContent();\n }\n });\n }\n}",
"function removeBasketItem(event) {\n let buttonClicked = event.target;\n let id = buttonClicked.previousElementSibling.innerText;\n buttonClicked.parentElement.parentElement.remove();\n let itemToRemove = { productId: id }\n basketArrayItemRemove(itemToRemove)\n updateBasketTotal();\n}",
"function removeCartDishItem(data){\n $.getJSON(\"/restaurace/removeItem\", data, function(dish){\n actualizeCalculationsAfterItemRemoved(dish);\n });\n }",
"function handleRecipeDelete() {\n var currentRow = $(this);\n var currentRecipe = currentRow.parent().data(\"recipe\");\n if (currentRecipe == undefined) {\n var currentRecipe = currentRow.parent().parent().data(\"recipe\"); \n }\n deleteRecipe(currentRecipe,currentRow.parent().parent());\n }",
"function removeCartItem(event){\r\n // event object has property target, which specifies the button clicked. \r\n var buttonClicked = event.target\r\n // So we want to go up 2 parent elements (classes) and remove the row when 'remove' button is clicked.\r\n buttonClicked.parentElement.parentElement.remove()\r\n updateCartTotal()\r\n}",
"function calculateOrder() {\n var itemOrder = order.getItems();\n // clear orderList \n orderList.innerHTML = '';\n\n itemOrder.forEach(function (item, i) {\n var elem = document.createElement('li');\n elem.classList.add('order__list-item');\n var elemContent = item.name + ' x ' + item.quantity + ', price: ' + parseInt(item.type.price) * parseInt(item.quantity) + ' ' + VALUE_PRICE + ', calories: ' + parseInt(item.type.calories\n ) * parseInt(item.quantity) + ' ' + VALUE_CALORY\n elem.textContent = elemContent\n\n var buttonRemove = document.createElement('button');\n // adding class for future remove handling with event delegation\n buttonRemove.classList.add('js-button-remove');\n // adding data attribute for easy finding element index when removing item\n buttonRemove.setAttribute('data-index', i);\n buttonRemove.textContent = 'X';\n\n elem.appendChild(buttonRemove);\n\n orderList.appendChild(elem);\n });\n}",
"function checkProductStockRoom(stockAmount, commonstockid, preorder, preorder_stock)\n{\n var isStock = true;\n\n if (stockAmount > 0)\n {\n if (document.getElementById('pdaddtocart' + commonstockid))\n {\n document.getElementById('pdaddtocart' + commonstockid).style.display = '';\n }\n\n if (USE_AS_CATALOG == 1)\n {\n if (document.getElementById('pdaddtocart' + commonstockid)) {\n document.getElementById('pdaddtocart' + commonstockid).style.display = 'none';\n }\n }\n if (document.getElementById('preordercart' + commonstockid)) {\n document.getElementById('preordercart' + commonstockid).style.display = 'none';\n }\n if (document.getElementById('stockaddtocart' + commonstockid)) {\n document.getElementById('stockaddtocart' + commonstockid).style.display = 'none';\n }\n\n isStock = true;\n } else {\n\n if (stockAmount == 0) {\n if ((preorder == 'global' && ALLOW_PRE_ORDER != 1) || (preorder == '' && ALLOW_PRE_ORDER != 1) || (preorder == 'no')) {\n\n\n\n //isPreorderProductStock\n if (document.getElementById('stockaddtocart' + commonstockid)) {\n document.getElementById('stockaddtocart' + commonstockid).style.display = '';\n }\n if (document.getElementById('stockaddtocart' + commonstockid)) {\n document.getElementById('stockaddtocart' + commonstockid).innerHTML = COM_REDSHOP_PRODUCT_OUTOFSTOCK_MESSAGE;\n }\n\n if (USE_AS_CATALOG == 1) {\n if (document.getElementById('stockaddtocart' + commonstockid)) {\n document.getElementById('stockaddtocart' + commonstockid).style.display = 'none';\n }\n }\n if (document.getElementById('preordercart' + commonstockid)) {\n document.getElementById('preordercart' + commonstockid).style.display = 'none';\n }\n if (document.getElementById('pdaddtocart' + commonstockid)) {\n document.getElementById('pdaddtocart' + commonstockid).style.display = 'none';\n }\n\n\n } else {\n\n if (preorder_stock == 0) {\n\n if (document.getElementById('stockaddtocart' + commonstockid)) {\n document.getElementById('stockaddtocart' + commonstockid).style.display = '';\n }\n if (document.getElementById('stockaddtocart' + commonstockid)) {\n document.getElementById('stockaddtocart' + commonstockid).innerHTML = COM_REDSHOP_PREORDER_PRODUCT_OUTOFSTOCK_MESSAGE;\n }\n\n if (USE_AS_CATALOG == 1) {\n if (document.getElementById('stockaddtocart' + commonstockid)) {\n document.getElementById('stockaddtocart' + commonstockid).style.display = 'none';\n }\n }\n if (document.getElementById('preordercart' + commonstockid)) {\n document.getElementById('preordercart' + commonstockid).style.display = 'none';\n }\n if (document.getElementById('pdaddtocart' + commonstockid)) {\n document.getElementById('pdaddtocart' + commonstockid).style.display = 'none';\n }\n\n\n } else {\n\n\n if (document.getElementById('stockaddtocart' + commonstockid)) {\n document.getElementById('stockaddtocart' + commonstockid).style.display = 'none';\n }\n if (document.getElementById('stockaddtocart' + commonstockid)) {\n document.getElementById('stockaddtocart' + commonstockid).innerHTML = \"\";\n }\n if (document.getElementById('pdaddtocart' + commonstockid)) {\n document.getElementById('pdaddtocart' + commonstockid).style.display = 'none';\n }\n if (document.getElementById('preordercart' + commonstockid)) {\n document.getElementById('preordercart' + commonstockid).style.display = '';\n }\n\n if (USE_AS_CATALOG == 1) {\n if (document.getElementById('preordercart' + commonstockid)) {\n document.getElementById('preordercart' + commonstockid).style.display = 'none';\n }\n }\n\n\n }\n\n\n }\n }\n\n\n //isStock = false;\n }\n if (document.getElementById('stockQuantity' + commonstockid)) {\n if (stockAmount > 0 || preorder_stock > 0) {\n document.getElementById('stockQuantity' + commonstockid).style.display = '';\n } else {\n document.getElementById('stockQuantity' + commonstockid).style.display = 'none';\n }\n }\n return isStock;\n}",
"function removeItem() {\n \n var idxToRemove = $('.remove-from-cart').attr('data-index');\n \n cart.items.splice(idxToRemove, 1);\n renderCart(cart, $('.template-cart'), $('.cart-container'));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adapted from Shdr Validator class Creates and validates a shader from a text source based on type (src, type) > false || [ok, line, error] src: glsl text to be validated type: 0 for vertex shader, 1 for fragment shader, else return false ok: boolean for whether the shader is ok or not line: which line number throws error (only if ok is false) error: description of error (only if ok is false and line != null) | function validate(src, type) {
// uniforms don't get validated by glsl
if (type !== 0 && type !== 1) {
return false;
}
if (!src) {
return [false, 0, "Shader cannot be empty"];
}
if (!context) {
console.warn("No WebGL context.");
}
var details, error, i, line, lines, log, message, shader, status, _i, _len;
try {
var shaderType = type === 0 ? context.VERTEX_SHADER : context.FRAGMENT_SHADER;
shader = context.createShader(shaderType);
context.shaderSource(shader, src);
context.compileShader(shader);
status = context.getShaderParameter(shader, context.COMPILE_STATUS);
}
catch(e) {
return [false, 0, e.getMessage];
}
if (status === true) {
return [true, null, null];
}
else {
// filters out THREE.js handled errors in the raw log
log = context.getShaderInfoLog(shader);
var rawLog = log;
lines = rawLog.split('\n');
for (_i = 0, _len = lines.length; _i < _len; _i++) {
i = lines[_i];
if (i.substr(0, 5) === 'ERROR') {
if (i.indexOf("undeclared identifier") > -1) {
if (i.indexOf("projectionMatrix") > -1 ||
i.indexOf("modelMatrix") > -1 ||
i.indexOf("modelViewMatrix") > -1 ||
i.indexOf("viewMatrix") > -1 ||
i.indexOf("cameraPosition") > -1 ||
i.indexOf("normal") > -1 ||
i.indexOf("uv") > -1 ||
i.indexOf("uv2") > -1 ||
i.indexOf("position") > -1) {
lines.splice(_i, 1);
_i--;
_len--;
}
}
else if (i.indexOf("No precision specified for (float)") > -1) {
lines.splice(_i, 1);
_i--;
_len--;
}
else if (i.indexOf("'constructor' : not enough data provided for construction") > -1) {
lines.splice(_i, 1);
_i--;
_len--;
}
}
}
for (_i = 0, _len = lines.length; _i < _len; _i++) {
i = lines[_i];
if (i.substr(0, 5) === 'ERROR') {
error = i;
}
}
if (!error || error[0] === "") {
return [true, null, null];
// return [false, 0, 'Unable to parse error.'];
}
details = error.split(':');
if (details.length < 4) {
return [false, 0, error];
}
line = details[2];
message = details.splice(3).join(':');
return [false, parseInt(line), message];
}
} | [
"function getShader(filepath, type)\n {\n var shaderScriptType = type;\n var shaderPath = filepath;\n \n if (!shaderPath || shaderPath.length == 0)\n return 0;\n \n var shader = Gles.createShader(type);\n \n if (shader == 0) return 0;\n \n //added method\n Gles.shaderSourceFile(shader, filepath);\n Gles.compileShader(shader);\n \n if (Gles.getShaderiv(shader, Gles.COMPILE_STATUS) != 1) {\n var error = Gles.getShaderInfoLog(shader);\n log(\"Error while compiling \" + id + \":\");\n log(shader);\n \n Gles.deleteShader(shader);\n return 0;\n }\n \n return shader;\n }",
"function importShader () {\n function createVertexShader (vert) {\n return createShader(require(`../shader/${vert}.vert`), 'vertex')\n }\n\n const noneVs = createVertexShader('nothing')\n\n function createProgram (name, frag, vert = noneVs, prg = prgs) {\n const fs = createShader(require(`../shader/${frag}.frag`), 'fragment')\n prg[name] = new Program(vert, fs)\n if (!prg[name]) throw new Error('program error')\n }\n\n try {\n // video\n createProgram('video', 'video')\n\n // Post Effect\n createProgram('postVideo', 'post/video')\n\n const postVs = createVertexShader('post/post')\n for (const name of POST_LIST) {\n createProgram(name, `post/${name}`, postVs, postPrgs)\n }\n\n // Particle\n createProgram('particleVideo', 'particle/video')\n createProgram('picture', 'particle/picture')\n createProgram('reset', 'particle/reset')\n createProgram('resetVelocity', 'particle/resetVelocity')\n createProgram('position', 'particle/position')\n createProgram('velocity', 'particle/velocity')\n createProgram('particleScene', 'particle/scene', createVertexShader('particle/scene'))\n\n // Pop\n createProgram('popVelocity', 'particle/pop_velocity')\n createProgram('popPosition', 'particle/pop_position')\n createProgram('popScene', 'particle/pop_scene', createVertexShader('particle/pop_scene'))\n\n // render\n createProgram('scene', 'scene', createVertexShader('scene'))\n } catch (error) {\n throw error\n }\n}",
"static domShaderSrc(elmID) {\n var elm = document.getElementById(elmID);\n if (!elm || elm.text == \"\") { console.log(elmID + \" shader not found or no text.\"); return null; }\n\n return elm.text;\n }",
"function Shader(glContext, vertexPath, fragmentPath)\n{\n this.uniforms = new Array();\n this.uniforms.count = 0;\n \n \n this.worldViewProjectionHandle = -1;\n this.worldMatrixHandle = -1;\n this.projectionMatrixHandle = -1;\n this.textureHandle = -1;\n \n //attribute handles \n this.positionHandle = -1;\n this.normalHandle = -1;\n this.colorHandle = -1;\n this.uvCoordinateHandle = -1;\n \n this.vertexShaderSource = \"\";\n this.vertexShaderLength = 0;\n this.vertexShaderHandle = -1;\n \n this.fragmentShaderSource = \"\";\n this.fragmentShaderLength = 0;\n this.fragmentShaderHandle = -1;\n \n this.programHandle = -1;\n \n this.loadShader(glContext, vertexPath, fragmentPath);\n \n \n //get attribute handles\n this.colorHandle = gl.getAttribLocation( this.programHandle, \"a_Color\" );\t\n this.positionHandle = gl.getAttribLocation( this.programHandle, \"a_Position\" );\t\n this.uvCoordinateHandle = gl.getAttribLocation( this.programHandle, \"a_UVCoordinates\" );\n this.normalHandle = gl.getAttribLocation(this.programHandle, \"a_Normal\");\n \n //get uniform handles\n this.worldViewProjectionHandle = gl.getUniformLocation(this.programHandle, \"u_WorldViewProjection\");\n this.worldMatrixHandle = gl.getUniformLocation(this.programHandle, \"u_WorldMatrix\");\n this.projectionMatrixHandle = gl.getUniformLocation(this.programHandle, \"u_ProjectionMatrix\");\n this.textureHandle = gl.getUniformLocation(this.programHandle, \"u_Texture\");\n}",
"function recompileShader() {\n shaderSourceChanged = true;\n}",
"function initShaders( vertexShaderId, fragmentShaderId )\n{\n var vertShdr;\n\tvar fragShdr;\n\t\n\n\n\t// --- Compiling vertex shader\n var vertElem = document.getElementById( vertexShaderId );\n if ( !vertElem ) { \n alert( \"Unable to load vertex shader \" + vertexShaderId );\n return -1;\n }\n else {\n vertShdr = gl.createShader( gl.VERTEX_SHADER );\n gl.shaderSource( vertShdr, vertElem.text );\n gl.compileShader( vertShdr );\n if ( !gl.getShaderParameter(vertShdr, gl.COMPILE_STATUS) ) {\n var msg = \"Vertex shader failed to compile. The error log is:\"\n \t+ \"<pre>\" + gl.getShaderInfoLog( vertShdr ) + \"</pre>\";\n alert( msg );\n return -1;\n }\n }\n\n\n\n\t// --- Compiling fragment shader\n var fragElem = document.getElementById( fragmentShaderId );\n if ( !fragElem ) { \n alert( \"Unable to load vertex shader \" + fragmentShaderId );\n return -1;\n }\n else {\n fragShdr = gl.createShader( gl.FRAGMENT_SHADER );\n gl.shaderSource( fragShdr, fragElem.text );\n gl.compileShader( fragShdr );\n if ( !gl.getShaderParameter(fragShdr, gl.COMPILE_STATUS) ) {\n var msg = \"Fragment shader failed to compile. The error log is:\"\n \t+ \"<pre>\" + gl.getShaderInfoLog( fragShdr ) + \"</pre>\";\n alert( msg );\n return -1;\n }\n }\n\n\n\n\t// --- Creating program\n var program = gl.createProgram();\n gl.attachShader( program, vertShdr );\n gl.attachShader( program, fragShdr );\n gl.linkProgram( program );\n \n if ( !gl.getProgramParameter(program, gl.LINK_STATUS) ) {\n var msg = \"Shader program failed to link. The error log is:\"\n + \"<pre>\" + gl.getProgramInfoLog( program ) + \"</pre>\";\n alert( msg );\n return -1;\n }\n\n return program;\n}",
"function _glsl() {\n\treturn {\n\t\ttransform(code, id) {\n\t\t\tif (/\\.glsl$/.test(id) === false) return;\n\t\t\tvar transformedCode = 'export default ' + JSON.stringify(\n\t\t\t\tcode\n\t\t\t\t\t.replace( /[ \\t]*\\/\\/.*\\n/g, '' ) // remove //\n\t\t\t\t\t.replace( /[ \\t]*\\/\\*[\\s\\S]*?\\*\\//g, '' ) // remove /* */\n\t\t\t\t\t.replace( /\\n{2,}/g, '\\n' ) // # \\n+ to \\n\n\t\t\t) + ';';\n\t\t\treturn {\n\t\t\t\tcode: transformedCode,\n\t\t\t\tmap: { mappings: '' }\n\t\t\t};\n\t\t}\n\t};\n}",
"function glShaderCompileError(error) {\n addError(error);\n}",
"function genShaderPrograms(){\r\n\r\n\tif(!(gl.program1 = util_InitShaders(gl, VSHADER_SOURCE1, FSHADER_SOURCE1))) {\r\n\t\tconsole.log(\"Error building program 1\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\tif(!(gl.program2 = util_InitShaders(gl, VSHADER_SOURCE2, FSHADER_SOURCE2))) {\r\n\t\tconsole.log(\"Error building program 2\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\tif(!(gl.program3 = util_InitShaders(gl, VSHADER_SOURCE3, FSHADER_SOURCE3))) {\r\n\t\tconsole.log(\"Error building program 3\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\treturn true;\r\n}",
"isSameShader(firstShader, secondShader) {\n return firstShader.localeCompare(secondShader) === 0;\n }",
"defineAttribute(inName, inSize, inTypeStr) {\n\t\tthis.attributes[inName] = new ShaderAttribute(this, inName, inSize, inTypeStr);\n\t}",
"function enableShaderAttrib(prog, name)\n{\n\tvar attribLoc = gl.getAttribLocation(prog, name);\n\tgl.enableVertexAttribArray(attribLoc);\n\treturn attribLoc;\n}",
"bind(){ gl.ctx.useProgram( this.shader.program ); return this; }",
"function parseUniforms(gl, uniformsJSON) {\n checkParameter(\"parseUniforms\", gl, \"gl\");\n checkParameter(\"parseUniforms\", uniformsJSON, \"uniformsJSON\");\n var shaderProgram = gl.getParameter(gl.CURRENT_PROGRAM);\n if (shaderProgram === null) {\n throw \"Applying vertex attributes with no shader program\";\n }\n\n for (uniform in uniformsJSON) {\n var location = gl.getUniformLocation(shaderProgram, uniform);\n if (location == null) {\n continue;\n }\n var uniformInfo = uniformsJSON[uniform];\n var func = uniformInfo[\"func\"];\n checkParameter(\"parseUniforms\", func, \"uniformsJSON[\" + uniform + \"][func]\");\n var args = uniformInfo[\"args\"];\n checkParameter(\"parseUniforms\", args, \"uniformsJSON[\" + uniform + \"][args]\");\n // Find function name and reflect.\n if (func === \"glUniform1f\") {\n gl.uniform1f(location, args[0]);\n } else if (func === \"glUniform2f\") {\n gl.uniform2f(location, args[0], args[1]);\n } else if (func === \"glUniform3f\") {\n gl.uniform3f(location, args[0], args[1], args[2]);\n } else if (func === \"glUniform4f\") {\n gl.uniform4f(location, args[0], args[1], args[2], args[3]);\n } else if (func === \"glUniform1fv\") {\n gl.uniform1fv(locationloc, args);\n } else if (func === \"glUniform2fv\") {\n gl.uniform2fv(location, args);\n } else if (func === \"glUniform3fv\") {\n gl.uniform3fv(location, args);\n } else if (func === \"glUniform4fv\") {\n gl.uniform4fv(location, args);\n } else if (func === \"glUniform1i\") {\n gl.uniform1i(location, args[0]);\n } else if (func === \"glUniform2i\") {\n gl.uniform2i(location, args[0], args[1]);\n } else if (func === \"glUniform3i\") {\n gl.uniform3i(location, args[0], args[1], args[2]);\n } else if (func === \"glUniform4i\") {\n gl.uniform4i(location, args[0], args[1], args[2], args[3]);\n } else if (func === \"glUniform1iv\") {\n gl.uniform1iv(location, args);\n } else if (func === \"glUniformMatrix4fv\") {\n gl.uniformMatrix4fv(location, false, args);\n } else {\n console.log(\"Do not know how to set uniform via function \" + func + \" and args \" + args);\n }\n }\n}",
"getProgramFromShaders(vsCode, fsCode) {\n return this.programs.find((element) => {\n return this.isSameShader(element.vsCode, vsCode) && this.isSameShader(element.fsCode, fsCode);\n });\n }",
"uploadUniforms() {\n const gl = EngineToolbox.getGLContext();\n if (!this.shaderProgram) {\n return;\n }\n\n // pass uniforms to shader only if defined\n gl.useProgram(this.shaderProgram);\n this.uniforms.modelViewMatrix.value &&\n uniformMatrix4fv(this.uniforms.modelViewMatrix);\n this.uniforms.projectionMatrix.value &&\n uniformMatrix4fv(this.uniforms.projectionMatrix);\n this.uniforms.normalMatrix.value &&\n uniformMatrix4fv(this.uniforms.normalMatrix);\n this.uniforms.directLightDirection.value &&\n uniform3fv(this.uniforms.directLightDirection);\n this.uniforms.directLightColor.value &&\n uniform3fv(this.uniforms.directLightColor);\n this.uniforms.directLightValue.value &&\n uniform1fv(this.uniforms.directLightValue);\n this.uniforms.ambientLightColor.value &&\n uniform3fv(this.uniforms.ambientLightColor);\n this.uniforms.ambientLightValue.value &&\n uniform1fv(this.uniforms.ambientLightValue);\n this.uniforms.useVertexColor.value &&\n uniform1iv(this.uniforms.useVertexColor);\n this.uniforms.color0Sampler.value &&\n uniform1iv(this.uniforms.color0Sampler);\n this.uniforms.color1Sampler.value &&\n uniform1iv(this.uniforms.color1Sampler);\n this.uniforms.normal0Sampler.value &&\n uniform1iv(this.uniforms.normal0Sampler);\n this.uniforms.useColor0.value && uniform1iv(this.uniforms.useColor0);\n this.uniforms.useColor1.value && uniform1iv(this.uniforms.useColor1);\n this.uniforms.useNormal0.value && uniform1iv(this.uniforms.useNormal0);\n this.uniforms.useEmission.value && uniform1iv(this.uniforms.useEmission);\n this.uniforms.mapOffsetX.value && uniform1fv(this.uniforms.mapOffsetX);\n this.uniforms.mapOffsetY.value && uniform1fv(this.uniforms.mapOffsetY);\n this.uniforms.mapTilingX.value && uniform1fv(this.uniforms.mapTilingX);\n this.uniforms.mapTilingY.value && uniform1fv(this.uniforms.mapTilingY);\n }",
"function _compileShaders()\n\t{\n\t\tvar vertexShader = _loadShaderFromDOM( _vertexShaderId );\t\t// Get shaders and compile them.\n\t\tvar fragmentShader = _loadShaderFromDOM( _fragmentShaderId );\n\n\t\t_renderingProgram = gl.createProgram();\n\t\tgl.attachShader( _renderingProgram, vertexShader );\t\t\t\t// Link shaders to program.\n\t\tgl.attachShader( _renderingProgram, fragmentShader );\n\t\tgl.linkProgram( _renderingProgram );\n\n\t\tif( !gl.getProgramParameter( _renderingProgram, gl.LINK_STATUS ) )\n\t\t\talert( \"Failed to set up shaders!\" );\n\t}",
"function parseOnePortRule(rule){\n if (validRule(rule)==false ) {\n return \"err\";\n }\n\n rule = rule.split(\"\\x02\");\n\n //------------SOURCE PORT-----------------------\n rule[_src] = rule[_src].split(\"+\"); //tcp+udp\n if(isArray(rule[_src])){\n if(rule[_src].length == 2){\n rule[_src][_TCP] = rule[_src][_TCP].split(\",\"); //TCP\n rule[_src][_UDP] = rule[_src][_UDP].split(\",\"); //UDP\n }else{\n alert(\"1 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'\");\n }\n }else{\n alert(\"2 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'; is not an array??\");return \"err\";\n }\n //------------DESTINATION PORT-----------------------\n rule[_dst] = rule[_dst].split(\"+\"); //tcp+udp\n if(isArray(rule[_dst])){\n if(rule[_dst].length == 2){\n rule[_dst][_TCP] = rule[_dst][_TCP].split(\",\"); //TCP\n rule[_dst][_UDP] = rule[_dst][_UDP].split(\",\"); //UDP\n }else{\n alert(\"1 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'\");return \"err\";\n }\n }else{\n alert(\"2 \"+\"rule\"+\"#\"+n+\"srcport format error: should consists of TCP and UDP: using '+'; is not an array??\");return \"err\";\n }\n return rule;\n}",
"function parseVertex(gl, vertexJSON) {\n checkParameter(\"parseVertex\", gl, \"gl\");\n checkParameter(\"parseVertex\", vertexJSON, \"vertexJSON\");\n var shaderProgram = gl.getParameter(gl.CURRENT_PROGRAM);\n if (shaderProgram === null) {\n throw \"Applying vertex attributes with no shader program\";\n }\n var maxAttribute = 0;\n\n for (attribute in vertexJSON) {\n var attributeIndex = maxAttribute++;\n gl.bindAttribLocation(shaderProgram, attributeIndex, attribute);\n var attributeInfo = vertexJSON[attribute];\n var enabled = attributeInfo[\"enabled\"];\n checkParameter(\"parseVertex\", enabled, \"vertexJSON[\" + attribute + \"][enabled]\");\n if (enabled == \"false\") {\n // For disabled, it is the same as uniforms.\n var func = attributeInfo[\"func\"];\n checkParameter(\"parseVertex\", func, \"vertexJSON[\" + attribute + \"][func]\");\n var args = attributeInfo[\"args\"];\n checkParameter(\"parseVertex\", args, \"vertexJSON[\" + attribute + \"][args]\");\n // Find function name and reflect.\n if (func === \"glVertexAttrib1f\") {\n gl.vertexAttrib1f(attributeIndex, args[0]);\n } else if (func === \"glVertexAttrib2f\") {\n gl.vertexAttrib2f(attributeIndex, args[0], args[1]);\n } else if (func === \"glVertexAttrib3f\") {\n gl.vertexAttrib3f(attributeIndex, args[0], args[1], args[2]);\n } else if (func === \"glVertexAttrib4f\") {\n gl.vertexAttrib4f(attributeIndex, args[0], args[1], args[2], args[3]);\n } else if (func === \"glVertexAttrib1fv\") {\n gl.vertexAttrib1fv(attributeIndex, args);\n } else if (func === \"glVertexAttrib2fv\") {\n gl.vertexAttrib2fv(attributeIndex, args);\n } else if (func === \"glVertexAttrib3fv\") {\n gl.vertexAttrib3fv(attributeIndex, args);\n } else if (func === \"glVertexAttrib4fv\") {\n gl.vertexAttrib4fv(attributeIndex, args);\n } else {\n console.log(\"Do not know how to set attribute via function \" + func + \" and args \" + args);\n }\n } else {\n // Otherwise the input comes form the bound buffer.\n var size = attributeInfo[\"size\"];\n checkParameter(\"parseVertex\", size, \"vertexJSON[\" + attribute + \"][size]\");\n var stride = attributeInfo[\"stride\"];\n checkParameter(\"parseVertex\", stride, \"vertexJSON[\" + attribute + \"][stride]\");\n var offset = attributeInfo[\"offset\"];\n checkParameter(\"parseVertex\", offset, \"vertexJSON[\" + attribute + \"][offset]\");\n gl.vertexAttribPointer(attributeIndex, size, gl.FLOAT, false, stride, offset);\n gl.enableVertexAttribArray(attributeIndex);\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extended Resource Settings storeOffline: true, resourceName: openmrs.patient usesEncryption: true, primaryKey : "uuid" queryFields : all (for now) | function getResource(){
var v = "custom:(uuid,identifiers:ref,person:(uuid,gender,birthdate,dead,deathDate,preferredName:(givenName,middleName,familyName),"
+ "attributes:(uuid,value,attributeType:ref)))";
r = $resource(OpenmrsSettings.getContext() + "/ws/rest/v1/patient/:uuid",
{uuid: '@uuid', v: v},
{query: {method: "GET", isArray: false}}
);
return new dataMgr.ExtendedResource(r,true,resourceName,true,"uuid",null);
} | [
"function getResource() {\n r = $resource(OpenmrsSettings.getContext() + \"/ws/rest/v1/provider/:uuid\",\n {uuid: '@uuid', v: v},\n {query: {method: \"GET\", isArray: false}}\n );\n return new dataMgr.ExtendedResource(r,true,resourceName,false,\"uuid\",null);\n }",
"function getResource() {\n r = $resource(OpenmrsSettings.getContext() + \"/ws/rest/v1/person/:uuid\",\n {uuid: '@uuid'},\n {query: {method: \"GET\", isArray: false}}\n );\n return new dataMgr.ExtendedResource($resource,true,resourceName,true,'uuid',null);\n }",
"function getResource() {\n r = $resource(OpenmrsSettings.getContext() + \"/ws/rest/v1/location/:uuid\",\n {uuid: '@uuid'},\n {query: {method: \"GET\", isArray: false}}\n );\n return new dataMgr.ExtendedResource(r,true,resourceName,false,\"uuid\",null);\n }",
"function getResource() {\n var v = \"custom:(uuid,name,encounterType:(uuid,name))\";\n r = $resource(OpenmrsSettings.getContext() + \"/ws/rest/v1/form/:uuid\",\n {uuid: '@uuid', v: v},\n {query: {method: \"GET\", isArray: false}}\n );\n return new dataMgr.ExtendedResource(r,true,resourceName,false,\"uuid\",null);\n }",
"function getResource() {\n var v = \"custom:(uuid,username,systemId,roles:(uuid,name,privileges))\";\n r = $resource(OpenmrsSettings.getContext() + \"/ws/rest/v1/user/:uuid\",\n {uuid: '@uuid', v: v},\n {query: {method: \"GET\", isArray: false}}\n );\n return new dataMgr.ExtendedResource(r,true,resourceName,false,\"uuid\",null);\n }",
"function getResource() {\n var v = \"custom:(uuid,encounterDatetime,patient:(uuid,uuid),form:(uuid,name),location:ref\";\n v += \",encounterType:ref,provider:ref,obs:(uuid,concept:ref,value:ref,groupMembers))\";\n r = $resource(OpenmrsSettings.getContext() + \"/ws/rest/v1/encounter/:uuid\",\n {uuid: '@uuid', v: v},\n {query: {method: \"GET\", isArray: false}}\n );\n return new dataMgr.ExtendedResource(r,true,resourceName,true,\"uuid\",null);\n }",
"loadResource() {\n // Load Selects\n // Assign Values\n this.is_auto_reclaimable.property('checked', this.resource.is_auto_reclaimable)\n this.ddl_statement.property('value', this.resource.ddl_statement)\n this.capacity_mode.property('value', this.resource.table_limits.capacity_mode)\n this.max_storage_in_gbs.property('value', this.resource.table_limits.max_storage_in_gbs)\n this.max_read_units.property('value', this.resource.table_limits.max_read_units)\n this.max_write_units.property('value', this.resource.table_limits.max_write_units)\n this.estimated_on_demand_reads_per_month.property('value', this.resource.pricing_estimates.estimated_on_demand_reads_per_month)\n this.estimated_on_demand_writes_per_month.property('value', this.resource.pricing_estimates.estimated_on_demand_writes_per_month)\n this.showHideReadWrite()\n this.loadIndexes()\n }",
"function serializeResourceProperties(label, props, opts) {\n return __awaiter(this, void 0, void 0, function* () {\n return serializeFilteredProperties(label, props, (key) => key !== \"id\" && key !== \"urn\", opts);\n });\n}",
"function readProperties() {\r\n\tlocalStorage.setItem(\"reloaded\", false);\r\n\t$.getJSON(\"manifest.webapp\", function( json ) {\r\n\t\tbaseUrl = json.activities.dhis.href;\r\n\t\t//TODO Update to new version when current DHIS version = 30!\t\t\r\n\t\tapiBaseUrl = baseUrl + \"/api/26\";\t\t\t\t\t\r\n\t})\r\n\t.done(function(){\r\n\t\tqueryUserRoles();\r\n\t});\t\t\r\n}",
"get informationRightsManagementSettings() {\n return SPQueryable(this, \"InformationRightsManagementSettings\");\n }",
"loadResource() {\n // Load Selects\n // Assign Values\n this.description.property('value', this.resource.description)\n }",
"function getConfigurationModel(axios$$1, identifier) {\n return restAuthGet(axios$$1, 'instance/microservice/' + identifier + '/configuration/model');\n }",
"get resourceMapper() {\n return this._resourceMapper;\n }",
"getResourceDetailsAPI() {\n const endpointGET = environment.apiUrl + moduleUrls.ProjectResources + '?_where=(projectId,eq,' + this.state.projectId + ')';\n return $.ajax({\n url: endpointGET,\n type: Type.get,\n data: ''\n });\n }",
"static get __resourceType() {\n\t\treturn 'ExpansionProfileDesignationExclude';\n\t}",
"function getConfigPricingFromResourceQuery(ownerid, elements, callback) {\n var configJson = {};\n\n // Identify configurable vs\n if((elements.uri).match('vs/') && (elements.uri).match('/configurable')){\n configJson.volumeStorageUri = elements.uri;\n if(elements.parameters && elements.parameters.sizeInGBytes){\n configJson.size = elements.parameters.sizeInGBytes;\n }\n }else if((elements.uri).match('saas/') && (elements.uri).match('/configurable')){\n configJson.uri = elements.uri;\n if(elements.parameters && elements.parameters.sizeInGBytes){\n configJson.size = elements.parameters.sizeInGBytes;\n }\n }else {\n if(elements.uri){\n configJson.instanceTypeUri = elements.uri;\n }\n if(elements.parameters && elements.parameters.imageUri){\n configJson.imageUri = elements.parameters.imageUri;\n }\n if(elements.parameters && elements.parameters.ram){\n configJson.ram = elements.parameters.ram;\n }\n if(elements.parameters && elements.parameters.cpuCount){\n configJson.cpuCount = elements.parameters.cpuCount;\n }\n if(elements.parameters && elements.parameters.localStorage){\n configJson.localStorage = elements.parameters.localStorage;\n }\n trace.info(configJson);\n }\n\n jsonObject = JSON.stringify(configJson);\n\n // prepare the header\n //TODO Implement new Auth Model\n var postheaders = {\n 'Content-Type' : 'application/json',\n 'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')\n //\"Authorization\": \"Basic \" + new Buffer(ownerid + \":\" + ownerid).toString(\"base64\")\n };\n\n postheaders[authConfig.bypassHeaderName] = 'billing'+':'+authConfig.billing;\n postheaders['ownerId'] = ownerid;\n\n // the post options\n var optionspost = {\n host : config.resourceServiceHost,\n port : config.resourceServicePort,\n path : '/apiv1.0/resourceQuery/validate',\n method : 'POST',\n headers : postheaders\n };\n\n // do the POST call to resource service\n restservices.postCall(optionspost,jsonObject).then(function (resourceServiceresult) {\n return callback(resourceServiceresult);\n\n }).catch(function onReject(err) {\n trace.error('Rejected', err);\n if(err.stack)\n trace.debug('Error Occurred in : '+ err.stack);\n return callback(null);\n\n }).catch(function(error){\n trace.error('Catch Error:', error);\n if(error.stack)\n trace.debug('Error Occurred in : '+ error.stack);\n return callback(null);\n });\n}",
"constructor(t, name, custom, props = {}, opts = {}, remote = false, dependency = false) {\n /**\n * A private field to help with RTTI that works in SxS scenarios.\n * @internal\n */\n // eslint-disable-next-line @typescript-eslint/naming-convention,no-underscore-dangle,id-blacklist,id-match\n this.__pulumiResource = true;\n this.__pulumiType = t;\n if (dependency) {\n this.__protect = false;\n this.__providers = {};\n return;\n }\n if (opts.parent && !Resource.isInstance(opts.parent)) {\n throw new Error(`Resource parent is not a valid Resource: ${opts.parent}`);\n }\n if (!t) {\n throw new errors_1.ResourceError(\"Missing resource type argument\", opts.parent);\n }\n if (!name) {\n throw new errors_1.ResourceError(\"Missing resource name argument (for URN creation)\", opts.parent);\n }\n // Before anything else - if there are transformations registered, invoke them in order to transform the properties and\n // options assigned to this resource.\n const parent = opts.parent || state_1.getStackResource();\n this.__transformations = [...(opts.transformations || []), ...((parent === null || parent === void 0 ? void 0 : parent.__transformations) || [])];\n for (const transformation of this.__transformations) {\n const tres = transformation({ resource: this, type: t, name, props, opts });\n if (tres) {\n if (tres.opts.parent !== opts.parent) {\n // This is currently not allowed because the parent tree is needed to establish what\n // transformation to apply in the first place, and to compute inheritance of other\n // resource options in the Resource constructor before transformations are run (so\n // modifying it here would only even partially take affect). It's theoretically\n // possible this restriction could be lifted in the future, but for now just\n // disallow re-parenting resources in transformations to be safe.\n throw new Error(\"Transformations cannot currently be used to change the `parent` of a resource.\");\n }\n props = tres.props;\n opts = tres.opts;\n }\n }\n this.__name = name;\n // Make a shallow clone of opts to ensure we don't modify the value passed in.\n opts = Object.assign({}, opts);\n // Check the parent type if one exists and fill in any default options.\n this.__providers = {};\n if (parent) {\n this.__parentResource = parent;\n this.__parentResource.__childResources = this.__parentResource.__childResources || new Set();\n this.__parentResource.__childResources.add(this);\n if (opts.protect === undefined) {\n opts.protect = parent.__protect;\n }\n this.__providers = parent.__providers;\n }\n // providers is found by combining (in ascending order of priority)\n // 1. provider\n // 2. self_providers\n // 3. opts.providers\n this.__providers = Object.assign(Object.assign(Object.assign({}, this.__providers), convertToProvidersMap(opts.providers)), convertToProvidersMap(opts.provider ? [opts.provider] : {}));\n // provider is the first option that does not return none\n // 1. opts.provider\n // 2. a matching provider in opts.providers\n // 3. a matching provider inherited from opts.parent\n if ((custom || remote) && opts.provider === undefined) {\n const pkg = resource_1.pkgFromType(t);\n const parentProvider = parent === null || parent === void 0 ? void 0 : parent.getProvider(t);\n if (pkg && pkg in this.__providers) {\n opts.provider = this.__providers[pkg];\n }\n else if (parentProvider) {\n opts.provider = parentProvider;\n }\n }\n this.__protect = !!opts.protect;\n this.__prov = custom || remote ? opts.provider : undefined;\n this.__version = opts.version;\n this.__pluginDownloadURL = opts.pluginDownloadURL;\n // Collapse any `Alias`es down to URNs. We have to wait until this point to do so because we do not know the\n // default `name` and `type` to apply until we are inside the resource constructor.\n this.__aliases = [];\n if (opts.aliases) {\n for (const alias of opts.aliases) {\n this.__aliases.push(collapseAliasToUrn(alias, name, t, parent));\n }\n }\n const sourcePosition = Resource.sourcePosition();\n if (opts.urn) {\n // This is a resource that already exists. Read its state from the engine.\n resource_1.getResource(this, parent, props, custom, opts.urn);\n }\n else if (opts.id) {\n // If this is a custom resource that already exists, read its state from the provider.\n if (!custom) {\n throw new errors_1.ResourceError(\"Cannot read an existing resource unless it has a custom provider\", opts.parent);\n }\n resource_1.readResource(this, parent, t, name, props, opts, sourcePosition);\n }\n else {\n // Kick off the resource registration. If we are actually performing a deployment, this\n // resource's properties will be resolved asynchronously after the operation completes, so\n // that dependent computations resolve normally. If we are just planning, on the other\n // hand, values will never resolve.\n resource_1.registerResource(this, parent, t, name, custom, remote, (urn) => new DependencyResource(urn), props, opts, sourcePosition);\n }\n }",
"static get __resourceType() {\n\t\treturn 'Patient';\n\t}",
"static getModelName() {\n return \"ApplicationCredential\";\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch documents with new permissions | fetchNowAccessibleDocuments(previous) {
const permissions = this.getAllPermissions().filter((permission) => {
const found = previous.getAllPermissions().find((previousPermission) => {
return permission.isSame(previousPermission)
})
return !found
}).map((permission) => {
return {
action: permission.action,
permissible_type: permission.permissibleType,
scope: permission.scope,
scope_id: permission.scopeId
}
})
/**
* Fetch documents that we can access with
* our new permissions if we have any.
*/
if (permissions.length ||
this.assignAllCountries !== previous.assignAllCountries ||
this.assignAllClients !== previous.assignAllClients ||
!_.isEqual(this.assignedCountries.slice().sort(), previous.assignedCountries.slice().sort()) ||
!_.isEqual(this.assignedClients.slice().sort(), previous.assignedClients.slice().sort())
) {
Api.post('documents/accessible', {
permissions
}).then((data) => {
for (let documentType in data) {
const repositoryName = getRepositoryName(documentType)
store.dispatch(`documents/repositories/${repositoryName}/ADD_ITEMS`, data[documentType])
}
})
}
} | [
"async editable(req) {\n if (!req.user) {\n throw self.apos.error('notfound');\n }\n const ids = self.apos.launder.ids(req.body.ids);\n if (!ids.length) {\n return {\n editable: []\n };\n }\n const found = await self.apos.doc.find(req, {\n _id: {\n $in: ids\n }\n }).project({ _id: 1 }).permission('edit').toArray();\n return {\n editable: self.apos.util.orderById(ids, found).map(doc => doc._id)\n };\n }",
"async shareDocumentToUser(id, userId, accessType = null) {\n\n const User = this.database.models().user\n const user = await User.get(userId)\n const document = await this.get(id)\n\n return new Promise((resolve, reject) => {\n\n if (!document) {\n return reject('Document found.')\n }\n if (!user) {\n return reject('User not found.')\n }\n\n // let remove\n\n // let remove in cache\n this.cache_remove(id)\n if (accessType === 'write') {\n this.getCollection().updateOne(\n { _id: document._id },\n {\n $pull: { readPermissions: user._id },\n $addToSet: { writePermissions: user._id },\n },\n (err, result) => {\n if (err) {\n return reject(err)\n }\n\n return resolve({\n firstName: _.get(user, 'firstName', ''),\n lastName: _.get(user, 'lastName'),\n email: null,\n type: 'write',\n userId: userId,\n documentId: id,\n })\n\n },\n )\n }\n else if (accessType === 'read') {\n this.getCollection().updateOne(\n { _id: document._id },\n {\n $pull: { writePermissions: user._id },\n $addToSet: { readPermissions: user._id },\n },\n (err, result) => {\n if (err) {\n return reject(err)\n }\n\n return resolve({\n firstName: _.get(user, 'firstName', ''),\n lastName: _.get(user, 'lastName'),\n email: null,\n type: 'read',\n userId: userId,\n documentId: id,\n })\n },\n )\n }\n else {\n\n // let remove read & write permission\n this.getCollection().updateOne(\n { _id: document._id },\n {\n $pull: { writePermissions: user._id, readPermissions: user._id },\n },\n (err, result) => {\n return err ? reject(err) : resolve({\n firstName: null,\n lastName: null,\n email: null,\n type: null,\n userId: userId,\n documentId: id,\n })\n },\n )\n }\n\n })\n\n }",
"function loadDocuments() {\n console.log(\"loadDocuments() started\");\n showMessage(\"Loading private documents for '\" + user.name + \"' ...\");\n user.privateDocuments.get({\n limit : 1000\n }).execute(function(response) {\n console.log(\"loadDocuments() response = \" + JSON.stringify(response));\n var html = '<ul>';\n documents = response.data;\n $.each(documents, function(index, doc) {\n html += '<li>';\n html += '<a href=\"#\" class=\"document-select\" data-index=\"' + index + '\">' + doc.subject + '</a>';\n html += ' (' + doc.viewCount + ' views)';\n html += '</li>';\n });\n html += '</ul>';\n $(\"#documents-list\").html(\"\").html(html);\n $(\".document-select\").click(function () {\n var index = $(this).attr(\"data-index\");\n current = documents[index];\n $(\".document-subject\").html(\"\").html(current.subject);\n showDocument();\n });\n showOnly(\"documents-div\");\n });\n}",
"getAllNews() {\n\n this.dataBase.findByIndex(\"/news\", [\"_id\", \"title\", \"attachment\"],\"categoryId\", mvc.routeParams.id).then( data => {\n if (data) {\n let length = data.docs.length;\n this.liftNewsInCategory = data.docs.slice(0, length / 2);\n this.rightNewsInCategory = data.docs.slice(length / 2, length);\n mvc.apply();\n } else {\n this.getAllNews()\n }\n }, () => {\n this.getAllNews();\n });\n\n }",
"static list(collection, filter={}) {\n return db.db.allDocs({include_docs: true});\n }",
"function fnsviewpermissiondetails() {\r\n\t\t$http.get('http://localhost:1337/viewpermissions').success(function (data) {\r\n\t\t\t$scope.userrelationcollection = data;\r\n\t\t});\r\n\t}",
"function loadArticles() {\n // clear article list\n clearArticleListChildren();\n\n // Create the query to load the last 12 articles and listen for new ones.\n var articlesRef = firebase.firestore().collection('articles');\n\n if (isUserSignedIn()) {\n // Get public articles\n var query_public = articlesRef.where('permission', '==', \"public\").orderBy('createdAt', 'desc').limit(10);\n loadArticlesWithQuery(query_public);\n\n // Get protected articles\n var query_protected = articlesRef.where('permission', '==', \"protected\").orderBy('createdAt', 'desc').limit(10);\n loadArticlesWithQuery(query_protected);\n\n // Get private articles owned by current user\n var query_own_private = articlesRef.where('permission', '==', \"private\").where('authorId', '==', getUserId()).orderBy('createdAt', 'desc').limit(10);\n loadArticlesWithQuery(query_own_private);\n } else {\n // Get public articles\n var query_public = articlesRef.where('permission', '==', \"public\").orderBy('createdAt', 'desc').limit(10);\n loadArticlesWithQuery(query_public);\n }\n}",
"updatePermissions() {\n this.permissions = this.codenvyAPI.getProject().getPermissions(this.workspaceId, this.projectName);\n }",
"getAllDocuments () {\n return this.getAllModels().map(model => model.document)\n }",
"async function getCurrentUserEffectivePermissions() {\n return SPQueryable(this, \"EffectiveBasePermissions\")();\n}",
"static listAction(filter = null, pager = null){\n\t\tlet kparams = {};\n\t\tkparams.filter = filter;\n\t\tkparams.pager = pager;\n\t\treturn new kaltura.RequestBuilder('document_documents', 'list', kparams);\n\t}",
"grantWriteAccess () {\n\n\t\t\tlet clientId = appConfig.auth[process.env.NODE_ENV === 'production' ? 'prod' : 'dev'],\n\t\t\t\turl = 'https://api.github.com/authorizations';\n\n\t\t\treturn transport.request(url)//, null, this.buildAuthHeader())\n\t\t\t.then(\n\t\t\t\tresponse => {\n\t\t\t\t\tlet openRedistApp = response.find(authedApp => authedApp.app.client_id === clientId);\n\n\t\t\t\t\tif (!openRedistApp) throw new Error('User is not currently authed.');\n\n\t\t\t\t\tif (openRedistApp.scopes.includes('public_repo')) {\n\t\t\t\t\t\treturn { userHasWriteAccess: true };\n\t\t\t\t\t} else {\n\t\t\t\t\t\turl = `https://api.github.com/authorizations/${ openRedistApp.id }`;\n\t\t\t\t\t\treturn transport.request(url, null, {\n\t\t\t\t\t\t\t...this.buildAuthHeader(),\n\t\t\t\t\t\t\tmethod: 'PATCH',\n\t\t\t\t\t\t\tbody: {\n\t\t\t\t\t\t\t\tadd_scopes: [ 'public_repo' ]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t)\n\t\t\t.then(\n\t\t\t\tresponse => {\n\t\t\t\t\treturn { userHasWriteAccess: true };\n\t\t\t\t}\n\t\t\t)\n\t\t\t.catch(error => {\n\t\t\t\t// fail loudly if the application errors further down the promise chain.\n\t\t\t\tthis.handleError(error);\n\t\t\t\tthrow error;\n\t\t\t});\n\n\t\t}",
"function GetDocuments()\n{\n\t// specify criteria for document search\n\tvar Criteria =\n\t{\n\t\t// extensions should be fixed to image\n\t\tDocIds: [1001],\n\t\t//Extensions: new Array(\".jpg\", \".png\", \".gif\", \".bmp\"),\n\t\t//DocTypeIds: new Array(1, 2), // specify document type ids which you canget from GetDocumentTypes()\n\t\t//Titles: ['Addenda_15497_rpt_s15%.pdf', 'Addenda_10000_rpt_s15%.pdf'],\n\t\t//FolderIds: [3]\n\t ExcludeStatuses: [4,5]\n\n\t\t// specify job number\n\t\t//AttributeCriterias: {\n\t\t//\tAttributes:\t[{\n\t\t//\t\t\tValues: {\n\t\t//\t\t\t\tid: 125, // can be fixed 3 (Job No)\n\t\t//\t\t\t\tatbValue: \"15497\" // job number (00007 is a test job number)\n\t\t//\t\t\t},\n\t\t//\t\t\tUseWildCard: false\n\t\t//\t}]\n\t\t//}\n\t}\n\n\t$.ajax({\n\t\turl: action_url + 'GetDocuments/' + UserId,\n\t\ttype: \"POST\",\n\t\tcontentType: \"application/json; charset=utf-8\",\n\t\tdata: JSON.stringify(Criteria), \n\t\tsuccess: function(Result)\n\t\t{\n\t\t\t// returns multiple document infomation\n\t\t\t$.each(Result.Documents, function(index, value)\n\t\t\t{\n\t\t\t\tvar JobNo;\n\t\t\t\tvar Sheet;\n\t\t\t\tvar PhotoType;\n\n\t\t\t\tfor(var i = 0; i < value.Attrs.length; i++)\n\t\t\t\t{\n\t\t\t\t\tswitch(value.Attrs[i].id)\n\t\t\t\t\t{\n\t\t\t\t\tcase 3:\n\t\t\t\t\t\tJobNo = value.Attrs[i].atbValueForUI;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 10:\n\t\t\t\t\t\tSheet = value.Attrs[i].atbValueForUI;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase 18:\n\t\t\t\t\t\tPhotoType = value.Attrs[i].atbValueForUI;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\talert(\"Document ID: \" + value.id + \"\\n\" +\n\t\t\t\t\t \"Version ID: \" + value.id_version + \"\\n\" +\n\t\t\t\t\t \"Title: \" + value.title + \"\\n\" +\n\t\t\t\t\t \"JobNo: \" + JobNo + \"\\n\" + \n\t\t\t\t\t \"Sheet: \" + Sheet + \"\\n\" + \n\t\t\t\t\t \"Photo Type: \" + PhotoType);\n\t\t\t});\n\t\t}\n\t});\n}",
"getNews() {\n\n this.dataBase.findByIndex(\"/news\",\n [\"_id\", \"title\", \"attachment\", \"seoDescription\", \"isMainNews\", \"createDate\", \"writerId\"], \"categoryId\", mvc.routeParams.id).then( data => {\n\n if (data) {\n this.listMainNews = data.docs.filter((el) => { return el.isMainNews});\n if (this.listMainNews.lenght > 3) {\n this.listMainNews = this.listMainNews.slice(0, 3);\n }\n this.mainNews = this.listMainNews[0];\n this.getWriters();\n mvc.apply();\n } else {\n this.getNews();\n }\n }, () => {\n this.getNews();\n });\n }",
"function refreshIndexes(){\r\n\tvar pubs\r\n\ttry {\r\n\t\tPublication.find({}).then((data) => {\r\n\t\t\tpubs = data\r\n\t\t\tpubs.forEach((pub) => {\r\n\t\t\t\tlet tempPub = indexarPub(pub)\r\n\t\t\t\tPublication.updateOne({\"_id\":pub.id}, tempPub)\r\n\t\t\t})\r\n\t\t})\r\n\t} catch (error) {\r\n\t\tconsole.log(error)\r\n\t}\r\n}",
"async function fetchTaskDocs(instanceURL, userToken) {\n //Base64 encode ticket\n var encodedTicket = base64.encode(userToken);\n var endPoint =\n instanceURL +\n '/alfresco/api/-default-/public/workflow/versions/1/tasks/' +\n taskItem.entry.id +\n '/items';\n\n try {\n let response = await fetch(endPoint, {\n method: 'GET',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n Authorization: 'Basic ' + encodedTicket,\n },\n });\n if (response.ok) {\n let json = await response.json();\n setTaskDocs(json.list.entries);\n } else {\n console.log('Could not fetch documents ' + response.status);\n alert('Could not fetch documents.');\n }\n } catch (error) {\n console.log(error);\n alert('Could not fetch documents. Please check Server URL.');\n }\n }",
"constructor(firestore) {\n this.publicidadCollection = firestore.collection('Publicidad');\n //this.probar1 = firestore.collection('Publicaciones'.where(\"Visibilidad\", \"==\", true).get();\n this.publicidad = this.publicidadCollection.snapshotChanges().pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[\"map\"])(actions => {\n return actions.map(a => {\n const data = a.payload.doc.data();\n const id = a.payload.doc.id;\n return Object.assign({ id }, data);\n });\n }));\n }",
"constructor(firestore) {\n this.publicacionesCollection = firestore.collection('PublicacionesGenerales');\n //this.probar1 = firestore.collection('Publicaciones'.where(\"Visibilidad\", \"==\", true).get();\n this.publicaciones = this.publicacionesCollection.snapshotChanges().pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[\"map\"])(actions => {\n return actions.map(a => {\n const data = a.payload.doc.data();\n const id = a.payload.doc.id;\n return Object.assign({ id }, data);\n });\n }));\n this.publicacionesMateriaCollection = firestore.collection('Publicaciones', ref => ref.orderBy(\"Fecha\", \"desc\"));\n this.publicacionesMateria = this.publicacionesMateriaCollection.snapshotChanges().pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[\"map\"])(actions => {\n return actions.map(a => {\n const data = a.payload.doc.data();\n const id = a.payload.doc.id;\n return Object.assign({ id }, data);\n });\n }));\n }",
"list(req, res) {\n const userId = req.param('userId');\n\n if(req.token.id !== userId) {\n return res.fail('You don\\'t have permission to do this.');\n }\n\n ApplianceService.fetchAllForUser(userId)\n .then(res.success)\n .catch(res.fail);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create nodes for all the existing activities and connect them | function loadActivities() {
clearCanvas();
nodesArray = [];
loadedStory.activities.forEach((a) => {
addActivityNode(a);
});
//After we created all nodes we create all outputs and make the connections
loadedStory.activities.forEach((a, index) => {
setNodeOutputs(a, nodesArray[index]);
});
} | [
"function addActivityNode(activity) {\n let n = new Node(activity.name, activity.position, {\n onCopy: () => {\n copiedActivity = JSON.stringify(activity);\n $(\"#activity-paste\").prop(\"disabled\", false);\n }, \n \n onDelete: () => {\n editorDirty = true;\n deleteActivity(activity);\n },\n \n onNameChange: (name) => {\n editorDirty = true;\n activity.name = name;\n },\n \n onPositionChange: (pos) => {\n editorDirty = true;\n activity.position = pos;\n }\n });\n \n if(activity.special)\n n.hideButtons();\n \n n.setColor(activityColor(activity));\n \n let modify = $('<button class=\"node-modify\">Modifica attività</button>');\n modify.on(\"click\", (e) => openActivityEditor(activity, n));\n n.body().append(modify);\n \n if(activity.special != \"begin\") {\n n.addInput({\n single: false\n });\n }\n \n nodesArray.push(n);\n \n return n;\n}",
"_createNodes() {\n // Test all statements for leadership\n // If they are leaders, create node\n for (const $stmt of Query.searchFromInclusive(this.#jp, \"statement\")) {\n if (CfgUtils.isLeader($stmt)) {\n\n if (this.#splitInstList && CfgUtils.getNodeType($stmt) === CfgNodeType.INST_LIST) {\n this._getOrAddNode($stmt, true, CfgNodeType.INST_LIST);\n\n for (const $right of $stmt.siblingsRight) {\n if (!CfgUtils.isLeader($right))\n this._getOrAddNode($right, true, CfgNodeType.INST_LIST);\n else \n break;\n }\n }\n else\n this._getOrAddNode($stmt, true);\n }\n }\n\n // Special case: if starting node is a statement and a graph node was not created for it (e.g. creating a graph starting from an arbitrary statement),\n // create one with the type INST_LIST\n if (\n this.#jp.instanceOf(\"statement\") &&\n this.#nodes.get(this.#jp.astId) === undefined\n ) {\n this._getOrAddNode(this.#jp, true, CfgNodeType.INST_LIST);\n }\n }",
"createTasks() {\n let jobProfile = null; // \"arwen_express\" or \"arwen_cpu\" for example\n let management = {\n 'jobManager': this.jobManager,\n 'jobProfile': jobProfile\n };\n return this.nodes.map((n) => {\n return new taskModules[n.tagtask](management);\n });\n }",
"_connectNodes() {\n // Connect start\n let startAstNode = this.#jp;\n if (startAstNode.instanceOf(\"function\")) {\n startAstNode = startAstNode.body;\n }\n\n if (!startAstNode.instanceOf(\"statement\")) {\n throw new Error(\n \"Not defined how to connect the Start node to an AST node of type \" +\n this.#jp.joinPointType\n );\n }\n\n let afterNode = this.#nodes.get(startAstNode.astId);\n\n // Add edge\n this.#addEdge(this.#startNode, afterNode, CfgEdgeType.UNCONDITIONAL);\n\n for (const astId of this.#nodes.keys()) {\n const node = this.#nodes.get(astId);\n\n // Only add connections for astIds of leader statements\n if (node.data().nodeStmt.astId !== astId) continue;\n\n const nodeType = node.data().type;\n\n if (nodeType === undefined) {\n throw new Error(\"Node type is undefined: \");\n //continue;\n }\n\n switch (nodeType) {\n case CfgNodeType.IF:\n this.#connectIfNode(node);\n break;\n case CfgNodeType.LOOP:\n this.#connectLoopNode(node);\n break;\n case CfgNodeType.COND:\n this.#connectCondNode(node);\n break;\n case CfgNodeType.BREAK:\n this.#connectBreakNode(node);\n break;\n case CfgNodeType.CONTINUE:\n this.#connectContinueNode(node);\n break;\n case CfgNodeType.SWITCH:\n this.#connectSwitchNode(node);\n break;\n case CfgNodeType.CASE:\n this.#connectCaseNode(node);\n break;\n case CfgNodeType.INIT:\n this.#connectInitNode(node);\n break;\n case CfgNodeType.STEP:\n this.#connectStepNode(node);\n break;\n case CfgNodeType.INST_LIST:\n this.#connectInstListNode(node);\n break;\n case CfgNodeType.RETURN:\n this.#connectReturnNode(node);\n break;\n case CfgNodeType.SCOPE:\n case CfgNodeType.THEN:\n case CfgNodeType.ELSE:\n this.#connectScopeNode(node);\n break;\n }\n }\n }",
"async function addNodes() {\n const territoryKeys = Object.keys(territoryGraph);\n let lenTerritories = territoryKeys.length;\n while (lenTerritories) {\n lenTerritories -= 1;\n const territoryKey = territoryKeys[lenTerritories];\n territoryGraphStructure.add(territoryKey);\n }\n}",
"function makeRelationshipProcessInstance(node,result){\n var root_node_id = node[0]._id;\n var other_node_id = result._id;\n db.insertRelationship(other_node_id, root_node_id, 'INSTANCE_OF', {}, function(err, result){\n });\n\n}",
"build_nodes_topological_ordering(){\n var topological_ordered_list = [];\n\n //get all nodes\n var all_nodes = this.get_nodes();\n var ids_queue = this.get_nodes_att_values(all_nodes, 'id');\n\n //console.log(ids_queue.shift(),ids_queue);\n //var count = 15;\n while (ids_queue.length > 0) {\n //count--; if (count == 0) {break;}\n\n //console.log(ids_queue.length, ids_queue, topological_ordered_list);\n var n_id = ids_queue.shift();\n var a_node = this.get_gen_elem_by_id(n_id);\n var a_node_config = this.CONFIG[a_node._private.data.type][a_node._private.data.value];\n\n //define the node method for both cases\n var a_node_class = null;\n var a_node_compatible_inputs = [];\n if (a_node._private.data.type == 'tool') {\n a_node_class = a_node_config[\"function\"];\n a_node_compatible_inputs = a_node_config[\"compatible_input\"];\n }else if (a_node._private.data.type == 'data') {\n a_node_class = a_node_config[\"data_class\"];\n }\n\n //var a_node_to_process = jQuery.extend(true, {}, a_node);\n var a_node_to_process = a_node._private.data;\n a_node_to_process['workflow'] = {};\n a_node_to_process.workflow['class'] = a_node_class;\n a_node_to_process.workflow['compatible_input'] = a_node_compatible_inputs;\n a_node_to_process.workflow['input'] = this.get_nodes_att_values(this.get_source_nodes(a_node),'id');\n a_node_to_process.workflow['output'] = this.get_nodes_att_values(this.get_target_nodes(a_node),'id');\n\n if(!(_process_node(a_node_to_process))){\n ids_queue.push(n_id);\n }\n }\n\n return topological_ordered_list;\n\n function _process_node(a_node){\n var add_it = false;\n var inputs = a_node.workflow.input;\n\n //check if all its inputs are inside the index_processed\n var all_processed = true;\n for (var j = 0; j < inputs.length; j++) {\n if(_in_topological_order(inputs[j], topological_ordered_list)) {\n all_processed = true;\n }else {\n all_processed = false;\n break;\n }\n }\n if (all_processed) {\n add_it = true;\n }\n\n if (add_it) {\n topological_ordered_list.push(a_node);\n }\n\n return add_it;\n\n function _in_topological_order(val, topological_ordered_list){\n for (var k = 0; k < topological_ordered_list.length; k++) {\n if(topological_ordered_list[k].id == val){\n return true;\n }\n }\n return false;\n }\n }\n }",
"function insertAllActivities(){\n var length = activities.length;\n\n if (length > 0) {\n //I go through all activities to get the the ids.\n for (var i = 0; i < activities.length; ++i) {\n getStravaDataActivity(activities[i]);\n }\n } else {\n console.error(\"No data activities\");\n }\n}",
"function addNodeAndLink(e, obj) {\n var adornment = obj.part\n var diagram = e.diagram\n diagram.startTransaction('Add State')\n\n // get the node data for which the user clicked the button\n var fromNode = adornment.adornedPart\n var fromData = fromNode.data\n // create a new \"State\" data object, positioned off to the right of the adorned Node\n var toData = { text: 'new' }\n var p = fromNode.location.copy()\n p.x += 200\n toData.loc = GO.Point.stringify(p) // the \"loc\" property is a string, not a Point object\n // add the new node data to the model\n var model = diagram.model\n model.addNodeData(toData)\n\n // create a link data from the old node data to the new node data\n var linkdata = {\n from: model.getKeyForNodeData(fromData), // or just: fromData.id\n to: model.getKeyForNodeData(toData),\n text: 'transition'\n }\n // and add the link data to the model\n model.addLinkData(linkdata)\n\n // select the new Node\n var newnode = diagram.findNodeForData(toData)\n diagram.select(newnode)\n\n diagram.commitTransaction('Add State')\n\n // if the new node is off-screen, scroll the diagram to show the new node\n diagram.scrollToRect(newnode.actualBounds)\n }",
"constructor(nodesToRemove, nodesToAdd) {\n this.nodesToRemove = nodesToRemove;\n this.nodesToAdd = nodesToAdd;\n }",
"function NewEmployeeNode(emp : Funcionario, slot : EmployeeList)\n{\n\tvar employeeNode : EmployeeNode = new EmployeeNode();\n\t\n\temployeeNode.employee = emp.Copy();\n\temployeeNode.actionList = new ActionList();\n\temployeeNode.secActionList = new ActionList();\n\temployeeNode.espActionList = new ActionList();\n\t\n\tslot.Add(employeeNode);\n\t\n\tvar prov : ExtractProvenance;\n\tprov = emp.GetComponentInChildren(ExtractProvenance);\n\t\n\tprov.SetCurrentVertex(null);\n\tprov.AddAttribute(\"Name\", employeeNode.employee.nome.ToString());\n\tprov.AddAttribute(\"Salary\", employeeNode.employee.salary.ToString());\n\tprov.AddAttribute(\"Job\", employeeNode.employee.job.ToString());\n\tprov.AddAttribute(\"Level\", employeeNode.employee.level.ToString());\n\tprov.AddAttribute(\"Adaptability\", employeeNode.employee.atributos.adaptabilidade.ToString());\n\tprov.AddAttribute(\"Auto Didact\", employeeNode.employee.atributos.autoDidata.ToString());\n\tprov.AddAttribute(\"Meticulous\", employeeNode.employee.atributos.detalhista.ToString());\n\tprov.AddAttribute(\"Negotiation\", employeeNode.employee.atributos.negociacao.ToString());\n\tprov.AddAttribute(\"Objectivity\", employeeNode.employee.atributos.objetividade.ToString());\n\tprov.AddAttribute(\"Organization\", employeeNode.employee.atributos.organizacao.ToString());\n\tprov.AddAttribute(\"Patience\", employeeNode.employee.atributos.paciencia.ToString());\n\tprov.AddAttribute(\"Logical Reasoning\", employeeNode.employee.atributos.raciocinioLogico.ToString());\n\tprov.AddAttribute(\"Human Relations\", employeeNode.employee.atributos.relacionamentoHumano.ToString());\n\t\n\tprov.NewAgentVertex(time.GetGameTime() + \":\" + time.GetTimeDayString(), \"Agent\", \"\");\n}",
"addConnection(connection){\r\n this.connections.push(connection);\r\n this.hasChildren = true;\r\n }",
"function createDocumentsAndActivities( itcb ) {\n async.eachSeries( ids, createSingle, onCreatedAll );\n\n function onCreatedAll( err ) {\n if( err ) {\n Y.log( `Problem while creating activities and documents: ${JSON.stringify( err )}`, 'warn', NAME );\n return itcb( err );\n }\n Y.log( `Created ${ids.length} activities and documents`, 'debug', NAME );\n itcb( null );\n }\n }",
"function initNetGraph(){\n // Graph label\n netGraph.setGraph(\"mPlane DEMO NET\");\n // Graph nodes\n _.each(netDef.networks , function(net , netName){\n var name = network.UNSPECIFIED_NET;\n netGraph.setNode(netName , net.description);\n if (net.subnet == network.UNSPECIFIED_NET){\n __subnetIndex[network.UNSPECIFIED_NET] = netName; //INDEXED\n __netNameIndex[netName] = network.UNSPECIFIED_NET;\n }\n else{\n __subnetIndex[ip.cidr(net.subnet)] = netName; //INDEXED\n __netNameIndex[netName] = ip.cidr(net.subnet);\n name = netName;\n }\n });\n info(\"Subnet nodes edges created\");\n // LEAFS edges!\n _.each(netDef.networks , function(net , netName){\n if (net.leafOf){\n netGraph.setEdge(netName, networkName(net.leafOf) , LEAF_GW);\n netGraph.setEdge( networkName(net.leafOf) , netName , LEAF_GW);\n }\n });\n info(\"Leaf nodes linked\");\n\n // Graph edges from gateways\n // Edges are identified using subnets\n _.each(netDef.gateways , function(gw , gwName){\n for (var i=0; i<gw.IPs.length ; i++){\n for (var j=0; j<gw.IPs.length;j++){\n if (i != j){\n // Subnet is the id of the node\n // We use the GW name as label of the edge for seamlessly retrive the connecting GW\n netGraph.setEdge(networkName(ip.cidr(gw.IPs[i])) , networkName(ip.cidr(gw.IPs[j])) , gwName );\n netGraph.setEdge( networkName(ip.cidr(gw.IPs[j])) , networkName(ip.cidr(gw.IPs[i])) ,gwName );\n }\n }\n }\n });\n info(\"Edges created\");\n info(\"Graph created\");\n info(\"...\"+netGraph.nodeCount()+\" networks\");\n info(\"...\"+netGraph.edgeCount()+\" links\");\n}",
"constructor() {\n // map module.id -> [outgoing connections]\n this.outEdges = {};\n\n // map module.id -> [incoming connections]\n this.inEdges = {};\n\n // map module.id -> module\n this.modules = {};\n\n this.allEdges = [];\n }",
"function fillListActivities(data) {\n if (data.length) {\n for (var i = 0; i < data.length; ++i) {\n var act = {};\n \n act.id = data[i].id;\n act.name = data[i].name;\n act.date = data[i].start_date;\n act.type = data[i].type;\n\n activities[i] = act;\n }\n }\n}",
"addPerson( args ) {\n let person = new NodePerson( this.idNodes, args );\n this.nodes.add( person );\n this.idNodes += 1;\n }",
"function extendConnections() {\n\n for (var iteration = 0; iteration < selection.connections; iteration++) {\n \n var nodesCopy = [];\n\tsummaryNodes.forEach(function (d){nodesCopy.push(d);});\n\n\tfor (var i = 0; i < selection.network.links.length; i++) { // for each link {\n\t\n\t\tvar subjectFound = findNode(selection.network.links[i].source.id, nodesCopy);\n\t\tvar objectFound = findNode(selection.network.links[i].target.id, nodesCopy);\n\n\t\tif ((subjectFound == -1 || objectFound == -1) && (!(subjectFound == -1 && objectFound == -1)) &&\t\t\t\t// only one concept is in graph (else already present)\n\t\t\t(selection.network.links[i].source.novel == true && selection.network.links[i].target.novel == true) ) { \t// arguments are novel\n\n\t\t\tfor (var j = 0; j < selection.network.links[i].predicate.length; j++) { \t// for each predicate of each link\n\t\t\n\t\t\t\tif (findUnconnectedPreds(selection.network.links[i].predicate[j].label) == -1 &&\t\t\t\t\t\t\t\t\t// predication is not excluded for domain \n\t\t\t\t\t\tfindRelevanceRule(selection.network.links[i].predicate[j].label, selection.network.links[i].source.semtype, // predication fits within a domain rule\n\t\t\t\t\t\t\t\tselection.network.links[i].target.semtype) != -1) {\n\t\t\t\t\n\t\t\t\t\tif (findNode(selection.network.links[i].source.id, summaryNodes) == -1) summaryNodes.push(selection.network.links[i].source);\n\t\t\t\t\tif (findNode(selection.network.links[i].target.id, summaryNodes) == -1) summaryNodes.push(selection.network.links[i].target);\n\n\t\t\t\t\tvar linkFound;\n\t\t\t\t\tif (summaryLinks.length > 0) linkFound = findLink(selection.network.links[i], summaryLinks);\n\t\t\t\t\telse linkFound = -1;\n\t\n\n\t\t\t\t\tif (linkFound != -1) { // link exists\n\n\t\t\t\t\t\tvar predicateFound = findPredicate(selection.network.links[i].predicate[j], summaryLinks[linkFound] );\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (predicateFound == -1 ) { // predicate doesn't exist\n\n\t\t\t\t\t\t\tsummaryLinks[linkFound].predicate.push(selection.network.links[i].predicate[j]);\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t} else { summaryLinks.push(selection.network.links[i]); }\n\t\t\t\t\t\n\t\t\t\t} // not in unconnectedPreds list\n\t\t\t\t\n\t\t\t} // for each predicate\n\t\t\t\n\t\t} // object or subject found\n\t\t\n\t} // for each link\n\t\n } // iterations\n}",
"async writeLinksOnNodeModules() {\n const links = await this.manyComponentsWriter._getAllLinks();\n const nodeModulesLinks = links.filterByPath(filePath => filePath.startsWith('node_modules'));\n await nodeModulesLinks.persistAllToCapsule(this.capsule);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
notify when new orders are made | function newOrder() {
db.collection("currentOrders").where("notify", "==", 1).onSnapshot((snapshot) => {
console.log("New order invoked!");
// console.log(snapshot.docChanges());
snapshot.docChanges().forEach(change => {
console.log("change: ",change.doc.data());
showNotification('top', 'right', `<b>New Order received!</b> <br> Customer Name: ${change.doc.data()['user_name']}
<br> Order ID: ${change.doc.id}`, 'info', 20000);
notified(change.doc);
});
});
} | [
"function notifySuccess() {\n successes++;\n if (successes >= orderItems.length) {\n console.log(\"order added for table \" + order.tableNum + \", party \" + party + \" with orderID \" + orderID);\n //all queries success. emit response.\n socket.emit(\"order_result\", {\n success: true,\n order_details: {\n orderID: orderID\n }\n });\n }\n }",
"triggerOrder(order) {\n if (!(order instanceof ExchangeOrder)) {\n throw 'Invalid order given'\n }\n\n // dont overwrite state closed order\n if (order.id in this.orders && ['done', 'canceled'].includes(this.orders[order.id].status)) {\n return\n }\n\n this.orders[order.id] = order\n }",
"async handleOrderItemCreatedEvent(data={}) {\n let {orderItem,trackId} = data,\n logger = Logger.create(\"handleOrderItemCreatedEvent\", trackId);\n\n logger.info(\"enter\", {orderItem});\n\n // @WARNING : We do not modify stock for orders items generated\n // from list subscriptions.\n if(orderItem.listSubscription) {return;}\n\n // Decrement product stock.\n logger.debug(\"decrement stock for product\", orderItem.product);\n\n this.collection.findOneAndUpdate({\n _id: Mongo.toObjectID(orderItem.product),\n deletedAt: {$type: \"null\"}\n }, {$inc: {stock: -(orderItem.quantity)}}, {returnOriginal: false})\n .then((result) => {\n let product = result.value;\n\n logger.debug(\"product stock updated\", product);\n\n // Emit to users\n Socket.shared.emit(\"product:updated\", {\n result: FindHandler.Model.format(product),\n updatedKeys: [\"stock\"]\n });\n });\n }",
"placeOrders() {\n for(let i = 0 ; i < this.orderCount ; ++i) {\n this.placeBuyOrder()\n this.placeSellOrder()\n }\n this.placedOrders = true;\n console.log('finished placing orders');\n }",
"function newOrder(){\n\t\tinquirer.prompt([{\n\t\t\tname: \"choice\",\n\t\t\ttype: \"confirm\",\n\t\t\tmessage: \"Would you like to place another order?\"\n\t\t}]).then(function(answer){\n\t\t\tif(answer.choice){\n\t\t\t\tuserRequest();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tconsole.log('Thank you for shopping at BAMazon!');\n\t\t\t\tconnection.end();\n\t\t\t}\n\t\t})\n\t}",
"function SaveOldOrder()\n{\n\tvar thisCtry = Accounts.Hash[Employee.work_country]\n\tvar Accts = thisCtry.OpenAccounts\n\n\tif (Rules.notify == \"Y\" || Rules.notifyee == \"Y\")\n\t{\n\t\tMailQueue = new Array()\n\t\tfor (var i=0;i<Accts.length;i++)\n\t\t{\n\t\t\tvar mlgth = MailQueue.length\n\t\t\tMailQueue[mlgth] = new Object()\n\t\t\tSaveAccountInfo(MailQueue[mlgth],i)\n\t\t}\n\t}\n}",
"function submitOrder() {\n if ($scope.order.orderId === null) {\n console.debug('Saving New Order', $scope.order);\n createOrder($scope.order);\n } else {\n updateOrder($scope.order);\n console.debug('Order updated with id ', $scope.order.orderId);\n }\n }",
"_order_accepted(event) {\n const order = event.detail;\n if (order.pcode == this.pcode)\n return;\n\n this.$.modal.modal_text = `Do you want to ${order.is_bid ? 'sell' : 'buy'} for ${order.price}?`\n this.$.modal.on_close_callback = (accepted) => {\n if (!accepted)\n return;\n\n this.$.trader_state.accept_order(order);\n };\n this.$.modal.show();\n }",
"function orderDetail(){\n\tsetTimeout(\n\t\tfunction(){\n\t\t\t$(function(){\n getOrderDetailToShow_wait_confirm();\n\t\t\t\tgetOrderDetailToShow_confirmed();\n });\n }, 1000);\n\t\trefreshAuto();\n}",
"confirmOrder() {\n\n // Trigger redirect in next render\n this.setState({confirmed: true});\n\n // create order model\n var orderModel = {\n cart: this.props.cart,\n offer: null\n }\n\n // Post order to API\n var confirmOrder = this.props.postOrder;\n confirmOrder(this.props.customer.telephone, orderModel);\n\n // Empty cart\n var replaceCart = this.props.replaceCart;\n var emptyCart = []\n replaceCart(emptyCart);\n }",
"async function sendOrderEmail({name, email, delivery, address, products}) {\n const emails = await getEmailsToNotify();\n\n const mailOptions = {\n from: `${siteName} <${functions.config().email.noreply}>`,\n to: `Undisclosed Recipients <${functions.config().email.noreply}>`,\n bcc: emails,\n subject: `New order from ${name}!`,\n }\n\n mailOptions.text = getOrderDetailString('text', name, email, delivery, address, products);\n mailOptions.html = getOrderDetailString('html', name, email, delivery, address, products);\n\n await mailTransport.sendMail(mailOptions)\n console.log('New order email sent.')\n}",
"storeOrder(order) {\n this.storeInSession(KEYS.ORDER, order);\n }",
"constructor() { \n \n OrderItemInformationEvent.initialize(this);\n }",
"function updateOrderLifeCycle(orderId, data) {\n logToFile('Going to update order life cycle');\n logToFile(data);\n\n // Check the order is relavent to us or not\n STATE.CURRENT[orderId].histories.push(data);\n logToFile('update order life cycle STATE.CURRENT');\n logToFile(STATE.CURRENT);\n switch (data.type) {\n case 'match':\n case 'received':\n case 'open':\n case 'change':\n break;\n case 'done':\n logToFile(`Done - orderId: ${orderId}`, true);\n\n // Delete it from the current and move it into history\n STATE.HISTORIES.push(STATE.CURRENT[orderId]);\n\n logToFile('Done - changing the trading to false', true);\n // Now a trading is finish\n STATE.TRADING = false;\n\n // Find the uuid corresponding to the order id and delete it\n // This is mark as the current task is done\n /*\n let clientId = _.findKey(STATE.UUID_ORDER_MAPPING, (t) => t === orderId);\n if (clientId) {\n logToFile(`Delete the client id off STATE.UUID_ORDER_MAPPING: ${clientId} > ${orderId}`, true);\n delete STATE.UUID_ORDER_MAPPING[clientId];\n }\n */\n\n // Delay the delete\n setTimeout(() => {\n delete STATE.CURRENT[orderId];\n }, 4000);\n break;\n default:\n // Do nothing\n }\n}",
"transaction() {\n let today = new Date();\n let day = today.getDate();\n let month = today.getMonth() + 1;\n let year = today.getFullYear();\n let time = today.getHours();\n let minutes = today.getMinutes();\n if (day < 10) day = '0' + day;\n if (month < 10) month = '0' + month;\n\n let orderType = 1;\n\n let todaysDate = year + '-' + month + '-' + day + ' ' + time + ':' + minutes + ':00';\n\n if (this.state.inBasket[0].dayRent == true) {\n orderType = 2;\n }\n\n orderService.makeOrder(\n this.state.activeC[0].id,\n orderType,\n todaysDate,\n this.state.inBasket[0].startDate,\n this.state.inBasket[0].endDate,\n this.discPrice,\n employeeID\n );\n\n for (let i = 0; i < this.state.inBasket.length; i++) {\n orderService.makeBikeOrder(this.state.activeC[0].id, todaysDate, this.state.inBasket[i].id);\n }\n\n if (equipmentBasket.length > 0) {\n for (let i = 0; i < equipmentBasket.length; i++) {\n orderService.makeEquipOrder(this.state.activeC[0].id, todaysDate, equipmentBasket[i].id);\n }\n }\n\n basket.length = 0;\n equipmentBasket.length = 0;\n this.totalPrice = 0;\n this.discPrice = 0;\n this.removeCustomer();\n this.updateBasket();\n this.handleClose();\n history.push('/overview/');\n }",
"updateCustomerList() {\r\n this.customers = this.calculateCustomerInfo(this.orders);\r\n }",
"function update_orders() {\n\t$.ajax({\n\t\tcontentType: 'application/json; charset=UTF-8',\n\t\tdata: null,\n\t\tdataType: 'json',\n\t\terror: function (jqXHR, textStatus, errorThrown) {\n\t\t\tfailure('Failed to get order data', jqXHR.statusText);\n\t\t},\n\t\tsuccess: function (data, textStatus, jqXHR) {\n\t\t\tif(data.result == 'ok') {\n\t\t\t\tfor(var i in data.orders) {\n\t\t\t\t\tvar order = data.orders[i];\n\n\t\t\t\t\tvar $row = $('.orders table tr[orderid=' + order.orderid + ']');\n\t\t\t\t\tif(!$row.length) {\n\t\t\t\t\t\tvar tr = document.createElement('TR');\n\t\t\t\t\t\ttr.setAttribute('orderid', order.orderid);\n\t\t\t\t\t\ttr.className = 'order';\n\n\t\t\t\t\t\tvar columns = ['orderid', 'amount', 'created', 'account', 'pending', 'credit', 'cancel', 'debit'];\n\n\t\t\t\t\t\tfor(var i in columns) {\n\t\t\t\t\t\t\tvar td = document.createElement('TD');\n\t\t\t\t\t\t\ttd.className = columns[i];\n\t\t\t\t\t\t\ttr.appendChild(td);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$row = $(tr);\n\t\t\t\t\t\t$('.orders table').append($row);\n\t\t\t\t\t}\n\t\t\t\t\tvar $row_td = $row.find('td');\n\t\t\t\t\t$row_td.eq(0).text(order.orderid);\n\n\t\t\t\t\tvar amount = '-';\n\t\t\t\t\tif(typeof(order.amount) != 'undefined' && order.amount != null) {\n\t\t\t\t\t\tamount = order.amount;\n\t\t\t\t\t}\n\t\t\t\t\tif(typeof(order.currency) != 'undefined' && order.currency != null) {\n\t\t\t\t\t\tamount = amount + ' ' + order.currency;\n\t\t\t\t\t}\n\t\t\t\t\t$row_td.eq(1).text(amount);\n\t\t\t\t\t$row_td.eq(2).text(order.created)?order.created:'';\n\n\t\t\t\t\t_build_notification_td($row_td.eq(3), order.account);\n\t\t\t\t\t_build_notification_td($row_td.eq(4), order.pending);\n\t\t\t\t\t_build_notification_td($row_td.eq(5), order.cancel);\n\t\t\t\t\t_build_notification_td($row_td.eq(6), order.credit);\n\t\t\t\t\t_build_notification_td($row_td.eq(7), order.debit);\n\t\t\t\t}\n\t\t\t\tif(data.orders.length) {\n\t\t\t\t\t$('.orders').removeClass('hidden');\n\n\t\t\t\t\t$('.orders table tr.order').click(function() {\n\t\t\t\t\t\t$(this).toggleClass('show-extra');\n\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\ttype: 'GET',\n\t\turl: '/php/example.php/orders',\n\t});\n}",
"function scheduleOrders() {\n console.log('Scheduling auto orders');\n schedule.scheduleJob({hour: 9, minute: 0}, () => {\n console.log('Generating orders');\n generateOrders(moment().format('dddd'));\n });\n}",
"trackPrices() {\n if(!this.placedOrders) {\n setTimeout(() => {\n this.trackPrices()\n }, 1000);\n return;\n }\n let orders = this.orderService.orders;\n let bestAsk = this.orderbook.bestAsk;\n let bestBid = this.orderbook.bestBid;\n for(const id in orders) {\n let order = orders[id];\n if(order.side == 'buy' && order.price < bestAsk) {\n console.log('buy order price', order.price, 'is below best ask:', bestAsk);\n let pnl = this.calculatePnl(order);\n this.orderService.fillOrder(id, pnl);\n this.updateBalances(pnl);\n this.placeBuyOrder();\n } else if(order.side == 'sell' && order.price > bestBid) {\n console.log('sell order price', order.price, 'is above best bid:', bestBid);\n let pnl = this.calculatePnl(order);\n this.orderService.fillOrder(id, pnl);\n this.updateBalances(pnl);\n this.placeSellOrder();\n }\n }\n setTimeout(() => {\n this.trackPrices()\n }, 1000);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renews subscriptions with the X32 (they expire every 10s). | function renewSubscriptions() {
udpPort.send({
address: '/batchsubscribe',
args: [
// First defines the local endpoint that the X32 will send this subscription data to.
{ type: 's', value: '/chMutes' },
{ type: 's', value: '/mix/on' },
{ type: 'i', value: 0 },
{ type: 'i', value: 63 },
{ type: 'i', value: 10 }
]
});
udpPort.send({
address: '/batchsubscribe',
args: [
// First defines the local endpoint that the X32 will send this subscription data to.
{ type: 's', value: '/chFaders' },
{ type: 's', value: '/mix/fader' },
{ type: 'i', value: 0 },
{ type: 'i', value: 63 },
{ type: 'i', value: 10 }
]
});
} | [
"refreshSubscriptions() {\n // just schedule if does not have a previous timer scheduled and if\n // the consumer is ready\n if ((!this.isWaitingForRefreshSubscriptions) && (this.isReady)) {\n this.isWaitingForRefreshSubscriptions = true;\n\n const subscriptionProcedure = (retries = 0) => {\n logger.debug('Refreshing subscriptions');\n // According to the node-rdkafka documentation we need to call\n // the unsubscribe method before call the subscribe with new topics\n try {\n this.consumer.unsubscribe();\n // concatenates the topics explicits with the regular expressions\n const topics = Array.prototype.concat(Object.keys(this.topicMap),\n this.topicRegExpArray.map((entry) => entry.regExp));\n logger.debug(`subscribing in the following topics (${topics.length}): ${JSON.stringify(topics)}`);\n if (topics.length > 0) {\n this.consumer.subscribe(topics);\n }\n this.isWaitingForRefreshSubscriptions = false;\n } catch (error) {\n logger.warn(`Error while subscribing: ${error}`);\n // schedules the next retry\n const timeout = this.backoffWithRandomDelta(retries);\n setTimeout(\n subscriptionProcedure,\n timeout,\n (retries + 1),\n );\n }\n };\n\n // run immediately!\n subscriptionProcedure();\n }\n }",
"function recreateStripeSubscription(req, res, next) {\n stripe.customers.update(\n req.user.subscription.customer,\n {\n card: req.body.stripeToken,\n },\n function (err) {\n if (err) return next(err);\n\n stripe.customers.createSubscription(\n req.user.subscription.customer,\n {\n plan: req.user.subscription.plan.id,\n quantity: req.user.subscription.quantity || 1,\n },\n function (err, subscription) {\n if (err || !subscription) {\n return next(err || new Error(\"No subscription\"));\n }\n\n User.set(req.user.uid, { subscription: subscription }, next);\n }\n );\n }\n );\n}",
"resetRenewalTimer(userSession) {\n if (this.renewalTimer) {\n window.clearTimeout(this.renewalTimer);\n this.renewalTimer = null;\n }\n\n if (userSession && userSession.renewAfter) {\n let timeout = Math.max(0, new Date(userSession.renewAfter) - new Date());\n\n // if the timeout is in the future, apply up to a few minutes to it\n // randomly. This avoids multiple tabs all trying to renew at the\n // same time.\n if (timeout > 0) {\n timeout += Math.random() * 5 * 60 * 1000;\n }\n\n this.renewalTimer = window.setTimeout(() => {\n this.renewalTimer = null;\n this.renew({ userSession });\n }, timeout);\n }\n }",
"async function subscribe () {\n for (let ex of tradeExchange) {\n let users = await User.findAllInExchange(ex.name);\n for (let user of users) {\n let userKey = `${user.exchange}:${user.address}:${user.apiKey}`;\n if (!(userKey in subscribedUsers)) {\n ex.subscribe(crypt.decrypt(user.apiKey), crypt.decrypt(user.apiSecret), user.address, onTrade);\n subscribedUsers[userKey] = true;\n }\n }\n }\n setTimeout(subscribe, subscriptionDelay);\n}",
"disposeSubscriptions() {\n const regex = new RegExp(this._subscribePrefixName);\n\n for (let key in this) {\n if (regex.test(key) && this[key] && typeof this[key] === 'object' && this[key].hasOwnProperty('dispose')) this[key].dispose();\n }\n }",
"async startSubscriptions() {\n // Subscribe to the games/ID doc\n this.subscribeDoc('games', this.props.gameId, (gameDoc) => this.setState({ game: gameDoc }));\n const gameDoc = await this.gameIsUpdated(true);\n\n // Subscribe to all the players/ID docs for this game\n gameDoc.players.forEach((gamePlayer, index) => {\n this.subscribeDoc('players', gamePlayer.id, (playerDoc) => {\n const newPlayers = [ ...this.state.players ];\n newPlayers[index] = playerDoc;\n this.setState({\n players: newPlayers\n });\n });\n });\n }",
"setupTokenReconnectTimer(){\n log.debug('[PageSharedDB] setting up timer for token refresh')\n let reconnectInMilliseconds = (this.expires_at * 1000) - Date.now() - 5000\n clearTimeout(this.tokenReconnectTimer)\n\n this.tokenReconnectTimer = setTimeout(() => {\n this.tokenReconnect()\n }, reconnectInMilliseconds)\n }",
"function dailyTokenRefresh(force){\n\n if(rollOver == true && force != true){ // If rollover has happened but we are within the timing window, do nothing.\n return;\n }\n\n // coin refresh\n let gameReader = getReader(config.gameFile);\n var keys = Object.keys(gameReader);\n for(var i = 10; i < Object.keys(gameReader).length; i++){\n if (gameReader[keys[i]] < 10){\n var num = gameReader[keys[i]];\n num = 10;\n gameReader[keys[i]] = num;\n }\n }\n // Scratch refresh\n let scratchReader = getReader(config.scratchFile);\n keys = Object.keys(scratchReader);\n for(i = 0; i < Object.keys(scratchReader).length; i++){\n if(scratchReader[keys[i]].playedToday == true){\n scratchReader[keys[i]].playedToday = false;\n }\n }\n // Write files and send reset.\n writeFile(config.gameFile, gameReader);\n writeFile(config.scratchFile, scratchReader);\n client.channels.find(\"name\", config.announceChannel).send(strings.dailyReset);\n rollOver = true;\n}",
"revToken (topic) {\n if (!topic || !topic.endsWith('token')) return // donot care this topic\n clearTimeout(this.waitTimer)\n this.counter = 0\n clearTimeout(this.timer)\n this.timer = setTimeout(() => { // refresh every 2 hours\n this.refreshToken()\n }, this.refreshTokenTime)\n }",
"async function _validate_subscription_count( plan_id, customer_id, subscription_id, test = false ) {\n if ( test ) {\n redis = require( 'redis-mock' );\n }\n\n const options = {\n host: process.env.REDIS_HOST,\n port: process.env.REDIS_PORT\n };\n\n const client = redis.createClient( options );\n\n // listen for errors\n client.on( 'error', ( err ) => {\n client.quit();\n throw new VError(err);\n } );\n\n let increment = true;\n client.hget( customer_id, subscription_id, ( err, reply ) => {\n if ( err ) {\n client.quit();\n throw new VError(err);\n }\n\n let count_to_set = '0';\n\n // means customer has changed to weekly plan on this renewal...\n if ( reply < 5 && ( plan_id == 'deluxe-box-weekly' || plan_id == 'premium-box-weekly' || plan_id == 'style-up-weekly' || plan_id == 'luxe-weekly' || plan_id == 'premium-weekly' ) ) {\n /*\n * map the current month to the last week in the monthly period and return true. This way the count\n * will be incremented and the appropriate action taken\n */\n if ( reply == 1 ) {\n count_to_set = 5;\n }\n else if ( reply == 2 ) {\n count_to_set = 9;\n }\n else {\n count_to_set = 13;\n }\n\n client.hset( customer_id, subscription_id, count_to_set );\n increment = true;\n\n } // ... and vice versa\n else if ( reply > 4 && ( plan_id == 'deluxe-box' || plan_id == 'premium-box' || plan_id == 'style-up' || plan_id == 'luxe' || plan_id == 'premium') ) {\n /*\n * maps weekly ranges to monthly counts. This assumes manual handling of the switch is correct (seeing out\n * weekly renewals for the rest of the current month and scheduling plan change on a renewal date the same\n * as the plan creation date - (ugh))\n */\n\n if ( reply > 5 && reply < 10 ) {\n count_to_set = 2;\n }\n else if ( reply > 9 && reply < 14 ) {\n count_to_set = 3;\n }\n else {\n count_to_set = 1;\n }\n\n return client.hset(customer_id, subscription_id, count_to_set);\n increment = true;\n }\n } );\n\n client.quit();\n return increment;\n}",
"_registerUpdates() {\n const update = this.updateCachedBalances.bind(this);\n this.accountTracker.store.subscribe(update);\n }",
"renewSession() {\n // implement in concrete authenticator\n }",
"function expired() {\n\n log.functionEntryPoint()\n \n log.fine('oldConfig.isTrial: ' + oldConfig.isTrial + ' (' + typeof oldConfig.isTrial + ')')\n\n // Ensure the user can only use the trial once\n if (oldConfig.isTrial) {\n log.fine('Flag trial as finished')\n self.properties.setProperty(PROPERTY_.TRIAL_FINISHED, 'true')\n }\n \n return updateProperties(false, SUBS_STATE.EXPIRED, TIMER_NOT_STARTED)\n \n }",
"function extendTTL(cond, by) {\n\t\t\t\tredis = openRedis();\n\t\t\t\tredis.TTL(\"session:\" + req.sess, function(err, reply) {\n\t\t\t\t\tif(!isNaN(parseInt(reply)) && parseInt(reply) < opts.expiry) {\n\t\t\t\t\t\tredis.expire(\"session:\" + req.sess, opts.expireExtend, function(err, reply) {\n\t\t\t\t\t\t\tredis.end();\n\t\t\t\t\t\t\tdebug(\"session:\" + req.sess + \" was \" + Number(reply)===0 ? \"not \" : \"\" +\n\t\t\t\t\t\t\t\t\"allowed to exist for another \" + opts.expireExtend + \" seconds.\");\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}",
"async renew({ userSession }) {\n try {\n if (this.canSignInUsing('auth0')) {\n await auth0Renew({ userSession, authController: this });\n }\n } catch (err) {\n // instance where a new scope was added and is now required in order to be logged in\n if (err.error === 'consent_required') {\n this.setUserSession(null);\n }\n\n // usually this is just \"user interaction required\" or the like, but just\n // in case the user wants to peek, put it in the console\n /* eslint-disable no-console */\n console.error('Could not renew login:', err);\n }\n }",
"function renewToken(req, res) {\n sec.authenticateApp(req.get('clientId')).then((result) => {\n return sec.renewToken(req.body.username, req.body.refreshToken);\n }).then((newAccessToken)=>{\n util.log('Successfully returning new access token to user');\n return res.status(constants.ACCEPTED).json({ 'accessToken' : newAccessToken });\n }).catch((err) => {\n util.log(`Error in renewToken method in user middleware.\\nError Message: ${err.message}`);\n return res.status(err.code).json({message : err.message });\n });\n}",
"async all() {\n const subscriptions = await this.db.subscriptions.toArray();\n return Promise.all(\n subscriptions.map(async (s) => ({\n ...s,\n new: await this.db.notifications.where({ subscriptionId: s.id, new: 1 }).count(),\n }))\n );\n }",
"clearSubscriptions() {\n this.events.clear();\n }",
"initTokens() {\n\n\t\t\twhile (this.tokens.length > 0 && Date.now() > this.tokens[0].expires) this.tokens.shift();\n\n\t\t\tif (this.tokens.length > 0) {\n\n\t\t\t\tTimers.token.start(this.tokens[0].expires);\n\n\t\t\t} else {\n\n\t\t\t\tTimers.token.stop();\n\n\t\t\t}\n\n\t\t\t//Sort by expriation.\n\t\t\tthis.tokens.sort((a, b) => a.expires - b.expires);\n\n\t\t\tStorage.saveTokens(this.tokens);\n\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a string, if the string "del" appears starting at index 1, return a string where that "del" has been deleted. Otherwise, return the string unchanged. | function delDel(str) {
if ((str.length >= 4) && (str.substring(1, 4).localeCompare("del") == 0)) {
return str.slice(0, 1) + str.slice(4);
} else {
return str;
}
} | [
"function remove(string, number) {\n // A place to store the number of times we're going to remove an !\n let timesWeRemove = number;\n\n // A Place to store our new string.\n let newString = \"\";\n\n // Iterate over string, and every time we find an ! and the number of !'s we're going to remove isn't 0, remove an !\n for (let i = 0; i < string.length; i++) {\n currentLetter = string[i];\n if (currentLetter !== \"!\") {\n newString += currentLetter;\n } else if (currentLetter === \"!\" && timesWeRemove !== 0) {\n timesWeRemove--;\n } else if (\n currentLetter === \"!\" ||\n (currentLetter !== \"!\" && timesWeRemove === 0)\n ) {\n newString += currentLetter;\n }\n }\n\n // Return string\n\n return newString;\n}",
"function keepFirst(str) {\n return str.slice(0, 2);\n}",
"function splice(str, token, replacement) {\r\n var i = str.indexOf(token);\r\n return str.substr(0, i) + replacement\r\n + str.substr(i + token.length);\r\n}",
"function indexoff(){\n\tvar isi = \"saya beajar di rumah\";\n\tconsole.log(isi.indexOf(\"beajar\"));\n}",
"function removeChar(str, letter) {\n //if indexOf char is greater than 0 it still has that letter in the string so..\n if(str.indexOf(letter) > 0) {\n //recursively call the function with updated args\n return removeChar(str.replace(letter, \"\"), letter);\n } else \n //otherwise, stop recursion and return the string\n return str;\n}",
"function find_last(s, sub) /* (s : string, sub : string) -> maybe<sslice> */ {\n var i = ((s).lastIndexOf(sub));\n if ((i<0)) {\n return Nothing;\n }\n else {\n return Just(Sslice(s, i, sub.length));\n }\n}",
"function ends_with(s, post) /* (s : string, post : string) -> maybe<sslice> */ {\n if (xends_with(s, post)) {\n return Just(Sslice(s, 0, (((s.length) - (post.length))|0)));\n }\n else {\n return Nothing;\n }\n}",
"function removeWord () {\n firstWord.remove();\n}",
"function cutFirst(string){\n return string.substr(2);\n }",
"function isPrefix(sub,str) {\n return str.lastIndexOf(sub,0)===0;\n}",
"removeWord(word) {\n if(typeof word !== 'string' || word === '') {\n throw(`Expected parameter string, received ${typeof word}`);\n }\n\n const { prefixFound, prefixNode } = checkPrefix(trie, word);\n\n if(prefixFound) {\n delete prefixNode[config.END_WORD];\n }\n\n return this;\n }",
"function trim_left_1(s, sub) /* (s : string, sub : string) -> string */ { tailcall: while(1)\n{\n if (empty_ques__1(sub)) {\n return s;\n }\n else {\n var _x34 = starts_with(s, sub);\n if (_x34 != null) {\n {\n // tail call\n var _x35 = (string_3(_x34.value));\n s = _x35;\n continue tailcall;\n }\n }\n else {\n return s;\n }\n }\n}}",
"function getFront(mainStr,searchStr)\r\n{\r\n var foundOffset=mainStr.indexOf(searchStr);\r\n if(foundOffset==-1)\r\n return null;\r\n return mainStr.substring(0,foundOffset);\r\n}",
"function last(){\n\tvar isi = \"saya beajar di rumah beajar\";\n\tconsole.log(isi.lastIndexOf(\"beajar\",5)); //nilai angka berfungsi sebagai startnya di index\n}",
"function getAutoComplete(sub,stringlist) {\n if (stringlist.length===0) { return \"-1\"; }\n var res=stringlist[0].substr(sub.length);\n for (var i=1;i<stringlist.length;++i) {\n if (res===\"\") {break;}\n var tail=stringlist[i].substr(sub.length);\n var len=res.length>tail.length ? tail.length : res.length;\n for (var j=0; j<len; ++j) {\n if (res.charAt(j)!==tail.charAt(j)) {\n res=res.substr(0,j);\n break;\n }\n }\n }\n return res;\n}",
"function removewords(text, words){\n if(isUndefined(words)){words = wordstoignore;}\n text = text.toLowerCase().split(\" \");\n for(var i=text.length-1; i>-1; i--){\n if(words.indexOf(text[i]) > -1){\n removeindex(text, i);\n }\n }\n text = removemultiples(text.join(\" \"), \" \", \" \");\n return text;\n}",
"function checkIfJavaAppears({ string }) {\n if(string.substr(0, 4) === \"Java\") {\n return string.slice(4,);\n }\n return string;\n}",
"function getWordAt(string, index) {\n const left = string.substr(0, index).split(' ');\n const right = string.substr(index).split(' ');\n return left[left.length - 1] + right[0];\n}",
"function spliceChars($, $el, startIndex, deleteCount, ...insertions) {\n let endIndex = startIndex + deleteCount;\n let textNodes = collectTextNodes($, $el);\n\n for (let nodeIdx = 0, charIdx = 0; nodeIdx < textNodes.length && charIdx <= endIndex; nodeIdx++) {\n let $node = textNodes[nodeIdx];\n let nodeText = $node.text();\n if (charIdx <= endIndex && startIndex < charIdx + nodeText.length) {\n // copy any text following the end of the deletion range\n let trailingText = nodeText.slice(startIndex - charIdx + deleteCount);\n if (trailingText) {\n // insert the trailing text\n $node.after(trailingText);\n }\n\n // insert insertions in front of the trailingText\n while (insertions.length) {\n $node.after(insertions.pop());\n }\n\n // copy any text preceding the beginning of the deletion range\n let leadingText = nodeText.slice(0, startIndex - charIdx);\n if (leadingText && startIndex - charIdx > 0) {\n // insert the leading range\n $node.after(leadingText);\n }\n\n // remove the original text node\n let $parent = $node.parent();\n $node.remove();\n // remove empty parent elements (if any)\n while (!$parent.contents().length && !$parent.is($el)) {\n let $grandparent = $parent.parent();\n $parent.remove();\n $parent = $grandparent;\n }\n }\n charIdx += nodeText.length;\n }\n return $el;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Control cursor position for phone field | function setPhoneCursor(field, event){
let cursorPosition = field.selectionStart;
let charAfter = $(field).val().substr(cursorPosition, 1);
// If cursor is directly before a non-number...
if(charAfter.match(/[^0-9]/)){
// If key pressed is left arrow, move cursor directly in front of number directly before non-number
if(event.which == 37 && cursorPosition > 1){
let cursorAdjust = charAfter == ' ' ? 2 : 1;
setCursorPosition(field, cursorPosition - cursorAdjust);
}
// Otherwise, move cursor directly in front of number directly after non-number
else{
let cursorAdjust = charAfter == ')' ? 2 : 1;
setCursorPosition(field, cursorPosition + cursorAdjust);
}
}
} | [
"function setCursorPosition(field, position){\n \n // If not focused, set focus on field\n \n if(!$(field).is(':focus')){\n \n $(field).focus();\n \n }\n \n // Set cursor position for field\n \n field.selectionStart = position;\n field.selectionEnd = position;\n}",
"_setDefault(){\n this.defaultCursor = \"default\";\n // this.hOverCursor = \"pointer\";\n }",
"function setCaretPosition(position) {\n\tdocument.getElementById(\"content-editor\").setSelectionRange(position, position);\n\tdocument.getElementById(\"content-editor\").focus();\n}",
"function SetKeyboardFocusHere(offset = 0) {\r\n bind.SetKeyboardFocusHere(offset);\r\n }",
"function moveCursor(ix, iy) {\n var cursor = editor.cursor;\n if(ix < 0 && iy < 0) {\n editor.ix = ix;\n editor.iy = iy;\n editor.focus = null;\n cursor.setAttribute('visibility', 'hidden');\n return;\n }\n\n /*\n if(ix < 0) {\n ix = nrow - 1;\n iy--;\n }\n else if(ix >= nrow) {\n ix = 0;\n iy++;\n }\n\n if(iy < 0 || iy >= nrow)\n return;\n */\n if(0 <= ix && ix < nrow && 0 <= iy && iy < nrow) {\n cursor.setAttribute('visibility', 'visible');\n cursor.setAttribute('x', editor.margin[3] + ix*editor.w + 2);\n cursor.setAttribute('y', editor.margin[0] + iy*editor.w + 2);\n\n p = editor.ban[iy*nrow + ix];\n editor.ix = ix;\n editor.iy = iy;\n editor.focus = {type: 'ban', ix: ix, iy: iy, p: p};\n }\n}",
"function add_character_move_cursor(input_string) {\r\n\ttextarea_element.setRangeText(input_string, textarea_element.selectionStart, textarea_element.selectionEnd, \"end\");\r\n\t//textarea_element.focus();\r\n\tscroll_to_cursor();\r\n\tupdate_printable_table();\r\n}",
"function doGetCaretPosition(oField){var iCaretPos=0;if(document.selection){oField.focus();var oSel=document.selection.createRange();oSel.moveStart('character',-oField.value.length);iCaretPos=oSel.text.length;}else if(oField.selectionStart||oField.selectionStart=='0'){iCaretPos=oField.selectionStart;}return iCaretPos;}",
"focusControl() {\n if (!this.showFocus || !this.focusActive) return;\n [].forEach.call(this.focusList, (item, index) => {\n item[`on${this.focusEvent}`] = () => {\n //Prevent repeated slide switch\n if (this.defaultIndex === index) return;\n //Fix animation from clone slide to previous slides\n if (this.defaultIndex === this.wrapperList.length - 1) {\n utils.css(this.wrapper, \"left\", -this.width * 0);\n }\n this.defaultIndex = index;\n this.playSlide();\n }\n })\n }",
"showSystemCursor() {\n if (this._cursorTracker.set_keep_focus_while_hidden)\n this._cursorTracker.set_keep_focus_while_hidden(false);\n this._cursorTracker.set_pointer_visible(true);\n }",
"function resetCursorPos(element) {\n element.selectionStart = 0;\n element.selectionEnd = 0;\n }",
"updateCaret() {\n\t\tthis.caret = this.textarea.selectionStart;\n\t}",
"__refreshCursor() {\n var currentCursor = this.getStyle(\"cursor\");\n this.setStyle(\"cursor\", null, true);\n this.setStyle(\"cursor\", currentCursor, true);\n }",
"focusInput(){\n this.amountInput.focus();\n }",
"_handleTopRowClick(){\n this.amountInput.focus();\n }",
"function move_cursor_right_to_100_and_back() \n{\n\ttry{\n\t\tvar sel = E._frame.selection;\n\t\tvar r = sel.createRange();\n\t\tr.moveEnd(\"character\", -100);\n\t\tr.moveStart(\"character\", -100);\n\t\tr.collapse(false);\n\t\tr.select();\n\t} catch(e){}\n}",
"function SetControlWinPosition(position : Vector2){\n\t_controlWinPosition = position;\n}//SetControlWinPosition",
"function storeCaret (txtarea) { \r\n if (txtarea.createTextRange) { \r\n txtarea.caretPos = document.selection.createRange().duplicate();\r\n } \r\n }",
"function updateCursorPosition(left, top) {\n cursor.style.left = `${left}px `;\n cursor.style.top = `${top}px`;\n cursor.scrollIntoView({\n behavior: \"smooth\",\n block: \"center\",\n inline: \"center\",\n });\n }",
"function changeCursor(cursor) {\n document.body.style.cursor = cursor; \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
reading what we have in list.json | function readListFS(){
console.log("welcome to listFS line 54 in auth.js");
//userName = getLoggedIn(cookies);
var data = fs.readFileSync('db/'+ userName +'/lists/list.json', "utf8"); //it's more fast for write and will return null
lists = JSON.parse(data); //an Object
console.log("line 54 auth "+ ++i);
} | [
"function readStartingData(){\n readUser = JSON.parse(fs.readFileSync('data/user.json'));\n listDoc = JSON.parse(fs.readFileSync('data/documents.json'));\n}",
"function list() {\n\tfs.readFile(\n\t\tpath.resolve(__dirname, \"../\", \"main.json\"),\n\t\t\"utf8\",\n\t\tfunction readFileCallback(err, data) {\n\t\t\tif (err) {\n\t\t\t\tconsole.log(err);\n\t\t\t} else {\n\t\t\t\tconsole.log(\n\t\t\t\t\t\"Current File \" + chalk.keyword(\"green\")(JSON.parse(data).currentFile)\n\t\t\t\t);\n\t\t\t\tfs.readdir(path.resolve(__dirname, \"../\", \"asciiArt\"), function (err, items) {\n\t\t\t\t\tconsole.log(\"Files: \");\n\t\t\t\t\titems.forEach(item => {\n\t\t\t\t\t\tconsole.log(\"Name: \" + chalk.keyword(\"green\")(item.replace(\".txt\", \"\")) + \" File: \" + chalk.keyword(\"green\")(item));\n\t\t\t\t\t})\n\n\t\t\t\t});\n\n\t\t\t}\n\t\t}\n\t);\n\n\n}",
"list() {\n const usersData = fs.readFileSync(`${__dirname}/users.json`, 'utf8');\n return JSON.parse(usersData);\n }",
"getMentorList() {\n const fileContent = fs.readFileSync(this.mentorsList).toString();\n let allMentors = JSON.parse(fileContent);\n return allMentors;\n }",
"function readProiectJson() \n{\n return JSON.parse(fs.readFileSync(\"proiect.json\"))[\"DetaliiContact\"];\n}",
"function readSecondJson() \n{\n return JSON.parse(fs.readFileSync(\"second.json\"))[\"DetaliiComenzi\"];\n}",
"function loadBatches(){\n let batch_data = fs.readFileSync('./batches.txt');\n batches = JSON.parse(batch_data);\n //console.log(batches);\n}",
"function getList(listKey) {\n var json = localStorage[getStorageKey(listKey)];\n var mruObject = json ? JSON.parse(json) : null;\n\n // Return list or new empty array\n return mruObject ? mruObject.list : [];\n }",
"function importList (obj) {\n let data = obj.dishes;\n let done = 0;\n $('#label_file_input').text(done + \" / \" + data.length);\n data.forEach(function (item) {\n let title = item.name + \" #\" + item.category.toLowerCase();\n let obj = {\n title: title,\n ingredients: item.ingredients.join('\\n'),\n description: \"\"\n };\n console.log(obj);\n // send to api\n $.post(\"/recipes/add\", obj, () => {\n done++;\n $('#label_file_input').text(done + \" / \" + data.length);\n if (done == data.length) {\n location.reload();\n }\n });\n });\n}",
"function readLoginJson() \n{\n return JSON.parse(fs.readFileSync(\"login.json\"))[\"DateLogin\"];\n}",
"function tlds() {\n // reading as file will make sure that we read new file upon package renewal\n try {\n return JSON.parse(fs.readFileSync(json_path,'utf8'))\n }catch(err) {}\n return false\n}",
"static loadRoles() {\n let roleList = [];\n let dataFile = fs.readFileSync('./data/roles.json', 'utf8');\n if (dataFile === '') return roleList;\n\n let roleData = JSON.parse(dataFile);\n\n roleData.forEach((element) => {\n roleList.push(\n new Role(\n element.roleID,\n element.title,\n element.description,\n element.image,\n element.color,\n element.emote\n )\n );\n });\n\n return roleList;\n }",
"function readAll(startPath,filter){\n let jsonContent, contents;\n\n if (!fs.existsSync(startPath)){\n console.log(\"no dir \",startPath);\n return;\n }\n\n var files=fs.readdirSync(startPath);\n for(var i=0;i<files.length;i++){\n var filename=path.join(startPath,files[i]);\n var stat = fs.lstatSync(filename);\n if (stat.isDirectory()){\n readAll(filename,filter); //recurse\n }\n else if (filename.indexOf(filter)>=0) {\n contents = fs.readFileSync(filename);\n // Define to JSON type\n jsonContent = JSON.parse(contents);\n studentArray.push(sanitizeJSON(jsonContent));\n };\n };\n}",
"function loadJSON(file) {\n return JSON.parse(FS.readFileSync(file, \"utf8\"));\n}",
"function handleFile(err, data){\n if(err){\n console.log(err);\n }\n\n obj = JSON.parse(data);\n console.log(\"JSON FILE: \"+ obj.main.temp);\n }",
"function loadInentory() {\n let invFile = fs.readFileSync('inventory.json', 'utf8');\n\n return JSON.parse(invFile);\n}",
"function readConfig() {\n fetch(\"/config/modules.json\")\n .then(response => response.json())\n .then(data => (config = data))\n .then(printModules);\n}",
"function LoadJson(){}",
"function loadBundlesFromFile(listFile) {\n function handleError(err) {\n $log.info([\n \"No external bundles loaded;\",\n \"could not load bundle listing in\",\n listFile,\n \"due to error\",\n err.status,\n err.statusText\n ].join(' '));\n return loadBundlesFromArray([]);\n }\n\n return getJSON(listFile)\n .then(loadBundlesFromArray, handleError);\n }",
"readObjectList(names, times, format) {\n if (!isFunction(format)) {\n format = defaultFormatter;\n }\n\n const input = this.getNextLine().split(\" \").map(i => i.trim()).filter(i => i !== '');\n\n if (Array.isArray(names) && !isNaN(times)) {\n let unique = [...new Set(names)];\n if (names.length !== unique.length) {\n throw new Error(\"All names MUST be unique.\");\n }\n if (names.length * times !== input.length) {\n throw new Error(`Input/Names length mismatch. Expected ${names.length} items but got ${input.length}.`);\n }\n const ret = [];\n let count = 0;\n for(let i = 0; i < times; i++) {\n const object = {};\n for (let name of names) {\n object[name] = input[count++];\n }\n ret.push(format(object));\n }\n return ret;\n } else {\n throw new Error('names must be an array and times must be a number');\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
chanllenge 4 3 essentials modules loadModule : add a module to the modules array Param index: where the module is in the availableModules array | function loadModule(index) {
//add in the challenge #8
if(!availableModules[index].essential){
availableModules[index].essential = true;//change essential property to true
}
ship.modules.push(availableModules[index]);
} | [
"function findLifeSupportModule(){\n \n for(var i = 0; i < availableModules.length; i++){\n if(availableModules[i].name == \"life-support\") {\n availableModules[i].enabled = true; //enable the module first\n loadModule(i); //load module into modules array\n }\n }\n}",
"function loaded() {\n var m = null,\n pending = [];\n\n for (m in modules) {\n if (modules.hasOwnProperty(m) && modules[m].name === undefined) {\n pending.push(m);\n }\n }\n\n if (pending.length === 0) {\n console.log('core::loaded,', 'all modules loaded');\n link();\n }\n }",
"function loadModule (moduleName, app, pool) {\n var fileName = __dirname + '/modules/' + moduleName;\n\n console.log('Loading module: [%s]', fileName);\n require(fileName)(app, pool);\n}",
"registerModules( modules ) {\n modules.forEach( function( module ) {\n if ( !module instanceof baseModule ) {\n console.log( 'Error trying to attach module to tatty-screen', module.name );\n return;\n }\n\n this.modules.push( module );\n\n if ( module.init ) {\n module.init.call( this, module );\n }\n\n var expose = module.expose( module );\n\n for ( let key in expose ) {\n if ( !this[ key ] && expose.hasOwnProperty( key ) ) {\n this[ key ] = expose[ key ];\n }\n }\n }, this );\n }",
"function addNewModule() {\r\n\r\n // Prompt user for the new module name\r\n //\r\n var modname = prompt(\"Name of the new module\", \"Module\");\r\n\r\n // if the user pressed cancel, just return\r\n //\r\n if (!modname)\r\n return;\r\n\r\n if (isExistingModuleOrLibName(modname) || isKeyword(modname)) {\r\n alert(\"Name \" + name + \" already exists!\");\r\n return;\r\n }\r\n\r\n // TODO: Check duplicate module/lib/grid/func name\r\n //\r\n\r\n // Create a new module and init it. Make it the current module\r\n //\r\n initCurModule(modname); // init module\r\n\r\n initMainFunc(DefMainFuncName); // add main function and init it\r\n\r\n initCurStep(); // add and init a step\r\n\r\n changeModule(CurProgObj.curModNum);\r\n}",
"function buildModules() {\n // loop through modules\n for (var i = 0, l = modules.length; i < l; i++) {\n var options = modules[i].options;\n // process styles\n var styleData;\n // loop through options\n for (var j = 0, m = options.length; j < m; j++) {\n if (options[j].isEnabled && options[j].head && options[j].head.css && (styleData = options[j].head.css) != null) {\n // loop through lines\n for (var k = 0, n = styleData.length; k < n; k++) {\n styles += '\\n ' + styleData[k];\n }\n styles += '\\n';\n }\n }\n\n // process head scripts\n var scriptData,\n fields = {};\n // loop through options\n for (var j = 0, m = options.length; j < m; j++) {\n if (options[j].isEnabled && options[j].head && options[j].head.js && (scriptData = options[j].head.js)) {\n // loop through lines\n for (var k = 0, n = scriptData.length; k < n; k++) {\n headScripts += '\\n ' + scriptData[k];\n }\n headScripts += '\\n';\n }\n if (options[j].fields && options[j].fields.length > 0) {\n // loop through fields\n for (var k = 0, n = options[j].fields.length; k < n; k++) {\n fields[options[j].fields[k].name] = options[j].fields[k].val;\n }\n }\n }\n _min.push(JSON.stringify(fields));\n\n // process body scripts\n var scriptData;\n // loop through options\n for (var j = 0, m = options.length; j < m; j++) {\n if (options[j].isEnabled && options[j].load && (scriptData = options[j].load.js)) {\n // loop through lines\n for (var k = 0, n = scriptData.length; k < n; k++) {\n bodyScripts += '\\n ' + scriptData[k];\n }\n bodyScripts += '\\n';\n }\n }\n\n // populate variables\n bodyScripts = bodyScripts.replace(/_min\\./g, '_min[' + i + '].');\n headScripts = headScripts.replace(/_min\\./g, '_min[' + i + '].');\n while (styles.indexOf('_min.') != -1) {\n styles = styles.replace(styles.substring(styles.indexOf('_min.'), styles.indexOf(' ', styles.indexOf('_min.'))), JSON.parse(_min[i])[styles.substring(styles.indexOf('_min.') + 5, styles.indexOf(' ', styles.indexOf('_min.')))]);\n }\n }\n headScripts = '\\n var _min = [' + _min + '];' + headScripts;\n}",
"function fetchModule(modulePath, text, modules, hasModules) {\n modules = modules || [];\n hasModules = hasModules || Object.create(null);\n // Fetch the requirements.\n var requires = fetchRequire(text);\n for (var i = 0; i < requires.length; i++) {\n var file = fs.readFileSync(path.join(aceHighlightDir, requires[i]));\n fetchModule(requires[i], file, modules, hasModules);\n }\n // Store the current module.\n if (hasModules[modulePath] === undefined) {\n // This module hasn't been included yet.\n modules.push(fetchDefine(modulePath, text));\n hasModules[modulePath] = true;\n }\n return modules;\n}",
"static loadModule(moduleName) {\n return new ToxenModule(moduleName);\n }",
"function register(loader) {\n if (typeof indexOf == 'undefined')\n indexOf = Array.prototype.indexOf;\n if (typeof __eval == 'undefined')\n __eval = eval;\n\n // define exec for easy evaluation of a load record (load.name, load.source, load.address)\n // main feature is source maps support handling\n var curSystem, curModule;\n function exec(load) {\n var loader = this;\n if (load.name == '@traceur') {\n curSystem = System;\n curModule = Module;\n }\n // support sourceMappingURL (efficiently)\n var sourceMappingURL;\n var lastLineIndex = load.source.lastIndexOf('\\n');\n if (lastLineIndex != -1) {\n if (load.source.substr(lastLineIndex + 1, 21) == '//# sourceMappingURL=')\n sourceMappingURL = toAbsoluteURL(load.address, load.source.substr(lastLineIndex + 22, load.source.length - lastLineIndex - 23));\n }\n\n __eval(load.source, loader.global, load.address, sourceMappingURL);\n\n // traceur overwrites System and Module - write them back\n if (load.name == '@traceur') {\n loader.global.traceurSystem = loader.global.System;\n loader.global.System = curSystem;\n //loader.global.Module = curModule;\n }\n }\n loader.__exec = exec;\n\n function dedupe(deps) {\n var newDeps = [];\n for (var i = 0; i < deps.length; i++)\n if (indexOf.call(newDeps, deps[i]) == -1)\n newDeps.push(deps[i])\n return newDeps;\n }\n\n // Registry side table\n // Registry Entry Contains:\n // - deps \n // - declare for register modules\n // - execute for dynamic modules, also after declare for register modules\n // - declarative boolean indicating which of the above\n // - normalizedDeps derived from deps, created in instantiate\n // - depMap array derived from deps, populated gradually in link\n // - groupIndex used by group linking algorithm\n // - module a raw module exports object with no wrapper\n // - evaluated indiciating whether evaluation has happend for declarative modules\n // After linked and evaluated, entries are removed\n var lastRegister;\n function register(name, deps, declare) {\n if (typeof name != 'string') {\n declare = deps;\n deps = name;\n name = null;\n }\n if (declare.length == 0)\n throw 'Invalid System.register form. Ensure setting --modules=instantiate if using Traceur.';\n\n if (!loader.defined)\n loader.defined = {};\n\n lastRegister = {\n deps: deps,\n declare: declare,\n declarative: true,\n };\n\n if (name)\n loader.defined[name] = lastRegister;\n }\n loader.defined = loader.defined || {};\n loader.register = register;\n\n function buildGroups(entry, loader, groups) {\n groups[entry.groupIndex] = groups[entry.groupIndex] || [];\n\n if (indexOf.call(groups[entry.groupIndex], entry) != -1)\n return;\n\n groups[entry.groupIndex].push(entry);\n\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n var depEntry = loader.defined[depName];\n \n // not in the registry means already linked / ES6\n if (!depEntry)\n continue;\n \n // now we know the entry is in our unlinked linkage group\n var depGroupIndex = entry.groupIndex + (depEntry.declarative != entry.declarative);\n\n // the group index of an entry is always the maximum\n if (depEntry.groupIndex === undefined || depEntry.groupIndex < depGroupIndex) {\n \n // if already in a group, remove from the old group\n if (depEntry.groupIndex) {\n groups[depEntry.groupIndex].splice(groups[depEntry.groupIndex].indexOf(depEntry), 1);\n\n // if the old group is empty, then we have a mixed depndency cycle\n if (groups[depEntry.groupIndex].length == 0)\n throw new TypeError(\"Mixed dependency cycle detected\");\n }\n\n depEntry.groupIndex = depGroupIndex;\n }\n\n buildGroups(depEntry, loader, groups);\n }\n }\n\n function link(name, loader) {\n var startEntry = loader.defined[name];\n\n startEntry.groupIndex = 0;\n\n var groups = [];\n\n buildGroups(startEntry, loader, groups);\n\n var curGroupDeclarative = !!startEntry.declarative == groups.length % 2;\n for (var i = groups.length - 1; i >= 0; i--) {\n var group = groups[i];\n for (var j = 0; j < group.length; j++) {\n var entry = group[j];\n\n // link each group\n if (curGroupDeclarative)\n linkDeclarativeModule(entry, loader);\n else\n linkDynamicModule(entry, loader);\n }\n curGroupDeclarative = !curGroupDeclarative; \n }\n }\n\n function linkDeclarativeModule(entry, loader) {\n // only link if already not already started linking (stops at circular)\n if (entry.module)\n return;\n\n // declare the module with an empty depMap\n var depMap = [];\n\n var declaration = entry.declare.call(loader.global, depMap);\n \n entry.module = declaration.exports;\n entry.exportStar = declaration.exportStar;\n entry.execute = declaration.execute;\n\n var module = entry.module;\n\n // now link all the module dependencies\n // amending the depMap as we go\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n var depEntry = loader.defined[depName];\n \n // part of another linking group - use loader.get\n if (!depEntry) {\n depModule = loader.get(depName);\n }\n // if dependency already linked, use that\n else if (depEntry.module) {\n depModule = depEntry.module;\n }\n // otherwise we need to link the dependency\n else {\n linkDeclarativeModule(depEntry, loader);\n depModule = depEntry.module;\n }\n\n if (entry.exportStar && indexOf.call(entry.exportStar, entry.normalizedDeps[i]) != -1) {\n // we are exporting * from this dependency\n (function(depModule) {\n for (var p in depModule) (function(p) {\n // if the property is already defined throw?\n Object.defineProperty(module, p, {\n enumerable: true,\n get: function() {\n return depModule[p];\n },\n set: function(value) {\n depModule[p] = value;\n }\n });\n })(p);\n })(depModule);\n }\n\n depMap[i] = depModule;\n }\n }\n\n // An analog to loader.get covering execution of all three layers (real declarative, simulated declarative, simulated dynamic)\n function getModule(name, loader) {\n var module;\n var entry = loader.defined[name];\n\n if (!entry)\n module = loader.get(name);\n\n else {\n if (entry.declarative)\n ensureEvaluated(name, [], loader);\n \n else if (!entry.evaluated)\n linkDynamicModule(entry, loader);\n module = entry.module;\n }\n\n return module.__useDefault ? module['default'] : module;\n }\n\n function linkDynamicModule(entry, loader) {\n if (entry.module)\n return;\n\n entry.module = {};\n\n // AMD requires execute the tree first\n if (!entry.executingRequire) {\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n var depEntry = loader.defined[depName];\n if (depEntry)\n linkDynamicModule(depEntry, loader);\n }\n }\n\n // lookup the module name if it is in the registry\n var moduleName;\n for (var d in loader.defined) {\n if (loader.defined[d] != entry)\n continue;\n moduleName = d;\n break;\n }\n\n // now execute\n try {\n entry.evaluated = true;\n var output = entry.execute(function(name) {\n for (var i = 0; i < entry.deps.length; i++) {\n if (entry.deps[i] != name)\n continue;\n return getModule(entry.normalizedDeps[i], loader);\n }\n }, entry.module, moduleName);\n }\n catch(e) {\n throw e;\n }\n \n if (output)\n entry.module = output;\n }\n\n // given a module, and the list of modules for this current branch,\n // ensure that each of the dependencies of this module is evaluated\n // (unless one is a circular dependency already in the list of seen\n // modules, in which case we execute it)\n // then evaluate the module itself\n // depth-first left to right execution to match ES6 modules\n function ensureEvaluated(moduleName, seen, loader) {\n var entry = loader.defined[moduleName];\n\n // if already seen, that means it's an already-evaluated non circular dependency\n if (entry.evaluated || !entry.declarative)\n return;\n\n seen.push(moduleName);\n\n for (var i = 0; i < entry.normalizedDeps.length; i++) {\n var depName = entry.normalizedDeps[i];\n if (indexOf.call(seen, depName) == -1) {\n if (!loader.defined[depName])\n loader.get(depName);\n else\n ensureEvaluated(depName, seen, loader);\n }\n }\n\n if (entry.evaluated)\n return;\n\n entry.evaluated = true;\n entry.execute.call(loader.global);\n delete entry.execute;\n }\n\n var registerRegEx = /System\\.register/;\n\n var loaderFetch = loader.fetch;\n loader.fetch = function(load) {\n var loader = this;\n if (loader.defined && loader.defined[load.name]) {\n load.metadata.format = 'defined';\n return '';\n }\n return loaderFetch(load);\n }\n\n var loaderTranslate = loader.translate;\n loader.translate = function(load) {\n this.register = register;\n\n this.__exec = exec;\n\n load.metadata.deps = load.metadata.deps || [];\n\n // we run the meta detection here (register is after meta)\n return Promise.resolve(loaderTranslate.call(this, load)).then(function(source) {\n \n // dont run format detection for globals shimmed\n // ideally this should be in the global extension, but there is\n // currently no neat way to separate it\n if (load.metadata.init || load.metadata.exports)\n load.metadata.format = load.metadata.format || 'global';\n\n // run detection for register format\n if (load.metadata.format == 'register' || !load.metadata.format && load.source.match(registerRegEx))\n load.metadata.format = 'register';\n return source;\n });\n }\n\n\n var loaderInstantiate = loader.instantiate;\n loader.instantiate = function(load) {\n var loader = this;\n\n var entry;\n \n if (loader.defined[load.name])\n loader.defined[load.name] = entry = loader.defined[load.name];\n\n else if (load.metadata.execute) {\n loader.defined[load.name] = entry = {\n deps: load.metadata.deps || [],\n execute: load.metadata.execute,\n executingRequire: load.metadata.executingRequire // NodeJS-style requires or not\n };\n }\n else if (load.metadata.format == 'register') {\n lastRegister = null;\n \n loader.__exec(load);\n\n // for a bundle, take the last defined module\n // in the bundle to be the bundle itself\n if (lastRegister)\n loader.defined[load.name] = entry = lastRegister;\n }\n\n if (!entry)\n return loaderInstantiate.call(this, load);\n\n entry.deps = dedupe(entry.deps);\n\n // first, normalize all dependencies\n var normalizePromises = [];\n for (var i = 0; i < entry.deps.length; i++)\n normalizePromises.push(Promise.resolve(loader.normalize(entry.deps[i], load.name)));\n \n return Promise.all(normalizePromises).then(function(normalizedDeps) {\n\n entry.normalizedDeps = normalizedDeps;\n\n // create the empty dep map - this is our key deferred dependency binding object passed into declare\n entry.depMap = [];\n\n return {\n deps: entry.deps,\n execute: function() {\n // this avoids double duplication allowing a bundle to equal its last defined module\n if (entry.esmodule) {\n delete loader.defined[load.name];\n return entry.esmodule;\n }\n\n // recursively ensure that the module and all its \n // dependencies are linked (with dependency group handling)\n link(load.name, loader);\n\n // now handle dependency execution in correct order\n ensureEvaluated(load.name, [], loader);\n\n // remove from the registry\n delete loader.defined[load.name];\n\n var module = Module(entry.module);\n\n // if the entry is an alias, set the alias too\n for (var name in loader.defined) {\n if (loader.defined[name].execute != entry.execute)\n continue;\n loader.defined[name].esmodule = module;\n }\n // return the defined module object\n return module;\n }\n };\n });\n }\n}",
"function getModules() {\n return _modules.concat();\n }",
"function addModule() {\n $('<section>')\n .attr('id', 'rsw-discord')\n .addClass('rsw-custom-module rail-module')\n .append(\n $('<a>')\n .attr('href', 'https://discord.gg/98hqjRg')\n .append(\n $('<img>')\n .attr('src', 'https://vignette.wikia.nocookie.net/dendro/images/9/94/WikiIcon.png/revision/latest/scale-to-width-down/240?cb=20190217055247')\n ),\n $('<div>')\n .append(\n $('<p>')\n .append(\n 'The Infinite Dendrogram Wiki has an Official Discord Server! Click the button below to join and chat with fellow fans live, or click ',\n $('<a>')\n .attr('href', mw.util.wikiGetlink('Infinite Dendrogram Wiki:Discord_Policy'))\n .text('here'),\n ' to read our chat rules.'\n ),\n $('<a>')\n .attr('href', 'https://discord.gg/98hqjRg')\n .addClass('wds-button')\n .text('Get invite')\n )\n )\n .insertBefore('#wikia-recent-activity');\n }",
"function link() {\n console.log('core::link,', 'linking modules');\n var i = 0,\n sorted = [],\n sortedLen = 0,\n parent = new Module(),\n name = '',\n module = null;\n\n // Sort modules in dependency order\n sorted = sort(modules);\n sortedLen = sorted.length;\n\n // Link modules in dependency order\n for (i = 0; i < sortedLen; i += 1) {\n name = sorted[i];\n module = modules[name];\n\n if (module.instance === undefined) {\n\n // Each module should inherit from a generic Module object\n module.def.prototype = parent;\n\n // Execute module code, pass requires, record exports\n modules[name].instance = instantiate(\n module.def,\n createParams(module.def, module.requires)\n );\n\n // Set module name\n modules[name].instance.name = name;\n\n if (typeof modules[name].instance.init === 'function') {\n modules[name].instance.init();\n }\n }\n }\n }",
"function ModelLoader(onLoadedHandler) {\n\n /// List of modules to load in given order\n\n var MODEL_MODULES = [\n// //\"model-browser.js\",\n// //\"model-photo.js\",\n// //\"model-directory.js\",\n// \"model/model-servicelist.js\",\n// \"model/model-sound.js\", // delete by ghl for headphoneinsert interface\n// \"model/model-hisfactory.js\",\n// \"model/model-tvservice.js\",\n// \"model/model-closedcaption.js\",\n// \"model/model-app-setting.js\",\n \"model/model-language.js\",\n \"model/model-parental-lock.js\",\n// \"model/model-softwareupdate.js\",\n// //\"model/model-cec.js\",\n \"model/model-system.js\",\n \"model/model-basic-settings.js\",\n// \"model/model-timer-functions.js\",\n// \"model/model-source.js\",\n \"model/model-network.js\",\n// \"model/model-channelsearch.js\",\n \"model/model-video.js\",\n// \"model/model-miracast.js\",\n \"model/model-picture.js\",\n \"model/model-mpctrl.js\",\n \"model/model-usb.js\",\n \"model/model-volume.js\",\n \"model/model-directory.js\"\n\n ];\n\n /// Number of loaded modules\n var loadedModules = 0;\n\n for (var i = 0; i < MODEL_MODULES.length; i++) {\n var module = MODEL_MODULES[i];\n var script = document.createElement('script');\n script.type = \"text/javascript\";\n script.src = module;\n script.onload = function () {\n loadedModules++;\n if (loadedModules == MODEL_MODULES.length) {\n onLoadedHandler();\n }\n }\n document.head.appendChild(script);\n }\n}",
"function lazyLoadModules() {\n\t\treturn requireAsync(\"sap/ui/fl/ChangePersistenceFactory\").then(function(oModule) {\n\t\t\t_oChangePersistenceFactory = oModule;\n\t\t})\n\t\t.catch(function(oError) {\n\t\t\tLog.error(\"Error loading modules: \" + oError.message);\n\t\t});\n\t}",
"function jbProjectModules(project) {\n return $.get('/projects/'+project+'/'+project+'.html').then(function(html){\n return (html.split('jbLoadModules(')[1] || '')\n .split('[')[1]\n .split(']')[0]\n .replace(/'|\"/g,'')\n .replace(/\\s/g,'')\n .split(',')\n })\n}",
"function initializeAllModules() {\r\n var modules = mj.modules;\r\n for (var moduleName in modules) {\r\n if (moduleName != 'main' && modules.hasOwnProperty(moduleName)) {\r\n if (typeof modules[moduleName].setup == 'function') {\r\n modules[moduleName].setup();\r\n }\r\n trigger('initialize-' + moduleName, null, true);\r\n }\r\n }\r\n }",
"function loadLibModules(pO) {\r\n\r\n // Create math library\r\n //\r\n loadMathLibrary(pO);\r\n\r\n loadFileInputLibrary(pO);\r\n\r\n loadFileOutputLibrary(pO);\r\n\r\n loadSystemLibrary(pO);\r\n\r\n loadMatrixLibrary(pO);\r\n\r\n loadTempSensorLibrary(pO);\r\n\r\n // TODO: load other libraries here\r\n\r\n}",
"function moduleappend_response(req)\n{\n appending = false;\n if (!req.isSuccess()) {\n Zikula.showajaxerror(req.getMessage());\n return;\n }\n var data = req.getData();\n\n // copy new module li from module_1.\n var newmodule = $('module_'+firstmodule).cloneNode(true);\n\n // update the ids. We use the getElementsByTagName function from\n // protoype for this. The 6 tags here cover everything in a single li\n // that has a unique id\n newmodule.id = 'module_' + data.id;\n $A(newmodule.getElementsByTagName('a')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('div')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('span')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('input')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; node.value = ''; });\n $A(newmodule.getElementsByTagName('select')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('button')).each(function(node) { node.id = node.id.split('_')[0] + '_' + data.id; });\n $A(newmodule.getElementsByTagName('textarea')).each(function(node){ node.id = node.id.split('_')[0] + '_' + data.id; });\n\n // append new module to the module list\n $('modulelist').appendChild(newmodule);\n\n // set initial values in input, hidden and select\n //$('modname_' + data.id).value = data.modname;\n //$('description_' + data.id).value = data.description;\n //$('members_' + data.id).href = data.membersurl;\n\n// Zikula.setselectoption('modulenavtype_' + data.id, data.navtype_disp);\n// Zikula.setselectoption('moduleenablelang_' + data.id, data.enablelang);\n\n // hide cancel icon for new modules\n// Element.addClassName('moduleeditcancel_' + data.id, 'z-hide');\n // update delete icon to show cancel icon\n// Element.update('moduleeditdelete_' + data.id, canceliconhtml);\n\n // update some innerHTML\n// Element.update('moduleid_' + data.id, data.id);\n// Element.update('modulemodname_' + data.id, data.modname);\n// Element.update('modulenavtype_' + data.id, data.navtype_disp);\n// Element.update('moduleenablelang_' + data.id, data.enablelang);\n //Element.update('members_' + data.id, data.membersurl);\n\n // add events\n Event.observe('modifyajax_' + data.id, 'click', function(){modulemodifyinit(data.id)}, false);\n Event.observe('moduleeditsave_' + data.id, 'click', function(){modulemodify(data.id)}, false);\n Event.observe('moduleeditdelete_' + data.id, 'click', function(){moduledelete(data.id)}, false);\n Event.observe('moduleeditcancel_' + data.id, 'click', function(){modulemodifycancel(data.id)}, false);\n\n // remove class to make edit button visible\n Element.removeClassName('modifyajax_' + data.id, 'z-hide');\n Event.observe('modifyajax_' + data.id, 'click', function(){modulemodifyinit(data.id)}, false);\n\n // turn on edit mode\n allownameedit[data.id] = true;\n enableeditfields(data.id);\n\n // we are ready now, make it visible\n Element.removeClassName('module_' + data.id, 'z-hide');\n new Effect.Highlight('module_' + data.id, { startcolor: '#99ff66', endcolor: '#ffffff' });\n\n\n // set flag: we are adding a new module\n adding[data.id] = 1;\n}",
"async loadNodeModules(x, start) {\n assert(typeof x === 'string');\n assert(typeof start === 'string');\n\n const dirs = this.nodeModulesPaths(start);\n\n for (const dir of dirs) {\n const dx = join(dir, x);\n const a = await this.loadAsFile(dx);\n\n if (a)\n return a;\n\n const b = await this.loadAsDirectory(dx);\n\n if (b)\n return b;\n }\n\n return null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a backdrop element and returns it | function createBackdropElement(isVisible) {
var backdrop = div();
backdrop.className = BACKDROP_CLASS;
backdrop.setAttribute('data-state', isVisible ? 'visible' : 'hidden');
return backdrop;
} | [
"createContainer() {\n const existingContainer = document.querySelector('#bitski-dialog-container');\n if (existingContainer) {\n return existingContainer;\n }\n const container = document.createElement('div');\n container.id = 'bitski-dialog-container';\n document.body.appendChild(container);\n return container;\n }",
"showBackdrop() {\r\n this.setState({ isBackdropVisible: true });\r\n }",
"function display_form(){\r\n $('#staticBackdrop').modal('show');\r\n}",
"hideBackdrop() {\r\n this.setState({ isBackdropVisible: false });\r\n }",
"function createDragImage(el) {\r\n var clone = deepClone(el);\r\n clone.style.position = 'fixed';\r\n clone.style.margin = '0';\r\n clone.style[\"z-index\"] = '1000';\r\n clone.style.transition = 'opacity 0.2s';\r\n return clone;\r\n}",
"function backdropClickHandler(event) {\n if (event.target === event.currentTarget) {\n closeModalHandler();\n };\n}",
"function createElementsForPopup() {\r\n _dom.el.css(\"position\", \"absolute\");\r\n _dom.el.addClass(\"s-c-p-popup\");\r\n _dom.arrow = $(\"<div></div>\")\r\n .appendTo(_dom.el)\r\n .addClass(\"s-c-p-arrow\");\r\n _dom.arrowInner = $(\"<div></div>\")\r\n .appendTo(_dom.arrow)\r\n .addClass(\"s-c-p-arrow-inner\");\r\n }",
"function getInventoryView() {\n let container = new createjs.Container();\n let bg = getRectangle(\"White\", \"Red\", 0, 0, 200, 40);\n // Text to display the score and other messages.\n rewardText = new createjs.Text( \"Reward: 0\", \"42px Arial\", \"#ffffff\");\n container.addChild(bg, rewardText);\n container.visible = false;\n return container;\n}",
"function Create_Exit_Box () {\n var exit_box = document.createElement(\"div\")\n exit_box.className = \"\"\n exit_box.setAttribute(\"id\", \"Exit_Box\")\n exit_box.innerHTML = \"\"\n document.body.appendChild(exit_box)\n}",
"function addOverlay() {\n console.log('add OVERLAY');\n $('body').append('<div class=\"overlay\"></div>');\n }",
"function ViewAssetClicked(url) {\n console.log(\"View Asset clicked!\");\n console.log(url);\n // get the click of the create button\n $('#assetModal').modal('show')\n .find('#viewAssetModalContent').load(url);\n $(\".modal-backdrop.in\").css({'opacity': 0});\n}",
"divHollow(template) {\n const newbie = document.createElement('div');\n $(newbie).html(' ').addClass(this.brickClass[template]);\n newbie.setAttribute('aria-hidden', 'true');\n return newbie;\n }",
"function createPopupContainer()\n{\n\tpopupContainer = document.createElement(\"div\");\n\tpopupContainer.style.background = \"blue\";\n\tpopupContainer.style.opacity = \"0.5\";\n\tpopupContainer.style.color = \"white\";\n\tpopupContainer.style.position = \"absolute\";\n\tpopupContainer.style.padding = \"25px\";\n\tpopupContainer.style.top = \"50%\";\n\tpopupContainer.style.left = \"50%\";\n\tpopupContainer.style.transform = \"translate(-50%, -50%)\";\n\tpopupContainer.style.visibility = \"hidden\";\n\n\tvar closeButton = document.createElement(\"div\");\n\tcloseButton.style.position = \"absolute\";\n\tcloseButton.style.top = \"2px\";\n\tcloseButton.style.right = \"2px\";\n\tcloseButton.innerHTML = \"X\";\n\tcloseButton.style.background = \"red\";\n\tcloseButton.style.paddingLeft = \"3px\";\n\tcloseButton.style.paddingRight = \"3px\";\n\tcloseButton.style.paddingTop = \"1px\";\n\tcloseButton.style.paddingBottom = \"1px\";\n\tcloseButton.opacity = \"0.5\";\n\tcloseButton.onclick = function(){popupContainer.style.visibility = \"hidden\";};\n\tpopupContainer.appendChild(closeButton);\n\n\tvar textContainer = document.createElement(\"pre\");\n\ttextContainer.id = \"popupTextContainer\";\n\ttextContainer.style.fontFamily = \"helvetica\";\n\ttextContainer.style.height = \"100%\";\n\ttextContainer.style.width = \"100%\";\n\tpopupContainer.appendChild(textContainer);\n}",
"createEl(tag = 'div', props = {}, attrs = {}) {\n\t\tprops = assign({\n\t\t\tclassName: 'ntk-dialog'\n\t\t}, props);\n\t\t\n\t\tconst el = super.createEl(tag, props, attrs);\n\t\t\n\t\treturn el;\n\t}",
"showOverlay_() {\n this.overlay_.setAttribute('i-amphtml-lbg-fade', 'in');\n this.controlsMode_ = LightboxControlsModes.CONTROLS_DISPLAYED;\n }",
"createFullElt() {\n const elt = createImgElt(`FishEye_Photos/Images/${this.src}`, this.alt);\n elt.setAttribute(\"id\", \"current-media-lightbox\");\n\n return elt;\n }",
"function createModal() {\n\tif (modal) {\n\t\treturn;\n\t}\n\n\tvar id = 'iisModal';\n\tvar dummy = document.createElement('div');\n\n\tdummy.innerHTML = '\\n\\t\\t<div id=\"' + id + '\" class=\"' + (0, _className2.default)('m-modal m-modal--has-overlay') + '\" data-container=\"true\" aria-hidden=\"true\" aria-labelledby=\"' + id + '-close\">\\n\\t\\t\\t<div class=\"' + (0, _className2.default)('m-modal__container') + '\">\\n\\t\\t\\t\\t<button type=\"button\" class=\"' + (0, _className2.default)('a-button a-button--standalone-icon a-button--transparent') + '\" data-modal-close aria-expanded=\"false\" data-a11y-toggle=\"' + id + '\" aria-controls=\"' + id + '\" id=\"' + id + '-close\">\\n\\t\\t\\t\\t\\t<span class=\"' + (0, _className2.default)('a-button__text') + ' u-visuallyhidden\">St\\xE4ng</span>\\n\\t\\t\\t\\t\\t<svg class=\"icon ' + (0, _className2.default)('a-button__icon') + '\">\\n\\t\\t\\t\\t\\t\\t<use xlink:href=\"#icon-close\"></use>\\n\\t\\t\\t\\t\\t</svg>\\n\\t\\t\\t\\t</button>\\n\\t\\t\\t\\t<div class=\"' + (0, _className2.default)('m-modal__content') + '\" data-modal-content></div>\\n\\t\\t\\t\\t<div class=\"' + (0, _className2.default)('m-modal__buttons') + ' u-m-t-2 u-hide\" data-modal-actions></div>\\n\\t\\t\\t</div>\\n\\t\\t</div>\\n\\t';\n\n\tmodal = dummy.firstElementChild;\n\tmodalContent = modal.querySelector('[data-modal-content]');\n\tmodalActions = modal.querySelector('[data-modal-actions]');\n\tmodalClose = modal.querySelector('[data-modal-close]');\n\n\tdocument.body.appendChild(modal);\n\n\tmodalClose.addEventListener('click', close);\n\n\tsetTimeout(function () {\n\t\tdispatch();\n\t}, 1);\n}",
"function addRemoveOverlay() {\n if (headerContent.hasClass(\"active\")) {\n // Create and show the menu overlay\n bodyContainer.append(menuOverlayHTML);\n $(menuOverlayClass).animate(\n { opacity: 0.67 },\n 150\n );\n // Add event handler for newly created menu overlay element\n $(menuOverlayClass).click(function() {\n openCloseMenu();\n addRemoveOverlay();\n });\n } else {\n // Remove the menu overlay\n $(menuOverlayClass).fadeOut(250, function() {\n $(this).remove();\n });\n }\n }",
"function makeBleachingButton() {\n\n // Create the clickable object\n bleachingButton = new Clickable();\n \n bleachingButton.text = \"What is bleaching?\";\n bleachingButton.textColor = \"#365673\"; \n bleachingButton.textSize = 25; \n\n bleachingButton.color = \"#8FD9CB\";\n\n // set width + height to image size\n bleachingButton.width = 380;\n bleachingButton.height = 62;\n\n // places the button on the page \n bleachingButton.locate( width * (12/32) , height * (7/8));\n\n // // Clickable callback functions, defined below\n bleachingButton.onPress = bleachingButtonPressed;\n bleachingButton.onHover = beginButtonHover;\n bleachingButton.onOutside = beginButtonOnOutside;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For example: if arr is [1, 2, 4, 6, 4, 3, 1] then your program should return 3 because 6 is the last point in the array where the numbers were increasing and the next number begins a decreasing sequence. The array will contain at least 3 numbers and it may contains only a single sequence, increasing or decreasing. If there is only a single sequence in the array, then your program should return 1. Indexing should begin with 0. | function ChangingSequence(arr) {
//loop through each number in array
for(var i = 1; i < arr.length - 1; i++){
//if current number is greater than previous number and also greater than next number, return index of number
if(arr[i] > arr[i-1] && arr[i] > arr[i+1]){
return i;
}
//else if current number is less than previous number and also less than next number, return index of number
else if(arr[i] < arr[i-1] && arr[i] < arr[i+1]){
return i;
}
}
//if loop finishes without returning out, return -1
return -1;
} | [
"function largestGapConsecutiveElements (arr){\n var gap = 0;\n for(var i = 0; i < arr.length; i++){\n var diff = arr[i] - (arr[i+1])\n if (diff > gap){\n gap = diff;\n }\n }\n return gap;\n}",
"function findMissing(array){\n\t// edge cases\n\tif(array[0] != 1) return 1;\n\tif(array[array.length - 1] != array.length + 1) return array.length + 1;\n\tfor(var i = 1; i < array.length; i++){\n\t\t\t// if next element is greater by more than 1, missing number is it minus 1.\n\t\t\tif(array[i] - array[i-1] > 1) return array[i-1] + 1;\n\t}\n\t// when the array is not missing a number\n\treturn -1;\n}",
"function check(arr) {\n\tconst a = [...new Set(arr.map((x, i) => x < arr[i + 1]).slice(0, -1))];\n\tif (a.length > 1) return 'neither';\n\tif (a[0]) {\n\t\treturn 'increasing';\t\n\t} else {\n\t\treturn 'decreasing';\n\t}\n\n}",
"function peak(arr){\n \n for(i=0; i < arr.length - 1; i++){\n \n if( arr.slice(0, i + 1).reduce((a,c) => a + c, 0) ===\n \n arr.slice(i + 2).reduce((a,c) => a + c, 0) ) {\n \n return i + 1\n }\n } \n \n return - 1\n \n}",
"function lastTime(arr, num) {\n // for (let i = arr.length - 1; i >= 0; i--) {\n // let num = arr[i];\n // if (num == target) {\n // return i;\n // }\n // }\n let targetIndex;\n for (let i = 0; i < arr.length; i++) {\n let num = arr[i];\n if (num == target) {\n targetIndex = i;\n }\n }\n}",
"function lastNumber(array) {\n //numbers are in descending order\n if(array.length>=(Math.pow(10,5))){\n return 0; //base case where; 1 < n < 10^5\n }\n array = array.sort((a,b)=>a-b);\n while(true){\n if(array.length==1) return array[0];\n if(array.length==0) return 0;\n let num1 = array.pop();\n let num2 = array.pop();\n\n if(num1!=num2){\n let newNumber = Math.abs( Number(num1) - Number(num2) );\n \n // insert this number back\n if(newNumber>=array[array.length-1]){\n array.push(newNumber);\n }else if( newNumber<=array[0]){\n array.splice(0,0,newNumber);\n }else{\n //place new number in sorted position in array\n let findIndex = array.findIndex(value=>value>newNumber);\n array.splice(findIndex,0,newNumber);\n }\n }\n }\n}",
"function incrementToTop(arr) {\n let biggestElem = Math.max(...arr);\n return arr.reduce((a,b) => { return a + (biggestElem - b) },0 );\n}",
"function getIndexToIns(arr, num) {\n arr.sort(function(a, b) {\n return a - b;\n });\n for (var i = 0; i < arr.length; i++) {\n if (num <= arr[i]) {\n break;\n }\n }\n return i;\n}",
"function countInversion(arr) {\n\tlet count = 0;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tfor (let j = i + 1; j <= arr.length - 1; j++) {\n\t\t\tif (arr[i] > arr[j] && i < j) {\n\t\t\t\t// inversion occurs when a number is greater than its neighbor\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\treturn count;\n}",
"function countPositives(arr) {\n var count = 0;\n for (var x=0; x<arr.length; x++) {\n if (arr[x] > 0) {\n count++\n }\n }\n arr[arr.length - 1] = count\n return arr\n}",
"function findLastIndex(arr, fn) {\n\tfor (let i = arr.length - 1; i >= 0; --i) {\n\t\tif (fn(arr[i])) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n}",
"function longestIncreasingSubsequence(nums) {\n let dp = new Array(nums.length).fill(1)\n let max = 0\n for (let i = 1; i < nums.length; i++) {\n for (let j = 0; j < i; j++) {\n if (nums[j] < nums[i]) {\n dp[i] = Math.max(dp[j] + 1, dp[i])\n }\n }\n max = Math.max(max, dp[i])\n }\n return max\n}",
"function cyclicArray(arr){\n let i=0, \n count =0;\n //create checks to see if arr[0] or i itself are out of bounds of the array, if so exit the loop\n while((i >=0 && arr[i]>=0) || (i <arr.length && arr[i] <arr.length)) {\n //if the count is greater than arr.length-1 that means one element is visited twice therefore there is a cycle\n if(count>= arr.length) {\n console.log(\"there is a cycle in the array\");\n return true;\n }\n //\n else{\n //increment counter and traverse to next index from current index value\n count++;\n i = arr[i];\n }\n }\n console.log(\"no cycle in array\");\n return false;\n}",
"function hasSingleCycle(array) {\n // Write your code here.\n //keep track of the currentIdx and jumpIdx\n //currentIdx+ jumpIdx = newIdx (points to integer from tha array)\n let currentIdx = 0;\n\n //track how many timewe visit each integer\n let count = 0;\n //need to visit all elements in the array\n while (count < array.length) {\n //1st edge case :if we visitied integer more than 1 time\n //and we came back to the first integer =>FALSE\n if (currentIdx === 0 && count > 0) return false;\n count++;\n let jumpIdx = array[currentIdx];\n\n //find a newIdx that will point to the next needed element\n let newIdx = (currentIdx + jumpIdx) % array.length; //% length because newIdx can become > than array.length\n //so we need to start over from the beginning\n\n //2nd EDGE case:if newIdx ecomes a negative integer=>we need to forward it to start pointing from the end\n\n if (newIdx < 0) {\n newIdx = newIdx + array.length;\n }\n currentIdx = newIdx;\n }\n //ONly if we visited all elements AND returned back from where we started(at 0 idx)=>TRUE\n return currentIdx === 0;\n}",
"function psuedoCode(arr, val) {\n let leftPtr = 0;\n let rightPtr = arr.length - 1;\n let middlePtr = Math.floor((leftPtr + rightPtr) / 2);\n // console.log(leftPtr, middlePtr, rightPtr)\n\n while (arr[middlePtr] !== val && leftPtr <= rightPtr) {\n if (val < middlePtr) rightPtr = middlePtr - 1;\n else leftPtr = middlePtr + 1;\n\n middlePtr = Math.floor((leftPtr + rightPtr) / 2);\n }\n\n // console.log(leftPtr, middlePtr, rightPtr)\n // if(arr[middlePtr] === val) {\n // return middlePtr\n // }\n // return -1\n\n return arr[middlePtr] === val ? middlePtr : -1;\n}",
"function nth(arr,num) {\n//Check to see if array is not too short \n if(arr.length <= 2){\n //If array is too short, return null \n return null; \n }\n //If array is long enough, return value of the proposed index\n return arr[arr.length-num]\n}",
"function minimumRemovals(arr) {\n\tlet sum = 0;\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tsum += arr[i];\n\t}\n\t\n\treturn sum % 2;\n}",
"function getRotationCount(arrA){\n var rotme = arrA.slice(); \n var rotSo = arrA.sort((a, b) => { return a - b });\n var rotationC = 0; \n while (JSON.stringify(rotme) != JSON.stringify(rotSo) && rotationC <= arrA.length) {\n // document.writeln('rotationC: ', rotationC);\n rotme.unshift(rotme.pop());\n rotationC = rotationC + 1;\n }\n if(rotationC > arrA.length){\n return null; \n }\n return rotationC; \n}",
"function nextPermutation(nums) {\n //finding the first decreasing number from right\n let i = nums.length - 2;\n while (i >= 0 && nums[i] >= nums[i + 1]) {\n i--;\n }\n //if not found meaning the biggest #\n //otherwise, find the next bigger number from right\n if (i >= 0) {\n let j = nums.length - 1;\n while (j >= 0 && nums[i] > nums[j]) {\n j--;\n }\n //swap to get ready to increment\n [nums[i], nums[j]] = [nums[j], nums[i]];\n }\n //reverse the right of the mutation part to increasing\n reverse(nums, i + 1)\n return nums;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the extended splash screen if it is currently visible. | function remove() {
if (isVisible()) {
var extendedSplashScreen = document.getElementById("extendedSplashScreen");
WinJS.Utilities.addClass(extendedSplashScreen, "hidden");
}
} | [
"async hideSplashScreen() {\n\t\ttry {\n\t\t\tif (!this.splashScreenWindow) return;\n\t\t\tthis.splashScreenWindow.close();\n\t\t\tthis.splashScreenWindow = null;\n\t\t} catch (err) {\n\t\t\tlogger.error(`Unable to hide splash screen ${err.message}`);\n\t\t\tconst error = new Error('Error hiding splash screen.');\n\t\t\tthrow (error);\n\t\t}\n\t}",
"hideSplashScreen()\n {\n this.changeView(\"appMainViews\", \"app-view-app\")\n }",
"function show(splash) {\n var extendedSplashImage = document.getElementById(\"extendedSplashImage\");\n\n // Position the extended splash screen image in the same location as the system splash screen image.\n extendedSplashImage.style.top = splash.imageLocation.y + \"px\";\n extendedSplashImage.style.left = splash.imageLocation.x + \"px\";\n extendedSplashImage.style.height = splash.imageLocation.height + \"px\";\n extendedSplashImage.style.width = splash.imageLocation.width + \"px\";\n\n // Position the extended splash screen's progress ring. Note: In this sample, the progress ring is not used.\n ////\n // var extendedSplashProgress = document.getElementById(\"extendedSplashProgress\");\n // extendedSplashProgress.style.marginTop = splash.imageLocation.y + splash.imageLocation.height + 32 + \"px\";\n ////\n\n // Once the extended splash screen is setup, apply the CSS style that will make the extended splash screen visible.\n var extendedSplashScreen = document.getElementById(\"extendedSplashScreen\");\n WinJS.Utilities.removeClass(extendedSplashScreen, \"hidden\");\n }",
"exitFullscreen() {\n if (this.isFullscreenEnabled()) {\n exitFullscreen();\n }\n }",
"function hideMobileIcon () {\n $('.loader').parent().removeClass('bg--none');\n}",
"function hide_preloader_on_load()\n{\n\t$(window).load(function()\n\t{\n\t\tfade_out_preloader();\n\t});\n}",
"function enterPage(){\n const mainPage = document.getElementById(\"mainPage\");\n mainPage.classList.remove(\"disappear\")\n const splashPage = document.getElementById(\"splashPage\");\n splashPage.classList.add(\"disappear\");\n splashPage.removeAttribute(\"id\");\n\n}",
"function _hideEndScreen() {\r\n hideEndScreen();\r\n }",
"function hide() {\n if (!settings.shown) return;\n win.hide();\n settings.shown = false;\n }",
"function exitSlider () {\nmainWrapper.style.display = 'none';\n}",
"function hideAppIcon() {\n if (app.dock) app.dock.hide();\n}",
"removePauseScreen() {\n\t\tgameState.pauseOverlay.destroy();\n\t\tgameState.pauseText.destroy();\n\t\tgameState.resumeText.destroy();\n\t}",
"function backToMain() {\n clearInterval(timer);\n $(\"game-view\").classList.add(\"hidden\");\n $(\"menu-view\").classList.remove(\"hidden\");\n }",
"hide() {\n\t\tthis.activityIndicator.hide();\n\n\t\tif (!this.isAndroid) {\n\t\t\tthis.containerView.animate({\n\t\t\t\topacity: 0.0\n\t\t\t}, () => {\n\t\t\t\tthis.view.remove(this.containerView);\n\t\t\t});\n\t\t}\n\t}",
"function unhide()\r\n{\r\n if (document.querySelector('.pumpkin').style.visibility == \"visible\")\r\n {\r\n document.querySelector('.pumpkin').style.visibility = \"hidden\";\r\n }\r\n else\r\n {\r\ndocument.querySelector('.pumpkin').style.visibility = \"visible\";\r\n }\r\n}",
"function hideLoading() {\n\t\tanimate(loadingDiv, {\n\t\t\topacity: 0\n\t\t}, {\n\t\t\tduration: options.loading.hideDuration,\n\t\t\tcomplete: function() {\n\t\t\t\tcss(loadingDiv, { display: NONE });\n\t\t\t}\n\t\t});\n\t\tloadingShown = false;\n\t}",
"function removeAnim() {\n let removeStartAnim = (document.getElementById(\n \"slideAnimStart\"\n ).style.display = \"none\");\n content.style.visibility = \"hidden\";\n\n // display second layer of animation ONLY if the first layer has been removed\n if (removeStartAnim) {\n animEnd.style.display = \"block\";\n }\n}",
"function removeLoadingOverlay() {\n if(document.getElementById('overlay') !== null) {\n body.removeChild( document.getElementById('overlay') );\n }\n }",
"function hideStatusBarDevelopmentOnly () {\n _el.style.display = 'none'\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate the response received after sending a speech request that is too long | function validateSpeechFailTooLongResponse(response) {
notEqual(response["requestError"], undefined, "requestError");
var re = response["requestError"];
if (re != null) {
notEqual(re["serviceException"], undefined, "serviceException");
var se = re["serviceException"];
if (se != null) {
equal(se["messageId"], "POL0001", "messageId");
equal(se["text"], "The audio length is larger than the allowed length", "text");
equal(se["variables"], "", "variables");
}
}
} | [
"function validateSpeechFailTMSResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"Too Much Speech\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}",
"function validateSpeechFailHCLBResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"HTTP Chunk length bad\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}",
"function validateSpeechFailNSResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"No Speech\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}",
"function validateSpeechFailUPResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0002\", \"messageId\");\n equal(se[\"text\"], \"Undefined Parameter\", \"text\");\n equal(se[\"variables\"], \"%1\", \"variables\");\n }\n }\n}",
"static validateReadingExceedsLength(pageClientAPI, dict) {\n\n //Reading is not allowed, or reading is optional and empty\n if (libThis.evalIgnoreReading(dict)) {\n return Promise.resolve(true);\n }\n\n //New reading length must be <= global maximum\n let max = libCom.getAppParam(pageClientAPI, 'MEASURINGPOINT', 'ReadingLength');\n\n if (libThis.evalReadingLengthWithinLimit(dict, max)) {\n return Promise.resolve(true);\n } else {\n let dynamicParams = [max];\n let message = pageClientAPI.localizeText('validation_maximum_field_length', dynamicParams);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ReadingSim'), message);\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n }\n }",
"function validateSpeechFailACNSResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"Audio coding not specified\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}",
"function validateSpeechFailBNSResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"Bitrate not supported\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}",
"static validateShortTextExceedsLength(pageClientAPI, dict) {\n\n //New short text length must be <= global maximum\n let max = libCom.getAppParam(pageClientAPI, 'MEASURINGPOINT', 'ShortTextLength');\n\n if (libThis.evalShortTextLengthWithinLimit(dict, max)) {\n return Promise.resolve(true);\n } else {\n let dynamicParams = [max];\n let message = pageClientAPI.localizeText('validation_maximum_field_length', dynamicParams);\n libCom.setInlineControlError(pageClientAPI, libCom.getControlProxy(pageClientAPI, 'ShortTextNote'), message);\n dict.InlineErrorsExist = true;\n return Promise.reject(false);\n }\n }",
"function validateSpeechFailAPNFResponse(response) {\n notEqual(response[\"requestError\"], undefined, \"requestError\");\n var re = response[\"requestError\"];\n if (re != null) {\n notEqual(re[\"serviceException\"], undefined, \"serviceException\");\n var se = re[\"serviceException\"];\n if (se != null) {\n equal(se[\"messageId\"], \"SVC0001\", \"messageId\");\n equal(se[\"text\"], \"App package not found\", \"text\");\n equal(se[\"variables\"], \"\", \"variables\");\n }\n }\n}",
"function validateResponse ( packet ) {\n\tlet result = false;\n\n\t//0 0 129 128 0 1 0\n\tif (packet.length > 7 &&\n\t\tpacket[2] === 129 &&\n\t\tpacket[3] === 128 &&\n\t\tpacket[4] === 0 &&\n\t\tpacket[5] === 1 &&\n\t\tpacket[6] === 0 &&\n\t\tpacket[7] > 0\n\t) {\n\t\tresult = true;\n\t}\n\n\treturn result;\n}",
"function tooLongContentLength() {\n var content = \"test\";\n var options = {\n path: '/check/blablablabla',\n method: 'GET',\n headers: {\n 'Content-Length': 1000 // it will wait for the whole request, and then timeout\n }\n };\n testResponse(options, content, function(res) {}, {\n 'error': function(d){\n console.log(\"Bad content-length (too long) - test succeeded\");\n }\n });\n\n}",
"function onSpeak(e) {\n // console.log(e);\n const msg = e.results[0][0].transcript;\n // console.log(msg);\n writeMessage(msg);\n checkNumber(msg);\n}",
"exceedsMaxSize() {\n return JSON.stringify(this.data).length > MAX_SESSION_DATA_SIZE;\n }",
"function responseTooQuickly(rt, loggvar){\n if(rt < dataService.timerOptions().tooFast){\n clearInterval(loggvar);\n $('#header').append(`<h2 style=\"position: absolute; left: 33%\" id=\"infoMessage\">${dataService.checkAnswer().quickMessage}</h2>`);\n }\n}",
"function throwTimeout() {\n \n if(!responseReceived) {\n \n throwError(\"The request timed out.\");\n }\n}",
"function isLineOverlong(text) {\n\t\tvar checktext;\n\t\tif (text.indexOf(\"\\n\") != -1) { // Multi-line message\n\t\t\tvar lines = text.split(\"\\n\");\n\t\t\tif (lines.length > MAX_MULTILINES)\n\t\t\t\treturn true;\n\t\t\tfor (var i = 0; i < lines.length; i++) {\n\t\t\t\tif (utilsModule.countUtf8Bytes(lines[i]) > MAX_BYTES_PER_MESSAGE)\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t} else if (text.startsWith(\"//\")) // Message beginning with slash\n\t\t\tchecktext = text.substring(1);\n\t\telse if (!text.startsWith(\"/\")) // Ordinary message\n\t\t\tchecktext = text;\n\t\telse { // Slash-command\n\t\t\tvar parts = text.split(\" \");\n\t\t\tvar cmd = parts[0].toLowerCase();\n\t\t\tif ((cmd == \"/kick\" || cmd == \"/msg\") && parts.length >= 3)\n\t\t\t\tchecktext = utilsModule.nthRemainingPart(text, 2);\n\t\t\telse if ((cmd == \"/me\" || cmd == \"/topic\") && parts.length >= 2)\n\t\t\t\tchecktext = utilsModule.nthRemainingPart(text, 1);\n\t\t\telse\n\t\t\t\tchecktext = text;\n\t\t}\n\t\treturn utilsModule.countUtf8Bytes(checktext) > MAX_BYTES_PER_MESSAGE;\n\t}",
"async function validateMediaFlow(room) {\n const testTimeMS = 6000;\n // wait for some time.\n await new Promise(resolve => setTimeout(resolve, testTimeMS));\n\n // get StatsReports.\n const statsBefore = await room.getStats();\n const bytesReceivedBefore = getTotalBytesReceived(statsBefore);\n\n // wait for some more time.\n await new Promise(resolve => setTimeout(resolve, testTimeMS));\n\n const statsAfter = await room.getStats();\n const bytesReceivedAfter = getTotalBytesReceived(statsAfter);\n console.log(`Total bytes Received in ${room.localParticipant.identity}'s Room: ${bytesReceivedBefore} => ${bytesReceivedAfter}`);\n if (bytesReceivedAfter <= bytesReceivedBefore) {\n throw new Error('no media flow detected');\n }\n}",
"function checkWordCount(inputMessage) {\n\tvar input = inputMessage;\n\tvar newInput = input.split(\" \");\n\tif (newInput.length >= 100) {\n\t\tconsole.log(\"input with less than 100\", newInput);\n\t\treturn false;\n\t};\n}",
"overflown() {\n let _this = this;\n\n return this.result.split('\\n').some((line) => {\n return line.length > _this.config['max-len'];\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert BN to 0xprefixed hex string. | function bnToHex(value) {
return "0x" + value.toString(16);
} | [
"function Hex(n) {\n n=Math.round(n);\n if (n < 0) {\n n = 0xFFFFFFFF + n + 1;\n }\n return n.toString(16).toUpperCase();\n}",
"function hex2base58(s){ return Bitcoin.Base58.encode(hex2bytes(s))}",
"function bigInt2hex(i){ return i.toString(16); }",
"function hex2hexKey(s){ return bigInt2hex(hex2bigIntKey(removeWhiteSpace(s))); }",
"function addr2pksh(addr) {\n // console.log(\"Cryptography\");\n // var addr = \"ALjSnMZidJqd18iQaoCgFun6iqWRm2cVtj\";\n var uint8 = ThinNeo.Helper.GetPublicKeyScriptHash_FromAddress(addr);\n var hexstr = uint8.reverse().toHexString();\n console.log(\"addr=\" + addr);\n console.log(\"hex=\" + hexstr);\n return '0x' + hexstr;\n\n}",
"function bigint2hex(m,l)\n{\n\tlet r = bigint2bytes(m, l);\n\treturn \"0x\" + r.map(c => ('00' + c.toString(16)).slice(-2) ).join('');\n}",
"function hex4(state) {\n return re(state, /^[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]/,\n function (s) {\n return parseInt(s, 16);\n });\n }",
"function fixedHex(number, length)\n{\n var str = number.toString(16).toUpperCase();\n while(str.length < length) {\n str = \"0\" + str;\n }\n return str;\n}",
"function base582hex(s){\r\n var res, bytes\r\n try { res = parseBase58Check(s); bytes = res[1]; }\r\n catch (err) { bytes = Bitcoin.Base58.decode(s); }\r\n return bytes2hex(bytes)\r\n}",
"function getDeviceAddress(b64_pubkey){\n\treturn `0${getChash160(b64_pubkey)}`;\n}",
"function changeHex(h, n){\r\n h=(typeof(h) == \"string\") ? parseInt(h,16) : h;\r\n if((h == 0 && n < 0)||(h == 255 && n > 0)){n = 0} \r\n h += n;\r\n h = (h > 255) ? 255 : (h < 0) ? 0 : h;\r\n return (h <= 15) ? \"0\" + h.toString(16) : h.toString(16);\r\n}",
"function toHex(byte) {\n\treturn ('0' + (byte & 0xFF).toString(16)).slice(-2);\n}",
"function GetHash160FromAddr(addr){\n const addrd = Address.fromString(addr);\n var script = bitcore.Script.buildPublicKeyHashOut(addrd).toString()\n script = script.split(\"0x\").pop();//Remove all text before 0x prefix of hash160\n script = script.replace(\" OP_EQUALVERIFY OP_CHECKSIG\",\"\");//Remove opcodes from output\n return script;\n}",
"function encode_addr(v) {\n if (!isString(v) ||\n !(v.length === 0 || v.length === 40)) {\n throw new Error(\"Address must be empty or 40 chars long\");\n }\n return decodeHex(v);\n }",
"function _rsapem_publicKeyToX509HexString(rsaKey) {\n var encodedIdentifier = \"06092A864886F70D010101\";\n var encodedNull = \"0500\";\n var headerSequence = \"300D\" + encodedIdentifier + encodedNull;\n\n var keys = _rsapem_derEncodeNumber(rsaKey.n);\n keys += _rsapem_derEncodeNumber(rsaKey.e);\n\n var keySequence = \"0030\" + _rsapem_encodeLength(keys.length / 2) + keys;\n var bitstring = \"03\" + _rsapem_encodeLength(keySequence.length / 2) + keySequence;\n\n var mainSequence = headerSequence + bitstring;\n\n return \"30\" + _rsapem_encodeLength(mainSequence.length / 2) + mainSequence;\n}",
"function negbigint2behex(intvalue) {\n if (intvalue >= 0) // ONLY NEGATIVE!\n return null;\n x = intvalue;\n /*\n // https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx\n The BigInteger structure assumes that negative values are stored by using two's complement representation. Because the BigInteger structure represents a numeric value with no fixed length, the BigInteger(Byte[]) constructor always interprets the most significant bit of the last byte in the array as a sign bit. To prevent the BigInteger(Byte[]) constructor from confusing the two's complement representation of a negative value with the sign and magnitude representation of a positive value, positive values in which the most significant bit of the last byte in the byte array would ordinarily be set should include an additional byte whose value is 0. For example, 0xC0 0xBD 0xF0 0xFF is the little-endian hexadecimal representation of either -1,000,000 or 4,293,967,296. Because the most significant bit of the last byte in this array is on, the value of the byte array would be interpreted by the BigInteger(Byte[]) constructor as -1,000,000. To instantiate a BigInteger whose value is positive, a byte array whose elements are 0xC0 0xBD 0xF0 0xFF 0x00 must be passed to the constructor.\n */\n //x=-1000000; // must become (big endian) \"f0bdc0\" => little endian C0 BD F0 (careful with positive 4,293,967,296 that may become negative, need to be C0 BD F0 FF 00)\n // ASSERT (x < 0) !!! x==0 is problematic! equals to 256...\n //x=-1; // ff\n //x=-2; // fe\n //x=-127; // 81\n //x=-255; // \"ff01\" => 01 ff\n //x=-256; // \"ff00\" => 00 ff\n //x=-257; // \"feff\" => ff fe\n //x=-128; // \"ff80\" => 80 ff\n // only for negative integers\n x *= -1; // turn into positive\n // ========================\n // perform two's complement\n // ========================\n // convert to binary\n y = x.toString(2);\n //console.log(\"FIRST BINARY: \"+y);\n // extra padding for limit cases (avoid overflow)\n y = \"0\" + y;\n //guarantee length must be at least 8, or add padding!\n while ((y.length < 8) || (y.length % 8 != 0)) {\n //console.log(\"ADDING PADDING 1!\");\n y = \"0\" + y;\n }\n // invert bits\n y2 = \"\";\n for (i = 0; i < y.length; i++)\n y2 += y[i] == '0' ? '1' : '0';\n //console.log(\"SECOND BINARY: \"+y2);\n // go back to int\n y3 = parseInt(y2, 2);\n //console.log(\"INT is \"+y3);\n // sum 1\n y3 += 1;\n //console.log(\"INT is after sum \"+y3);\n // convert to binary again\n y4 = y3.toString(2);\n //guarantee length must be at least 8, or add padding!\n while (y4.length < 8) {\n //console.log(\"ADDING PADDING!\");\n y4 = \"0\" + y4;\n }\n ///// verify if most important bit in LAST byte would is already set... (NO NEED.. ONLY FOR POSITIVE INTEGERS)\n //index = y4.length-8;\n //if(y4[index]=='0') {\n //console.log(\"CREATING EXTRA BYTE! BUT HOW?\");\n // must create an extra byte just to inform sign...\n //y4=\"10000000\"+y4; // could be 1xxxxxxx I guess, but everyone is just using f0 (which is 11110000)...\n //}\n\n //console.log(\"final binary:\"+y4);\n\n // convert to hex\n y5 = parseInt(y4, 2).toString(16);\n // adjust padding\n\n return revertHexString(y5); // big endian\n}",
"function toHex$1(requestId) {\n return blobToHex(requestId);\n}",
"function intToHex(integer){if(integer<0){throw new Error('Invalid integer as argument, must be unsigned!');}var hex=integer.toString(16);return hex.length%2?\"0\"+hex:hex;}",
"function hexAsciiToStr(hexAscii)\n{\n\t// Force conversion of hexAscii to string\n\tvar hex = hexAscii.toString();\n\tvar str = '';\n\tfor (var i = 0; i < hex.length; i=i+2)\n\t\tstr += String.fromCharCode(parseInt(hex.substr(i, 2), 16));\n\treturn str;\n}",
"function sha256_encode_bytes() {\n var j = 0;\n var output = new Array(32);\n for (var i = 0; i < 8; i++) {\n output[j++] = ((ihash[i] >>> 24) & 0xff);\n output[j++] = ((ihash[i] >>> 16) & 0xff);\n output[j++] = ((ihash[i] >>> 8) & 0xff);\n output[j++] = (ihash[i] & 0xff);\n }\n return output;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Value of the toggle group. | get value() {
const selected = this._selectionModel ? this._selectionModel.selected : [];
if (this.multiple) {
return selected.map(toggle => toggle.value);
}
return selected[0] ? selected[0].value : undefined;
} | [
"getValue() {\n return this.node.value;\n }",
"handleGetValueClick() {\n const value = this.refs.cbTestGetValue.getValue();\n alert('Checkbox value: ' + value);\n }",
"function getRadioGroupVal(name) {\n return $('input:radio[name=\"' + name + '\"]:checked').val();\n }",
"function getCheckboxValue(event){\n\t\t\tif(event.target.checked){\n\t\t\t\tresult = event.target.value;\n\t\t\t}\n\t\t}",
"function getToggledIndex() {\n var i = 0;\n for (var obj of children) {\n if (typeof obj.isToggled != \"undefined\" && obj.isToggled())\n return i;\n i += 1;\n }\n return -1;\n }",
"_handleNumberCheckboxClick(e) {\n this.showNumber = dom(e).rootTarget.checked;\n }",
"getDisplayValue() {}",
"isSelected() {\n return this.selected;\n }",
"function getStateLabel(){\n\t\t/*jshint validthis:true */\n\t\tif (! this.state){\n\t\t\treturn \"off\";\n\t\t}\n\n\t\tvar position = (_dec2bin(this.state).length - 1).toString(),\n\t\t\tlabels = _.invert(this.conditions);\n\n\t\treturn labels[position];\n\t}",
"getRawValue() {\n return this.value;\n }",
"getStateNumber(){\r\n\t\tvar temp = this.name.slice(1,this.name.length);\r\n\t\treturn(parseInt(temp));\r\n\t}",
"static get radioButton() {}",
"getStatValue(statEnum){\n verifyType(statEnum, TYPES.number);\n return this.stats.get(statEnum).getValue();\n }",
"static set radioButton(value) {}",
"getLabel() { return this.labelP.innerText; }",
"switchAfterZero(val) {\n /*\n Override by component\n */\n return val\n }",
"function updateElementValue(el) {\n const isAllSelected = el.children.find(child => !child.value);\n let res = 1;\n if (isAllSelected) {\n res = 0;\n }\n el.value = res;\n}",
"onSliderValueChanged() {\n this.setBase();\n const label = `${this.name}: ${JSON.stringify(this.value)}`;\n ChromeGA.event(ChromeGA.EVENT.SLIDER_VALUE, label);\n }",
"function getActiveItemValue()/*:**/ {\n return AS3.getBindable(this,\"activeItemValueExpression\").getValue();\n }",
"isValue() {\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Walk the Collada tree and flatten the bones into a list, extract the position, quat and scale from the matrix | function flattenSkeleton(skeleton) {
var list = [];
var walk = function(parentid, node, list) {
var bone = {};
bone.name = node.sid;
bone.parent = parentid;
bone.matrix = node.matrix;
var data = [new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3()];
bone.matrix.decompose(data[0],data[1],data[2]);
bone.pos = [data[0].x,data[0].y,data[0].z];
bone.scl = [data[2].x,data[2].y,data[2].z];
bone.rotq = [data[1].x,data[1].y,data[1].z,data[1].w];
list.push(bone);
for(var i in node.nodes) {
walk(node.sid,node.nodes[i],list);
}
};
walk(-1,skeleton,list);
return list;
} | [
"function Bone(/**\n * defines the bone name\n */name,skeleton,parentBone,localMatrix,restPose,baseMatrix,index){if(parentBone===void 0){parentBone=null;}if(localMatrix===void 0){localMatrix=null;}if(restPose===void 0){restPose=null;}if(baseMatrix===void 0){baseMatrix=null;}if(index===void 0){index=null;}var _this=_super.call(this,name,skeleton.getScene())||this;_this.name=name;/**\n * Gets the list of child bones\n */_this.children=new Array();/** Gets the animations associated with this bone */_this.animations=new Array();/**\n * @hidden Internal only\n * Set this value to map this bone to a different index in the transform matrices\n * Set this value to -1 to exclude the bone from the transform matrices\n */_this._index=null;_this._absoluteTransform=new BABYLON.Matrix();_this._invertedAbsoluteTransform=new BABYLON.Matrix();_this._scalingDeterminant=1;_this._worldTransform=new BABYLON.Matrix();_this._needToDecompose=true;_this._needToCompose=false;_this._skeleton=skeleton;_this._localMatrix=localMatrix?localMatrix.clone():BABYLON.Matrix.Identity();_this._restPose=restPose?restPose:_this._localMatrix.clone();_this._baseMatrix=baseMatrix?baseMatrix:_this._localMatrix.clone();_this._index=index;skeleton.bones.push(_this);_this.setParent(parentBone,false);if(baseMatrix||localMatrix){_this._updateDifferenceMatrix();}return _this;}",
"_initBoneAabbs(morphTargets) {\r\n\r\n this.boneAabb = [];\r\n this.boneUsed = [];\r\n var numVerts = this.vertexBuffer.numVertices;\r\n var i, j, k, l;\r\n var x, y, z;\r\n var bMax, bMin;\r\n var boneMin = [];\r\n var boneMax = [];\r\n var boneUsed = this.boneUsed;\r\n var numBones = this.skin.boneNames.length;\r\n var aabb;\r\n var boneWeight, boneIndex;\r\n var minMorphX, minMorphY, minMorphZ;\r\n var maxMorphX, maxMorphY, maxMorphZ;\r\n var dx, dy, dz;\r\n var target;\r\n\r\n // start with empty bone bounds\r\n for (i = 0; i < numBones; i++) {\r\n boneMin[i] = new Vec3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);\r\n boneMax[i] = new Vec3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);\r\n }\r\n\r\n // access to mesh from vertex buffer\r\n var iterator = new VertexIterator(this.vertexBuffer);\r\n var posElement = iterator.element[SEMANTIC_POSITION];\r\n var weightsElement = iterator.element[SEMANTIC_BLENDWEIGHT];\r\n var indicesElement = iterator.element[SEMANTIC_BLENDINDICES];\r\n\r\n\r\n // Find bone AABBs of attached vertices\r\n for (j = 0; j < numVerts; j++) {\r\n for (k = 0; k < 4; k++) {\r\n boneWeight = weightsElement.array[weightsElement.index + k];\r\n if (boneWeight > 0) {\r\n boneIndex = indicesElement.array[indicesElement.index + k];\r\n boneUsed[boneIndex] = true;\r\n\r\n x = posElement.array[posElement.index];\r\n y = posElement.array[posElement.index + 1];\r\n z = posElement.array[posElement.index + 2];\r\n\r\n // adjust bounds of a bone by the vertex\r\n bMax = boneMax[boneIndex];\r\n bMin = boneMin[boneIndex];\r\n\r\n if (bMin.x > x) bMin.x = x;\r\n if (bMin.y > y) bMin.y = y;\r\n if (bMin.z > z) bMin.z = z;\r\n\r\n if (bMax.x < x) bMax.x = x;\r\n if (bMax.y < y) bMax.y = y;\r\n if (bMax.z < z) bMax.z = z;\r\n\r\n if (morphTargets) {\r\n\r\n // find maximum displacement of the vertex by all targets\r\n minMorphX = maxMorphX = x;\r\n minMorphY = maxMorphY = y;\r\n minMorphZ = maxMorphZ = z;\r\n\r\n // morph this vertex by all morph targets\r\n for (l = 0; l < morphTargets.length; l++) {\r\n target = morphTargets[l];\r\n\r\n dx = target.deltaPositions[j * 3];\r\n dy = target.deltaPositions[j * 3 + 1];\r\n dz = target.deltaPositions[j * 3 + 2];\r\n\r\n if (dx < 0) {\r\n minMorphX += dx;\r\n } else {\r\n maxMorphX += dx;\r\n }\r\n\r\n if (dy < 0) {\r\n minMorphY += dy;\r\n } else {\r\n maxMorphY += dy;\r\n }\r\n\r\n if (dz < 0) {\r\n minMorphZ += dz;\r\n } else {\r\n maxMorphZ += dz;\r\n }\r\n }\r\n\r\n if (bMin.x > minMorphX) bMin.x = minMorphX;\r\n if (bMin.y > minMorphY) bMin.y = minMorphY;\r\n if (bMin.z > minMorphZ) bMin.z = minMorphZ;\r\n\r\n if (bMax.x < maxMorphX) bMax.x = maxMorphX;\r\n if (bMax.y < maxMorphY) bMax.y = maxMorphY;\r\n if (bMax.z < maxMorphZ) bMax.z = maxMorphZ;\r\n }\r\n }\r\n }\r\n iterator.next();\r\n }\r\n\r\n // store bone bounding boxes\r\n for (i = 0; i < numBones; i++) {\r\n aabb = new BoundingBox();\r\n aabb.setMinMax(boneMin[i], boneMax[i]);\r\n this.boneAabb.push(aabb);\r\n }\r\n }",
"function AABBTree() {}",
"function toTHREEAnimation( bones ) {\n\n\t\t\tvar tracks = [];\n\n\t\t\t// create a position and quaternion animation track for each node\n\n\t\t\tfor ( var i = 0; i < bones.length; i ++ ) {\n\n\t\t\t\tvar bone = bones[ i ];\n\n\t\t\t\tif ( bone.type === 'ENDSITE' )\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// track data\n\n\t\t\t\tvar times = [];\n\t\t\t\tvar positions = [];\n\t\t\t\tvar rotations = [];\n\n\t\t\t\tfor ( var j = 0; j < bone.frames.length; j ++ ) {\n\n\t\t\t\t\tvar frame = bone.frames[ j ];\n\n\t\t\t\t\ttimes.push( frame.time );\n\n\t\t\t\t\t// the animation system animates the position property,\n\t\t\t\t\t// so we have to add the joint offset to all values\n\n\t\t\t\t\tpositions.push( frame.position.x + bone.offset.x );\n\t\t\t\t\tpositions.push( frame.position.y + bone.offset.y );\n\t\t\t\t\tpositions.push( frame.position.z + bone.offset.z );\n\n\t\t\t\t\trotations.push( frame.rotation.x );\n\t\t\t\t\trotations.push( frame.rotation.y );\n\t\t\t\t\trotations.push( frame.rotation.z );\n\t\t\t\t\trotations.push( frame.rotation.w );\n\n\t\t\t\t}\n\n\t\t\t\tif ( scope.animateBonePositions ) {\n\n\t\t\t\t\ttracks.push( new THREE.VectorKeyframeTrack( '.bones[' + bone.name + '].position', times, positions ) );\n\n\t\t\t\t}\n\n\t\t\t\tif ( scope.animateBoneRotations ) {\n\n\t\t\t\t\ttracks.push( new THREE.QuaternionKeyframeTrack( '.bones[' + bone.name + '].quaternion', times, rotations ) );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn new THREE.AnimationClip( 'animation', - 1, tracks );\n\n\t\t}",
"normalize(){\n for (var column = 0; column < 4; column++){\n for(var row = 0; row < 4; row++){\n this.matArray[column][row]\n }\n }\n }",
"_mapMaze () {\n return this.maze.map((row, rowIndex) => {\n const mappedRow = row.map((column, columnIndex) => ({\n row: rowIndex,\n column: columnIndex,\n parent: null,\n value: column,\n f: 0,\n g: 0,\n h: 0\n }))\n\n return mappedRow\n })\n }",
"getFloorMeshes() {\n if ( this.floorMeshes && this.floorMeshes.length > 0 ) {\n return this.floorMeshes; \n } else if ( this.ground ) {\n return [ this.ground ];\n }\n return [];\n }",
"static getHitbox(child) {\r\n if (isser_1.isDisplayObjectContainer(child)) {\r\n const hitboxes = child.getChildren().map(child => this.getHitbox(child));\r\n const allX = [];\r\n const allY = [];\r\n hitboxes.forEach((box) => {\r\n allX.push(box.topLeft.x, box.topRight.x, box.bottomLeft.x, box.bottomRight.x);\r\n allY.push(box.topLeft.y, box.topRight.y, box.bottomLeft.y, box.bottomRight.y);\r\n });\r\n const left = Math.min(...allX);\r\n const right = Math.max(...allX);\r\n const top = Math.min(...allY);\r\n const bottom = Math.max(...allY);\r\n const result = {\r\n topLeft: { x: left, y: top },\r\n topRight: { x: right, y: top },\r\n bottomLeft: { x: left, y: bottom },\r\n bottomRight: { x: right, y: bottom }\r\n };\r\n return result;\r\n }\r\n else {\r\n const matrix = child.worldMatrix;\r\n const topLeft = this.transformPoint(0, 0, matrix);\r\n const topRight = this.transformPoint(child.width, 0, matrix);\r\n const bottomLeft = this.transformPoint(0, child.height, matrix);\r\n const bottomRight = this.transformPoint(child.width, child.height, matrix);\r\n const result = {\r\n topLeft: topLeft,\r\n topRight: topRight,\r\n bottomLeft: bottomLeft,\r\n bottomRight: bottomRight\r\n };\r\n return result;\r\n }\r\n }",
"getAllArgsToInterpolateSubmobject() {\n let mobjectHierarchies = [];\n for (let mobjectCopy of this.getCopiesForInterpolation()) {\n let hierarchy = mobjectCopy.getMobjectHierarchy();\n let hierarchyMembersWithPoints = hierarchy.filter(\n submob => submob.points().length > 0\n );\n mobjectHierarchies.push(hierarchyMembersWithPoints);\n }\n let argsList = [];\n for (let i = 0; i < mobjectHierarchies[0].length; i++) {\n argsList.push(mobjectHierarchies.map(h => h[i]));\n }\n return argsList;\n }",
"static GetPlanes(transform) {\n const frustumPlanes = [];\n for (let index = 0; index < 6; index++) {\n frustumPlanes.push(new Plane_1.Plane(0.0, 0.0, 0.0, 0.0));\n }\n Frustum.GetPlanesToRef(transform, frustumPlanes);\n return frustumPlanes;\n }",
"split () {\n\n const subWidth = this.bounds.width / 2\n const subHeight = this.bounds.height / 2\n const x = this.bounds.x\n const y = this.bounds.y\n\n this.nodes[0] = new QuadTree(this.level+1, new Rectangle(x + subWidth, y, subWidth, subHeight) )\n this.nodes[1] = new QuadTree(this.level+1, new Rectangle(x, y, subWidth, subHeight) )\n this.nodes[2] = new QuadTree(this.level+1, new Rectangle(x, y + subHeight, subWidth, subHeight) )\n this.nodes[3] = new QuadTree(this.level+1, new Rectangle(x + subWidth, y + subHeight, subWidth, subHeight) )\n\n }",
"function forEachDepthMaterial(cb) {\n\t\t\tcb(_depthMaterial);\n\t\t\tfor(var i = 1; i < _depthMaterial.variants.length; i++) {\n\t\t\t\tcb(_depthMaterial.variants[i]);\n\t\t\t}\n\t\t}",
"static _get2DFootprint (meshes, scene) {\n var mat1 = new BABYLON.PBRMaterial('mat1', scene)\n mat1.albedoColor = BABYLON.Color3.FromHexString('#f5f5f5').toLinearSpace() \n mat1.metallic = 1\n mat1.roughness = 0.2\n var mat2 = new BABYLON.PBRMaterial('mat2', scene)\n mat2.albedoColor = BABYLON.Color3.FromHexString('#adadad').toLinearSpace() \n mat2.metallic = 1\n mat2.roughness = 0.2\n\n var multimat = new BABYLON.MultiMaterial('MaterialLayer1', scene)\n multimat.subMaterials.push(mat1)\n multimat.subMaterials.push(mat2)\n\n const box = BABYLON.Mesh.MergeMeshes(meshes, true, true, undefined, true)\n // box.metadata = { isFootprint: true }\n box.material = multimat\n // box.material = mat1\n for (let i = 0; i < box.subMeshes.length; i++) {\n if (i % 2 === 0) {\n box.subMeshes[i].materialIndex = 1\n }\n }\n\n return box\n }",
"parsePerspective(children, indexPerspective)\n {\n \t// default values\n var id=\"\";\n var near=0;\n var far=0;\n var angle=0;\n\n // reads the values from xml file\n id=this.reader.getString(children[indexPerspective],'id');\n near=this.reader.getFloat(children[indexPerspective],'near');\n far=this.reader.getFloat(children[indexPerspective],'far');\n angle=this.reader.getFloat(children[indexPerspective],'angle');\n \n // error handling \n if (!(near != null && !isNaN(near))) {\n near = 0.1;\n this.onXMLMinorError(\"unable to parse value for near plane; assuming 'near = 0.1'\");\n }\n else if (!(far != null && !isNaN(far))) {\n far = 500;\n this.onXMLMinorError(\"unable to parse value for far plane; assuming 'far = 500'\");\n }\n else if (!(angle != null && !isNaN(far))) {\n angle = 30;\n this.onXMLMinorError(\"unable to parse value for angle plane; assuming 'far = 500'\");\n }\n\n if (near >= far)\n return \"'near' must be smaller than 'far'\";\n\n // default values\n var from = [];\n var to = [];\n \n // access to 'from' and 'to'\n var persChildren = children[indexPerspective].children;\n var persNodeNames = [];\n\n for (var i = 0; i < persChildren.length; i++)\n persNodeNames.push(persChildren[i].nodeName);\n \n var fromIndex = persNodeNames.indexOf(\"from\");\n var toIndex = persNodeNames.indexOf(\"to\");\n\n // error handling\n if (fromIndex == -1)\n this.onXMLMinorError(\"from undefined\");\n \n // reading values from the xml related to 'from'\n else {\n var fx = this.reader.getFloat(persChildren[fromIndex], 'x');\n var fy = this.reader.getFloat(persChildren[fromIndex], 'y');\n var fz = this.reader.getFloat(persChildren[fromIndex], 'z');\n from.push(fx); from.push(fy); from.push(fz);\n }\n // error handling\n if (toIndex == -1)\n this.onXMLMinorError(\"to undefined\");\n \n // reading values from the xml related to 'to'\n else {\n var tx = this.reader.getFloat(persChildren[toIndex], 'x');\n var ty = this.reader.getFloat(persChildren[toIndex], 'y');\n var tz = this.reader.getFloat(persChildren[toIndex], 'z');\n to.push(tx); to.push(ty); to.push(tz);\n }\n\n // error handling - check if there aren´t repeated ids\n if (this.perspectives.hasOwnProperty(id))\n this.onXMLMinorError(\"id of perspective duplicated, initial perspective overwritten\");\n \n //save data \n this.perspectives[id] = [angle*degToRad, near, far, from, to];\n\n return id;\n }",
"buildMaterials () {\n this._meshes.forEach((mesh) => {\n let material = mesh.material;\n\n let position = new THREE.PositionNode();\n let alpha = new THREE.FloatNode(1.0);\n let color = new THREE.ColorNode(0xEEEEEE);\n\n // Compute transformations\n material._positionVaryingNodes.forEach((varNode) => {\n position = new THREE.OperatorNode(\n position,\n varNode,\n THREE.OperatorNode.ADD\n );\n });\n\n let operator;\n material._transformNodes.forEach((transNode) => {\n position = getOperatornode(\n position,\n transNode.get('node'),\n transNode.get('operator')\n );\n });\n\n // Compute alpha\n material._alphaVaryingNodes.forEach((alphaVarNode) => {\n alpha = new THREE.OperatorNode(\n alpha,\n alphaVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._alphaNodes.forEach((alphaNode) => {\n alpha = getOperatornode(\n alpha,\n alphaNode.get('node'),\n alphaNode.get('operator')\n );\n });\n\n // Compute color\n material._colorVaryingNodes.forEach((colorVarNode) => {\n color = new THREE.OperatorNode(\n color,\n colorVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._colorNodes.forEach((colorNode) => {\n color = getOperatornode(\n color,\n colorNode.get('node'),\n colorNode.get('operator')\n );\n });\n\n // To display surfaces like 2D planes or iso-surfaces whatever\n // the point of view\n mesh.material.side = THREE.DoubleSide;\n\n // Set wireframe status and shading\n if (mesh.type !== 'LineSegments' && mesh.type !== 'Points') {\n mesh.material.wireframe = this._wireframe;\n mesh.material.shading = this._wireframe\n ? THREE.SmoothShading\n : THREE.FlatShading;\n } else {\n mesh.material.wireframe = false;\n // Why ?\n // mesh.material.shading = THREE.SmoothShading;\n }\n\n // Get isoColor node\n mesh.material.transform = position;\n mesh.material.alpha = alpha;\n mesh.material.color = color;\n mesh.material.build();\n });\n }",
"function transformation(objects, matrix, scaleRadius=false) {\r\n objects.forEach(item => {\r\n switch(item.type) {\r\n case \"line\":\r\n transform(item, \"p1x\", \"p1y\", matrix);\r\n transform(item, \"p2x\", \"p2y\", matrix);\r\n break;\r\n case \"circle\":\r\n transform(item, \"centerx\", \"centery\", matrix);\r\n if(scaleRadius)\r\n item.radius = item.radius*matrix[0][0];\r\n break;\r\n case \"curve\":\r\n transform(item, \"p1x\", \"p1y\", matrix);\r\n transform(item, \"p2x\", \"p2y\", matrix);\r\n transform(item, \"p3x\", \"p3y\", matrix);\r\n transform(item, \"p4x\", \"p4y\", matrix);\r\n break;\r\n }\r\n })\r\n}",
"function readFrameData( data, frameTime, bone ) {\n\n\t\t\t// end sites have no motion data\n\n\t\t\tif ( bone.type === 'ENDSITE' ) return;\n\n\t\t\t// add keyframe\n\n\t\t\tvar keyframe = {\n\t\t\t\ttime: frameTime,\n\t\t\t\tposition: new THREE.Vector3(),\n\t\t\t\trotation: new THREE.Quaternion()\n\t\t\t};\n\n\t\t\tbone.frames.push( keyframe );\n\n\t\t\tvar quat = new THREE.Quaternion();\n\n\t\t\tvar vx = new THREE.Vector3( 1, 0, 0 );\n\t\t\tvar vy = new THREE.Vector3( 0, 1, 0 );\n\t\t\tvar vz = new THREE.Vector3( 0, 0, 1 );\n\n\t\t\t// parse values for each channel in node\n\n\t\t\tfor ( var i = 0; i < bone.channels.length; i ++ ) {\n\n\t\t\t\tswitch ( bone.channels[ i ] ) {\n\n\t\t\t\tcase 'Xposition':\n\t\t\t\t\tkeyframe.position.x = parseFloat( data.shift().trim() );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Yposition':\n\t\t\t\t\tkeyframe.position.y = parseFloat( data.shift().trim() );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Zposition':\n\t\t\t\t\tkeyframe.position.z = parseFloat( data.shift().trim() );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Xrotation':\n\t\t\t\t\tquat.setFromAxisAngle( vx, parseFloat( data.shift().trim() ) * Math.PI / 180 );\n\t\t\t\t\tkeyframe.rotation.multiply( quat );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Yrotation':\n\t\t\t\t\tquat.setFromAxisAngle( vy, parseFloat( data.shift().trim() ) * Math.PI / 180 );\n\t\t\t\t\tkeyframe.rotation.multiply( quat );\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'Zrotation':\n\t\t\t\t\tquat.setFromAxisAngle( vz, parseFloat( data.shift().trim() ) * Math.PI / 180 );\n\t\t\t\t\tkeyframe.rotation.multiply( quat );\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tconsole.warn( 'THREE.BVHLoader: Invalid channel type.' );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// parse child nodes\n\n\t\t\tfor ( var i = 0; i < bone.children.length; i ++ ) {\n\n\t\t\t\treadFrameData( data, frameTime, bone.children[ i ] );\n\n\t\t\t}\n\n\t\t}",
"function cells_of_thermos(thermos){\n var res = new Array(thermos.length);\n\n for(var i = 0; i < thermos.length; i++){\n res[i] = new Array();\n\n var p = thermos[i].bulb;\n res[i].push(p);\n\n for(var j = 0; j < thermos[i].path.length; j++){\n build_path(p, thermos[i].path[j]).forEach(function(p){\n res[i].push(p);\n });\n\n p = thermos[i].path[j];\n }\n }\n\n return res;\n}",
"function acarbajaLeaf(textures){\n \n \n // bezier surface to map leaf image onto. this surface is like a saddle\n var topToBottom = [ \n [ [0,0,0], [1,0,0], [2,0,0], [3,0,0] ],\n [ [0,2,1], [1,0,1], [2,0,1], [3,2,1] ],\n [ [0,2,2], [1,0,2], [2,0,2], [3,2,2] ],\n [ [0,0,4], [1,0,4], [2,0,4], [3,2,4] ],\n ];\n\n\n var surfGeom = new THREE.BezierSurfaceGeometry( topToBottom.reverse(), 10, 10 );\n var surfMat = new THREE.MeshPhongMaterial({color: \"#f2af55\",\n shininess: 20,\n transparent: true,\n side: THREE.DoubleSide,\n map: textures[3] \n });\n\n var surf = new THREE.Mesh( surfGeom, surfMat );\n \n return surf;\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show a `:double` in exponential (scientific) notation. The optional `precision` (= `17`) specifies the precision. If `>=0` it specifies the number of digits behind the dot (up to `17` max). If negative, then at most the absolute value of `precision` digits behind the dot are used. | function show_exp(d, precision) /* (d : double, precision : ?int) -> string */ {
var _precision_17864 = (precision !== undefined) ? precision : -17;
return show_expx(d, $std_core._int_to_int32(_precision_17864));
} | [
"function show_fixed(d, precision) /* (d : double, precision : ?int) -> string */ {\n var _precision_17876 = (precision !== undefined) ? precision : -2;\n var dabs = Math.abs(d);\n var _x27 = (((dabs < (1.0e-15))) || ((dabs > (1.0e21))));\n if (_x27) {\n return show_exp(d, _precision_17876);\n }\n else {\n return show_fixedx(d, $std_core._int_to_int32(_precision_17876));\n }\n}",
"function ep(x) { return Number(x.toFixed(5)).toString(); }",
"function scientific(int) {\n // convert d to scientific power notation with \"e\"\n if (int !== 0) {\n var log = Math.floor(Math.log10(int));\n return \"<span>\" + (int / Math.pow(10, log)).toFixed(2) + \"e\" + log\n + \"</span>\"\n }\n return \"<span>\" + int.toFixed(2) + \"</span>\";\n}",
"function _formatExp( exp, e ) {\n return (\n (exp <= -10) ? e+\"-\" + -exp :\n (exp < 0) ? e+\"-0\" + -exp :\n (exp >= 10) ? e+\"+\" + exp :\n e+\"+0\" + exp\n );\n}",
"function precision_function() {\n var a = 1234567.89876543210;\n document.getElementById(\"precision\").innerHTML = a.toPrecision(10);\n}",
"function format( n, i, k ) { // 934\n var d, str, z, // 935\n e = ( n = new BigNumber(n) )['e']; // 936\n // 937\n // i == null when toExponential(no arg), or toString() when x >= toExpPos etc. // 938\n if ( i == null ) { // 939\n d = 0; // 940\n } else { // 941\n rnd( n, ++i, ROUNDING_MODE ); // 942\n // 943\n // n['e'] may have changed if the value was rounded up. // 944\n d = k ? i : i + n['e'] - e; // 945\n e = n['e']; // 946\n } // 947\n str = coefficientToString( n['c'] ); // 948\n // 949\n // toPrecision returns exponential notation if the number of significant digits specified // 950\n // is less than the number of digits necessary to represent the integer part of the value // 951\n // in normal notation. // 952\n // 953\n // Exponential notation. // 954\n if ( k == 1 || k == 2 && ( i <= e || e <= TO_EXP_NEG ) ) { // 955\n // 956\n // Append zeros? // 957\n for ( ; str.length < d; str += '0' ); // 958\n if ( str.length > 1 ) str = str.charAt(0) + '.' + str.slice(1); // 959\n str += ( e < 0 ? 'e' : 'e+' ) + e; // 960\n // 961\n // Fixed point notation. // 962\n } else { // 963\n k = str.length; // 964\n // 965\n // Negative exponent? // 966\n if ( e < 0 ) { // 967\n z = d - k; // 968\n // 969\n // Prepend zeros. // 970\n for ( ; ++e; str = '0' + str ); // 971\n str = '0.' + str; // 972\n // 973\n // Positive exponent? // 974\n } else { // 975\n // 976\n if ( ++e > k ) { // 977\n z = d - e; // 978\n // 979\n // Append zeros. // 980\n for ( e -= k; e-- ; str += '0' ); // 981\n if ( z > 0 ) str += '.'; // 982\n } else { // 983\n z = d - k; // 984\n // 985\n if ( e < k ) { // 986\n str = str.slice( 0, e ) + '.' + str.slice(e); // 987\n } else if ( z > 0 ) { // 988\n str += '.'; // 989\n } // 990\n } // 991\n } // 992\n // 993\n // Append more zeros? // 994\n if ( z > 0 ) for ( ; z--; str += '0' ); // 995\n } // 996\n return n['s'] < 0 && n['c'][0] ? '-' + str : str; // 997\n } // 998",
"function convertFloatG( width, padChar, rightPad, signChar, v, precision, eSym ) {\n if (v < 0) { signChar = \"-\"; v = -v }\n if (precision === 0) precision = 1;\n\n // pre-round v for magnitude test to know when to convert as a float.\n // Since rouding is expensive, only round if likely to be needed\n var roundv;\n if (!v) return \"0\";\n if (v >= 1 && v < pow10(precision)) {\n // between 1 and max digits\n var ndigits = countDigits(v);\n roundv = (precision > ndigits)\n ? roundv = v + pow10n(precision - ndigits) / 2\n : roundv = v + pow10(ndigits - precision) / 2;\n }\n else if (v < 1 && v >= .000004) { // .0001 - .5 round - .1 guard\n var zeros = countLeadingZeros(v);\n roundv = v + pow10n(precision + zeros) / 2;\n }\n // else will be converted as exponential, which is rounded below\n\n // values between .0001 and 10^precision are converted as %f float\n // with trailing zeros to the right of the decimal point omitted\n if (roundv >= .0001 && roundv < pow10(precision)) {\n precision = (roundv && roundv < 1)\n ? precision + countLeadingZeros(v)\n : precision - countDigits(roundv);\n var s = formatFloatTruncate(roundv, precision, true, false);\n return padNumber(width, padChar, rightPad, signChar, s);\n }\n // values outside the range .0001 to 10^precision are converted as %e exponential\n // with trailing decimal zeros omitted\n else {\n // 123.4567 prec=2 at 10.6m/s\n // exponential notation, round once converted, correct any overflow\n var ve = _normalizeExp(v); // normalize to exponential format\n ve.val += pow10n(precision - 1) / 2; // round the fraction\n if (ve.val >= 10) { ve.val /= 10; ve.exp += 1 } // add overflow from rounding to the int\n\n // keep the leading digit and precision-1 following, truncate the rest\n var s = formatFloatTruncate(ve.val, precision-1, true, false) + _formatExp(ve.exp, eSym);\n return padNumber(width, padChar, rightPad, signChar, s);\n }\n}",
"function expandDecimal(num) {\n return [...String(num)].reduce((acc, e, i) => {\n // If number is zero, ignore it.\n if (Number(e) === 0) return acc;\n\n // Compute the x/y fractional part.\n // <1>\n return [...acc, `${e}/${10 ** i * 10}`];\n }, [])\n .filter(isNotZero);\n}",
"function setPrecision(src, precision) {\n if (src.substring(0, 9) !== \"precision\") {\n return \"precision \" + precision + \" float;\" + src;\n }\n return src;\n}",
"function formatDecimal4(val, n) {\n n = n || 2;\n var str = \"\" + Math.round ( parseFloat(val) * Math.pow(10, n) );\n while (str.length <= n) {\n str = \"0\" + str;\n }\n var pt = str.length - n;\n return str.slice(0,pt) + \".\" + str.slice(pt);\n}",
"function formatDecimal3(val, n) {\n n = n || 2;\n var str = \"\" + Math.round ( parseFloat(val) * Math.pow(10, n) );\n while (str.length <= n) {\n str = \"0\" + str;\n }\n var pt = str.length - n;\n return str.slice(0,pt) + \".\" + str.slice(pt);\n}",
"function setPrecision(version, precision) {\n var semver = semverutils.parseRange(version)[0];\n return stringify(semver, precision);\n}",
"function getEnergy(num, power, secs, formatted){\n var e = num * power * secs / 100;\n var units = ['','k','M','G','T','P','E'];\n var i = 0;\n while(e>100){\n e /= 1000;\n i ++\n }\n if(formatted)\n return e.toFixed(2) + ' ' + units[i];\n return num * power * secs / 100;\n}",
"function toprecision_number_method(number, precision){\n document.getElementById(\"PrecisionNumber\").innerHTML = \"To number \" + number\n + \" it was applied the method toPrecision with a parameter value of \" + precision\n + \", and the result is \" + number.toPrecision(precision);\n}",
"function toRep(str){\n\n str = str.toFixed(12);\n str = (str/1).toPrecision(14);\n\n while( (str[str.length-1] == '0' || str[str.length-1] == '.') && str.length > 1){\n str = str.substring(0, str.length-1);\n }\n\n\n return str;\n}",
"function ExponentialEase(/** Defines the exponent of the function */exponent){if(exponent===void 0){exponent=2;}var _this=_super.call(this)||this;_this.exponent=exponent;return _this;}",
"function SysFmtRoundDecimal() {}",
"function expandedForm(num) {\n const [integral, decimal] = String(num).split('.');\n\n return [\n ...expandIntegral(integral),\n ...expandDecimal(decimal),\n ].join(' + ');\n}",
"function consoleFloatLog(floatNumber)\n {\n var paragraph = document.createElement(\"p\");\n paragraph.innerHTML = floatNumber;\n document.getElementById(\"output\").appendChild(paragraph);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function returns an array of integers created by parsing a stringinput. | function createIntArray(input) {
let inputStringArray = input.split(",");
let inputArray = [];
inputStringArray.forEach((num) => {
inputArray.push(BigInt(num));
});
return inputArray;
} | [
"function extractIntegers(srcstr) {\n return srcstr.split(\" \").map((substr) => parseInt(substr));\n}",
"function getNumberArraysFromString(string) {\r\n\t let array = [];\r\n\t let re = /\\[(.*?)(?=\\])/g;\r\n\t let matches;\r\n\t do {\r\n\t matches = re.exec(string);\r\n\t if(matches)\r\n\t array.push(matches[1].split(',').map(Number));\r\n\t } while (matches);\r\n\t\r\n\t return array;\r\n\t}",
"function intArrayFromString(stringy, dontAddNull, length /* optional */) {\n\tvar ret = (new Runtime.UTF8Processor()).processJSString(stringy);\n\tif (length) {\n\t\tret.length = length;\n\t}\n\tif (!dontAddNull) {\n\t\tret.push(0);\n\t}\n\treturn ret;\n}",
"function makeIntList(str)\n\t{\n\t\tif (!str)\n\t\t\treturn [];\n\n\t\tvar out = [];\n\n\t\t$.each(str.split(','), function(idx, val) {\n\t\t\tout.push(parseFloat(val));\n\t\t});\n\n\t\treturn out.sort();\n\t}",
"function _toIntArray(string) {\n var w1\n , w2\n , u\n , r4 = []\n , r = []\n , i = 0\n , s = string + '\\0\\0\\0' // pad string to avoid discarding last chars\n , l = s.length - 1\n ;\n\n while (i < l) {\n w1 = s.charCodeAt(i++);\n w2 = s.charCodeAt(i + 1);\n\n // 0x0000 - 0x007f code point: basic ascii\n if (w1 < 0x0080) {\n r4.push(w1);\n\n } else\n\n // 0x0080 - 0x07ff code point\n if (w1 < 0x0800) {\n r4.push(((w1 >>> 6) & 0x1f) | 0xc0);\n r4.push(((w1 >>> 0) & 0x3f) | 0x80);\n\n } else\n\n // 0x0800 - 0xd7ff / 0xe000 - 0xffff code point\n if ((w1 & 0xf800) != 0xd800) {\n r4.push(((w1 >>> 12) & 0x0f) | 0xe0);\n r4.push(((w1 >>> 6) & 0x3f) | 0x80);\n r4.push(((w1 >>> 0) & 0x3f) | 0x80);\n\n } else\n\n // 0xd800 - 0xdfff surrogate / 0x10ffff - 0x10000 code point\n if (((w1 & 0xfc00) == 0xd800) && ((w2 & 0xfc00) == 0xdc00)) {\n u = ((w2 & 0x3f) | ((w1 & 0x3f) << 10)) + 0x10000;\n r4.push(((u >>> 18) & 0x07) | 0xf0);\n r4.push(((u >>> 12) & 0x3f) | 0x80);\n r4.push(((u >>> 6) & 0x3f) | 0x80);\n r4.push(((u >>> 0) & 0x3f) | 0x80);\n i++;\n\n } else {\n // invalid char\n }\n\n /* _add integer (four utf-8 value) to array */\n if (r4.length > 3) {\n\n // little endian\n r.push(\n (r4.shift() << 0) | (r4.shift() << 8) | (r4.shift() << 16) | (r4.shift() << 24)\n );\n }\n }\n\n return r;\n }",
"function parseCsvIdsToNumericArray(ids,delimeter){\n\treturn ids.split(delimeter).map(Number);\n}",
"function chunksAsInts(chunks) {\n return chunks.split(',').map(Number);\n}",
"function toArray(num) {\n\tconst a = num.toString().split(\"\");\n\treturn a.map(x => parseInt(x));\n}",
"function array (date) {\n return date.split(/\\s+/).map(function (e) { return parseInt(e, 10) });\n}",
"function inputToArray(inputtedNumber) {\n console.log(inputtedNumber);\n for (let i = 1; i <= inputtedNumber; i++)\n callArray.push(i.toString());\n console.log(callArray);\n}",
"function sumArray(input) {\r\n\tvar operands = [];\r\n\tvar result = [];\r\n\tvar sum = 0;\r\n\r\n\tfor (var i = 1; i < input.length; i++) {\r\n\t\toperands = (input[i].split(' '));\r\n\t\tsum = parseInt(operands[0]) + parseInt(operands[1]);\r\n\t\tresult.push(sum);\r\n\t}\r\n\r\n\treturn result;\r\n}",
"function extractNumber(input, start) {\n if(start >= input.length){\n return [ NaN, -1]\n }\n\n let isNeg = 1; \n let number = 0; \n let i;\n for(i = start; i < input.length; i++) {\n if(input[i] === '-'){\n isNeg = -1;\n }else if(input[i] === '(' || input[i] === ')'){\n break;\n }else {\n number = number * 10 + Number(input[i]); \n }\n }\n return [ isNeg * number, i]\n}",
"function getBatchNums(rangesStr, parseValue) {\n var nums = [];\n var count = 0;\n var ranges = rangesStr.split(\",\");\n _.each(ranges, function (range) {\n var bounds = range.split(\"..\");\n if (bounds.length == 1) {\n if (count == BATCH_LIMIT) {\n return;\n }\n nums.push(parseValue(bounds[0]));\n } else if (bounds.length == 2) {\n var minBound = parseValue(bounds[0]);\n var maxBound = parseValue(bounds[1]);\n for (var i = minBound; i <= maxBound; i++) {\n if (count == BATCH_LIMIT) {\n return;\n }\n nums.push(i);\n count++;\n }\n } else {\n console.log(\"Unexpected number of bounds in range: \" + bounds.length);\n }\n });\n return nums;\n }",
"function hex_str_to_byte_array(in_str) {\n var i\n var out = []\n var str = in_str.replace(/\\s|0x/g, \"\")\n for (i = 0; i < str.length; i += 2) {\n if (i + 1 > str.length) {\n out.push(get_dec_from_hexchar(str.charAt(i)) * 16)\n } else {\n out.push(\n get_dec_from_hexchar(str.charAt(i)) * 16 +\n get_dec_from_hexchar(str.charAt(i + 1))\n )\n }\n }\n return out\n }",
"function convertIntoArray(string){\n return string.split(\" \");\n}",
"castToNumArray(value) {\n if (typeof value === 'number') {\n return [value];\n }\n if (typeof value === 'string') {\n return value.split(',').map((one) => Number(one));\n }\n if (Array.isArray(value)) {\n return value.map((prop) => Number(prop));\n }\n return undefined;\n }",
"function genNumArr(inputArr) {\n let strArr = [];\n let hour = inputArr[0];\n let minute = inputArr[1];\n strArr.push([hour, minute]);\n \n incArr.forEach(inc => {\n minute+=inc;\n if(minute>=.60){\n minute=minute%.60;\n hour+=1;\n }\n if(hour>=24){\n hour=hour%24\n }\n strArr.push([hour, minute]);\n })\n \n return strArr;\n}",
"function identifyArmstrongNumbers(num1, num2) {\n // initialize the array\n let armstrongNumbers = [];\n // loop from NUM1 to NUM2\n for (i = num1; i <= num2; i++) {\n // change the i to a string\n let string = i.toString();\n // initialize total to 0\n let total = 0;\n // loop through each string\n for (j = 0; j < string.length; j++) {\n // change each index of the value to a number\n let number = parseInt(string[j]);\n // add that number to the power of the .LENGTH of the string\n total = total + Math.pow(number, string.length);\n // push the i to the array\n if (total === i) {\n armstrongNumbers.push(i);\n }\n }\n }\n return armstrongNumbers\n}",
"function obtenerArreglo(_INPUT)\n{\ndividir = _INPUT.split(\"\\n\");\narreglo = dividir;\nreturn arreglo;\n}",
"function getIntArray() {\n var intArray = [];\n $('#week-table td').each(function() { \n if($(this).hasClass(\"busy\")){ \n intArray.push(2);\n }\n else if($(this).hasClass(\"free\")){\n intArray.push(1);\n }\n else{\n intArray.push(0);\n };\n });\n return intArray;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION: returns formatted url to a single country's JSON | function getCountryJSON(){
countryNameFormatted = countryName.replace(/ /g, "_");
var countryURL = "https://galvanize-cors-proxy.herokuapp.com/https://travelbriefing.org/"+countryNameFormatted+"?format=json";
return countryURL
} | [
"function flagUrl (country) {\n country = country.split(' ').join('-')\n return \"https://www.countries-ofthe-world.com/flags-normal/flag-of-\"+(country)+\".png\"\n }",
"function getCountryName(place) {\n for (var i = 0; i < place.address_components.length; i++) {\n var addressType = place.address_components[i].types[0];\n if (addressType == 'country') {\n country = place.address_components[i]['long_name'];\n }\n }\n // console.log(\"Current country\" + country);\n}",
"function makeURL2(latt1, long1) {\n url = \"https://api.weatherstack.com/current?access_key=f631c2dd65202e68a5fec5c3549f0b88&query=\" + latt1 + \",\" + long1;\n print(encodeURI(url));\n}",
"function CountryObj(country) {\n this.name = country.name;\n this.region = country.region;\n this.subregion = country.subregion;\n this.capital = country.capital;\n this.langauges = country[\"languages\"][0][\"name\"];\n this.population = country.population;\n this.currencies = country.currencies[0][\"symbol\"];\n this.flag = country.flag;\n}",
"function formatCountry(country) {\n let formattedCountry;\n if (country === 'USA') {\n formattedCountry = 'the United States';\n } else if (country === 'UK') {\n formattedCountry = 'the United Kingdom';\n } else if (country === 'S.Korea') {\n formattedCountry = 'South Korea';\n } else if (country === 'CAR') {\n formattedCountry = 'the Central African Republic';\n } else if (country === 'DRC') {\n formattedCountry = 'the Democratic Republic of the Congo / Congo Kinshasa';\n } else if (country === 'Congo') {\n formattedCountry = 'the Congo Republic / Congo Brazzaville';\n } else if (country === 'U.S. Virgin Islands') {\n formattedCountry = 'the U.S. Virgin Islands';\n } else {\n formattedCountry = country;\n }\n return formattedCountry;\n}",
"function getWeatherApiUrl(latitude, longitude) {\n var apiUrl = \"https://api.wunderground.com/api/1bc2b90471cb41bd/conditions/q/\";\n return apiUrl + latitude + \",\" + longitude + \".json\";\n }",
"function getCountryPopupHTML(name, code, recordcount) {\n var url = \"javascript:void(0);\";\n if (code != \"\") {\n url = \"/search?country=\" + code;\n }\n var imgExample = \"<img src=\\\"placeholders/2014-09-15_08432.png\\\" class=\\\"img-responsive\\\" >\";\n\n var html = \"<a class=\\\"leaflet-link\\\" href=\\\"\" + url + \"\\\"><div class=\\\"leaflet-popup-wrapper\\\"><div class=\\\"leaflet-popup-title\\\">\" + name +\n \"</div><div class=\\\"leaflet-popup-budget-wrapper\\\">\"+charExample+\"No. of documents: <span>\" + recordcount + \"</span></div></div></a>\";\n return html;\n}",
"function createWeatherURL() {\n weatherURL = \"https://api.openweathermap.org/data/2.5/weather?q=\" + city + \",\" + region + \",\" + country + \"&units=imperial&appid=\" + APIKey\n}",
"function getClaytonPaths()\r\n{\r\n let data = {\r\n campus: \"clayton\",\r\n callback: \"initPage\"\r\n };\r\n jsonpRequest(\"https://eng1003.monash/api/campusnav/\", data);\r\n}",
"function getCountryNames(){\n for(let i = 0; i < country_info[\"ref_country_codes\"].length; i++){\n let country = country_info[\"ref_country_codes\"][i][\"country\"];\n countryNames.push(country);\n countryCodes[country] = country_info[\"ref_country_codes\"][i][\"alpha2\"];\n }\n}",
"static buildApiUrl(opts) {\n if (!opts.apiKey) {\n return null;\n }\n const urlBase = 'https://maps.googleapis.com/maps/api/js';\n const params = {\n key: opts.apiKey,\n callback: opts.callback,\n libraries: (opts.libraries || ['places']).join(','),\n client: opts.client,\n v: opts.version || '3.27',\n channel: null,\n language: null,\n region: null,\n };\n const urlParams = _.reduce(params, (result, value, key) => {\n if (value) result.push(`${key}=${value}`);\n return result;\n }, []).join('&');\n\n return `${urlBase}?${urlParams}`;\n }",
"formatUrl(date) {\n return this.url.replace(/\\{\\{([^}]+)\\}\\}/, (_, fmt) => strftime(date, fmt))\n }",
"function getGoalsByCountry(){\n\t\tvar country = hashValue;\n\t\tcountry = country.charAt(0).toUpperCase() + country.substring(1);\n\t\tshotsPerCountry = _.where(data, {TEAM: country});\n\t\t$('h1#title').html('All of '+ country + '\\'s goals and shots at the 2014 World Cup mapped: click on the dots for more info')\n\t\t_.each(shotsPerCountry, populateGoals);\n\t}",
"function stripUrlFromJson(jsonObj) {\n var siteIDArray = Object.keys(jsonObj.query.pages);\n // console.log(siteIDArray);\n var siteID = siteIDArray[0];\n // console.log(siteID);\n var output = jsonObj.query.pages[siteID].thumbnail.source;\n // console.log(output);\n return output;\n}",
"function getCountryFromApi(country) {\n if (country === \"faroe islands\") {\n $(\"#js-error-message\").append(\n \"Sorry, there was a problem. Please select a country from the drop-down list!\"\n );\n throw new Error(\n \"Sorry, there was a problem. Please select a country from the drop-down list!\"\n );\n }\n\n const url = `https://agile-oasis-81673.herokuapp.com/api/country/${country}`;\n\n request(url)\n .then((rawCountryData) => {\n let translateRes, geoCodeRes, timeZone1Res, timeZone2Res;\n\n let countryData = findCountry(rawCountryData, country);\n\n $(\"html\").removeClass(\"first-background\");\n $(\"html\").addClass(\"second-background\");\n\n const googleTranslatePromise = googleTranslateApi(countryData).then(\n (res) => {\n translateRes = res;\n }\n );\n\n const geoCodingPromise = geoCodeCapitalApi(countryData)\n .then((res) => {\n geoCodeRes = res;\n return timeZoneApi1(geoCodeRes);\n })\n .then((res) => {\n timeZone1Res = res;\n return timeZoneApi2(timeZone1Res);\n })\n .then((res) => {\n timeZone2Res = res;\n });\n\n Promise.all([googleTranslatePromise, geoCodingPromise]).then(() => {\n $(\"body\").addClass(\"centered\");\n let countryCapital = countryData.capital;\n let countryName = countryData.name;\n displayTimeResults(\n timeZone2Res,\n countryCapital,\n countryName,\n translateRes\n );\n restartButton();\n $(\"header\").addClass(\"hidden\");\n $(\"footer\").addClass(\"hidden\");\n });\n })\n .catch((err) => {\n $(\"#js-error-message\").append(\n \"Sorry, there was a problem. Please select a country from the drop-down list! \" +\n err.message +\n \".\"\n );\n });\n}",
"function getUrl(city, type){\n var count = type === 'weather' ? 1 : 5\n var params = {\n q: city,\n type: 'accurate',\n APPID: _api_key,\n cnt: count,\n units: 'metric'\n }\n return _apiUrl + type + '?' + prepRouteParams(params);\n }",
"function formatLocation(city, state, country, zipCode) {\n return (\n city + \", \" + state + \" \" + zipCode + \" \" + country\n );\n}",
"function getCityName() {\n 'use strict';\n\n var keyGoogle = 'AIzaSyBmCk28nEs1OWXgwS0VQ1752o_cYwrkxHs',\n url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=',\n location = latitude + ',' + longitude;\n\n $.ajax({\n url: url + location,\n type: 'GET',\n dataType: 'json',\n data: {\n //location_type: 'GEOMETRIC_CENTER',\n key: keyGoogle\n }\n }).done(function (googleResponse) {\n $city.text(googleResponse.results[0].formatted_address);\n }).fail(function (googleResponse) {\n Materialize.toast('Cannot get City Name from google', 600);\n });\n}",
"function formUrlRoad(locLat,locLng,apiKey){\n\treturn \t\"https://roads.googleapis.com/v1/nearestRoads?points=\" + locLat + \",\" + locLng + \"&key=\" + apiKey;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns code of given department (full name, code, or alias). Insensitive to capitalization and padding. Returns empty string if no department matches input. | function toDepartmentCode(name) {
var name = trim(name).toUpperCase();
for (var i = 0; i < departments.length; i++) {
var deptObj = departments[i];
if (name === deptObj.full ||
name === deptObj.code ||
deptObj.aliases.indexOf(name) != -1) {
return deptObj.code;
}
}
return "";
} | [
"function findCoursesByDepartment(code) {\n var courseIds = [];\n var courses = coursesByDepartments[code];\n for (var i = 0; i < courses.length; i++) {\n courseIds.push(code + '.' + courses[i].cnum);\n }\n return courseIds;\n}",
"function getDepartmentId(departments, departmentName) {\n for (let i=0; i<departments.length; i++) {\n if (departments[i].name === departmentName) {\n return departments[i].id;\n };\n };\n }",
"static getCurrencyName(code) {\n let currencyName = this.getPhrase(code, \"CurrencyCode\");\n if (currencyName != \"\" && currencyName.length > 0)\n return currencyName;\n else\n return code;\n }",
"function getPostalCode(address) {\r\n\tvar firstCommaPos = address.indexOf(\",\");\r\n\tvar lastCommaPos = address.lastIndexOf(\",\", address.length);\r\n\tif (lastCommaPos != firstCommaPos)\r\n\t\treturn address.substring(firstCommaPos + 2, firstCommaPos + 7);\r\n\telse\r\n\t\treturn \"\";\r\n}",
"async function getDeptByName(deptName) {\n //validates number of arguments\n if (arguments.length != 1) {\n throw new Error(\"Wrong number of arguments\");\n }\n //validates arguments type\n if (!deptName || typeof deptName == \"undefined\" || typeof deptName != \"string\" || deptName.length == 0) {\n throw \"Invalid department name is provided for getDeptByName function\";\n }\n const deptCollection = await dept();\n const department = await deptCollection.findOne({ deptName: deptName });\n if (!department) {\n throw `Department not found with name ${deptName}`;\n }\n \n return department;\n}",
"function CODE() {\n var text = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];\n var index = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];\n\n if (index < 1) return error$2.na;\n if (text.length < index) return error$2.value;\n return text.charCodeAt(index - 1);\n}",
"function getCodeFromKey(key) {\r\n //Constants for key\r\n if (key == STUDENT_INBOX_KEY) return 1;\r\n if (key == ADMIN_INBOX_KEY) return 2;\r\n if (key == STUDENT_SENT_ITEMS_KEY) return 3;\r\n if (key == ADMIN_SENT_ITEMS_KEY) return 4;\r\n}",
"function getNeptunCode() {\n if ($(\"#upTraining_topname\").size() > 0) {\n const input = $(\"#upTraining_topname\").text();\n return input.substring(input.indexOf(\" - \") + 3).toUpperCase();\n }\n}",
"function getCodeFromLetter(str){\n return str.charCodeAt(0)-96;\n}",
"function getScheduleBuilderId(code, courseNumber) {\n var courses = coursesByDepartments[code];\n for (var i = 0; i < courses.length; i++) {\n if (courses[i].cnum === courseNumber) {\n return courses[i].sbid;\n }\n }\n return '';\n}",
"function translateCodeName(translationCodeList, code, defaultName) {\n\tvar name = defaultName;\n\n\tfor( var t in translationCodeList ) {\n\t\tif( translationCodeList[t].code == code ) {\n\t\t\tname = translationCodeList[t].description;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn name;\n}",
"function getUrlCode() {\n\n const param = 'code';\n\n return getUrlParameter( param );\n\n }",
"function get_dcode(){\n\tvar dcode = get_variable_from_query(\"dcode\");\n\tif(dcode){\n\t\t$.ajax({\n\t \ttype: \"GET\",\n\t \turl: \"https://blooom-api-staging.herokuapp.com/discount_codes/\" + dcode,\n\t \tdataType: 'json',\n\t \tsuccess: function (response) {\n\t\t\t\t$(\"#discount_code_id\").val(response.discount_code.id);\n\t \t},\n\t \terror: function (xhr, status, error) {\n\t \t}\n\t });\n\t}\n}",
"function SpeciesToCode(species) {\n var speciesCode;\n \n switch(species){\n case \"DOUGLAS FIR\":\n speciesCode = \"DF\";\n break;\n case \"PONDEROSA PINE\":\n speciesCode = \"WP\";\n break;\n case \"WESTERN RED CEDAR\":\n speciesCode = \"WC\";\n break; \n case \"JACK PINE\":\n speciesCode = \"JP\";\n break;\n case \"LODGEPOLE PINE\":\n speciesCode = \"LP\";\n break; \n case \"RED PINE\":\n speciesCode = \"NP\";\n break;\n //NO CODE YET\n case \"REDWOOD\":\n speciesCode = 'NA REDWOOD';\n break;\n //NO CODE YET\n case \"SITKA SPRUCE\":\n speciesCode = 'NA SITKA';\n break; \n case \"WESTERN FIR\":\n speciesCode = 'NA WESTERN FIR';\n break;\n //NO CODE YET\n case \"WHITE SPRUCE\":\n speciesCode = \"NA WHITE SPRUCE\";\n break; \n case \"ALASKA YELLOW CEDAR\":\n speciesCode = \"YC\";\n break; \n case \"OTHER\":\n speciesCode = \"NA\";\n break; \n case \"SOUTHERN PINE\":\n speciesCode = \"SP\";\n break; \n case \"WESTERN LARCH\":\n speciesCode = \"WL\";\n break; \n default:\n speciesCode = \"NA\"\n break; \n }\n \n return speciesCode;\n}",
"get id() {\n let cityID = this.city\n\n if (cityID === 'Berlin') {\n cityID = 'Frankfurt'\n } else if (cityID.includes('_')) {\n cityID = cityID.replace('_', '-')\n }\n\n return cityID.toLowerCase()\n }",
"function get_currency_code(str) {\n return str.match(/\\((.*?)\\)/)[1];\n}",
"function getLetterFromCode(num){\n return String.fromCharCode(num+96);\n}",
"function findStationCode(stationName, stationLine) {\n let toReturn = \"\";\n for(let i=0; i<stationList.length; i++) {\n let checkingStation = stationList[i];\n if(checkingStation.name === stationName && checkingStation.isOnLine(stationLine)) {\n toReturn = checkingStation.code;\n break;\n }\n }\n\n //Check that we were able to find a return code\n if(toReturn === \"\") {\n //Read the matchupDict to get the station code\n toReturn = matchupDict[stationName];\n }\n\n if(!toReturn) {\n //if we were still unable to find a code to return, we have something wrong!! print something about it\n console.log(\"unable to resolve code for station\", stationName);\n }\n\n return toReturn;\n}",
"static generateAbilityCode(characterCode) {\n switch (characterCode) {\n case 'q': return 'Abilities[1]';\n case 'w': return 'Abilities[2]';\n case 'e': return 'Abilities[3]';\n case 'r': return 'Abilities[4]';\n case 't': return '\"talent\"';\n case 'n': return '\"nil\"';\n default: return '';\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the array of transmitters. | function updateTransmitters(sample) {
for(var transmitterTemp in sample) {
if(!(transmitterTemp in $scope.transmitters) && ($scope.numTransmitters < $scope.maxNumberOfTransmitters)) {
$scope.transmitters[transmitterTemp]; // Adding new transmitters as they come.
$scope.transmitters[transmitterTemp] = { value : transmitterTemp};
$scope.numTransmitters++; // Incrementing the number of receivers.
}
}
} | [
"update() {\n for (let device of this.devices) {\n device.update();\n }\n }",
"function updateRssiArray(sample) {\n for(var receiverTemp in $scope.receivers) {\n var updated = false;\n var seconds = $scope.rssiSeconds;\n \n // Try to update the rssi corresponding to the receiver.\n for(var cRadio = 0;\n cRadio < sample[$scope.transmitterId].radioDecodings.length;\n cRadio++) {\n if(sample[$scope.transmitterId].radioDecodings[cRadio].identifier.value === receiverTemp) {\n var rssi = sample[$scope.transmitterId].radioDecodings[cRadio].rssi;\n \n if($scope.rssiSamples[receiverTemp]) {\n $scope.rssiSamples[receiverTemp].push({ seconds: seconds,\n rssi: rssi });\n }\n else {\n $scope.rssiSamples[receiverTemp] = [];\n $scope.rssiSamples[receiverTemp].push({ seconds: seconds,\n rssi: rssi });\n }\n \n updated = true; \n break;\n }\n }\n \n // If it failed to be updated, push 0 as default.\n if(!updated) {\n if($scope.rssiSamples[receiverTemp]) {\n $scope.rssiSamples[receiverTemp].push({ seconds: seconds,\n rssi: 0 });\n }\n else {\n $scope.rssiSamples[receiverTemp] = [];\n $scope.rssiSamples[receiverTemp].push({ seconds: seconds,\n rssi: 0 });\n }\n }\n \n // If it has reached the maximum number of samples, drop the oldest one.\n if($scope.rssiSamples[receiverTemp].length > $scope.maxNumberOfSamples) {\n $scope.rssiSamples[receiverTemp].shift();\n }\n } \n }",
"function updateServoValues(){\n for( var i = 0; i < servoCount; i++){\n\tupdateServoValue(i);\n }\n}",
"sendBeakers()\n {\n this.socket.emit('sendRandomBeaker', { beakerC: this.randomBeaker.getBeakerContents() });\n\n this.socket.emit('sendPlayerBeaker', { beakerC: this.beaker.getBeakerContents() });\n\n this.socket.emit(\"sendTime\", {timeArray: this.stopwatch.digit_values});\n\n }",
"function updateAll()\n{\n\t//\tUpdate actors\n\tfor (i = 0; i < actors.length; ++i) {\n\t\tactors[i].update();\n\t}\n}",
"function updateRssiSamples(sample) {\n for(var transmitterTemp in $scope.transmitters) {\n if(!(transmitterTemp in $scope.rssiSamples)) {\n $scope.rssiSamples[transmitterTemp];\n $scope.rssiSamples[transmitterTemp] = [];\n }\n if(sample[transmitterTemp]) {\n for(var cRadio = 0;\n cRadio < sample[transmitterTemp].radioDecodings.length;\n cRadio++) {\n var radioDecodingReceiver = sample[transmitterTemp].radioDecodings[cRadio].identifier.value;\n if(radioDecodingReceiver === $scope.receiverId) {\n var rssi = sample[transmitterTemp].radioDecodings[cRadio].rssi;\n $scope.rssiSamples[transmitterTemp].push(rssi);\n updated = true;\n break;\n }\n }\n }\n else {\n $scope.rssiSamples[transmitterTemp].push(0);\n }\n if($scope.rssiSamples[transmitterTemp].length > $scope.maxNumberOfSamples) {\n $scope.rssiSamples[transmitterTemp].shift();\n }\n }\n }",
"function updateReceivers(sample) {\n for(var cRadio = 0;\n cRadio < sample[$scope.transmitterId].radioDecodings.length;\n cRadio++) {\n var receiverTemp = sample[$scope.transmitterId].radioDecodings[cRadio].identifier.value;\n if(!(receiverTemp in $scope.receivers)) {\n var colorTemp = COLORS_ARRAY[cCOlOR_TRANSMITTER++ % COLORS_ARRAY.length];\n $scope.receivers[receiverTemp] = { color: colorTemp, isDrawn: false, isDisplayed: true, latest: 0, receiverId: receiverTemp };\n }\n }\n }",
"refreshAllBuffers() {\n\t\tfor (const attributeName in this.attributes)\n\t\t\tthis.refreshAttribData(attributeName);\n\t}",
"init() {\n let default_input = new Array(8);\n default_input.fill(0);\n\n // Map data to all slave devices using the specific address\n for (var device_name in this.devices) {\n\n // Get the device\n var device = this.devices[device_name];\n\n this.updateDevice(device, default_input);\n\n }\n\n }",
"async function SendingUpdates() {\n var d = new Date();\n console.log('publish sensors updates: ', d)\n console.log('there are: ', Object.keys(users).length, \" users\");\n for (userKey in users) {\n console.log('User: ', userKey)\n var mqttTransmitMsg = JSON.stringify(users[userKey]);\n var extraLogMsg = mqttTransmitMsg.length > 100 ? \" ....}\" : \"\";\n console.log('sending state:', mqttTransmitMsg.substring(0,100), extraLogMsg)\n mqtt_client.publish('virtualsensor/' + userKey, mqttTransmitMsg)\n }\n}",
"function sendData() {\n\n // Get all PID input data and store to right index of charVal\n for(var i = 1; i <= 18; i++) {\n txCharVal[i] = select(inputMap[i]).value;\n }\n\n // Get all control input data and store to right index of exCharVal\n exCharVal[0] = select('#throttle').value;\n\n // Sending PID data with rxChar over BLE\n writeArrayToChar(txChar, txCharVal)\n .then( () => {\n console.log(\"PID data sent:\", txCharVal);\n\n // Sending throttle data with exChar over BLE\n writeArrayToChar(exChar, exCharVal)\n .then( () => {\n console.log(\"Data sent:\", exCharVal);\n })\n .catch( (error) => {\n console.log('Control data sending failed:', error)\n });\n })\n .catch( (error) => {\n console.log('PID data sending failed:', error)\n });\n}",
"updatePreBinded() {\n const id = this.target.id;\n const controllerHandler = this.target.controllerHandler;\n if (!id || !controllerHandler) return;\n\n this.register.forEach((entry, attrName) => {\n if (entry.isPreBinded && !this.isSubscriptionTried(attrName)) {\n const status = new ControllerStatus({ hasChannel: false });\n const channel = `${id}-${attrName}`;\n const value = controllerHandler.subscribe(channel, null, entry.receiverHandler, status);\n\n // Needed for unsubscribe\n if (status.hasChannel) {\n entry.bindedChannel = channel;\n entry.bindedController = controllerHandler;\n }\n if (value != null) entry.update(value);\n }\n });\n }",
"_updatePeers() {\n var peers = this.peers;\n peers.clear();\n mergeMaps(peers, this.ocluster, this.ncluster);\n this.configAry = Array.from(peers);\n peers.delete(this.peerId);\n }",
"updateThrust() {\n this._thrust = this.fuel * 0.04;\n }",
"resend() {\n this.streamStatus = 'initialize';\n this.requester.addToSendList(this.data);\n }",
"updateEnchantments() {\n\t\t\tthis.enchantments.forEach((e) => {\n\t\t\t\t/*\n\t\t\t\t\tThis first method removes old <tw-enchantment> elements...\n\t\t\t\t*/\n\t\t\t\te.disenchant();\n\t\t\t\t/*\n\t\t\t\t\t...and this one adds new ones.\n\t\t\t\t*/\n\t\t\t\te.enchantScope();\n\t\t\t});\n\t\t}",
"sendChatsToList() {\n if (!this._chats)\n return;\n\n this._componenets.chatsList.setChats(this._chats)\n }",
"update ( data ) {\n if ( !this.deepEqual(data, this.data) ) {\n Object.assign(this.data, data);\n this.notify();\n }\n }",
"updateList() {\n console.log(\"$$$$$$$$ updateList\");\n this.forceUpdate();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return ID and ZIP blob for integration/widget to save in API. | async saveFiles ({ commit, state }) {
commit(t.PROJECT_SAVE)
try {
const { id } = state
const blob = await Zip.getBlob()
return { id, blob }
} catch (e) {
throw e
}
} | [
"function store_zip(zip,callback) {\n var postURL = \"/\";\n var postRequest = new XMLHttpRequest();\n\n postRequest.open('POST',postURL);\n postRequest.setRequestHeader('Content-Type','application/json');\n\n postRequest.addEventListener('load', function(event){\n var error;\n if(event.target.status !== 200){\n error = event.target.response;\n }\n callback(error);\n });\n console.log('Zip: ' + zip);\n var post_content = { zipCode: zip.toString(), setting: false, remove: false };\n postRequest.send(JSON.stringify(post_content));\n}",
"function saveAsset(libAsset, formElement){\n let xhr = new XMLHttpRequest();\n\n xhr.onreadystatechange = function() {\n if(xhr.readyState === 4){\n // get the new library asset with a generated id\n var updatedAsset = JSON.parse(xhr.responseText);\n\n // add the new asset to the table\n addAssetToTable(updatedAsset);\n\n // clear the new asset form\n formElement.reset();\n\n // let the user know what the new id is\n alert('Asset created with ID: ' + updatedAsset.assetId);\n }\n }\n\n xhr.open('POST', '/library-api/api/library-asset');\n\n xhr.send(JSON.stringify(libAsset));\n}",
"function getBlobstoreURL() {\n fetch('/blobstore-upload-url')\n .then((response) => {\n return response.text();\n })\n .then((imageUploadUrl) => {\n const commentForm = document.getElementById('donation-form');\n commentForm.action = imageUploadUrl;\n });\n}",
"function getQrImagePathToSave()\n{\n return path.join(__dirname,'../../../client/qr-images/');\n}",
"function Blob(repository, obj) {\n this.repository = repository;\n _immutable(this, obj).set(\"id\").set(\"data\");\n }",
"function DownloadPublished(el_input) {\n console.log( \" ==== DownloadPublished ====\");\n const tblRow = t_get_tablerow_selected(el_input);\n const pk_int = get_attr_from_el_int(tblRow, \"data-pk\");\n\n const data_dict = get_mapdict_from_datamap_by_id(published_map, tblRow.id);\n const filepath = data_dict.filepath\n const filename = data_dict.filename\n console.log( \"filepath\", filepath);\n console.log( \"filename\", filename);\n\n // window.open = '/ticket?orderId=' + pk_int;\n\n // UploadChanges(upload_dict, urls.url_download_published);\n const upload_dict = { published_pk: pk_int};\n if(!isEmpty(upload_dict)) {\n const parameters = {\"upload\": JSON.stringify (upload_dict)}\n let response = \"\";\n $.ajax({\n type: \"POST\",\n url: urls.url_download_published,\n data: parameters,\n dataType:'json',\n success: function (response) {\n var a = document.createElement('a');\n var url = window.URL.createObjectURL(response);\n a.href = url;\n a.download = 'myfile.pdf';\n document.body.append(a);\n a.click();\n a.remove();\n window.URL.revokeObjectURL(url);\n },\n\n\n /*\n success: function (data) {\n //const a = document.createElement('a');\n //const url = window.URL.createObjectURL(data);\n console.log( \"data\");\n console.log( data);\n /*\n a.href = url;\n a.download = 'myfile.pdf';\n document.body.append(a);\n a.click();\n a.remove();\n window.URL.revokeObjectURL(url);\n */\n /*\n var blob = new Blob(data, { type: 'application/pdf' });\n var a = document.createElement('a');\n a.href = window.URL.createObjectURL(blob);\n a.download = filename;\n a.click();\n window.URL.revokeObjectURL(url);\n\n },\n*/\n\n error: function (xhr, msg) {\n // --- hide loader\n el_loader.classList.add(cls_visible_hide)\n console.log(msg + '\\n' + xhr.responseText);\n } // error: function (xhr, msg) {\n }); // $.ajax({\n } // if(!!row_upload)\n\n\n\n\n\n // PR2021-03-06 from https://stackoverflow.com/questions/1999607/download-and-open-pdf-file-using-ajax\n //$.ajax({\n // url: urls.url_download_published,\n // success: download.bind(true, \"<FILENAME_TO_SAVE_WITH_EXTENSION>\", \"application/pdf\")\n // });\n\n //PR2021-03-07 from https://codepen.io/chrisdpratt/pen/RKxJNo\n //This one works, the demo does at least\n /*\n $.ajax({\n url: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/172905/test.pdf',\n method: 'GET',\n xhrFields: {\n responseType: 'blob'\n },\n success: function (data) {\n var a = document.createElement('a');\n var url = window.URL.createObjectURL(data);\n a.href = url;\n a.download = 'myfile.pdf';\n document.body.append(a);\n a.click();\n a.remove();\n window.URL.revokeObjectURL(url);\n }\n });\n */\n\n }",
"function annotationBlob() {\n return new Blob([JSON.stringify(annotationData())], {\n type: \"application/json\",\n });\n }",
"saveNetworkToJson(){\n\n // Networksettings into json object\n const networkSetting = this.client.NN.getNetworkSettings();\n // networkSetting['LossChoice'] = ElementHandler.getElementValFromId(\"lossChoice\");\n // networkSetting['OptimizerChoice'] = ElementHandler.getElementValFromId(\"optimizerChoice\");\n // networkSetting['LearningRate'] = ElementHandler.getElementValFromId(\"learningRate\");\n\n // Create blob from dict\n const jsonFile = JSON.stringify(networkSetting, null, 1);\n const blob = new Blob(\n [ jsonFile ],\n {\n type: \"application/json\"\n }\n );\n const downloadUrl = URL.createObjectURL(blob);\n\n // Get filename and set attr.\n const filename = ElementHandler.getElementValFromId(\"jsonFileName\") + \".json\";\n ElementHandler.setAttrById(\"hrefNetworkModal\", \"download\", filename);\n ElementHandler.setAttrById(\"hrefNetworkModal\", \"href\", downloadUrl);\n\n this.hide();\n }",
"@api get assetId(){\n return this.recordId;\n }",
"getPluginStoreData() {\n return axios.get(Craft.getActionUrl('plugin-store/plugin-store-data'), '', {\n headers: {\n 'X-CSRF-Token': Craft.csrfTokenValue,\n }\n })\n }",
"function storeIBjson(gdun, jsonBodyToStore, callback) {\t\t\t\t\n\n\t// put the data in the ECS bucket\n\tvar params = {\n\t\tBucket: 'installBase',\n\t\tKey: gdun + '.json',\n\t\tBody: JSON.stringify(jsonBodyToStore)\n\t};\t \n\t \n\tecs.putObject(params, function(err, data) {\n\t\tif (err) {\n\t\t\t// an error occurred\n\t\t\tconsole.log('Error in ECS putObject: ' + err, err.stack); \n\t\t} else {\n\t\t\t// successful response\n\t\t\t\n\t\t\ttry {\n\t\t\t\tvar parsedBodyToStore = JSON.parse(jsonBodyToStore);\n\t\t\t\tvar customer = parsedBodyToStore.rows[0].CS_CUSTOMER_NAME;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t} catch (e) {\n\t\t\t\tvar customer = 'not able to retrieve';\n\t\t\t}\t\t\n\t\n\t\t\tconsole.log(gdun + '.json object saved to ECS for customer: ' + customer);\n\t\t\tjsonBodyToStore = null; // free up memory\n\t\t\tcallback(null, customer); // this is the callback saying this storeIBjson function is complete\t\t\t\n\t\t};\n\t});\n}",
"function retrieveHash() {\n window.fileStorageInstance.get.call(function(err, result){\n if (err) {\n console.error('Error getting data: ', err);\n } else if (result) {\n var imageURL = window.ipfsDataHost + \"/\" + result;\n console.log('File: ', result);\n console.log(imageURL);\n } else {\n console.error('No data. Transaction not mined yet?');\n }\n });\n}",
"function getSaveRep() {\n return topBlock.getRep();\n }",
"function savedSavingObject(){\n\t//returns the saved saving object from local storage\n\tvar savingObject = localStorage[\"savingObject\"];\n\tif(savingObject != undefined){\n\t\tsavingObject = JSON.parse(savingObject);\n\t}\n\treturn savingObject;\n<<<<<<< HEAD\n}",
"static save_both (comp) {\n if (comp.object3D) {\n const kid = comp.object3D\n kid.isVisible = true\n const kids = kid.getChildren()\n for (let i = 0; i < kids.length; i++) {\n kids[i].setEnabled(true)\n }\n kids[kids.length - 1].isVisible = false\n\n var myser = BABYLON.SceneSerializer.SerializeMesh(comp.object3D, false, true)\n var jsonData = JSON.stringify(myser)\n\n // Component.doDownload('part.babylon', new Blob([jsonData], { type: 'octet/stream' }))\n return [new Blob([jsonData], { type: 'octet/stream' }), new Blob([jsonData], { type: 'octet/stream' })]\n }\n }",
"function BlockSave() {\n return /*#__PURE__*/React.createElement(InnerBlocks.Content, null);\n }",
"pack(data) {\n Object.assign(data, {\n dataSetId: Utilities.normalizeHex(data.dataSetId.toString('hex').padStart(64, '0')),\n });\n return data;\n }",
"function saveJsonButton(fileSpec, selector) {\n let parent = document.querySelector(selector);\n let a = document.createElement(\"a\");\n let b = document.createElement(\"button\");\n let uc = encodeURIComponent(fileSpec.data);\n let hr = `data:application/json;charset=utf-8,${uc}`;\n a.setAttribute(\"href\", hr);\n a.setAttribute(\"download\", fileSpec.name);\n a.style.visibility = \"hidden\";\n b.innerHTML = `Download file: ${fileSpec.name}`;\n b.onclick = _ => a.click();\n parent.append(a);\n parent.append(b);\n return;\n}",
"function deviceRootSerialize(device_id, datastore_id, root_uuid, device_root) {\n var data_id = datastore_id + '.' + root_uuid;\n var device_root_data_id = (0, _blockstack.makeFullyQualifiedDataId)(device_id, data_id);\n var device_root_data = JSON.stringify(device_root);\n var device_root_blob = (0, _blob.makeDataInfo)(data_id, device_root_data, device_id, device_root_data_id);\n return device_root_blob;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array of all queues. | get queues() {
return Object.keys(this._queues).map(name => this._queues[name]);
} | [
"getQueueNames() {\n return Object.keys(this.queues);\n }",
"async purgeQueues() {\n this.notify.debug('Clear all queues');\n const promises = this.queues.map(queue => queue.purgeQueue());\n await Promise.all(promises);\n }",
"getQueueAsArr(roomId){\n if(!this.isValidRoomId(roomId)){\n return null;\n }\n\n return this.roomsUsed[roomId]['queue'].queue;\n }",
"function ArrayQueue() {}",
"start() {\n this.notify.debug('Start all queues');\n this.started = true;\n for (let queue of this.queues)\n queue.start();\n }",
"stop() {\n this.notify.debug('Stop all queues');\n this.started = false;\n for (let queue of this.queues)\n queue.stop();\n }",
"getQueue(name) {\n assert(name, 'Missing queue name');\n if (!this._queues.hasOwnProperty(name)) {\n const queue = new Queue(this, name);\n if (this.started)\n queue.start();\n this._queues[name] = queue;\n }\n return this._queues[name];\n }",
"function getPlayQueue (pid, range) {\n sendCmd('player/get_queue', {\n pid: '-652946493'\n });\n}",
"function getQueue(lobby, role) {\n if(getPlayer(lobby, role) != undefined)\n return getPlayer(lobby, role).queue;\n}",
"static async getConsumers(req, res) {\n const queueId = req.params.qid;\n const queueIndex = queues.findIndex((queue) => queue.id === queueId);\n\n res.status(200).json({\n status: \"success\",\n data: queues[queueIndex].consumers,\n message: \"Retrieved All Consumers\",\n });\n }",
"function getQueueFromLocalStorage() {\n localforage.getItem(QUEUE_STORAGE_KEY)\n .then((storageItem) => {\n if (storageItem !== null && Array.isArray(storageItem)) {\n analyticsQueue = [...storageItem, ...analyticsQueue].slice(-100);\n }\n })\n .catch(err => log.warn(`Error fetching from localstorage: ${err.message}`));\n}",
"function tasks_queue() {\r\n let q_data = new Queue(1);\r\n q_data.push(4);\r\n q_data.push(8);\r\n q_data.push(9);\r\n q_data.push(19);\r\n\r\n q_data.parse_llist();\r\n let out = q_data.pop();\r\n let out1 = q_data.pop();\r\n let out2 = q_data.pop();\r\n let out3 = q_data.pop();\r\n console.log(\r\n \" queue gotten out \",\r\n out.value,\r\n out1.value,\r\n out2.value,\r\n out3.value\r\n );\r\n q_data.push(100);\r\n // q_data.pop();\r\n\r\n console.log(\"queueu peeking out \", q_data.peek(), q_data.is_empty());\r\n q_data.parse_llist();\r\n }",
"function Queue(){\nvar _1=[],_2=0;\nthis.getLength=function(){ return (_1.length-_2); };\nthis.isEmpty=function() { return (_1.length==0); };\nthis.peek=function() { return (_1.length>0?_1[_2]:undefined); };\nthis.enqueue=function(_3){ _1.push(_3); };\nthis.dequeue=function(){\nif(_1.length==0) return undefined;\nvar _4=_1[_2];\nif(++_2*2>=_1.length){ _1=_1.slice(_2);_2=0; }\nreturn _4;\n};\n}",
"bindQueue() {\n return this._channel && this._channel.bindQueue.apply(this._channel, arguments);\n }",
"function bindQueueMultipleKeys(commObj, channel, queue, exchange, keys){\n return Promise.all(keys.map(function(singleKey){\n return bindQueueKey(commObj, channel, queue, exchange, singleKey);\n }))\n .catch((err) => Promise.reject(\"Queue not binded with routingkeys \" + keys + \". \" + err));\n}",
"function getRunningQueuingJobs_(endpoint, apikey) {\n var options = {\n \"method\": \"GET\",\n \"contentType\" : \"application/json\",\n \"headers\" : {\n \"Authorization\" : \"TD1 \" + apikey\n }\n };\n // status=running contains Running and Queued\n var response = UrlFetchApp.fetch('https://' + endpoint + '/v3/job/list?status=running', options); \n var response_json = JSON.parse(response.getContentText());\n return response_json['jobs']\n}",
"static create(arr) {\n const queue = new QueueImpl();\n arr.forEach((item) => {\n queue.enqueue(item);\n });\n return queue;\n }",
"function FetchAndPopAll() {\n return FailedEventQueue.splice(0, FailedEventQueue.length);\n }",
"function Queue() {\r\n var array = new Array();\r\n\r\n /**\r\n * Check inf the given data already exist in the queue\r\n * @param {type} data input data\r\n * @returns {Boolean} result\r\n */\r\n this.isDuplicate = function(data) {\r\n return array.indexOf(data) > -1 ? true : false;\r\n };\r\n /**\r\n * Put the specific object into the queue and return the queue size\r\n * @param {type} data\r\n * @returns {Number}\r\n */\r\n this.enqueue = function enqueue(data) {\r\n if (!this.isDuplicate(data)) {\r\n array.push(data);\r\n }\r\n return array.length;\r\n };\r\n /**\r\n * Remove and return the first object in queue\r\n * @returns {Object}\r\n */\r\n this.dequeue = function dequeue() {\r\n return array.shift();\r\n };\r\n /**\r\n * Get the queue size\r\n * @returns {Number}\r\n */\r\n this.size = function() {\r\n return array.length;\r\n };\r\n /**\r\n * check if the queue iis empty\r\n * @returns {Boolean}\r\n */\r\n this.isEmpty = function() {\r\n return array.length === 0;\r\n };\r\n this.toString = function() {\r\n return ('Queue: ' + array).green;\r\n };\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generates an empty line in the console via a console log optional `number` can be specified for the number of lines required | function emptyLines(number) {
if (typeof number !== 'undefined') {
for (i = 1; i <= number; i++) {
console.log(' ');
}
}
else {
console.log(' ');
}
} | [
"function printNewLines(numberOfLines) {\r\n\tfor (var i = 0; i < numberOfLines; i++) { \r\n\t\tdocument.write('<br>');\r\n\t}\r\n}",
"function logNumber(num = 0) {\n console.log(num);\n}",
"function writeLog(message, rowNumber)\n{\n Logger.log( \"Row: \" + rowNumber + \" : \" + message);\n}",
"function printNewLine() {\r\n\tterminal.innerHTML += '\\n';\r\n}",
"function loop(limit) {\n let printedMessage = '';\n // loop until limit\n for (let currentNumber = 1; currentNumber <= limit; currentNumber++) {\n // loop until currentNumber\n for (let printedNumber = 1; printedNumber <= currentNumber; printedNumber++) {\n printedMessage += currentNumber;\n }\n // add return space for each completed row\n if (currentNumber !== limit) {\n printedMessage += '\\n';\n }\n }\n console.log(printedMessage);\n}",
"function Divider(text)\n {\n console.log(\"\\r\\n--------------------\");\n console.log(text);\n }",
"function playback(number){\n //This guarantees we will never playback more element\n //than what exists in the history\n var playback_length = Math.min(history_index, configs.history_length);\n\n //If we have a non-zero number, prefer that\n if(!(number === 0 || number === undefined)){\n playback_length = Math.min(number, playback_length);\n }\n\n\n var start_index = 0;\n //when the index is longer than the length, we've made a ring\n //handle this appropriately;\n if(history_index >= configs.history_length) {\n start_index = history_index % configs.history_length;\n }\n\n for(var i = start_index; i < playback_length; i++){\n console[history[i][type]].apply(console,history[i][args]); //output to console\n }\n }",
"function drawConsolePyramid(height) {\n console.log(\" \".repeat(height) + \"*\");\n for (let i = 1; i < height; i++) {\n\n console.log(\" \".repeat(height - i) + \"*\".repeat(i) + \"*\".repeat(i) + \" \".repeat(height - i));\n }\n}",
"function simulateConsole(){\n let code = generateRandomJSCode();\n let codeElement = document.getElementById(\"desktopBkGroundOverlay\");\n codeElement.innerHTML += \"<p>\"+code+\"</p>\";\n while(codeElement.scrollHeight > codeElement.clientHeight){\n //Remove the first child of the element with a scroll up effect.\n codeElement.removeChild(codeElement.firstChild);\n }\n setTimeout(simulateConsole, Math.random()*50 + 450);\n}",
"static addBlankLine(excerptTokens) {\n let newlines = '\\n\\n';\n // If the existing text already ended with a newline, then only append one newline\n if (excerptTokens.length > 0) {\n const previousText = excerptTokens[excerptTokens.length - 1].text;\n if (/\\n$/.test(previousText)) {\n newlines = '\\n';\n }\n }\n excerptTokens.push({ kind: \"Content\" /* Content */, text: newlines });\n }",
"function write() {\n var length = arguments.length;\n for (var i = 0; i < length; i++) {\n output.print(String(arguments[i]));\n if (i < length - 1)\n output.print(' ');\n }\n}",
"function outputText(){\n for(let i = 1; i <= 5; i++){\n if(i >= 2){ console.log(`There are ${i} bottles of beer on the wall`);}\n if(i < 2){ console.log(`There is ${i} bottle of beer on the wall`);}\n }\n \n}",
"PrintProgress() {\n process.stdout.clearLine()\n process.stdout.cursorTo(0) \n process.stdout.write('Progress: '+this.folIter+' from '+this.totalFol)\n }",
"function addSequenceTnel(fileData) { //similar to above just avoid lines which does not have any data\n let lines = fileData.split(\"\\n\"); \n let count = 1; \n for(let i = 0; i < lines.length; i++) { \n if(lines[i] != \"\") { \n console.log(count + \". \" + lines[i]); \n count++; \n }\n else { \n console.log(\"\"); \n }\n } \n}",
"function writeln() {\n write.apply(this, arguments);\n output.println();\n}",
"function deleteLine() {\n\tif (options[1] <= 0) { //Check if the line number is 0 and show help\n\t\tconsole.log('Please enter right line number!!! ' + '\\n');\n\t\tshowHelp();\n\t} else {\n\t\tvar lineNumber = options[1] - 1; // Get the line number\n\t\tvar data = fs.readFileSync('todo.txt', 'utf8') // get file content\n\t\tvar dataRendering = data.split('\\n'); // create new array\n\t\tdataRendering.splice(lineNumber, 1); // slice the line number\n\t\tvar newLines = dataRendering.join('\\n'); // rejoin data\n\t\tfs.writeFileSync('todo.txt', newLines); // write to the file \n\t\tconsole.log('Line ' + options[1] + ' is deleted!' + '\\n'); // show confirmation message\n\t\tlistTodos(); // show the result\n\t}\n}",
"function logLine(input, level) {\n\tif ((level == \"error\" || level <= verbosity) && process.env.NODE_ENV !== \"test\") {\n\t\tconsole.log(`${prefixMap[level]}${input}`);\n\t}\n}",
"set minLines(value) {}",
"function blank() {\n putstr(padding_left(seperator, seperator, sndWidth));\n putstr(\"\\n\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Objects Queue Abstract Datatype implementation | function Queue() {
var array = new Array();
/**
* Check inf the given data already exist in the queue
* @param {type} data input data
* @returns {Boolean} result
*/
this.isDuplicate = function(data) {
return array.indexOf(data) > -1 ? true : false;
};
/**
* Put the specific object into the queue and return the queue size
* @param {type} data
* @returns {Number}
*/
this.enqueue = function enqueue(data) {
if (!this.isDuplicate(data)) {
array.push(data);
}
return array.length;
};
/**
* Remove and return the first object in queue
* @returns {Object}
*/
this.dequeue = function dequeue() {
return array.shift();
};
/**
* Get the queue size
* @returns {Number}
*/
this.size = function() {
return array.length;
};
/**
* check if the queue iis empty
* @returns {Boolean}
*/
this.isEmpty = function() {
return array.length === 0;
};
this.toString = function() {
return ('Queue: ' + array).green;
};
} | [
"function ArrayQueue() {}",
"function Queue(){\nvar _1=[],_2=0;\nthis.getLength=function(){ return (_1.length-_2); };\nthis.isEmpty=function() { return (_1.length==0); };\nthis.peek=function() { return (_1.length>0?_1[_2]:undefined); };\nthis.enqueue=function(_3){ _1.push(_3); };\nthis.dequeue=function(){\nif(_1.length==0) return undefined;\nvar _4=_1[_2];\nif(++_2*2>=_1.length){ _1=_1.slice(_2);_2=0; }\nreturn _4;\n};\n}",
"function tasks_queue() {\r\n let q_data = new Queue(1);\r\n q_data.push(4);\r\n q_data.push(8);\r\n q_data.push(9);\r\n q_data.push(19);\r\n\r\n q_data.parse_llist();\r\n let out = q_data.pop();\r\n let out1 = q_data.pop();\r\n let out2 = q_data.pop();\r\n let out3 = q_data.pop();\r\n console.log(\r\n \" queue gotten out \",\r\n out.value,\r\n out1.value,\r\n out2.value,\r\n out3.value\r\n );\r\n q_data.push(100);\r\n // q_data.pop();\r\n\r\n console.log(\"queueu peeking out \", q_data.peek(), q_data.is_empty());\r\n q_data.parse_llist();\r\n }",
"enque(object) {\n this.queArr.push(object);\n this.length++;\n return true;\n }",
"function onQueue(data) {\n\tif (\"Error\" in data) {\n\t\tonError(data.Error);\n\t} else if (\"Value\" in data) {\n\t\tqueueSize = data.Value.length;\n\t\t$(\"#current-queue>tbody\").empty();\n\t\tfor (i = currentTrack; i < data.Value.length; i++) {\n\t\t\twriteTrackRow(data.Value[i], i + 1);\n\t\t}\n\t\tfor (i = 0; i < currentTrack; i++) {\n\t\t\twriteTrackRow(data.Value[i], i + 1);\n\t\t}\n\t}\n}",
"static create(arr) {\n const queue = new QueueImpl();\n arr.forEach((item) => {\n queue.enqueue(item);\n });\n return queue;\n }",
"function Queue(){\n //Stack1 for pushing Queue Items\n let stack1 = new Stack();\n //Stack2 for popping Queue Items\n let stack2 = new Stack();\n\n this.push = function(element){\n stack1.push(element);\n }\n\n this.pop = function(){\n stack2.clear();\n while(!stack1.isEmpty()){\n let temp = stack1.pop();\n stack2.push(temp);\n } \n !stack2.isEmpty() && stack2.pop();\n let peaked = stack2.peak();\n while(!stack2.isEmpty()){\n let temp = stack2.pop();\n stack1.push(temp);\n } \n return peaked;\n }\n\n this.print = function(){\n stack2.clear();\n while(!stack1.isEmpty()){\n stack2.push(stack1.pop());\n }\n let str = stack2.print();;\n while(!stack2.isEmpty()){\n stack1.push(stack2.pop());\n }\n return str;\n }\n}",
"function Queue(props) {\n return __assign({ Type: 'AWS::SQS::Queue' }, props);\n }",
"publish(queue, event, payload) {\n let message = {queue,event,payload};\n this.q.emit('publish', message); \n }",
"function VisualQueue(domContainer, defs){\n defs = defs ? defs : {};\n this.domContainer = domContainer;\n if(defs[\"defaultDisplay\"]){\n this.domContainer.mainendChild(defs[\"defaultDisplay\"]);\n }\n this.superContainer = defs[\"defaultLocation\"] ? defs[\"defaultLocation\"] : document.body;\n this.queueCounter = 0;\n}",
"enqueue(item) {\n if (this.canEnqueue()) {\n this.queueControl.push(item);\n return this.queueControl;\n } \n throw new Error('QUEUE_OVERFLOW');\n }",
"push(element){\n\t\tthis.size++;\n\t\tthis.q2.push(element);\n\t\twhile(this.q1.length > 0)\n\t\t\tthis.q2.push(this.q1.shift()); // shift is same as dequeue\n\t\t//swap q1 and q2\n\t\tlet q = this.q1;\n\t\tthis.q1 = this.q2;\n\t\tthis.q2 = q;\n\t}",
"function deQueue(){\n this.string=new Array();\n /*\n * remove the item from back\n */\n this.popback=function(){\n return this.string.pop();\n }\n /*\n * add the item into back\n */\n this.pushback=function(item){\n return this.string.push(item);\n }\n /*\n * remove the item from front\n */\n this.popfront=function(){\n return this.string.shift();\n }\n /*\n * add the item into front\n */\n this.pushfront=function(item){\n return this.string.unshift(item);\n }\n /*\n * print dequeue\n */\n this.printQueue=function(){\n var str='';\n for(var i=0;i<this.string.length;i++){\n str+=this.string[i]+\" \";\n }\n return str;\n }\n /*\n returns the length of deQueue\n */\n this.size=function(){\n return this.string.length;\n }\n}",
"get queue() {\n return this.device.queue;\n }",
"async processQueue() {\n let message;\n while (this.queue.length) {\n if (!message || this.needsTaskBoundaryBetween(this.queue[0], message)) {\n await async_1.timeout(0);\n }\n message = this.queue.shift();\n if (!message) {\n return; // may have been disposed of\n }\n switch (message.type) {\n case 'event':\n if (this.eventCallback) {\n this.eventCallback(message);\n }\n break;\n case 'request':\n if (this.requestCallback) {\n this.requestCallback(message);\n }\n break;\n case 'response':\n const response = message;\n const clb = this.pendingRequests.get(response.request_seq);\n if (clb) {\n this.pendingRequests.delete(response.request_seq);\n clb(response);\n }\n break;\n }\n }\n }",
"queueStanza(iq) {\n this.otherStanzas.push(iq);\n }",
"bindQueue() {\n return this._channel && this._channel.bindQueue.apply(this._channel, arguments);\n }",
"function JobQueue(props) {\n return __assign({ Type: 'AWS::Batch::JobQueue' }, props);\n }",
"dequeue() {\n // if the queue is empty, return immediately\n if (this.queue.length == 0) return undefined;\n\n // store the item at the front of the queue\n var item = this.queue[this.offset];\n\n // increment the offset and remove the free space if necessary\n if (++this.offset * 2 >= this.queue.length) {\n this.queue = this.queue.slice(this.offset);\n this.offset = 0;\n }\n\n // return the dequeued item\n this.emit('dequeued', this.queue.length, item);\n return item;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visit a parse tree produced by PlSqlParsertype_body_elements. | visitType_body_elements(ctx) {
return this.visitChildren(ctx);
} | [
"visitType_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitProcedure_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitCreate_procedure_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitPackage_obj_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_definition(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitReplace_type_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_elements_parameter(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitCreate_package_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitSubtype_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitFunction_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_declaration(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitCompile_type_clause(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitType_procedure_spec(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitProc_decl_in_type(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitXmltype_table(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function tcbProcessNodes(nodes, tcb, scope) {\n nodes.forEach(function (node) {\n // Process elements, templates, and bindings.\n if (node instanceof compiler_1.TmplAstElement) {\n tcbProcessElement(node, tcb, scope);\n }\n else if (node instanceof compiler_1.TmplAstTemplate) {\n tcbProcessTemplateDeclaration(node, tcb, scope);\n }\n else if (node instanceof compiler_1.TmplAstBoundText) {\n var expr = tcbExpression(node.value, tcb, scope);\n scope.addStatement(ts.createStatement(expr));\n }\n });\n }",
"visitTrigger_body(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitObject_type_def(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Count of Closed Door | function ClosedDoors() {
var CountClosedDoors = CloseDoor.counterIncrement = 'inherit';
} | [
"function OpenedDoors() {\n\t\tvar CountOpenedDoors = OpenDoor.counterIncrement = 'inherit';\n\t}",
"function getAliveCount() {\n\tvar count = 0;\n\tcells.map(function(alive) {\n\t\tif (alive) count++;\n\t});\n\treturn count;\n}",
"count() {\n const values = utils.removeMissingValuesFromArray(this.values);\n return values.length;\n }",
"function nrCommittees(x){\n\t\tvar count=0;\n\t\tfor (var j=0; j < x.committees.length; j++){\n\t\t\t var committee = x.committees[j];\n\t\t\t if (conferences[committee.conference.series] && withinRange(committee)){\n\t\t\t\t count++;\n\t\t\t }\n\t\t }\n\t\t return count;\n\t}",
"function get_rarity_counts (rarity_dice) {\n// !!!\n}",
"calculateCompletion() {\n let openIssues = parseInt(this.props.data[\"open_issues\"]);\n let closedIssues = parseInt(this.props.data[\"closed_issues\"]);\n let total = openIssues + closedIssues;\n let completion = 0;\n if (total > 0) {\n completion = Math.round(closedIssues / total * 100);\n }\n\n return completion;\n }",
"static async countColleges(){\n const result=await pool.query('SELECT COUNT(collegecode) AS count FROM college');\n return result[0].count;\n }",
"get numClassDays()\n {\n if(this.classDays && this.classDays.length)\n return this.classDays.length;\n \n return 0;\n }",
"crotonTripsCounter(state) {\n var crotonTrips = 0;\n for (var i = 0; i < state.recordsList.length; i++) {\n if (state.recordsList[i].reservoir === \"Croton\") {\n crotonTrips++;\n }\n }\n return crotonTrips;\n }",
"countEpiniacReports() {\n return this.r.table('epiniac').count().run();\n }",
"function numberOfActiveSoldiers(square) {\n var totalNumberOfSoldier = square.contents.length;\n var counter = 0;\n\n for (var i = 0; i < totalNumberOfSoldier; i++) {\n if (square.contents[i].active) {\n counter++;\n }\n }\n\n return counter;\n}",
"count() {\n return Object.keys(this.locations).reduce(\n ((total, current) => total + Object.keys(this.locations[current]).length)\n , 0);\n }",
"countActive() {\n var counter = 0\n this.state.todos.forEach( todo => {\n if (todo.status === 'active') {\n counter += 1\n }\n })\n return counter\n }",
"countMeals(data) {\n this.counter = data.length;\n return this.counter;\n }",
"getCount(callback) {\n let count = {\n active: 0,\n completed: 0,\n total: 0\n }\n\n this.items.forEach(item => {\n if(item.completed) {\n count.completed++\n } else {\n count.active++\n }\n count.total++\n })\n\n if(typeof callback === 'function') {\n callback(count)\n }\n\n return count\n }",
"function committees(x, conf){\n\t\tif (conf == undefined){\n\t\t\treturn x.committees.length;\n\t\t} else {\n\t\t\tvar count = 0;\n\t\t\tfor (var i=0; i < x.committees.length; i++){\n\t\t\t\tvar committee = x.committees[i];\n\t\t\t\tif (committee.conference.series == conf && withinRange(committee)){\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn count;\n\t\t}\n\t}",
"numDescendants() {\n let num = 1;\n for (const branch of this.branches) {\n num += branch.numDescendants();\n }\n return num;\n }",
"function getItemHoleNumEagleCityOut(){\n let daysPassed = getDaysPassed();\n let remainder = daysPassed % 9; //9 days for a full cycle\n let itemHoleNumInit = Number(eagleCityOutItemHoleNum);\n let itemHoleNumEagleCityOut = itemHoleNumInit + remainder;\n return itemHoleNumEagleCityOut;\n}",
"function YDataRun_get_valueCount()\n {\n if(this._isLive) this.refresh();\n return Math.ceil(this._duration / this._browseInterval);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace the given link element with an embed. If the given link element is a link to an embeddable media and if its link text is the same as its href then it will be replaced in the DOM with an embed (e.g. an or html5 element) of the same media. If the link text is different from the href, then the link will be left untouched. We want to convert links like these from the Markdown source into embeds: < But we don't want to convert links like this: [Custom link text]( because doing so would destroy the user's custom link text, and leave users with no way to just insert a media link without it being embedded. If the link is not a link to an embeddable media it will be left untouched. | function replaceLinkWithEmbed(link) {
if (link.href !== link.textContent) {
return;
}
var embed = embedForLink(link);
if (embed){
link.parentElement.replaceChild(embed, link);
}
} | [
"function showembed(){\n document.getElementById('hideembed').style.visibility=\"hidden\";\n document.getElementById('hideembed').style.display=\"none\";\n document.getElementById('showembed').style.display=\"block\";\n document.getElementById('showembed').style.visibility=\"visible\";\n document.getElementById('embed').innerHTML=\"<a style=\\\"cursor:pointer;\\\" onClick=\\\"hideembed()\\\"><img src=\\\"addons/mw_eclipse/skin/images/icons/icon_share.png\\\" align=\\\"absmiddle\\\" /> Share / Embed<\\/a>\";\n\n}",
"function updateLink(value) {\n var item = new Array;\n\n //! Update Link\n item.modified = new Date();\n item.id = 1\n item.link = value;\n Storage.updateLink(item);\n strLink = value;\n}",
"function update_link(video_id, is_in_stack) {\n var video = video_map[video_id];\n\n if (typeof video != 'undefined') {\n video.is_in_stack = is_in_stack;\n\n for (var i in video.containers) {\n $('.flixstack-wrapper', video.containers[i]).remove();\n $(video.containers[i]).append(make_link(video_id));\n }\n }\n}",
"function getLinkRef(link) {\n return link ? link.link : false;\n}",
"function ProcessLink(instanceId, linkId, settings) {\n if (!(this instanceof ProcessLink)) { return new ProcessLink(instanceId, linkId, settings); }\n this._external = settings.hasOwnProperty('external') ? !!settings.external : false;\n ProtocolLink.call(this, instanceId, linkId, settings);\n}",
"function withMagicLinksReplaced(text) {\n let replaced_text = text\n // ticket id\n .replace(new RegExp(\"ticket[:#]([0-9]{3,6})(?=\\\\b)\", \"ig\"), \"<a href=\\\"https://tickets.agdsn.de/index.pl?Action=AgentTicketZoom;TicketID=$1\\\">$&</a>\")\n // ticket number (YYYYMMDDhhmmss¿¿)\n .replace(new RegExp(\"(?<=\\\\b)(ticket[:#])?([0-9]{16})(?=\\\\b)\", \"ig\"), \"<a href=\\\"https://tickets.agdsn.de/index.pl?Action=AgentTicketZoom;TicketNumber=$2\\\">Ticket#$2</a>\")\n ;\n console.debug(`${text} ⇒ ${replaced_text}`);\n return replaced_text;\n}",
"function replaceLinksToCards(tr, cardAdf, schema, request) {\n var inlineCard = schema.nodes.inlineCard;\n var url = request.url;\n if (!adf_schema_1.isSafeUrl(url)) {\n return;\n }\n // replace all the outstanding links with their cards\n var pos = tr.mapping.map(request.pos);\n var $pos = tr.doc.resolve(pos);\n var node = tr.doc.nodeAt(pos);\n if (!node || !node.type.isText) {\n return;\n }\n if (!shouldReplace(node, request.compareLinkText, url)) {\n return;\n }\n // ED-5638: add an extra space after inline cards to avoid re-rendering them\n var nodes = [cardAdf];\n if (cardAdf.type === inlineCard) {\n nodes.push(schema.text(' '));\n }\n tr.replaceWith(pos, pos + (node.text || url).length, nodes);\n return $pos.node($pos.depth - 1).type.name;\n}",
"function MODIFIER_EMBEDDED$static_(){LinkListBEMEntities.MODIFIER_EMBEDDED=( LinkListBEMEntities.BLOCK.createModifier(\"embedded\"));}",
"function PrepareNewPostForAdding(text) {\r\n //Remove extra spaces\r\n text = $.trim(text);\r\n\r\n //Get youtube video id instead of full link\r\n text = text.replace(/\\[[^\\/].*?\\]/g, function(item) {\r\n if (item.indexOf(\"video\") > -1) {\r\n var attrData = GetYoutubeVideoId(GetAtrrData(item, \"src\"));\r\n item = SetAttrData(item, \"src\", attrData);\r\n }\r\n\r\n return item;\r\n });\r\n\r\n return text;\r\n}",
"linkMD( text, url ) {\n if (url && url.trim()) { return (`[${text}](${url})`); } else { return text; }\n }",
"replaceLinks (text) {\n text = text.replace(/(<a href)([^.]*?)(>.*)(a>)/g, '<router-link to$2$3router-link>')\n text = text.replace(/<a xlink:href/, '<router-link to')\n return text\n }",
"function MediaElement(entry) {\n\n\tvar link = document.createElement('a');\n\tlink.href = entry.content.src;\n\tvar videoid = link.pathname.substr(link.pathname.length - 11);\n\n\tvar li_node = document.createElement(\"LI\");\n\tli_node.ontouchstart = function() {\n\t\tLoadVideo(this.childNodes[0]);\n\t\treturn false;\n\t}\n\tli_node.innerHTML = \"<a href=\\\"#\" + videoid + \"\\\" onclick=\\\"LoadVideo(this); return false;\\\" class=\\\"item-link item-content\\\">\"\n\t\t+ \"<div class=\\\"item-inner\\\">\"\n\t\t\t+ \"<div class=\\\"item-title-row\\\">\"\n\t\t\t+ \"<div class=\\\"item-title\\\">\" + entry.title.$t + \"</div>\"\n\t\t+ \"</div>\"\n\t\t+ \"<div class=\\\"item-text\\\">\" + entry.summary.$t + \"</div>\"\n\t\t+ \"</div></a>\"\n\treturn li_node;\n}",
"function handleLinkParse(link) {\n // init dictionary of all the links we already parsed\n let parsedLinks = {};\n // recursive function in case sub-links has more links\n function parseLink(linkToParse) {\n // parse link with the mock parser\n let parsedLink = parser(linkToParse);\n // save the link parse result in the dictionary\n parsedLinks[linkToParse] = parsedLink.html;\n // run over all the current sub-links\n parsedLink.links.forEach(l => {\n // in case we did not parsed the current sub-link\n if (parsedLinks[l] === undefined) {\n parseLink(l);\n }\n });\n }\n parseLink(link);\n // convert our dictionary to array of links and their parsed html\n return Object.keys(parsedLinks).map((key) => ({ url: key, html: parsedLinks[key] }));\n}",
"function linkIf( text, href, title ) {\n\ttitle = H( title || text ).replace( /\"/g, '"' );\n\ttext = H( text );\n\treturn ! href ? text : S(\n\t\t'<a target=\"_blank\" href=\"', href, '\" title=\"', title, '\">',\n\t\t\ttext,\n\t\t'</a>'\n\t);\n}",
"set link(aValue) {\n this._logService.debug(\"gsDiggEvent.link[set]\");\n this._link = aValue;\n\n var uri;\n try {\n uri = this._ioService.newURI(this._link, null, null);\n } catch (e) {\n uri = this._ioService.newURI(\"http://\" + this._link, null, null);\n }\n this._domain = uri.host;\n }",
"function addPlanarLink(link, links) {\n if (!links.some (function (to) {\n return intersect (link, to);\n }))\n {\n links.push (link);\n }\n }",
"function isLinkIgnored(link, options) {\n return options.linksToIgnore.some(function(isLinkIgnored) {\n return (isLinkIgnored === link);\n });\n }",
"set link(aValue) {\n this._logger.debug(\"link[set]\");\n this._link = aValue;\n\n let uri;\n\n try {\n uri = this._ioService.newURI(this._link, null, null);\n } catch (e) {\n uri = this._ioService.newURI(\"http://\" + this._link, null, null);\n }\n\n this._domain = uri.host;\n }",
"function fixLinks() {\n // Catch only text links, not pictures and other stuff\n var links = $( '.twitter-timeline-link[data-link-fixed!=1]:not(.media, .u-hidden)' );\n\n $( links ).each(function(){\n setUrlToLink(this, this.dataset.expandedUrl);\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
private function, makes element invisible (display:none cannot be used with transition/amimation). By setting the right attribute to large negative number, the element will be placed far off screen to the right and this will be where it starts when it is next made visible (for the "zoom in from right" animation). | function hide(ele) {
ele.style.right = hiddenRight;
ele.style.visibility = "hidden";
} | [
"function hidejsaccessiblehideObject() {\n\tvar jsaccessiblehidevar = getElementsByClass(\"jsaccessiblehide\");\n\t\t\n\tfor ( j=0;j<jsaccessiblehidevar.length;j++ ) {\n\t\tjsaccessiblehidevar[j].style.position = 'absolute';\n\t\tjsaccessiblehidevar[j].style.left = '-5000px';\n\t}\n}",
"function hideHelper(event, element) {\n element.removeAttribute(\"visible\");\n element.style.visibility = \"hidden\";\n }",
"hide() {\n\t\tthis.element.style.visibility = 'hidden';\n\t}",
"show() {\n\t\tthis.element.style.visibility = '';\n\t}",
"function toggleButton() {\n leftPosition == 0 ? arrowLeft.hide() : arrowLeft.show();\n Math.abs(leftPosition) >= innerBoxWidth - containerWidth ? arrowRight.hide() : arrowRight.show();\n }",
"function hideAxis() {\n g.select('.x.axis')\n .transition().duration(500)\n .style('opacity', 0);\n }",
"function hideSideBar(trigger) {\n createTapInteraction(trigger);\n var slideMainViewIn = createMoveAnimation(mainView);\n slideMainViewIn.name = \"Hide side bar\";\n slideMainViewIn.basedOn = trigger.tap;\n slideMainViewIn.animates = AnimationMode.withDuration;\n slideMainViewIn.toX = 0;\n slideMainViewIn.easing = EasingCurve.easeInOutQuadratic;\n slideMainViewIn.duration = 0.4;\n}",
"function topContentRight() {\n let top_content_R = gsap.timeline({\n id: \"top content right\"\n });\n top_content_R.from($top_Content_Right, {\n y: -200,\n autoAlpha: 0,\n duration: 1.5,\n ease: bo,\n delay: 3\n })\n }",
"reverseVisibility(){\n for(let i = 0; i < this.children[2].children.length; i++){\n this.children[2].children[i].visible = !this.children[2].children[i].visible;\n }\n }",
"function makeInvisible(element) {\n\telement.className = \"invisible\";\n}",
"showToScreenReader() {\n this.adapter_.removeAttr(_constants.strings.ARIA_HIDDEN);\n }",
"function remove() {\n if (isVisible()) {\n var extendedSplashScreen = document.getElementById(\"extendedSplashScreen\");\n WinJS.Utilities.addClass(extendedSplashScreen, \"hidden\");\n }\n }",
"function participants_view_hide() {\n\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"rgba(0,0,0,.2)\";\n\tsetTimeout(function() {\n\t\tDOM(\"PARTICIPANTS_CLOSE\").style.backgroundColor = \"transparent\";\n\t\tparticipants_view_visible = false;\n\t\tDOM(\"PARTICIPANTS_VIEW\").style.top = \"-100%\";\n\t\tsetTimeout(function() {\n\t\t\tDOM(\"PARTICIPANTS_VIEW\").style.display = \"none\";\n\t\t}, 500);\n\t}, 50);\n}",
"function dontGoOffScreenX() {\r\n\t\t\t\t\r\n\t\t\t\t\tvar windowLeft = $(window).scrollLeft();\r\n\t\t\t\t\t\r\n\t\t\t\t\t// if the tooltip goes off the left side of the screen, line it up with the left side of the window\r\n\t\t\t\t\tif((myLeft - windowLeft) < 0) {\r\n\t\t\t\t\t\tarrowReposition = myLeft - windowLeft;\r\n\t\t\t\t\t\tmyLeft = windowLeft;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\t// if the tooltip goes off the right of the screen, line it up with the right side of the window\r\n\t\t\t\t\tif (((myLeft + tooltipWidth) - windowLeft) > windowWidth) {\r\n\t\t\t\t\t\tarrowReposition = myLeft - ((windowWidth + windowLeft) - tooltipWidth);\r\n\t\t\t\t\t\tmyLeft = (windowWidth + windowLeft) - tooltipWidth;\r\n\t\t\t\t\t}\r\n\t\t\t\t}",
"function hideGeoportalView() {\n var gppanel= viewer.getVariable('gppanel');\n gppanel.style.visibility= 'hidden';\n gppanel.style.position= 'absolute';\n gppanel.style.top= '-9999px';\n gppanel.style.left= '-9999px';\n}",
"function displaceRight() {\n\tvar currentRight = $(pictureArray[rightPic]).offset().left;\n\t$(pictureArray[rightPic]).offset({left: currentRight - slideshowWidth});\n\t\n\tleftPic = (leftPic + pictureArray.length - 1) % pictureArray.length;\n\t\n\trightPic = (rightPic + pictureArray.length - 1) % pictureArray.length;\n}",
"function hideLanding() {\r\n let videoBox = document.getElementById('video-box');\r\n let textBar = document.getElementById('text-bar');\r\n let explainerBox = document.getElementById('explainer-box');\r\n let buttonBox = document.getElementById('btn-holder');\r\n let footBox = document.getElementById('foot-holder');\r\n let equalSign = document.getElementById('equal')\r\n \r\n videoBox.classList.add('hidden');\r\n textBar.classList.add('hidden');\r\n explainerBox.classList.add('hidden');\r\n buttonBox.classList.add('hidden');\r\n footBox.classList.add('hidden');\r\n equalSign.classList.add('hidden')\r\n hideChildElements(videoBox)\r\n hideChildElements(textBar)\r\n hideChildElements(explainerBox)\r\n hideChildElements(buttonBox)\r\n hideChildElements(footBox);\r\n }",
"function hideSlider() {\r\n\tvar mydiv = document.getElementById('day-panel');\r\n\tmydiv.style.display = (mydiv.style.display = 'none');\r\n}",
"hide() {\n const hideTL = new TimelineLite();\n hideTL.to(this.$.flag, FLAG_ENTRANCE_DURATION, {\n y: 55,\n opacity: 0,\n ease: Sine.easeInOut\n });\n hideTL.call(() => {\n this._showing = false;\n });\n return hideTL;\n }",
"_hide() {\n this._updateTriggerWidth();\n if (this._settings.get_boolean('dock-fixed')) {\n return;\n }\n\n if (this._isHovering() || (this._hoveringDash && !Main.overview._shown)) {\n return;\n }\n\n let intellihideAction = this._settings.get_enum('intellihide-action');\n if (!Main.overview._shown && intellihideAction == IntellihideAction.SHOW_FULL && !this._autohideStatus) {\n return;\n }\n\n let overviewAction = this._settings.get_enum('overview-action');\n if (Main.overview._shown && overviewAction == OverviewAction.SHOW_FULL && !this._autohideStatus) {\n return;\n }\n\n // Only hide if dock is shown, is showing, or is partially shown\n if (this._dockState == DockState.SHOWN || this._dockState == DockState.SHOWING || this._slider.slidex > 0) {\n this._removeAnimations();\n\n // If the dock is shown, wait this._settings.get_double('show-delay') before hiding it;\n // otherwise hide it immediately.\n let delay = 0;\n if (this._dockState == DockState.SHOWN)\n delay = this._settings.get_double('hide-delay');\n\n if (Main.overview._shown && Main.overview.viewSelector._activePage == Main.overview.viewSelector._workspacesPage) {\n this._animateOut(this._settings.get_double('animation-time'), delay, false);\n } else {\n this._animateOut(this._settings.get_double('animation-time'), delay, this._autohideStatus);\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function to run tests to check if we can successfully set and evaluate breakpoints on an instrumentation pause. | async function runSetBreakpointOnInstrumentationTest(condition) {
const builder = new WasmModuleBuilder();
const start_fn = builder.addFunction('start', kSig_v_v).addBody([kExprNop]);
builder.addStart(start_fn.index);
await Protocol.Runtime.enable();
await Protocol.Debugger.enable();
InspectorTest.log('Setting instrumentation breakpoint');
await Protocol.Debugger.setInstrumentationBreakpoint(
{instrumentation: 'beforeScriptExecution'});
InspectorTest.log('Compiling wasm module.');
WasmInspectorTest.compile(builder.toArray());
// First pause: compile script.
await handlePause(await Protocol.Debugger.oncePaused());
InspectorTest.log('Instantiating module.');
const evalPromise = WasmInspectorTest.evalWithUrl(
'new WebAssembly.Instance(module)', 'instantiate');
// Second pause: instantiate script.
await handlePause(await Protocol.Debugger.oncePaused());
// Third pause: wasm script. This will set a breakpoint. Pass on a condition.
const msg = await Protocol.Debugger.oncePaused();
await setBreakpoint(msg, condition);
await handlePause(msg);
// Fourth pause: wasm script, if condition evaluates to true.
if (!condition || eval(condition)) {
await handlePause(await Protocol.Debugger.oncePaused());
}
InspectorTest.log('Done.');
await evalPromise;
await Protocol.Debugger.disable();
await Protocol.Runtime.disable();
} | [
"function runPauseResumeStopTests() {\n //run all tests without an instance running\n try {\n ap.stopAllSounds();\n assert.ok(true, \"stopAllSounds(): no instance running\");\n }\n catch (e) {\n assert.ok(false, \"stopAllSounds(): no instance running\");\n }\n\n try {\n ap.stopSound(\"instanceId\");\n assert.ok(true, \"stopSound(): no instance running\");\n }\n catch (e) {\n assert.ok(false, \"stopSound(): no instance running\");\n }\n\n try {\n ap.pauseAllSounds();\n assert.ok(true, \"pauseAllSounds(): no instance running\");\n }\n catch (e) {\n assert.ok(false, \"pauseAllSounds(): no instance running\");\n }\n\n try {\n ap.resumeAllSounds();\n assert.ok(true, \"resumeAllSounds(): no instance running\");\n }\n catch (e) {\n assert.ok(false, \"resumeAllSounds(): no instance running\");\n }\n\n runPauseTest();\n }",
"function runTests(){\n var len = testsQueue.length;\n while(testsQueueIndex < len && !testIsRunning){\n currentTestHash = testsQueue[testsQueueIndex];\n currentTestStep = 0;\n testIsRunning = true;\n runTest();\n }\n if(testsQueueIndex === len){\n //Run the assertions in the assertionsQueue.\n runAssertions();\n }\n }",
"function setTestRanTrue() {\n testRan = true;\n}",
"function test_suspend_vm_service_details(context) {}",
"function runPauseSequence() {\n var time = getVideoTime();\n logVideoEvent('pause', time, VIDEO_EVENT_LOG_URL).\n then(function() {\n pauseVideo();\n });\n}",
"function runAssertions(){\n var i,\n len,\n item;\n //Show totals for groups, test, assertions before running the tests.\n showTotalsToBeRun();\n //A slight delay so user can see the totals and they don't flash.\n setTimeout(function(){\n //Synchronously iterate over the assertionsQueue, running each item's assertion.\n for (i = 0, len = assertionsQueue.length; i < len; i++) {\n item = assertionsQueue[i];\n item.result = item.assertion(typeof item.value === 'function' ? item.value() : item.value, item.expectation);\n if(item.result){\n totAssertionsPassed++;\n }else{\n totAssertionsFailed++;\n }\n switch(item.assertion.name){\n case 'assertIsTrue':\n item.displayAssertionName = 'isTrue';\n break;\n case 'assertIsTruthy':\n item.displayAssertionName = 'isTruthy';\n break;\n case 'assertIsFalse':\n item.displayAssertionName = 'isFalse';\n break;\n case 'assertIsNotTruthy':\n item.displayAssertionName = 'isNotTruthy';\n break;\n case 'assertEqual':\n item.displayAssertionName = 'equal';\n break;\n case 'assertNotEqual':\n item.displayAssertionName = 'notEqual';\n break;\n }\n results.push(item);\n if(config.shortCircuit && totAssertionsFailed){\n reporter();\n return;\n }\n }\n //Record the end time.\n timerEnd = Date.now();\n //Report the results.\n reporter();\n }, 1);\n }",
"async function isSimulatorAppRunningAsync() {\n try {\n const zeroMeansNo = (await osascript.execAsync('tell app \"System Events\" to count processes whose name is \"Simulator\"')).trim();\n if (zeroMeansNo === '0') {\n return false;\n }\n }\n catch (error) {\n if (error.message.includes('Application isn’t running')) {\n return false;\n }\n throw error;\n }\n return true;\n}",
"static run() {\n // Perform each test\n if (zbDateTimeToolsTest._getDayOfYear() === false) { console.log('zbDateTimeToolsTest.getDayOfYear FAILED'); return; }\n if (zbDateTimeToolsTest._getDayOfWeek() === false) { return; }\n if (zbDateTimeToolsTest._isLeapYear() === false) { console.log('zbDateTimeToolsTest.isLeapYear FAILED'); return; }\n if (zbDateTimeToolsTest._getDaysInMonth() === false) { console.log('zbDateTimeToolsTest.getDaysInMonth FAILED'); return; }\n if (zbDateTimeToolsTest._getDaysInYear() === false) { console.log('zbDateTimeToolsTest.getDaysInYear FAILED'); return; }\n if (zbDateTimeToolsTest._dateToDays() === false) { return; }\n if (zbDateTimeToolsTest._daysToDate() === false) { return; }\n if (zbDateTimeToolsTest._dateToDaysToDate() === false) { console.log('zbDateTimeToolsTest.dateToDaysToDate FAILED'); return; }\n if (zbDateTimeToolsTest._getTimeToSeconds() === false) { return; }\n }",
"function checkBreakpoint() {\n\t\t\t// Use an actual media-query-driven property of an element\n\t\t\t// to ensure JS and CSS are synced.\n\t\t\tvars.modelWidth = $(settings.modelSelector + ':first').outerWidth();\n\n\t\t\t// Loop through breakpoints and try to find a match with the model's current width.\n\t\t\tvar foundBreakpoint = false;\n\t\t\t$.each(settings.breakpoints, function(breakpoint, size) {\n\t\t\t\tif (!foundBreakpoint && size == vars.modelWidth) {\n\t\t\t\t\tif (breakpoint !== vars.currentView) {\n\t\t\t\t\t\tif (vars.initial === false) {\n\t\t\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + vars.currentView + ':exit');\n\t\t\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + breakpoint);\n\t\t\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + breakpoint + ':enter');\n\t\t\t\t\t\t\tif (settings.debug) {\n\t\t\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + vars.currentView + ':exit');\n\t\t\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + breakpoint);\n\t\t\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + breakpoint + ':enter');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + breakpoint);\n\t\t\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + breakpoint + ':initial');\n\t\t\t\t\t\t\tif (settings.debug) {\n\t\t\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + breakpoint);\n\t\t\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + breakpoint + ':initial');\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tvars.initial = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvars.currentView = breakpoint;\n\t\t\t\t\t}\n\t\t\t\t\tfoundBreakpoint = true;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t// If none of the breakpoint pixel values matched the current model width,\n\t\t\t// then we are on the default (smallest) breakpoint.\n\t\t\tif (!foundBreakpoint && vars.currentView != settings.defaultBreakpoint) {\n\t\t\t\tif (!vars.initial) {\n\t\t\t\t\t// Trigger exit & entry events if needed\n\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + vars.currentView + ':exit');\n\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint);\n\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint + ':enter');\n\t\t\t\t\tif (settings.debug) {\n\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + vars.currentView + ':exit');\n\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint);\n\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint + ':enter');\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// This will only trigger if something is very wrong, but it's a safeguard anyway\n\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint);\n\t\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint + ':initial');\n\t\t\t\t\tif (settings.debug) {\n\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint);\n\t\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint + ':initial');\n\t\t\t\t\t}\n\t\t\t\t\tvars.initial = false;\n\t\t\t\t}\n\t\t\t\tvars.currentView = settings.defaultBreakpoint;\n\t\t\t} else if (vars.initial) {\n\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint);\n\t\t\t\t$(settings.eventTarget).first().trigger('bp:' + settings.defaultBreakpoint + ':initial');\n\t\t\t\tif (settings.debug) {\n\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint);\n\t\t\t\t\tconsole.log('Triggered breakpoint event: bp:' + settings.defaultBreakpoint + ':initial');\n\t\t\t\t}\n\t\t\t\tvars.initial = false;\n\t\t\t}\n\t\t}",
"function runTests(tests, maxWaitingTime) {\n var idx = 0;\n function runTestCase(func) {\n return new Promise(function(resolve) {\n func.call(null, resolve);\n }).then(function() {\n idx++;\n if (idx == tests.length) {\n xwalk.app.test.notifyPass();\n return;\n }\n runTestCase(tests[idx]);\n }, function(e) {\n console.error(e);\n xwalk.app.test.notifyFail(); \n });\n };\n\n if (typeof(maxWaitingTime) === 'number' && isFinite(maxWaitingTime)) {\n setTimeout(function() {\n xwalk.app.test.notifyTimeout();\n }, maxWaitingTime);\n }\n\n runTestCase(tests[idx]);\n}",
"function doCheck() {\n if (hasStarted === false) {\n // The test has not started, but the user is typing already -- maybe we should start?\n beginTest(); // Yes, we should -- consider it done!\n }\n}",
"function shouldInstrument () {\n if (process.env.CI) {\n return !!process.env.REPORT_COVERAGE;\n }\n return true;\n}",
"function test() {\n app.tag(\"Main\").w+=0.001;\n const start = app.stage.platform.getHrTime();\n app.stage.ctx._update();\n const end = app.stage.platform.getHrTime();\n if (end-start < 1.0) {\n total += (end - start);\n measurements++;\n if ((measurements % 100) === 0) {\n console.log(total / measurements + 'ms in ' + measurements + ' tests');\n }\n\n if (measurements === 1000) {\n measurements = 0;\n total = 0;\n }\n }\n}",
"function testMakePointValue() {\n Logger.log('Testing makePointValue...');\n \n if (!checkMakePointValue('3 pts.', 'Each shared item', 3)) {\n return false;\n }\n \n if (!checkMakePointValue('5 pts./15 min.', '15 minutes', 5)) {\n return false;\n }\n \n if (!checkMakePointValue('15 pts./1 hr.', '1 hour', 15)) {\n return false;\n }\n \n Logger.log('Test passed.');\n return true; \n}",
"onPrepare() {\n jasmine.getEnv().addReporter({\n specDone: (res) => {\n if (res.status === 'failed') {\n const failedInfo = {\n fullName: res.fullName,\n failedExpectations: JSON.stringify(res.failedExpectations)\n }\n\n this.promises.push(browser.takeScreenshot()\n .then(imgur.uploadBase64)\n .then((imgurJson) => {\n failedInfo.screenshot = imgurJson.data.link\n })\n .then(() => {\n return browser.manage().logs().get('browser')\n })\n .then((browserLog) => {\n failedInfo.browserLog = JSON.stringify(browserLog)\n })\n .then(() => {\n this.failedSpecs.push(failedInfo)\n })\n .catch(GDocsPlugin.logError))\n }\n }\n })\n }",
"function main() {\n console.log(`testing ngtools API...`);\n\n Promise.resolve()\n .then(() => codeGenTest())\n .then(() => i18nTest())\n .then(() => lazyRoutesTest())\n .then(() => {\n console.log('All done!');\n process.exit(0);\n })\n .catch((err) => {\n console.error(err.stack);\n console.error('Test failed');\n process.exit(1);\n });\n}",
"function runSyncMatrixTests() {\n testStructure();\n testValues();\n testBehaviour();\n}",
"function hangupTest(expected) {\n\t\n\tvar tropo = new TropoWebAPI();\n\ttropo.hangup();\n\treturn runTest(TropoJSON(tropo), expected);\n}",
"function check() {\n clearTimeout(timer)\n\n if (device.present) {\n // We might get multiple status updates in rapid succession,\n // so let's wait for a while\n switch (device.type) {\n case 'device':\n case 'emulator':\n willStop = false\n timer = setTimeout(work, 100)\n break\n default:\n willStop = true\n timer = setTimeout(stop, 100)\n break\n }\n }\n else {\n willStop = true\n stop()\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if user already exists | static checkUserExists(req, res, next) {
User.getUserByEmail(req.body.email)
.then(newUser =>{
if (newUser.rows[0]) return errHandle(409, 'user already exists', res);
return next();
})
} | [
"userExists(id) {\n /** find index of user with that id */\n let index = this.data.users.findIndex((user) => {\n return user.id === id\n })\n /** check if index is valid */\n if (index > -1) {\n return true\n } else {\n return false\n }\n }",
"async function validateExistence(req, res, next){\n try{\n const { username, email } = req.body;\n const [user_database] = await sequelize.query(\n `SELECT * FROM user_database`,\n { raw: true },\n );\n \n const user = user_database.find( item => item.username == username || item.email == email);\n const userExist = Boolean(user);\n\n if(!userExist){\n next();\n }else{\n throw 'Este usuario ya existe en la base de datos';\n };\n }catch(fail){\n res.json({ Error: fail });\n };\n}",
"function RegisterAccount(username, pass, email, phone, name, birthday, sex, avatarLink) {\n user.ThemUser(username, name, birthday, sex, phone, email, pass, avatarLink);\n return userIsExisting(username);\n}",
"async ensureUnique () {\n\t\tconst user = await this.data.users.getOneByQuery(\n\t\t\t{\n\t\t\t\tsearchableEmail: decodeURIComponent(this.request.body.toEmail).toLowerCase()\n\t\t\t},\n\t\t\t{\n\t\t\t\thint: UserIndexes.bySearchableEmail\n\t\t\t}\n\t\t);\n\t\tif (user) {\n\t\t\tthrow this.errorHandler.error('emailTaken');\n\t\t}\n\t}",
"function check_name_exist() {\r\tvar parameters = '/users/checkExist?name=' + encodeURIComponent($.trim($name.val())) + '&id=' + $('#id').val();\r\tcheck_exist($name_error,parameters,'该用户名称已存在!');\r}",
"function createUserAttempt(userName,password){\n if (userNameExists(userName) == 1) return -1;\n\n else return createNewUser(userName,password);\n}",
"async uniqueEmail(email){\n let user=await dao.find(this.USERS,{email: email})\n if(user.length)\n return false\n return true\n }",
"function check_user_pers(err,row,data,response){\n if(err === null && row != undefined){\n if(row.persistentLogin === data.per){\n validSignUp(response,err,data.usr);\n }\n else{\n submitionError(9,response);\n }\n }\n else{\n submitionError(1,response);\n }\n}",
"isNewUserCheck() {\n let userCookie = this.helper.getCookieInfo('userName');\n\n // If cookie exists, it means that user visited site earlier.\n if (userCookie.cookieExists) {\n this.userCookie = userCookie.value;\n }\n\n return !userCookie.cookieExists;\n }",
"async registerUser (provider, name) {\n let user = await this.getUserByName(name, true)\n if (user) {\n if (user._provider !== provider) {\n throw new Error(`the name ${name} is already taken`)\n }\n\n return user\n }\n\n if (!this._config.createUserOnFirstSignin) {\n throw new Error(`registering ${name} user is forbidden`)\n }\n\n return await this.createUser(name, {\n _provider: provider\n })\n }",
"async isFirstUser() {\n return (await this.stores.users.count({type: 'user'})) === 0;\n }",
"function createUser(name, email, perms, pass){\n var existing = getUserByName(name);\n if(existing == null){\n console.log(\"Creating new user \"+name);\n new_user = new User(name, email, perms);\n new_user.password = pass;\n this.users.push(new_user);\n dbInsert({username: name, emailaddr: email, permissions: perms, password: pass}, \"users\");\n return new_user;\n }else{\n return existing;\n }\n}",
"function isUsersReal (req, project4webaudio) {\n\tconsole.log(\"checking user\");\n\n\tif (req.user.name !== project4webaudio.username) {\n\n\t\tconsole.log(\"Invalid User\");\n\t\tres.json({ message: 'FAILED' });\n\t\treturn false\n\t}\n\treturn true\n}",
"static async register(data) {\n const duplicateCheck = await db.query(\n `SELECT username \n FROM users \n WHERE username = $1`,\n [data.username]\n );\n\n if (duplicateCheck.rows[0]) {\n throw new ExpressError(\n `There already exists a user with username '${data.username}`,\n 400\n );\n }\n\n const hashedPassword = await bcrypt.hash(data.password, BCRYPT_WORK_FACTOR);\n\n // create shrimpy user\n const shrimpy_user_id = await client.createUser(data.username);\n\n if (!shrimpy_user_id)\n throw new ExpressError(\"Could not create user in Shrimpy\");\n\n // create API keys in shrimpy for user management\n await client.createApiKeys(shrimpy_user_id);\n\n const result = await db.query(\n `INSERT INTO users \n (username, password, email, shrimpy_user_id) \n VALUES ($1, $2, $3, $4) \n RETURNING username, password, email, shrimpy_user_id`,\n [data.username, hashedPassword, data.email, shrimpy_user_id]\n );\n\n return result.rows[0];\n }",
"async function checkIfRefExist(userId) {\n const refs = await db_utils.execQuery(\n \"SELECT userId FROM dbo.Referees\" \n );\n if (refs.find((r) => r.userId === parseInt(userId))){\n return true;\n }\n return false;\n }",
"function validateId(user_id, callback){\n\tvar sel_q = \"SELECT id, user_name, xp_sent, xp_received, send_count, receive_count, last_activity FROM spg_users WHERE id = \" + user_id;\n\tc.query(sel_q, function(err, rows, fields) {\n\t\tr_val = {is_valid:false,user_obj:{}};\n\t\tif (!err) {\n\t\t\tif (rows.length == 1) {\n\t\t\t\tconsole.log(\">>> User(\" + user_id + \") exists on DB\");\n\t\t\t\tr_val.is_valid = true;\n\t\t\t\tr_val.user_obj = rows[0];\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconsole.log(\">>> User(\" + user_id + \") does not exist on DB\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tconsole.log(\"Error selecting [\" + user_id + \"]\");\n\t\t\tconsole.log(\"Err: \" + err );\n\t\t}\n\n\t\tcallback(r_val);\n\t});\n}",
"async function isSessionUserValid(req){\r\n\tvar sessionVar = req.session;\r\n\tif(sessionVar.theUser){\r\n\t\tvar usersMap = await userDB.getAllUsers();\r\n\t\treturn usersMap.has(sessionVar.theUser);\r\n\t}\r\n\treturn false;\r\n}",
"async checkNewAccount(accountId) {\n if (!this.isLegitAccountId(accountId)) {\n throw new Error('Invalid username.');\n }\n\n // TODO: This check doesn't seem up to date on what are current account name requirements\n // TODO: Is it even needed or is checked already both upstream/downstream?\n if (accountId.match(/.*[.@].*/)) {\n if (!accountId.endsWith(`.${ACCOUNT_ID_SUFFIX}`)) {\n throw new Error('Characters `.` and `@` have special meaning and cannot be used as part of normal account name.');\n }\n }\n\n if (await this.accountExists(accountId)) {\n throw new Error('Account ' + accountId + ' already exists.');\n }\n\n return true;\n }",
"function check() {\r\n\r\n // stored data from the register-form\r\n let storedID = localStorage.getItem('id_no1');\r\n let storedName = localStorage.getItem('name1');\r\n let storedPw = localStorage.getItem('psw1');\r\n\r\n // entered data from the login-form\r\n let userID = document.getElementById('id_no');\r\n let userName = document.getElementById('name');\r\n var userPw = document.getElementById('psw');\r\n\r\n // check if stored data from register-form is equal to data from login form\r\n if(userID.value == storedID && userName == storedName && userPw.value == storedPw) {\r\n alert('Error already hav an account');\r\n }else {\r\n alert('You Logged in.');\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
util functions for client.js empty the messages div | function emptyMessagesDiv() {
setInterval(function() {
$('#messages').html("");
$('#messages').removeClass();
}, 4000);
} | [
"function clearSomeMessages(){\n for(var i=0;i<10;i++){\n $(DOMelements.botBody+\" div:first-child\").remove();\n }\n messagesNum=0;\n }",
"function clear() {\n messages = [];\n }",
"clearStatusMessages() {\n const status_div = document.querySelector('.form-options-widget .status');\n status_div.innerHTML = '';\n }",
"function clearScreen()\n{\n document.body.removeChild( document.getElementById( \"space\" ) );\n document.getElementById( \"messages\" ).removeChild( document.getElementById( \"messages\" ).lastChild );\n}",
"resetChatBox() {\n\t\t$('#chat-message-box').val(\"\");\n\t}",
"function removeMessages(){\n\t//remove note message\n\tdocument.getElementById(\"notePopup1\").classList.remove(\"notePopup1\");\n\tdocument.getElementById(\"notePopup2\").classList.remove(\"notePopup2\");\n\n\t//remove win/lose/draw message\n\tvar status = Session.get(\"onMessage\");\n\tif(status == \"lock\"){\n\t\tSession.set(\"onMessage\", \"hold\");\n\t}else if(status == \"hold\" || status == \"free\"){ //should not include 'free', but hardcoded to solve a bug(rare though). look forward a better solution.\n\tdocument.getElementById(\"winPopup1\").classList.remove(\"winPopup1\");\n\tdocument.getElementById(\"winPopup2\").classList.remove(\"winPopup2\");\n\tdocument.getElementById(\"drawPopup\").classList.remove(\"drawPopup\");\n\tdocument.getElementById(\"losePopup1\").classList.remove(\"losePopup1\");\n\tdocument.getElementById(\"losePopup2\").classList.remove(\"losePopup2\");\n\n\tSession.set(\"onMessage\", \"free\");\n}\n}",
"function clearEndMsg()\n {\n endMsg.textContent = \"\";\n endMsg.style.visibility = \"hidden\";\n }",
"function removeAllmsg() {\n alertAdded.style.display = 'none';\n alertAdded.innerHTML = '';\n\n alertRemoved.style.display = 'none';\n alertRemoved.innerHTML = '';\n\n alertModified.style.display = 'none';\n alertModified.innerHTML = '';\n}",
"function sendAndClear(message) {\n if(message !== \"\") {\n ws.send(message);\n id(\"message\").value =\"\";\n }\n}",
"function unloadMessage(){\r\n $(\"#printMessageBox\").delay(1000).animate({opacity:0}, 700, function(){\r\n $(this).remove();\r\n });\r\n }",
"function clearContentBox(){\n\t\tcontent.html('');\n\t}",
"function clear_message_on_click($target) {\n $target.click(function() {\n $('#discourse-message').html('').removeClass();\n });\n }",
"function messageLosing() {\n\n $(`<section class=\"game-over\"><div class=\"message-box\"><h2>Try harder Marites 😔</h2>\n <h3>Kulang ang almusal mong tsismis</h3>\n <p>Number of attempts: ${attempts}</p>\n <p>Total Time: ${60-(seconds/1000)} seconds <p>Rating: ${stars} </p><p><i class=\"fas fa-undo\"></i><i class=\"fas fa-sign-out-alt\"></i><object data=\"leaderboard.svg\"></object>\n </p></div></section>`).insertAfter($('.gamebg'));\n restart(); goBack();\n $('.message-box').fadeIn(1000);\n }",
"function clearPlayerOneChat(i) {\n if (i.toLowerCase() == \"clear\") {\n for (var j = 0; j < self.playerOneMessages.length + 1; j++) {\n self.playerOneMessages.$remove(j);\n }\n }\n }",
"function setMessageDeleted (message_id){\n\tconst delete_msg = `<p>---CHAT DELETED---</p>`\n\tdocument.getElementById(message_id).innerHTML = delete_msg;\n\n}",
"function displayEmpty() {\n blogContainer.empty();\n var messageh2 = $(\"<h2>\");\n messageh2.css({ \"text-align\": \"center\", \"margin-top\": \"50px\" });\n // messageh2.html(\"No recipes yet for this category, navigate <a href='/cms'>here</a> in order to create a new Recipe.\");\n blogContainer.append(messageh2);\n }",
"function borrarMensajes() {\n let mensaje = document.getElementById(\"mensaje\");\n mensaje.innerHTML=\"\";\n}",
"function displayEmpty() {\n productContainer.empty();\n var messageH2 = $(\"<h2>\");\n messageH2.attr('id', 'no-product');\n messageH2.html(\"No products have been added that match your search yet. Check back regularly to see new products! <br> Try a different <a href='/index'>search.</a>\");\n productContainer.append(messageH2);\n }",
"function removeWinningMessage() {\n winningMessage.textContent = \"\";\n boardElement.classList.remove(\"hidden\");\n winningMessage.classList.remove(\"visible\");\n winningMessage.classList.add(\"hidden\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compares two values while ignoring undefined values. | function compare (a, b) {
return (a === b) ? (typeof a === 'undefined' ? a : true) : (typeof a === 'undefined' || typeof b === 'undefined');
} | [
"function compareValues(val1, val2){\r\n\tif (val1 > val2) {\r\n\t\treturn -1;\r\n\t} else if(val2 > val1) {\r\n\t\treturn 1;\r\n\t} else {\r\n\t\treturn 0;\r\n\t}\r\n}",
"function sameValueExact(a, b) { // flag for exaxt? which ignores eg 0\n var type = a.type\n\n if (type === \"Dimension\") {\n if (a.val === b.val && a.unit === b.unit)\n return true\n }\n if (type === \"Number\") { // dont exists, only 0?\n // we know b exists, only prop can give us undefined back, so no need to check if b.unit exists\n if (a.val === b.val)\n return false\n }\n if (type === \"Percentage\") {\n if (a.val === b.val)\n return false\n }\n // need to comapre args too..\n if (type === \"Function\") {\n if (isFunctionSame()) // pass arg?\n return false\n }\n\n // value can be auto - so can be ident?\n if (type === \"Identifier\") { // custom or not, WL, trust user.\n return false\n }\n\n}",
"function check(oval, nval) {\n if (oval !== undefined) {\n if (oval != nval) {\n throw Error(\"Values don't match\");\n }\n }\n return nval;\n}",
"function positCompareByValue(posit1, posit2) {\n return posit1.value-posit2.value;\n}",
"function NE(a, b) {\n return !EQ(a, b);\n}",
"function notEqual(first, second) {\n if (first !== second) {\n return \"Opposites do attact.\";\n }\n else {\n return \"Cause it's like you're my mirror.\";\n }\n}",
"function check_eq(a, b) {\n\tcheck_args(a, b);\n\ttoAInt(a).check_eq(b);\n}",
"function xorForMaybe(a, b) {\n var aIsSome = Maybe_1.isNotNullAndUndefined(a);\n var bIsSome = Maybe_1.isNotNullAndUndefined(b);\n if (aIsSome && !bIsSome) {\n return a;\n }\n if (!aIsSome && bIsSome) {\n return b;\n }\n // XXX: We can choose both `null` and `undefined`.\n // But we return `undefined` to sort with [Optional Chaining](https://github.com/TC39/proposal-optional-chaining)\n return undefined;\n}",
"function isCompatibleProperty(a, b) {\n\tif (a.blockStructure === b) {\n\t\treturn a.version > b.version ? 1 : 0\n\t}\n\tif (a.code === b.code && a.extendedType === b.extendedType) {\n\t\tvar sharedLength = Math.min(a.length, b.length)\n\t\tvar compatibility = 0\n\t\tfor (var i = 0; i < sharedLength; i++) {\n\t\t\tif (a[i].key !== b[i].key)\n\t\t\t\treturn -2\n\t\t\tvar childCompatibility = isCompatibleProperty(a[i], b[i])\n\t\t\tif (childCompatibility === -2)\n\t\t\t\treturn -2\n\t\t\tif (childCompatibility === -1) {\n\t\t\t\tif (compatibility === 1)\n\t\t\t\t\treturn -2\n\t\t\t\tcompatibility = -1\n\t\t\t}\n\t\t\tif (childCompatibility === 1) {\n\t\t\t\tif (compatibility === -1)\n\t\t\t\t\treturn -2\n\t\t\t\tcompatibility = 1\n\t\t\t}\n\t\t}\n\t\tvar sharedValuesLength = Math.min(a.values ? a.values.length : 0, b.values ? b.values.length : 0)\n\t\tfor (var i = 0; i < sharedValuesLength; i++) {\n\t\t\tif (a.values[i] !== b.values[i]) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t}\n\t\tif (a.length < b.length) {\n\t\t\tif (compatibility === 1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = -1\n\t\t} else if (a.length < b.length) {\n\t\t\tif (compatibility === -1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = 1\n\t\t}\n\t\t/*if (a.values.length < b.values.length) {\n\t\t\tif (compatibility === 1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = -1\n\t\t} else if (a.values.length < b.values.length) {\n\t\t\tif (compatibility === -1) {\n\t\t\t\treturn -2\n\t\t\t}\n\t\t\tcompatibility = 1\n\t\t}*/\n\t\treturn compatibility\n\t} else {\n\t\treturn -2\n\t}\n}",
"function notEqual (first, second){\n\tif (first !== second){\n\t\treturn \"Opposites do attract.\";\n\t} else {\n\t\treturn \"Cuz it's like you're my mirror\";\n\t}\n}",
"function unequal(a, b, c) {\n //return a !== b && ...\n return a !== b && a !== c && b !== c\n // if(a !== b && a !== c && b !== c){\n // return \"true\";\n // } else {\n // return \"false\";\n // }\n }",
"function LT(a, b) {\n if (ISREF(a) && ISREF(b)) {\n return error.na;\n } else if (ISARRAY(a) && ISARRAY(b)) {\n return error.na;\n } else if (ISREF(a) || ISARRAY(a)) {\n return a.map(function (d) {\n return d < b;\n });\n } else if (ISREF(b) || ISARRAY(b)) {\n return b.map(function (d) {\n return d < a;\n });\n } else {\n return a < b;\n }\n}",
"function min(a, b){\n if (a === null) a = 0;\n if (b === null) b = 0;\n if (isNaN(a) || isNaN(b)) return NaN;\n \n return a < b ? a : b;\n}",
"function arraySorter(a, b) {\n var retval = _.chain(_.zip(a.sort, b.sort)).map(function (x) {\n var aval = x[0]; \n var bval = x[1];\n if (aval === null || bval === null) {\n return 0;\n } else if (typeof(aval) === \"number\") {\n return aval - bval;\n } else {\n return aval.localeCompare(bval);\n };\n }).find(function(n) { return n !== 0; }).value();\n if (retval === undefined) {\n /* all the same, return 0 */\n return 0;\n } else {\n return retval;\n }\n}",
"function approxEqual(a, b, tolerance) {\n if (tolerance === void 0) {\n tolerance = 0.00001;\n }\n return Math.abs(a - b) <= tolerance;\n}",
"static pseudo_cmp(a, b) {\n if (a['$reql_type$'] === 'BINARY') {\n if (!('data' in a && 'data' in b)) {\n console.error(\"BINARY ptype doc lacking data field\", a, b);\n throw \"BINARY ptype doc lacking data field\";\n }\n const aData = rethinkdbGlobal.binary_to_string(a['data']);\n const bData = rethinkdbGlobal.binary_to_string(b['data']);\n return aData < bData ? -1 : aData > bData ? 1 : 0;\n }\n if (a['$reql_type$'] === 'TIME') {\n if (!('epoch_time' in a && 'epoch_time' in b)) {\n console.error(\"TIME ptype doc lacking epoch_time field\", a, b);\n throw \"TIME ptype doc lacking epoch_time field\";\n }\n // These are both numbers. And if they aren't, we'll just compare them.\n const aEpoch = a['epoch_time'];\n const bEpoch = b['epoch_time'];\n return aEpoch < bEpoch ? -1 : aEpoch > bEpoch ? 1 : 0;\n }\n console.error(\"pseudo_cmp logic error\", a, b);\n throw \"pseudo_cmp encountered unhandled type\";\n }",
"static compareReqlDocs(a, b) {\n // Handle undefined case, which may happen.\n if (a === undefined) {\n return b === undefined ? 0 : -1;\n }\n else if (b === undefined) {\n return 1;\n }\n // The logic here is cribbed from datum_t::cmp_unchecked_stack.\n const a_ptype = this.is_ptype(a) && !this.pseudo_compares_as_obj(a);\n const b_ptype = this.is_ptype(b) && !this.pseudo_compares_as_obj(b);\n if (a_ptype && b_ptype) {\n const a_reql_type = this.get_reql_type(a);\n const b_reql_type = this.get_reql_type(b);\n if (a_reql_type !== b_reql_type) {\n return a_reql_type < b_reql_type ? -1 : a_reql_type > b_reql_type ? 1 : 0;\n }\n return this.pseudo_cmp(a, b);\n }\n if (a_ptype || b_ptype) {\n const a_name_for_sorting = this.get_type_name(a);\n const b_name_for_sorting = this.get_type_name(b);\n return a_name_for_sorting < b_name_for_sorting ? -1 : a_name_for_sorting > b_name_for_sorting ? 1 : 0;\n }\n const a_type = this.get_type_name(a);\n const b_type = this.get_type_name(b);\n if (a_type !== b_type) {\n return a_type < b_type ? -1 : a_type > b_type ? 1 : 0;\n }\n switch (a_type) {\n case 'NULL':\n return 0;\n case 'BOOL':\n return a < b ? -1 : a > b ? 1 : 0;\n case 'NUMBER':\n return a < b ? -1 : a > b ? 1 : 0;\n case 'STRING':\n return this.reqlCompareStrings(a, b);\n case 'ARRAY':\n return this.reqlCompareArrays(a, b);\n case 'OBJECT':\n return this.reqlCompareArrays(this.sorted_keyvals(a), this.sorted_keyvals(b));\n default:\n console.error(\"Unhandled type in switch in compareReqlDocs\", a_type, a, b);\n throw \"compareReqlDocs: unhandled type\";\n }\n }",
"function assertEqual(a, b){\n return a_equals_b(a, b);\n }",
"function isEqualPass(obj1,obj2){\r\n\t var pw1 = obj1.value;\r\n\t var pw2 = obj2.value;\r\n\t \r\n\t if(pw1.length ==0 || pw2.length ==0){\r\n\t\t return true;\r\n\t }\r\n\t if(pw1 == pw2){\r\n\t\t return false;\r\n\t }\r\n\t \r\n\t return true;\r\n }",
"function equivalent(x,y){\n\tif(JSON.stringify(clone(x)) == JSON.stringify(clone(y))){\n\t\treturn true;\n\t}\n\telse{\n\t\treturn false;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.