query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
rectSet An object for tracking collections of intersecting rectangles and the path around them | function rectSet(){
this.covers = [];
this.paths = [];
this.primed = null;
} | [
"function rectSetPath(ctx, rectSet) {\n rectSet.forEach(function(r) {\n ctx.rect(r[0], r[1], r[2], r[3]);\n });\n }",
"function rectChooseMultiObject(){\n\tthis.beginPoint = createVector(0, 0); // is position of mouse when mouse down\n\tthis.endPoint = createVector(0, 0); // is positioni of mouse when mouse drag\n\tthis.isActive = false;\n\n\tthis.setActive = function(trueOrFalse){\n\t\tthis.isActive = trueOrFalse;\n\t}\n\n\tthis.setBegin = function(x, y){\n\t\tthis.beginPoint = createVector(x, y);\n\t}\n\n\tthis.setEnd = function(x, y){\n\t\tthis.endPoint = createVector(x, y);\n\t}\n\n\tthis.show = function(){\n\t\tstroke(255);\n\t\tstrokeWeight(1);\n\t\tnoFill();\n\t\tvar center = createVector(this.beginPoint.x+this.endPoint.x, this.beginPoint.y+this.endPoint.y).mult(0.5);\n\t\tvar size = createVector(abs(this.beginPoint.x-this.endPoint.x), abs(this.beginPoint.y-this.endPoint.y));\n\t\trect(center.x, center.y, size.x, size.y);\n\t}\n}",
"intersection(_rect) {\n return new HRect(\n Math.max(this.left, _rect.left), Math.max(this.top, _rect.top),\n Math.min(this.right, _rect.right), Math.min(this.bottom, _rect.bottom)\n );\n }",
"function rectChooseMultiObject() {\r\n\tthis.beginPoint = createVector(0, 0); // is position of mouse when mouse down\r\n\tthis.endPoint = createVector(0, 0); // is positioni of mouse when mouse drag\r\n\tthis.isActive = false;\r\n\r\n\tthis.setActive = function(trueOrFalse) {\r\n\t\tthis.isActive = trueOrFalse;\r\n\t}\r\n\r\n\tthis.setBegin = function(x, y) {\r\n\t\tthis.beginPoint = createVector(x, y);\r\n\t}\r\n\r\n\tthis.setEnd = function(x, y) {\r\n\t\tthis.endPoint = createVector(x, y);\r\n\t}\r\n\r\n\tthis.show = function() {\r\n\t\tstroke(255);\r\n\t\tstrokeWeight(1);\r\n\t\tnoFill();\r\n\t\tvar center = createVector(this.beginPoint.x + this.endPoint.x, this.beginPoint.y + this.endPoint.y).mult(0.5);\r\n\t\tvar size = createVector(abs(this.beginPoint.x - this.endPoint.x), abs(this.beginPoint.y - this.endPoint.y));\r\n\t\trect(center.x, center.y, size.x, size.y);\r\n\t}\r\n}",
"setRect(_rect) {\n if (this.rect) {\n this.rect.releaseView(this);\n }\n if (this.isString(_rect) && this.isFunction(this[_rect])) {\n _rect = this[_rect]();\n }\n if (this.isArray(_rect)) {\n this._setArrayRect(_rect);\n }\n else if (this.isObject(_rect) && _rect.hasAncestor(HRect)) {\n this.rect = _rect;\n }\n if (this.rect) {\n this.rect.bindView(this);\n }\n // this.refresh();\n return this;\n }",
"function drawIntersectionRects() {\n var intersections = calculateIntersections(data, startDate, selectedHour, data.agentCount - 1);\n\n var redScale = d3.scale.linear()\n .domain([data.agentCount, intersections.maxIntersections])\n .range([230, 255]);\n var opacityScale = d3.scale.linear()\n .domain([data.agentCount, intersections.maxIntersections])\n .range([0.2, 0.7]);\n\n var intersectionContainer = drawingPlane.selectAll(\".intersectionRect\")\n .data(intersections.intersections);\n intersectionContainer.enter()\n .append(\"rect\")\n .attr(\"class\", \"intersectionRect\")\n .attr(\"height\", height)\n .style(\"fill\", function (d) {\n return d3.rgb(redScale(d.intersectionCount), 0, 0);\n })\n .style(\"opacity\", function (d) {\n return opacityScale(d.intersectionCount)\n });\n intersectionContainer.exit().remove();\n }",
"intersected(rectangle) {\n return new QRectF(this.native.intersected(rectangle.native));\n }",
"function rectSetDraw(ctx, rectSet) {\n // First, draw the shadow.\n ctx.save();\n ctx.beginPath();\n ctx.translate(6, 6);\n rectSetPath(ctx, rectSet);\n ctx.globalAlpha = 0.2;\n ctx.fillStyle = 'black';\n ctx.fill();\n ctx.restore();\n\n // Now for the actual rectangle. We draw it in a blue color to make\n // it stand out from the white background.\n ctx.beginPath();\n rectSetPath(ctx, rectSet);\n ctx.fillStyle = '#ddddff';\n ctx.fill();\n ctx.lineWidth = 2;\n ctx.stroke();\n }",
"union(rect) {\n const ref = Rectangle.clone(rect);\n const myOrigin = this.origin;\n const myCorner = this.corner;\n const rOrigin = ref.origin;\n const rCorner = ref.corner;\n const originX = Math.min(myOrigin.x, rOrigin.x);\n const originY = Math.min(myOrigin.y, rOrigin.y);\n const cornerX = Math.max(myCorner.x, rCorner.x);\n const cornerY = Math.max(myCorner.y, rCorner.y);\n return new Rectangle(originX, originY, cornerX - originX, cornerY - originY);\n }",
"union(_rect) {\n return new HRect(\n Math.min(this.left, _rect.left), Math.min(this.top, _rect.top),\n Math.max(this.right, _rect.right), Math.max(this.bottom, _rect.bottom)\n );\n }",
"static union (rects) {\n let minx = null; let miny = null; let maxx = -Infinity; let maxy = -Infinity\n _.each(rects, function (rect) {\n minx = minx || rect.x\n miny = miny || rect.y\n minx = Math.min(minx, rect.x)\n miny = Math.min(miny, rect.y)\n maxx = Math.max(maxx, rect.right())\n maxy = Math.max(maxy, rect.bottom())\n })\n minx = minx || 0\n miny = miny || 0\n return new Rectangle(minx, miny, maxx - minx, maxy - miny)\n }",
"static containingRect(rects) {\n if (!rects || !rects.length) return undefined;\n\n // If only one thing, just clone it.\n if (rects.length === 1) return rects[0].clone();\n\n let { left, top, right, bottom } = rects[0];\n rects.forEach( (rect, index) => {\n if (index === 0) return;\n if (rect.left < left) left = rect.left;\n if (rect.top < top) top = rect.top;\n if (rect.right > right) right = rect.right;\n if (rect.bottom > bottom) bottom = rect.bottom;\n });\n\n return new Rect(left, top, right-left, bottom-top);\n }",
"function _via_region_rect() {\n this.is_inside = _via_region_rect.prototype.is_inside;\n this.is_on_edge = _via_region_rect.prototype.is_on_edge;\n this.move = _via_region_rect.prototype.move;\n this.resize = _via_region_rect.prototype.resize;\n this.initialize = _via_region_rect.prototype.initialize;\n this.dist_to_nearest_edge = _via_region_rect.prototype.dist_to_nearest_edge;\n}",
"convertRects() {\n\n const items = this.getElements('rect');\n\n for (let n = 0; n < (items || []).length; n++) {\n\n let x,\n y,\n w,\n h,\n proxy = [],\n path,\n node;\n\n node = items.item(n);\n\n console.log('Converting Rect to Path');\n\n x = +node.getAttribute(\"x\");\n y = +node.getAttribute(\"y\");\n w = +node.getAttribute(\"width\");\n h = +node.getAttribute(\"height\");\n\n proxy = this.getProxy(x, y, w, h, this.getAngle(node));\n\n path = this.addPath();\n\n path.setAttribute(\n \"d\",\n \"M\" + proxy[0].x + \" \" + proxy[0].y +\n \" L\" + proxy[1].x + \" \" + proxy[1].y +\n \" L\" + proxy[2].x + \" \" + proxy[2].y +\n \" L\" + proxy[3].x + \" \" + proxy[3].y +\n \" Z\"\n );\n\n path.setAttribute('class', node.getAttribute('class'));\n\n path.setAttribute(\n 'data-prevId',\n node.getAttribute('id') ||\n node.getAttribute('data-name') ||\n 'from-' + node.nodeName\n )\n\n if (node.getAttribute('transform')) {\n path.setAttribute(\n 'transform',\n node.getAttribute('transform')\n )\n }\n\n node.parentNode.insertBefore(path, node);\n }\n\n while ((items || []).length > 0) {\n items.item(0).parentNode.removeChild(items.item(0));\n }\n }",
"function drawRectangles(collection,coords)\n{\n\tvar latlng = new Array();\n\tvar latlng2 = new Array();\n\t\n\t//iterate through entire coords array unprojecting values and storing them \n\tvar i = 0;\n\twhile(coords[i] != null)\n\t{\n\t\tlatlng.push(rc.unproject([coords[i].x1, coords[i].y1]));\n\t\tlatlng2.push(rc.unproject([coords[i].x2, coords[i].y2]));\n\t\ti++;\n\t}\n\t\n\t//iterate through entire coords array\n\tvar j = 0;\n\twhile(coords[j] != null)\n\t{\n\t\tvar entryData; // This may not be in use anymore \n\t\t//create a rectangle object based on unprojected values of coords\n\t\t//add that rectangle object to viewer\n\t\tvar rectangle = L.rectangle([[latlng[j].lat, latlng[j].lng],\n\t\t[latlng2[j].lat, latlng2[j].lng]],{color: \"\t #58d68d\", weight: 1});\n\t\trectangleArray.push(rectangle);\n\t\tmap.addLayer(rectangleArray[j]);\n\t\t\n\t\t//click function that highlights clicked object and calls getEntryData.php \n\t\t//passes JSON from getEntryData.php as parameter to displayEntryData()\n\t\trectangle.on('click', function()\n\t\t{ \n\t\t\t// if the user has a marker drawn on the map exit click function early \n\t\t\tif(markerCount > 0)\n\t\t\t\treturn;\n\t\t\t\n\t\t\trectangleSelected = true; \n\t\t\t\n\t\t\tvar highlight = {color: \"#FF0000\", weight: 1};\n\t\t\tvar defaultColor = {color: \"#58d68d\", weight: 1};\t\t\t\n\n\t\t\tfor(var i = 0; i < rectangleArray.length; i++)\n\t\t\t{\n\t\t\t\trectangleArray[i].setStyle(defaultColor);\n\t\t\t}\n\t\t\t\n\t\t\tthis.setStyle(highlight);\n\n\t\t\tremoveTags(\"Client_Table\");\n\t\t\tremoveTags(\"RelatedPaper_Table\");\n\t\t\tremoveTags('JobNumber_Table');\n\t\t\t\n\t\t\t//get projected bounds latlng values of clicked rectangle to be used for querying database \n\t\t\tpoint1 = rc.project(this.getBounds()._southWest);\n\t\t\tpoint2 = rc.project(this.getBounds()._northEast);\n\t\t\t//initiates entryObject with coordinates and path of selected rectangle. \n\t\t\t//for use in getEntryData.php to query for other entry field date.\n\t\t\tentryObject = addEntryObject(collection,docID,point1.x, point1.y, point2.x, point2.y, fileName);\n\t\t\t$.ajax({\n\t\t\t\ttype: 'post',\n\t\t\t\turl: 'php/getEntryData.php',\n\t\t\t\tdata: {\"entryObject\": JSON.stringify(entryObject)},\n\t\t\t\tsuccess:function(data){\n\t\t\t\t\tentryData = JSON.parse(data);\n\t\t\t\t\tdisplayEntryData(entryData);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t\tj++;\n\t}\n}",
"intersects(rect) {\n return this.x <= rect.x + rect.width && rect.x <= this.x + this.width && this.y <= rect.y + rect.height && rect.y <= this.y + this.height;\n }",
"static intersection(...rects) {\n const { length } = rects;\n switch (length) {\n case 0:\n return Rectangle.INVALID;\n case 1:\n return Rectangle.of(rects[0]);\n default: {\n const rect0 = Rectangle.of(rects[0]);\n if (!rect0.isValid())\n return rect0;\n let { left, right, top, bottom } = rect0;\n for (let i = 1; i < length; i += 1) {\n const r = Rectangle.of(rects[i]);\n if (!r.isValid())\n return r;\n if (r.left > left)\n left = r.left;\n if (right > r.right)\n right = r.right;\n if (right < left)\n return Rectangle.INVALID;\n if (r.top > top)\n top = r.top;\n if (bottom > r.bottom)\n bottom = r.bottom;\n if (bottom < top)\n return Rectangle.INVALID;\n }\n return Rectangle.of({ left, right, top, bottom });\n }\n }\n }",
"function intersectRects(rect1,rect2){var res={left:Math.max(rect1.left,rect2.left),right:Math.min(rect1.right,rect2.right),top:Math.max(rect1.top,rect2.top),bottom:Math.min(rect1.bottom,rect2.bottom)};if(res.left<res.right&&res.top<res.bottom){return res;}return false;}",
"getRectangle(rect) {\n return this.minX > this.maxX || this.minY > this.maxY ? Rectangle.EMPTY : (rect = rect || new Rectangle(0, 0, 1, 1), rect.x = this.minX, rect.y = this.minY, rect.width = this.maxX - this.minX, rect.height = this.maxY - this.minY, rect);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the fx from the queue | function fx_remove_from_queue(fx) {
var currents = fx.cr;
if (currents) {
currents.splice(currents.indexOf(fx), 1);
}
} | [
"dequeue (fn) {\n this.queue.splice(this.getFunctionIndex(fn), 1)\n }",
"function remove () {\n fsCount[key]--\n\n // Remove from queue when emptied.\n if (fsCount[key] === 0) {\n delete fsQueue[key]\n delete fsCount[key]\n }\n }",
"function remove_file_from_queue() {\n\tvar file_id = $(this).data('fileid');\n\tvar file_to_remove = uploader.getFile(file_id);\n\tuploader.removeFile(file_to_remove);\n\t$(this).parent().remove();\n}",
"removes() {\n while (this.q.length) {\n this.q.pop();\n }\n }",
"removeQueue (event) {\n if (this._queue) {\n if (this._queue[event.stamp]) {\n delete this._queue[event.stamp]\n if (isEmpty(this._queue)) {\n delete this._queue\n }\n }\n }\n }",
"clearQueue() {\n if (this.isAnimating) {\n this._queue = [this._queueFirst];\n return;\n }\n this._queue = [];\n }",
"_unload () {\n forEach(this.queue, f => f(this.vendor))\n this.queue.splice(0, this.queue.length)\n }",
"function dequeue() {\n if (!queues[qname]) {\n return;\n }\n var nextCallback = queues[qname].shift();\n if (nextCallback) {\n nextCallback();\n }\n else {\n delete queues[qname];\n }\n }",
"clear() {\n this.queue = null;\n }",
"clear () {\n this._queue = []\n }",
"dequeue() {\n if(!this.isEmpty()) {\n delete this.queue[0];\n }\n }",
"removeAll() {\n this.queue = []\n }",
"remove (file) {\n\t\tlet queues = this.handling(file);\n\n\t\tqueues = queues.filter(queuedFile => queuedFile !== file);\n\t}",
"remove_from_queue(){ //takes off of front of queue, returns the removed instruction\n let done_instruction_array = this.queue.shift()\n if(this.is_queue_empty()) {\n this.unset_queue_blocking_instruction_maybe()\n }\n }",
"[types.DELMESSAGEQUEUE](state) {\n state.messageQueue.shift()\n }",
"function dequeue () {\n var element;\n\n while (this.queue.length > 0) {\n element = this.queue.shift();\n\n this[element.action].apply(this, element.args);\n }\n}",
"function clearQueue() {\n\n\tif (!currentUnit)\n\t\treturn;\n\n\tdeleteActions(currentUnit, function(data) {});\n\t$(\"#command-list\").html(\"\");\n\n}",
"clear() {\n this.queue = [];\n }",
"function done() {\n\t\t\tvar f = queue.shift();\n\t\t\tif (queue.length > 0) {\n\t\t\t\tqueue[0]();\n\t\t\t}\n\t\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns array of items in_array that are not_in array | array_new_items(in_array, not_in) {
let result = [];
for (let i = 0; i < in_array.length; i++) {
if (not_in.indexOf(in_array[i]) === -1) {
result.push(in_array[i]);
}
}
return result;
} | [
"function arrayNotContains(array, values) {\n if (!(array instanceof Array))\n return false;\n return values.every(value => array.indexOf(value) === -1);\n}",
"function arrayNotContains(array, values) {\n if (!(array instanceof Array))\n return false;\n return values.every(function (value) { return array.indexOf(value) === -1; });\n}",
"function exclude_array(a,e) {\n return a.filter(i=>i!==e);\n}",
"function notcontains(data, array) {\n for (i in array) {\n if (data == array[i]) {\n return false\n }\n\n }\n return true\n }",
"function except(array, excluded) {//This function takes in two arrays\n const output = []; //set output to an empty array, we will store exluded numbers in this array.\n for (let element of array) //itereate through each element of the first array\n if (!excluded.includes(element)) //check to see if the current element is in the excluded array\n output.push(element);// If it's not then we'll add this element to our output array.\n return output; \n}",
"function array_diff(a,b) {\r\n\treturn a.filter( val => !b.includes(val))\r\n}",
"function array_diff(a, b) {\n return a.filter(x => !b.includes(x))\n}",
"function array_diff(a, b) {\n return a.filter(x => !b.includes(x));\n}",
"function missing(arr) {\n var start = arr[0];\n var end = arr[arr.length - 1];\n var allElements = [];\n var missingElements = [];\n for (var i = start; i <= end; i++) {\n allElements.push(i);\n }\n for (var i = 0; i < allElements.length - 1; i++) {\n if (arr.indexOf(allElements[i]) === -1) {\n missingElements.push(allElements[i]);\n }\n }\n return missingElements;\n}",
"function array_diff(a, b) {\n let result = [];\n for (let i = 0; i < a.length; i ++) {\n if (!b.includes(a[i])){\n result.push(a[i]);\n }\n }\n return result;\n}",
"function arrayDiff(a, b) {\n return a.filter(x => !b.includes(x)); \n}",
"function findMissingValues(originalArr, newArr) {\n var result = [];\n for (var i = 0; i < originalArr.length; i++) {\n // check if in original array and then add if not in the result set already\n if (newArr.indexOf(originalArr[i]) === -1 && result.indexOf(originalArr[i]) === -1) {\n result.push(originalArr[i]);\n }\n }\n return result;\n}",
"function discardFromSet(p, q) {\n let arr = []\n for (let i = 0; i < q.length; i++) {\n if (arraysEqual(p, q[i])) {\n continue\n } else {\n arr.push(q[i])\n }\n }\n\n return arr\n }",
"notIn(a, b, prefix = '') {\n let notIn = [];\n prefix = prefix.length > 0 ? `${prefix}.` : '';\n\n for (const key of Array.from(Object.keys(a))) {\n const thisPath = `${prefix}${key}`;\n\n if (b[key] === undefined) {\n notIn.push(thisPath);\n\n } else if ((typeof a[key] === 'object') && (!(a[key] instanceof Array))) {\n notIn = notIn.concat(this.notIn(a[key], b[key], thisPath));\n }\n }\n\n return notIn;\n }",
"function missing(arr) {\n var result = [];\n var first = arr[0];\n var last = arr[arr.length - 1];\n\n for (var i = first; i < last; i++) {\n if (arr.indexOf(i) === -1) {\n result.push(i);\n }\n }\n\n return result;\n}",
"function removeNoVotesFromList(initialOptions, noArray){\n let updatedOptions = []\n for (let noInd = 0; noInd < initialOptions.length; noInd++) {\n if (noArray.indexOf(initialOptions[noInd]) == -1) {\n updatedOptions = updatedOptions.concat(initialOptions[noInd]);\n }\n }\n return updatedOptions;\n}",
"function filterNonUnique(array) {\n let uniqueArray = [];\n uniqueArray = array.filter(function (element) {\n return (array.indexOf(element) === array.lastIndexOf(element))\n })\n return uniqueArray;\n}",
"function filterFalsy(array) {\n var result = [];\n for (var i = 0; i < array.length; i++) {\n if (!array[i]) {\n continue;\n }\n result[result.length] = array[i];\n }\n return result;\n}",
"function set_difference(arr1, arr2) {\n return arr1.filter(x => !arr2.includes(x));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a stack parser implementation from Options.stackParser | function stackParserFromStackParserOptions(stackParser) {
if (Array.isArray(stackParser)) {
return createStackParser(...stackParser);
}
return stackParser;
} | [
"function stackParserFromStackParserOptions(stackParser) {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n }",
"function _getParser(options){\r\n return (options && options.parser) || setDefaultParser();\r\n}",
"get stack() {\n // Lazy import to break cyclic import\n const stack = require('./stack');\n return this._stack || (this._stack = _lookStackUp(this));\n function _lookStackUp(_this) {\n if (stack.Stack.isStack(_this.host)) {\n return _this.host;\n }\n if (!_this.scope) {\n throw new Error(`No stack could be identified for the construct at path ${_this.path}`);\n }\n return _this.scope.node.stack;\n }\n }",
"getParser() {\n return this.parser;\n }",
"getParserFor(source) {\n const config = this.getConfigFor(source.filename);\n return new parser_1.Parser(config);\n }",
"get parser() {\n return this._parser || this.scope?.parser\n }",
"getParser(){\n \treturn this.parser;\n }",
"function getParserConfig(parserName){\n var out = null;\n config.parsers.forEach(function(item){\n if(item.name === parserName){\n out = item;\n }\n })\n return out;\n }",
"function getParser(ext) {\n return _.find(PARSERS, function(input) {\n return input.name == ext || _.contains(input.extensions, ext);\n });\n}",
"get parser() { return this.p.parser; }",
"instantiateParser() {\n return new this.ParserClass(this.config);\n }",
"stackToTree(stack) {\n stack.close();\n return Tree.build({ buffer: StackBufferCursor.create(stack),\n nodeSet: this.parser.nodeSet,\n topID: this.topTerm,\n maxBufferLength: this.parser.bufferLength,\n reused: this.reused,\n start: this.ranges[0].from,\n length: stack.pos - this.ranges[0].from,\n minRepeatType: this.parser.minRepeatTerm });\n }",
"stackToTree(stack) {\n stack.close();\n return Tree.build({ buffer: StackBufferCursor.create(stack),\n nodeSet: this.parser.nodeSet,\n topID: this.topTerm,\n maxBufferLength: this.parser.bufferLength,\n reused: this.reused,\n start: this.ranges[0].from,\n length: stack.pos - this.ranges[0].from,\n minRepeatType: this.parser.minRepeatTerm });\n }",
"function createStackParser(...parsers) {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack, skipFirst = 0) => {\n const frames = [];\n\n for (const line of stack.split('\\n').slice(skipFirst)) {\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = line.replace(/\\(error: (.*)\\)/, '$1');\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n }\n\n return stripSentryFramesAndReverse(frames);\n };\n}",
"getDefaultParser() {\n return this.namespace().PlainTextStructureParser.new()\n }",
"function getParser(name, opts) {\n let parser = name;\n\n // We don't want to deal with some weird recursive parser situation, so we\n // need to explicitly call out the HAML parser here and just return null\n if (parser === \"haml\") {\n return null;\n }\n\n // In HAML the name of the JS filter is :javascript, whereas in prettier the\n // name of the JS parser is babel. Here we explicitly handle that conversion.\n if (parser === \"javascript\") {\n parser = \"babel\";\n }\n\n // If there is a plugin that has a parser that matches the name of this\n // element, then we're going to assume that's correct for embedding and go\n // ahead and switch to that parser\n if (\n opts.plugins.some(\n (plugin) =>\n plugin.parsers &&\n Object.prototype.hasOwnProperty.call(plugin.parsers, parser)\n )\n ) {\n return parser;\n }\n\n return null;\n}",
"function parserSwitch ( tag ) {\n var parser;\n if(grunt.file.isFile('tasks/user-parsers/' + tag)){\n var req_path = './user-parsers/' + tag;\n parser = require(req_path);\n }else{\n switch (tag.toString().toLowerCase())\n {\n case 'json':\n parser = require('./default-parsers/JSONParser');\n break;\n case 'minimalxml':\n parser = require('./default-parsers/minimalXMLParser');\n break;\n case 'plaintext':\n parser = require('./default-parsers/plainTextParser');\n break;\n case 'decoratedplaintext':\n parser = require('./default-parsers/decoratedPlainTextParser');\n break;\n default:\n parser = require('./default-parsers/plainTextParser');\n }\n }\n parser.init(grunt, options);\n return parser;\n }",
"function setStack(s) {\n if (arguments.length) {\n if (s) {\n stack = s;\n } else {\n stack = undefined;\n }\n }\n return stack || ostack;\n }",
"getStack (stackName) {\n let stacks = this.get('stacks');\n if (stacks[stackName]) {\n return stacks[stackName];\n } else {\n throw new Error(`Stack with name ${stackName} not found.`);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change provider in home route | function changeProvider(route, provider) {
switch (route.type) {
case 'collections':
case 'collection':
case 'search':
if (route.params === void 0) {
route.params = {};
}
route.params.provider = provider;
}
if (route.parent) {
changeProvider(route.parent, provider);
}
} | [
"function go_providers() {\n $state.go('providers.list');\n }",
"function setProvider(p) {\n\t\tprovider = p;\n\t}",
"function setProvider(provider) {\n _provider = provider;\n}",
"function registerHomeRoute(\n $stateProvider\n ) {\n $stateProvider.state(\n \"home\",\n {\n url: \"/views/home\",\n component: \"spiderHome\"\n }\n );\n }",
"function go_providers() {\n $state.go('providers_debts.list');\n }",
"function updateProviderDetailsRoute(req, res, next) {\n\tif (req.session.isAdmin !== 1) {\n\t\t!req.session.isAdmin;\n\t\tres.redirect('/logout');\n\t} else {\n\t\tlet query =\n\t\t\t'UPDATE care_provider SET careprovider_firstname=?, careprovider_lastname=?, careprovider_username=? WHERE careprovider_id=?';\n\t\tdb.query(\n\t\t\tquery,\n\t\t\t[ req.body.provider_fname, req.body.provider_lname, req.body.provider_username, req.params.id ],\n\t\t\t(error, results, fields) => {\n\t\t\t\tres.redirect(`/provider/${req.params.id}`);\n\t\t\t}\n\t\t);\n\t}\n}",
"setProvider()\n {\n this.provider = new ProviderList[this.settings.provider](this.settings);\n }",
"changeProvider(providerName = DEFAULT_PROVIDER) {\n this.dispatch(changeProvider(providerName));\n }",
"function routeProvider($routeProvider) {\n $routeProvider\n .when(\"/collections\", {\n templateUrl: \"app/cakes-list/cakes.html\",\n controller: \"CakesController\",\n controllerAs: \"vm\"\n })\n .when(\"/christmas\", {\n templateUrl: \"app/cakes-list/christmas.html\",\n controller: \"CakesController\",\n controllerAs: \"vm\"\n })\n .when(\"/collections/paradise/:cakeID\", {\n templateUrl: \"app/cake/cake.html\",\n controller: \"CakeDetailController\",\n controllerAs: \"vm\"\n })\n .when(\"/collections/quartets/:cakeID\", {\n templateUrl: \"app/cake/seasonal-cake.html\",\n controller: \"CakeDetailController\",\n controllerAs: \"vm\"\n })\n .when(\"/collections/seasonal/:cakeID\", {\n templateUrl: \"app/cake/collection-cake.html\",\n controller: \"CakeCollectionDetailController\",\n controllerAs: \"vm\"\n })\n .when(\"/collections/holiday/:cakeID\", {\n templateUrl: \"app/cake/collection-cake.html\",\n controller: \"CakeCollectionDetailController\",\n controllerAs: \"vm\"\n })\n .when(\"/collections/celebration/:cakeID\", {\n templateUrl: \"app/cake/collection-cake.html\",\n controller: \"CakeCollectionDetailController\",\n controllerAs: \"vm\"\n })\n .when(\"/cupcake/:cakeID\", {\n templateUrl: \"app/cupcakes/cupcakes-single.html\",\n controller: \"CupCakeDetailController\",\n controllerAs: \"vm\"\n })\n .when(\"/collections/cake-order/:cakeID\", {\n templateUrl: \"app/cake-order/order.html\",\n controller: \"CakeOrderController\",\n controllerAs: \"vm\"\n })\n .when(\"/cupcake-order/:cakeID\", {\n templateUrl: \"app/cupcakes/cupcakeorder.html\",\n controller: \"CakeOrderController\",\n controllerAs: \"vm\"\n })\n .when(\"/thank-you\", {\n templateUrl: \"app/thanks/thanks.html\",\n controller: \"ThanksController\",\n controllerAs: \"vm\"\n })\n .when(\"/home\", {\n templateUrl: \"app/home/home.html\",\n controller: \"HomeController\",\n controllerAs: \"vm\"\n })\n .when(\"/contact\", {\n templateUrl: \"app/contact/contact.html\",\n controller: \"\",\n controllerAs: \"vm\"\n })\n .when(\"/cupcakes\", {\n templateUrl: \"app/cupcakes/cupcakes.html\",\n controller: \"CupCakeController\",\n controllerAs: \"vm\"\n })\n .when(\"/menu\", {\n templateUrl: \"app/menu/menu.html\",\n controller: \"\",\n controllerAs: \"vm\"\n })\n .when(\"/gluten\", {\n templateUrl: \"app/gluten/gluten.html\",\n controller: \"HomeController\",\n controllerAs: \"vm\"\n })\n .when(\"/customcakes\", {\n templateUrl: \"app/custom/customcakes.html\",\n controller: \"CakeOrderController\",\n controllerAs: \"vm\"\n })\n .when(\"/faqs\", {\n templateUrl: \"app/home/faqs.html\",\n controller: \"HomeController\",\n controllerAs: \"vm\"\n })\n .otherwise({\n redirectTo: \"/home\"\n });\n }",
"onSocialLogin(provider) {\r\n this.provider = provider;\r\n this.authService.socialLogin(provider);\r\n }",
"function CapstoneRouteConfig($routeProvider, $locationProvider) {\n var app_dir = '../../pages/new';\n\n $routeProvider.otherwise('/login');\n\n $routeProvider\n .when('/list', {\n templateUrl: app_dir + '/list.html',\n controller: productCtrl\n }).when('/cart', {\n templateUrl: app_dir + '/cart.html',\n controller: cartCtrl\n }).when('/login', {\n templateUrl: app_dir + '/login.html',\n controller: productCtrl\n }).when('/productDetails/:id', {\n templateUrl: app_dir + '/product-details.html',\n controller: detailsCtrl\n })\n}",
"function changeProviderId() {\n\tlet id = providerList.options[providerList.selectedIndex].value;\n\tif (typeof providers !== 'undefined' && providers.hasOwnProperty(id) && providers[id].hasOwnProperty('provider_id')) {\n\t\tproviderId = providers[id].provider_id;\n\t\tbackground.setProviderId(providerId);\n\t}\n}",
"defaultRoute() {\n this.navigate('contacts', true);\n }",
"function AppConfig($routeProvider){\n $routeProvider\n .when('/home',{\n templateUrl: '../templates/home.tpl.html',\n controller: 'homeController'\n })\n .when('/about',{\n templateUrl: '../templates/about.tpl.html',\n controller: 'projectController'\n })\n .otherwise('/home');\n }",
"setLocationProvider( name, options ) {\n if(typeof name === 'object') {\n this.locationProvider = name;\n }\n\n this.locationProvider = locationProviderFactory.create(name, options);\n }",
"function Config($routeProvider) {\n $routeProvider\n .when(\"/\",{\n redirectTo: \"/login\"\n })\n .when(\"/user/:uid/website/:wid/page/:pid/widget/:wgid/flickr\", {\n templateUrl: \"views/widget/widget-flickr-search.view.client.html\",\n controller: \"FlickrImageSearchController\",\n controllerAs: \"model\"\n })\n .when(\"/login\", {\n templateUrl: \"views/user/login.view.client.html\",\n //To make the controller and the corresponding HTML aware that they are associated with each other.\n controller: \"LoginController\",\n //To access the instance of the LoginController in the view. Binds the controller instance to a name\n //which is used in the view.\n controllerAs: \"model\"\n })\n .when(\"/register\", {\n templateUrl: \"views/user/register.view.client.html\",\n controller: \"RegisterController\",\n controllerAs: \"model\"\n })\n .when(\"/user\", {\n templateUrl: \"views/user/profile.view.client.html\",\n controller: \"ProfileController\",\n controllerAs: \"model\",\n resolve: {\n loggedIn: checkLoggedIn\n }\n })\n .when(\"/user/:uid\", {\n templateUrl: \"views/user/profile.view.client.html\",\n controller: \"ProfileController\",\n controllerAs: \"model\",\n resolve: {\n loggedIn: checkLoggedIn\n }\n })\n .when(\"/user/:uid/website\", {\n templateUrl: \"views/website/website-list.view.client.html\",\n controller: \"WebsiteListController\",\n controllerAs: \"model\"\n })\n .when(\"/user/:uid/website/new\", {\n templateUrl: \"views/website/website-new.view.client.html\",\n controller: \"NewWebsiteController\",\n controllerAs: \"model\"\n })\n .when(\"/user/:uid/website/:wid\", {\n templateUrl: \"views/website/website-edit.view.client.html\",\n controller: \"EditWebsiteController\",\n controllerAs: \"model\"\n })\n .when(\"/user/:uid/website/:wid/page\", {\n templateUrl: \"views/page/page-list.view.client.html\",\n controller: \"PageListController\",\n controllerAs: \"model\"\n })\n .when(\"/user/:uid/website/:wid/page/new\", {\n templateUrl: \"views/page/page-new.view.client.html\",\n controller: \"NewPageController\",\n controllerAs: \"model\"\n })\n .when(\"/user/:uid/website/:wid/page/:pid\", {\n templateUrl: \"views/page/page-edit.view.client.html\",\n controller: \"EditPageController\",\n controllerAs: \"model\"\n })\n .when(\"/user/:uid/website/:wid/page/:pid/widget\", {\n templateUrl: \"views/widget/widget-list.view.client.html\",\n controller: \"WidgetListController\",\n controllerAs: \"model\"\n })\n .when(\"/user/:uid/website/:wid/page/:pid/widget/new\", {\n templateUrl: \"views/widget/widget-chooser.view.client.html\",\n controller: \"NewWidgetController\",\n controllerAs: \"model\"\n })\n .when(\"/user/:uid/website/:wid/page/:pid/widget/:wgid\", {\n templateUrl: \"views/widget/widget-edit.view.client.html\",\n controller: \"EditWidgetController\",\n controllerAs: \"model\"\n })\n .otherwise({\n redirectTo: \"/login\"\n });\n\n //$q allows to work with promises and asynchronous call\n function checkLoggedIn(UserService, $location, $q, $rootScope) {\n\n var deferred = $q.defer();\n\n UserService\n .loggedIn()\n .then(\n function(response) {\n var user = response.data;\n if(user == '0') {\n $rootScope.currentUser = null;\n deferred.reject();\n $location.url(\"/login\");\n }\n else {\n $rootScope.currentUser = user;\n deferred.resolve();\n }\n },\n function(error) {\n $location.url(\"/login\");\n }\n );\n\n return deferred.promise;\n }\n\n }",
"addProvider(provider) {\n let entryIndex = this.providers.findIndex((command) => {\n return command === provider;\n });\n entryIndex = entryIndex === -1 ? this.providers.length : entryIndex;\n this.providers[entryIndex] = provider;\n this.set(`providers[${entryIndex}]`, provider);\n }",
"navigateToSeatManager() {\n\t\tthis.context.router.push('/admin/seats');\n\t}",
"function initProviderIfNull () {\n if (currentProvider === undefined) {\n const newProvider = readFromStorage('authProvider')\n if (newProvider !== undefined && newProvider !== null) {\n setProvider(newProvider)\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Aging LIFO queue A queue where elements will have two fates: > The element is dequeued within a specific peroid of time > A queue specific period of times passes and the element is dequeued. TOOD: Is there a better name? This could also be confused with a LIFO queue where a number of operations occur before evicting elements | function aging_lifo_queue( timer ){
timer = timer || real_clock_timer();
var self = [];
self.timeout = 1000;
self.enqueue = function( element, expiryCallback ){
expiryCallback = expiryCallback || nope;
var expiryClock = timer.expiresAt( self.timeout, function(){
self.splice( self.lastIndexOf( handle ), 1 );
expiryCallback();
});
var handle = { //TODO: Probably should become a real object
datum: element,
cancelTimer: function(){
expiryClock.cancel();
}
};
self.push( handle );
}
self.dequeue = function(){
if( self.length == 0 ){ throw new Error("empty"); }
var handle = self.pop();
handle.cancelTimer();
return handle.datum;
}
return self;
} | [
"function TidyFifoQueue() { }",
"timeout() {\n if (this.queue.length === 0 && this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n return;\n }\n\n const removed = [];\n const now = Date.now();\n\n this.queue.forEach((item) => {\n if (item.timeout <= now) {\n removed.push(item);\n this.emit('timeout', item.data);\n }\n });\n\n removed.forEach((item) => uset.remove(this.queue, item));\n\n if (this.queue.length !== 0) {\n this.reset();\n }\n }",
"_cleanQueue () {\n const now = Date.now();\n let lastDocumentIndex = -1;\n\n if (this.queueTTL > 0) {\n this.offlineQueue.forEach((query, index) => {\n if (query.ts < now - this.queueTTL) {\n lastDocumentIndex = index;\n }\n });\n\n if (lastDocumentIndex !== -1) {\n this.offlineQueue\n .splice(0, lastDocumentIndex + 1)\n .forEach(droppedRequest => {\n this.emit('offlineQueuePop', droppedRequest.query);\n });\n }\n }\n\n if (this.queueMaxSize > 0 && this.offlineQueue.length > this.queueMaxSize) {\n this.offlineQueue\n .splice(0, this.offlineQueue.length - this.queueMaxSize)\n .forEach(droppedRequest => {\n this.emit('offlineQueuePop', droppedRequest.query);\n });\n }\n }",
"scheduleOp(op) {\n const q = [...this.queue];\n q.push(op);\n this.queue = q;\n }",
"enqueue(element, priority) {\n let el = new QueueElement(element, priority);\n let contain = false;\n\n //iterate through the entire item array to add element at the correct location of the Queue\n for (let i = 0; i < this.items.length; i++) {\n if (el.priority < this.items[i].priority) {\n //once the correct location is found, it is enqueued\n this.items.splice(i, 0, el);\n contain = true;\n break;\n }\n }\n //if the element has the highest priority it is added at the end of the queue\n if (!contain) {\n this.items.push(el);\n }\n }",
"enqueue(element, priority){\n var newElement = new QueueEntry(element, priority);\n var valueExists = false; \n\n for(var i = 0; i < this.items.length; i++){\n if(this.items[i].priority > newElement.priority) {\n this.items.splice(i, 0, newElement);\n valueExists = true; \n break; \n }\n }\n if(!valueExists){\n this.items.push(newElement);\n }\n }",
"function ExpiringQueue(callback, ttl) {\n var queue = [];\n var timeoutId;\n\n this.push = function (event) {\n if (event instanceof Array) {\n queue.push.apply(queue, event);\n } else {\n queue.push(event);\n }\n\n reset();\n };\n\n this.updateWithWins = function (winEvents) {\n winEvents.forEach(function (winEvent) {\n queue.forEach(function (prevEvent) {\n if (prevEvent.event === 'bidResponse' && prevEvent.auctionId == winEvent.auctionId && prevEvent.adUnitCode == winEvent.adUnitCode && prevEvent.adId == winEvent.adId && prevEvent.adapter == winEvent.adapter) {\n prevEvent.bidWon = true;\n }\n });\n });\n };\n\n this.popAll = function () {\n var result = queue;\n queue = [];\n reset();\n return result;\n };\n /**\n * For test/debug purposes only\n * @return {Array}\n */\n\n\n this.peekAll = function () {\n return queue;\n };\n\n this.init = reset;\n\n function reset() {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n\n timeoutId = setTimeout(function () {\n if (queue.length) {\n callback();\n }\n }, ttl);\n }\n}",
"queueReverse(){}",
"enqueue(element, priority) \n{ \n\t// creating object from queue element \n\tvar qElement = new QElement(element, priority); \n\tvar contain = false; \n\t// iterating through the entire \n\t// item array to add element at the \n\t// correct location of the Queue \n\tfor (var i = 0; i < this.items.length; i++) { \n\t\tif (this.items[i].priority > qElement.priority) { \n\t\t\t// Once the correct location is found it is \n\t\t\t// enqueued \n\t\t\tthis.items.splice(i, 0, qElement); \n\t\t\tcontain = true; \n\t\t\tbreak; \n\t\t} \n\t} \n\t// if the element have the highest priority \n\t// it is added at the end of the queue \n\tif (!contain) { \n\t\tthis.items.push(qElement); \n\t} \n}",
"function Queue(){var a=[],b=0;this.getLength=function(){return a.length-b};this.isEmpty=function(){return 0==a.length};this.enqueue=function(b){a.push(b)};this.dequeue=function(){if(0!=a.length){var c=a[b];2*++b>=a.length&&(a=a.slice(b),b=0);return c}};this.peek=function(){return 0<a.length?a[b]:void 0}}",
"enqueue(element, priority) { \n // creating object from queue element \n var qElement = new QElement(element, priority); \n var contain = false; \n \n // iterating through the entire \n // item array to add element at the \n // correct location of the Queue \n for (var i = 0; i < this.items.length; i++) { \n if (this.items[i].priority > qElement.priority) { \n // Once the correct location is found it is \n // enqueued \n this.items.splice(i, 0, qElement); \n contain = true; \n break; \n } \n } \n \n // if the element have the highest priority \n // it is added at the end of the queue \n if (!contain) { \n this.items.push(qElement); \n } \n }",
"function process_queue( last_element ) {\n if ( queue.length > 0 ) {\n var element = queue.shift();\n element.toggleClass( \"collapsed\" );\n setTimeout( process_queue, 300, element );\n }\n if ( last_element !== undefined && last_element.hasClass( \"collapsed\" ) ) {\n last_element.remove();\n }\n }",
"enQueue(element) {\r\n if (this.isFull()) {\r\n console.log('The queue is completely full..');\r\n } else {\r\n // Overflow\r\n if (this.front == -1) {\r\n this.front = 0;\r\n }\r\n this.rear = (this.rear + 1) % this.size;\r\n // console.log(this.rear);\r\n this.items[this.rear] = element;\r\n console.log('The item ' + element + ' inserted');\r\n }\r\n }",
"dequeue(){ \n // removing element from the queue \n // returns underflow when called \n // on empty queue \n if(this.isEmpty()) \n return console.log(\"Underflow\");\n return this.items.shift(); \n }",
"scheduleDequeue() {\n if (this.dequeue_scheduled) {\n // A dequeue is already going to happen, don't trigger it twice\n return;\n }\n\n // Prevent multiple dequeue's from stacking\n this.dequeue_scheduled = true;\n\n this.dequeue_tmr = setTimeout(() => {\n this.dequeue_scheduled = false;\n this.dequeue();\n }, this.queue_interval);\n }",
"dequeue() {\n\n // if the queue is empty, return immediately\n if (this._queue.length == 0) {\n return undefined;\n }\n\n // store the item at the front of the queue\n const 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 return item;\n\n }",
"removeQueue (event) {\n if (this._queue) {\n if (this._queue[event.stamp]) {\n delete this._queue[event.stamp]\n if (isEmpty(this._queue)) {\n delete this._queue\n }\n }\n }\n }",
"function batchingQueue(\n { max_qty, quiesce_time},\n { current_timestamp, setTimeout, clearTimeout },\n sink,\n) {\n let buf = [];\n let quiescing;\n const toDate = ts => new Date(ts);\n\n function flush() {\n if (buf.length > 0) {\n sink(buf); // ISSUE: async? consume promise?\n buf = [];\n }\n if (quiescing !== undefined) {\n clearTimeout(quiescing);\n quiescing = undefined;\n }\n }\n\n return harden({\n push: (item) => {\n let due = false;\n const t = current_timestamp();\n buf.push(item);\n if (buf.length >= max_qty) {\n console.log({ current: toDate(t), qty: buf.length, max_qty });\n flush();\n } else {\n if (quiescing !== undefined) {\n clearTimeout(quiescing);\n }\n const last_activity = t;\n quiescing = setTimeout(() => {\n const t = current_timestamp();\n console.log({\n quiesce_time,\n current: toDate(t),\n last_activity: toDate(last_activity),\n delta: (t - last_activity) / 1000,\n });\n flush();\n }, quiesce_time);\n }\n },\n finish: () => {\n flush();\n }\n });\n}",
"function TweetQueue() {\n EE.call(this);\n this.queue = [];\n // This queue shouldn't be pushed onto because another\n // fill request is in session.\n this.lock = false;\n // The # of queue items the queue contains\n // or less where a 'low' event will be emitted by\n // the queue.\n this.lowThreshold = 10; \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ajax adm com post | function ajaxPostAdmin(funcao, array, action){
jQuery(function(){
jQuery.ajax({
url: getUrlController()+"/admin"+action,
dataType: "json",
type: "post",
data:array,
beforeSend: function() {
},
success: function(json){
funcao(json);
}
});
});
return false;
} | [
"function ajax_post(url,cmd){\r\n var dt = new Date();\r\n url = url + '?t=' + dt.getTime();\r\n var xmlhttp = false;\r\n xmlhttp = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject(\"Microsoft.XMLHTTP\");\r\n xmlhttp.open(\"POST\", url,false);\r\n xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');//使用POST\r\n xmlhttp.send(cmd);\r\n if (xmlhttp.readyState == 4 && xmlhttp.status == 200){\r\n return xmlhttp.responseText;\r\n }else{\r\n alert('伺服器錯誤' + xmlhttp.status );\r\n return null;\r\n }\r\n}",
"function postGuardaRegistro(categoria,pollo,lote,cantidad,kilos){\n $.ajax({\n type: 'ajax',\n method: 'post',\n url: 'http://localhost/polleria/inventario/add_ahogado_descompuesto',\n data: { categoria:categoria,pollo:pollo,lote:lote,cantidad:cantidad,kilos:kilos },\n async: true,\n dataType: 'json',\n success: function(response){ \n console.log(response);\n if (response.success) {\n alertify.set('notifier','position', 'bottom-center');\n alertify.success('Registro Guardado !');\n } \n },\n error: function(response){\n console.log('error');\n console.log(response);\n\n }\n\n });\n}",
"function postGuardaProcesado(categoria,kilos,lote,cantidad){\n $.ajax({\n type: 'ajax',\n method: 'post',\n url: 'http://localhost/polleria/entrada_stock_procesado/add',\n data: { categoria:categoria,kilos:kilos,lote:lote,cantidad:cantidad},\n async: true,\n dataType: 'json',\n success: function(response){ \n console.log(response); \n if (response.success) {\n alertify.set('notifier','position', 'bottom-center');\n alertify.success('Entrada Pollo Procesado Guardada !');\n } \n },\n error: function(response){\n console.log('error');\n console.log(response);\n\n }\n\n });\n}",
"function postGuardaVivo(cantidadPollo){\n $.ajax({\n type: 'ajax',\n method: 'post',\n url: 'http://localhost/polleria/entrada_stock_vivo/add',\n data: { cantidad:cantidadPollo},\n async: true,\n dataType: 'json',\n success: function(response){ \n console.log(response);\n if (response.success) {\n alertify.set('notifier','position', 'bottom-center');\n alertify.success('Entrada Guardada !');\n } \n },\n error: function(response){\n console.log('error');\n console.log(response);\n\n }\n\n });\n}",
"function doPost(e) {\r\n // data e kita verifikasi\r\n var update = tg.doPost(e);\r\n\r\n // jika data valid proses pesan\r\n if (update) {\r\n prosesPesan(update);\r\n }\r\n}",
"function postAjax(){\n console.log(\"POST message\");\n var sendingData = \n {\n name: $(\"#Nom\").val(),\n link: $(\"#Lien\").val()\n }\n\n $.ajax({\n\n url: \"http://localhost:3000/profile\",\n method: \"POST\",\n contentType: \"application/json\",\n data: sendingData,\n }).done(function(response) {\n\n //Return response after post request\n console.log(response);\n \n });\n }",
"function doPost(e) {\n \n // Memastikan pesan yang diterima hanya dalam format JSON \n if(e.postData.type == \"application/json\") {\n \n // Kita parsing data yang masuk\n var update = JSON.parse(e.postData.contents);\n \n // Jika data pesan update valid, kita proses\n if (update) {\n //kirim variable update ke fungsi 'prosesPesan'\n prosesPesan(update);\n }\n } \n}",
"function AjaxSendRequestPost(tabla, uid, showdate){\t\n\t//!creando el objeto ResponseObject\n\tvar obj = new Object();\n\t//!Creando la funcion ResponseFunction para el ResponseObject\n\tobj.responseFunction = function(responseText){\t\t\n\t\t//!Esta funcion, la cual sera invocada cuando se reciba un mensaje de vuelta del servidor, ejecutara el metodo CatchNewPost, ubicado en EditInPlace.js\n\t\tCatchNewPost(tabla, responseText);\n\t}\n\tvar xmlHttp = AjaxSend(\"action=getpost&tabla=\" + tabla + \"&uid=\" + uid + \"&showdate=\" + showdate, obj);\n}",
"function ajaxPostNoticia () {\n var formData = new FormData($('#formNoticia')[0])\n\n $.ajax({\n type: \"POST\",\n url: '/api/noticias',\n data: formData,\n processData: false,\n contentType: false,\n success: result => { \n window.location.replace('/admin/noticias')\n },\n error: error => {\n $('#formNoticia p').remove()\n $('#formNoticia').append('<p style=\"color: red;\">Erro na criação da notícia.</p>' )\n }\n });\n }",
"function postIncrementaProcesado(categoria,kilos,cantidad){\n $.ajax({\n type: 'ajax',\n method: 'post',\n url: 'http://localhost/polleria/stock_procesado/incrementa',\n data: { categoria:categoria,kilos:kilos,cantidad:cantidad},\n async: true,\n dataType: 'json',\n success: function(response){ \n console.log(response); \n if (response.success) {\n alertify.set('notifier','position', 'bottom-center');\n alertify.success('Stock Actualizado !');\n } \n },\n error: function(response){\n console.log('error');\n console.log(response);\n\n }\n\n });\n}",
"function postDecrementaVivo(cantidad){\n $.ajax({\n type: 'ajax',\n method: 'post',\n url: 'http://localhost/polleria/ventas/decrementa_vivo_post',\n data: {cantidad:cantidad},\n async: true,\n dataType: 'json',\n success: function(response){ \n console.log(response);\n if (response.success) {\n alertify.set('notifier','position', 'bottom-center');\n alertify.success('Stock Actualizado !');\n } \n },\n error: function(response){\n console.log('error');\n console.log(response);\n\n }\n\n });\n}",
"function postIncrementaVivo(cantidad){\n $.ajax({\n type: 'ajax',\n method: 'post',\n url: 'http://localhost/polleria/stock_vivo/incrementa',\n data: { cantidad:cantidad},\n async: true,\n dataType: 'json',\n success: function(response){ \n console.log(response); \n if (response.success) {\n alertify.set('notifier','position', 'bottom-center');\n alertify.success('Stock Actualizado !');\n } \n },\n error: function(response){\n console.log('error');\n console.log(response);\n\n }\n\n });\n}",
"function acount_ajax_handler() {\n var ajaxgo = false; // глобальная переменная, чтобы проверять обрабатывается ли в данный момент другой запрос\n // после загрузки DOM\n var userform = $('.userform'); // пишем в переменную все формы с классом userform\n function req_go(data, form, options) { // ф-я срабатывающая перед отправкой\n if (ajaxgo) { // если какой либо запрос уже был отправлен\n form.find('.response').addClass('response-block');\n form.find('.response').html('<p class=\"error\"><?php _e( \"Waite...\") ?></p>'); // в див для ответов напишем ошибку\n return false; // и ничего не будет делать\n }\n form.find('input[type=\"submit\"]').attr('disabled', 'disabled'); // выключаем кнопку и пишем чтоб подождали\n form.find('.response').html(''); // опусташаем див с ответом\n ajaxgo = true; // записываем в переменную что аякс запрос ушел\n }\n function req_come(data, statusText, xhr, form) { // ф-я срабатывающая после того как пришел ответ от сервера, внутри data будет json объект с ответом\n console.log(arguments); // это для дебага\n var response = '';\n if (data.success) { // если все хорошо и ошибок нет\n response = '<p class=\"success\">' + data.data.message + '</p>'; // пишем ответ в <p> с классом success\n } else { // если есть ошибка\n response = '<p class=\"error\">' + data.data.message + '</p>'; // пишем ответ в <p> с классом error\n form.find('.response').addClass('response-block');\n form.find('.response').html(response); // выводим ответ\n }\n \n if (data.data.redirect) window.location.href = data.data.redirect; // если передан redirect, делаем перенаправление\n ajaxgo = false; // аякс запрос выполнен можно выполнять следующий\n }\n\n var args = { // аргументы чтобы прикрепить аякс отправку к форме\n dataType: 'json', // ответ будем ждать в json формате\n beforeSubmit: req_go, // ф-я которая сработает перед отправкой\n success: req_come, // ф-я которая сработает после того как придет ответ от сервера\n error: function(data) { // для дебага\n console.log(arguments);\n },\n url: ajax_var.url // куда отправляем, задается в wp_localize_script\n };\n userform.ajaxForm(args); // крепим аякс к формам\n\n $('.logout').click(function(e){ // ловим клик по ссылке \"выйти\"\n e.preventDefault(); // выключаем стандартное поведение\n if (ajaxgo) return false; // если в данный момент обрабатывается другой запрос то ничего не делаем\n var lnk = $(this); // запишем ссылку в переменную\n $.ajax({ // инициализируем аякс\n type: 'POST', // шлем постом\n url: ajax_var.url, // куда шлем\n dataType: 'json', // ответ ждем в json\n data: 'action=logout_me&nonce=' + $(this).data('nonce'), // что отправляем\n beforeSend: function(data) { // перед отправкой\n ajaxgo = true; // аякс отпраляется\n },\n success: function(data){ // после того как ответ пришел\n if (data.success) { // если ошибок нет\n window.location.reload(true); // и обновляемся\n } else { // если ошибки есть\n alert(data.data.message); // просто покажим их алертом\n }\n },\n error: function (xhr, ajaxOptions, thrownError) { // для дебага\n console.log(arguments);\n },\n complete: function(data) { // при любом исходе\n ajaxgo = false; // аякс больше не выполняется\n }\n });\n });\n }",
"function POST(){\n\n}",
"function addAlunoNoBanco(){\n\t//manda ajax assim q a pagina carregar para pegar as informacoes do diario\n\tvar url = \"../Controller/alunoInterface.php\";\n\t//informacoes passadas para a url\n\tvar nome = $(\"#nomeAluno\").val().trim();\n\tvar req = {\n\t\tacao: 'addAluno',\n\t\tidDiario: idDiario,\n\t\tnomeAluno: nome\n\t};\n\t$.post(url, req, function (data) {\n\t\tvar res = JSON.parse(data);\n\t\tif (res.status) {//deu certo\n\t\t\talert(\"Adicionado com sucesso!\");\n\t\t\t//adiciona na lista\n\t\t\t$(\"#aluno\").html(\" \");\n\t\t\tgetAlunos();\n\t\t} else {\n\t\t\talert(res.resposta);\n\t\t}\n\t});\n}",
"function envoyerRequeteMedicamentSuivant() {\n var requeteHttp=getRequeteHttp();\n if (requeteHttp==null)\n {\n alert(\"Impossible d'utiliser Ajax sur ce navigateur\");\n }\n else\n {\n //declenche un post sur la page getinfoclasse.php puis declenchera recevoirInfoMedSuivant\n requeteHttp.open('POST','getInfoMedSuivant.php',true);\n requeteHttp.onreadystatechange = function() {recevoirInfoMedSuivant(requeteHttp);};\n requeteHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');\n requeteHttp.send('MED_DEPOTLEGAL='+escape(document.getElementById('listeMed').value));\n }\n }",
"function ajouter_element(urlmaj,data,div) {\n $.post(urlmaj,{texte:data},function(response){ \n if (response.resultat==1) { \n montrer_notification('success', response.message);\n refresh_liste(response.todo_id);\n $('#input_ajouter_todo').val(\"\");\n } else { \n montrer_notification('error', response.message);\n }\n },\"json\");\n }",
"function m_sol_cita(){\n var cliente = getid();\n $.ajax({\n url: \"https://beta.changero.online/includes/php/sistemacitas.php\",\n type: \"post\",\n data: {tipo:1,cliente:cliente} ,\n success: function (response) {\n console.log(response);\n }\n });\n \n}",
"function AjaxSendSuscripcion(content, obj){\t\n\tAjaxSend(\"action=editsuscripcion&value=\" + content, obj);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
3. Display the product of all numbers using reduce Answer: | function reduceProduct() {
const product = numbers.reduce((acc, cur) => {
return acc * cur
})
document.getElementById('reduced').innerHTML += ' ' + product
} | [
"function reduceProduct() {\n const result = numbers.reduce((prev, curr) => {\n return prev * curr\n })\n document.getElementById('reduced').innerHTML += ' ' + result\n}",
"function myReduce() {\n const reducer = (accumulator, currentValue, currentIndex, array) => accumulator * currentValue;\n console.log('Displaying the product of all numbers using reduce method ' + numbers.reduce(reducer));\n document.getElementById(\"reduce\").innerHTML = 'Displaying the product of all numbers using reduce method ' + numbers.reduce(reducer);\n}",
"function productReduce(numbers) {\n return numbers.reduce((total, number) => { return total *= number; }, 1);\n}",
"function productReduce(array) {\n return array.reduce((total, n) => { return total *= n});\n}",
"function compute() {\n var numbers = prompt('Please enter multiple integers separated by spaces:');\n var arrayOfNums = numbers.split(' ').map(Number);\n var productOrSum = prompt('Enter \"s\" to compute the sum, \"p\" to compute the product:');\n var isSum = productOrSum.toLowerCase() === 's';\n var type = isSum ? 'sum' : 'product';\n var total;\n\n total = arrayOfNums.reduce(function(acc, value) {\n if (isSum) {\n return acc + value;\n } else {\n return acc * value;\n }\n });\n\n\n\n console.log('The ' + type + ' of the integers ' +\n arrayOfNums.join(', ') + ' is ' + total + '.');\n}",
"function findProduct(arr) {\n let product = arr.reduce((acc, curr) => {\n return acc * curr;\n });\n // console.log(product);\n return product;\n}",
"function sumProduct(input)\n{\n let sum=0;\n let product=1;\n input.forEach(function(element) {\n sum+=element;\n product*=element;\n });\n console.log(` Sum = ${sum} & Product = ${product} `);\n}",
"function func12(arr) {\r\n console.log(\r\n \"sum = \" +\r\n arr.reduce((sum, item) => {\r\n return (sum += item);\r\n }, 0)\r\n );\r\n console.log(\r\n \"product = \" +\r\n arr.reduce((prod, item) => {\r\n return (prod *= item);\r\n }, 1)\r\n );\r\n}",
"function printArrayProduct(arrayOfNumbers) {\n console.log(Array\n .from(arrayOfNumbers)\n .reduce((previous, current) =>\n previous *= current)\n )\n}",
"function computeProductOfAllElements(arr) {\n // your code here\n if ( arr.length === 0 ) {\n return 0;\n }\n return arr.reduce( (a,b) => {\n return a * b;\n })\n}",
"function product(numbers) {\n var total = 1;\n for(var i = 0; i < numbers.length; i++) {\n total *= numbers[i];\n }\n return total;\n}",
"function productOfAllElements(arr) {\n return arr.reduce(function (total, elem, i, arr) {\n return total * elem;\n }, 1);\n}",
"function multiplyNums(arr){\n return arr.reduce(function(acc,curVal){\n return acc * curVal;\n })\n}",
"function multiplyFunctionalProg(arr){\n let prod=ar.reduce(function(preValue, elt, i, array){\n return preValue*elt;\n });\n return prod;\n}",
"function computeProductOfAllElements(arr) {\n var output = 0;\n if (arr.length > 0){\n output = 1;\n for (var i = 0; i < arr.length; i++){\n output *= arr[i];\n }\n }\n return output;\n}",
"function product(numbers){\n //calculate product of array\n\tfor(var i = 0; i < numbers.length; i++){\n //return product;\n\t numbers[i] * numbers[i];\n\t}\n}",
"function productOfAll(arr) {\n var final = 1;\n for(var i=0;i<arr.length;i++) {\n final *= arr[i];\n }\n return final;\n}",
"function computeProductOfAllElements(arr) {\n\t//if arr length is zero\n\tif (arr.length === 0) {\n\t\t// then return 0\n\t\treturn 0;\n\t}\n\t// use reduce with the starting point = 0\n\treturn arr.reduce((prev, next) => {\n\t\treturn prev * next;\n\t});\n\t// add the acc + currentVal and return it\n}",
"function multEasy(n1,n2,n3,n4) {\n console.log(n1*n2*n3*n4)\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
encode data as json string | _jsonEncode( data ) {
if ( typeof data === 'object' ) {
try { let json = JSON.stringify( data ); return json; }
catch ( e ) { return JSON.stringify( e ); }
}
return '{}';
} | [
"function encode(data) {\r\n if (data == null) {\r\n return null;\r\n }\r\n if (data instanceof Number) {\r\n data = data.valueOf();\r\n }\r\n if (typeof data === 'number' && isFinite(data)) {\r\n // Any number in JS is safe to put directly in JSON and parse as a double\r\n // without any loss of precision.\r\n return data;\r\n }\r\n if (data === true || data === false) {\r\n return data;\r\n }\r\n if (Object.prototype.toString.call(data) === '[object String]') {\r\n return data;\r\n }\r\n if (Array.isArray(data)) {\r\n return data.map(function (x) { return encode(x); });\r\n }\r\n if (typeof data === 'function' || typeof data === 'object') {\r\n return mapValues(data, function (x) { return encode(x); });\r\n }\r\n // If we got this far, the data is not encodable.\r\n throw new Error('Data cannot be encoded in JSON: ' + data);\r\n }",
"function encode(data) {\r\n if (data == null) {\r\n return null;\r\n }\r\n if (data instanceof Number) {\r\n data = data.valueOf();\r\n }\r\n if (typeof data === 'number' && isFinite(data)) {\r\n // Any number in JS is safe to put directly in JSON and parse as a double\r\n // without any loss of precision.\r\n return data;\r\n }\r\n if (data === true || data === false) {\r\n return data;\r\n }\r\n if (Object.prototype.toString.call(data) === '[object String]') {\r\n return data;\r\n }\r\n if (data instanceof Date) {\r\n return data.toISOString();\r\n }\r\n if (Array.isArray(data)) {\r\n return data.map(x => encode(x));\r\n }\r\n if (typeof data === 'function' || typeof data === 'object') {\r\n return mapValues(data, x => encode(x));\r\n }\r\n // If we got this far, the data is not encodable.\r\n throw new Error('Data cannot be encoded in JSON: ' + data);\r\n}",
"function encode(data) {\n if (data == null) {\n return null;\n }\n\n if (data instanceof Number) {\n data = data.valueOf();\n }\n\n if (typeof data === 'number' && isFinite(data)) {\n // Any number in JS is safe to put directly in JSON and parse as a double\n // without any loss of precision.\n return data;\n }\n\n if (data === true || data === false) {\n return data;\n }\n\n if (Object.prototype.toString.call(data) === '[object String]') {\n return data;\n }\n\n if (data instanceof Date) {\n return data.toISOString();\n }\n\n if (Array.isArray(data)) {\n return data.map(x => encode(x));\n }\n\n if (typeof data === 'function' || typeof data === 'object') {\n return mapValues(data, x => encode(x));\n } // If we got this far, the data is not encodable.\n\n\n throw new Error('Data cannot be encoded in JSON: ' + data);\n}",
"MarshalJSON() {\n return `\"${this.data.toString('hex')}\"`;\n }",
"encode(obj) {\n logger_1.Logger.log.debug(\"JsonEncoder.encode: start.\");\n return JSON.stringify(obj);\n }",
"function encode(data) {\n if (_.isNull(data) || _.isUndefined(data)) {\n return null;\n }\n // Oddly, _.isFinite(new Number(x)) always returns false, so unwrap Numbers.\n if (data instanceof Number) {\n data = data.valueOf();\n }\n if (_.isFinite(data)) {\n // Any number in JS is safe to put directly in JSON and parse as a double\n // without any loss of precision.\n return data;\n }\n if (_.isBoolean(data)) {\n return data;\n }\n if (_.isString(data)) {\n return data;\n }\n if (_.isArray(data)) {\n return _.map(data, encode);\n }\n if (_.isObject(data)) {\n // It's not safe to use _.forEach, because the object might be 'array-like'\n // if it has a key called 'length'. Note that this intentionally overrides\n // any toJSON method that an object may have.\n return _.mapValues(data, encode);\n }\n // If we got this far, the data is not encodable.\n console.error('Data cannot be encoded in JSON.', data);\n throw new Error('Data cannot be encoded in JSON: ' + data);\n}",
"encodeJSON(text) {\n // var utf8 = require('utf8');\n // var binaryToBase64 = require('binaryToBase64');\n var bytes = utf8.encode(text);\n var encoded = base64.encode(bytes);\n return encoded;\n }",
"static serializeJSONBlob(data) {\n return JSON.stringify(data);\n }",
"_encodeQRCodeData(data) {\n try {\n const jsonString = JSON.stringify(data);\n return this._compressAndBase32Encode(jsonString);\n } catch (encodeJSONError) {\n console.error(encodeJSONError);\n throw new Error(\"Unable to create QR code (JSON encode error).\");\n }\n }",
"function stringify(data) {\n return JSON.stringify(data, null, 4);\n}",
"encodeJSON(obj) {\n return new Buffer(JSON.stringify(obj)).toString('base64')\n }",
"getJSONString() {\n var obj = {\n 'templateinfo' : this.templateinfo,\n 'settings' : this.settings,\n 'data' : this.data\n };\n return JSON.stringify(obj);\n }",
"function toJSONDataUri(obj) {\n if (typeof obj !== 'string')\n obj = JSON.stringify(obj);\n return 'data:application/json;base64,' + base64EncodeUnicode(obj);\n}",
"encodeToString ( data ) {\n return BufToCode( this.encode( data ) );\n }",
"function JSONConvert(data) {\n var retVal;\n //intenta realizar la operación con el objeto JSON nantivo.\n if (typeof data !== \"undefined\" && data instanceof String)\n retVal = JSON.parse(data);\n else\n retVal = JSON.stringify(data);\n\n return retVal;\n }",
"function renderJSON(data) {\n\treturn JSON.stringify(data)\n\t\t.replace(/\\\\/g, '\\\\\\\\') // escape backslashes\n\t\t.replace(/\\'/g, '\\\\\\''); // escape single quotes\n}",
"function WebSocketEncodeData(data) {\n\tvar query = [];\n\n\tif (data instanceof Object) {\n\t\tfor (var k in data) {\n\t\t\tquery.push(encodeURIComponent(k) + '=' + encodeURIComponent(data[k]));\n\t\t}\n\n\t\treturn query.join('&');\n\t} else {\n\t\treturn encodeURIComponent(data);\n\t}\n}",
"function creaJsonSeguir() {\n\n let obj = {\n id: id,\n siguen: sigue\n };\n\n return JSON.stringify(obj);\n}",
"function serializeJSON(dataObject)\n\t{\n\t\tvar dataArray = [];\n\t\tvar retval;\n\t\t\n\t\t$.each(dataObject,function(key,data){\n\t\t\tdataArray.push(key + '=' + escape(data));\n\t\t});\n\t\t\n\t\tretval = dataArray.join('&');\n\t\treturn retval;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
API call to backend app to get all publications | getPublications() {
return this.perform('get', '/publications');
} | [
"function getPublications(){\n const AUTHOR = \"Ayoub-Karine\";\n const HAL_API_URL = 'https://api.archives-ouvertes.fr/search/' +\n '?q=auth_t:(\"'+AUTHOR+'\")'+ \n '&fl=docType_s,authFullName_s,title_s,citationRef_s,label_s,label_bibtex,seeAlso_s' +\n '&sort=producedDate_s desc';\n fetch(HAL_API_URL)\n .then(publis => publis.json()) \n .then(function(data){\n showJournals(data.response);\n showConferences(data.response);\n showThesis(data.response);\n })\n .catch(error => console.log(\"Erreur !\"));\n}",
"function getUserPublications(req, res) {\r\n var userId = req.query.userId ? req.query.userId : req.decoded.uid\r\n dashboardService.getUserPublications(userId).then((result) => {\r\n res.json(result)\r\n }).catch((err) => {\r\n res.json(err)\r\n })\r\n}",
"function getAllPublished() {\n return db.getData(\"/published/\")\n}",
"async function getPublishers() {\n var res = await repo.retrieve('publishers');\n return res;\n}",
"async function leerPublicacion() {\n const response = await fetch('/publicacionesJson');\n const publicaciones = await response.json();\n mostrarPublicaciones(publicaciones);\n }",
"retrievePublishersList() {\n return thegamesDbApi.retrievePublishersList();\n }",
"static fetchPubCrawls(){\n return fetch (`${URL}/pubcrawls`,{\n method:\"GET\",\n headers: {\n \"Authorization\": `Bearer ${localStorage.getItem('jwt')}`\n },\n }).then(r => r.json())\n }",
"all()\n {\n return this.ApiService.get(`/galleries`);\n }",
"function getPublicVideos(){\n return getVideos('PublicVideos');\n}",
"function getPublications() {\n\tvar pubmedSearchAPI = \"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?\";\n\tvar pubmedSummaryAPI =\"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?\";\n\tvar database = \"pubmed\";\n\tvar returnmode = \"json\";\n\tvar returnmax = \"100\";\n\tvar searchterm = \"ansley+l[author]\";\n\tvar returntype = \"abstract\";\n\n\tgetPubmedId(pubmedSearchAPI,database,returnmode,returnmax,searchterm,pubmedSummaryAPI,returntype);\n}",
"async function FetchGetPublishers() {\n try {\n const response = await fetch(`http://localhost:3001/api/publishers`);\n\n const responseJSON = await response.json();\n\n const data = responseJSON;\n setPublishers(data);\n } catch (error) {\n console.log(\"get publisher fail: \", error.message);\n }\n }",
"static getAllPublishers(){\n try{\n\n const data = connection.query(`select distinct publisher from magazine`);\n\n return {status: 0, message: 'Ok', results: data};\n } catch (error){\n return{ status: 1, message: 'Error: ' + error, error}\n }\n }",
"function listInstitutions() {\n return axios.get(`${API}/institution`, {'headers': authHeader()});\n}",
"listPublic(req, res) {\n Document.findAndCountAll({\n where: {\n access: 'public',\n },\n limit: req.query.limit,\n offset: req.query.offset,\n order: [['id', 'ASC']],\n })\n .then((document) => {\n if (document.count === 0) {\n res.status(200).send({ message: 'No Public documents. Sign up to create one.' });\n } else {\n res.status(200).send(document);\n }\n });\n }",
"function serviceGetPubliclyReadableModels(req, resp) {\n\t\tlogger.info(\"<Service> GetPubliclyEditableModels.\");\n\t\tvar getData = parseRequest(req, ['limit', 'offset']);\n\t\t\n\t\twriteHeaders(resp);\n\t\tgetPubliclyReadableModels(getData.limit, getData.offset, function (err, objects) {\n\t\t\tif (err) error(2, resp);\n\t\t\telse resp.end(JSON.stringify({ models: objects })); \n\t\t});\n\t}",
"function getPublications(start, pageQty, pageNum) {\n $(pageBlock).empty();\n $(publicationsWrap).empty();\n\n arg = {\n apiKey: apiKey,\n startIndex: start,\n access: \"public\",\n action: \"issuu.documents.list\",\n documentSortBy: \"publishDate\",\n documentStates: \"A\", // A, F, P\n format: format,\n resultOrder: \"desc\", // \"asc\"; || \"desc\";\n pageSize: pageQty, //default is 10; 30 is max to return\n responseParams: \"\" // \"description,documentId,folders,name,orgDocName,pageCount,publicationId,publishDate,title,tags,views\";\n };\n\n URIlink = getSignature(arg);\n\n var itemsListed = arg.pageSize;\n\n $.get(URIlink).done(function (data) {\n console.log(\"API Publication data:\");\n console.log(data);\n var pagesDiv, totalCount, divID, category, username, documentIdData, documentId, folderString, folderId, pageCountData, pubDate1, pubDate2, pubDate3, pubDate4, pubDate5, pubDate6;\n\n pagesDiv = document.createElement('a');\n //pagesDiv.setAttribute('href', 'http://www.ksbar.org/');\n folderId = [];\n for (i = 0; i < itemsListed; i++) {\n divID = \"current-issue_Journal_Journal\";\n nameData = data.rsp._content.result._content[i].document.name;\n published = data.rsp._content.result._content[i].document.publishDate;\n pageCountData = data.rsp._content.result._content[i].document.pageCount;\n titleData = data.rsp._content.result._content[i].document.title;\n descriptionData = data.rsp._content.result._content[i].document.description;\n documentIdData = data.rsp._content.result._content[i].document.documentId;\n folderString = data.rsp._content.result._content[i].document.folders;\n //categoryData = data.rsp._content.result._content[i].document.category;\n username = data.rsp._content.result._content[i].document.username;\n startIndex = data.rsp._content.result.startIndex;\n\n published = moment.tz(published, 'US/Central').add(1, 'days').format('MMMM Do, YYYY');\n\n var listingBlockEl = document.createElement('div');\n listingBlockEl.setAttribute('class', 'stream-list');\n divOutWrap = document.createElement('div');\n divOutWrap.setAttribute('id', divID);\n divOutWrap.setAttribute('class', 'publication');\n divWrap = document.createElement('div');\n // divWrap.setAttribute('id', divID);\n divWrap.setAttribute('class', 'publication-content');\n divMeta = document.createElement('div');\n divMeta.setAttribute('class', 'metadata');\n divMeta.setAttribute('style', 'flex-grow: 2; width: 100%;');\n cover = document.createElement('img');\n cover.src = 'https://image.issuu.com/' + documentIdData + '/jpg/page_1.jpg';\n cover.setAttribute('class', 'cover');\n cover.setAttribute('style', '');\n\n name = document.createElement('p');\n name.innerHTML = nameData;\n\n var archiveBlock = document.createElement('div');\n archiveBlock.setAttribute('style', 'display: inline-block; margin-right: 10px;');\n archiveBlock.setAttribute('class', '');\n\n var linkText = document.createTextNode('Archives');\n var archives = document.createElement('a');\n archives.setAttribute('class', 'btn btn-default pull-right');\n archives.setAttribute('target', '_blank');\n archives.appendChild(linkText);\n archives.href = '/page/journal_archives';\n //archives.innerHTML = '<a href=\"/page/journal_archives\" target=\"_blank\">Archives</a>';\n\n title = document.createElement('h3');\n title.setAttribute('class', 'title');\n title.innerHTML = '<a href=\"https://issuu.com/' + username + '/docs/' + nameData + '\" target=\"_blank\">' + titleData + '</a>';\n\n description = document.createElement('p');\n description.setAttribute('class', 'jrnl-description');\n description.innerHTML = descriptionData;\n\n pageCount = document.createElement('p');\n pageCount.innerHTML = '<span class=\"bold\">Pages:</span> ' + pageCountData;\n\n $(publicationsWrap).append(listingBlockEl);\n $(listingBlockEl).append(divOutWrap);\n $(divOutWrap).append(divWrap);\n $(divWrap).append(cover);\n (divWrap).append(divMeta);\n $(divMeta).append(title);\n $(divMeta).append(description);\n $(divMeta).append(documentId);\n $(divMeta).append(pageCount);\n\n $(divMeta).append(' <b>Published:</b> ' + published + '<br><br>');\n $(divWrap).append(archiveBlock);\n $(archiveBlock).append(archives);\n }\n $(listingBlock + '-folder').show();\n $(publicationsWrap).show();\n $(listingBlock).show();\n\n }, \"json\");\n}",
"async function getPrismicOrgs() {\n let orgResults = []\n const prismicOrgs = await prismic.getDocs(\"organizations\")\n await prismicOrgs.results.forEach(item => {\n orgResults.push(item.data)\n })\n \n getUpdatedPumps(orgResults)\n}",
"getAllProjects() {\n console.log(\"to get the api\")\n return API.get(\"projects\", \"/projects\");\n }",
"function getPublications() {\n\n\t//create a new Worker object referencing the pub-worker js file\n\tvar pubWorker = new Worker('js/pub-worker.js');\n\n\tvar pubmedSearchAPI = \"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?\";\n var pubmedSummaryAPI =\"http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?\";\n var database = \"pubmed\";\n var returnmode = \"json\";\n var returnmax = \"100\";\n var searchterm = \"ansley+l[author]\";\n var returntype = \"abstract\";\n\n $('#publication').append(HTMLpublicationContainer);\n //start the web-worker\n pubWorker.postMessage(100);\n\n //listen for response from web-worker\n pubWorker.onmessage = function(e) {\n var publication = e.data;\n $('#publication-container').append(HTMLpublicationStart);\n $('.publication-entry').append(publication);\n \t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a new instance of a Fullscreen action set | function create(app) {
return new Fullscreen(app);
} | [
"_initFullScreenControl(opt) {\n let topt = {};\n if (opt.hasOwnProperty('className') && opt.className) {\n topt.className = opt.className\n }\n if (opt.hasOwnProperty('label') && opt.label) {\n topt.label = opt.label\n }\n if (opt.hasOwnProperty('labelActive') && opt.labelActive) {\n topt.labelActive = opt.labelActive\n }\n if (opt.hasOwnProperty('tipLabel') && opt.tipLabel) {\n topt.tipLabel = opt.tipLabel\n }\n if (opt.hasOwnProperty('target') && opt.target) {\n topt.target = opt.target\n }\n if (opt.hasOwnProperty('source') && opt.source) {\n topt.source = opt.source\n }\n\n let control = new FullScreen(topt)\n return control\n }",
"get FullscreenWindowWithDockAndMenuBar() {}",
"function Fullscreen(app) {\n return _super.call(this, app, types_1.Group.Fullscreen, types_1.Group.Fullscreen) || this;\n }",
"function FullscreenRequest() {\n }",
"function fullscreen() {\n return {\n on: on,\n request: request,\n release: release,\n dispose: disposeMock,\n };\n}",
"function fullScreen(){\n if($(this).attr('fullScreen') == 'false' && $(this).attr('openScreen') == 'true'){\n className = $(this).parent().attr('class');\n $(this).parent().removeClass();\n $(this).prev().addClass('fullscreen');\n $(this).attr('fullScreen', true);\n }else{\n $(this).parent().addClass(className);\n $(this).prev().removeClass('fullscreen');\n $(this).attr('fullScreen', false);\n }\n }",
"function toggleScreenFull() {\n\tscreenfull.toggle();\n}",
"screenToggle(state) {\n state.fullScreen = !state.fullScreen;\n }",
"function makeFullScreenButton(){\n var newHTML =\n '<input type=\"button\" style=\"margin:20px; position:fixed; top:0px; right:0px; z-index: 10000; height:50px; width:150px;\" id=\"fullscreenButton\" value=\"Enter Full Screen Mode\"/>';\n\n var buttonDiv = document.createElement(\"div\");\n\n buttonDiv.innerHTML = newHTML;\n\n buttonDiv.setAttribute(\"id\", \"fullscreen\");\n\n document.body.appendChild(buttonDiv);\n }",
"function toggleFiltersFull() {\n var views = ['default', 'minimized', 'full', 'attached'];\n\n var currentMode = stateManager.state.filters.morph; // stateManager.getMode('filters');\n var index = (views.indexOf(currentMode) + 1) % 4;\n\n // Make sure the filters panel is open\n stateManager.setActive({\n side: false\n }, {\n filtersFulldata: true\n });\n stateManager.setMode('filters', views[index]);\n }",
"_toggleFullscreen() {\n const logConsole = this._resourceLogRef.current;\n if (!logConsole) {\n return;\n }\n\n if (screenfull.enabled) {\n screenfull.toggle(logConsole);\n }\n }",
"togglePseudoFullscreenMode() {\n if (this.state.isFullWindow) {\n this.exitFullWindow();\n } else {\n this.enterFullWindow();\n }\n }",
"function ActionSet() {\n this.action_ids = [];\n this.actions = {};\n}",
"function HomescreenWindowManager() {}",
"function initFullscreen() {\n\tvar el = document.createElement( \"div\" );\n\tif ( el.requestFullScreen ) {\n\t\t// standards\n\t\treturn {\n\t\t\t\"request\": \"requestFullScreen\",\n\t\t\t\"exit\": \"exitFullScreen\",\n\t\t\t\"event\": \"fullscreenchange\",\n\t\t\t\"element\": \"fullscreenElement\"\n\t\t};\n\t} else if ( el.webkitRequestFullScreen ) {\n\t\t// Webkit / Blink\n\t\treturn {\n\t\t\t\"request\": \"webkitRequestFullScreen\",\n\t\t\t\"exit\": \"webkitExitFullscreen\",\n\t\t\t\"event\": \"webkitfullscreenchange\",\n\t\t\t\"element\": \"webkitFullscreenElement\"\n\t\t};\n\t} else if ( el.mozRequestFullScreen ) {\n\t\t// Firefox\n\t\treturn {\n\t\t\t\"request\": \"mozRequestFullScreen\",\n\t\t\t\"exit\": \"mozCancelFullScreen\",\n\t\t\t\"event\": \"mozfullscreenchange\",\n\t\t\t\"element\": \"mozFullScreenElement\"\n\t\t};\n\t} else if ( el.msRequestFullScreen ) {\n\t\t// IE\n\t\treturn {\n\t\t\t\"request\": \"msRequestFullScreen\",\n\t\t\t\"exit\": \"msExitFullscreen\",\n\t\t\t\"event\": \"msfullscreenchange\",\n\t\t\t\"element\": \"msFullscreenElement\"\n\t\t};\n\t} else {\n\t\treturn {};\n\t}\n}",
"function getAction() {\n\t\treturn new Action();\n\t}",
"function createFullscreenControls() {\r\n var fullscreenControls = $('<div class=\"full-screen-controls\"></div>').appendTo(slideWrapper);\r\n\r\n fullscreenControls.click(function () {\r\n if (fullscreenState == 'off')\r\n requestFullscreen();\r\n else if (fullscreenState == 'on')\r\n cancelFullscreen();\r\n });\r\n\r\n\r\n document.addEventListener('fullscreenchange', fullscreenChange);\r\n document.addEventListener('mozfullscreenchange', fullscreenChange);\r\n document.addEventListener('webkitfullscreenchange', fullscreenChange);\r\n\r\n\r\n // display the icon\r\n if (self.settings.fullscreenControlsToggle && !isHover) {\r\n fullscreenControls.css('opacity', 0);\r\n } else {\r\n // fade in the canvas\r\n if (!isOldIE)\r\n fullscreenControls.css({'opacity': 0})\r\n .stop().animate({'opacity': 1}, self.settings.fullscreenIconHideDuration);\r\n }\r\n\r\n\r\n if (self.settings.fullscreenControlsToggle) {\r\n slideWrapper.hover(\r\n function () {\r\n if (isOldIE)\r\n fullscreenControls.css('filter', '');\r\n else\r\n fullscreenControls.stop().animate({'opacity': 1}, self.settings.fullscreenIconShowDuration);\r\n },\r\n\r\n function () {\r\n if (isOldIE)\r\n fullscreenControls.css('opacity', 0);\r\n else\r\n fullscreenControls.stop().animate({'opacity': 0}, self.settings.fullscreenIconHideDuration);\r\n });\r\n }\r\n }",
"toggleFullScreen () {\n return this.setFullScreen(!this.isFullScreen())\n }",
"function makeFullScreenButton(){\n var newHTML =\n '<input type=\"button\" style=\"margin:20px; position:fixed; top:0px; right:0px; z-index: 10000; height:50px; width:200px;\" id=\"fullscreenButton\" value=\"Full Screen Mode (Dpt v0.1)\"/>';\n\n var buttonDiv = document.createElement(\"div\");\n\n buttonDiv.innerHTML = newHTML;\n\n buttonDiv.setAttribute(\"id\", \"fullscreen\");\n\n document.body.appendChild(buttonDiv);\n\n buttonMes = document.createElement(\"div\");\n\n\tstStyle='<input type=\"button\" style=\"font-size: 600%; margin:20px; position:fixed; top:0px; left:0px; z-index: 10000; height:120px; width:900px;\" value=\"';\n\n buttonMes.setAttribute(\"id\", \"message\");\n\n document.body.appendChild(buttonMes);\n\tbuttonMes.style.visibility =\"hidden\";\n\tHSMes=0;\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copy placeholder value from clue table to the newly created curr clue. | function copyOrphanEntryToCurr(clueIndex) {
if (!clueIndex || !clues[clueIndex] || !clues[clueIndex].clueTR ||
!isOrphan(clueIndex) || clues[clueIndex].parentClueIndex) {
return
}
let clueInputs = clues[clueIndex].clueTR.getElementsByTagName('input')
if (clueInputs.length != 1) {
console.log('Missing placeholder input for clue ' + clueIndex)
return
}
let curr = document.getElementById(CURR_ORPHAN_ID)
if (!curr) {
return
}
let currInputs = curr.getElementsByTagName('input')
if (clueInputs.length != 1) {
return
}
currInputs[0].value = clueInputs[0].value
} | [
"updatePlaceholder() {\n if (!this.node.placeholder) {\n const placeholder = this.getPlaceholderFormat();\n this.node.placeholder = placeholder;\n }\n }",
"function addClue () {\n viewModel.selectedClue = {\n name: 'New Clue',\n question: ' ',\n answers: [\n { key: 'A', answer: ' '},\n { key: 'B', answer: ' '},\n { key: 'C', answer: ' '},\n { key: 'D', answer: ' '}\n ],\n correctAnswer: 'A'\n };\n viewModel.clues.push(viewModel.selectedClue);\n viewModel.selectedClueIndex = viewModel.clues.length;\n localModel.root.Ui.turnOn('clueEdit');\n }",
"function updateOrphanEntry(clueIndex, inCurr) {\n if (!clueIndex || !clues[clueIndex] || !clues[clueIndex].clueTR ||\n !isOrphan(clueIndex) || clues[clueIndex].parentClueIndex) {\n return\n }\n let clueInputs = clues[clueIndex].clueTR.getElementsByTagName('input')\n if (clueInputs.length != 1) {\n console.log('Missing placeholder input for clue ' + clueIndex)\n return\n }\n let theInput = clueInputs[0]\n if (!inCurr) {\n let cursor = theInput.selectionStart\n theInput.value = theInput.value.toUpperCase().trimLeft()\n theInput.selectionEnd = cursor\n updateAndSaveState()\n }\n let curr = document.getElementById(CURR_ORPHAN_ID)\n if (!curr) {\n return\n }\n let currInputs = curr.getElementsByTagName('input')\n if (currInputs.length != 1) {\n return\n }\n let theCurrInput = currInputs[0]\n if (inCurr) {\n let cursor = theCurrInput.selectionStart\n theCurrInput.value = theCurrInput.value.toUpperCase().trimLeft()\n theCurrInput.selectionEnd = cursor\n theInput.value = theCurrInput.value\n updateAndSaveState()\n } else {\n theCurrInput.value = theInput.value\n }\n}",
"placePiece() {\n\t\t\t$(\".cell[temp]\").removeAttr(\"temp\");\n\t\t\tvar newPiece = JSON.parse(JSON.stringify(this.place_piece));\n\t\t\tthis.board[this.place_location] = newPiece;\n\t\t\tconsole.log(this.board, this.place_location, this.place_piece);\n\t\t}",
"setPlaceholder() {\n let target = this.target;\n\n this.placeholder = document.createElement('div');\n\n this.placeholder.className = 'fixit-placeholder';\n\n target.parentNode.insertBefore(this.placeholder, target);\n }",
"substituteScalar(cell, string, placeholder, substitution) {\n var self = this;\n\n if (placeholder.full) {\n return self.insertCellValue(cell, substitution);\n } else {\n var newString = string.replace(placeholder.placeholder, self.stringify(substitution));\n cell.attrib.t = \"s\";\n return self.insertCellValue(cell, newString);\n }\n\n }",
"function initClueVals(){\n setHorizClues();\n setVertClues();\n}",
"onFnaPlaceholderChanged(placeholder) {}",
"function placeHold(){\n document.getElementById(\"editbox\").placeholder = document.getElementById(\"edit\").value;\n}",
"set placeholder(placeholder) {\n this._palette.inputNode.placeholder = placeholder;\n }",
"function pushPlaceholder() {\n if (editMode == 'none') {\n $('#er-lyric-input').attr('placeholder', 'Click here or hit pause to lick a lyric at ' + currentString());\n }\n}",
"function _createDropPlaceholder() {\n\n for (var j = 0; j < $scope.gridsterOpts.maxRows; j++) {\n\n for (var i = 0; i < gridMaxItemsPerRow; i++) {\n\n if (loDash.findIndex($scope.gridItems, { positionY: i, positionX: j }) < 0) {\n $scope.gridItems.push({\n positionX: j,\n positionY: i,\n placeholder: true\n });\n\n }\n }\n\n }\n }",
"function _createPlaceholder() {\n this._renderController = new RenderController();\n this.add(this._renderController);\n this.placeholder = new RenderNode();\n this._renderController.show(this.placeholder, {duration: 0});\n this._placeholderVisible = true;\n }",
"static createPlaceholder(device) {\n const texture = AreaLightLuts.createTexture(device, device.areaLightLutFormat, 2, 'placeholder');\n\n const pixels = texture.lock();\n pixels.fill(0);\n texture.unlock();\n\n AreaLightLuts.applyTextures(device, texture, texture);\n }",
"function updateBlankPosition( currentPieceBlank, newPieceBlank )\n{\n\t//console.log( \"***********Actualiza: \" +currentPieceBlank.text() + \" y \" + newPieceBlank.text());\n\tcurrentPieceBlank.css( \"background-color\", \"\" );\n\tcurrentPieceBlank.css( { position: \"\" } );\n\tcurrentPieceBlank.css( { top: \"\" } );\n\tcurrentPieceBlank.css( { right: \"\" } );\n\tcurrentPieceBlank.text( newPieceBlank.text( ) );\n\n\tnewPieceBlank.css( \"background-color\", \"black\" );\n\tnewPieceBlank.css( { position: \"\" } );\n\tnewPieceBlank.css( { top: \"\" } );\n\tnewPieceBlank.css( { right: \"\" } );\n\tnewPieceBlank.text( \"B\" );\n\t//console.log(\"ACT\");\n}",
"function assignQ(row, col) {\n\tlet $cell = $(`td[id=\"${row}${col}\"]`);\n\t// console.log($cell);\n\t// console.log(categories[col - 1].clues);\n\t$cell.html(`<div class=\"shownQ m3-5\">${categories[col - 1].clues[row - 1].question}</div>`);\n}",
"function renderCorrectPlaceholder(event, ui) {\n jQuery(\"#drag_placeholder\").addClass(\"column_placeholder\").html(i18nLocale.drag_drop_me_in_column);\n}",
"set placeholder(val) {\n this._setAttributes(val,'placeholder')\n }",
"function createPlaceholder() {\n if (usePlaceholder) {\n // Remove the previous placeholder\n if (placeholder) {\n placeholder.remove();\n }\n\n placeholder = angular.element('<div>');\n placeholder.css('height', $elem[0].offsetHeight + 'px');\n\n $elem.after(placeholder);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
numberOfAnswers should return an integer that is the number of choices for the current question | function numberOfAnswers () {
return quiz.questions[quiz.currentQuestion].choices.length
} | [
"function numberOfAnswers () {\n return quiz.questions[quiz.currentQuestion].choices.length;\n}",
"function numberOfAnswers() {\n return quiz.questions[quiz.questionIndex].choices.length\n}",
"function numberOfAnswers() {\n return quiz.questions[quiz.currentQuestion].options.length\n}",
"function numberOfChoices() {\n console.log(quiz.questions[quiz.currentQuestion].choices.length);\n return quiz.questions[quiz.currentQuestion].choices.length; //2 consisting of [\"true\", \"false\"]\n }",
"function numberOfChoices () {\n return quiz.totalQns[quiz.currentQns].choices.length\n }",
"function countAnswers() {\n for (var i = 0; i < gameQuestions.length; i++) {\n if (\n $(\"input:radio[name='choice\" + i + \"']:checked\").value() ===\n gameQuestions[i].correctAnswer\n ) {\n correctAnswers++;\n } else if (\n $(\"input:radio[name='choice\" + i + \"']:checked\").value() !=\n gameQuestions[i].correctAnswer\n ) {\n incorrectAnswers++;\n } else {\n unansweredQuestions++;\n }\n }\n }",
"function numberOfQuestions () {\n return 10\n }",
"function numberOfQuestions () {\n return quiz.questions.length;\n}",
"function numberOfQuestions() {\n quizlength = quiz.questions.length;\n return quizlength // notetoself = if do not return, no number given\n}",
"function countCorrectAnswers() {\n correctAnswers++;\n}",
"function numberOfQuestions () {\n return quiz.questions.length\n}",
"getAnsweredCount(answeredQuestions) {\n var count = 0;\n for (var item in answeredQuestions) {\n count++;\n }\n return count;\n }",
"getNumberOfCorrectAnswers() {\n const answerArray = this.getCheckedAnswers();\n let numberOfCorrectAnswers = 0;\n\n answerArray.forEach(element => {\n if (element.correct) {\n numberOfCorrectAnswers++;\n }\n })\n\n return numberOfCorrectAnswers;\n }",
"function numberOfQuestions() {\n return quiz.questions.length\n}",
"countCorrectAnswers(){\n let numCorrect = 0;\n let quiz = document.getElementById(\"main-quiz\");\n \n //tracks which question we're on\n let num = 0;\n\n for (let question of quiz.children){\n let name = question.className.replace('question','answer');\n let choice = this.getChoice(name);\n let correctAnswer = this.getCorrectAnswer(num);\n \n //highlights response depending on whether or not the choice is correct\n this.highlightResponse(question, choice, correctAnswer);\n \n if (correctAnswer == choice){\n numCorrect+=1;\n }\n num+=1;\n }\n return numCorrect;\n }",
"function numberOfQuestions() {\n console.log(quiz.questions.length - 5);\n return quiz.questions.length - 5; //return 15 questions\n }",
"function countOfCorrectAnswers(answer, correctAnswer) {\n\tconsole.log(numberofQuestionsCorrect);\n\tif (answer === correctAnswer) {\n\t\tnumberofQuestionsCorrect = numberofQuestionsCorrect + 1;\n\t}\n\trenderQuestionHeader(numberofQuestionsCorrect);\n}",
"function getChoices(qnumber) {\n\treturn quiz_qs[qnumber][\"choices\"].length;\n}",
"function counting_questions() {\n for (let i = 0; i < questions.length; i++) {\n number_of_questions++;\n }\n return number_of_questions;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Selects the first element with a given class name that is a child of a given parent object. | function selectOne(parent, classtext) {
var objects = parent.getElementsByClassName(classtext);
return objects[0];
} | [
"function findClassInChildren(parent, name) {\n\tif ( !parent ) return null;\n\tif ( !parent.childNodes ) return null;\n\tfor (var i = 0, childNode; i <= parent.childNodes.length; i ++) {\n \tchildNode = parent.childNodes[i];\n \t\tif (childNode && name == childNode.className) {\n \treturn childNode;\n \t}\n }\n}",
"function getChildByName (a_parent, name) \n{\n\treturn a_parent.get_children().filter(\n\tfunction(elem)\n\t{\n\t\treturn elem.name == name\n\t})[0];\n}",
"function getChild(element, name) {\n return element.getElementsByClassName(name).item(0);\n}",
"function findParentClass(child, targetClass) {\n var parent = child.parentElement;\n while (!parent.classList.contains(targetClass)) {\n parent = parent.parentElement;\n if (parent === undefined) {\n break;\n }\n }\n return parent;\n }",
"function findParent(thisElement, parentTagName, className) {\n if (className != '') {\n while (\n (thisElement = thisElement.parentElement) && !thisElement.classList.contains(className)\n );\n return thisElement\n } else {\n while (\n (thisElement = thisElement.parentElement) &&\n thisElement.tagName != parentTagName\n );\n //Searching loop only stop while parent is founded\n return thisElement //if searching no one will return null\n }\n}",
"function childByEl(parent, selector) {\n return parent.getElementsByClassName(selector);\n }",
"function find_parent(node, className) {\n var pattern;\n pattern = new RegExp(\"\\\\b\" + className + \"\\\\b\");\n do {\n if (node.nodeType == Node.ELEMENT_NODE && \n pattern.test(node.className)) {\n return node;\n }\n } while (node = node.parentNode);\n return null;\n}",
"function find($parent, css) {\n\tvar $el = $parent.find(css).first()\n\tif ($el.length == 0)\n\t\tthrow 'no child element with selector [' + css + ']'\n\t\t+ ' found in parent ' + $parent.attr('id')\n\treturn $el\n}",
"function getFirstClass(parent, cls, predicate) {\n return findFirst(predicate, parent.getElementsByClassName(cls));\n }",
"function getChildByClassName(sourceElement, name) {\r\n if (sourceElement == null) {\r\n alert(name);\r\n }\r\n \r\n var descendents = sourceElement.getElementsByTagName('*');\r\n\r\n for (var i = 0; i < descendents.length; i++) {\r\n if (descendents[i].className == name) {\r\n return descendents[i];\r\n }\r\n }\r\n}",
"function getClassChild(cElement, cClass)\r\n{\r\n var childElems = getChildElems(cElement);\r\n if(childElems) for(var i = 0; i < childElems.length; i++)\r\n if(hasClass(childElems[i], cClass)) return childElems[i];\r\n return null;\r\n}",
"function findParentClass(elem, parentClassName) {\n while (elem && elem.className != parentClassName) { elem = elem.parentNode; }\n return elem;\n}",
"function findParent(inEl, className) {\n var el = inEl; // this is for Flow.\n do {\n if (el.classList.contains(className)) return el;\n el = el.parentElement;\n } while (el);\n return null;\n}",
"static getChild(el, klass) {\n if (el == null)\n return null;\n for (let node = el.firstElementChild; node != null; node = node === null || node === void 0 ? void 0 : node.nextElementSibling) {\n if (Dom.hasClass(node, klass))\n return node;\n }\n return null;\n }",
"function child(parent, index){\r\n var i = 0,\r\n n = parent.firstChild;\r\n while(n){\r\n if(n.nodeType == 1){\r\n if(++i == index){\r\n return n;\r\n }\r\n }\r\n n = n.nextSibling;\r\n }\r\n return null;\r\n }",
"function child(parent, index){\n var i = 0,\n n = parent.firstChild;\n while(n){\n if(n.nodeType == 1){\n if(++i == index){\n return n;\n }\n }\n n = n.nextSibling;\n }\n return null;\n }",
"function getParentByClass(className, element) {\n\tvar tester = new ClassTester(className);\n\tvar node = element.parentNode;\n\n\twhile(node != null && node != document)\n\t{\n\t\tif(tester.isMatch(node))\n\t\t\treturn node;\n\n\t\tnode = node.parentNode;\n\t}\n\n\treturn null;\n}",
"findChildByType(t, parent) {\n if (!parent)\n return null;\n if (!parent.children)\n return null;\n var result = null;\n for (var i = 0; i < parent.children.length; i++) {\n var child = parent.children[i];\n if (child.type === t)\n return child;\n }\n if (1 == 1)\n return null;\n parent.children.forEach((c) => {\n if (c.type === t) {\n result = c;\n }\n });\n return result;\n }",
"firstParent(selector) {\n let parent = this.parent();\n while (parent.isPresent()) {\n if (parent.matchesSelector(selector)) {\n return parent;\n }\n parent = parent.parent();\n }\n return DomQuery.absent;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this lists the intervals of the scale | function listIntervals(scale) {
const intervals = document.querySelector("#scaleIntervals");
if (scale === "major") {
intervals.innerHTML = "P1, M2, M3, P4, P5, M6, M7"
}
else if (scale === "minor") {
intervals.innerHTML = "P1, M2, m3, P4, P5, m6, m7"
}
else if (scale === "majorPentatonic") {
intervals.innerHTML = "P1, M2, M3, P5, M6"
}
else if (scale === "minorPentatonic") {
intervals.innerHTML = "P1, m3, P4, P5, m7"
}
else if (scale === "chromatic") {
intervals.innerHTML = "P1, m2, M2, m3, M3, P4, TT, P5, m6, M6, m7, M7"
}
} | [
"function calculateIntervals(scale){\n var intervals = [];\n // Setting up scale array for the interval calculation process\n scale.push(scale[0]+12);\n // Calculating interval array\n var prec = scale[0];\n for(var i = 1; i < scale.length; i++){\n intervals.push(scale[i]-prec)\n prec = scale[i];\n }\n return [...intervals];\n}",
"get intervals()\n\t{\n\t\treturn {\n\t\t\tpx: \t\t\t\t1.00,\n\t\t\tem: \t\t\t\t0.01,\n\t\t\trem: \t\t\t\t0.01,\n\t\t\tdefault: \t\t0.00\n\t\t}\n\t}",
"get intervals() {\r\n return this._intervals;\r\n }",
"get intervals() {\n return this._intervals;\n }",
"function getScaleList() {\n return [\n \"linear\",\n \"log\",\n \"exp\",\n \"invlinear\",\n \"invlog\",\n \"invexp\",\n \"binary\"\n ];\n}",
"function entries() {\r\n return scales.slice();\r\n }",
"getTickValues () {\n const domain = this.props.scale.domain();\n const max = domain[domain.length - 1];\n\n if (max < 4) {\n return [0, max];\n }\n\n if (max < 100) {\n return [0, Math.round(max / 2), max];\n }\n\n return [\n 0,\n Math.round(max / 3),\n Math.round(max / 3) * 2,\n max\n ];\n }",
"getRanges() {\n\t\tlet xm = 0,\n\t\t\tym = 0,\n\t\t\txn = 0,\n\t\t\tyn = 0,\n\t\t\tpoints = this.points;\n\t\tpoints.forEach((el, i) => {\n\t\t\txm = Math.max(...points.map(e => e.x));\n\t\t\tym = Math.max(...points.map(e => e.y));\n\t\t\txn = Math.min(...points.map(e => e.x));\n\t\t\tyn = Math.min(...points.map(e => e.y));\n\t\t});\n\n\t\treturn {\n\t\t\txrange: xm - xn,\n\t\t\tyrange: ym - yn\n\t\t}\n\t}",
"getTicks() {\n const { scale, tickSize, tickValues, interval } = this.props;\n const dimension = this.getDimension();\n const ticks = getTicks(scale, tickSize, tickValues, dimension, interval);\n const adjustedScale = this.getAdjustedScale();\n const format = this.getLabelFormat();\n const result = [];\n const midpoint = dimension / 2;\n for (const tick of ticks) {\n const text = format(tick);\n const scaledTick = adjustedScale(tick);\n result.push({\n text,\n fullText: text,\n position: this.getPosition(scaledTick),\n half: scaledTick === midpoint\n ? 'center'\n : scaledTick < midpoint\n ? 'start'\n : 'end'\n });\n }\n return result;\n }",
"calculateIntervalSize() {\n // Scale to have at least 4 graduation line intervals\n let verticalInterval = Math.pow(10, Math.floor(Math.log10(this.verticalSpan)));\n if (this.verticalSpan / verticalInterval < 2) {\n verticalInterval /= 5;\n } else if (this.verticalSpan / verticalInterval < 5) {\n verticalInterval /= 2;\n };\n return verticalInterval;\n }",
"function getVoicingFromIntervals(range, size) {\n\tif (size <= 0) {\n\t\treturn `Error: Size ${size} must be positive.`;\n\t}\n\n\tlet voicing = [];\n\tfor (let i = 0; i < size; i++) {\n\t\tvoicing.push(range[0] * (i + 1));\n\t\tvoicing.push(range[1] * (i + 1));\n\t}\n\tvoicing.push(0);\n\tvoicing.sort((a, b) => a - b);\n\tlet intervalMap = voicing.map((note) => Tonal.Interval.fromSemitones(note));\n\treturn intervalMap;\n}",
"get min_intervals() {\n return this.tickers.map((ticker) => ticker.get_min_interval());\n }",
"function getScaleNotes(scale,base,max) {\n interval = 0;\n ni = 0;\n notes = new Array();\n ints = new Array();\n for(n = 0; n < max; n++) {\n note = calcNote(base,interval);\n interval = interval + scale[ni];\n ints[n] = scale[ni];\n notes[n] = note;\n ni++;\n if (ni >= scale.length) ni = 0;\n }\n return notes;\n}",
"range() {\n let minX = this.x,\n maxX = this.x,\n minY = this.y,\n maxY = this.y;\n\n for(let n of this) {\n if (n.x < minX) {minX = n.x}\n else if (n.x > maxX) {maxX = n.x}\n\n if (n.y < minY) {minY = n.y}\n else if (n.y > maxY) {maxY = n.y}\n }\n\n return [minX, maxX, minY, maxY]\n }",
"function scaleInt(interval) {\r\n let domain;\r\n let min, max, range;\r\n// console.log(min);\r\n// console.log(max);\r\n// console.log(\"range\");\r\n switch (interval) {\r\n case 0:\r\n //range = p3.int0.map(x => x.map(r => r.rate).filter(r => r > 0))\r\n // .map(x => d3.extent(x));\r\n // min = Math.max.apply(null, range.map(x => x[0]));\r\n // max = Math.min.apply(null, range.map(x => x[1]));\r\n domain = [0, 20000];\r\n break;\r\n case 1:\r\n // range = p3.int1.map(x => x.map(r => r.rate).filter(r => r > 0))\r\n // .map(x => d3.extent(x));\r\n // min = Math.max.apply(null, range.map(x => x[0]));\r\n // max = Math.min.apply(null, range.map(x => x[1]));\r\n domain = [0, 6000];\r\n break;\r\n case 2:\r\n // range = p3.int2.map(x => x.map(r => r.rate).filter(r => r > 0))\r\n // .map(x => d3.extent(x));\r\n // min = Math.max.apply(null, range.map(x => x[0]));\r\n // max = Math.min.apply(null, range.map(x => x[1]));\r\n domain = [0, 500];\r\n break;\r\n default:\r\n // range = p3.int3.map(x => x.map(r => r.rate).filter(r => r > 0))\r\n // .map(x => d3.extent(x));\r\n // min = Math.max.apply(null, range.map(x => x[0]));\r\n // max = Math.min.apply(null, range.map(x => x[1]));\r\n domain = [0, 200];\r\n break;\r\n }\r\n return d3.scaleLinear()\r\n .domain(domain)\r\n .range([p3.plotHght, 0]);\r\n}",
"get min_intervals() {\n return this.tickers.map((ticker) => ticker.get_min_interval());\n }",
"function subset (start, end) {\n\t\tif (start == null) start = 0;\n\t\tif (end == null) end = scales[0].length;\n\n\t\tstart = nidx(start, scales[0].length);\n\t\tend = nidx(end, scales[0].length);\n\n\t\tfor (let group = 2, idx = 1; group <= maxScale; group*=2, idx++) {\n\t\t\tlet groupEnd = Math.round(end/group);\n\t\t\tlet groupStart = Math.floor(start/group);\n\t\t\tscales[idx] = scales[idx].slice(groupStart, groupEnd);\n\t\t}\n\n\t\treturn scales;\n\t}",
"*intervals(){\n for(let node of this.nodes()){\n // Note: for...of is about 40% as performant as of node v10.7.0\n // for(let interval of node.intervals) yield interval;\n for(let i = 0; i < node.intervals.length; i++){\n yield node.intervals[i];\n }\n }\n }",
"getChartDataDomain() {\n const networthData = this.getSelectedNetworthData();\n\n const domain = networthData.reduce(\n (acc, pos) => {\n if (pos.value < acc.min) {\n acc.min = pos.value;\n }\n\n if (pos.value > acc.max) {\n acc.max = pos.value;\n }\n\n return acc;\n },\n {\n min: networthData[0].value,\n max: networthData[0].value\n }\n );\n\n return [Math.floor(domain.min), Math.ceil(domain.max)];\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete all students that have homework score <= 60 | async function example14() {
try {
const {result} = await studentsCollection.deleteMany({
scores: {
$elemMatch: {
type: 'homework',
score: {$lt: 60}
}
}
});
console.log(`Deleted ${result.n} articles with results lower than 60`);
} catch (error) {
console.log(error);
}
} | [
"async function deleteNonEligibleStudents(client, eligibleScore) {\n const result = await client\n .db(\"myDB\")\n .collection(\"enrollment\")\n .deleteMany({ score: { $lt: eligibleScore } });\n console.log(`${result.deletedCount} document(s) was/were deleted`);\n}",
"function filter90AndAbove(score){\n return submissions.score >= 90;\n }",
"function removeScoresFromDB() {\n Score.remove({}, (err) => {\n if (err) throw err;\n });\n}",
"removeStudentFromStudentsExams(studentID){\n let check = this.checkIfStudentInExamList(studentID);\n if(check[0]){\n this.students_exams.splice(check[1], 1);\n }\n }",
"function destroyOldSkillScore(successCallback, errorCallback) {\n var UserSkillScore = Parse.Object.extend('User_Skill_Score'), // User Skill table\n query = new Parse.Query(UserSkillScore).include('skill'); // query to include skill data\n query.equalTo('user', user); // filter query for particular user\n query.find({\n success: function (userSkillScores) { // success callback\n if (userSkillScores.length > 0) {\n Parse.Object.destroyAll(userSkillScores).then(function () {\n saveSkillScore(successCallback, errorCallback);\n }, errorCallback);\n }\n else {\n saveSkillScore(successCallback, errorCallback);\n }\n },\n error: errorCallback\n });\n }",
"remove(school){\n var dex = this.mySchools.indexOf(school);\n this.mySchools.splice(dex, 1);\n }",
"function verifyEnrolledCourses(student_number, level, programme) { // new level and new programme\n const db = new sqlite3.Database(dbfile);\n db.run(\"DELETE FROM enrolled WHERE course_code NOT IN (SELECT code FROM course WHERE programme = ? AND level = ?)\", [sanitizer.sanitize(programme), sanitizer.sanitize(level)]);\n db.close();\n}",
"function filterScore(users, scoresGreaterThan) {\n return users.filter((it) => it.scores > scoresGreaterThan);\n}",
"async removeFromGrades() {\n\t\tif (!this.canEditScoreOutOf()) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst fields = [{ name: 'inGrades', value: false }];\n\t\tawait performSirenAction(this._token, this._getScoreOutOfAction(), fields);\n\t}",
"function deleteStudents() {\n\t$(\"#list-students li\").each( function() {\n\t\tvar selection = $(this); \n\t\tif (selection.hasClass('active')) { \n\t\t\tvar selectionContent = selection.html(); \n\t\t\tvar locate = selectionContent.lastIndexOf(\"<span\");\n\t\t\tvar thestudent;\n\t\t\tif (locate == -1) {\n\t\t\t\tthestudent = selectionContent;\n\t\t\t} else { \n\t\t\t\tthestudent = selectionContent.substring(0,locate);\n\t\t\t} \n\t\t\tdb.transaction(function (tx) { \n\t\t\t\ttx.executeSql(\"SELECT studentId FROM students WHERE studentName = ?;\", [thestudent], function(tx, result) {\n\t\t\t\t\tvar studentID = result.rows.item(0).studentId; \n\t\t\t\t\ttx.executeSql(\"DELETE FROM class_students WHERE classId =? AND studentId =?;\", [classID,studentID]);\n\t\t\t\t});\n\t\t\t});\t\t\t//need to specify if delete from students table when is not used for any class\n\t\t}\n\t});\n\tshowStudents();\n}",
"function filter90AndAbove(array) {\r\n let highScore = array.filter(function (submission) {\r\n return submission.score >= 90;\r\n });\r\n console.log(highScore);\r\n}",
"deleteHighScore() {\n localStorage.setItem(this.#highScoreLocation, this.#minHS);\n this.#highScore = this.#minHS;\n }",
"function removeStudent(student, ENo, Class)\n{\n // params -> both 'student name' and 'Enroll No.' to detect right student\n\t\n // special characters not allowed\n\t\n if(!(box.tableExists(Class)))\n\t{\n\t /* throw an error pop-up with 'bootstrap' */\n\t}\n\telse\n\t{\t\n\t\tbox.deleteRows(Class, function(row) {\n\t\t if((row.Student == student) && (row.EnrollNo == ENo))\n\t\t\t{\n\t\t\t // delete :- 'student' with given details\n\t\t\t return true;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t /* error pop-up : unable to detect exactly */\n\t\t\t}\n\t\t});\n\t}\n}",
"function clearAllScores() {\n localStorage.setItem(\"scoreList\", []);\n while (highscoreTable.children.length > 1) {\n highscoreTable.removeChild(highscoreTable.lastChild);\n }\n}",
"removeUser(students, token_res, tas, instructors) {\n for (let i = 0; i < students.length; i++) {\n if (students[i] === token_res.data.id) {\n students.splice(i--, 1);\n }\n }\n for (let i = 0; i < tas.length; i++) {\n if (tas[i] === token_res.data.id) {\n tas.splice(i--, 1);\n }\n }\n for (let i = 0; i < instructors.length; i++) {\n if (instructors[i] === token_res.data.id) {\n instructors.splice(i--, 1);\n }\n }\n }",
"function filterPassingGrades(grades) {\n let result = grades.filter(grade => grade >= 70);\n return result\n}",
"function checkRemoveStudents() {\n console.log(className);\n db.collection(\"Students\")\n .where(\"Student_Class\", \"==\", className)\n .get()\n .then((querySnapshot) => {\n let numStudents = querySnapshot.size;\n if (numStudents > 0) {\n enableRemoveStudents();\n }\n console.log(numStudents);\n })\n .catch((error) => {\n console.log(\"Error getting students in class: \", error);\n });\n}",
"function deleteStudentSheets() {\n var ss = SpreadsheetApp.getActiveSpreadsheet(); // ss means spreadsheet, or all the sheets combined\n var ssIndex = ss.getSheetByName(\"Yearly Student Reference Sheet\").getIndex();\n var saIndex = ssIndex - 1; // Spreadsheets are 1-indexed; sa = sheet actual\n var s = ss.getSheets()[saIndex];\n var range;\n var allSheets = ss.getSheets();\n var ssLength = allSheets.length;\n \n for (var i = ssIndex; i < ssLength; i++) {\n ss.deleteSheet(allSheets[i]);\n }\n}",
"function delAllStudents(classsel) {\n for (i = 1; i < 36; i++) {\n var stnm = localStorage.getItem(classsel + \"st\" + i);\n\n localStorage.removeItem(classsel + \"st\" + i);\n };\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
intWhile(); / You say it's your birthday If 2 given numbers represent your birth month and day in either order, log "How did you know?", else log "Just another day...." | function birthday(month,day){
if (month===7 && day===7){
console.log("How did you know?");
} else console.log("Just another day....")
} | [
"function youSayItsYourBirthday(num1, num2) {\n let month = 8;\n let day = 2;\n if(num1 == month || num2 == month){\n if(num1 == day || num2 == day){\n console.log(\"How did you know?\");\n }\n } else{\n console.log(\"Just another day...\");\n }\n}",
"function yourBirthday(numOne, numTwo)\n{\n var month = 4;\n var day = 22;\n\n //...if represents birthday\n if((numOne == month && numTwo == day) || (numTwo == month && numOne == day))\n {\n console.log('How did you know?');\n }\n //...else not birthday\n else\n {\n console.log('Just another day....');\n }\n}",
"function isItMyBirthday(num1, num2) {\n let day = 12;\n let month = 1;\n\n if (num1 == day || num2 == day) {\n if (num1 == month || num2 == month) {\n console.log(\"How did you know?\");\n }\n } else {\n console.log(\"Just antoher day...\");\n }\n}",
"function birthday(month, day){\r\n if (month === 7 && day === 21){\r\n console.log(\"How did you know?\");\r\n }\r\n else {\r\n console.log(\"Just another day\");\r\n }\r\n}",
"function yourBirthday(num1, num2) {\n if ((num1 == 7) && (num2 == 23)) {\n console.log(\"How did you know ?\");\n } else if ((num1 == 23) && (num2 == 7)) {\n console.log(\"How did you know\");\n } else {\n console.log(\"Just another day....\");\n }\n}",
"function birthday(day, month) {\nreturn (day == 15 && month == 11) || (day == 11 && month == 15) ? \"How did you know?\" : \n\"Just another day....\" ;\n}",
"function birthday(num1, num2) {\n\tvar myMonth = 6;\n\tvar myDate = 20;\n\tif((num1 === myMonth && num2 === myDate) || (num1 === myDate && num2 === myMonth)) {\n\t\tconsole.log(\"How did you know?\");\n\t} else {\n\t\tconsole.log(\"Just another day...\");\n\t}\n}",
"function birthday()\n{\n var birthDay = Math.floor((Math.random() * 31) + 1);\n var birthMonth = Math.floor((Math.random() *12) + 1);\n if (birthDay === 1 || birthMonth === 10) \n {\n console.log(\"How did you know?\")\n } \n else \n {\n console.log(\"Justher day…\")\n }\n console.log(\"Birthday = \" + birthDay, \"Birth Month number = \" + birthMonth)\n}",
"function checkAge(birth_day, birth_month, birth_year) {\n var date = new Date();\n var currentMonth = 10;\n var currentDate = 31;\n var monthDays = 30;\n\n\n if (birth_month == currentMonth && birth_day == currentDate) {\n return \"Today is your birthday!!!\";\n } else if (birth_month < currentMonth) {\n return \"Sorry your birthday is passed for this year\";\n } else if (birth_month > currentMonth) {\n\n var months = birth_month - currentMonth - 1;\n var currentMonthDays = monthDays - currentDate;\n var totalDays = currentMonthDays + birth_day;\n\n if (totalDays > monthDays) {\n months++;\n totalDays = totalDays - monthDays;\n }\n if (months > 0)\n return \"Your birthday will be in \" + months + \" months and \" + totalDays + \" days\";\n else {\n return \"Your birthday will be in \" + totalDays + \" days\";\n }\n } else if (birth_month == currentMonth) {\n if (birth_day < currentDate) {\n return \"Your birthday already passed for this year\";\n } else {\n var daysLeft = birth_day - currentDate;\n return \"Your birthday will be in \" + daysLeft;\n }\n }\n}",
"function monthDays()\n{\n var month=prompt('Enter month','Month')\n month=month.toLowerCase()\n if (month=='february')\n {\n console.log(28)\n }\n else if (month=='january' || month=='march' || month=='may' || month=='july' || month=='august' || month=='october' || month=='december')\n {\n console.log(31)\n }\n else\n {\n console.log(30)\n }\n}",
"function getBirthday(birthday){ \n var today = new Date();\n var dd = String(today.getDate()).padStart(2, '0');\n var mm = String(today.getMonth() + 1).padStart(2, '0'); \n\n today = mm + dd;\n var birthdayString =\"\";\n \n if( birthday == today) {\n birthdayString = \"Birthday is today!\"; \n } else if ( birthday > today){\n birthdayString = \"Birthday has yet to occur\"; \n } else {\n birthdayString = \"Birthday already happened\"; \n }\n return birthdayString; \n }",
"function yourBirthday() {\n today = new Date();\n dd = String(today.getDate()).padStart(2, '0');\n mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!\n yyyy = today.getFullYear();\n today = mm + '/' + dd;\n isBirthday = birthdayLog.substring(0,5);\n // get all friends birthdays\n if (today === isBirthday) {\n if(bdayAlert === true) {\n bdayAlert = false;\n }\n }\n}",
"verifyBirthday(date) {\n let today = new Date();\n let bDate = new Date(date);\n let todayDate = today.getDate();\n let bDateDate = bDate.getDate();\n let todayMonth = today.getMonth();\n let bDateMonth = bDate.getMonth();\n let msg = \"\";\n if (todayMonth < bDateMonth) {\n msg = \"has yet to occur\";\n } else if (todayMonth > bDateMonth) {\n msg = \"already happened\";\n } else {\n if (todayDate < bDateDate) {\n msg = \"has yet to occur\";\n } else if (today > bDateDate) {\n msg = \"already happened\";\n } else {\n msg = \"is today(!)\";\n }\n }\n\n return msg;\n }",
"function birthday(s, d, m) {\n let answer = 0;\n\n for (let i = m - 1; i < s.length; i++) {\n let tempSum = 0;\n for (let k = m - 1; k >= 0; k--) {\n let tempNum = i - k;\n tempSum = tempSum + s[tempNum];\n }\n if (tempSum === d) {\n answer++;\n }\n }\n return answer;\n}",
"function calculateDays(birthdate) {\n birthdate = birthdate.split(\"-\");\n let now = new Date();\n let birthMonth = parseInt(birthdate[1]);\n let birthDay = parseInt(birthdate[2]);\n let currentMonth = now.getMonth()+1;\n let description = \"\";\n \n if (birthMonth >= currentMonth) {\n let months = birthMonth - currentMonth;\n if (months <= 1) {\n months = 0;\n } \n description += months + \" months, \";\n } else {\n let months = 12 - currentMonth;\n if (birthMonth > 1) {\n months += (birthMonth - 1);\n }\n if (months == 1) {\n description += months + \" month, \";\n } else {\n description += months + \" months, \";\n }\n }\n let weeks = 0;\n if (birthDay > 7) {\n weeks = Math.floor(birthDay / 7);\n description += weeks + \" week\" + (weeks != 1 ? \"s \" : \" \");\n }\n description += \"and \" + ((birthDay - (weeks * 7)) + \" days\");\n\n return description;\n }",
"function starsign(dob) {\n const dobDay = Number(dob.split('-')[2])\n const dobMonth = Number(dob.split('-')[1])\n if ((dobDay >= 21 && dobMonth === 3) || (dobDay <= 19 && dobMonth === 4)) {\n return \"aries\"\n }\n if ((dobDay >= 20 && dobMonth === 4) || (dobDay <= 20 && dobMonth === 5)) {\n return \"taurus\"\n }\n if ((dobDay >= 21 && dobMonth === 5) || (dobDay <= 20 && dobMonth === 6)) {\n return \"gemini\"\n }\n if ((dobDay >= 21 && dobMonth === 6) || (dobDay <= 22 && dobMonth === 7)) {\n return \"cancer\"\n }\n if ((dobDay >= 23 && dobMonth === 7) || (dobDay <= 22 && dobMonth === 8)) {\n return \"leo\"\n }\n if ((dobDay >= 23 && dobMonth === 8) || (dobDay <= 22 && dobMonth === 9)) {\n return \"virgo\"\n }\n if ((dobDay >= 23 && dobMonth === 9) || (dobDay <= 22 && dobMonth === 10)) {\n return \"libra\"\n }\n if ((dobDay >= 23 && dobMonth === 10) || (dobDay <= 22 && dobMonth === 11)) {\n return \"scorpio\"\n }\n if ((dobDay >= 23 && dobMonth === 11) || (dobDay <= 21 && dobMonth === 12)) {\n return \"sagittarius\"\n }\n if ((dobDay >= 22 && dobMonth === 12) || (dobDay <= 19 && dobMonth === 1)) {\n return \"capricorn\"\n }\n if ((dobDay >= 20 && dobMonth === 1) || (dobDay <= 18 && dobMonth === 2)) {\n return \"aquarius\"\n }\n if ((dobDay >= 19 && dobMonth === 2) || (dobDay <= 20 && dobMonth === 3)) {\n return \"pisces\"\n }\n}",
"function birthday(s, d, m) {\n let count = 0;\n let sum = 0;\n\n for (let i = 0; i < m; i++) {\n sum += s[i];\n }\n\n for (let i = m; i < s.length; i++) {\n if (sum == d) {\n count++;\n }\n\n sum -= s[i - m];\n sum += s[i];\n }\n\n if (sum == d) {\n count++;\n }\n\n return count;\n}",
"function how_many_days(input) {\n if (input < 1 | input > 12) {\n return 'That is not a valid number of days for a month!...please pick a number between 1 - 12 and try again!';\n}\n if (input === 1) {\n return days_in_month[0];\n }\n if (input === 2) {\n return days_in_month[1];\n }\n if (input === 3) {\n return days_in_month[2];\n }\n if (input === 4) {\n return days_in_month[3];\n }\n if (input === 5) {\n return days_in_month[4];\n }\n if (input === 6) {\n return days_in_month[5];\n }\n if (input === 7) {\n return days_in_month[6];\n }\n if (input === 8) {\n return days_in_month[7];\n }\n if (input === 9) {\n return days_in_month[8];\n }\n if (input === 10) {\n return days_in_month[9];\n }\n if (input === 11) {\n return days_in_month[10];\n }\n if (input === 12) {\n return days_in_month[11];\n }\n return false;\n}",
"function getZodiac() {\n switch($userBirthday.month) {\n case 0:\n if ($userBirthday.day < 20) {\n return 'capricorn';\n } else {\n return 'aquarius';\n }\n break;\n case 1:\n if ($userBirthday.day < 19) {\n return 'aquarius';\n } else {\n return 'pisces';\n }\n break;\n case 2:\n if ($userBirthday.day < 21) {\n return 'pisces';\n } else {\n return 'aries';\n }\n break;\n case 3:\n if ($userBirthday.day < 20) {\n return 'aries';\n } else {\n return 'taurus';\n }\n break;\n case 4:\n if ($userBirthday.day < 21) {\n return 'taurus';\n } else {\n return 'gemini';\n }\n break;\n case 5:\n if ($userBirthday.day < 21) {\n return 'gemini';\n } else {\n return 'cancer';\n }\n break;\n case 6:\n if ($userBirthday.day < 23) {\n return 'cancer';\n } else {\n return 'leo';\n }\n break;\n case 7:\n if ($userBirthday.day < 23) {\n return 'leo';\n } else {\n return 'virgo';\n }\n break;\n case 8:\n if ($userBirthday.day < 23) {\n return 'virgo';\n } else {\n return 'libra';\n }\n break;\n case 9:\n if ($userBirthday.day < 23) {\n return 'libra';\n } else {\n return 'scorpio';\n }\n break;\n case 10:\n if ($userBirthday.day < 22) {\n return 'scorpio';\n } else {\n return 'sagittarius';\n }\n break;\n case 11:\n if ($userBirthday.day < 22) {\n return 'sagittarius';\n } else {\n return 'capricorn';\n }\n break;\n default:\n break;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
API call to get current Account settings | function getAccountSettings() {
APIUtils.getAllUserAccountProperties()
.then((settings) => {
$scope.accountSettings = settings;
})
.catch((error) => {
console.log(JSON.stringify(error));
$scope.accountSettings = null;
})
} | [
"static getSettings() {\n const apiClient = new APIClientFactory().getAPIClient(Utils.getCurrentEnvironment(), Utils.CONST.API_CLIENT).client;\n const promisedSettings = apiClient.then(client => {\n return client.apis['Settings'].getSettings();\n });\n return promisedSettings.then(response => response.body);\n }",
"function getSettings() {\n getIrtSettings();\n // Async ask for the user settings in 250ms after sending last request.\n setTimeout(function () {\n getUserConfiguration();\n }, 250);\n setTimeout(function () {\n getIrtSettingsPowerAdjust();\n }, 500); \n }",
"function getAccountInfo(){\n return ex.privateGetAccountAccounts();\n /*\n {\n status: 'ok',\n data: [ { id: '26502858', type: 'spot', subtype: '', state: 'working' } ]\n }\n */\n }",
"function getAccount() {\n const config = zxeth.getConf();\n\n return config.accounts[0];\n}",
"function getDocmgrSettingData() {\n\n var data = protoReqSync(\"index.php?module=accountinfo&accountId=\" + account);\n\n //set our globals from contact information\n setGlobals(data.account[0]);\n\n return data.account[0];\n\n}",
"async getSettings() {\n const settings = await request.get(`${BASE_URL}/settings`);\n return JSON.parse(settings);\n }",
"getChatSettings() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/chat/settings', \n\t\t\t'GET', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}",
"getWebchatSettings() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/webchat/settings', \n\t\t\t'GET', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}",
"getSettings() {\n const promisedSettings = this.client.then(client => {\n return client.apis['Settings'].getSettings();\n });\n return promisedSettings.then(response => response.body);\n }",
"async getAccountInfo () {\n try {\n const params = { timestamp: Date.now() }\n\n const response = await this.HttpClient.get('/v3/account', { params, secure: true })\n\n return response.data\n } catch (error) {\n console.log('Error when fetching account info')\n console.log(error.stack)\n if (error.response) {\n console.log('error.response.data=', error.response.data)\n }\n }\n }",
"getSettings() {\n const promisedSettings = this.client.then(client => {\n return client.apis['Settings'].get_settings();\n });\n return promisedSettings.then(response => response.body);\n }",
"async settings(authTokenKey, tenant) {\n let result = await this.executeOperation(\"/ldap/settings\", {\n authTokenKey: authTokenKey,\n tenant: tenant,\n clientInfo: \"mobile\"\n });\n\n if (result) {\n return result.content;\n } else {\n throw Error(`failed to retrieve ldap settings for tenant ${tenant}`);\n } \n }",
"function getSettings() {\n\t\tif (!name) {\n\t\t\tvar usernameLine = document.getElementById(\"title\");\n\t\t\tusernameLine = usernameLine.innerHTML;\n\t\t\tvar username = usernameLine.split(\"'\");\n\t\t\tname = username[0].toLowerCase();\n\t\t}\n\t\tvar php = \"?mode=account&username=\" + name;\n\t\tajax(USER_URL, php, setSettings, \"GET\", false);\n\t}",
"function getAccountData() {\n\n var data = protoReqSync(\"index.php?module=accountinfo&accountId=\" + account);\n\n //set our globals from contact information\n\tsetGlobals(data.account[0]);\n\n\treturn data.account[0];\n\t\n}",
"getOrganizationsAuthenticationSettings() { \n\n\t\treturn this.apiClient.callApi(\n\t\t\t'/api/v2/organizations/authentication/settings', \n\t\t\t'GET', \n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\t{ },\n\t\t\tnull, \n\t\t\t['PureCloud OAuth'], \n\t\t\t['application/json'],\n\t\t\t['application/json']\n\t\t);\n\t}",
"async function getSettingsFields() {\n return await axios({\n method: \"get\",\n url: url + \"/user/settings/\",\n headers: { Authorization: \"Bearer \" + localStorage.jwt }\n });\n}",
"function getSettings() {\n\t\treturn data.settings;\n\t}",
"function getAccountDetails() {\n\tvar baseUrl = getClientStore().baseURL; \n\tvar accessor = objCommon.initializeAccessor(baseUrl, cellName);\n\tvar objAccountManager = new _pc.AccountManager(accessor);\n\tvar count = retrieveAccountRecordCount();\n\tvar uri = objAccountManager.getUrl();\n\turi = uri + \"?$orderby=__updated desc &$top=\" + count;\n\tvar restAdapter = _pc.RestAdapterFactory.create(accessor);\n\tvar response = restAdapter.get(uri, \"application/json\");\n\tvar json = response.bodyAsJson().d.results;\n\treturn json;\n}",
"function getAccountData() {\n var userProperties = PropertiesService.getUserProperties();\n return JSON.parse(userProperties.getProperty('account_data'));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
else if Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3. Example: addWithSurcharge(10, 30) should return 44. | function addWithSurcharge(a, b) {
let surcharge = 0;
if (a <= 10) {
surcharge = surcharge + 1;
} else if (a >= 10 && a<=20) {
surcharge = surcharge + 2;
} else {
surcharge = surcharge + 3;
}
if (b <= 10) {
surcharge = surcharge + 1;
} else if (b >= 10 && b <= 20) {
surcharge = surcharge + 2;
} else {
surcharge = surcharge + 3;
}
return a + b + surcharge;
} | [
"function addWithSurcharge(a, b) {\n\nlet surcharge = 0;\n\nif (a <= 10) {\n surcharge = surcharge + 1;\n} else {\n surcharge = surcharge + 2;\n}\n\nif (b <= 10) {\n surcharge = surcharge + 1;\n} else {\n surcharge = surcharge + 2;\n}\n\nreturn a + b + surcharge;\n}",
"function addWithSurcharge(a, b) {\n\n let surcharge = 0;\n\n if (a <= 10) {\n surcharge = surcharge + 1;\n } else {\n surcharge = surcharge + 2;\n }\n\n if (b <= 10) {\n surcharge = surcharge + 1;\n } else {\n surcharge = surcharge + 2;\n }\n\n return a + b + surcharge;\n}",
"function addWithSurcharge(amount1, amount2) {\n if(amount1 <= 10 && amount2 <= 10) {\n return ((amount1 + 1) + (amount2 + 1));\n } else if(amount1 > 10 && amount2 > 10) {\n return ((amount1 + 2) + (amount2 + 2));\n } else if(amount1 <= 10 && amount2 > 10) {\n return ((amount1 + 1) + (amount2 + 2));\n } else if(amount1 > 10 && amount2 <= 10) {\n return ((amount1 + 2) + (amount2 + 1));\n }\n}",
"function addWithSurcharge(pOne, pTwo) {\n if(pOne <= 10 && pTwo <= 10) {\n return pOne + pTwo + 2;\n } else if((pOne > 10 && pOne <= 20) && (pTwo > 10 && pTwo <= 20)) {\n return pOne + pTwo + 4;\n } else if((pOne > 20) && (pTwo > 20)) {\n return pOne + pTwo + 6;\n } else if(pOne <= 10 && (pTwo > 10 && pTwo <= 20)) {\n return pOne + pTwo + 1 + 2;\n } else if(pTwo <= 10 && (pOne > 10 && pOne <= 20)) {\n return pOne + pTwo + 1 + 2;\n } else if((pOne <= 10 && pTwo > 20) ||(pTwo <= 10 && pOne > 20)) {\n return pOne + pTwo + 1 + 3;\n } else if((pOne > 10 && pOne <= 20) && (pTwo > 20)) {\n return pOne + pTwo + 2 + 3;\n } else if((pTwo > 10 && pTwo <= 20)&& (pOne > 20)) {\n return pOne + pTwo + 2 + 3;\n }\n}",
"function addWithSurcharge(x, y) {\n let surcharge = 0;\n if (x <= 10) {\n surcharge += 1;\n } else if (x > 10) {\n surcharge += 2;\n }\n\n if (y <= 10) {\n surcharge += 1;\n } else if (y > 10) {\n surcharge += 2;\n }\n return x + y + surcharge;\n}",
"function calcSurcharge(n) {\n let surcharge = 0;\n if (n > 20) {\n surcharge += 3;\n } else if (n > 10 && n <= 20) {\n surcharge += 2;\n } else {\n surcharge += 1;\n }\n return surcharge;\n\n}",
"function surchargeAmount(ticketCost, surchargeRate) { // calculates surcharge amount\n\n return ticketCost * surchargeRate;\n}",
"function sumOf2nr(nr1, nr2){\n let sum = nr1 + nr2\n if(sum >= 50 && sum <= 80){\n return 65\n }else{\n return 80\n }\n}",
"function mySum(int1,int2) {\n if (((int1 + int2) >= 50) && ((int1 + int2) <= 80)) {\n return 65\n }\n else return 80\n}",
"addWeight(value1, value2){\n return value1 + value2\n }",
"function practiceFunc(arg1, arg2) {\n\tvar newNumb = arg1+arg2\n if (newNumb < 20) {\n console.log(newNumb)\n } else {\n console.log(\"Can't count that high!\")\n }\n}",
"function buy10() {\n const credit = 1100;\n addCredit(credit);\n return credit;\n}",
"function addsTwoForJumanji(numA, numB){\n let over50 = numA + numB\n if (over50 > 50){\n //alert(\"jumanji\")\n return over50\n }else return over50\n}",
"plusGood() {\r\n if (this.costOngood >= 0 && this.costOngood < this.other - this.costOnentertainment - this.costOnrotten) {\r\n this.costOngood++;\r\n document.getElementById(\"costForgood\").innerHTML = \"$\" + this.costOngood;\r\n }\r\n }",
"function addIfPositive(a, b) {\n\n\tif (b > 0) {\n\t\treturn a + b;\n\t}\n\n\treturn a;\n\n}",
"function calsurchargeOnAmtcAboveCrore(){\r\n\tvar taxPayable = document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnDeemedTI.taxDeemedTISec115JC')[0];\r\n\tvar surchargeOnAboveCrore = document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnDeemedTI.surchargeA')[0];\r\n\tvar totInc = document.getElementsByName('itrScheduleAMT.adjustedUnderSec115JC')[0];\ttotInc.value = coalesce(totInc.value);\r\n\r\n\t// for surcharge\r\n\t\t\t\tvar taxOnTotInc = parseInt(taxPayable.value,10);\r\n\t\t\t\tvar taxOnCutOffInc = (10000000 * .185);\r\n\r\n\t\t\t\tif( rndOffNrsTen(totInc.value) > 10000000 ){\r\n\t\t\t\t\tvar tempSurcharge = taxOnTotInc * 0.1 ;\r\n\t\t\t\t\t\r\n\t\t\t\t\t//check if eligible for marginal relief\r\n\t\t\t\t\tvar extraInc = rndOffNrsTen(totInc.value) - 10000000;\r\n\t\t\t\t\tif( (taxOnTotInc + tempSurcharge ) > (taxOnCutOffInc + extraInc)){\r\n\t\t\t\t\t\tvar marginalRelief = taxOnTotInc + tempSurcharge - (taxOnCutOffInc + extraInc );\r\n\t\t\t\t\t\tsurchargeOnAboveCrore.value = tempSurcharge - marginalRelief;\r\n\t\t\t\t\t\tsurchargeOnAboveCrore.value = Math.round(surchargeOnAboveCrore.value);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tsurchargeOnAboveCrore.value = tempSurcharge;\r\n\t\t\t\t\t\tsurchargeOnAboveCrore.value = Math.round(surchargeOnAboveCrore.value);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\t surchargeOnAboveCrore.value = parseInt('0' ,10);\r\n\t\t\t\t}\r\n\t}",
"function buy20() {\n const credit = 2300;\n addCredit(credit);\n return credit;\n}",
"function insurance(age, size, numofdays){\n let sum = age < 25 ? numofdays * (50 + 10) : numofdays * 50\n console.log(sum)\n if (numofdays < 0) return 0\n switch (size) {\n case 'economy':\n sum = sum;\n break\n case 'medium':\n sum = sum + numofdays * 10;\n break\n case 'full-size':\n default:\n sum = sum + numofdays * 15\n break\n }\n return sum\n}",
"function buy50() {\n const credit = 6000;\n addCredit(credit);\n return credit;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
finction that controls the reel 2 spinning | function spin2(){
i2++;
if (i2>=numeberReel2){
coin[1].play();
clearInterval(reel2);
return null;
}
reelTile = document.getElementById("slot2");
if (reelTile.className=="s1"){
reelTile.className = "s0";
}
let d2 = Math.floor(Math.random() * 5) + 1;
reelTile.className = "s"+ d2
} | [
"function Spin() {\n wheel.AcclToRadsPerSec(Math.PI * 2, 3000, new ArcsinMapper_1.default());\n setTimeout(() => {\n console.log(\"slowing down\");\n //note this currently always decels to 0.\n wheel.AcclToRadsPerSec(0, 3000, new ArcsinMapper_1.default());\n setTimeout(DoFish, 3000);\n }, 10000);\n }",
"function spin2(){\n\t\ti2++;\n\t\tif (i2>=numeberReel2){\n coin[1].play();\n\t\t\tclearInterval(reel2);\n\t\t\treturn null;\n\t\t}\n\t\treelTile = document.getElementById(\"slot2\");\n\t\tif (reelTile.className==\"s1\"){\n\t\t\treelTile.className = \"s0\";\n }\n\t\treelTile.className = \"s\"+ question2\n }",
"function spin2() {\n\t\t\tvar $myElm = $(\".roulette-small\");\n\n\t\t\tfunction rotate2(degrees) {\n\t\t\t\t$myElm.css({\n\t\t\t\t\t'-webkit-transform': 'rotate(-' + degrees + 'deg)',\n\t\t\t\t\t'-moz-transform': 'rotate(-' + degrees + 'deg)',\n\t\t\t\t\t'-ms-transform': 'rotate(-' + degrees + 'deg)',\n\t\t\t\t\t'transform': 'rotate(-' + degrees + 'deg)'\n\t\t\t\t});\n\n\t\t\t}\n\t\t\t$({\n\t\t\t\tdeg: 0\n\t\t\t}).animate({\n\t\t\t\tdeg: degVal\n\t\t\t}, {\n\t\t\t\tduration: time,\n\t\t\t\teasing: \"easeOutCubic\",\n\t\t\t\tstep: function (now) {\n\t\t\t\t\tvar deg = now;\n\t\t\t\t\trotate2(deg);\n\t\t\t\t}\n\t\t\t});\n\t\t\tvar audio = new Audio('audio/spinsound.mp3');\t\n\t\t\taudio.play();\n\t\t}",
"function spin(){\nchange -= turn;\ndraw();\n}",
"async startSpin() {\n const spinSound = AssetLoader.sounds[AssetLoader.audioAssets.spinning].play();\n AssetLoader.sounds[AssetLoader.audioAssets.spinning].loop(spinSound, spinSound);\n this.enableSpinButton(false);\n\n this.state = 'spinning';\n // reset the total win\n this.entity.eventEmitter.emit('spinStarted');\n\n // velocity used for filter calculation\n const velocity = { x: 0, y: 0 };\n const filter = new MotionBlurFilter([0, 0], 9);\n\n //this.container.filters = [filter];\n\n new TWEEN.Tween(velocity)\n .to({ x: 1, y: 50 }, 1500)\n .easing(TWEEN.Easing.Quadratic.InOut)\n .onUpdate((o) => {\n filter.velocity = [o.x, o.y];\n })\n .repeat(1)\n .yoyo(true)\n .start();\n\n // lets stop the reels after 1.5sec which gives us roughly 2 second spin\n new TWEEN.Tween(this.container)\n .delay(1500)\n .onComplete(() => {\n this.stop();\n AssetLoader.sounds[AssetLoader.audioAssets.spinning].stop(spinSound);\n })\n .start();\n\n for (let i = 0; i < this.reels.length - 1; i++) {\n this.reels[i].spin(Math.round(Math.random() * 20));\n }\n // we can wait for the last reel to start spinning and we can execute more actions after\n await this.reels[this.reels.length - 1].spin(Math.round(Math.random() * 20));\n\n this.container.filters = [];\n }",
"function spin() {\r\n removeClasses();\r\n getInputOneColor();\r\n getInputTwoColor();\r\n getInputThreeColor();\r\n displayText(); \r\n changePic();\r\n winningSound();\r\n }",
"function stopSpin () {\n\t\t// stop reel 1\n\t\tsetTimeout(function() {\n\t\t\t$('.slots').removeClass('spinning1');\n\t\t\t$('.slot-one').css('background-image', 'url(' + $scope.slotData[0].imgSlug + ')');\n\t\t}, 1200)\n\t\t// stop reel 2\n\t\tsetTimeout(function() {\n\t\t\t$('.slots').removeClass('spinning2');\n\t\t\t$('.slot-two').css('background-image', 'url(' + $scope.slotData[1].imgSlug + ')');\n\t\t}, 1800)\n\t\t// stop reel 3\n\t\tsetTimeout(function() {\n\t\t\t$('.slots').removeClass('spinning3');\n\t\t\t$('.slot-three').css('background-image', 'url(' + $scope.slotData[2].imgSlug + ')');\n\t\t\tcheckForWinner();\n\t\t}, 2100)\n\t}",
"function startSpinWheelInner(){\n\tif(!secondWheel){\n\t\treturn;\t\n\t}\n\t\n\twheelInnerContainer.rotation = 0;\n\tvar wheelInnerRadius = 360 / wheelSecond_arr.length;\n\tvar rotateNum = gameData.fixedInnerRotate;\n\tif(rotateNum == -1){\n\t\tif(enablePercentage){\n\t\t\trotateNum = getResultOnPercentInner();\n\t\t}else{\n\t\t\trotateNum = Math.floor(Math.random()*wheelSecond_arr.length);\n\t\t}\n\t}\n\tvar innerNum = rotateNum;\n\tif(!gameData.spinDirection){\n\t\trotateNum = wheelSecond_arr.length - rotateNum;\n\t}\n\tif(gameData.spinDirection){\n\t\trotateNum = Math.abs((wheelInnerRadius * (rotateNum+1)) - (wheelInnerRadius/2));\n\t}else{\n\t\trotateNum = Math.abs((wheelInnerRadius * (rotateNum)) - (wheelInnerRadius/2));\t\n\t}\n\t\n\tvar totalRound = Math.floor(spinSpeed/4);\n\tvar totalRoundNum = 360 * totalRound;\n\tvar toRotate = -(totalRoundNum + rotateNum);\n\tif(!gameData.spinDirection){\n\t\ttoRotate = Math.abs(totalRoundNum + rotateNum);\n\t}\n\tTweenMax.to(wheelInnerContainer, totalRound, {rotation:toRotate, overwrite:true, ease: Circ.easeOut, onComplete:function(){\n\t\tplaySound('soundSelect');\n\t\tgameData.wheelInnerNum = innerNum;\n\t\t$.wheelInner[gameData.wheelInnerNum].visible = true;\n\t\tanimateWheelSegment($.wheelInner[gameData.wheelInnerNum], true);\n\t\t\n\t\t//slot color feature\n\t\tif(wheelSecond_arr[gameData.wheelInnerNum].slot != undefined && wheelSecond_arr[gameData.wheelInnerNum].slot.highlightColor != ''){\n\t\t\t$.wheelInner['slotH'+gameData.wheelInnerNum].visible = true;\n\t\t\tanimateWheelSegment($.wheelInner['slotH'+gameData.wheelInnerNum], true);\n\t\t\t\t\t\n\t\t\twheelInnerContainer.setChildIndex($.wheelInner['slot'+gameData.wheelInnerNum], wheelInnerContainer.getNumChildren()-1);\n\t\t}\n\t\t\n\t\tTweenMax.to(wheelInnerContainer, 1, {overwrite:true, onComplete:function(){\n\t\t\tcheckWheelScore();\n\t\t}});\n\t}});\n}",
"function rightReelSpin() {\n //If the current image has reached the bottom of the viewing window, and we are not at the max number of spins, get the next image and continue.\n if (rightReel.regY <= -250 && (timesSpunRight < spinsRight))\n newReelRight();\n else if (timesSpunRight < spinsRight)\n rightReel.regY = (rightReel.regY - 10);\n else if (timesSpunRight == spinsRight && (rightReel.regY > -170))\n rightReel.regY = (rightReel.regY - 10);\n}",
"function Back() {\n deg -= 43;\n $(\".FoodSpin .spin\").css(\"transform\", \"rotate(\" + deg + \"deg) scale(0.9)\");\n setTimeout(function () {\n $(\".FoodSpin .spin\").css(\"transform\", \"rotate(\" + deg + \"deg)\");\n }, 250);\n $(\".svg\").toggleClass(\"svgSecond\");\n $(\".controls .back\").toggleClass(\"SecondColor\");\n $(\".controls .next\").toggleClass(\"SecondColor\");\n}",
"function spin_reels() {\n $('#keyframes').empty();\n $('.reel, #results *').removeClass('active');\n\n var reel_params = get_reel_params();\n\n $('#keyframes').append(keyframe_rule('reel-1-spin', reel_params[0]),\n keyframe_rule('reel-2-spin', reel_params[1]),\n keyframe_rule('reel-3-spin', reel_params[2]));\n\n $('.reel').addClass('active');\n\n $('#reel-3').unbind('animationend webkitAnimationEnd')\n .bind('animationend webkitAnimationEnd', {reel_params: reel_params}, get_results);\n}",
"function startSpin () {\t\t\n\t\t// start each reel spinning\n\t\t$('.slot-one').addClass('spinning1');\n\t\t$('.slot-two').addClass('spinning2');\n\t\t$('.slot-three').addClass('spinning3');\t\t\n\t\t// stop reels\n\t\tstopSpin();\n\t}",
"function spinDone() {\n\n log('Spin finished');\n\n //reset reel container y positions\n reelPosCleanup(reel1);\n reelPosCleanup(reel2);\n reelPosCleanup(reel3);\n\n checkWins();\n\n //enable interactions\n spinButton.prop('disabled', false);\n inputElement.prop('disabled', false);\n}",
"function spin() {\n\t\t\tvar $myElm = $(\".roulette-big\");\n\n\t\t\tfunction rotate(degrees) {\n\t\t\t\t$myElm.css({\n\t\t\t\t\t'-webkit-transform': 'rotate(' + degrees + 'deg)',\n\t\t\t\t\t'-moz-transform': 'rotate(' + degrees + 'deg)',\n\t\t\t\t\t'-ms-transform': 'rotate(' + degrees + 'deg)',\n\t\t\t\t\t'transform': 'rotate(' + degrees + 'deg)'\n\t\t\t\t});\n\n\t\t\t}\n\t\t\t$({\n\t\t\t\tdeg: 0\n\t\t\t}).animate({\n\t\t\t\tdeg: degVal\n\t\t\t}, {\n\t\t\t\tduration: time,\n\t\t\t\teasing: \"easeOutCubic\",\n\t\t\t\tstep: function (now) {\n\t\t\t\t\tvar deg = now;\n\t\t\t\t\trotate(deg);\n\n\n\t\t\t\t}\n\t\t\t});\n\t\t}",
"spinRight(){ \n this.position.cardinal = (this.position.cardinal === 3) ? 0 : this.position.cardinal + 1;\n }",
"function Update() {\n\t//Spin(speed, axis);\n}",
"function callback_SecondFade()\n{\n\tif (g_bFirstRotateTime)\n\t{\n\t\tg_bFirstRotateTime = false;\n\t}\n\t\n\t/* Rotation is no longer in progress. Set the variable back to false. */\n\tg_bRotateInProgress = false;\n}",
"function setSpinner(son, mom, base, speed){\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\r\n\t// spin 360\r\n\tvar autospin, posXori = 1, mdown=false, posXori, tickAmount = speed, autoId = 0;\r\n\t \r\n\tfunction moveBack(){\r\n\t\ti++;\r\n\t\tif(i > spinMax - 1){\r\n\t\t\ti=0;\r\n\t\t}\r\n\t\tspinner(i)\r\n\t}\r\n\t\r\n\tfunction moveForward(){\r\n\t\ti--;\r\n\t\tif(i < 0){\r\n\t\t\ti = spinMax-1;\r\n\t\t}\r\n\t\tspinner(i);\r\n\t}\r\n\t\r\n\tmom.appendChild(son);\r\n\t\t\r\n\tspinner = function(sp){\r\n\t\t// spinner frame has all the to be spinner images on x gap space, so we can place them on x=spinId*image width, so we give illusion of spin, haha\r\n\t\t// display -none vs block- is too much on processor, using one div with images as train, moving x direction is so far, best to spin \r\n\t\tarrFrame[1].style.left = -gap*sp;\r\n\t\t//trace(sp)\r\n\t}\r\n\r\n}",
"static flashSpin() {\n Draw.ctx.putImageData(Draw.behindSpin, Draw.dim.ratios[\"spin\"][0] * Draw.dim.width, Draw.dim.ratios[\"spin\"][1] * Draw.dim.height, 0, 0, Draw.behindSpin.width * Draw.dim.shrink, Draw.behindSpin.height * Draw.dim.shrink);\n if (Draw.spinOn) {\n Draw.spinOn = false;\n }\n else {\n Draw.ctx.drawImage(Draw.spin, Draw.dim.ratios[\"spin\"][0] * Draw.dim.width, Draw.dim.ratios[\"spin\"][1] * Draw.dim.height, Draw.spin.width * Draw.dim.shrink, Draw.spin.height * Draw.dim.shrink);\n Draw.spinOn = true;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
drawsnitch() Draw the snitch as an ellipse with alpha based on health | function drawsnitch() {
image(snitchImage, snitchX, snitchY);
} | [
"function setupsnitch() {\n snitchX = width/5;\n snitchY = height/2;\n snitchVX = -snitchMaxSpeed;\n snitchVY = snitchMaxSpeed;\n snitchHealth = snitchMaxHealth;\n}",
"function drawHat() {\n\tctx.strokeStyle = 'yellow';\n\tctx.strokeRect(player.x, player.y, player.width, player.height / 3);\n\tctx.strokeRect(player.x - 5, player.y + (player.height / 3), player.width + 10, 0);\n}",
"function drawHealth() {\n ctx.lineWidth = 1\n // Draw empty health circles\n for (let i = hero.maxhealth; i > 0; i--) {\n circle(20+(30*i), 50, 30, 'white', 'black', 0, 2 * Math.PI, [5, 5])\n }\n // Fill health circles\n for (let i = hero.health; i > 0; i--) {\n circle(20+(30*i), 50, 30, 'hotpink', 'black', 0 - frame, 2 * Math.PI + frame, [5, 5])\n }\n}",
"function drawPlayer() {\n push();\n tint(255,255,255,playerHealth);\n image(playerCat,playerX, playerY, playerRadius * 3, playerRadius * 3);\n pop();\n\n\n}",
"function drawHealth() {\n ctx.font = \"20px Courier\";\n ctx.fillStyle= GREEN_COLOR;\n var healthText = \"Health: \";\n var healthMeasure = ctx.measureText(healthText);\n var healthWidth = healthMeasure.width;\n ctx.fillText(healthText, 5, 23);\n // draw the grey background of the health bar\n ctx.fillStyle = \"grey\";\n ctx.fillRect(healthWidth+5, 12, 200, 10);\n\n // draw the ship health\n if (Math.floor(ship.health) >= 25) {\n ctx.fillStyle = GREEN_COLOR;\n } else {\n ctx.fillStyle = \"red\"; // I will make this more specific / prettier\n }\n var percentageFull = ship.health / MAX_HEALTH;\n percentageFull = max(0.0, percentageFull);\n ctx.fillRect(healthWidth+5, 12,\n Math.floor(percentageFull*200), 10);\n\n // now draw all the shield on top of that (last shield to first shield)\n for (var i = ship.shields.length-1; i >= 0; i--) {\n percentageFull = ship.shields[i].health / ship.shields[i].maxHealth;\n percentageFull = max(0.0, percentageFull);\n ctx.fillStyle = ship.shields[i].color;\n ctx.fillRect(healthWidth+5, 12, Math.floor(percentageFull*200), 10);\n }\n}",
"draw_pawn(graphics_state, model_transform, side){\r\n //create base with flattened sphere - draw at center of square\r\n let base = model_transform.times(Mat4.scale(Vec.of(0.65, 0.3, 0.65)));\r\n base = base.times(Mat4.translation([0, -2, 0]));\r\n\r\n let ring = model_transform.times(Mat4.scale(Vec.of(0.5, 0.1, 0.5)));\r\n ring = ring.times(Mat4.translation([0, 0.5, 0]));\r\n\r\n //create body of pawn \r\n let mid = model_transform.times(Mat4.scale(Vec.of( 0.25, 0.5, 0.25)));\r\n mid = mid.times(Mat4.translation([0,0.25,0]));\r\n\r\n let top = model_transform.times(Mat4.scale(Vec.of( 0.35, 0.35, 0.35)));\r\n top = top.times(Mat4.translation([0,1.5,0]));\r\n\r\n if (side == \"w\"){\r\n this.shapes.ball.draw(graphics_state, base, this.board.override({color: this.piece_color_white}));\r\n this.shapes.ball.draw(graphics_state, ring, this.board.override({color: this.piece_color_white}));\r\n this.shapes.ball.draw(graphics_state, mid, this.board.override({color: this.piece_color_white}));\r\n this.shapes.ball.draw(graphics_state, top, this.board.override({color: this.piece_color_white}));\r\n } else {\r\n this.shapes.ball.draw(graphics_state, base, this.board.override({color: this.piece_color_black}));\r\n this.shapes.ball.draw(graphics_state, ring, this.board.override({color: this.piece_color_black}));\r\n this.shapes.ball.draw(graphics_state, mid, this.board.override({color: this.piece_color_black}));\r\n this.shapes.ball.draw(graphics_state, top, this.board.override({color: this.piece_color_black}));\r\n }\r\n }",
"function invincibleShipThrustStroke() {\n context.strokeStyle = \"rgb(\" +\n Math.floor(Math.random() * (255 - 200) + 200) + \" ,\" +\n Math.floor(Math.random() * 0) + \" ,\" +\n Math.floor(Math.random() * 0) + \")\";\n}",
"function drawharry() {\n image(harryImage, harryX, harryY);\n}",
"function drawPrey() {\n tint(255, preyHealth);\n image(preyGhost, preyX, preyY, preyRadius * 2, preyRadius * 2);\n tint(255, 255);\n}",
"collide(snitch) {\n let d = dist(this.x, this.y, snitch.x, snitch.y)\n if (d < 30) {\n introspellSFX.play();\n image(this.image, width / 2, height / 2, 1400, 1400);\n snitch.frozen = true;\n }\n }",
"function applyHat(head){\n //creates line skin on box\n if(gameMode!==\"Two Player\"){\n if(hat===\"Eyes\"){\n //places eyes on the head of the snake based on the direction it's going\n if(head){\n if(secondPosition[0]===position[0]-50){\n drawEye(25,-30,10,5,0,0,5,10,5);\n drawEye(25,-30,-10,5,0,0,5,10,5);\n }\n if(secondPosition[0]===position[0]+50){\n drawEye(-25,-30,10,-5,0,0,5,10,5);\n drawEye(-25,-30,-10,-5,0,0,5,10,5);\n }\n if(secondPosition[2]===position[2]-50){\n drawEye(10,-30,25,0,0,5,5,10,5);\n drawEye(-10,-30,25,0,0,5,5,10,5);\n }\n if(secondPosition[2]===position[2]+50){\n drawEye(10,-30,-25,0,0,-5,5,10,5);\n drawEye(-10,-30,-25,0,0,-5,5,10,5);\n }\n if(secondPosition[1]===position[1]-50){\n drawEye(10,30,25,0,5,0,5,5,10);\n drawEye(-10,30,25,0,5,0,5,5,10);\n }\n if(secondPosition[1]===position[1]+50){\n drawEye(10,-30,25,0,-5,0,5,5,10);\n drawEye(-10,-30,25,0,-5,0,5,5,10);\n }\n }\n }else if(hat===\"Top Hat\"){\n //places a top hat on the head based on the direction it is going\n if(head){\n fill(0);\n if(secondPosition[0]===position[0]-50||secondPosition[0]===position[0]+50||secondPosition[2]===position[2]-50||secondPosition[2]===position[2]+50){\n push();\n translate(0,-25,0);\n rotateX(1.4);\n circle(0,0,40,40);\n pop();\n push();\n translate(0,-35,0);\n cylinder(10,20,30,30);\n pop();\n push();\n translate(0,-27.5,0);\n fill(255,0,0);\n cylinder(12,5,30,30,false,false);\n pop();\n }else{\n push();\n translate(0,0,25);\n circle(0,0,40,40);\n pop();\n push();\n translate(0,0,35);\n rotateX(1.4);\n cylinder(10,20,30,30);\n pop();\n push();\n translate(0,0,27.5);\n rotateX(1.4);\n fill(255,0,0);\n cylinder(12,5,30,30,false,false);\n pop();\n }\n }\n }else if(hat===\"Train\"){\n //places smoke stake on the head based on the direction the snake is going\n if(head){\n if(secondPosition[0]===position[0]-50||secondPosition[0]===position[0]+50||secondPosition[2]===position[2]-50||secondPosition[2]===position[2]+50){\n push();\n fill(200);\n translate(0,-30,0);\n cylinder(10,10,30,30);\n pop();\n push();\n fill(0);\n translate(0,-37.5,0);\n cylinder(12,5,30,30);\n translate(0,-7.5,0);\n //sends smoke out of smoke stack\n let mySmoke = new Smoke(position[0],position[1],position[2],false);\n theSmoke.push(mySmoke);\n pop();\n }else{\n push();\n fill(200);\n translate(0,0,30);\n rotateX(1.4);\n cylinder(10,10,30,30);\n pop();\n push();\n fill(0);\n translate(0,0,37.5);\n rotateX(1.4);\n cylinder(12,5,30,30);\n rotateX(-1.4);\n translate(0,0,7.5);\n //sends smoke out of smoke stack\n let mySmoke = new Smoke(position[0],position[1],position[2],true);\n theSmoke.push(mySmoke);\n pop();\n }\n }\n }\n }else{\n box(50);\n }\n}",
"display() {\n push();\n // Predator will only have a bright stroke color (no fill)\n noFill();\n strokeWeight(5);\n stroke(this.strokeColor);\n this.radius = this.health;\n // Once the health/radius reaches zero, remove stroke as well\n // so that is disappears entirely\n if (this.radius === 0) {\n strokeWeight(0);\n // Once the health/radius reaches 0, end the game\n gameOver = true;\n gameStart = false;\n // Resetting the predator\n this.reset();\n }\n ellipse(this.x, this.y, this.radius * 2);\n pop();\n }",
"display() {\n push();\n noStroke();\n this.radius = this.health;\n // Display Black hole\n if (this.radius > 20) {\n imageMode(CENTER);\n image(this.holeImg, this.x, this.y, this.radius * 2, this.radius * 2);\n }\n pop();\n }",
"function drawSilly(){\n C.sprite({n:\"points\",w:50,h:30, x:0,y:0,z:0,html:\"+50\"})\n selectFeatures()\n C.plane({n:\"s_jetstream\",g:\"silly\",w:35,h:65,x:0,y:0,z:-20,b:\"linear-gradient(red, yellow)\",rx:-90,css:\"triangle-bottom\"});\n document.getElementById(\"s_jetstream\").style.visibility = \"hidden\";\n C.sprite({n:\"s_body\",g:\"silly\",w:40,h:50,x:0,y:0,z:20,b:colors[color][0],css:\"circle\"});\n if (eyes > 1) {\n C.plane({n:\"s_eyes\",g:\"silly\",w:30,h:16,y:20,z:32,html:eye_sets[eyes],rx:-70,o:\"bottom\",css:\"glasses\"});\n }\n else\n {\n C.plane({n:\"s_eyes\",g:\"silly\",w:30,h:16,y:20,z:27,html:eye_sets[eyes],rx:-70,o:\"bottom\",css:\"face\"});\n }\n C.plane({n:\"s_mouth\",g:\"silly\",w:30,h:16,y:20,z:10,html:mouths[mouth],rx:-95,o:\"bottom\",css:\"face\"});\n C.cube({n:\"s_firstleg\",g:\"silly\",w:10,h:22,x:20,y:0,z:-10,b:colors[color][0],b1:colors[color][2],b2:colors[color][1]});\n C.cube({n:\"s_secondleg\",g:\"silly\",w:10,h:22,x:-20,y:0,z:-10,b:colors[color][0],b1:colors[color][2],b2:colors[color][1]});\n}",
"function invincibleShipStroke() {\n context.strokeStyle = \"rgb(\" +\n Math.floor(Math.random() *204) + \" ,\" +\n Math.floor(Math.random() * 255) + \" ,\" +\n Math.floor(Math.random() * 229) + \")\";\n}",
"function drawPrey() {\n // For daisy image opacity (use 255 so colours do not change)\n tint(255, preyHealth);\n image(preyDaisyImage, preyX, preyY, 70, 70);\n}",
"function drawPlayer() {\n fill(250,20,50,playerHealth);\n ellipse(playerX,playerY,playerRadius*2,playerRadius*2);\n}",
"function drawPlayer() {\n // For bee image opacity (use 255 so colours do not change)\n tint(255, playerHealth);\n imageMode(CENTER);\n image(playerBeeImage, playerX, playerY, playerWidth, playerHeight);\n}",
"function drawPlayerHealthRing() {\n\n var playerHealthRingLength = playerHealthLostRad + icon_offset_angle;\n var baseHealthRingLength = baseHealthLostRad + icon_offset_angle;\n\n // Prevent the bar wrapping round\n if (playerHealthRingLength > 3.13) {\n playerHealthRingLength = 3.14;\n }\n\n if (baseHealthRingLength > 3.13) {\n baseHealthRingLength = 3.14;\n }\n\n // caluclate the size of health ring to draw based on the health lost\n // get angle from the top (270 degree) position\n var startAngle = ((3 / 2) * Math.PI) + playerHealthRingLength;\n var endAngle = ((3 / 2) * Math.PI) - playerHealthRingLength;\n \n ctx.fillStyle = teamColors.health.player.remaining;\n ctx.strokeStyle = teamColors.health.player.remaining;\n ctx.lineWidth = 10;\n ctx.beginPath();\n ctx.arc(centerX, centerY, Math.floor(padRadius * 0.85), endAngle, startAngle, true);\n ctx.stroke(); \n\n \n startAngle = ((3 / 2) * Math.PI) + baseHealthRingLength;\n endAngle = ((3 / 2) * Math.PI) - baseHealthRingLength;\n ctx.strokeStyle = teamColors.health.base.remaining;\n ctx.fillStyle = teamColors.health.base.remaining;\n ctx.beginPath();\n ctx.arc(centerX, centerY, Math.floor(padRadius * 0.65), endAngle, startAngle, true);\n ctx.stroke();\n \n ctx.drawImage(userImageObj, Math.floor(centerX - userImageWidth / 2), Math.floor((centerY - padRadius * 0.86) - userImageWidth / 2));\n ctx.drawImage(baseImageObj, Math.floor(centerX - baseImageWidth / 2), Math.floor((centerY - padRadius * 0.65) - baseImageWidth / 2));\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function confirms if the use wants to exit the Modal | function AskBeforeExit(modal) {
var question = confirm('Are you sure you want to exit? You might loose the your values!');
if (question == true){
modal.style.display = 'none';
}
return modal.style.display;
} | [
"function onClosePopupYesBtnClick() {\n app.exit();\n }",
"function confirmExit() {\r\n // 'view' and 'status' (which is the instrument status view) do not have editable data, so \r\n // do not prompt user\r\n if (!submitted && !quicklink && componentView != 'view' && componentView != 'status') {\r\n return \"Are you sure you want to leave this page without saving ?\";\r\n }\r\n // if user clicked on a quicklink thereby setting the quicklink flag, need to turn it back\r\n // off so it will not prevent the confirm exit dialog \r\n quicklink = false;\r\n}",
"showExitConfirmation() {\n return true\n }",
"showExitConfirmation() {\n var res = confirm(\"Changes won't be saved! Are you sure you want to close?\") ? undefined : true\n return res\n }",
"function pressCancelMealDialogue() {\n\n\tdisplayMessageToUser(\"\", \"Are you sure you want to exit the meal editor?\" +\n\t\" All changes will be lost.\", \n\t\t\t\t\"okc\", cancelMealDialogue, hideMessageToUser);\n\n\t} //end of if statement",
"function handleModalClose() {\n handlePrevMove(true);\n setPromotionModalOpen(false);\n }",
"function ok() {\n logger.success('Confirm Modal: Close/Ok');\n $modalInstance.close();\n }",
"function onCancelButtonClick() {\n modal.close();\n }",
"_closeOutOfSyncModal() {\r\n this.hideChoiceModal();\r\n }",
"function onExitAlertOkClick() {\n app.exit();\n }",
"function quitFromQuitModal(){\n document.getElementById(\"quit-modal\").style.display = 'none';\n returnToMenu();\n}",
"beforeWindowClose(){\n return new Promise(resolve => {\n // Open modal\n this.appData.openModal({\n type: 'choice',\n message: <>\n Closing this window will stop all the widgets.<br /><br />¿Do you want to exit the app?\n </>,\n confirmLabel: 'Exit',\n cancelLabel: 'Return',\n buttonType: 'destructive',\n onCancel: () => resolve(true),\n onConfirm: () => resolve()\n })\n })\n }",
"function cancel() {\n modalInstance.close();\n }",
"function exitModal() {\n $( '.js-modal-target' ).removeClass(modalEnterClasses);\n $( '.js-modal-target' ).addClass(modalExitClasses);\n\n $( '.js-overlay-target' ).removeClass(overlayEnterClasses);\n $( '.js-overlay-target' ).addClass(overlayExitClasses);\n\n clearButtonState();\n disableButton( '.js-exit-button, .js-execute-button' );\n}",
"function exitToVk(){\n document.location.href='#vk_comments';\n Modal.close();\n}",
"closeConfirmationModal() {\n this.showActionModal = false;\n this.errors = new Errors()\n }",
"function handleCancel() {\n hideModal()\n onCancel()\n }",
"exit() {\n if (this.view) {\n $('#modalShadow').hide();\n this.view.hide();\n this.view = null;\n }\n }",
"function cancel() {\n logger.warning('Confirm Modal: Cancel/Dismiss');\n $modalInstance.dismiss();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
USER DATA Get session user ID. | getUserId() {
return this.getSession().user.userId;
} | [
"function getuserid() {\n return getCookie(\"USER_ID\")\n}",
"getUserID() {\n if(this.loggedIn()) {\n const payload = Token.payload(AppStorage.getToken())\n return payload.sub\n }\n }",
"function getUserID() {\r\n\treturn _spUserId;\r\n}",
"async function getUserId(req) {\n if(req && req.user && req.user.userId) {\n console.log(\"User found in session scope\");\n return { userId: req.user.userId };\n } else {\n console.warn(\"User not found in session scope. Session is expired or user has not logged in\");\n return { error: \"User not logged in\" };\n }\n }",
"function getUserId() {\n return userInfo.id;\n}",
"function storeUserId(data) {\n window.sessionStorage.setItem('userId', data);\n }",
"getUserId() {\n const userData = JSON.parse(localStorage.getItem('data'));\n const userId = userData.id;\n return userId;\n }",
"function getUserID() {\n\t\tlocalStorage.mariotttUser = (localStorage.mariotttUser || \"user-\" + Math.floor(Math.random()*9999));\n\t\treturn localStorage.mariotttUser;\n\t}",
"function getUserId(){\n if(!passport.cookie || !passport.cookie.lenovoId){\n return getCookie(\"leid\");\n }else{\n return passport.cookie.lenovoId;\n }\n }",
"function getUserID() {\n\n var token = getCookie()\n if (token == \"guest\") {\n return 'guest'\n }\n var decodedJWT = jwt_decode(token);\n return decodedJWT.sub\n}",
"function GetUserId() {\r\n var uid = getCookie(\"UserId\");\r\n //console.log(\"UserId '\" + uid + \"'\");\r\n if (uid == \"\") {\r\n // No UID. generate one\r\n uid = uniqueID();\r\n //console.log(\"generated id '\" + uid + \"'\");\r\n setCookie(\"UserId\", uid, 365);\r\n }\r\n return uid;\r\n}",
"function getProfileID(){\n\n\t\treturn Ulo.get(\"profile\").getAttribute(\"data-user-id\");\n\n\t}",
"function getUserID(data){\n\treturn data['user']['id_str'];\n}",
"function getSessionUserId(socket) {\n return (socket.handshake && socket.handshake.session && socket.handshake.session.userId) ?\n socket.handshake.session.userId : 0;\n}",
"function getUserId(){\n var user = JSON.parse(localStorage.getItem('user'));\n return user.id;\n }",
"function auth_getUserID() {\n var handler = \"authhandler\";\n var authMgr = null;\n try {\n authMgr = cocoon.getComponent(Packages.org.apache.cocoon.webapps.authentication.AuthenticationManager.ROLE);\n\n // autentificación\n if (authMgr.checkAuthentication(null, handler, null)) {\n // Usuario autenticado, tomamos el userID\n var userId = authMgr.getState().getHandler().getUserId();\n return parseInt(userId);\n }\n } finally {\n cocoon.releaseComponent(authMgr);\n }\n return null;\n}",
"getUserDataId(context) {\n assert(context.userId);\n return `user:${context.userId}`;\n }",
"static async get_session_user ( session_id ){\n\t\tvar db = await MongoClient.connect(db_url);\n\t\tvar session = await db.collection(\"Sessions\").findOne( {\"session_id\" : session_id} )\n\n\t\tdb.close();\n\t\treturn session.username;\n\t}",
"function extractUserId(event) {\n var userId;\n if (event.context) {\n userId = event.context.System.user.userId;\n } else if (event.session) {\n userId = event.session.user.userId;\n }\n return userId;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The friendly display should use month names instead of numbers and ordinal dates instead of cardinal (1st instead of 1). Do not display information that is redundant or that can be inferred by the user: if the date range ends in less than a year from when it begins, do not display the ending year. Additionally, if the date range begins in the current year (i.e. it is currently the year 2016) and ends within one year, the year should not be displayed at the beginning of the friendly range. If the range ends in the same month that it begins, do not display the ending year or month. Examples: makeFriendlyDates(["20160701", "20160704"]) should return ["July 1st","4th"] makeFriendlyDates(["20160701", "20180704"]) should return ["July 1st, 2016", "July 4th, 2018"]. | function makeFriendlyDates(arr) {
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var start = arr[0].split('-'), startStr = '';
var end = arr[1].split('-'), endStr = '';
var result = [];
function toNum(str) {
return +str;
}
// convert to readable day formant
function dayFormat(day) {
switch (day) {
case 1:
case 21:
return day + 'st';
case 2:
case 22:
return day + 'nd';
case 3:
case 23:
return day + 'rd';
default:
return day + 'th';
}
}
start = start.map(toNum);
end = end.map(toNum);
var startYear = start[0], startMonth = start[1], startDay = start[2];
var endYear = end[0], endMonth = end[1], endDay = end[2];
// ending date equals to starting date
if (arr[0] === arr[1]) {
result.push(months[startMonth - 1] + ' ' + dayFormat(startDay) + ', ' + startYear);
return result;
}
startStr += months[startMonth - 1] + ' ' + dayFormat(startDay);
if (endYear === startYear) {
if (startYear !== 2016) {
startStr += ', ' + startYear;
}
if (endMonth === startMonth ) {
endStr += dayFormat(endDay); // two dates within a month, just output ending day
} else {
endStr += months[endMonth - 1] + ' ' + dayFormat(endDay);
}
} else if (endYear - startYear === 1) {
if (endMonth === startMonth && endDay < startDay || endMonth < startMonth) { // within one year
endStr += months[endMonth - 1] + ' ' + dayFormat(endDay);
if (startYear !== 2016) {
startStr += ', ' + startYear;
}
} else if (endMonth >= startMonth) { // exceed one year
startStr += ', ' + startYear;
endStr += months[endMonth - 1] + ' ' + dayFormat(endDay) + ', ' + endYear;
}
} else if (endYear - startYear > 1) { // exceed one year
startStr += ', ' + startYear;
endStr += months[endMonth - 1] + ' ' + dayFormat(endDay) + ', ' + endYear;
}
result.push(startStr, endStr);
return result;
} | [
"function makeFriendlyDates(arr) {\n \n \n var tracker = [];\n \n var output = [];\n \n \n \n \n var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\n \n \n \n // Months & Day Variables -----------------------------------------------\n var numMonth1 = Number(arr[0].substr(5, 2));\n \n var numMonth2 = Number(arr[1].substr(5, 2));\n \n var numDay1 = Number(arr[0].substr(8, 2));\n \n var numDay2 = Number(arr[1].substr(8, 2));\n //------------------------------------------------------------------------\n\n \n function ordinal(num) { // adds ordinal letters to end of number\n \n if (num == 1 || num == 21 || num == 31) {\n\n return num + \"st\";\n }\n \n else if (num == 2 || num == 22) {\n \n return num + \"nd\";\n }\n \n else if (num == 3 || num == 23) {\n \n return num + \"rd\";\n }\n \n else if (num >= 4 && num <= 20 || num >= 24 && num < 31) {\n \n return num + \"th\";\n }\n\n }\n \n \n // New Months & Day Variables --------------------------------------------\n var month1 = months[numMonth1 - 1];\n \n var month2 = months[numMonth2 - 1];\n \n var day1 = ordinal(numDay1);\n \n var day2 = ordinal(numDay2);\n \n var year1 = Number(arr[0].substr(0, 4));\n \n var year2 = Number(arr[1].substr(0, 4));\n //------------------------------------------------------------------------\n \n //ONE\n \n if ((year2 == year1) || (year2 == year1 + 1) && (numMonth2 < numMonth1 || (numMonth2 == numMonth1 && numDay2 < numDay1))) {\n \n // if date-range ends in less than a year from start, does NOT display ending year.\n \n \n tracker.push(1);\n }\n \n//------------------------------------------------------------------------------- \n \n //TWO\n \n if (year1 == 2016 && (year2 == 2016 || (year2 == 2017 && (numMonth2 < numMonth1 || (numMonth2 == numMonth1 && numDay2 <= numDay1))))) { \n \n // if date range begins in current year (2016) and ends within one year, beginning year is NOT displayed. \n \n tracker.push(2);\n \n \n }\n \n//------------------------------------------------------------------------------\n \n //THREE\n \n if (year2 == year1 && month2 == month1) {\n \n // If range ends in same month it begins, ending year & month NOT displayed.\n \n tracker.push(3);\n }\n \n//------------------------------------------------------------------------------\n \n //FOUR\n \n if (year2 == year1 && (numMonth2 == numMonth1 && numDay2 == numDay1)) {\n \n // If start date & end date are EXACTLY the SAME: output start date\n \n tracker.push(4);\n }\n \n \n \n \n \n // Situational Constructs -------------------------------------------------\n \n var one1 = month1 + \" \" + day1 + \", \" + year1;\n \n var one2 = month2 + \" \" + day2;\n \n // Satisfies requirements of a \"1\" also.\n var two1 = month1 + \" \" + day1;\n \n var two2 = month2 + \" \" + day2;\n \n \n var three1 = month1 + \" \" + day1;\n \n var three2 = day2;\n \n \n var none1 = month1 + \" \" + day1 + \", \" + year1;\n \n var none2 = month2 + \" \" + day2 + \", \" + year2; \n \n \n \n //-------------------------------------------------------------------------\n \n \n var filler = [];\n \n filler.push(none1);\n \n filler.push(none2);\n \n \n // Checking \"tracker\" array -----------------------------------------------\n \n \n var reg4 = /4/g;\n \n var reg3 = /3/g;\n \n var reg2 = /2/g;\n \n var reg1 = /1/g;\n \n \n \n var str = tracker.join(\"\");\n \n \n if (str.match(reg4)) {\n \n output.push(none1);\n \n return output;\n }\n \n \n \n else if (str.match(reg3)) {\n \n output.push(three1);\n \n output.push(three2);\n \n return output;\n }\n \n \n else if (str.match(reg2)) {\n \n output.push(two1);\n \n output.push(two2);\n \n return output;\n }\n \n else if (str.match(reg1)) {\n \n output.push(one1);\n \n output.push(one2);\n \n return output;\n }\n \n \n else {\n \n output.push(none1);\n \n output.push(none2);\n \n return output;\n }\n \n \n //-------------------------------------------------------------------------\n \n \n \n \n //return tracker;\n}",
"function makeFriendlyDates(arr) {\n var monthNames = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n ];\n var currentYear = new Date().getFullYear();\n\n var tmpDateArr, tmpDateObjArr, tmpFormatArr;\n tmpDateObjArr = arr.map(function(date) {\n tmpDateArr = date.split('-');\n var tmpDate = new Date();\n tmpDate.setFullYear(tmpDateArr[0], parseInt(tmpDateArr[1]) - 1, parseInt(tmpDateArr[2]));\n return tmpDate;\n });\n //Parse input arr to formatted date arr.\n tmpFormatArr = arr.map(function(date) {\n tmpDateArr = date.split('-');\n return monthNames[parseInt(tmpDateArr[1]) - 1] + \" \" + convertDay(tmpDateArr[2]) + \", \" + tmpDateArr[0];\n });\n\n if (tmpFormatArr[0] === tmpFormatArr[1]) return tmpFormatArr.slice(1);\n //Time diff less than a year\n if (tmpDateObjArr[1].setFullYear(tmpDateObjArr[1].getFullYear() - 1) - tmpDateObjArr[0].getTime() < 0) {\n tmpFormatArr[1] = tmpFormatArr[1].split(',')[0]; //remove year if less than a year\n\n if (tmpDateObjArr[0].getFullYear() === currentYear) {\n tmpFormatArr[0] = tmpFormatArr[0].split(',')[0]; //remove year if also start from current year\n\n if (tmpDateObjArr[0].getMonth() === tmpDateObjArr[1].getMonth()) {\n tmpFormatArr[1] = tmpFormatArr[1].split(' ')[1]; //remove month if also end in same month\n }\n }\n\n\n\n return tmpFormatArr;\n }\n\n\n return tmpFormatArr;\n\n function convertDay(day) {\n day = parseInt(day);\n if (day == 1) return \"1st\";\n if (day == 2) return \"2nd\";\n if (day == 3) return \"3rd\";\n return day + \"th\";\n }\n}",
"function makeFriendlyDates(arr) {\n // Array to return\n var dateArray = [];\n // Split array into year, month, and day\n var date1 = arr[0].split(\"-\");\n var date2 = arr[1].split(\"-\");\n // Turn Strings into nums for month\n // subtract 1 because the months in the monthNames array are zero indexed (array)\n date1[1] = Number(date1[1]) - 1;\n date2[1] = Number(date2[1]) - 1;\n // day\n date1[2] = Number(date1[2]);\n date2[2] = Number(date2[2]);\n // year\n date1[0] = Number(date1[0]);\n date2[0] = Number(date2[0]);\n // Store name of months\n var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\n\n // check dates if year, month, and day are the same\n if((date1[0] === date2[0]) && (date1[1] === date2[1]) && (date1[2] === date2[2])) {\n // dateArray.push(monthNames[date1[1]] + \" \" + dayChange(date1[2]) + \", \" + date1[0]);\n dateArray.push(monthNames[date1[1]] + ' ' + dayChange(date1[2]) + \", \" + date1[0]);\n return dateArray;\n // check dates for different months, but within the same year\n } else if(date2[1] - date1[1] >= 1 && (date2[0] - date1[0] === 0)) {\n dateArray.push(monthNames[date1[1]] + ' ' + dayChange(date1[2]) + \", \" + date1[0]);\n dateArray.push(monthNames[date2[1]] + ' ' + dayChange(date2[2]));\n return dateArray;\n // same month, same day, different year\n } else if((date1[1] === date2[1]) && (date1[2] === date2[2]) && (date2[0] - date1[0] >= 1)) {\n dateArray.push(monthNames[date1[1]] + ' ' + dayChange(date1[2]) + \", \" + date1[0]);\n dateArray.push(monthNames[date2[1]] + ' ' + dayChange(date2[2]) + \", \" + date2[0]);\n return dateArray;\n // same month, but different years\n } else if((date1[1] === date2[1]) && (date2[0] - date1[0] >= 1)) {\n dateArray.push(monthNames[date1[1]] + ' ' + dayChange(date1[2]) + \", \" + date1[0]);\n dateArray.push(monthNames[date2[1]] + ' ' + dayChange(date2[2]));\n return dateArray;\n // check if the months are the same\n }else if(date1[1] === date2[1]) {\n dateArray.push(monthNames[date1[1]] + ' ' + dayChange(date1[2]));\n dateArray.push(dayChange(date2[2]));\n return dateArray;\n // if the years between the two dates are not the same then include the year in the output\n } else if (date2[0] - date1[0] > 1) {\n dateArray.push(monthNames[date1[1]] + ' ' + dayChange(date1[2]) + \", \" + date1[0]);\n dateArray.push(monthNames[date2[1]] + ' ' + dayChange(date2[2]) + \", \" + date2[0]);\n\n return dateArray;\n // else if the dates include years that are the same then do not include the year in the output\n } else {\n dateArray.push(monthNames[date1[1]] + \" \" + dayChange(date1[2]));\n dateArray.push(monthNames[date2[1]] + \" \" + dayChange(date2[2]));\n return dateArray;\n }\n // reformat the day\n function dayChange(day) {\n if(day === 1) {\n return day + 'st';\n } else if (day === 3) {\n return day + 'rd';\n } else {\n return day + 'th';\n }\n }\n // return storage array\n return dateArray;\n}",
"dateRange() {\n // Setting some defaults to make calls to\n // Date.toLocaleDateString() a bit less verbose\n const year = 'numeric',\n month = 'short',\n day = 'numeric';\n\n let returnStr = \"\";\n\n // If there's only one performance, we only need one date.\n if(this.singlePerformance) {\n returnStr = this.startDate.toLocaleDateString(this.lang, this.dateFormat);\n }\n // Testing to see if the years match. If so, we'll only\n // display the year once, at the end.\n else if(this.startDate.getFullYear() == this.endDate.getFullYear()) {\n returnStr = `${this.startDate.toLocaleDateString(this.lang, {month, day})} – `;\n\n // Testing to see if the months match. If so, we'll only\n // display the month once, at the beginning.\n if(this.startDate.getMonth() == this.endDate.getMonth()) {\n let str = this.endDate.toLocaleDateString(this.lang, {day, year});\n\n const s1 = str.indexOf(\" \");\n\n returnStr += str.slice(0, s1) + \",\" + str.slice(s1);\n }\n // If not, we'll display the date normally.\n else {\n returnStr += this.endDate.toLocaleDateString(this.lang, this.dateFormat);\n }\n }\n // If all else fails, return both dates in full.\n else returnStr = `${this.startDate.toLocaleDateString(this.lang, this.dateFormat)} – ${this.endDate.toLocaleDateString(this.lang, this.dateFormat)}`;\n\n if (this.singlePerformance) {\n const timeHour = (this.startDate.getHours() > 12 ? this.startDate.getHours() - 12 : this.startDate.getHours());\n const timeMinutes = (this.startDate.getMinutes() > 0 ? (\"0\" + this.startDate.getMinutes()).slice(-2) : 0);\n const amPm = (this.startDate.getHours() > 11 ? \"PM\" : \"AM\");\n\n returnStr += `, ${timeHour}${timeMinutes ? `:${timeMinutes}` : \"\"}${amPm}`;\n }\n else {\n returnStr += `, <small>Multiple Performances</small>`;\n }\n\n // Return the result\n return returnStr;\n }",
"function friendlyDate(date){\n\tvar months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\tvar suffix = findSuffix(date[2]);\n\tvar month = months[date[1] - 1];\n\t\n\treturn [month, date[2], suffix, date[0] ];\n}",
"function getDateDisplay(start, end) {\n var dayStart = start.getDate();\n var dayEnd = end.getDate();\n\n var monthStart = start.getMonth();\n var monthEnd = end.getMonth();\n\n var yearStart = start.getFullYear();\n var yearEnd = end.getFullYear();\n\n if (monthStart != monthEnd || yearStart != yearEnd)\n return dayStart + '. <small>' + MONTHS[monthStart] + ' ' + yearStart + '</small> - ' +\n dayEnd + '. <small>' + MONTHS[monthEnd] + ' ' + yearEnd + '</small>';\n\n return dayStart + '. - ' + dayEnd + '. <small>' + MONTHS[monthStart] + ' ' + yearStart + '</small>';\n }",
"normalizeMonth(month, fulldate) {\n switch(fulldate) {\n case 'start': {\n return \"1-\" + month\n .replace(\" \", \"-\");\n }\n\n case 'end': {\n let day;\n let date = month.split(\"-\");\n let year = date[1];\n\n switch(date[0]) {\n case \"4\":\n case \"6\":\n case \"9\":\n case \"11\":\n day = 30;\n break;\n\n case \"2\":\n day = (year % 4 === 0) ? 29 : 28;\n break;\n\n default:\n day = 31;\n break;\n }\n\n return day + \"-\" + date[0] + \"-\" + year;\n }\n\n default:\n return month\n .replace(\"-\", \" \")\n .replace(\"10 \", \"Oct \")\n .replace(\"11 \", \"Nov \")\n .replace(\"12 \", \"Dec \")\n .replace(\"1 \", \"Jan \")\n .replace(\"2 \", \"Feb \")\n .replace(\"3 \", \"Mar \")\n .replace(\"4 \", \"Apr \")\n .replace(\"5 \", \"May \")\n .replace(\"6 \", \"Jun \")\n .replace(\"7 \", \"Jul \")\n .replace(\"8 \", \"Aug \")\n .replace(\"9 \", \"Sep \")\n .replace(\" 20\", \" \");\n }\n }",
"static allowedMonths(intl, birthdate, year) {\n const start = moment(birthdate);\n const end = moment();\n let possibleMonths = [{ value: '0', display: intl.formatMessage({ id: 'Terra.onsetPicker.january' }) },\n { value: '1', display: intl.formatMessage({ id: 'Terra.onsetPicker.february' }) },\n { value: '2', display: intl.formatMessage({ id: 'Terra.onsetPicker.march' }) },\n { value: '3', display: intl.formatMessage({ id: 'Terra.onsetPicker.april' }) },\n { value: '4', display: intl.formatMessage({ id: 'Terra.onsetPicker.may' }) },\n { value: '5', display: intl.formatMessage({ id: 'Terra.onsetPicker.june' }) },\n { value: '6', display: intl.formatMessage({ id: 'Terra.onsetPicker.july' }) },\n { value: '7', display: intl.formatMessage({ id: 'Terra.onsetPicker.august' }) },\n { value: '8', display: intl.formatMessage({ id: 'Terra.onsetPicker.september' }) },\n { value: '9', display: intl.formatMessage({ id: 'Terra.onsetPicker.october' }) },\n { value: '10', display: intl.formatMessage({ id: 'Terra.onsetPicker.november' }) },\n { value: '11', display: intl.formatMessage({ id: 'Terra.onsetPicker.december' }) }];\n if (start.year().toString() === year || start.year() === end.year()) {\n possibleMonths = possibleMonths.filter(month => month.value > start.month());\n }\n\n if (end.year().toString() === year || start.year() === end.year()) {\n possibleMonths = possibleMonths.filter(month => month.value <= end.month());\n }\n return possibleMonths;\n }",
"function rangeToDate(x) {\n\tvar year = 1990 + Math.floor(x/12);\n\tvar month = 1 + (x % 12);\n\tif(month < 10) {\n\t\tmonth = \"0\" + month.toString();\n\t}\n\treturn year.toString() + month.toString();\n}",
"formatRange(start, end) {\n // @ts-ignore\n if (typeof this.numberFormatter.formatRange === \"function\") // @ts-ignore\n return this.numberFormatter.formatRange(start, end);\n if (end < start) throw new RangeError(\"End date must be >= start date\");\n // Very basic fallback for old browsers.\n return `${this.format(start)} – ${this.format(end)}`;\n }",
"function date_range_filter(date_input,strf){\n if (date_input){\n this_month = moment().format(strf) //01\n\n completed_date_moment = new moment(date_input)\n completed_month = completed_date_moment.format(strf)\n\n\n return completed_month === this_month\n }\n}",
"function getDateRange() {\n let startDate = start.value.split(\"-\").map(Number);\n let endDate = end.value.split(\"-\").map(Number);\n let currentDate = start.value;\n let currentMonth = startDate[1]\n let currentDay = startDate[2];\n\n for (let year = startDate[0]; year <= endDate[0]; year++) {\n while (currentMonth <= 12) {\n while (currentDay <= howManyDays(year, currentMonth)) {\n\n let day = year + \"-\" + lessThanTen(currentMonth) + \"-\" + lessThanTen(currentDay);\n //arr.push(year + \"-\" + lessThanTen(currentMonth) + \"-\" + lessThanTen(currentDay));\n\n let p = document.createElement(\"p\");\n p.textContent = day;\n output.appendChild(p);\n\n currentDate = day;\n //currentDate = arr[arr.length - 1];\n if (currentDate === end.value) {\n break;\n }\n\n currentDay++;\n }\n\n if (currentDate === end.value) {\n break;\n }\n currentDay = 1;\n currentMonth++;\n }\n\n if (currentDate === end.value) {\n break;\n }\n currentMonth = 1;\n }\n //console.log(arr);\n //arr = [];\n}",
"formatRange(start, end) {\n // @ts-ignore\n if (typeof this.formatter.formatRange === \"function\") // @ts-ignore\n return this.formatter.formatRange(start, end);\n if (end < start) throw new RangeError(\"End date must be >= start date\");\n // Very basic fallback for old browsers.\n return `${this.formatter.format(start)} – ${this.formatter.format(end)}`;\n }",
"function formatRange(date1,date2,formatStr,separator,isRTL){var localeData;date1=moment_ext_1[\"default\"].parseZone(date1);date2=moment_ext_1[\"default\"].parseZone(date2);localeData=date1.localeData();// Expand localized format strings, like \"LL\" -> \"MMMM D YYYY\".\n// BTW, this is not important for `formatDate` because it is impossible to put custom tokens\n// or non-zero areas in Moment's localized format strings.\nformatStr=localeData.longDateFormat(formatStr)||formatStr;return renderParsedFormat(getParsedFormatString(formatStr),date1,date2,separator||' - ',isRTL);}",
"formatRangeToParts(start, end) {\n // @ts-ignore\n if (typeof this.numberFormatter.formatRangeToParts === \"function\") // @ts-ignore\n return this.numberFormatter.formatRangeToParts(start, end);\n if (end < start) throw new RangeError(\"End date must be >= start date\");\n let startParts = this.numberFormatter.formatToParts(start);\n let endParts = this.numberFormatter.formatToParts(end);\n return [\n ...startParts.map((p)=>({\n ...p,\n source: \"startRange\"\n })),\n {\n type: \"literal\",\n value: \" – \",\n source: \"shared\"\n },\n ...endParts.map((p)=>({\n ...p,\n source: \"endRange\"\n }))\n ];\n }",
"function formatRange(date1,date2,formatStr,separator,isRTL){var localeData;date1=moment_ext_1.default.parseZone(date1);date2=moment_ext_1.default.parseZone(date2);localeData=date1.localeData();// Expand localized format strings, like \"LL\" -> \"MMMM D YYYY\".\n// BTW, this is not important for `formatDate` because it is impossible to put custom tokens\n// or non-zero areas in Moment's localized format strings.\nformatStr=localeData.longDateFormat(formatStr)||formatStr;return renderParsedFormat(getParsedFormatString(formatStr),date1,date2,separator||' - ',isRTL);}",
"colorDates() {\n let firstDay;\n if (this.state.startDate) {\n if (this.inCurrentMonth(this.state.startDate)) {\n firstDay = Number(this.state.startDate.slice(-2));\n }\n\n if (this.state.secondaryStartDate) {\n if (this.inCurrentMonth(this.state.secondaryStartDate)) {\n firstDay = Number(this.state.secondaryStartDate.slice(-2)) - 1;\n }\n }\n let endDay;\n if (this.state.endDate) {\n if (\n this.state.monthNumber === Number(this.getMonth(this.state.endDate))\n ) {\n endDay = Number(this.state.endDate.slice(-2));\n }\n if (\n this.state.monthNumber ===\n Number(this.getMonth(this.state.secondaryEndDate))\n ) {\n endDay = Number(this.state.secondaryEndDate.slice(-2));\n }\n } else {\n endDay = Number(this.state.hoverDate.slice(-2));\n }\n return this.listBetweenTwoNumbers(firstDay + 1, endDay);\n }\n return [];\n }",
"function addYearRangeOptions() {\n var min = minDate.getFullYear();\n var max = maxDate.getFullYear();\n var optionsStart = \"\";\n var optionsEnd = \"\";\n for (year = min; year <= max - 1; year++) {\n optionsStart += \"<option>\"+ year +\"</option>\";\n }\n for (year = min + 1; year <= max; year++) {\n optionsEnd += \"<option>\"+ year +\"</option>\";\n }\n document.getElementById(\"startyearrange\").innerHTML = optionsStart;\n document.getElementById(\"endyearrange\").innerHTML = optionsEnd;\n}",
"function setRenderRangeText() {\n var renderRange = document.getElementById('renderRange');\n var options = cal.getOptions();\n var viewName = cal.getViewName();\n var html = [];\n if (\n viewName === 'month' &&\n (!options.month.visibleWeeksCount || options.month.visibleWeeksCount > 4)\n ) {\n html.push(moment(cal.getDate().getTime()).format('YYYY.MM'));\n } else {\n html.push(moment(cal.getDateRangeStart().getTime()).format('YYYY.MM.DD'));\n html.push(' ~ ');\n html.push(moment(cal.getDateRangeEnd().getTime()).format(' MM.DD'));\n }\n renderRange.innerHTML = html.join('');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders the date of the party. | renderDate() {
return moment.utc(this.props.party.date).format('MM/DD/YYYY [at] h:mm A');
} | [
"function displayDate(date) {\r\n if (showDate === true) {\r\n return (\r\n <Typography color=\"textSecondary\">\r\n Departure Date: {date}\r\n </Typography>\r\n );\r\n }\r\n }",
"function dateRendered() {\r\n \"use strict\";\r\n //define all variables\r\n var todaysDate;\r\n\r\n //get date and make pretty\r\n todaysDate = new Date();\r\n todaysDate = todaysDate.toDateString();\r\n\r\n //display date\r\n document.write(\"Rendered: \" + todaysDate);\r\n}",
"function displayCurrentDate(day, date) {\n $(\"<h3 class=\\\" badge badge-primary m-2 \\\">\" + day + \" - \" + date + \"</h3>\").appendTo('#currentDay');\n\n }",
"displayDate() {\n this._currentDay.text(this._calendar.getFormattedMoment(this._DISPLAY_DATE_FORMAT));\n }",
"function printCoverDate(date) {\n let dfDate = dfCreateAndInit(df4Cover)\n let font4Cover = font4CoverLarge // large size widget\n let spacerHeight = spacerHeight4CoverLarge // large size widget\n\n if (config.runsInWidget) {\n font4Cover = (config.widgetFamily.indexOf(\"small\") >= 0) ? font4CoverSmall : font4CoverLarge\n spacerHeight = (config.widgetFamily.indexOf(\"small\") >= 0) ? spacerHeight4CoverSmall : spacerHeight4CoverLarge\n } \n widget.addSpacer(spacerHeight)\n let stack = widget.addStack()\n let dateLine = stack.addText(dfDate.string(date))\n dateLine.font = font4Cover\n dateLine.textColor = fontColor4Cover\n widget.addSpacer()\n}",
"function myDate() \n\t\t{\n\t\t\tvar d = new Date();\n\t\t\t//The current date is saved to the date string\n\t\t\tdocument.getElementById(\"date\").innerHTML = d.toDateString();\n\t\t}",
"displayDate(date) {\n if (date === undefined) {\n return \"undefined time\"\n } else {\n dateComponents = date.split('-');\n year = dateComponents[0];\n month = dateComponents[1];\n day = dateComponents[2].substring(0, 2);\n time = dateComponents[2].substring(3);\n d = [month, day, year].join(\"/\")\n return d + \" @ \" + time;\n }\n }",
"function showDate(date) {\n\t\tvar months = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n\t\tvar day = date.getDate();\n\t\t//Access months array through getMonth() method\n\t\t//Month returned corresponds to array\n\t\tvar month = months[date.getMonth()];\n\t\tvar year = date.getFullYear();\n\t\tvar fullDate = month + \" \" + day + \", \" + year;\n\t\t$(\"#date-time-container p:last-child\").html(fullDate);\n\t}",
"drawDate(){\n d=this.date ? this.date : new Date();\n\n const FONT_SIZE=20;\n const Y=Bangle.appRect.y;\n var render=false;\n var dateStr = \"\";\n if (this.settings().shwDate>0) { //skip if exactly -none\n const dateSttngs = [\"\",\"l\",\"M\",\"m.Y #W\"];\n for (let c of dateSttngs[this.settings().shwDate]) { //add part as configured\n switch (c){\n case \"l\":{ //locale\n render=true;\n dateStr+=require(\"locale\").date(d,1);\n break;\n } \n case \"m\":{ //month e.g. Jan.\n render=true;\n dateStr+=require(\"locale\").month(d,1);\n break;\n }\n case \"M\":{ //month e.g. January\n render=true;\n dateStr+=require(\"locale\").month(d,0);\n break;\n }\n case \"y\":{ //year e.g. 22\n render=true;\n dateStr+=d.getFullYear().slice(-2);\n break;\n }\n case \"Y\":{ //year e.g. 2022\n render=true;\n dateStr+=d.getFullYear();\n break;\n }\n case \"w\":{ //week e.g. #2\n dateStr+=(this.ISO8601calWeek(d));\n break;\n }\n case \"W\":{ //week e.g. #02\n dateStr+=(\"0\"+this.ISO8601calWeek(d)).slice(-2);\n break;\n }\n default: //append c\n dateStr+=c;\n render=dateStr.length>0; \n break; //noop\n }\n }\n }\n if (render){\n g.setFont(\"Vector\", FONT_SIZE).setColor(g.theme.fg).setFontAlign(0, -1).clearRect(Bangle.appRect.x, Y, Bangle.appRect.x2, Y+FONT_SIZE-3).drawString(dateStr,this.centerX,Y);\n }\n //g.drawRect(Bangle.appRect.x, Y, Bangle.appRect.x2, Y+FONT_SIZE-3); //DEV-Option\n }",
"displayDate(date) {\n if (date === undefined) {\n return \"undefined time\"\n } else {\n dateComponents = date.split('-');\n year = dateComponents[0];\n month = dateComponents[1];\n day = dateComponents[2].substring(0, 2);\n time = dateComponents[2].substring(3);\n d = [month, day, year].join(\"/\")\n return d + \" @ \" + time;\n }\n }",
"render() {\n const formattedDate = getFormattedDate(this.props.date);\n return (\n <div className=\"formatted-date\">\n <h3 className=\"formatted-date-text\">{formattedDate}</h3>\n </div>\n );\n }",
"function printDate()\n\t{\n\t\tvar time = getTime();\n\n\t\t// Print time\n\t\ttaskline.obj.time_date.innerHTML = time.day + '.' + time.monthNameShort + ' ' + time.year;\n\t}",
"function renderCurrentDay() {\n currentday.text(curday);\n }",
"_renderDate() {\n\t\t// Create a span element for every day in the current month.\n\t\tlet dayElements = [];\n\t\tfor(let i=0; i < this.getFirstDayInMonth(); i++){\n\t\t\t// Create empty offset elements if the first day in month is not a Sunday\n\t\t\tdayElements.push('<span> </span>');\n\t\t}\n\t\tlet selected = function(date){\n\t\t\tif(this._date.getFullYear() != this._selected.getFullYear()){\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\tif(this._date.getMonth() != this._selected.getMonth()){\n\t\t\t\treturn '';\n\t\t\t}\n\t\t\t\n\t\t\treturn this._selected.getDate() == date ? 'selected' : '';\n\t\t}.bind(this);\n\t\t\n\t\tfor(let i=1; i <= this.getDaysInMonth(); i++){\n\t\t\tdayElements.push(`<span class=\"${selected(i)} day\">${i}</span>`);\n\t\t}\n\t\t\n\t\treturn `<div>\n\t\t\t\t\t<div class=\"month\">\n\t\t\t\t\t\t<span id=\"previous\" class=\"control\">❮</span><div>\n\t\t\t\t\t\t\t<span id=\"month\">${Calendar.MONTHS[this.getMonth()]}</span>\n\t\t\t\t\t\t\t<span id=\"year\">${this.getYear()}</span>\n\t\t\t\t\t\t</div><span id=\"next\" class=\"control\">❯</span>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"days\">\n\t\t\t\t\t\t<span>Sun</span><span>Mon</span><span>Tue</span><span>Wen</span><span>Thu</span><span>Fri</span><span>Sat</span>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"page\">\n\t\t\t\t\t\t${dayElements.reduce((a,b)=>a+b)}\n\t\t\t\t\t</div>\n\t\t\t\t<div>`;\n\t}",
"getDate(){\n if(this.state.poem.date !== \"None\"){\n return <p><i>{this.state.poem.date}</i></p>\n }else{\n return null\n }\n }",
"function renderStartDate(value, p, record) {\r\n\t\treturn Ext.String\r\n\t\t\t\t.format(\r\n\t\t\t\t\t\t'<a href='+\r\n\t\t\t\t\t\t\t\tcontextPath +\r\n\t\t\t\t\t\t\t\t'/menuSelected.do?leftMenuId=-1&topMenuId=16&targetUrl=/user/viewDataCollectionGroup.do?reqCode=display&sessionId={1}>{0}</a>',\r\n\t\t\t\t\t\tExt.Date.format(value, 'd-m-Y'), record.getId());\r\n\t}",
"function displayDate() {\n currentDay\n}",
"function drawDate(d,x,y) {\n noStroke();\n fill(this.labelColor);\n textAlign(CENTER,BOTTOM);\n textSize(8);\n text('~' + d, x, height - y - DATE_HEIGHT);\n}",
"render() {\n return (\n <div className='invoice-due-date-block'>\n <label className='due-date-label'>{`Due Date`}</label>\n <div>\n {this.renderDueDateField()}\n </div>\n </div>\n );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process requests in provided JSON, the "items" field. | processRequests() {
debug('Processing requests ...');
let buffer = [];
const { item } = this.data;
if (!item || !item.length) {
throw new Error('JSON is missing requests ("item" field)');
}
for (const request of item) {
const array = this.processRequest(request);
buffer = buffer.concat(array);
}
return buffer;
} | [
"processItems() {}",
"_processItems()\n\t{\n\t\tconst response = {\n\t\t\torigin: \"Form._processItems\",\n\t\t\tcontext: \"when processing the form items\",\n\t\t};\n\n\t\ttry\n\t\t{\n\t\t\tif (this._autoLog)\n\t\t\t{\n\t\t\t\t// note: we use the same log message as PsychoPy even though we called this method differently\n\t\t\t\tthis._psychoJS.experimentLogger.exp(\"Importing items...\");\n\t\t\t}\n\n\t\t\t// import the items:\n\t\t\tthis._importItems();\n\n\t\t\t// sanitize the items (check that keys are valid, fill in default values):\n\t\t\tthis._sanitizeItems();\n\n\t\t\t// randomise the items if need be:\n\t\t\tif (this._randomize)\n\t\t\t{\n\t\t\t\tutil.shuffle(this._items);\n\t\t\t}\n\t\t}\n\t\tcatch (error)\n\t\t{\n\t\t\t// throw { ...response, error };\n\t\t\tthrow Object.assign(response, { error });\n\t\t}\n\t}",
"fetchItems(){\n\t\tfetch(Constants.restApiPath+'items')\n\t\t.then(function(res){\n\t\t\tif(res.ok){\n\t\t\t\tres.json().then(function(res){\n\t\t\t\t\tdispatcher.dispatch({\n\t\t\t\t\t\ttype: \t\"FETCH_ITEMS_FROM_API\",\n\t\t\t\t\t\tres,\n\t\t\t\t\t});\n\t\t\t\t})\n\t\t\t}\n\t\t\telse{\n\t\t\t\tconsole.log(Strings.error.restApi);\n\t\t\t\tconsole.log(res);\n\t\t\t}\n\t\t});\n\t}",
"function parse_to_items(json) {\n var jsonobj = $.parseJSON(json);\n for(var i in jsonobj) {\n var itm = new item(jsonobj[i].key, jsonobj[i].value);\n items.push(itm);\n }\n}",
"function parseJson(json) {\n var i = 0;\n for (i = 0; i < json.length; i++) {\n data = {\n getDlvrCalRequest: {\n country: \"USA\", // this can be static\n locationType: \"1\", // this can be static\n productSku: json[i][\"SKU\"].toString(), // this will be the dynamic SKU value that will change for every product\n siteId: \"18F\", // this can be static\n sourceSystem: \"web\", // this can be static\n zipCode: \"11514\", // this can be static\n brandCode: json[i][\"BrandCode (N)\"].toString() // this will be the dynamic brandCode value that will change for every product\n }\n };\n\n makePost(\"\", data, success_f, error_f);\n }\n}",
"function process(item, callback){\n if (item.date != parseInt(item.date,10)){\n var date_obj = new Date(item.date)\n item.date = date_obj.getTime()/1000\n }\n\n items = [item];\n item.links = item.links || []\n if (item.links.length > 0) {\n items = claim(item,callback)\n }\n if (items){\n items.forEach(function(item){\n // check if item is processable, i.e not a dupe\n if (processable(item)) {\n if (hyve.queue_enable){\n enqueue(item)\n }\n try {\n callback(item)\n } catch(e) {\n console.error('process:', e.message, item.service, item.id, item)\n }\n }\n })\n }\n }",
"function processItems(action)\n{\n /**\n * DEFINE RESPONDING EVENT HANDLER FOR AJAX REQUEST\n */\n function eventHandler()\n {\n \n //! Only update the list HTML when updating\n if (action == \"update-list\")\n { document.getElementById(\"results\").innerHTML = xhrResponse; }\n //! Otherwise, processing all items and push xhrResponse'th values sold/hold updated\n //! (therefore call this method again but to update the list only!)\n else \n { \n var soldItems = xhrResponse.split(\",\")[0];\n var soldOutItems = xhrResponse.split(\",\")[1];\n\n pushAlert( \"page-header\", \n \"Processed \"+soldItems+\" items that were sold. <br/>\"+\n soldOutItems+\" items have sold out. Sold out items (if any) were removed from the catalogue. <br/>\",\n \"alert-success\", 5000);\n processItems(\"update-list\"); \n }\n }\n \n //! Send the request\n sendRequest(\"./php/processing.php\", eventHandler, \"action=\"+action); \n}",
"refineForApi (item, callback) {\n\n var responseItem = {};\n\n this._responseFields.forEach((function (responseFiled) {\n responseItem[responseFiled] = item[responseFiled];\n }));\n\n callback(null, responseItem);\n }",
"function loadItems() {\n $.ajax({\n type: \"GET\",\n url: \"items\",\n dataType: \"JSON\",\n data: { '_token' : $('input[name=\"_token\"]').val() },\n success: function(response) {\n for (var i = 0; i < response.length; i++) {\n insertItem(response[i]);\n }\n }\n });\n}",
"function loadItemsFromServer()\n {\n $.ajax({\n dataType: \"json\",\n url: itemFiles[0],\n cache: false,\n success: processItems,\n error: loadingError\n });\n }",
"function processJSONBody(req, res, controller, methodName) {\n let response = new Response(res);\n let body = [];\n req.on('data', chunk => {\n body.push(chunk);\n }).on('end', () => {\n try {\n // we assume that the data is in JSON format\n if (req.headers['content-type'] === \"application/json\") {\n controller[methodName](JSON.parse(body));\n }\n else \n response.unsupported();\n } catch(error){\n console.log(error);\n response.unprocessable();\n }\n });\n}",
"itemHandler(request, response) {\n if (!this.checkAuth(request, response)) {\n return;\n }\n\n if (!/\\/[\\w-]+\\.ics$/.test(request.path)) {\n response.setStatusLine(\"1.1\", 404, \"Not Found\");\n response.setHeader(\"Content-Type\", \"text/plain\");\n response.write(`Item not found at ${request.path}`);\n return;\n }\n\n switch (request.method) {\n case \"GET\":\n this.getItem(request, response);\n return;\n case \"PUT\":\n this.putItem(request, response);\n return;\n case \"DELETE\":\n this.deleteItem(request, response);\n return;\n }\n\n Assert.report(true, undefined, undefined, \"Should not have reached here\");\n response.setStatusLine(\"1.1\", 405, \"Method Not Allowed\");\n response.setHeader(\"Content-Type\", \"text/plain\");\n response.write(`Method not allowed: ${request.method}`);\n }",
"function json_submit(){\n\t\tvar json_input = document.getElementById('json_input');\n\n\t\ttry {\n\t\t\tjson_list = JSON.parse(json_input.value);\n\t\t\tvar item_list = document.getElementById('item_list');\n\t\t\tvar json_error = document.getElementById('json_error');\n\t\t\tjson_error.style.visibility='hidden';\n\t\t\t\n\t\t\twhile(item_list.firstChild){\n\t\t\t\titem_list.removeChild(item_list.firstChild);\n\t\t\t}\n\t\t\titems = [];\n\t\t\tfor(var x = 0; x< json_list.length;x++){\n\t\t\t\tadd_item(json_list[x]);\n\t\t\t}\n\n\t\t}\t\n\t\tcatch (e) {\n\t\t\tvar json_error = document.getElementById('json_error');\n\t\t\tjson_error.style.visibility='visible';\n\t\t}\n\t\tfinally {\n\t\t\tif (items.length === 0){\n\t\t\t\tjson_input.value = \"\";\t\t\n\t\t\t}\n\t\t\telse {\n\t\t\t\tjson_input.value = JSON.stringify(items);\n\t\t\t}\n\t\t}\n\t}",
"function getItems() {\n let call = apiCall(\"/item/get\", 'GET');\n call.send()\n}",
"function auxiliar(json){\n if(json.length==0 || json == null){\n alert(\"No hay productos en ese rango de precios\");\n return;\n }\n for(let producto of json){\n items(producto);\n }\n }",
"function loadItems(){\n $.ajax({\n url: \"/items\",\n method: \"GET\",\n dataType: \"json\",\n success: function(items) {\n renderItems(items);\n }\n })\n}",
"function processRequests() {\n return _.pipeline(\n // flatten the incoming array of streams into a single stream\n _.sequence(),\n // Parse JSON out of each stream\n JSONStream.parse(),\n // Do a special transform for certain payload content\n _.map(specialHello)\n )\n}",
"function fetchItemsSuccess(response) {\n if (response.data.length) {\n response.data.map(function (value) {\n if (value.item.name === 'Ammunition') {\n controller.ammo += value.quantity;\n }\n if (value.item.name === 'Water') {\n controller.water += value.quantity;\n }\n if (value.item.name === 'Food') {\n controller.food += value.quantity;\n }\n if (value.item.name === 'Medication') {\n controller.medic += value.quantity;\n }\n });\n }\n }",
"receiveJson(json) {\n const message = JSON.parse(json);\n if (Array.isArray(message)) {\n message.forEach(this.receiveRequest);\n }\n else if (message.method) {\n this.receiveRequest(message);\n }\n else {\n this.receiveResponse(message);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Router function to set public routes. | function setPrivateRoutes() {
// PUT routes
_app.put('/user-admin', UserAdminCtrl.handleRequest);
} | [
"function setPublicRoutes() {\n}",
"initRoutes() {\n }",
"createRouters() {\n for (let resource in this.resources.public) {\n this.addPublicRouter(this.resources.public[resource]);\n }\n for (let resource in this.resources.private) {\n this.addPrivateRouter(this.resources.private[resource]);\n }\n }",
"routes () {\n\n }",
"setRoutes () {\n ['model', 'collection'].forEach(route => this.setRoute(route));\n }",
"setRouters() {\n const app = this.app;\n\n this.prepareDatabase();\n\n this.setMiddleWare(app);\n\n this.setGetLoginRouter(app);\n this.setPostLoginRouter(app);\n this.setGetLogoutRouter(app);\n }",
"initializeRoutes(){\n if(this.routes.length > 0) return;\n this.routes = [\n {\n method: \"GET\",\n permission: \"STANDARD\",\n endpoint: this.controllerEndpoint + \"/searches\",\n handler: getSearchesHandler\n },\n {\n method: \"GET\",\n permission: \"STANDARD\",\n endpoint: this.controllerEndpoint + \"/loads\",\n handler: getLoadsHandler\n }\n ];\n }",
"initializeRoutes(){\n if(this.routes.length > 0) return;\n this.routes = [\n {\n method: \"GET\",\n permission: \"STANDARD\",\n endpoint: \"/:param\",\n handler: getHandler\n },\n {\n method: \"PUT\",\n permission: \"STANDARD\",\n endpoint: \"/:param\",\n handler: putHandler\n },\n {\n method: \"POST\",\n permission: \"STANDARD\",\n endpoint: \"/:param\",\n handler: postHandler\n },\n {\n method: \"DELETE\",\n permission: \"STANDARD\",\n endpoint: \"/:param\",\n handler: deleteHandler\n }\n ];\n }",
"function setUpRouting() {\n\n // Set up routing table\n app.router.mount(paths.routes);\n app.router.configure({ \n recurse: false\n , strict: false\n , async: true\n });\n\n // Attach HTTP utilities to route context\n app.router.attach(function() {\n var self = this;\n Object.keys(hu).forEach(function(name) {\n self[name] = hu[name];\n });\n });\n}",
"setupRoutes(){\n this.indexController = new IndexController({ layout: this.layout });\n this.indexRouter = new IndexRouter({ controller: this.indexController });\n \n this.channelController = new ChannelController({ layout: this.layout });\n this.channelRouter = new ChannelRouter({ controller: this.channelController });\n }",
"applyRoutes() {\n // Rotas públicas\n this.express.post(\n '/api/authentication/sign_in',\n (request, response, next) => this.signin(request, response, next),\n );\n this.express.post(\n '/api/authentication/sign_up',\n (request, response, next) => this.signup(request, response, next),\n );\n\n // Rotas privadas\n // this.express.get('/api/authentication/sign_off', (request, response, next) => this.authenticate(request, response, next), (request, response, next) => this.signoff(request, response, next));\n }",
"static setupRoutes() {\n // this is a route. the asterisk denotes that the route applies to \n // all incoming path requests.\n //\n // *** IMPORTANT ***\n //\n // it's very *important* the order in which routes are added, since \n // an incoming request will be checked against the available routes in\n // order!\n Server.app.all('*', function(req, res, next) {\n console.log('Requested path: ', req.path); // the reuested URI\n console.log('Query string: ', req.query); // the querystring for GET requests\n\n // our req object tells about the HTTP request.\n // our res object gives us access to control the response.\n // our next object allows us to programmatically goto the next route\n next(); // goto the next routes\n\n // if we didn't call next, we'd never fulfill the request!\n });\n }",
"routes() {\n return internals.routes\n }",
"mountRoutes() {\n this.express = Routes_1.default.mountWeb(this.express);\n this.express = Routes_1.default.mountApi(this.express);\n }",
"inclueRoutes(){\n new Routes(this.app).routeConfig();\n }",
"init() {\r\n if (location.pathname.match(/^\\/[public]/)) {\r\n // let routeName\r\n const s = location.search\r\n if (s) {\r\n const pos = s.match('=').index + 1,\r\n routeName = s.slice(pos)\r\n this.rewrite(routeName)\r\n return this.getRoute(routeName)\r\n }\r\n this.rewrite(routeName)\r\n }\r\n }",
"function publish_routes(router) {\n console.log(\"starting routes ...\");\n _.forOwn(published_routes, (publish, name) => {\n console.log(`\\t . ${name}`);\n publish(router);\n });\n}",
"initStaticRoutes() {\n var routes = [\n /** Application routes **/\n { method: 'GET', path: '/', config: { auth: false }, handler: ApplicationController.getIndexView },\n { method: 'GET', path: '/login', config: { auth: false }, handler: ApplicationController.getIndexView },\n ];\n\n this.server.route(routes);\n }",
"setupRoutes() {\n let expressRouter = express.Router();\n\n for (let route of this.router) {\n let methods;\n let middleware;\n if (typeof route[1] === 'string') {\n methods = route[1].toLowerCase().split(',');\n middleware = route.slice(2);\n } else {\n methods = ['get'];\n middleware = route.slice(1);\n }\n for (let method of methods) {\n expressRouter[method.trim()](route[0], middleware.map(this.errorWrapper));\n }\n }\n this.app.use(this.config.mountPoint, expressRouter);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
stores a custom field for the selected account should one exist | function storeCustomFieldIfExistsThenRedirect() { // TODO: FIX THIS
let acc = JSON.parse(accessAccount());
let shortID = acc.currentAccountID;
let th = accessSignIn();
console.log(th);
th = JSON.parse(th);
let token = th.token;
console.log(token);
let longAccountID = "http%3A%2F%2Faccess.auth.theplatform.com%2Fdata%2FAccount%2F" + shortID;
let urlOneAccount = "https://data.media.theplatform.com/media/data/Media/Field" + "?byFieldName=show" +
"&token=" + token + "&account=" + longAccountID +
"&schema=1.8.0&fields=id%2Ctitle%24allowedValues&form=json";
// this fetches the stuff at the url that will return one account
fetch(urlOneAccount)
.then((response) => response.json())
.then((data) => {
console.log(data);
if (data.entryCount == 0) {
let err = new Error('zero entries in response - There is no custom field for this account');
console.error(err, data);
}
let entries = data.entries;
console.log(entries);
let firstOfEntriesArray = entries[0];
console.log(firstOfEntriesArray);
let idOfDesiredInfo = firstOfEntriesArray.id;
console.log(idOfDesiredInfo);
if (typeof idOfDesiredInfo !== "string" || idOfDesiredInfo == "") {
console.error('wierd', idOfDesiredInfo);
throw new Error("couldn't pull out custom field");
}
// TODO FIX PROMISES
enterCustomFieldID(idOfDesiredInfo);
return true;
})
.then((data) => moveToWarble())
.catch((error) => console.log(error));
let allAccountsWithTitle = "https://data.media.theplatform.com/media/data/Media/Field" + "?byFieldName=show" +
"&token=" + token +
"&schema=1.8.0&fields=id%2Ctitle%24allowedValues&form=json";
} | [
"function defaultPaidField() {\n return \"NO\";\n}",
"addAccount() {}",
"function customFieldEdit(userId, doc) {\n const card = ReactiveCache.getCard(doc.cardId);\n const customFieldValue = ReactiveCache.getActivity({ customFieldId: doc._id }).value;\n Activities.insert({\n userId,\n activityType: 'setCustomField',\n boardId: doc.boardIds[0], // We are creating a customField, it has only one boardId\n customFieldId: doc._id,\n customFieldValue,\n listId: doc.listId,\n swimlaneId: doc.swimlaneId,\n });\n}",
"function ChangeLookUpViewForAccount() {\n var viewId = \"F0EE06D5-BB78-465F-BADA-FC3F5CF05300\";\n var entityName = \"account\";\n var viewDisplayName = \"Gu Custom View\";\n var fetchXml = \"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>\" +\n \"<entity name='account'>\" +\n \"<attribute name='name' />\" +\n \"<attribute name='accountid' />\" +\n \"<filter type='and'>\" +\n \"<condition attribute='emailaddress1' operator='not-null'/>\" +\n \"</filter>\" +\n \"</entity>\" +\n \"</fetch>\";\n\n var layoutXml = \"<grid name='resultset' object='1' jump='accountid' select='1' icon='1' preview='1'>\" +\n \"<row name='result' id='accountid'>\" +\n \"<cell name='name' width='150' />\" +\n \"<cell name='emailaddress1' width='150' />\" +\n \"</row>\" +\n \"</grid>\";\n var isDefault = true;\n\n Xrm.Page.getControl(\"new_lookupfield\").addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, isDefault);\n Xrm.Page.getControl(\"new_lookupfield\").setDefaultView(viewId);\n\n}",
"function register() {\n\t\t\tif (isNormalInteger(vm.userIdField) && vm.typeField !== null) {\n\t\t\t\tif (dbService.checkId(vm.userIdField, function(exists) {\n\t\t\t\t\tif (!exists) {\n\t\t\t\t\t\tvm.userId = vm.userIdField;\n\t\t\t\t\t\tvm.type = vm.typeField;\n\t\t\t\t\t\tcommon.userId = vm.userIdField;\n\t\t\t\t\t\tcommon.type = vm.typeField;\n\n\t\t\t\t\t\tvm.message = '';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvm.message = 'Id already exists';\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t} else {\n\t\t\t\tvm.message = 'Inputs not valid';\n\t\t\t}\n\t\t}",
"setAddAccount() {\n this.acResult_ = 'Add account';\n }",
"function save_form_field(field) {\n\n\tvar obj= {};\n\tobj[field] = document.getElementById(field).value;\n\tif (obj[field].length > 0) {\n\t\tchrome.storage.local.set(obj, function () {console.log(\"saved \" + field + \"/ value = \" + document.getElementById(field).value);});\n\t}\n\n}",
"function onblur_accountNumber_newAccount( accountNumberField, coaCodePropertyName ) {\n //var coaCodeFieldName = findCoaFieldName( accountNumberField.name );\n\tvar accountNumberFieldName = accountNumberField.name;\n\tvar coaCodeFieldName = findElPrefix(accountNumberFieldName) + \".\" + coaCodePropertyName;\n var accountNumber = getElementValue( accountNumberFieldName );\t \n\t//alert(\"coaCodeFieldName = \" + coaCodeFieldName + \", accountNumberFieldName = \" + accountNumberFieldName);\n\n var chartCodePKName = \"document.newMaintainableObject.chartOfAccountsCode\";\n var accountNumberPKName = \"document.newMaintainableObject.accountNumber\";\n var chartCodePK = getElementValue(chartCodePKName);\n var accountNumberPK = getElementValue(accountNumberPKName);\n //alert(\"chartCodePK = \" + chartCodePK + \", accountNumberPK = \" + accountNumberPK);\n\n\tvar dwrReply = {\n\t\tcallback: function (param) {\n\t\t\tif ( typeof param == \"boolean\" && param == false) {\t\n\t\t\t\t// if accountNumber is the same as accountNumberPK, copy chartCodePK to chart code\n\t\t\t\tif (accountNumber == accountNumberPK) {\n\t\t\t\t\t//alert(\"accountNumber == accountNumberPK\");\n\t\t\t\t\tsetRecipientValue(coaCodeFieldName, chartCodePK);\n\t\t\t\t}\n\t\t\t\t// otherwise retrieve chart code from account as usual\n\t\t\t\telse {\n\t\t\t\t\tloadChartCode(accountNumber, coaCodeFieldName);\n\t\t\t\t}\n\t\t\t}\n\t\t},\t\n\t\terrorHandler:function( errorMessage ) { \n\t\t\twindow.status = errorMessage;\n\t\t}\n\t};\n\tAccountService.accountsCanCrossCharts(dwrReply);\t\n}",
"function addAddAccountOption() {\n var option = $('<option/>')\n option.text('')\n option.val('add')\n $('select.ayla-accounts').append(option)\n $(option).prop('selected', true)\n $(option).hide()\n fillAccountForm()\n}",
"didCreateAccount (account) {\n }",
"function set_form_field(field) {\n\n\tchrome.storage.local.get(field, function(items) {\n\t if (items[field]) {\n\t \tdocument.getElementById(field).value = items[field];\n\t }\n\t});\n\t\n\n}",
"function update(account) {\n account.getCustomData(function(err, data) {\n if (err) throw err;\n\n intercom.createUser({\n email: account.email,\n name: account.givenName + ' ' + account.surname,\n custom_data: data,\n }, function(err, res) {\n if (err) {\n console.log(err);\n } else {\n console.log('Finished syncing data for user:', account.email);\n }\n });\n });\n}",
"onAccountClick() {\n const { cms } = this.props;\n const label = this.state.guest ? cms.createAccount : cms.seeMyAccount;\n\n this.pushAnalytics(label);\n }",
"add_account(data) {\n\n\t\tif((data.AccountName!='')&&(data.Category=='yes')){\n\n\t\t\tdata.AccountName=data.AccountName+util.randomnumbergeneration(999);\n\t\t}\n\t\tif((data.AccountNumber!='')||(data.Category='yes')){\n\n\t\t\tdata.AccountNumber=data.AccountNumber+util.randomnumbergeneration(99);\n\t\t}\n\t\tutil.selectDropDown(this.group,data.Group,'Group','Account Info');\n\t\tutil.selectDropDown(this.clientName,data.ClientName,'Client Name','Account Info ');\n\t\tutil.inputValidation(this.accountName,data.AccountName,'Account Name','Account Info');\n\t\tutil.inputValidation(this.accountNumber,data.AccountNumber,'Account Number','Account Info');\n\t\tutil.inputValidation(this.addressLine1,data.AddressLine1,'Address line 1','Account Info ');\n\t\tutil.inputValidation(this.addressLine2,data.AddressLine2,'Address Line 2','Account Info');\n\t\tutil.inputValidation(this.city,data.City,'City','Account Info');\n\t\tutil.inputValidation(this.state,data.State,'State','Account Info');\n\t\tutil.inputValidation(this.zip,data.Zip,'Zip','Account Info');\n\t\tutil.inputValidation(this.phone,data.Phone,'Phone','Account Info');\n\t\tutil.inputValidation(this.phoneContact,data.PhoneContact,'Phone Contact','Account Info');\n\t\tutil.inputValidation(this.fax,data.Fax,'Fax','Account Info');\n\t\tutil.inputValidation(this.faxContact,data.FaxContact,'Fax Contact','Account Info');\n\t\tutil.inputValidation(this.description,data.Description,'Description','Account Info');\n\t\tutil.scrolldown(this.nextBtn1)\n\t\tutil.elementClickable(this.nextBtn1);\n\t\treturn util.resultMessage(data.TestResultType);\n\t}",
"async create(customField) {\n let response = await this.client.post(`${this.baseResource}`, customField)\n return response.data\n }",
"function askForField() {\n const context = this.context;\n this.log.log(chalk.green(`\\nGenerating field #${this.entityConfig.fields.length + 1}\\n`));\n const skipServer = context.skipServer;\n const databaseType = context.databaseType;\n const clientFramework = context.clientFramework;\n const possibleFiltering = databaseType === SQL && !context.reactive;\n const prompts = [\n {\n type: 'confirm',\n name: 'fieldAdd',\n message: 'Do you want to add a field to your entity?',\n default: true,\n },\n {\n when: response => response.fieldAdd === true,\n type: 'input',\n name: 'fieldName',\n validate: input => {\n if (!/^([a-zA-Z0-9_]*)$/.test(input)) {\n return 'Your field name cannot contain special characters';\n }\n if (input === '') {\n return 'Your field name cannot be empty';\n }\n if (input.charAt(0) === input.charAt(0).toUpperCase()) {\n return 'Your field name cannot start with an upper case letter';\n }\n if (input === 'id' || getFieldNameUndercored(this.entityConfig.fields).includes(_.snakeCase(input))) {\n return 'Your field name cannot use an already existing field name';\n }\n if ((clientFramework === undefined || clientFramework === ANGULAR) && isReservedFieldName(input, ANGULAR)) {\n return 'Your field name cannot contain a Java or Angular reserved keyword';\n }\n if ((clientFramework !== undefined || clientFramework === REACT) && isReservedFieldName(input, REACT)) {\n return 'Your field name cannot contain a Java or React reserved keyword';\n }\n // we don't know, if filtering will be used\n if (possibleFiltering && isReservedPaginationWords(input)) {\n return 'Your field name cannot be a value, which is used as a parameter by Spring for pagination';\n }\n return true;\n },\n message: 'What is the name of your field?',\n },\n {\n when: response => response.fieldAdd === true && (skipServer || ['sql', 'mongodb', 'neo4j', 'couchbase'].includes(databaseType)),\n type: 'list',\n name: 'fieldType',\n message: 'What is the type of your field?',\n choices: [\n {\n value: STRING,\n name: 'String',\n },\n {\n value: INTEGER,\n name: 'Integer',\n },\n {\n value: LONG,\n name: 'Long',\n },\n {\n value: FLOAT,\n name: 'Float',\n },\n {\n value: DOUBLE,\n name: 'Double',\n },\n {\n value: BIG_DECIMAL,\n name: 'BigDecimal',\n },\n {\n value: LOCAL_DATE,\n name: 'LocalDate',\n },\n {\n value: INSTANT,\n name: 'Instant',\n },\n {\n value: ZONED_DATE_TIME,\n name: 'ZonedDateTime',\n },\n {\n value: DURATION,\n name: 'Duration',\n },\n {\n value: BOOLEAN,\n name: 'Boolean',\n },\n {\n value: ENUM,\n name: 'Enumeration (Java enum type)',\n },\n {\n value: UUID,\n name: 'UUID',\n },\n {\n value: BYTES,\n name: '[BETA] Blob',\n },\n ],\n default: 0,\n },\n {\n when: response => {\n if (response.fieldType === ENUM) {\n response.fieldIsEnum = true;\n return true;\n }\n response.fieldIsEnum = false;\n return false;\n },\n type: 'input',\n name: 'enumType',\n validate: input => {\n if (input === '') {\n return 'Your class name cannot be empty.';\n }\n if (isReservedTableName(input, 'JAVA')) {\n return 'Your enum name cannot contain a Java reserved keyword';\n }\n if (!/^[A-Za-z0-9_]*$/.test(input)) {\n return 'Your enum name cannot contain special characters (allowed characters: A-Z, a-z, 0-9 and _)';\n }\n if (context.enums && context.enums.includes(input)) {\n context.existingEnum = true;\n } else if (context.enums) {\n context.enums.push(input);\n } else {\n context.enums = [input];\n }\n return true;\n },\n message: 'What is the class name of your enumeration?',\n },\n {\n when: response => response.fieldIsEnum,\n type: 'input',\n name: 'fieldValues',\n validate: input => {\n if (input === '' && context.existingEnum) {\n context.existingEnum = false;\n return true;\n }\n if (input === '') {\n return 'You must specify values for your enumeration';\n }\n // Commas allowed so that user can input a list of values split by commas.\n if (!/^[A-Za-z0-9_,]+$/.test(input)) {\n return 'Enum values cannot contain special characters (allowed characters: A-Z, a-z, 0-9 and _)';\n }\n const enums = input.replace(/\\s/g, '').split(',');\n if (_.uniq(enums).length !== enums.length) {\n return `Enum values cannot contain duplicates (typed values: ${input})`;\n }\n for (let i = 0; i < enums.length; i++) {\n if (/^[0-9].*/.test(enums[i])) {\n return `Enum value \"${enums[i]}\" cannot start with a number`;\n }\n if (enums[i] === '') {\n return 'Enum value cannot be empty (did you accidentally type \",\" twice in a row?)';\n }\n }\n\n return true;\n },\n message: () => {\n if (!context.existingEnum) {\n return 'What are the values of your enumeration (separated by comma, no spaces)?';\n }\n return 'What are the new values of your enumeration (separated by comma, no spaces)?\\nThe new values will replace the old ones.\\nNothing will be done if there are no new values.';\n },\n },\n {\n when: response => response.fieldAdd === true && databaseType === CASSANDRA,\n type: 'list',\n name: 'fieldType',\n message: 'What is the type of your field?',\n choices: [\n {\n value: UUID,\n name: 'UUID',\n },\n {\n value: STRING,\n name: 'String',\n },\n {\n value: INTEGER,\n name: 'Integer',\n },\n {\n value: LONG,\n name: 'Long',\n },\n {\n value: FLOAT,\n name: 'Float',\n },\n {\n value: DOUBLE,\n name: 'Double',\n },\n {\n value: BIG_DECIMAL,\n name: 'BigDecimal',\n },\n {\n value: LOCAL_DATE,\n name: 'LocalDate',\n },\n {\n value: INSTANT,\n name: 'Instant',\n },\n {\n value: ZONED_DATE_TIME,\n name: 'ZonedDateTime',\n },\n {\n value: DURATION,\n name: 'Duration',\n },\n {\n value: ENUM,\n name: 'Enumeration (Java enum type)',\n },\n {\n value: BOOLEAN,\n name: 'Boolean',\n },\n {\n value: BYTE_BUFFER,\n name: '[BETA] blob',\n },\n ],\n default: 0,\n },\n {\n when: response => response.fieldAdd === true && response.fieldType === BYTES,\n type: 'list',\n name: 'fieldTypeBlobContent',\n message: 'What is the content of the Blob field?',\n choices: [\n {\n value: IMAGE,\n name: 'An image',\n },\n {\n value: ANY,\n name: 'A binary file',\n },\n {\n value: TEXT,\n name: 'A CLOB (Text field)',\n },\n ],\n default: 0,\n },\n {\n when: response => response.fieldAdd === true && response.fieldType === BYTE_BUFFER,\n type: 'list',\n name: 'fieldTypeBlobContent',\n message: 'What is the content of the Blob field?',\n choices: [\n {\n value: IMAGE,\n name: 'An image',\n },\n {\n value: ANY,\n name: 'A binary file',\n },\n ],\n default: 0,\n },\n {\n when: response => response.fieldAdd === true && response.fieldType !== BYTE_BUFFER,\n type: 'confirm',\n name: 'fieldValidate',\n message: 'Do you want to add validation rules to your field?',\n default: false,\n },\n {\n when: response => response.fieldAdd === true && response.fieldValidate === true,\n type: 'checkbox',\n name: 'fieldValidateRules',\n message: 'Which validation rules do you want to add?',\n choices: response => {\n // Default rules applicable for fieldType 'LocalDate', 'Instant',\n // 'ZonedDateTime', 'Duration', 'UUID', 'Boolean', 'ByteBuffer' and 'Enum'\n const opts = [\n {\n name: 'Required',\n value: REQUIRED,\n },\n {\n name: 'Unique',\n value: UNIQUE,\n },\n ];\n if (response.fieldType === STRING || response.fieldTypeBlobContent === TEXT) {\n opts.push(\n {\n name: 'Minimum length',\n value: MINLENGTH,\n },\n {\n name: 'Maximum length',\n value: MAXLENGTH,\n },\n {\n name: 'Regular expression pattern',\n value: PATTERN,\n },\n );\n } else if ([INTEGER, LONG, FLOAT, DOUBLE, BIG_DECIMAL].includes(response.fieldType)) {\n opts.push(\n {\n name: 'Minimum',\n value: MIN,\n },\n {\n name: 'Maximum',\n value: MAX,\n },\n );\n }\n return opts;\n },\n default: 0,\n },\n {\n when: response => response.fieldAdd === true && response.fieldValidate === true && response.fieldValidateRules.includes('minlength'),\n type: 'input',\n name: 'fieldValidateRulesMinlength',\n validate: input => (inputIsNumber(input) ? true : 'Minimum length must be a positive number'),\n message: 'What is the minimum length of your field?',\n default: 0,\n },\n {\n when: response => response.fieldAdd === true && response.fieldValidate === true && response.fieldValidateRules.includes('maxlength'),\n type: 'input',\n name: 'fieldValidateRulesMaxlength',\n validate: input => (inputIsNumber(input) ? true : 'Maximum length must be a positive number'),\n message: 'What is the maximum length of your field?',\n default: 20,\n },\n {\n when: response => response.fieldAdd === true && response.fieldValidate === true && response.fieldValidateRules.includes('min'),\n type: 'input',\n name: 'fieldValidateRulesMin',\n message: 'What is the minimum of your field?',\n validate: (input, response) => {\n if ([FLOAT, DOUBLE, BIG_DECIMAL].includes(response.fieldType)) {\n return inputIsSignedDecimalNumber(input) ? true : 'Minimum must be a decimal number';\n }\n return inputIsSignedNumber(input) ? true : 'Minimum must be a number';\n },\n default: 0,\n },\n {\n when: response => response.fieldAdd === true && response.fieldValidate === true && response.fieldValidateRules.includes('max'),\n type: 'input',\n name: 'fieldValidateRulesMax',\n message: 'What is the maximum of your field?',\n validate: (input, response) => {\n if ([FLOAT, DOUBLE, BIG_DECIMAL].includes(response.fieldType)) {\n return inputIsSignedDecimalNumber(input) ? true : 'Maximum must be a decimal number';\n }\n return inputIsSignedNumber(input) ? true : 'Maximum must be a number';\n },\n default: 100,\n },\n {\n when: response =>\n response.fieldAdd === true &&\n response.fieldValidate === true &&\n response.fieldValidateRules.includes(MINBYTES) &&\n response.fieldType === BYTES &&\n response.fieldTypeBlobContent !== TEXT,\n type: 'input',\n name: 'fieldValidateRulesMinbytes',\n message: 'What is the minimum byte size of your field?',\n validate: input => (inputIsNumber(input) ? true : 'Minimum byte size must be a positive number'),\n default: 0,\n },\n {\n when: response =>\n response.fieldAdd === true &&\n response.fieldValidate === true &&\n response.fieldValidateRules.includes(MAXBYTES) &&\n response.fieldType === BYTES &&\n response.fieldTypeBlobContent !== TEXT,\n type: 'input',\n name: 'fieldValidateRulesMaxbytes',\n message: 'What is the maximum byte size of your field?',\n validate: input => (inputIsNumber(input) ? true : 'Maximum byte size must be a positive number'),\n default: 5000000,\n },\n {\n when: response => response.fieldAdd === true && response.fieldValidate === true && response.fieldValidateRules.includes('pattern'),\n type: 'input',\n name: 'fieldValidateRulesPattern',\n message: 'What is the regular expression pattern you want to apply on your field?',\n default: '^[a-zA-Z0-9]*$',\n },\n ];\n return this.prompt(prompts).then(props => {\n if (props.fieldAdd) {\n if (props.fieldIsEnum) {\n props.fieldType = _.upperFirst(props.fieldType);\n props.fieldValues = props.fieldValues.toUpperCase();\n }\n\n const field = {\n fieldName: props.fieldName,\n fieldType: props.enumType || props.fieldType,\n fieldTypeBlobContent: props.fieldTypeBlobContent,\n fieldValues: props.fieldValues,\n fieldValidateRules: props.fieldValidateRules,\n fieldValidateRulesMinlength: props.fieldValidateRulesMinlength,\n fieldValidateRulesMaxlength: props.fieldValidateRulesMaxlength,\n fieldValidateRulesPattern: props.fieldValidateRulesPattern,\n fieldValidateRulesMin: props.fieldValidateRulesMin,\n fieldValidateRulesMax: props.fieldValidateRulesMax,\n fieldValidateRulesMinbytes: props.fieldValidateRulesMinbytes,\n fieldValidateRulesMaxbytes: props.fieldValidateRulesMaxbytes,\n };\n\n this.entityConfig.fields = this.entityConfig.fields.concat(field);\n }\n logFieldsAndRelationships.call(this);\n if (props.fieldAdd) {\n return askForField.call(this);\n }\n return undefined;\n });\n}",
"setAccountInput(elementCss, accountText) {\n commonActions.setValue(elementCss, accountText);\n }",
"function afterSelectValue(fieldName, newValue, oldValue) {\n\tvar formPanel = View.panels.get('abCbDefAccr_form');\n\tvar personCode = formPanel.getFieldValue('cb_accredit_person.person_id');\n\tif (!personCode ||\n\t\t\t(!abCbDefAccrCtrl.abCbDefAccr_alreadyClickedOnEmployee && personCode == oldValue)\n\t\t\t|| (abCbDefAccrCtrl.abCbDefAccr_alreadyClickedOnEmployee && personCode == abCbDefAccrCtrl.abCbDefAccr_oldValueEmployee)) {\n\t\tformPanel.setFieldValue('cb_accredit_person.person_id', newValue);\n\t}\n\tabCbDefAccrCtrl.abCbDefAccr_alreadyClickedOnEmployee = true;\n\tabCbDefAccrCtrl.abCbDefAccr_oldValueEmployee = newValue;\n}",
"function checkAcctAndSave()\n{\n\t//check to see if the ac_id entered is null\n\tvar parsed_ac_id = $('ac_id_part1').value +\n\t\t\t\t$('ac_id_part2').value +\n\t\t\t\t$('ac_id_part3').value +\n\t\t\t\t$('ac_id_part4').value +\n\t\t\t\t$('ac_id_part5').value +\n\t\t\t\t$('ac_id_part6').value +\n\t\t\t\t$('ac_id_part7').value +\n\t\t\t\t$('ac_id_part8').value;\n\tparsed_ac_id.replace(\" \", \"\");\n\n\t//if parsed is null then save form directly\n\tif (parsed_ac_id==\"\") {\n\t\tsaveFormCallback(\"\");\n\t}\n\telse {\n\t\t// check account code through php\n\t\tuc_psAccountCode(\n\t\t\t$('ac_id_part1').value,\n\t\t\t$('ac_id_part2').value,\n\t\t\t$('ac_id_part3').value,\n\t\t\t$('ac_id_part4').value,\n\t\t\t$('ac_id_part5').value,\n\t\t\t$('ac_id_part6').value,\n\t\t\t$('ac_id_part7').value,\n\t\t\t$('ac_id_part8').value,\n\t\t\t'saveFormCallback');\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If evaluated tag is an img, pass to image reformatting process If anything else, insert contents into inline text frame at new column width and 1px height Apply autoSize object style to inline frame to scale height to contents | function parseTags(nodes, size) {
//Locate Object Styles defined in document
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
var figureWidth = String(textFrameWidth * (columnSizes[size] / 100)) + "in"; //width of inline figure calculated based on column width
//targeting figure thumbnails
if (size === SIZES.small) {
//places image into an inline frame (anchored to text and flows with text flow)
//and applies the appropriate object style
node
.placeIntoInlineFrame([figureWidth, textFrameHeight])
.applyObjectStyle(objectStyles.imgFit);
//resize image to proportionally fit into the frame
node.graphics[0].fit(FitOptions.PROPORTIONALLY);
//resize frame to fit to the image.
node.graphics[0].fit(FitOptions.FRAME_TO_CONTENT);
}
//targeting inline figures
else if (size === SIZES.large) {
//places image into an inline frame (anchored to text and flows with text flow)
//and applies the appropriate object style
//note that the image is originally placed in a square frame
node
.placeIntoInlineFrame([figureWidth, figureWidth])
.applyObjectStyle(objectStyles.figureInline);
//resize image to proportionally fit into the square frame
node.graphics[0].fit(FitOptions.PROPORTIONALLY);
//resize frame to fit to the image.
node.graphics[0].fit(FitOptions.FRAME_TO_CONTENT);
//calculate width of this frame
//places the parent of the image into a frame
//this in necessary because this parent frame contains a figcaption, which we want to be anchored to the figure.
//also sets the width of the parent frame to be the same width of the figure.
var bounds = node.graphics[0].visibleBounds;
var figureFrameWidth = String(bounds[3] - bounds[1]) + "in";
node.parent
.placeIntoInlineFrame([figureFrameWidth, textFrameHeight])
.applyObjectStyle(objectStyles.autoSize);
}
}
} | [
"function createImageInfor(img) {\n\t\t\t\tvar html = '';\n\t\t\t\thtml += '<p class=\"stc-imginf\"><span>' + img.width + ' x ' + img.height + '<span></p>';\n\t\t\t\treturn html;\n\t\t\t}",
"function createSummaryAndThumb(pID, isRegular) {\r\n var div = document.getElementById(pID);\r\n var imgtag = \"\";\r\n var img = div.getElementsByTagName(\"img\");\r\n var summ = summary_noimg;\r\n /*if (isRegular && (img.length >= 1)) {\r\n imgtag = '<span style=\"overflow:hidden; border: none; margin:0 15px 10px 0; float:left; max-height:' + img_thumb_height + 'px;width:auto;\"><img src=\"' + img[0].src + '\" width=\"' + img_thumb_width + 'px\" height=\"auto\"/></span>';\r\n summ = summary_img;\r\n }*/\r\n if( img.length >= 1 ) {\r\n if (isRegular) {\r\n //imgtag = '<span style=\"overflow:hidden; border: none; margin:0 15px 10px 0; float:left; max-width:' + img_thumb_width_reg + 'px;height:auto;\"><img src=\"' + img[0].src + '\" height=\"' + img_thumb_height_reg + 'px\" width=\"auto\"/></span>';\r\n //imgtag = '<span style=\"overflow:hidden; border: none; margin:0 15px 10px 0; float:left; max-width:' + img_thumb_width_reg + 'px;height:auto;\"><img src=\"' + img[0].src + '\" width=\"' + img_thumb_width_reg + 'px\" height=\"auto\"/></span>';\r\n imgtag = '<img style=\"float:left; margin: 0 1em 0.5em 0;\" src=\"' + img[0].src + '\" width=\"' + img_thumb_width_reg + 'px\" height=\"auto\"/>';\r\n //imgtag = '<td valign=\"top\" style=\"border: none; padding:0 15px 10px 0;\" width=\"20%\"\" ><img src=\"' + img[0].src + '\"/></td>';\r\n //imgtag = '<span style=\"overflow:hidden; border: none; margin:0 15px 10px 0; float:left; max-height:' + img_thumb_height_reg + 'px;width:auto;\"><img src=\"' + img[0].src + '\" width=\"' + img_thumb_width_reg + 'px\" height=\"auto\"/></span>';\r\n summ = summary_img_reg;\r\n }\r\n else {\r\n //imgtag = '<center><img src=\"' + img[0].src + '\" width= 50%\" height=\"auto\"/></center>';\r\n imgtag = '<img style=\"float:left; margin: 0 1em 0.5em 0;\" src=\"' + img[0].src + '\" width=\"' + img_thumb_width_feat + 'px\" height=\"auto\"/>';\r\n summ = summary_img_feat;\r\n }\r\n }\r\n var resul = compSumAndImg(div.innerHTML, summ, imgtag)\r\n var summary;\r\n //if( isRegular ) summary = '<table><tr>' + imgtag + '<td valign=\"top\"><div class=\"mySumReg\">' + resul.summary + '</div></td></tr></table>';\r\n //if( isRegular ) summary = imgtag + '<div class=\"mySumReg\">' + resul.summary + '</div>';\r\n if( isRegular ) summary = '<div style=\"position: 0;\" class=\"mySumReg\"><div style=\"display: inline-block; margin: 1em 0 1em 0;\">' + imgtag + resul.summary + '</div></div>';\r\n else summary = '<div style=\"position: 0;\" class=\"mySumFeat\"><div style=\"display: inline-block; margin: 1em 0 1em 0;\">' + imgtag + resul.summary + '</div></div>';\r\n div.innerHTML = summary;\r\n}",
"formatImage() {\n\t\tthis.image.style.width = 'auto';\n\t\tthis.image.style.height = '100%';\n\t\t\n\t\tif (this.image.clientWidth <= this.conatiner.clientWidth) {\n\t\t\tthis.image.style.width = '100%';\n\t\t\tthis.image.style.height = 'auto';\n\t\t}\n\t}",
"function bf_SizeContainerToInnerImg(imgElement, add) {\r\n\t/* Erst muss das Bild vollstaendig geladen sein, sonst kann seine Breite nicht bestimmt werden - daher einen Event-Handler an das \r\n\t load-Ereignis binden. */\r\n\timgElement.load(function() {\r\n\t\t// Die Breite des Elternelements dauerhaft an die Breite des Bildes binden.\r\n\t\tbindElementWidth(imgElement.parent(), imgElement, add);\r\n\t});\r\n}",
"function formatHTML() {\n $('.emojionearea-editor')\n .contents()\n .filter(function () {\n return (\n this.nodeType !== 1 ||\n this.tagName === 'IMG'\n );\n })\n .wrap('<div style=\"display: inline-block !important\" />');\n}",
"function decorateImages() {\n document.querySelectorAll('.post-page .post-body picture').forEach(($e) => {\n let hasText = false;\n $e.parentNode.childNodes.forEach(($c) => {\n if ($c.nodeName == '#text') hasText=true;\n })\n if (hasText) $e.parentNode.classList.add('left');\n const $next=$e.parentNode.nextElementSibling;\n if ($next && $next.tagName=='P') {\n const inner=$next.innerHTML.trim();\n let punctCount=0;\n let italicMarker=false;\n let slashMarker=false;\n\n punctCount+=(inner.split('.').length-1);\n punctCount+=(inner.split('?').length-1);\n punctCount+=(inner.split('!').length-1);\n if (inner.startsWith('<em>')) {\n italicMarker=true;\n }\n if (inner.startsWith('/')) {\n slashMarker=true;\n $next.innerHTML=inner.substr(1);\n }\n\n let maxlength=200;\n\n // date cutoff for italic only image captions\n if (new Date(window.blog.date)>=new Date('August 21, 2020')) {\n maxlength=0;\n }\n\n if ((punctCount<=1 && inner.length<maxlength && inner.endsWith('.')) || italicMarker) {\n if (!slashMarker) $next.classList.add('legend');\n }\n }\n })\n}",
"function setSize(img, opt) {\n\n\n opt.width = parseInt(opt.container.width(), 0);\n opt.height = parseInt(opt.container.height(), 0);\n\n opt.bw = opt.width / opt.startwidth;\n opt.bh = opt.height / opt.startheight;\n\n if (opt.bh > 1) {\n opt.bw = 1;\n opt.bh = 1;\n }\n\n\n // IF IMG IS ALREADY PREPARED, WE RESET THE SIZE FIRST HERE\n if (img.data('orgw') != undefined) {\n img.width(img.data('orgw'));\n img.height(img.data('orgh'));\n }\n\n\n var fw = opt.width / img.width();\n var fh = opt.height / img.height();\n\n\n opt.fw = fw;\n opt.fh = fh;\n\n if (img.data('orgw') == undefined) {\n img.data('orgw', img.width());\n img.data('orgh', img.height());\n }\n\n\n\n if (opt.fullWidth == \"on\") {\n\n var cow = opt.container.parent().width();\n var coh = opt.container.parent().height();\n var ffh = coh / img.data('orgh');\n var ffw = cow / img.data('orgw');\n\n\n img.width(img.width() * ffh);\n img.height(coh);\n\n if (img.width() < cow) {\n img.width(cow + 50);\n var ffw = img.width() / img.data('orgw');\n img.height(img.data('orgh') * ffw);\n }\n\n if (img.width() > cow) {\n img.data(\"fxof\", (cow / 2 - img.width() / 2));\n\n img.css({ 'position': 'absolute', 'left': img.data('fxof') + \"px\" });\n }\n\n\n } else {\n\n img.width(opt.width);\n img.height(img.height() * fw);\n\n if (img.height() < opt.height && img.height() != 0 && img.height() != null) {\n\n img.height(opt.height);\n img.width(img.data('orgw') * fh);\n }\n }\n\n\n\n img.data('neww', img.width());\n img.data('newh', img.height());\n if (opt.fullWidth == \"on\") {\n opt.slotw = Math.ceil(img.width() / opt.slots);\n } else {\n opt.slotw = Math.ceil(opt.width / opt.slots);\n }\n opt.sloth = Math.ceil(opt.height / opt.slots);\n\n }",
"function _sizeImage(image) {\n\t\timage = $(image);\n\t\t\n\t\tvar nativeWidth = image[0].naturalWidth;\n\t\tvar nativeHeight = image[0].naturalHeight;\n\t\t\n\t\tif (image.attr(options.prefix+\"columnSpan\")) {\n\t\t\tvar columnSpan = image.attr(options.prefix+\"columnSpan\");\n\t\t\tconsole.log(columnSpan);\n\t\t\tif (/^[0-9]+$/.test(columnSpan) == true) {\n\t\t\t\t//columnSpan property of image was given - size image to span as many columns\n\t\t\t\tvar newWidth, newHeight;\n\t\t\t\tdo {\n\t\t\t\t\tnewWidth = columnSpan*options.columnWidth + (columnSpan-1)*options.columnGap;\n\t\t\t\t\tnewHeight = nativeHeight * (newWidth/nativeWidth);\n\t\t\t\t\t\n\t\t\t\t\tcolumnSpan--;\n\t\t\t\t} while (newWidth > nativeWidth && image.attr(options.prefix+'allowOverscale') != \"true\" && columnSpan > 0)\n\t\t\t\t\n\t\t\t\tif (newWidth > nativeWidth) {\n\t\t\t\t\t//the image is smaller than a single column\n\t\t\t\t\tnewWidth = nativeWidth;\n\t\t\t\t\tnewHeight = nativeHeight;\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\timage.css('width', newWidth+'px');\n\t\t\t\timage.css('height', newHeight+'px');\n\t\t\t} else {\n\t\t\t\tconsole.warn(\"newsify: columnSpan property is not a number for image \"+image.attr('src'));\n\t\t\t}\n\t\t} else {\n\t\t\t//Determine if width and height were explictly set by the user\n\t\t\t//Also, make sure that if width/height were only set as the element attribute, they\n\t\t\t//are copied to the CSS of the image so jQuery's height()/width() return correct values\n\t\t\tif (image.attr('height') == undefined && image[0].style.height.length == 0) {\n\t\t\t\timage.data(\"newsify_explicit_height\", false);\n\t\t\t\timage.css('height', nativeHeight);\n\t\t\t} else {\n\t\t\t\timage.data(\"newsify_explicit_height\", true);\n\t\t\t\tif (image[0].style.height.length == 0) {\n\t\t\t\t\timage.css('height', image.attr('height')+'px');\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (image.attr('width') == undefined && image[0].style.width.length == 0) {\n\t\t\t\timage.data(\"newsify_explicit_width\", false);\n\t\t\t\timage.css('width', nativeWidth);\n\t\t\t} else {\n\t\t\t\timage.data(\"newsify_explicit_width\", true);\n\t\t\t\tif (image[0].style.width.length == 0) {\n\t\t\t\t\timage.css('width', image.attr('width')+'px');\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t//No image is allowed to be higher than a column\n\t\tif (image.height() > options.height) {\n\t\t\tvar newHeight = options.height;\n\t\t\tvar newWidth = nativeWidth * (newHeight/nativeHeight);\n\t\t\t\n\t\t\timage.css('height', newHeight+'px');\n\t\t\tif (image.data(\"newsify_explicit_width\") != true) image.css('width', newWidth+'px');\n\t\t}\n\t}",
"_checkImage(start)\n {\n if (this._isEscaped(start) || start == this.text.length - 1 || this.text[start + 1] != '[')\n {\n return start;\n }\n\n let result = this._testUrl(start + 1);\n if (!result)\n {\n return start;\n }\n\n if (this.currentRun.end < result.end)\n {\n return start;\n }\n\n // Non-standard width/height syntax, since I explicitly don't want\n // to support direct HTML insertion.\n // \n let dimen = /(.*)[[ ]([wh])=(\\d+(?:px|%)?)(?:,h=(\\d+(?:px|%)?))?$/.exec(result.text);\n let width = '';\n let height = '';\n if (dimen !== null)\n {\n if (dimen[4])\n {\n width = dimen[3];\n height = dimen[4];\n }\n else if (dimen[2] == 'w')\n {\n width = dimen[3];\n }\n else\n {\n height = dimen[3];\n }\n\n if (dimen[1])\n {\n result.text = dimen[1];\n }\n else\n {\n result.text = '_'; // For substring(1)\n }\n }\n\n new Image(start, result.end, result.text.substring(1), result.url, width, height, this.currentRun);\n return result.end - 1; // Nothing allowed inside of an image\n }",
"function deployImage() {\n \n // just the fileName, without the full path\n let fileName = event.target.src.split('/').pop()\n \n // current cursor position (string index) in the blog entry box\n let x = blogEntry.selectionStart;\n \n let flt = 'none'\n let w = event.target.width\n alert(w)\n // if pic is less than 70% width of blog text, float it left\n if(w < 500) {\n flt = 'left'\n }\n \n let fig = `<figure style=\"margin:0 1rem 0 0; float:${flt}\"><img src=\"${event.target.src}\" alt=\"${fileName}\" style=\"max-width:100%;\"><figcaption>${event.target.title}</figcaption></figure>`\n \n // insert the image HTML tag in the X spot\n blogEntry.value = blogEntry.value.slice(0, x) + fig + blogEntry.value.slice(x)\n \n}",
"function picture_2across_inline(position, width, border, image_number1, image_number2, image_credit1, image_credit2, image_caption1, image_caption2)\n{\n\nvar picwidth\nvar picborder\nvar pic_string \nvar pic_string2 \nvar caption_position\nvar credit_position\nvar picture_class\nvar credit_class\n\n//alert( \"Starting\" );\n\ncredit_position = \"right\"\n\ncaption_position = \"left\";\nif (position == \"center\") { caption_position = \"left\"; }\nif (position == \"right\") { caption_position = \"right\"; }\n\npicture_class = \"inpicsr\";\nif (position == \"left\") { picture_class = \"inpicsl\"; }\nif (position == \"center\") { picture_class = \"inpicsc\"; }\n\ncredit_class = \"inlineimagecredit\"\nif (position == \"left\") { credit_class = \"inlineimagecredit\"; }\n\nif (width != 0) { picwidth = 'width=\"' + width + '\"'; }\t\nelse { \tpicwidth = \"\"; }\t\n\nif (border == true) { \tpicborder = \"\"; }\nelse { \tpicborder = \"nb\"; }\t\n\npic_string = '<div align=\"center\"><table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"display: inline; vertical-align: top;\"><tr><td align=\"center\" valign=\"top\"><img src=\"../200511gc03.php_files/images/' + rm_issue + '/' + rm_issue + '_' + rm_article_type + '_' + rm_article_number + '_' + image_number1 + '.jpg\" border=\"1\" class=\"' + picture_class + picborder + '\"></td></tr><tr><td class=\"' + credit_class + '\">' + image_credit1 + '</td></tr><tr><td ' + picwidth + '\" class=\"inlineimagecaption\">' + image_caption1 + '</td></tr></table><table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"display: inline; vertical-align: top;\"><tr><td align=\"center\" valign=\"top\"><img src=\"../200511gc03.php_files/images/' + rm_issue + '/' + rm_issue + '_' + rm_article_type + '_' + rm_article_number + '_' + image_number2 + '.jpg\" border=\"1\" class=\"' + picture_class + picborder + '\"></td></tr><tr><td class=\"' + credit_class + '\">' + image_credit2 + '</td></tr><tr><td ' + picwidth + '\" class=\"inlineimagecaption\">' + image_caption2 + '</td></tr></table></div>';\n\n//alert( \"Pic_string:\" + pic_string);\n\ndocument.write(pic_string); \n\nreturn true;\n\n}",
"function setImageContent(title, image, date)\n{\n var content = document.getElementById(\"content\");\n if (content) {\n clearContent();\n\n if (image != null) {\n var imgElement = document.createElement(\"img\");\n imgElement.setAttribute(\"src\", image.src);\n\n var boxStyle = document.defaultView.getComputedStyle(content, '');\n var boxHeight = parseInt(boxStyle.height);\n var boxWidth = parseInt(boxStyle.width);\n var boxAspect = boxHeight / boxWidth;\n var imgAspect = image.height / image.width;\n\n var w = boxWidth;\n var h = boxHeight;\n var x = 0;\n var y = 0;\n\n if (imgAspect > boxAspect) {\n // Tall\n var ratio = boxHeight / image.height;\n w = Math.round(image.width * ratio);\n h = Math.round(image.height * ratio);\n x = Math.floor((boxWidth - w) / 2);\n }\n else if (imgAspect < boxAspect) {\n // Wide\n var ratio = boxWidth / image.width;\n w = Math.round(image.width * ratio);\n h = Math.round(image.height * ratio);\n y = Math.floor((boxHeight - h) / 2);\n }\n\n imgElement.setAttribute(\"width\", w);\n imgElement.setAttribute(\"height\", h);\n\n imgElement.style.width = w + \"px\";\n imgElement.style.height = h + \"px\";\n imgElement.style.marginTop = y + \"px\";\n imgElement.style.marginLeft = x + \"px\";\n\n content.appendChild(imgElement);\n }\n\n setDateText(date);\n }\n}",
"function loadImage() {\n\tvar n = WYSIWYG_Popup.getParam('wysiwyg');\n\tif (!n || !WYSIWYG) return;\n\t// get selection and range\n\tvar sel = WYSIWYG.getSelection(n);\n\tvar range = WYSIWYG.getRange(sel);\n\n\t// the current tag of range\n\tvar img = WYSIWYG.findParent(\"img\", range);\n\n\t// if no image is defined then return\n\tif(img == null) return;\n\n\t// assign the values to the form elements\n\tfor(var i = 0;i < img.attributes.length;i++) {\n\t\tvar attr = img.attributes[i].name.toLowerCase();\n\t\tvar value = img.attributes[i].value;\n\t\tif(attr && value && value != \"null\") {\n\t\t\tswitch(attr) {\n\t\t\t\tcase \"src\":\n\t\t\t\t\t// strip off urls on IE\n\t\t\t\t\tif(WYSIWYG_Core.isMSIE) value = WYSIWYG.stripURLPath(n, value, false);\n\t\t\t\t\tdocument.getElementById('src').value = value;\n\t\t\t\t\t/*---------- imgLib support ------*/\n\t\t\t\t\tselectImage(value);\n\t\t\t\t\t/*------- End imgLib support ------*/\n\t\t\t\tbreak;\n\t\t\t\tcase \"alt\":\n\t\t\t\t\tdocument.getElementById('alt').value = value;\n\t\t\t\tbreak;\n\t\t\t\tcase \"align\":\n\t\t\t\t\tselectItemByValue(document.getElementById('align'), value);\n\t\t\t\tbreak;\n\t\t\t\tcase \"border\":\n\t\t\t\t\tdocument.getElementById('border').value = value;\n\t\t\t\tbreak;\n\t\t\t\tcase \"hspace\":\n\t\t\t\t\tdocument.getElementById('hspace').value = value;\n\t\t\t\tbreak;\n\t\t\t\tcase \"vspace\":\n\t\t\t\t\tdocument.getElementById('vspace').value = value;\n\t\t\t\tbreak;\n\t\t\t\tcase \"width\":\n\t\t\t\t\tdocument.getElementById('width').value = value;\n\t\t\t\tbreak;\n\t\t\t\tcase \"height\":\n\t\t\t\t\tdocument.getElementById('height').value = value;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t// get width and height from style attribute in none IE browsers\n\tif(!WYSIWYG_Core.isMSIE && document.getElementById('width').value == \"\" && document.getElementById('width').value == \"\") {\n\t\tdocument.getElementById('width').value = img.style.width.replace(/px/, \"\");\n\t\tdocument.getElementById('height').value = img.style.height.replace(/px/, \"\");\n\t}\n}",
"function formatImages () {\n\tlet sizedElements = document.querySelectorAll('.article-content img, .article-content table, .article-content td'),\n elementArray = Array.prototype.slice.call(sizedElements);\n elementArray.forEach(function(el) {\n el.removeAttribute('style');\n el.removeAttribute('width');\n el.removeAttribute('height');\n });\n}",
"function img2embed2(code) {\r\n\tif (useXHTML == 1) {\r\n\t\tcode = code.replace(/<\\/embed\\/?>/gi, \"\");\r\n\t}\r\n\r\n\tc1 = /(<img[^>]*?name2=\"([\\s\\S]*?)\"[^>]*?>)/gi;\r\n\r\n\tcode = code.replace(c1,function(s1,s2,s3){\r\n\t\t\tr1 = s2.match(/width\\s*[:|=]\\s*(\\S+)[%|px]?/gi);\r\n\t\t\tr2 = s2.match(/height\\s*[:|=]\\s*(\\S+)[%|px]?/gi);\r\n\t\t\ts3 = unescape(s3);\r\n\r\n\t\t\tif (useXHTML == 1) {\r\n\t\t\t\ts3 = getXHTML(s3);\r\n\t\t\t}\r\n\r\n\t\t\tvar h = r2[0].replace(/:/gi,\"=\");\r\n\t\t\tvar w = r1[0].replace(/:/gi,\"=\");\r\n\t\t\tw = w.replace(/[>|;|\\/\" | ]/gi,\"\");\r\n\t\t\th = h.replace(/[>|;|\\/|\" ]/gi,\"\");\r\n\t\t\th = h.replace(/=/gi,'=\"')+'\"';\r\n\t\t\tw = w.replace(/=/gi,'=\"')+'\"';\r\n\r\n\t\t\ts3 = s3.replace(/(height\\s*=\\s*[\\d\\\"\\']+)/gi,h);\r\n\t\t\ts3 = s3.replace(/(width\\s*=\\s*[\\d\\\"\\']+)/gi,w);\r\n\r\n\t\t\treturn s3;\r\n\r\n\t\t}\r\n\t);\r\n\treturn code;\r\n}",
"updateImageSize(selfObject) {\n var img = new Image();\n img.onload = function () {\n //console.log(this.width, this.height);\n //var imgWidth = selfObject.image.width;\n var imgWidth = this.width;\n //var imgHeight = selfObject.image.height;\n var imgHeight = this.height;\n //console.log(imgHeight, imgWidth);\n var widthRatio = selfObject.widget_body.clientWidth / imgWidth;\n var heightRatio = (selfObject.widget_body.clientHeight - 85) / imgHeight;\n //console.log(widthRatio, heightRatio);\n if (widthRatio < heightRatio) {\n //0.7777777777777778 1.1232876712328768\n selfObject.image.setAttribute('width', selfObject.widget_body.clientWidth);\n selfObject.image.setAttribute('height', imgHeight * widthRatio);\n } else {\n selfObject.image.setAttribute('width', imgWidth * heightRatio);\n selfObject.image.setAttribute('height', (selfObject.widget_body.clientHeight - 85));\n }\n };\n img.src = selfObject.image.src;\n }",
"function add_image_to_cell(params) {\n // get params\n var cell = params.cell;\n var id = params.id; if (!id) {_cell_id_++; id = 'Cell_'+_cell_id_;};\n var clss = params.clss || '';\n var priority = params.priority;\n var image = params.image || console.log('error: please provide image');\n var css = params.css || {};\n\n // position new cell\n var pos = {position: 'relative', display:'block', \n 'margin-left': 'auto', 'margin-right': 'auto'};\n for (var k in css) {\n pos[k] = css[k];\n }\n\n if (priority) {\n // add empty image\n $(cell.id).append(\n '<div style=\"display:table; width:100%; height:100%\"> \\\n <div style=\"display:table-cell;vertical-align:middle\"> \\\n <img class=\"'+clss+'\" id=\"' + id + '\" /> \\\n </div> \\\n </div>'\n );\n\n // queue image with priority\n image_queue.push_image({priority: priority, dest: id, src: image});\n\n } else {\n // add content\n $(cell.id).append(\n '<div style=\"display:table; width:100%; height:100%\"> \\\n <div style=\"display:table-cell;vertical-align:middle\"> \\\n <img class=\"'+clss+'\" id=\"' + id + '\" src=\"'+ image + '\"/> \\\n </div> \\\n </div>'\n );\n };\n\n // set style\n $('#'+id).css(pos);\n\n // return container\n return {id:'#'+id};\n}",
"function graphicBundle() {\n var c = tinyMCE.activeEditor.getContent({format : 'raw'});\n var parser = new DOMParser(),\n doc = parser.parseFromString(c, \"text/html\");\n var arr = Array.prototype.slice.call(doc.querySelectorAll(\"img\"));\n for (var j = 0; j < arr.length; j++) {\n arr[j].className = \"image-border\";\n }\n var arr1 = \"<h1>\" + $('input#title').val() + \"</h1><div class='CDPAlignCenter'>\";\n for(var i = 0; i < arr.length; i++) {\n arr1 += arr[i].outerHTML;\n arr1 += \"<br/><br/>\";\n }\n arr1 += \"</div><pagebreak></pagebreak>\";\n return arr1.replace( / /g, \" \" );\n }",
"function wrapImageWithAlt(thisObj){\n \n // Crea un DIV per inserire la descrizione sotto all'immagine sempre nel wrap\n\n // Incapsula l'immagine con ALT della sezione news in un contenitore\n thisObj.wrap('<div class=\"imageWrapper\" />');\n\n thisObj.parent(\".imageWrapper\").append(\"<div class='imgDesc'></div>\");\n var description = thisObj.parent(\".imageWrapper\").children(\"div.imgDesc\");\n var descriptionText = description.parent(\".imageWrapper\").children(\"img\").attr('alt');\n\n //remove # from alt and add <br> to description (#is <br> marker)\n \tdescriptionTextNoAlt = descriptionText.replace(\"#\", \"\");\n \tdescription.parent(\".imageWrapper\").children(\"img\").attr('alt',descriptionTextNoAlt);\n\n // add br to description\n \tdescriptionText = descriptionText.replace(\"#\", \"<br/>\");\n\n // create description under images\n \tdescription.append(descriptionText);\n\n description.parent(\".imageWrapper\").css('float',description.parent(\".imageWrapper\").children(\"img\").css('float'));\n var wrapperWidth = (description.parent(\".imageWrapper\").children(\"img\").width());\n //alert(wrapperWidth);\n\n description.parent(\".imageWrapper\").css('width',wrapperWidth);\n description.parent(\".imageWrapper\").children('.imgDesc').css('float',description.parent(\".imageWrapper\").children(\"img\").css('float'));\n //description.css('width',description.parent(\".imageWrapper\").children(\"img\").attr('width'));\n description.css('width',wrapperWidth);\n\n //remove alt text\n \tjQuery(this).attr('alt',\"\");\n\n // gestione immagine centrata (centratura descrizione)\n \tvar block_image = thisObj.css('display');\n \tvar floatAttr = thisObj.css('float');\n \tvar centerViaWord = thisObj.parent().css('text-align');\n\n \tif (((block_image ==\"block\") && floatAttr==\"none\") || centerViaWord == \"center\") {\n \t\tdescription.css('margin','0');\n \t\tfloatAttr =\"\";\n \t\tblock_image = \"\";\n \t\tthisObj.parent(\".imageWrapper\").css('margin','auto');\n \t}\n\n // add margin left or right to the wrapper\n switch(floatAttr) {\n \t case \"left\":\n \t description.parent(\".imageWrapper\").css('margin-right',20);\n \t break;\n \t case \"right\":\n \t description.parent(\".imageWrapper\").css('margin-left',20);\n \t break;\n \t}\n \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Receive damage should receive 1 argument and remove received damage from the health | receiveDamage(damage) {
this.health -= damage;
} | [
"applyDamage(damage){\n this.hp -= damage;\n }",
"takeDamage(damage = 1) {\n if (this.health - damage < 0) {\n this.health = 0;\n } else {\n this.health -= damage;\n }\n }",
"applyDamage(damage) {\n if (this.health > 0) {\n this.health = Math.max( this.health - damage, 0 );\n if (this.health === 0) {\n // TODO: Raise 'unit dead' event\n }\n }\n }",
"takeDamage(damage) {\n this.hp -= damage\n return this.hp\n }",
"receiveDamage(damage) {\n this.health -= damage;\n if (this.health > 0) {\n return `A Saxon has received ${damage} points of damage`;\n } else {\n return `A Saxon has died in combat`;\n }\n }",
"takeDamage(damage) {\n if (this.isPlayerAlive()) {\n this.hp -= damage;\n console.log(`${this.name} have ${this.hp} Health Points remaining.`);\n } else {\n this.state = LOSER;\n console.log(`${this.name} is dead :(`);\n }\n }",
"@action receiveAttack(ammo, damage) {\n if (this.currentHitPoints <= 0) {\n return\n }\n\n if (damage === undefined) {\n if (ammo.damage === undefined) {\n throw 'Must pass damage in ammo object or separately.'\n }\n damage = ammo.damage\n }\n\n this.takeHit(ammo.type)\n return this.takeDamage(damage, ammo.type, ammo.armourPiercing)\n }",
"takeDamage(damage, index, user) {\n //Deal damage and check if hp of item\n // is 0 if so, remove from array\n this.array[index].hp -= damage;\n if(this.array[index].hp <= 0){\n this.remove(index);\n user.scoreUpdate(400);\n }\n }",
"recieveDamage(damage) {\n super.recieveDamage(damage);\n game.sound.play('damage');\n this.updateTexture();\n if (this.curHealth <= 0) { this.onDeath(); }\n }",
"function removeHp(target, damage, logType = \"dmg\") {\r\n if (target.bar.hp.now > 0) {\r\n if (target.bar.hp.now >= damage && target.bar.hp.now - damage != 0) {\r\n target.bar.hp.now = target.bar.hp.now - damage\r\n // add dmg to log\r\n fightLog(getLang(logType, [damage]), target, logType);\r\n } else {\r\n target.bar.hp.now = 0;\r\n }\r\n }\r\n if (target.bar.hp.now == 0) {\r\n handleDeath(target, damage);\r\n }\r\n}",
"takeDamage(incomingDamage, ignoreArmorBool = 0) {\n let damageTaken;\n if(ignoreArmorBool) {\n damageTaken = incomingDamage;\n } else {\n damageTaken = Math.max(incomingDamage-this.calculateDR(),1); //Always take 1 damage\n }\n //This is the wound chip damage\n let woundChipDamage = Math.floor(damageTaken/3.5);\n damageTaken -= woundChipDamage; //Vigor damage is CONVERTED to wound chip damage\n let vigorDamageTaken = Math.min(damageTaken, this.vigor); //no negative vigor allowed\n //Make sure all the damage is properly accounted for.\n let woundDamage = (damageTaken-vigorDamageTaken) + woundChipDamage;\n this.vigor -= vigorDamageTaken;\n this.wounds -= woundDamage;\n let damageMessage = `${this.name} lost ${vigorDamageTaken} vigor`;\n if(woundDamage > 1) {\n damageMessage += ` and took ${woundDamage} wounds!`;\n } else if (woundDamage === 1) {\n damageMessage += ` and took ${woundDamage} wound!`;\n } else {\n damageMessage += \"!\";\n }\n addToCombatLog(damageMessage);\n this.currentBattlefield.updateHealthValues();\n //If dead, clear threat and let the player know\n if( this.wounds <= 0) {\n addToCombatLog(`${this.name} has perished.`);\n $(`#${this.battlefieldId}Block`).css(\"backgroundColor\", \"#4f2b2b\");\n this.aliveBool = false;\n this.clearAllThreat();\n }\n }",
"function onDamage(entity, from, amount) {}",
"function hurt() {\n //drop health by 1 per call\n health -= 1;\n}",
"function ApplyDamage(damage : float) {\n\t//if the player is invincible, do not apply damage\n\tif(this.invincible) {\n\t\treturn;\n\t}\n\t\t\n}",
"survivorDamage(dmg) {\n console.log(\"Survivor taking damage = \" + dmg);\n //Deduct health.\n this.currPlayerHealth -= dmg;\n\n }",
"function decreaseHealth(enemyCounterAttack) {\n this.health -= enemyCounterAttack;\n}",
"function removeHealth(){\n this.health = this.health - 1;\n}",
"TakeDamage(dmg){\n\t\t\tif (this.shield) {\n\t\t\t\tvar dmgRemainder = dmg + this.shield;\n\t\t\t\tthis.shield += dmg;\n\t\t\t\tdmg = dmgRemainder;\n\t\t\t}\n\t\t\tvar HBWidthPrev = this.HBWidth;\n\t\t\tlet pixelsLost = Math.round((dmg/this.healthremaining) * this.HBWidth);\n\t\t\tthis.healthremaining += dmg;\n\t\t\tif (this.healthremaining <= 0) {\n\t\t\t\treturn this.Die();\n\t\t\t}\n\t\t\tthis.percenthealthremaining = HF.roundToDecimal(this.healthremaining/this.health, 2);\n\t\t\tthis.HBWidth += pixelsLost;\n\t\t\tthis.healthbar.clearRect(this.HBWidth,0 ,HBWidthPrev, 36);\n\t\t}",
"damage(playerId, cardId, amount) {\n let card = findCardInField(playerId, cardId);\n card.health -= amount;\n if (card.health <= 0) {\n this.fieldPop(playerId, cardId);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the player could use badly romantic arrow in theory | function couldUseBadlyRomanticArrow() {
return have() && haveBadlyRomanticArrowUsesRemaining();
} | [
"isArrowKey( keyCode ) {\n return ( keyCode === KeyboardUtils.KEY_RIGHT_ARROW || keyCode === KeyboardUtils.KEY_LEFT_ARROW ||\n keyCode === KeyboardUtils.KEY_UP_ARROW || keyCode === KeyboardUtils.KEY_DOWN_ARROW );\n }",
"function getBadlyRomanticArrowUses() {\n return Math.max(0, (0, _property.get)(\"_badlyRomanticArrows\"));\n}",
"function getBadlyRomanticArrowUses() {\n return Math.max(0, property_1.get(\"_badlyRomanticArrows\"));\n}",
"function checkRelaxingDirection() {\n if (lastMove == \"right\") {\n let currentImages = characterImages.idle[1];\n relax(currentImages);\n }\n else {\n let currentImages = characterImages.idle[0];\n relax(currentImages);\n }\n}",
"currentPlayerIsWiner() {return false;}",
"function checkLoseCondition() {\n wrongMoveCount++;\n if (wrongMoveCount === 3) {\n $('#loser').show('fade');\n clearGame();\n return true;\n }\n }",
"updateArrow(){\n\t\tif(Phaser.Point.distance(this.player.position, this.brain.position) < 500){\t\t \n\t\t\tthis.arrow.alpha = 0;\t\t\t\n\t\t} else {\n\t\t\tthis.arrow.alpha = 0.6;\n\t\t\tthis.arrow.position = this.player.position;\n\t\t\tthis.arrow.rotation = this.game.physics.arcade.angleBetween(this.arrow, this.brain);\t\n\t\t}\t\n\t}",
"function checkFlagpole() {\n\tif (dist(gameChar_world_x, gameChar_y, flagpole.x_pos, floorPos_y) < 75) {\n\t\tflagpole.isReached = true;\n\t}\n}",
"function canRoverMoveBack() {\n if (rover.direction === \"N\" || rover.direction === \"S\") {\n canRoverMoveBackInY();\n } else {\n canRoverMoveBackInX();\n }\n}",
"function refuseIfAITurn() {\n if (playArea.hasClass('interaction-disabled')) {\n console.assert(currentPlayer === 2 && gameMode === 'ai', 'Interaction blocked unexpectedly');\n showError('Wait for your turn');\n return true;\n }\n}",
"function checkAllArrows() {\r\n //return;\r\n\tvar x;\r\n\t//clearArrows();\r\n\tfor(x = gamePieces.length-1; x >= 0 ; x-- )\r\n\t{\r\n\t\tgamePieces[x].removeArrows();\r\n\t\tgamePieces[x].drawArrows();\r\n\t}\r\n}",
"function _hasPolyonError(){\n var det1 = _getDeterminant(this.topLeft, this.topRight, this.bottomRight);\n var det2 = _getDeterminant(this.bottomRight, this.bottomLeft, this.topLeft);\n if(this.useBackFacing){\n if(det1*det2<=0) return true;\n }else{\n if(det1<=0||det2<=0) return true;\n }\n var det1 = _getDeterminant(this.topRight, this.bottomRight, this.bottomLeft);\n var det2 = _getDeterminant(this.bottomLeft, this.topLeft, this.topRight);\n if(this.useBackFacing){\n if(det1*det2<=0) return true;\n }else{\n if(det1<=0||det2<=0) return true;\n }\n return false;\n }",
"function isRock(position) {\n if(lightCell(position) == \"^\") {\n return true;\n }\n return false;\n}",
"checkPossibilities () {\n this.undoPossible = (this.pointer > 0)\n this.redoPossible = (this.pointer < this.history.length - 1)\n }",
"function valid_arrow_key(key){\n\t\treturn _o.list.matchingItems.length > 1 && ['ArrowLeft', 'ArrowRight'].includes(key) && (!document.activeElement || !['AUDIO', 'VIDEO', 'TEXTAREA'].includes(document.activeElement.nodeName));\n\t}",
"function wrongMove() {\n playSound('#wrong');\n switchPlayerTurn();\n if (!checkLoseCondition()) {\n wrongMoveAlert();\n }\n }",
"function wellFlankedByExcitedNotNextExcitedConfluent() {\n return (\n (((right == C10) || (right == C11)) && (dir != dirRight)) ||\n (((up == C10) || (up == C11)) && (dir != dirUp )) ||\n (((left == C10) || (left == C11)) && (dir != dirLeft )) ||\n (((down == C10) || (down == C11)) && (dir != dirDown )));\n }",
"function checkLevelActiveUserKeyboard() {\n\t// Affect ship speed/angle\n\tif (keyIsDown(LEFT_ARROW)) {\n\t\tship.turn(-1);\n\t}\n\tif (keyIsDown(RIGHT_ARROW)) {\n\t\tship.turn(1);\n\t}\n\tif (keyIsDown(UP_ARROW)) {\n\t\tship.accelerate();\n\t}\n}",
"canPlaceTrap() {\n if (this.hasTrap && this.iqla && this.key.place_trap.isDown) {\n this.scene.sceneData.serverConnection.trapPlace();\n this.playerTrap();\n this.hasTrap = false;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We want to disable legend for small screen sizes | function onPieResize(pie, sizes) {
if(sizes.width < 300) {
pie.options.legend.display = false;
}
else {
pie.options.legend.display = true;
}
} | [
"function minimize() {\r\n\r\n\t\tlegendContent.selectAll('*').style(\"visibility\", \"hidden\");\r\n\t\tplusSignVLine.style(\"visibility\", \"visible\");\r\n\t\tlegendsOn = false;\r\n\t}",
"function showMiniLegend()\n{\n\tvar l_hide = SVGDocument.getElementById(\"legendpanel_detail\");\n\tif (l_hide)\n\t{\n\t \tl_hide.setAttributeNS(null, 'visibility', 'hidden');\n\t}\n\tvar l_show = SVGDocument.getElementById(\"legendpanel_mini\");\n\tif (l_show)\n\t{\n\t \tl_show.setAttributeNS(null, 'visibility', 'visible');\n\t}\n}",
"function preRenderCallback(preRenderConfig) {\r\n\t\tpreRenderConfig.moonbeamInstance.legend.visible = false;\r\n\t}",
"_drawLegend() {\n if (this.displayOptions.legend.position !== scada.chart.AreaPosition.NONE) {\n const layout = this._chartLayout;\n const legend = this.displayOptions.legend;\n\n let trendCnt = this.chartData.trends.length;\n let lineCnt = Math.ceil(trendCnt / legend.columnCount);\n let useStatusColor = this._getUseStatusColor();\n\n let columnMarginTop = scada.chart.DisplayOptions.getMargin(legend.columnMargin, 0);\n let columnMarginRight = scada.chart.DisplayOptions.getMargin(legend.columnMargin, 1);\n let columnMarginLeft = scada.chart.DisplayOptions.getMargin(legend.columnMargin, 3);\n\n let fullColumnWidth = legend.columnWidth + columnMarginLeft + columnMarginRight;\n let lineXOffset = layout.legendAreaRect.left + layout.canvasXOffset + columnMarginLeft;\n let lineYOffset = layout.legendAreaRect.top + layout.canvasYOffset + columnMarginTop;\n\n this._context.textAlign = \"left\";\n this._context.textBaseline = \"middle\";\n this._context.font = legend.fontSize + \"px \" + this.displayOptions.chartArea.fontName;\n\n for (let trendInd = 0; trendInd < trendCnt; trendInd++) {\n let trend = this.chartData.trends[trendInd];\n let columnIndex = Math.trunc(trendInd / lineCnt);\n let lineIndex = trendInd % lineCnt;\n let lineX = fullColumnWidth * columnIndex + lineXOffset;\n let lineY = legend.lineHeight * lineIndex + lineYOffset;\n let iconX = lineX + 0.5;\n let iconY = lineY + (legend.lineHeight - legend.iconHeight) / 2 - 0.5;\n let lblX = lineX + legend.iconWidth + legend.fontSize / 2;\n let lblY = lineY + legend.lineHeight / 2;\n\n if (!useStatusColor) {\n this._setColor(trend.color);\n this._context.fillRect(iconX, iconY, legend.iconWidth, legend.iconHeight);\n this._setColor(legend.foreColor);\n this._context.strokeRect(iconX, iconY, legend.iconWidth, legend.iconHeight);\n }\n\n this._context.fillText(trend.caption, lblX, lblY);\n }\n }\n }",
"function createMapLegend() {\n\n}",
"function showLegend(overlay) {\n $(\"#legend_img\").attr(\"src\",overlay.legendPath);\n if (showLegendSetting && !isMobile) $(\"#legend\").show();\n}",
"function setLegends() {\n legends = $(\"#placeholder .legendLabel\");\n legends.each(function () {\n // fix the widths so they don't jump around\n $(this).css('width', $(this).width);\n });\n }",
"function legendFilter() {\n\n}",
"function disableScaleFactor() {\n $('input[name=\"mapfit-scale\"]').addClass('disabled');\n $('input[name=\"mapfit-scale\"]').attr('disabled', 'disabled');\n }",
"function showDetailedLegend()\n{\n\tvar l_hide = SVGDocument.getElementById(\"legendpanel_mini\");\n\tif (l_hide)\n\t{\n\t \tl_hide.setAttributeNS(null, 'visibility', 'hidden');\n\t}\n\tvar l_show = SVGDocument.getElementById(\"legendpanel_detail\");\n\tif (l_show)\n\t{\n\t \tl_show.setAttributeNS(null, 'visibility', 'visible');\n\t}\n}",
"function chartPropertiesCustomization(chart) {\n\t\tif ($(window).outerWidth() >= 1920) {\t\t\t\n\t\t\t\n\t\t\tchart.options.legend.fontSize = 14;\n\t\t\tchart.options.legend.horizontalAlign = \"left\";\n\t\t\tchart.options.legend.verticalAlign = \"center\";\n\t\t\tchart.options.legend.maxWidth = null;\n\t\t\t\n\t\t}else if (1920 >= $(window).outerWidth() && $(window).outerWidth() >= 1200) {\n\t\t\t\n\t\t\tchart.options.legend.fontSize = 14;\n\t\t\tchart.options.legend.horizontalAlign = \"left\";\n\t\t\tchart.options.legend.verticalAlign = \"center\";\n\t\t\tchart.options.legend.maxWidth = 140;\n\t\t\t\n\t\t} else if ( 1200 >= $(window).outerWidth() && $(window).outerWidth() >= 992) {\n\t\t\t\n\t\t\tchart.options.legend.fontSize = 12;\n\t\t\tchart.options.legend.horizontalAlign = \"center\";\n\t\t\tchart.options.legend.verticalAlign = \"top\";\n\t\t\tchart.options.legend.maxWidth = null;\n\t\t\t\n\t\t} else if ( 992 >= $(window).outerWidth()) {\n\t\t\t\n\t\t\tchart.options.legend.fontSize = 14;\n\t\t\tchart.options.legend.horizontalAlign = \"center\";\n\t\t\tchart.options.legend.verticalAlign = \"bottom\";\n\t\t\tchart.options.legend.maxWidth = null;\n\t\t\t\n\t\t}\n\t\t\n\t\tchart.render();\n\t}",
"function hideLegend() {\n document.getElementById(\"legend\").style.width = '1';\n document.getElementById(\"legend\").style.display = 'none';\n document.getElementById(\"showLegend\").style.display = 'block';\n}",
"function chartPropertiesCustomization(chart) {\r\n\t\tif ($(window).outerWidth() >= 1920) {\t\t\t\r\n\t\t\t\r\n\t\t\tchart.options.legend.fontSize = 14;\r\n\t\t\tchart.options.legend.horizontalAlign = \"left\";\r\n\t\t\tchart.options.legend.verticalAlign = \"center\";\r\n\t\t\tchart.options.legend.maxWidth = null;\r\n\t\t\t\r\n\t\t}else if ($(window).outerWidth() < 1920 && $(window).outerWidth() >= 1200) {\r\n\t\t\t\r\n\t\t\tchart.options.legend.fontSize = 14;\r\n\t\t\tchart.options.legend.horizontalAlign = \"left\";\r\n\t\t\tchart.options.legend.verticalAlign = \"center\";\r\n\t\t\tchart.options.legend.maxWidth = 140;\r\n\t\t\t\r\n\t\t} else if ($(window).outerWidth() < 1200 && $(window).outerWidth() >= 992) {\r\n\t\t\t\r\n\t\t\tchart.options.legend.fontSize = 12;\r\n\t\t\tchart.options.legend.horizontalAlign = \"center\";\r\n\t\t\tchart.options.legend.verticalAlign = \"top\";\r\n\t\t\tchart.options.legend.maxWidth = null;\r\n\t\t\t\r\n\t\t} else if ($(window).outerWidth() < 992) {\r\n\t\t\t\r\n\t\t\tchart.options.legend.fontSize = 14;\r\n\t\t\tchart.options.legend.horizontalAlign = \"center\";\r\n\t\t\tchart.options.legend.verticalAlign = \"bottom\";\r\n\t\t\tchart.options.legend.maxWidth = null;\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\tchart.render();\r\n\t}",
"function deselect_type_in_legend(){\n //set legend back to normal\n var legendRects = document.querySelectorAll(\".legendRect\");\n var legendLabels = document.querySelectorAll(\".legendLabel\");\n\n if(legendClicked == \"0\"){\n legendRects.forEach(function(e){\n e.style.opacity = 1.0;\n e.style.stroke = \"white\";\n e.style.strokeWidth = 0.0;\n });\n\n legendLabels.forEach(function(e){\n e.style.opacity = 1.0;\n });\n }else{\n legendRects.forEach(function(e){\n e.style.opacity = 0.3;\n });\n var rect = document.querySelector(\"#idrect\"+legendClicked);\n rect.style.opacity = 1.0;\n rect.style.stroke = chart_color(legendClicked);\n rect.style.strokeWidth = 3.0;\n \n legendLabels.forEach(function(e){\n e.style.opacity = 0.3;\n });\n\n var label = document.querySelector(\"#idlabel\"+legendClicked);\n label.style.opacity = 1.0;\n }\n}",
"function legendClickHandler(d, i) {\n\tsn.runtime.excludeSources.toggle(d.source);\n\tregenerateChart(sn.runtime.powerIOAreaChart);\n}",
"function remLegendImg(tmpName) {\n d3.select(\"#\" + tmpName + \"Legend\").remove();\n\n if(d3.select(\"#legendImgDiv\").selectAll(\"div\")._groups[0].length == 0) {\n d3.select(\"#legendImgDiv\").style(\"display\", \"none\");\n d3.select(\"#legendDefault\").style(\"display\", \"block\");\n }\n }",
"function legendClickHandler(d, i) {\n\tsn.runtime.excludeSources.toggle(d.source);\n\tregenerateChart();\n}",
"function chartPropertiesCustomization(chart) {\n\t\tif ($(window).outerWidth() >= 1920) {\n\n\t\t\tchart.options.legend.fontSize = 14;\n\t\t\tchart.options.legend.horizontalAlign = \"left\";\n\t\t\tchart.options.legend.verticalAlign = \"center\";\n\t\t\tchart.options.legend.maxWidth = null;\n\n\t\t}else if ($(window).outerWidth() < 1920 && $(window).outerWidth() >= 1200) {\n\n\t\t\tchart.options.legend.fontSize = 14;\n\t\t\tchart.options.legend.horizontalAlign = \"left\";\n\t\t\tchart.options.legend.verticalAlign = \"center\";\n\t\t\tchart.options.legend.maxWidth = 140;\n\n\t\t} else if ($(window).outerWidth() < 1200 && $(window).outerWidth() >= 992) {\n\n\t\t\tchart.options.legend.fontSize = 12;\n\t\t\tchart.options.legend.horizontalAlign = \"center\";\n\t\t\tchart.options.legend.verticalAlign = \"top\";\n\t\t\tchart.options.legend.maxWidth = null;\n\n\t\t} else if ($(window).outerWidth() < 992) {\n\n\t\t\tchart.options.legend.fontSize = 14;\n\t\t\tchart.options.legend.horizontalAlign = \"center\";\n\t\t\tchart.options.legend.verticalAlign = \"bottom\";\n\t\t\tchart.options.legend.maxWidth = null;\n\n\t\t}\n\n\t\tchart.render();\n\t}",
"function maximize() {\r\n\t\tlegendContent.selectAll('*').style(\"visibility\", \"visible\");\r\n\t\tplusSignVLine.style(\"visibility\", \"hidden\");\r\n\r\n\t\tlegendsOn = true;\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if this Bezier curve is approximately a straight line within given tolerance. | isLine(tolerance = 1e-6) {
if (this.dimension !== 2) {
throw new Error("isFlat check only supported for 2D Bezier curves");
}
if (this.degree === 1) {
return true;
}
return helper_1.arePointsColinear(this.cpoints, tolerance);
} | [
"function isCloseToLine(dotloc){\n\n var isClose = false;\n for(var i=0; i<points.length-1; i++){ //check every line segment\n \n var d = calcDist(points[i], dotloc, points[i+1]); //calculate the line segment distance between these points\n\n if(d < TOLERANCE){\n //console.log(\"\\tClose to \"+i+\" and \"+(i+1)+\": \"+d);\n isClose = true;\n if(SHOW_TOLERANCE_LINES){\n setStrokeWidth(0.5);\n\n drawLine(points[i],dotloc);\n drawLine(points[i+1],dotloc);\n setStrokeWidth(3);\n\n drawLine(points[i],points[i+1]);\n }\n \n \n //return true; \n }\n \n }\n if(isClose){ //could move this into loop to short-circuit but more fun for SHOW_TOLERANCE_LINES\n return true;\n }\n if(isClose == false){\n //console.log(\"\\tNOT close. \");\n \n //reset();\n }\n return false;\n}",
"pointIsWithinLine(p) {\n\t\tconst a1 = this.endPoint.y - this.startPoint.y;\n\t\tconst b1 = -(this.endPoint.x - this.startPoint.x);\n\t\tconst c1 = -this.startPoint.y * b1 - this.startPoint.x * a1;\n\n\t\tif (round(a1 * p.x + b1 * p.y + c1) != 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst lineDirection = this.getLineDirection();\n\t\tconst lengthLineSegment = this.getLength();\n\t\tlet distanceFromStart;\n\n\t\tif (lineDirection.y != 0) {\n\t\t\tdistanceFromStart = (p.y - this.startPoint.y) / lineDirection.y;\n\t\t}\n\t\telse if (lineDirection.x != 0) {\n\t\t\tdistanceFromStart = (p.x - this.startPoint.x) / lineDirection.x;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (distanceFromStart >= 0 && distanceFromStart <= lengthLineSegment)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}",
"function isStraightLine(points) {\n var angle = angleBetweenTwoPoints(points[0], points[1]);\n for (var i = 1; i < points.length - 1; i++) {\n var newAngle = angleBetweenTwoPoints(points[i], points[i + 1]);\n // Have a tolerance of 1 degree.\n if (Math.abs(newAngle - angle) > 1) {\n return false;\n }\n angle = newAngle;\n }\n return true;\n }",
"function isApprox(actual, expected, tolerance)\n{\n return ((expected - tolerance) < actual) && (actual < (expected + tolerance));\n}",
"onLine(p1, p2) {\n return this.distToLine(p1, p2) < config.precision_point_on_line;\n }",
"function getNextNonBoundarySegment (line, startIndex, tolerance) {\n var endIndex = startIndex;\n while (line[endIndex + 1] && outsideTile(line[endIndex], line[endIndex + 1], tolerance)) {\n endIndex++;\n }\n\n // If there is a line segment remaining that is within the tile, push it to the lines array\n return (line.length - endIndex >= 2) ? line.slice(endIndex) : false;\n}",
"static isIn01WithTolerance(x, tolerance) { return x + tolerance >= 0.0 && x - tolerance <= 1.0; }",
"static CheckLineSegmentCrossing (x1,y1,x2,y2,x3,y3,x4,y4) {\n let result = false;\n let l1 = Geometry.LineEquation(x1,y1,x2,y2);\n let l2 = Geometry.LineEquation(x3,y3,x4,y4);\n let check1 = (l1[0]*x3+l1[1]*y3+l1[2])*(l1[0]*x4+l1[1]*y4+l1[2]) < 0;\n let check2 = (l2[0]*x1+l2[1]*y1+l2[2])*(l2[0]*x2+l2[1]*y2+l2[2]) < 0;\n if (check1 && check2) result = true;\n return result;\n }",
"function is_close_to_start(){\n if(numpts > 0){\n var d2 = (cx-x[0])*(cx-x[0]) + (cy-y[0])*(cy-y[0]);\n return d2 < tr*tr;\n }else{\n return false;\n }\n}",
"function isPointOnLine(pointA, pointB, pointToCheck) {\n return (\n Math.hypot(pointToCheck[0] - pointA[0], pointToCheck[1] - pointA[1]) +\n Math.hypot(pointB[0] - pointToCheck[0], pointB[1] - pointToCheck[1]) ===\n Math.hypot(pointB[0] - pointA[0], pointB[1] - pointA[1])\n )\n}",
"function FindNearbyLineSegmentPoint(mousePoint, tolerance)\n{\n for (i = 0; i < segments.length; i++)\n {\n if (PointDistance(segments[i].segments[0].point, mousePoint) < tolerance)\n {\n return segments[i].segments[0].point;\n }\n if (PointDistance(segments[i].segments[1].point, mousePoint) < tolerance)\n {\n return segments[i].segments[1].point;\n }\n }\n return mousePoint;\n}",
"function _onSegment(A,B,p, tolerance){\n\t\tif(!tolerance){\n\t\t\ttolerance = TOL;\n\t\t}\n\t\t\t\t\n\t\t// vertical line\n\t\tif(_almostEqual(A.x, B.x, tolerance) && _almostEqual(p.x, A.x, tolerance)){\n\t\t\tif(!_almostEqual(p.y, B.y, tolerance) && !_almostEqual(p.y, A.y, tolerance) && p.y < Math.max(B.y, A.y, tolerance) && p.y > Math.min(B.y, A.y, tolerance)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t// horizontal line\n\t\tif(_almostEqual(A.y, B.y, tolerance) && _almostEqual(p.y, A.y, tolerance)){\n\t\t\tif(!_almostEqual(p.x, B.x, tolerance) && !_almostEqual(p.x, A.x, tolerance) && p.x < Math.max(B.x, A.x) && p.x > Math.min(B.x, A.x)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\t\t\n\t\t\n\t\t//range check\n\t\tif((p.x < A.x && p.x < B.x) || (p.x > A.x && p.x > B.x) || (p.y < A.y && p.y < B.y) || (p.y > A.y && p.y > B.y)){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t\n\t\t// exclude end points\n\t\tif((_almostEqual(p.x, A.x, tolerance) && _almostEqual(p.y, A.y, tolerance)) || (_almostEqual(p.x, B.x, tolerance) && _almostEqual(p.y, B.y, tolerance))){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tvar cross = (p.y - A.y) * (B.x - A.x) - (p.x - A.x) * (B.y - A.y);\n\t\t\n\t\tif(Math.abs(cross) > tolerance){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tvar dot = (p.x - A.x) * (B.x - A.x) + (p.y - A.y)*(B.y - A.y);\n\t\t\n\t\t\n\t\t\n\t\tif(dot < 0 || _almostEqual(dot, 0, tolerance)){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tvar len2 = (B.x - A.x)*(B.x - A.x) + (B.y - A.y)*(B.y - A.y);\n\t\t\n\t\t\n\t\t\n\t\tif(dot > len2 || _almostEqual(dot, len2, tolerance)){\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn true;\n\t}",
"isProperEdge(index) {\n const extents = this.extents;\n const nextIdx = (index + 1) % this.points.length;\n const curr = this.points[index];\n const next = this.points[nextIdx];\n if (this.clippedPointIndices !== undefined) {\n if (curr.x !== next.x && curr.y !== next.y) {\n // `curr` and `next` must be connected with a line\n // because they don't form a vertical or horizontal lines.\n return true;\n }\n const currAtEdge = curr.x % this.extents === 0 || curr.y % this.extents === 0;\n if (!currAtEdge) {\n // the points are connected with a line\n // because at least one of the points is not on\n // the tile boundary.\n return true;\n }\n const nextAtEdge = next.x % this.extents === 0 || next.y % this.extents === 0;\n if (!nextAtEdge) {\n // the points are connected with a line\n // because at least one of the points is not on\n // the tile boundary.\n return true;\n }\n const currWasClipped = this.clippedPointIndices.has(index);\n const nextWasClipped = this.clippedPointIndices.has(nextIdx);\n return !currWasClipped && !nextWasClipped;\n }\n return !((curr.x <= 0 && next.x <= 0) ||\n (curr.x >= extents && next.x >= extents) ||\n (curr.y <= 0 && next.y <= 0) ||\n (curr.y >= extents && next.y >= extents));\n }",
"function isLine(ps) {\n if (ps.length === 2) {\n // Line\n return true;\n }\n if (ps.length === 3) {\n // Quadratic bezier\n return flo_numerical_1.orient2d(ps[0], ps[1], ps[2]) === 0;\n }\n if (ps.length === 4) {\n // Cubic bezier\n return (flo_numerical_1.orient2d(ps[0], ps[1], ps[2]) === 0 &&\n flo_numerical_1.orient2d(ps[1], ps[2], ps[3]) === 0 &&\n // The below check is necessary for if ps[1] === ps[2]\n flo_numerical_1.orient2d(ps[0], ps[2], ps[3]) === 0);\n }\n}",
"function inTolerance(actual, projected, tolerance) {\n return projected - tolerance < actual && projected + tolerance > actual;\n}",
"function linePointIntersection(lPath, point, difference) {\n var v = lPath.endpos.clone().sub(lPath.startpos);\n if (v.length < 1) {\n if (lPath.startpos.clone().sub(point).length() <= difference) {\n return lPath.starttime;\n }\n else {\n return false;\n }\n }\n v.multiplyScalar(lPath.speed / v.length());\n var vectToPt = lPath.startpos.clone().sub(point);\n\n // Solve the quadratic formula (solved analytically on paper.)\n var a = v.dot(v);\n var b = 2 * vectToPt.dot(v);\n var c = vectToPt.dot(vectToPt) - difference * difference;\n\n var discriminant = b*b - 4*a*c;\n if (discriminant <= 0) {\n return false;\n }\n\n var t1 = (-b + Math.sqrt(discriminant)) / (2*a);\n var t2 = (-b - Math.sqrt(discriminant)) / (2*a);\n\n // Check if any of the options are viable.\n t1 += lPath.starttime;\n t2 += lPath.starttime;\n\n if (t1 < lPath.endtime && t1 > lPath.starttime &&\n t2 < lPath.endtime && t2 > lPath.starttime) {\n return Math.min(t1, t2);\n }\n else if (t1 < lPath.endtime && t1 > lPath.starttime) {\n return t1;\n }\n else if (t2 < lPath.endtime && t2 > lPath.starttime) {\n return t2;\n }\n else {\n return false;\n }\n}",
"areStrokedBoundsDilated() {\n const epsilon = 0.0000001;\n\n // If the derivative at the start/end are pointing in a cardinal direction (north/south/east/west), then the\n // endpoints won't trigger non-dilated bounds, and the interior of the curve will not contribute.\n return Math.abs(this.startTangent.x * this.startTangent.y) < epsilon && Math.abs(this.endTangent.x * this.endTangent.y) < epsilon;\n }",
"function plotLine(pxTolerance, Ax, Ay, Bx, By) {\n var dx = Bx - Ax;\n var dy = By - Ay;\n var ptCount = parseInt(Math.sqrt(dx * dx + dy * dy)) * 3;\n var lastX = -10000;\n var lastY = -10000;\n var pts = [{ x: Ax, y: Ay }];\n for (var i = 1; i <= ptCount; i++) {\n var t = i / ptCount;\n var x = Ax + dx * t;\n var y = Ay + dy * t;\n var dx1 = x - lastX;\n var dy1 = y - lastY;\n if (dx1 * dx1 + dy1 * dy1 > pxTolerance) {\n pts.push({ x: x, y: y });\n lastX = x;\n lastY = y;\n }\n }\n pts.push({ x: Bx, y: By });\n return pts;\n}",
"_withinTolerance(actual, expected, tolerance) {\n const tolerances = {\n lower: actual,\n upper: actual,\n };\n if (tolerance) {\n tolerances.lower -= Math.max(tolerance, 0);\n tolerances.upper += Math.max(tolerance, 0);\n }\n return Math.max(expected, 0) >= Math.max(tolerances.lower, 0) &&\n Math.max(expected, 0) <= Math.max(tolerances.upper, 0);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If name contains an alphabetical character, check the name checkbox. Used by multiple readers. | function checkName(namestring) {
if (/[A-Za-z]/.test(namestring)) nameCheckbox.checked = true;
} | [
"function checknameControl(name) {\n if (!name) {\n return 'An name is required.';\n }\n return '';\n }",
"function checkName(Name) {\n\tName = document.getElementById('playerName').value;\n\tif (Name == 0) {\n\t\treturn false;\n\t}\n\telse {\n\t\treturn true;\n\t}\n}",
"function nameValidation () {\n const nameRequirement = /^\\w+/;\n return nameRequirement.test(nameInput.value);\n }",
"function checkName(controlName, FieldName, blankFlag) {\n\tif (blankFlag != 'Y') {\n\t\tif ( $('#'+controlName).val() == '') {\n\t\t\tbootbox.alert(FieldName + ' can not be blank'); \n\t\t\treturn false;\n\t\t}\n\t}\n\tif( /^[a-zA-Z0-9- ]*$/.test( $('#'+controlName).val() ) == false ) {\n\t\tbootbox.alert(FieldName + ': input is not alphanumeric');\n\t\treturn false;\n\t}\n\treturn true;\n}",
"function isNameValid () {\n return $name.val().length > 0;\n }",
"function isValidName(name) {\n \n if(typeof name !== 'string'){ // Tip kontrolü yapıyoruz\n return false;\n }\n \t\n if(name === \"\"){\t\t\t// Hiçbirşey girilmemişse yapıyoruz.\n \treturn false;\n }\n \n if(name.length === 1){\t//Uzunluk 1 mi değil mi diye kontrol ediyoruz\n \t return false\n }\n \n if(name.trim() !== name){\t//Sağında solunda boşluk silip eşit mi kontrol ediyoruz\n return false;\n }\n \n var nameCharacterArr=name.split(\"\"); // Karakterleri array'a atıyoruz\n \n for(let nameCharacter in nameCharacterArr){\t// Array'e attığımız karakterleri dönüyoruz.\n \t\n if(nameCharacterArr[nameCharacter] == \" \"){ // Boşluk kontrolü yaptırıyoruz.\n \treturn false;\n }else{\n \t\treturn true;\n }\n \n }\n \n}",
"function YAPI_CheckLogicalName(name)\n {\n if(name == \"\") return true;\n if(!name) return false;\n if(name.length > 19) return false;\n return /^[A-Za-z0-9_\\-]*$/.test(name);\n }",
"function checkCardName() {\n\n let name = cardName.value\n let regexpEng = RegExp(/^[a-zA-Z0-9 ]*$/);\n let regexpRus = RegExp(/^[а-яА-Я0-9 ]*$/);\n\n if (!regexpEng.test(name) && !regexpRus.test(name)) {\n error_cardName = true;\n } else {\n error_cardName = false;\n }\n displayError(error_cardName, cardNameError)\n }",
"function nameValidate() {\r\n const nameRegex = /^([A-Z][a-z]{2,9})(\\s?[a-zA-Z]{3,10})?$/;\r\n wrongInp.classList.replace(\"d-block\", \"d-none\");\r\n rightInp.classList.replace(\"d-block\", \"d-none\");\r\n\r\n if (nameRegex.test(suNameInput.value) == true && suNameInput.value != \"\") {\r\n suNameInput.classList.add(\"is-valid\");\r\n suNameInput.classList.remove(\"is-invalid\");\r\n suNameAlert.classList.replace(\"d-block\", \"d-none\");\r\n return true;\r\n } else {\r\n suNameInput.classList.add(\"is-invalid\");\r\n suNameInput.classList.remove(\"is-valid\");\r\n suNameAlert.classList.replace(\"d-none\", \"d-block\");\r\n return false;\r\n }\r\n }",
"function isValidName(name){ \n if(typeof name !== \"string\") {\n return false\n } else if (name === \"\") {\n return false\n } else if (name === false){\n return false\n } else if (name === undefined){\n return false\n } else if (name === null){\n return false\n } else if (name.length < 3){\n return false\n } else if (!!name.toLowerCase().split(\"\").map(n => n.charCodeAt()).find(n => n < 97 || n > 123 && n !== 231 && n !== 305 && n !== 287 && n !== 246 && n !== 351 && n !== 252 )) {\n return false;\n } else {\n return true\n }\n}",
"static isValidCustomElemName (name) {\n try {\n const cutName = name.split('-')\n const nameValid = this.isOpen(name) && cutName.length > 1 && cutName[0] !== ''\n\n return nameValid\n }\n catch (e) {\n console.error('Please specify a name for your component in format \"a-b\"')\n return false\n }\n }",
"function validName() {\n return document.getElementById('name').value !== '';\n}",
"function CheckUserName(name)\r\n{\r\n if( (name.length > 16) || (name.length < 4) )\r\n {\r\n return false;\r\n }\r\n var name1 = new String(name);\r\n var SpeficCharFilter = /([,; &\"<>\\\\?])/;\r\n if( name1.match(SpeficCharFilter) )\r\n {\r\n return false;\r\n }\r\n else\r\n {\r\n return true;\r\n }\r\n}",
"function nameValidator() {\n const nameValue = name.value;\n const nameIsValid = /^[a-zA-Z]+ ?[a-zA-Z]*? ?[a-zA-Z]*?$/.test(nameValue);\n validator(nameIsValid, name);\n return nameIsValid;\n}",
"function itItNameCheck(name) {\n // true at the first occurence of a vowel\n var vowelflag = false; // true at the first occurence of an X AFTER vowel\n // (to properly handle last names with X as consonant)\n\n var xflag = false;\n\n for (var i = 0; i < 3; i++) {\n if (!vowelflag && /[AEIOU]/.test(name[i])) {\n vowelflag = true;\n } else if (!xflag && vowelflag && name[i] === 'X') {\n xflag = true;\n } else if (i > 0) {\n if (vowelflag && !xflag) {\n if (!/[AEIOU]/.test(name[i])) {\n return false;\n }\n }\n\n if (xflag) {\n if (!/X/.test(name[i])) {\n return false;\n }\n }\n }\n }\n\n return true;\n}",
"function validateName(name) {\n if (name.length > 20 || name == \"\" || !name.match(/^[0-9a-z]+$/)) {\n return false;\n }\n\n return true;\n}",
"function validate_name(name){\n\treturn /^[A-Za-z\\s-]+$/.test(name.value) || /^[a-zA-Z ]+$/.test( name.value);\n\n}",
"function validate_name(name) {\n return /^[A-Za-z\\s-]+$/.test(name.value) || /^[a-zA-Z ]+$/.test(name.value);\n\n}",
"function validate_name(input_name) {\n\tvar re = /(?=.*[a-zA-Z ])^[a-zA-Z ]{5,100}$/;\n\treturn re.test(input_name);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to retrieve wikipedia data | function getWikipediaData(data){
var numberPages = 10;
var searchString = encodeURI(data);
var apiURL = prot + '//en.wikipedia.org/w/api.php?action=opensearch&search=' + searchString + '&profile=fuzzy&suggest=true&format=json';
//formatversion=2 - for json requests
//continue= - empty passed to get continue
//make ajax request
var request = $.ajax({
type: 'GET',
url: apiURL,
dataType: 'jsonp',
jsonp: "callback",
headers: { 'Api-User-Agent': 'FreeCodeCamp Wikipedia Viewer' }
});
//handle succesful request
request.success(function(data){
//do something with the received data
//check for continue string. If present, resubmit request with continue to get more
console.log(data);
//console.log(data[0]); //search string
//console.log(data[1]); // array listing titles
//console.log(data[2]); // array listing description
//console.log(data[3]); // array listing link
$("#articles").html("");
for(var i = 0; i < data[1].length; i++){
//console.log("Title: " + data[1][i] + "\n Description: " + data[2][i] + "\n Link: " + data[3][i]);
console.log(data);
$("#articles").append("<div class='article'><a href='" + data[3][i] + "' target='_blank'><h3>" + data[1][i] + "</h3><p>" + data[2][i] + "</p></a></div>");
}
});
//handle errors
request.error(function(error){
console.log("An error has occured while retrieving data!");
});
} | [
"function getWikiInfo() {\n var url = \"https://en.wikipedia.org/w/api.php?action=query\" +\n \"&list=search&srsearch=\" + attributes.name + \"&srwhat=text&prop=extracts|pageimages|imageinfo|pageterms|info&exintro=1&explaintext=1&exlimit=20&pilimit=20&piprop=original\" +\n \"&generator=geosearch&ggscoord=\" + position.latitude + \"%7C\" + position.longitude + \"&ggsradius=200&ggslimit=20&origin=*&format=json\";\n return esriRequest(url, {\n responseType: \"json\"\n }).then(function(response) {\n var pages = response.data.query.pages;\n var search = response.data.query.search;\n var article = null, i = 0;\n while ((!article) && (i < search.length)) {\n for (var prop in pages) {\n if ((pages.hasOwnProperty(prop)) && (search[i].title === pages[prop].title)) {\n article = pages[prop];\n break;\n }\n }\n i++;\n }\n if (article) {\n var extract = article.extract.length > 200 ? article.extract.substring(0, article.extract.indexOf(\".\", 200) + 1) : article.extract;\n view.popup.content += \"<p>\" + extract +\n \" <a href='http://en.wikipedia.org/wiki/\" + article.title.replace(\" \", \"_\") + \"' target='_blank'> Read the entire article on Wikipedia</a></p>\";\n }\n });\n }",
"function getWiki(name) {\n // The wikipedia API call we will use with the author's name as the title\n var apiUrl = encodeURI('//en.wikipedia.org/w/api.php?action=query&titles=' + name + '&prop=pageimages|info&piprop=thumbnail&inprop=url&format=jsonty&pithumbsize=500&utf8=&redirects&callback=?')\n\n // resets the thumbnail and wikipedia URL because we are getting a new quote\n wikiThumb = \"\";\n wikiUrl = \"\";\n\n // the wikipedia API call\n $.ajax({\n url: apiUrl,\n data: {\n format: 'json'\n },\n dataType: 'jsonp'\n }).done(function(data) {\n //console.log(JSON.stringify(data, undefined, 2));\n var pages = data.query.pages;\n parseWiki(pages);\n });\n}",
"function getData(info) {\n var wikiUrl = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=' + info + '&format=json&callback=?';\n //set time out, so if time out passed without get any info alert the user\n var requestTimeout = setTimeout(function () {\n alert('Failed to get wikipedia resourses');\n }, 8000);\n //send request to get the data from wikipedia\n $.ajax({\n url: wikiUrl,\n dataType: 'jsonp',\n success: function (response) {\n $('#output').html('');\n // in case no info comes from the wikipedia\n if (response.length == 0) {\n $('#output').prepend('<p><strong> There is no data ti display!</strong></p>');\n }\n else{\n // console.log(response)\n // Through each item and add it to html\n $('#output').html('<h3>'+response[0]+'</h3>')\n for (var i = 0; i < response[1].length; i++) {\n $('#output').append('<p><strong>'+response[2][i]+'</strong></p>');\n }\n }\n clearTimeout(requestTimeout); //clear time out in case of success\n },\n error: function(){\n alert(\"Failed to get wikipedia resourses\");\n }\n });\n}",
"function getWikipedia(url) {\n // First change the URL from a regular wikipedia one to a wikipedia api url\n let apiUrl = `https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=${url.split(\"/\").splice(-1).pop()}`;\n let x = rp(apiUrl).then((body) => {\n console.log(\"Responce received\");\n // Get the body of the wikipedia article\n let contentHtml = JSON.parse(body)[\"query\"][\"pages\"];\n contentHtml = contentHtml[Object.keys(contentHtml)[0]][\"extract\"];\n // Limit to 150 characters\n const LIMIT = 150;\n let content = contentHtml.substring(0, LIMIT - 3) + \"...\";\n // Return the trimmed content\n return content;\n });\n return x;\n}",
"static extractDataFromWikipedia(res, content) {\n\t\tlet json = JSON.parse(content);\n\t\tif(typeof json.query.pages == 'undefined'){\n\t\t\tUtil.sendResults(res, JSON.stringify({'error' : 'Nothing found'}));\n\t\t\treturn;\n\t\t}\n\t\tlet page = Object.keys(json.query.pages)[0];\n\t\tlet p = json.query.pages[page];\n\t\tlet data;\n\t\tif (typeof p.thumbnail != 'undefined' && typeof p.pageid != 'undefined')\n\t\t\tdata = new WikipediaData(p.thumbnail.source, p.title, p.extract, p.pageid);\n\t\telse\n\t\t\tdata = new WikipediaData('', '', '', '');\n\t\tUtil.sendResults(res, JSON.stringify(data));\n\t}",
"function wikiAPI() {\n var wikiURL = 'https://en.wikipedia.org/w/api.php?action=opensearch&search=' + name + '&format=json&callback=wikiCallback';\n var wikiRequestTimeout = setTimeout(function() {\n infowindow.setContent('Error loading Wikipedia links! Please try again later.');\n }, 5000);\n\n $.ajax({\n url: wikiURL,\n dataType: \"jsonp\",\n success: function(response) {\n self.wikiList.removeAll();\n var articles = response[1];\n if (articles.length == 0) {\n infowindow.setContent('No Wikipedia article found.');\n }\n for (var i = 0; i < articles.length; i++) {\n articlename = articles[i];\n var url = 'https://en.wikipedia.org/wiki/' + articlename;\n self.wikiList.push(new wiki(articlename, url));\n }\n clearTimeout(wikiRequestTimeout);\n }\n });\n }",
"function getInfo (link) {\r\n $(function () {\r\n $.ajax({\r\n type: 'GET',\r\n url: `https://www.mediawiki.org/w/api.php?action=query&origin=https://en.wikipedia.org`,\r\n success: function(data) {\r\n \r\n }\r\n })\r\n })\r\n}",
"function getWikipediaApi(wikiSearch) {\n let wikiParams = {\n origin: '*',\n action: 'query',\n format: 'json',\n prop: 'extracts|pageimages',\n indexpageids: 1,\n redirects: 1,\n exchars: 1200,\n exsectionformat: 'plain',\n piprop: 'name|thumbnail|original',\n pithumbsize: 250\n };\n wikiParams.titles = wikiSearch;\n const queryString = formatQueryParams(wikiParams)\n let url = 'https://en.wikipedia.org/w/api.php?' + queryString;\n fetch (url, wikiParams)\n .then(response => {\n if (response.ok) {\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .then(responseJson => displayResultsWiki(responseJson))\n .catch(err => {\n $('#js-error-message').text(`Something went wrong: ${err.message}`);\n });\n}",
"function viewRandomWiki() {\n $.ajax({\n type: 'GET',\n url: 'https://simple.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=extract&format=json&callback=?',\n contentType: 'application/json; charset=utf-8',\n async: false,\n dataType: 'json',\n success: function(data) {\n var page = data[\"query\"][\"pages\"][Object.keys(data[\"query\"][\"pages\"])[0]][\"title\"];\n viewWikipediaPage(page);\n },\n error: function(errorMessage) {\n console.log('Error: ' + errorMessage);\n }\n });\n}",
"function wiki(b) {\n\t// api URL\n var url = \"https://en.wikipedia.org/w/api.php?action=opensearch&search=\" + b + \"&limit=\" + String(limit) + \"&namespace=0&format=json\";\n $.ajax({\n type: \"GET\",\n url: url,\n dataType: \"jsonp\",\n success: function(data) {\n\t\t\t// Reset the results\n contentContainer.innerHTML = \"\";\n for (i = 0; i < limit; i++) {\n\t\t\t\t// If there are wiki articles to display\n if (data[2][i] != undefined) {\n\t\t\t\t\t// Format the data\n var newData = \"<a href=\" + \"'https://en.wikipedia.org/wiki/\" + data[1][i] + \"' class='entry' id='\" + i + \"' target='_blank'>\" + \"<h3>\" + data[1][i] + \"</h3>\" + \"<br>\" + data[2][i] + \"</a>\" + \"<br>\";\n\t\t\t\t\t// Add the data to the results\n contentContainer.innerHTML += newData;\n } else if (data[2][i] == undefined) {\n\t\t\t\t\t// If there's no wikipedi articles, tell the user\n contentContainer.innerHTML = \"<h3 class='entry'> There are no articles to display </h3>\"\n }\n }\n },\n\t\t// Error handling: tell the error. \n error: function(xhr, ajaxOptions, thrownError) {\n alert(xhr.status);\n alert(thrownError);\n }\n });\n}",
"getWikipediaInfo(marker) {\n let self = this;\n let pageId = marker.pageId;\n let url = 'https://cors-anywhere.herokuapp.com/https://pl.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&pageids=' + pageId;\n // ew. explaintext=&\n fetch(url)\n .then(function(response){\n return response.json();\n }).then(function(data){\n let title = data.query.pages[pageId].title;\n let content = data.query.pages[pageId].extract;\n self.state.infoWindow.setContent(`<p>From Wikipedia</p><h3>${title}</h3><p>${content}<p>`);\n }).catch(function(error){\n alert('Failed to load Wikipedia resources ' + error);\n })\n }",
"function getWikiInfo(callback, place) {\n // check callback is a function\n if(typeof callback !== 'function') {\n console.warn('callback is not a function');\n return;\n }\n var endPoint = 'https://en.wikipedia.org/w/api.php',\n results;\n\n $.ajax({\n url: endPoint,\n dataType: 'jsonp',\n data: {\n action: 'query',\n format: 'json',\n prop: 'coordinates|pageimages|pageterms|info',\n generator: 'geosearch',\n formatversion: 2,\n colimit: 5,\n piprop: 'thumbnail',\n pithumbsize: 144,\n pilimit: 5,\n wbptterms: 'description',\n inprop: 'url',\n ggscoord: place.lat+'|'+place.lng,\n ggsradius: 10000,\n ggslimit: 5\n }\n })\n .done(function(data) {\n if(data.query && data.query.pages) {\n results = data.query.pages\n .map(function(page) {\n return {\n siteUrl: page.fullurl,\n thumbnail: page.thumbnail,\n title: page.title,\n description: page.terms ? page.terms.description : undefined\n };\n });\n }\n })\n .fail(function() {\n // When failed, just set the result to null so that the callback is called with null\n results = null;\n })\n .always(function() {\n callback(results);\n });\n }",
"function loadWikipedia(title, infowindow){\n var newContent = '<ul class=\"list-unstyled\">';\n\n $.ajax({\n url: 'http://en.wikipedia.org/w/api.php',\n data: {action: 'opensearch', search: title, limit: '4', format: 'json'},\n dataType: 'jsonp'\n }).done(function(response){\n var articleList = response[1];\n for (var i = 0; i < articleList.length; i++) {\n var url = 'https://en.wikipedia.org/wiki/' + articleList[i];\n newContent += '<li><a target=\"_blank\" href=\"' + url + '\">' +\n articleList[i] +'</a></li>';\n };\n newContent += '</ul></div></div>';\n infowindow.setContent(infowindow.getContent() + newContent);\n }).fail(function( xhr, status, errorThrown ){\n alert(\"Fail to load wikipedia articles\");\n console.log(\"Fail to load wikipedia articles\");\n console.log( \"Error: \" + errorThrown );\n console.log( \"Status: \" + status );\n console.dir( xhr );\n });\n}",
"function wikiLoad(stationStr) {\n\t\t var wikiUrl = \"https://en.wikipedia.org/w/api.php?action=opensearch&search=\" +\n\t\t\t\t\t\t stationStr +\n\t\t\t\t\t\t \"&limit=1&format=json&namespace=0&callback=?\";\n\n\t\t $.ajax({\n\t\t url: wikiUrl,\n\t\t dataType: \"json\",\n\t\t }).done(function(data){\n\t\t\t\tvar result = {\n\t\t\t\t\ttitle : data[1][0],\n\t\t\t\t\tsnippet : data[2][0],\n\t\t\t\t\tweb_url : data[3][0]\n\t\t\t\t};\n\t\t\t\tinfowindow.setContent(\"<a href='\" + result.web_url + \"' class='infowindow' target='_blank'>\" + \n\t\t\t\t\t\t\t\t\t marker.title + \"</a><p><div class='snippet'>\" +\n\t\t\t\t\t\t\t\t\t result.snippet + \"</div></p>\" +\n\t\t\t\t\t\t\t\t\t \"<p><i>Source: <a href='https://www.mediawiki.org/wiki/API:Main_page' target='_blank'>\" +\n\t\t\t\t\t\t\t\t\t \"Wikipedia API</a></i></p>\");\n\t\t }).fail(function(error){\n\t\t \tinfowindow.setContent(\"Failed to get wikipedia resources on \" + stationStr);\n\t\t });\n\t\t}",
"function searchWiki() {\n var term = $(\"input\").val();\n var apiUrl = 'https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=40&search=' + term + '&callback=?';\n\n $.getJSON(apiUrl, success).fail(error);\n \n // on success, create a new array of WikiEntry objects from the returned data\n function success(data) {\n console.log(data);\n var result = [];\n for (var i = 0; i < data[1].length; i++) {\n result.push(new WikiEntry([data[1][i], data[2][i], data[3][i]]));\n }\n // pass the array of WikiEntry objects on to be displayed\n displayResults(result);\n }\n\n function error() {\n alert(\"Error accessing Wikipedia. Please reload the page or try again later.\");\n }\n }",
"_fetchWikiInfo() {\n const wiki = this._fetching.shift();\n if (!wiki) {\n return;\n }\n io.query(wiki, {\n meta: 'siteinfo',\n siprop: [\n 'general',\n 'namespaces',\n 'statistics',\n 'wikidesc'\n ].join('|')\n }).then(function(d) {\n if (\n typeof d === 'object' &&\n typeof d.query === 'object' &&\n typeof d.error !== 'object'\n ) {\n const {query} = d;\n this._wikis.filter(w => w.wiki === wiki).forEach(function(w) {\n w.id = Number(query.wikidesc.id);\n w.sitename = query.general.sitename;\n w.path = query.general.articlepath;\n w.namespaces = {};\n for (const i in query.namespaces) {\n const ns = query.namespaces[i];\n w.namespaces[ns['*']] = ns.id;\n w.namespaces[ns.canonical] = ns.id;\n }\n w.statistics = query.statistics;\n }, this);\n }\n this._fetchWikiInfo();\n }.bind(this)).catch(e => console.log(e));\n }",
"function getWikipediaContent(keyword) {\n\n var url = \"http://en.wikipedia.org/w/api.php?action=query&titles=\" + keyword + \"&prop=extracts&format=json\";\n\n var content = UrlFetchApp.fetch(url).getContentText();\n var data = JSON.parse(content);\n\n var page = data.query.pages[Object.keys(data.query.pages)[0]];\n var extract = page.extract;\n var title = page.title;\n\n return [extract];\n}",
"function getInformation(subreddit){\n$.getJSON(\"https://ajax.googleapis.com/ajax/services/search/web?v=1.0&hl=en&gl=en&userip=&q=\" + subreddit + \" en.wikipedia&start=0&rsz=1&callback=?\", subreddit, function (data) {\n if(data!==undefined){\n if(data.responseData.results.length !== 0){\n $.getJSON(\"https://en.wikipedia.org/w/api.php?&format=json&action=query&generator=search&gsrsearch=\" + data.responseData.results[\"0\"].url.slice(30) + \"&utf8&gsrlimit=1&gsrwhat=nearmatch&prop=extracts&exintro&redirects&exchars=1059&callback=?\", subreddit, function(data){\n setInformation(subreddit,data);\n });\n }\n else\n wikiDict[subreddit]=\"No preview available\";\n }\n else{\n $.getJSON(\"https://en.wikipedia.org/w/api.php?&format=json&action=query&generator=search&gsrsearch=\" + subreddit + \"&utf8&gsrlimit=1&gsrwhat=nearmatch&prop=extracts&exintro&redirects&exchars=1059&callback=?\", subreddit, function(data){\n if(data.hasOwnProperty(\"query\")===false){\n $.getJSON(\"https://en.wikipedia.org/w/api.php?&format=json&action=query&generator=search&gsrsearch=\" + subreddit + \"&utf8&gsrlimit=1&gsrwhat=text&prop=extracts&exintro&exchars=1059&callback=?\",subreddit, function(data){\n if(data.hasOwnProperty(\"query\")===false){\n $.getJSON(\"https://en.wikipedia.org/w/api.php?&format=json&action=query&list=search&srsearch=\" + subreddit + \"&exchars=1059&callback=?\",subreddit, function(data){\n $.getJSON(\"https://en.wikipedia.org/w/api.php?&format=json&action=query&generator=search&gsrsearch=\" + data.query.searchinfo.suggestion + \"&utf8&gsrlimit=1&gsrwhat=text&prop=extracts&exintro&exchars=1059&callback=?\",subreddit, function(data){\n setInformation(subreddit, data);\n });\n });\n }\n else{\n setInformation(subreddit, data);\n }\n });\n }\n else{\n setInformation(subreddit, data);\n }\n\n });\n }\n});\n}",
"function fetchWiki(title, language) {\n\t\n\t//Reset the text feed.\n\ttextFeed = \"\";\n\t\n\t//Encode the title so that it can be read by the API \n\ttitle = prepareTitle(title);\n\t\n\t//Build the URL.\n\tvar url = TEXT_JS_HTTP + language + TEXT_JS_API + title;\n\t\n\t/*************************************\n\t\tAJAX request to the Wikipedia API.\n\t*************************************/\n\t$.getJSON(url, function(result) {\n\t\t\n\t\t//Put the JSON response in a string.\n\t\tvar string = JSON.stringify(result.query.pages);\n\t\t\n\t\t//Get the start index of the extract text.\n\t\tvar index = string.indexOf(JSON_INDEX_SUBSTRING);\n\t\t\n\t\t//Get the extract text.\n\t\tstring = string.substring(index + JSON_START_SUBSTRING, string.length - JSON_END_SUBSTRING);\n\t\t\n\t\t//check that it returned a text extract of at least the minimum specified length.\n\t\tif(string.length >= MIN_EXTRACT_LENGTH)\n\t\t{\n\t\t\ttextFeed = string;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t//If it didn't, get a random Wikipedia page.\n\t\t\tgetRandomPage(language);\n\t\t}\n\t\t\n\t}).fail(function(xhr, status, error){\t\t\n\t\t\t\n\t\t\t//Get a random Wikipedia page if it fails to get a page.\n\t\t\tgetRandomPage(language);\n\t\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ACK ALL ALERT ////////////////////////////////////////// triggered by: user button arguemnts: MID what it does: sends a message to the server to ack all the alerts for this box why: to get ridge of all alerts in the alert view at once ///////////////////////////////////////// ACK ALL ALERT | function ack_all_alert(mid){
var cmd_data = { "cmd":"ack_all_alert", "mid":mid};
con.send(JSON.stringify(cmd_data));
show_alarms(mid); // its already open, but this will reset the content
get_alarms(mid); // and this should send us an empty list
} | [
"function ack_alert(id,mid){\n\t// remove field\n\t$(\"#alert_\"+mid+\"_\"+id).fadeOut(600, function() { $(this).remove(); });\n\n\t// decrement nr\n\tvar button=$(\"#\"+mid+\"_toggle_alarms\");\n\tvar open_alarms=parseInt(button.text().substring(0,button.text().indexOf(\" \")))-1;\n\tvar txt=$(\"#\"+mid+\"_toggle_alarms_text\");\n\tvar counter=$(\"#\"+mid+\"_alarm_counter\");\n\tset_alert_button_state(counter,button,txt,open_alarms);\n\n\tvar cmd_data = { \"cmd\":\"ack_alert\", \"mid\":mid, \"aid\":id};\n\t//console.log(JSON.stringify(cmd_data));\n\tcon.send(JSON.stringify(cmd_data)); \t\t\n}",
"function alertBtn(text){\n if(text === 'Start'){\n acknowledge();\n } else {\n closeAlert();\n }\n }",
"function resetAlert () {\r\n alertify.set({\r\n labels : {\r\n ok : \"OK\",\r\n cancel : \"Cancel\"\r\n },\r\n delay : 5000,\r\n buttonReverse : false,\r\n buttonFocus : \"ok\"\r\n });\r\n }",
"function resetAlert () {\n\talertify.set({\n\t\tlabels : {\n\t\t\tok : \"OK\",\n\t\t\tcancel : \"Cancel\"\n\t\t},\n\t\tdelay : 5000,\n\t\tbuttonReverse : false,\n\t\tbuttonFocus : \"ok\"\n\t});\n }",
"ackAll() {\n this._channel && this._channel.ackAll();\n }",
"publishClearAllAlert() {\r\n const alertTitle = \"INFO:\";\r\n const alertDescription = \"Your recent calculation has been deleted\";\r\n const alertNote = \"You can now start entering a new calculation\";\r\n\r\n const newAlert = this.__buildAlert(alertTypeEnum.INFO, alertTitle, alertDescription, alertNote, false);\r\n\r\n this.__parseMessageToDocument(newAlert);\r\n this.__waitAndReturnToDefaultAlert(2500);\r\n }",
"function clear_alert() {\n let action = {\n type: 'clear/set',\n data: \"\",\n }\n store.dispatch(action);\n }",
"function DT_AlertBoxResponse(idNumber, buttonTitle)\n{\n //Create an \"AlertResponse\" event and pass it the data.\n //EventListeners in the app handle what to do (then delete themselves)\n \n var AlertEvent = document.createEvent(\"Event\");\n AlertEvent.response = buttonTitle;\n \n AlertEvent.initEvent(idNumber,true,true);\n document.dispatchEvent(AlertEvent);\n}",
"function triggerUpdateMessaageAlert(msg)\n{\n\t//Defining basicConf parameter for alert\n\tvar basicConf = {message:msg ,alertType: constants.ALERT_TYPE_INFO, alertHandler: handle2};\n\t//Defining pspConf parameter for alert\n\tvar pspConf = {};\n\t//Alert definition\n\tvar infoAlert = kony.ui.Alert(basicConf,pspConf);\n\tfunction handle2(response)\n\t{\n\t\tkony.print(JSON.stringify(response));\n\t\tvar response = JSON.stringify(response);\n\t\tif(response == \"true\")\n\t\t{\n\t\t frmEvent.txtBoxEventId.text=null;\n\t\t}\n\t}\t\n}",
"confirmationAlert(title, message, positiveText, negativeText, positiveOnPress, negativeOnPress, cancelableFlag){\n Alert.alert(\n title,\n message,\n [\n {text: negativeText, onPress: negativeOnPress, style: 'cancel',},\n {text: positiveText, onPress: positiveOnPress, style : 'default'},\n ],\n {cancelable: cancelableFlag},\n ); \n }",
"function resetAlerts() {\n}",
"_buttonClick() {\n Alert.alert(\n 'Alert Title',\n 'My Alert Msg',\n [\n {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},\n {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},\n {text: 'OK', onPress: () => console.log('OK Pressed')},\n ],\n { cancelable: false }\n );\n }",
"function consume_alert() { //to override normal alert behavior\n if (_alert) return;\n var _alert = window.alert;\n window.alert = function(message) {\n $.pnotify({\n text: message\n });\n };\n}",
"clear() {\n EventsHandler.broadcast('closeAlertMessage', new Date())\n }",
"relaxAgent(){\n this.setAlertRemaining(-1);\n this.setAlerted(false);\n }",
"function send_alert(id,mid){\n\t$(\"#alert_\"+mid+\"_\"+id+\"_send\").text(\"hourglass_empty\");\n\n\tvar cmd_data = { \"cmd\":\"send_alert\", \"mid\":mid, \"aid\":id};\n\t//console.log(JSON.stringify(cmd_data));\n\tcon.send(JSON.stringify(cmd_data)); \t\t\n}",
"function formatAlertMsg(tgtWin)\n{\n if ( typeof AlertMsg == \"string\" &&\n AlertMsg == \"updateOK\" ) {\n AlertMsg = msgtext(\"Save_Successful\");\n if ( typeof ahdtop.saveAckMsgNum == \"number\" &&\n ahdtop.saveAckMsgNum > 0 ) {\n if ( typeof ahdtop.saveAckMsgObjectName == \"string\" && \n ahdtop.saveAckMsgObjectName.length > 0 )\n {\n // Replace all \"<\" and \">\" with corresponding char constants so name is not interpreted as a html tags.\n ahdtop.saveAckMsgObjectName = ahdtop.saveAckMsgObjectName.replace(/>/gi,'>'); // > (greater than)\n ahdtop.saveAckMsgObjectName = ahdtop.saveAckMsgObjectName.replace(/</gi,'<'); // < (less than)\n }\n AlertMsg += msgtext(ahdtop.saveAckMsgNum,\n \" \" + ahdtop.saveAckMsgFactoryName,\n \" \" + ahdtop.saveAckMsgObjectName );\n\t\t//Check fo rexistance of variable 'saveAckMsgExtra'\n\t\t//if value in it is not empty, append it to 'AlertMsg'\n\t\t//E.g. value for \"saveAckMsgExtra\" is initialized usign a local attribute\n\t\t//of change object\n\t\tif( typeof saveAckMsgExtra != \"undefined\" && saveAckMsgExtra != '' )\n\t\t{\n\t\t\tAlertMsg += \"<br/>\"+ saveAckMsgExtra;\n\t\t}\n\t\tif(typeof reset_update_lrel == \"function\") reset_update_lrel();\n }\n if ( typeof tgtWin == \"object\" && tgtWin != null )\n tgtWin.AlertMsg = \"\";\n }\n ahdtop.saveAckMsgNum = void(0);\n ahdtop.saveAckMsgFactoryName = void(0);\n ahdtop.saveAckMsgObjectName = void(0);\n}",
"function bind_alert_to_button(){\n document.getElementById(\"alert\").onclick = send_alert;\n}",
"confirmationAlertwithOptionButton(title, message, positiveText, negativeText, skipText, positiveOnPress, negativeOnPress, skipOnPress, cancelableFlag ){\n Alert.alert(\n title,\n message,\n [\n {text: skipText, onPress: skipOnPress, style: 'destructive',},\n {text: negativeText, onPress: negativeOnPress, style : 'cancel'},\n {text: positiveText, onPress: positiveOnPress, style : 'default'},\n ],\n {cancelable: cancelableFlag},\n ); \n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
12 Create a function called addToEnd that accept an array and value and return the entire array with add this value to the end of this array var nums= [1,2,3,8,9] Ex: addToEnd(nums,55) => [1,2,3,8,55] try more cases by your self | function addToEnd(arr,x){
arr.splice(nums.length-1, 1,x);
return arr;
} | [
"function addToEnd(number,value){\n return number.push(value);\n}",
"function addToEnd(arr,value){\r\n\tarr.splice(arr.length,0,value)\r\n\treturn arr\r\n}",
"function addToEnd(arr, val) {\n\n arr[arr.length - 1] = val\n\n return arr\n}",
"function addToEnd(arr,x){\n\tarr.push(x);\n\treturn arr;\n}",
"function addToEnd (arr,val){\n\tarr.pop();\n\tarr.push(val);\n\treturn arr;\n}",
"function addToEnd (x,y)\n{\n var l = x.length;\n return x[l-1]=y;\n\n}",
"function addToArrayEnd(array, newArrayItem) {\n // console.log(array, newArrayItem);\n array.push(newArrayItem);\n return array;\n}",
"function addLast(array, val) {\n if (Array.isArray(val)) return array.concat(val);\n return array.concat([val]);\n } // -- #### addFirst()",
"function makeEnds(nums){\n return [nums[0], nums[nums.length-1]]\n}",
"function rangeOfNumbers(startNum, endNum) { // assuming startNum is less than or equal to the endNum\n if (startNum === endNum) {\n return [startNum];\n } else {\n // let arr = rangeOfNumbers(startNum+1, endNum); // add to the end of the element\n let arr = rangeOfNumbers(startNum, endNum-1);\n arr.push(endNum);\n return arr;\n }\n}",
"function addLast(array, val) {\n if (Array.isArray(val)) return array.concat(val);\n return array.concat([val]);\n} // -- #### addFirst()",
"function addElementToEndOfArray (array, element){\n array.push(element)\n return array\n}",
"function makeEnds(array1, array2){\n array2.push(array1[0],array1[array1.length-1]) \n console.log(array2) \n}",
"function pushToEnd(arr, value) {\n const index = arr.indexOf(value);\n if (index > -1) {\n arr.splice(index, 1);\n arr.push(value);\n }\n }",
"function pushToEnd(arr, value) {\n var index = arr.indexOf(value);\n if (index > -1) {\n arr.splice(index, 1);\n arr.push(value);\n }\n}",
"function pushToEnd(arr, value) {\n var index = arr.indexOf(value);\n\n if (index > -1) {\n arr.splice(index, 1);\n arr.push(value);\n }\n}",
"function addElementToEndOfArray(array, element){\n var newArray = [...array, element]\n return newArray\n}",
"function addLast(array, val) {\n if (Array.isArray(val)) return array.concat(val);\n return array.concat([val]);\n}",
"function addAtTheBeginning(arr) {\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a dataflow operator. | function parseOperator(spec, ctx) {
if (isOperator(spec.type) || !spec.type) {
ctx.operator(spec,
spec.update ? operatorExpression(spec.update, ctx) : null);
} else {
ctx.transform(spec, spec.type);
}
} | [
"function parseOperator(spec) {\n const ctx = this;\n if (isOperator(spec.type) || !spec.type) {\n ctx.operator(spec, spec.update ? ctx.operatorExpression(spec.update) : null);\n } else {\n ctx.transform(spec, spec.type);\n }\n }",
"function parseOperatorParameters(spec,ctx){var op,params;if(spec.params){if(!(op=ctx.get(spec.id))){error$1('Invalid operator id: '+spec.id);}params=parseParameters$1(spec.params,ctx);ctx.dataflow.connect(op,op.parameters(params));}}",
"function parseOperator(spec) {\n const ctx = this;\n\n if (isOperator(spec.type) || !spec.type) {\n ctx.operator(spec, spec.update ? ctx.operatorExpression(spec.update) : null);\n } else {\n ctx.transform(spec, spec.type);\n }\n }",
"function parseOperator(spec) {\n const ctx = this;\n\n if (isOperator(spec.type) || !spec.type) {\n ctx.operator(spec, spec.update ? ctx.operatorExpression(spec.update) : null);\n } else {\n ctx.transform(spec, spec.type);\n }\n}",
"parseOperator() {\n if (this.peek().name == 'block-start') {\n return this.parseBlock();\n } else {\n return [this.parsePrimOp()];\n }\n }",
"function parseDataflow(spec, ctx) {\n var operators = spec.operators || [];\n\n // parse background\n if (spec.background) {\n ctx.background = spec.background;\n }\n\n // parse event configuration\n if (spec.eventConfig) {\n ctx.eventConfig = spec.eventConfig;\n }\n\n // parse operators\n operators.forEach(function(entry) {\n parseOperator(entry, ctx);\n });\n\n // parse operator parameters\n operators.forEach(function(entry) {\n parseOperatorParameters(entry, ctx);\n });\n\n // parse streams\n (spec.streams || []).forEach(function(entry) {\n parseStream$2(entry, ctx);\n });\n\n // parse updates\n (spec.updates || []).forEach(function(entry) {\n parseUpdate$1(entry, ctx);\n });\n\n return ctx.resolve();\n }",
"function parseDataflow(spec, ctx) {\n var operators = spec.operators || [];\n\n // parse background\n if (spec.background) {\n ctx.background = spec.background;\n }\n\n // parse event configuration\n if (spec.eventConfig) {\n ctx.eventConfig = spec.eventConfig;\n }\n\n // parse operators\n operators.forEach(function(entry) {\n parseOperator(entry, ctx);\n });\n\n // parse operator parameters\n operators.forEach(function(entry) {\n parseOperatorParameters(entry, ctx);\n });\n\n // parse streams\n (spec.streams || []).forEach(function(entry) {\n parseStream(entry, ctx);\n });\n\n // parse updates\n (spec.updates || []).forEach(function(entry) {\n parseUpdate(entry, ctx);\n });\n\n return ctx.resolve();\n }",
"function parseOperatorParameters(spec, ctx) {\n var op, params;\n if (spec.params) {\n if (!(op = ctx.get(spec.id))) {\n error('Invalid operator id: ' + spec.id);\n }\n params = parseParameters$1(spec.params, ctx);\n ctx.dataflow.connect(op, op.parameters(params));\n }\n }",
"function parseOperatorParameters(spec) {\n const ctx = this;\n if (spec.params) {\n const op = ctx.get(spec.id);\n if (!op) vegaUtil.error('Invalid operator id: ' + spec.id);\n ctx.dataflow.connect(op, op.parameters(ctx.parseParameters(spec.params), spec.react, spec.initonly));\n }\n }",
"function parseOperatorParameters(spec) {\n const ctx = this;\n\n if (spec.params) {\n const op = ctx.get(spec.id);\n if (!op) vegaUtil.error('Invalid operator id: ' + spec.id);\n ctx.dataflow.connect(op, op.parameters(ctx.parseParameters(spec.params), spec.react, spec.initonly));\n }\n }",
"function parseOperatorParameters(spec) {\n const ctx = this;\n\n if (spec.params) {\n const op = ctx.get(spec.id);\n if (!op) (0, _vegaUtil.error)('Invalid operator id: ' + spec.id);\n ctx.dataflow.connect(op, op.parameters(ctx.parseParameters(spec.params), spec.react, spec.initonly));\n }\n}",
"function parseOperatorParameters(spec, ctx) {\n if (spec.params) {\n var op = ctx.get(spec.id);\n if (!op) vegaUtil.error('Invalid operator id: ' + spec.id);\n ctx.dataflow.connect(op, op.parameters(\n parseParameters(spec.params, ctx),\n spec.react,\n spec.initonly\n ));\n }\n }",
"function parse_operator_ParseNode(pWord) {\n\t//----Debugging------------------------------------------\n\t// The following alert-Command is useful for debugging \n\t//alert(\"parsenode.js:parse_operator(pWord)-Call\")\n\t//----Create Object/Instance of ParseNode----\n\t// var vMyInstance = new ParseNode();\n\t// vMyInstance.parse_operator(pWord);\n\t//-------------------------------------------------------\n\tvar vOperator = \"\";\n\tvar vFound = pWord.indexOf(\"=\");\n\tif (vFound >0) {\n\t\tvOperator = \"=\";\n\t};\n\tvFound = pWord.indexOf(\"+\");\n\tif (vFound >0) {\n\t\tvOperator = \"+\";\n\t};\n\tvFound = pWord.indexOf(\"-\");\n\tif (vFound >0) {\n\t\tvOperator = \"-\";\n\t};\n\tvar vBlankPos = pWord.indexOf(\" \");\n\tif ((vBlankPos>=0) && (vBlankPos<vFound)) {\n\t\tvOperator = \"\";\n\t}\n\treturn vOperator;\n\n}",
"parseLogicOperator(inst) {\n if(!/^(\\s*(<=|>=|!=|==|>|<|=)\\s*)/.test(inst))\n if(!/^(\\s*\\b(x?or|and)\\b\\s*)/.test(inst))\n return false\n\n const log_op_block = RegExp.$1\n const log_op = RegExp.$2\n\n return {\n original: inst,\n remain: inst.substr(log_op_block.length),\n parsed: {\n type: 'log_op',\n args: {\n value: log_op\n }\n }\n }\n }",
"function parseFilterOperation(operators,filterString,p) {\n\tvar operator, operand, bracketPos;\n\t// Skip the starting square bracket\n\tif(filterString.charAt(p++) !== \"[\") {\n\t\tthrow \"Missing [ in filter expression\";\n\t}\n\t// Process each operator in turn\n\tdo {\n\t\toperator = {};\n\t\t// Check for an operator prefix\n\t\tif(filterString.charAt(p) === \"!\") {\n\t\t\toperator.prefix = filterString.charAt(p++);\n\t\t}\n\t\t// Get the operator name\n\t\tbracketPos = filterString.indexOf(\"[\",p);\n\t\tif(bracketPos === -1) {\n\t\t\tthrow \"Missing [ in filter expression\";\n\t\t}\n\t\toperator.operator = filterString.substring(p,bracketPos);\n\t\tif(operator.operator === \"\") {\n\t\t\toperator.operator = \"title\";\n\t\t}\n\t\tp = bracketPos + 1;\n\t\t// Get the operand\n\t\tbracketPos = filterString.indexOf(\"]\",p);\n\t\tif(bracketPos === -1) {\n\t\t\tthrow \"Missing ] in filter expression\";\n\t\t}\n\t\toperator.operand = filterString.substring(p,bracketPos);\n\t\tp = bracketPos + 1;\n\t\t// Push this operator\n\t\toperators.push(operator);\n\t} while(filterString.charAt(p) !== \"]\");\n\t// Skip the ending square bracket\n\tif(filterString.charAt(p++) !== \"]\") {\n\t\tthrow \"Missing ] in filter expression\";\n\t}\n\t// Return the parsing position\n\treturn p;\n}",
"function readOperator() {\n\t\t\t\tvar operator = readWhile(function (char) { return isOperator(char); });\n return operator;\n }",
"function parse (spec) {\n const ctx = this,\n operators = spec.operators || []; // parse background\n\n if (spec.background) {\n ctx.background = spec.background;\n } // parse event configuration\n\n\n if (spec.eventConfig) {\n ctx.eventConfig = spec.eventConfig;\n } // parse locale configuration\n\n\n if (spec.locale) {\n ctx.locale = spec.locale;\n } // parse operators\n\n\n operators.forEach(entry => ctx.parseOperator(entry)); // parse operator parameters\n\n operators.forEach(entry => ctx.parseOperatorParameters(entry)); // parse streams\n\n (spec.streams || []).forEach(entry => ctx.parseStream(entry)); // parse updates\n\n (spec.updates || []).forEach(entry => ctx.parseUpdate(entry));\n return ctx.resolve();\n }",
"function parse (spec) {\n const ctx = this,\n operators = spec.operators || []; // parse background\n\n if (spec.background) {\n ctx.background = spec.background;\n } // parse event configuration\n\n\n if (spec.eventConfig) {\n ctx.eventConfig = spec.eventConfig;\n } // parse locale configuration\n\n\n if (spec.locale) {\n ctx.locale = spec.locale;\n } // parse operators\n\n\n operators.forEach(entry => ctx.parseOperator(entry)); // parse operator parameters\n\n operators.forEach(entry => ctx.parseOperatorParameters(entry)); // parse streams\n\n (spec.streams || []).forEach(entry => ctx.parseStream(entry)); // parse updates\n\n (spec.updates || []).forEach(entry => ctx.parseUpdate(entry));\n return ctx.resolve();\n}",
"readAndReturnOperator() {\n let ss = this.ss;\n let str = ss.read();\n while (!ss.eof() && str.length < operatorsAndKeywords_4.longestOperatorLength) {\n str += ss.read();\n }\n // trim down to longest valid operator\n while (!(str in operatorsAndKeywords_5.allOperators)) {\n str = str.substring(0, str.length - 1);\n ss.unread();\n }\n return str;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create two arrays, initialize their elements and display them | function start()
{
var n1 = new Array( 5 ); // allocate five-elements array
var n2 = new Array(); // allocate empty array
// assign values to each element of array n1
var length = n1.length; // get array's length once before the loop
for ( var i = 0; i < length; ++i )
{
n1[ i ] = i;
} // end for
// create and initialize five elements in array n2
for ( i = 0; i < 5; ++i )
{
n2[ i ] = i;
} // end for
outputArray( "Array n1:", n1, document.getElementById("output1" ) );
outputArray( "Array n2:", n2, document.getElementById("output2" ) );
} // end function start | [
"function start()\n{\n var n1 = new Array( 5 ); // allocate five-element array\n var n2 = new Array(); // allocate empty array \n \n // assign values to each element of array n1 \n var length = n1.length; // get array's length once before the loop\n\n for ( var i = 0; i < n1.length; ++i ) \n {\n n1[ i ] = i;\n } // end for\n \n // create and initialize five elements in array n2\n for ( i = 0; i < 5; ++i )\n {\n n2[ i ] = i;\n } // end for\n\n outputArray( \"Array n1:\", n1, document.getElementById( \"output1\" ) );\n outputArray( \"Array n2:\", n2, document.getElementById( \"output2\" ) );\n} // end function start",
"function start() {\n var n1 = new Array(5);\n var n2 = new Array();\n\n var length = n1.length;\n\n for (var i = 0; i < length; ++i) {\n n1[i] = i;\n }\n\n for (i = 0; i < 5; ++i) {\n n2[i] = i;\n }\n \n outputArray(\"Array n1:\", n1, document.getElementById(\"output1\") );\n outputArray(\"Array n2:\", n2, document.getElementById(\"output2\") );\n}",
"function initializeArrays(){\n //Initializing walls two dimensional array\n for ( i = 0; i < 30; i++ ) {\n walls[i] = [];\n for ( j = 1; j < 22; j++ ) {\n walls[i][j] = 0;\n }\n }\n\n //Initializing dots two dimensional array\n for ( i = 0; i < 30; i++ ) {\n dots[i] = [];\n for ( j = 1; j < 22; j++ ) {\n dots[i][j] = 0;\n }\n }\n\n //Initializing cookies two dimensional array\n for ( i = 0; i < 30; i++ ) {\n cookies[i] = [];\n for ( j = 1; j < 22; j++ ) {\n cookies[i][j] = 0;\n }\n }\n}",
"function renderArrays() {\n for (var i = 0; i < allProducts.length; i++){\n namesArray.push(allProducts[i].name);\n votesArray.push(allProducts[i].votes);\n viewsArray.push(allProducts[i].views);\n }\n}",
"function createArrayWithTwoNumbers() {\n}",
"function initialise_display_result_array(){\n\n//Fill the memorygame_display_array\nfor(var i = 0; i<memorygame_display_array.length; i++){\n\nif(i <= 7){\nmemorygame_display_array[i] = memorygame_exercises[i];\n}\nelse{\nmemorygame_display_array[i] = memorygame_results[i-8];\n}\n}//End for loop\n\n//Fill the memorygame_result_array\nfor(var i = 0; i<2; i++){\n\nfor(var j = 0; j<8; j++){\nmemorygame_result_array[(i*8)+j] = memorygame_results[j];\n}//End first for\n\n} //End second for\n\nrandomize_memorygame_arrays();\n\n}",
"function multiDimensi(num1, num2){\n var arr1 = [];\n var arr2 = [];\n var i = 1;\n var j = 1;\n var k = 0;\n var x = 0;\n var y = 0;\n var hehe = num2;\n\n // [1-num2]\n\n for(i; i <= num1*num2 ; i++){\n arr1.push(i) \n }\n\n // Memasukan arr1 yang telah dibagi kedalam arr2\n\n for(j; j <= num1; j++){\n y += hehe\n arr2.push(arr1.slice(x, y))\n x += hehe\n }\n\n // Mengganti angka pertama dan angka terahkir arr1 yang telah dibagi menjadi \"First\" dan \"Last\"\n \n for (k; k < num1; k++){\n arr2[k].shift()\n arr2[k].unshift(\"First\")\n arr2[k].pop()\n arr2[k].push(\"Last\")\n }\n return arr2\n}",
"function alternatingElements(array1, array2) {\n\n let emptyArray = [];\n\n for (let i = 0, j = 0; i < array1.length, j < array2.length; i++, j++) {\n emptyArray[emptyArray.length] = array1[i];\n emptyArray[emptyArray.length] = array2[j];\n \n }\n return emptyArray;\n}",
"function twoArraysIntoObject()\n{\n let a=[0,1,2,3];\n let b=['a','b','c','d'];\n let obj={};\n if(a.length!=b.length || a.length==0 || b.length==0)\n {\n console.log(\"Not possible\");\n }\n else\n {\n for(let i=0;i<a.length;i++)\n {\n obj[a[i]]=b[i];\n }\n }\n console.log(obj);\n}",
"function showHide(array1,array2) {\n for(i=0;i<array1.length;i++){\n $(array1[i]).show();\n }\n for(i=0;i<array2.length;i++){\n $(array2[i]).hide();\n }\n }",
"arrayGenerate(rows, cols) {\n\n var array = [];\n var i, j;\n for (i = 0; i < rows; i++) {\n array[i] = [];\n\n for (j = 0; j < cols; j++) {\n array[i][j] = rd.question(\" Enter one array value \" + i\n + \" enter another array value \" + j + \" ::\\n\");\n }\n }\n\n console.log(array);\n }",
"function generateUnitArrays() {\n\tcount = units.barrack.length + units.stable.length + units.garage.length; //Amount of units in the game\n\tallUnits = units.barrack.concat(units.stable).concat(units.garage); //Array with all the units in the game\n\tcurrentUnits = Array(count).fill(0);\n\tdisplayUnits = Array(count).fill(null);\n\tresearchedUnits = Array(count).fill(false);\n}",
"function problem14(arr1, arr2) {\n var combinedArray = [];\n // start coding here\n\n\n // done coding here\n return combinedArray;\n}",
"function plusTwo(array1, array2){\n var arrayNew =[array1, array2]\n console.log (\"[\" + arrayNew.toString() + \"]\")\n}",
"function createBabyArrays(){\n for (var k = 0; k < num1; k++) {\n tempArray = null;\n tempArray = outputArray.splice(k, num1);\n outputArray.unshift(tempArray);\n };\n }",
"function append(array1, array2){\n for(var i = 0, len = array2.length; i < len; i++){\n array1.push(array2[i]);\n }\n }",
"function arrayInjector (firstData, index, secondData) {\n // Code disini\n var newArr=[];\n for(var i=0;i<firstData.length;i++) {\n if(i===index) {\n for(var j=0;j<secondData.length;j++) {\n newArr.push(secondData[j]);\n }newArr.push(firstData[i]);\n }else {\n newArr.push(firstData[i]);\n }\n \n }\nreturn newArr; \n}",
"function createArrays() {\n phraseArray = [];\n blankArray = [];\n phraseArray = secretPhrase.split(\"\");\n phraseArray.forEach( () => blankArray.push(\"_\"));\n spanSecretRandom.innerHTML = blankArray.join(\" \");\n}",
"function randomArray(arr1, arr2) {\n let whichArry = Math.round(Math.random());\n if (whichArry === 0) {\n thisArry = arr1;\n } else {\n thisArry = arr2;\n }\n for (i=0; i < 2; i++){\n console.log(randomSelection(thisArry));\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate an oldstyle exception return. | function gen_exception_return(/* DisasContext * */ s)
{
gen_op_movl_reg_TN[0][15]();
gen_op_movl_T0_spsr();
gen_op_movl_cpsr_T0(0xffffffff);
s.is_jmp = 2;
} | [
"function Exception() {}",
"static throwError() { return new Error(...arguments); }",
"function Exception() {\n return;\n}",
"function exception_example_return( ) {\n\n\t//\n\t//\tTRY Block\n\t//\n\ttry {\n\t\t//\n\t\t// Werfe eine neue Exception vom Typ MyError\n\t\t//\n\t//\tthrow new MyError(\"Banane\")\n\t\treturn -1;\n\t}\n\t//\n\t//\tCATCH Block\n\t//\n\tcatch( err ) {\n\t\t\n\t\t//\n\t\t// Teste, ob ein Fehler vom Typ MyError geworfen wurde\n\t\t//\t\n\t\tif( err instanceof MyError ) {\n\t\t\tconsole.warn(\"A MyError occured\" ,err);\n\t\t}\n\t\t\n\t\t//\n\t\t// War die Exception nicht vom Typ MyError dann werfe die Exception weiter\n\t\t//\n\t\telse {\n\t\t\tthrow err;\n\t\t}\n\t\treturn -2;\n\t}\n\tfinally {\n\t\treturn 3;\n\t}\n}",
"function genCatch(invMsg){\n if(!invMsg)\n return TRY_END; \n\n return TRY_END.replace('e.getMessage()', `${invMsg.endsWith(';') ? invMsg.split(';')[0] : invMsg }`); \n}",
"function pythonize_exceptions(object, exception_constructor) {}",
"function f1() {\n\n return new Error(\"From f1(): an error has occurred!\");\n \n}",
"function Ra() {\n var returnVal = returnStack.pop();\n wrappedExceptionVal = undefined;\n return returnVal;\n }",
"function Serializer$CatchStatement$E() {\n}",
"function throw_body() {\n var code1 = \"var old_yc = $yc_value\";\n var code2 = \"$yc_value = function() { throw value; }\";\n var code3 = \"try { void this.next(); } finally { $yc_value = old_yc }\";\n return [ ast_gen(code1),\n ast_gen(code2),\n ast_gen(code3) ];\n}",
"function caml_wrap_exception(e) {\n if(e instanceof Array) return e;\n //Stack_overflow: chrome, safari\n if(joo_global_object.RangeError\n && e instanceof joo_global_object.RangeError\n && e.message\n && e.message.match(/maximum call stack/i))\n return caml_return_exn_constant(caml_global_data.Stack_overflow);\n //Stack_overflow: firefox\n if(joo_global_object.InternalError\n && e instanceof joo_global_object.InternalError\n && e.message\n && e.message.match(/too much recursion/i))\n return caml_return_exn_constant(caml_global_data.Stack_overflow);\n //Wrap Error in Js.Error exception\n if(e instanceof joo_global_object.Error)\n return [0,caml_named_value(\"jsError\"),e];\n //fallback: wrapped in Failure\n return [0,caml_global_data.Failure,caml_js_to_string (String(e))];\n}",
"static raise(e) { return new IOPure(Failure(e)); }",
"function caml_wrap_exception(e) {\n if(e instanceof Array) return e;\n //Stack_overflow: chrome, safari\n if(joo_global_object.RangeError\n && e instanceof joo_global_object.RangeError\n && e.message\n && e.message.match(/maximum call stack/i))\n return caml_return_exn_constant(caml_global_data.Stack_overflow);\n //Stack_overflow: firefox\n if(joo_global_object.InternalError\n && e instanceof joo_global_object.InternalError\n && e.message\n && e.message.match(/too much recursion/i))\n return caml_return_exn_constant(caml_global_data.Stack_overflow);\n //Wrap Error in Js.Error exception\n if(e instanceof joo_global_object.Error && caml_named_value(\"jsError\"))\n return [0,caml_named_value(\"jsError\"),e];\n //fallback: wrapped in Failure\n return [0,caml_global_data.Failure,caml_js_to_string (String(e))];\n}",
"function makeError(code, msg) {\n return Object.assign(new Error(msg), { code: code });\n}",
"function makeError(err) {\n var einput;\n\n var defautls = {\n index: furthest,\n filename: env.filename,\n message: 'Parse error.',\n line: 0,\n column: -1\n };\n for (var prop in defautls) {\n if (err[prop] === 0) {\n err[prop] = defautls[prop];\n }\n }\n\n if (err.filename && that.env.inputs && that.env.inputs[err.filename]) {\n einput = that.env.inputs[err.filename];\n } else {\n einput = input;\n }\n\n err.line = (einput.slice(0, err.index).match(/\\n/g) || '').length + 1;\n for (var n = err.index; n >= 0 && einput.charAt(n) !== '\\n'; n--) {\n err.column++;\n }\n return new Error([err.filename, err.line, err.column, err.message].join(\";\"));\n }",
"function Ra() {\n var returnVal = returnStack.pop();\n exceptionVal = undefined;\n return returnVal;\n }",
"function writeThrow(expression,operationLocation){lastOperationWasAbrupt=true;lastOperationWasCompletion=true;writeStatement(ts.setTextRange(ts.createThrow(expression),operationLocation));}",
"static makeReturnEnvelope(originalEnvelope, err){\n const returnEnvelope = new CrossIslandEnvelope(originalEnvelope.origin, originalEnvelope, originalEnvelope.destination);\n returnEnvelope.setReturn(err);\n return returnEnvelope;\n }",
"function $rt_throwExc(excVal)\n{\n $ir_throw(excVal);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handles pushing the zoom level up button | function ControllerMagUp(e) {
'use strict';
var sel = this.parentNode.zoomsel;
magzoom += 1;
if (magzoom === 10) {
magzoom = 9;
}
checkZoomLevel(magzoom, this.parentNode);
sel.selectedIndex = magzoom;
zoomImage(sel.options[sel.selectedIndex].value, this.parentNode.canvas);
haveZoomed = true;
// if the zoom is 100% or greater, we need to force pan mode
if (magzoom >= 5) {
this.parentNode.buttonPan.onclick();
}
} | [
"function ControllerMagUp(e) {\n var sel = this.parentNode.zoomsel;\n // removed this... but it requires that magzoom *always* be set correctly\n //if (sel.selectedIndex == 0 || sel.selectedIndex == 1) {\n //magzoom = this.parentNode.canvas.origZoom;\n //}\n\n magzoom += 1;\n if (magzoom == 10) magzoom = 9;\n\n checkZoomLevel(magzoom, this.parentNode);\n sel.selectedIndex = magzoom;\n ZoomImage(sel.options[sel.selectedIndex].value, this.parentNode.canvas);\n haveZoomed = true;\n\n // if the zoom is 100% or greater, we need to force pan mode\n if (magzoom >= 5) this.parentNode.buttonPan.onclick();\n\n}",
"_handleButtonZoomIn()\n {\n this.guiChannel.request(GUI_EVENTS.REQUEST__WORKFLOWBUILDER_GUI_ZOOM_IN);\n }",
"handleClick_zoomIn()\n {\n if (this.factor < 85) \n {\n this.factor += 5;\n this.toggleSize();\n this.toggleVisibility();\n this.render();\n }\n }",
"_handleButtonZoomOut()\n {\n this.guiChannel.request(GUI_EVENTS.REQUEST__WORKFLOWBUILDER_GUI_ZOOM_OUT);\n }",
"handleClick_zoomOut()\n {\n if (this.factor > 20) \n {\n this.factor -= 5;\n this.toggleSize();\n this.toggleVisibility();\n this.render();\n }\n }",
"function ZoomButton() {\n\tif(gridZoom == 10) {\n\t\tgridZoom = 3;\n\t}\n\telse {\n\t\tgridZoom = 10;\n\t\tUpdateGraphicsZoomMap();\n\t}\n\tUpdateTileMap();\n\tUpdateNoteGrid();\n}",
"zoomIn () {}",
"afterZoom() {}",
"function zoomButtonClicked(which_button) {\n\t\t\tswitch(which_button) {\n\t\t\t\tcase \"zoom_in\":\n\t\t\t\t\tzoomInByClick(); break;\n\t\t\t\tcase \"zoom_out\":\n\t\t\t\t\tzoomOutByClick(); break;\n\t\t\t\tdefault: break;\n\t\t\t}\n\t\t}",
"function ControllerZoomLevel(e) {\n var sel = this.parentNode.zoomsel;\n magzoom = sel.selectedIndex;\n checkZoomLevel(magzoom, this.parentNode);\n ZoomImage(sel.options[sel.selectedIndex].value, this.parentNode.canvas);\n}",
"_zoomButton(evt) {\n this.setMagnification(this.$(evt.currentTarget).data('value'));\n this._zoomSliderInput();\n }",
"function ControllerMagDown(e) {\n var sel = this.parentNode.zoomsel;\n if (sel.selectedIndex == 0 || sel.selectedIndex == 1) {\n magzoom = this.parentNode.canvas.origZoom;\n }\n\n if (haveZoomed)\n magzoom -= 1;\n if (magzoom <= 1) magzoom = 2;\n\n checkZoomLevel(magzoom, this.parentNode);\n sel.selectedIndex = magzoom;\n ZoomImage(sel.options[sel.selectedIndex].value, this.parentNode.canvas);\n haveZoomed = true;\n}",
"function handleZoomInButtonClick () {\n if ('tracker' in svl) svl.tracker.push('Click_ZoomIn');\n\n if (!status.disableZoomIn) {\n var pov = svl.panorama.getPov();\n setZoom(pov.zoom + 1);\n svl.canvas.clear().render2();\n }\n }",
"function ControllerZoomLevel(e) {\r\n 'use strict';\r\n var sel = this.parentNode.zoomsel;\r\n magzoom = sel.selectedIndex;\r\n checkZoomLevel(magzoom, this.parentNode);\r\n zoomImage(sel.options[sel.selectedIndex].value, this.parentNode.canvas);\r\n}",
"function move_screen()\r\n{\r\n\tzoomClicked = true;\r\n\tzoomCount++;\r\n\r\n}",
"function zoomHandler() {\n moveHandler();\n }",
"_handleButtonZoomReset()\n {\n this.guiChannel.request(GUI_EVENTS.REQUEST__WORKFLOWBUILDER_GUI_ZOOM_RESET);\n }",
"zoomOut () {}",
"beforeZoom() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
chase(chased) Sets velocity to move towards the position of the provided "chased" clown | chase(chased) {
// Determine the distance between the two
let dx = this.x - chased.x;
let dy = this.y - chased.y;
// If x distance is negative, the chaser should move right
if (dx < 0) {
this.vx = this.speed;
}
// If x distance positive the chaser should move left
else {
this.vx = -this.speed;
}
// If y distance is negative, the chaser should move up
if (dy < 0) {
this.vy = this.speed;
}
// If y distance is positive, the chaser should move down
else {
this.vy = -this.speed;
}
} | [
"function chase(chaser, chased) {\n // Determine the distance between the two\n let dx = chaser.x - chased.x;\n let dy = chaser.y - chased.y;\n\n // If x distance is negative, the chaser should move right\n if (dx < 0) {\n chaser.vx = chaser.speed;\n }\n // If x distance positive the chaser should move left\n else {\n chaser.vx = -chaser.speed;\n }\n\n // If y distance is negative, the chaser should move up\n if (dy < 0) {\n chaser.vy = chaser.speed;\n }\n // If y distance is positive, the chaser should move down\n else {\n chaser.vy = -chaser.speed;\n }\n}",
"chase() {\n let cx = this.x - player.x;\n let cy = this.y - player.y;\n\n if (cx < 0) {\n this.ax = this.accel;\n } else if (cx > 0) {\n this.ax = -this.accel;\n }\n\n if (cy < 0) {\n this.ay = this.accel;\n } else if (cy > 0) {\n this.ay = -this.accel;\n }\n\n this.vx = this.vx * this.friction;\n this.vy = this.vy * this.friction;\n\n this.x = this.x + this.vx;\n this.y = this.y + this.vy;\n\n this.vx = this.ax + this.vx;\n this.vx = constrain(this.vx, -this.MaxV, this.MaxV);\n this.vy = this.ay + this.vy;\n this.vy = constrain(this.vy, -this.MaxV, this.MaxV);\n }",
"initChase() {\n let size = Board.tileSize,\n yPos = DemoData.chase.playersY * size,\n dir = DemoData.chase.playersDir;\n \n this.createPlayers();\n this.blob.chaseDemo(dir, -size, yPos);\n this.blinky.chaseDemo(dir, -4 * size, yPos);\n this.pinky.chaseDemo(dir, -6 * size, yPos);\n this.inky.chaseDemo(dir, -8 * size, yPos);\n this.clyde.chaseDemo(dir, -10 * size, yPos);\n \n this.endPos = DemoData.chase.endTile * Board.tileSize;\n }",
"chase(scene,tank, deltaTime) {\n if (!this.bounder) return;\n if (this.dyingAnim.weight > 0) return;\n if (tank == undefined) return;\n this.zombieMesh.position = new BABYLON.Vector3(this.bounder.position.x,\n this.bounder.position.y, this.bounder.position.z);\n this.followGround(scene);\n // follow the tank\n //let tank = scene.getMeshByName(\"heroTank\");\n // let's compute the direction vector that goes from Dude to the tank\n let direction = tank.position.subtract(this.zombieMesh.position);\n let distance = direction.length(); // we take the vector that is not normalized, not the dir vector\n //console.log(distance);\n let dir = direction.normalize();\n // angle between Dude and tank, to set the new rotation.y of the Dude so that he will look towards the tank\n // make a drawing in the X/Z plan to uderstand....\n let alpha = Math.atan2(-dir.x, -dir.z);\n this.zombieMesh.rotation.y = alpha;\n this.frontVector = new BABYLON.Vector3(Math.sin(this.zombieMesh.rotation.y), 0, Math.cos(this.zombieMesh.rotation.y));\n // let make the Dude move towards the tank\n if(distance > 25) {\n this.setRunningAnim();\n this.bounder.moveWithCollisions(dir.multiplyByFloats(this.speed*0.5*deltaTime/16, this.speed*0.5*deltaTime/16, this.speed*0.5*deltaTime/16));\n //this.zombieMesh.moveWithCollisions(dir.multiplyByFloats(this.speed*0.5*deltaTime/16, this.speed*0.5*deltaTime/16, this.speed*0.5*deltaTime/16));\n }\n else { \n this.setBiteAnim();\n if (tank.Girl.slashAnim.weight != 1.0)\n tank.Girl.setImpactAnim();\n\n } \n }",
"move(dx, dy){\n\t\tconst velocity = new Pair(dx, dy);\n\t\tthis.velocity = velocity;\n\t}",
"velocityNext(distance, duckDir) {\n\t\t// If the duck is close, jump to horizontally converge on the duck.\n\t\t//console.log(distance)\n\t\tif (distance <= 570 && this.game.duck.state != \"dead\") {\n\t\t\tconsole.log(\"Going for the duck.\")\n\t\t\t// If the duck is extremely close, jump to kill the duck.\n\t\t\tif (distance < 220) {\n\t\t\t\tthis.velocityN = 300 * duckDir / 3 + 2 * this.game.duck.velocityX / 3\n\t\t\t} else {\n\t\t\t\tthis.velocityN = 450 * duckDir + this.game.duck.velocityX / 4\n\t\t\t}\n\t\t}\n\t\telse {// Jump at random.\n\t\t\tthis.velocityN = -250 + Math.random() * 500\n\t\t\tif (duckDir > 0) this.velocityN += 100\n\t\t\telse this.velocityN -= 100\n\t\t}\n\n\t\tif (this.velocityN > 0) {\n\t\t\tthis.facing = \"r\"\n\t\t}\n\t\telse {\n\t\t\tthis.facing = \"l\"\n\t\t}\n\t}",
"startChasing(skier) {\n this.x = skier.x;\n this.y = skier.y - (Constants.GAME_HEIGHT / 2);\n this.setDirection(skier.direction);\n this.chasing = true;\n }",
"function moveDown(x,y){\r\n\tif(x==horse1)\r\n\t\ty(horse1, 0.49);\r\n\telse if(x == horse2)\r\n\t\ty(horse2, 0.47);\r\n\telse if(x == horse3)\r\n\t\ty(horse3, 0.45);\r\n\telse if(x == horse4)\r\n\t\ty(horse4, 0.43);\r\n}",
"moveSkierDown() {\n this.y += this.speed;\n }",
"setBulletVector(dx, dy, bulletSpeed) {\n\t\tif (dx != 0) { this.dx = dx * bulletSpeed; }\n\t\tif (dy != 0) { this.dy = dy * bulletSpeed; }\n\t}",
"downer(velocity = 0) {\n this.jumping = false;\n this.velocityY = velocity;\n }",
"moveDown(){\n target = ypos + 100;\n }",
"moveCapy() {\n this.y += this.vel;\n this.vel += CONSTANTS.GRAVITY;\n \n \n /*\n Logic to determine whether or not to reset the velocity to the terminal\n velocity. Though switch case is not necessary, it is an alternative to \n if comments, and I prefer the clarity of switch cases.\n */\n if (Math.abs(this.vel) > CONSTANTS.TERMINAL_VEL) {\n switch(this.vel > 0) {\n case true:\n this.vel = CONSTANTS.TERMINAL_VEL;\n break;\n case false:\n this.vel = CONSTANTS.TERMINAL_VEL * -1;\n break;\n }\n }\n }",
"function dattack()\n{\n\tdragatk = Math.floor(Math.random()*4);\n\tif (drag == 0)\n\t{\n\t\tif (dragatk == 0)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*11+25);\n\t\t\tdflavortext = \"claws\";\n\t\t\tdragattackresult()\n\t\t\tstdhit()\n\t\t}\n\t\telse if (dragatk == 1)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*11+35);\n\t\t\tdflavortext = \"tail swipes\";\n\t\t\tdragattackresult()\n\t\t\tpow()\n\t\t}\n\t\telse if (dragatk == 2)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*25+50);\n\t\t\tdflavortext = \"bites\";\n\t\t\tdragattackresult()\n\t\t\tclaw2()\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*35+75);\n\t\t\tdflavortext = \"bum rushes\";\n\t\t\tdragattackresult()\n\t\t\tbumrush()\n\t\t}\n\t}\n\telse if (drag == 1)\n\t{\n\t\tif (dragatk == 0)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*21+15);\n\t\t\tdflavortext = \"rakes\";\n\t\t\tdragattackresult()\n\t\t\tstdhit()\n\t\t}\n\t\telse if (dragatk == 1)\n\t\t{\n\t\t\tdragdamage = Math.floor(hp/4);\n\t\t\tdflavortext = \"freezes\";\n\t\t\tdragattackresult()\n\t\t\t\tfor (var i = 0; i < 18; i++)\n\t\t\t\t{\n\t\t\t\t\tsetTimeout(\"dblizzardcanvas()\", (i*35))\n\t\t\t\t}\n\t\t}\n\t\telse if (dragatk == 2)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*150);\n\t\t\tdflavortext = \"headbutts\";\n\t\t\tdragattackresult()\n\t\t\tpow()\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*30+30);\n\t\t\tdflavortext = \"bites\";\n\t\t\tdragattackresult()\n\t\t\tclaw2()\n\t\t}\n\t}\n\telse if (drag == 2)\n\t{\n\t\tif (dragatk == 0)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*21+15);\n\t\t\tdflavortext = \"claws\";\n\t\t\tdragattackresult()\n\t\t\tstdhit()\n\t\t}\n\t\telse if (dragatk == 1)\n\t\t{\n\t\t\tdragdamage = Math.floor(hp/3);\n\t\t\tdflavortext = \"fires dark energy that burns\";\n\t\t\tdragattackresult()\n\t\t\tdargbeam()\n\t\t}\n\t\telse if (dragatk == 2)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*50+55);\n\t\t\tdflavortext = \"smacks\";\n\t\t\tdragattackresult()\n\t\t\tpow()\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*16+45);\n\t\t\tdflavortext = \"bites\";\n\t\t\tdragattackresult()\n\t\t\tclaw2()\n\t\t}\n\t}\n\telse if (drag == 3)\n\t{\n\t\tif (dragatk == 0)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*15+25);\n\t\t\tdflavortext = \"pokes\";\n\t\t\tdragattackresult()\n\t\t\tstdhit()\n\t\t}\n\t\telse if (dragatk == 1)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*40+25);\n\t\t\tdflavortext = \"bludgeons\";\n\t\t\tdragattackresult()\n\t\t\tpow()\n\t\t}\n\t\telse if (dragatk == 2)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*45+45);\n\t\t\tdflavortext = \"tail lashes\";\n\t\t\tdragattackresult()\n\t\t\tclaw2()\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*100+75);\n\t\t\tdflavortext = \"sprays golden quills that pierce\";\n\t\t\tdragattackresult()\n\t\t\tfor (var i = 0; i < 7; i++)\n\t\t\t\tsetTimeout('gneedle()', i*35)\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (dragatk == 0)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*21+10);\n\t\t\tdflavortext = \"rips\";\n\t\t\tdragattackresult()\n\t\t\tstdhit()\n\t\t}\n\t\telse if (dragatk == 1)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*50+100);\n\t\t\tdflavortext = \"belches flame and burns\";\n\t\t\tdragattackresult()\n\t\t\tflamebelch()\n\t\t}\n\t\telse if (dragatk == 2)\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*25+15);\n\t\t\tdflavortext = \"bites\";\n\t\t\tdragattackresult()\n\t\t\tclaw2()\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdragdamage = Math.floor(Math.random()*60+40);\n\t\t\tdflavortext = \"summons a meteor that crushes\";\n\t\t\tdragattackresult()\n\t\t\tbumrush()\n\t\t}\n\t}\n}",
"down(y = this.speed[1]){\n this.pos[1] -= y;\n this.boundY();\n }",
"function setGoal(dancer, pos) {\n dancer.goal = new vec2(pos)\n }",
"steerTo(d) {\r\n // Calculate the vector that points to the target.\r\n d.sub(this.pos);\r\n let dist = d.mag();\r\n \r\n if (dist > 0) {\r\n // Normalise and scale the vector based on the distance to the target.\r\n d.normalize().mult(this.maxSpeed);\r\n this.vel.add(d.sub(this.vel).limit(cohesionWeight));\r\n }\r\n }",
"moveMovingEntityDown() {\n this.y += this.speed;\n }",
"keyDown(e){\r\n if(e.key === 'd' || e.key === 'D' || e.key === 'ArrowRight'){\r\n this.dx = this.speed; // outrora isso era undefined\r\n }else if(e.key === 'a' || e.key === 'A' || e.key === 'ArrowLeft'){\r\n this.dx = -this.speed;// mas agora o pai ta chato vindo de nova\r\n }\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines user's email address from a given user ID. | function idToEmail(user_id) {
if (users[user_id].email !== undefined) {
return users[user_id].email;
} else return "None";
} | [
"function IdToEmail(id) {\n const arr = users.filter(u => u.id === id);\n return arr[0] ? arr[0].email : 'unknown_email';\n}",
"function getUserEmail(userId, cb) {\n\t\tmodelUser.findById(userId).select('email').lean().exec(cb);\n\t}",
"function userEmail(userId) { \n user=Meteor.users.findOne(userId);\n if(user!=null){\n if (user.emails && user.emails.length)\n return user.emails[0].address; \n if (user.services && user.services.github && user.services.github.email) \n return user.services.github.email; \n return null;\n }\n else{\n return null;\n } \n}",
"function getEmailAddressForUser() {\n try {\n for (let account of /* COMPAT for TB 68 */toArray(MailServices.accounts.accounts, Ci.nsIMsgAccount)) {\n if (account.incomingServer.type == \"exquilla\") {\n return account.defaultIdentity.email;\n }\n }\n } catch (ex) {\n console.error(ex);\n }\n try {\n return MailServices.accounts.defaultAccount.defaultIdentity.email;\n } catch (ex) {\n console.error(ex);\n return \"unknown\";\n }\n}",
"function getEmailAddress(user) {\n var otpDelivery = state.get(\"email\");\n if(otpDelivery == null) {\n if(user != null) {\n if(user.emails != null && user.emails.length > 0) {\n otpDelivery = user.emails[0].value;\n state.put(\"email\", otpDelivery);\n }\n }\n }\n return jsString(otpDelivery);\n}",
"function getEmailId(user_id) {\n var Allusr = JSON.parse(localStorage.getItem(\"Users\"));\n for (var i = 0; i < Allusr.length; i++) {\n if (Allusr[i].userid == user_id) {\n return Allusr[i].email;\n }\n }\n}",
"async function getEmailAddressOfUser(username) {\n if (username.indexOf('@') !== -1) return username;\n\n const query = datastore.createQuery('User').filter('username', '=', username);\n\n try {\n const [[user]] = await datastore.runQuery(query);\n\n if (user) {\n return user.email;\n } else {\n throw new Error('No email found');\n }\n } catch (error) {\n return null;\n }\n}",
"function getUserEmailbyID(userid){\r\n\tgetAllUsers(); // This has to be called again for some odd reason...its causes another call to the server but...\r\n\tvar userEmail = \"\";\r\n\tfor (x=1;x<SPUser.length;x++) {\r\n\t\tif (String(userid)==String(SPUser[x].value)) {userEmail=SPUser[x].email;}\r\n\t}\r\n\treturn userEmail;\r\n}",
"function getUserEmail(name) {\n\tif (name.indexOf('@')>-1){\n\t\treturn name;\n\t} else if (name){\n\t\tvar gr = new GlideRecord('sys_user');\n\t\tgr.addQuery('user_name', name);\n\t\tgr.query();\n\t\tif (gr.next()){\n\t\t\treturn gr.email;\n\t\t} else {\n\t\t\treturn 'no user found';\n\t\t}\n\t} else {\n\t\tvar u = gs.getUserID();\n\t\tvar gr2 = new GlideRecord('sys_user');\n\t\tgr2.get(u);\n\t\treturn gr2.email;\n\t}\n}",
"getEmailById(id){\n return UserDB.findOne({_id:id}, \"email\");\n }",
"function getEmailFromID(p_session, p_id) {\n\tfor(var i = 0; i < customerData.customers.length; i++) {\n\t\tif(customerData.customers[i].id == p_id) {\n\t\t\treturn customerData.customers[i].email;\n\t\t}\n\t}\n\treturn null;\n}",
"function getEmailInfo(callback, id, email) {\n if ((id === undefined) || (email === undefined) || (!email.length)) {\n callback(returnError('Empty email or book id'));\n return;\n }\n this.sendRequest(`addressbooks/${id}/emails/${email}`, 'GET', {}, true, callback);\n}",
"async getEmail(){\n\n\t\tif(!this.data) return new Error('getEmail error: No Employee Selected');\n\n\t\tlet cache = await db.query('select * from users where empybnid = ?',{conditions:[this.data.empybnid]});\n\t\t\n\t\tif(cache.length > 0 && cache[0].email !== null){\n\t\treturn cache[0].email;\n\t\t}\n\n\t\tlet result = await ldapSearchClient.search(this.data.empybnid)\n\t\t.catch(err => err);\n\n\t\tif(result.data.length === 0){\n\t\t\treturn Promise.reject(new Error('Employee could not be found with the provided bnid'));\n\t\t}\n\n\t\tlet email = result.data[0].mail;\n\n\t\tdb.query('update users set email = ? where empybnid = ?',{conditions:[email,this.data.empybnid]})\n\t\t.catch(err => console.log(err));\n\n\t\treturn email;\n \t}",
"function getEmailOrHash( user ) {\n var emailOrHash;\n if ( user && Avatar.options.emailHashProperty && user[Avatar.options.emailHashProperty] ) {\n emailOrHash = user[Avatar.options.emailHashProperty];\n }\n else if ( user && user.emails ) {\n emailOrHash = user.emails[0].address; // TODO: try all emails\n }\n else {\n // If all else fails, return 32 zeros (trash hash, hehe) so that Gravatar\n // has something to build a URL with at least.\n emailOrHash = '00000000000000000000000000000000';\n }\n return emailOrHash;\n}",
"function emailLookup(email) {\n for (let id in users) {\n if (users[id].email === email) {\n return users[id];\n }\n }\n return null;\n}",
"get userEmail() {\n var _a;\n return (_a = this._data.email) !== null && _a !== void 0 ? _a : null;\n }",
"function getEmailInfo(callback, id, email) {\n if ((id === undefined) || (email === undefined) || (!email.length)) {\n return callback(returnError('Empty email or book id'));\n }\n sendRequest('addressbooks/' + id + '/emails/' + email, 'GET', {}, true, callback);\n\n}",
"function getEmailInfo(callback, id, email) {\n if ((id === undefined) || (email === undefined) || (!email.length)) {\n return callback(returnError(\"Empty email or book id\"));\n }\n sendRequest('addressbooks/' + id + '/emails/' + email, 'GET', {}, true, callback);\n\n}",
"githubUserNoreplyEmail(id) {\n if (id !== undefined)\n this._githubUserNoreplyEmail = id + \"+\" + this.githubUserLogin() + \"@users.noreply.github.com\";\n return this._githubUserNoreplyEmail;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Funcion para crear mediante javascript el listado de canciones | function crearPlayList(){
const listado = document.createElement('ol')
listado.setAttribute("id", 'listadoMusica')
for (let i = 0; i<canciones.length; i++){
const item = document.createElement('li')
item.appendChild(document.createTextNode(canciones[i]))
item.setAttribute("id", canciones.indexOf(canciones[i]))
listado.appendChild(item)
}
return listado
} | [
"function crearPlayList(){\n\tconst listado = document.createElement('ol')\n\tlistado.setAttribute(\"id\", 'listadoMusica')\n\tfor (let i = 0; i<canciones.length; i++){\n\t\tconst item = document.createElement('li')\n\t\titem.appendChild(document.createTextNode(canciones[i])) \n\t\titem.setAttribute(\"id\", canciones.indexOf(canciones[i]))\n\t\tlistado.appendChild(item)\n\t}\n\treturn listado\n}",
"function cargarCanciones(sitio){\r\n var canciones = [];\r\n var html = \"\"\r\n $(document).ready(function () {\r\n \r\n //Carga los datos que estan en el JSON (datos.json) usando AJAX\r\n $.ajax({\r\n url: \"datos.json\"\r\n }).done(function (resultado) {\r\n console.log(resultado);\r\n console.log(sitio);\r\n\r\n//var canciones;\r\n\r\n //Si la longitud de buscar es mayor a 0 filtra canciones \r\nif (sitio != 'home' ){\r\n var cajaBuscar = formBuscarCancion.buscar.value.trim();\r\n if(cajaBuscar.length > 0){\r\n canciones = resultado.canciones;\r\n canciones = filterItems(canciones, cajaBuscar);\r\n console.log(\"Despues del filter\");\r\n }\r\n else{\r\n canciones = resultado.canciones;\r\n }\r\n html = dibujarCanciones(canciones);\r\n\r\n}\r\nif (sitio == 'home'){\r\n var cancionesTop = [];\r\n //Ordena segun mayor en reproducciones \r\n canciones = resultado.canciones;\r\n console.log(canciones);\r\n canciones = canciones.sort(function(x,y){\r\n if (x.reproducciones < y.reproducciones){\r\n return 1;\r\n }\r\n return -1;\r\n });\r\n \r\n canciones =resultado.canciones;\r\n for (var j = 0; j < 3; j++){\r\n cancionesTop.push(canciones[j]);\r\n }\r\n console.log(cancionesTop);\r\n html = dibujarCancionestop(cancionesTop);\r\n \r\n\r\n} \r\n //Modifica el DOM agregando el html generado\r\n document.getElementById(\"canciones\").innerHTML = html\r\n\r\n })\r\n });\r\n\r\n\r\n\r\n}",
"function crearPlayList() {\n const listado = document.createElement('ol')\n listado.setAttribute(\"id\", 'listadoMusica')\n for (let i = 0; i < canciones.length; i++) {\n const item = document.createElement('li')\n item.appendChild(document.createTextNode(canciones[i]))\n item.setAttribute(\"id\", canciones.indexOf(canciones[i]))\n listado.appendChild(item)\n }\n return listado\n}",
"function generateHtmlListOfCannedResponses() {\n getCannedResponses();\n\n HtmlListOfCannedResponses = '<li id=\"new-canned-response\"><a href=\"javascript:void(0);\">Create new</a></li>';\n\n for (i in cannedResponses) {\n HtmlListOfCannedResponses += '<li data-canned-response-id=\"' + i + '\"><a href=\"javascript:void(0);\">' + cannedResponses[i][\"name\"] + '</a></li>';\n }\n\n return HtmlListOfCannedResponses;\n}",
"function build_allowed_campaigns(lst) {\n\tres = \"<ul class='chain_links'>\";\n $.each(lst, function(i, v) {\n res += \"<li><a ui='ui-widget-content' href='javascript:redirect(\\\"/edit/campaigns/\";\n res += this+\"/\\\");'>\"+this+\"</a></li>\";\n\t\tif (i < lst.lenght - 1)\n\t\t\tres += \", \";\n\t});\n\tres += \"</ul>\"; \n\treturn res;\n}",
"function creaSelect(list)\n{\n\t//crea un menu per la resta de resultats\n\tvar select=document.createElement('select');\n\tselect.style.display='block';\n\tlist.items.forEach(function(item)\n\t{\n\t\tvar id = item.id.videoId;\n\t\tvar canal = item.snippet.channelTitle;\n\t\tvar titol = item.snippet.title;\n\t\t//new option\n\t\tvar option=document.createElement('option');\n\t\tselect.appendChild(option)\n\t\toption.value=id;\n\t\tvar text=canal+\": \"+titol;\n\t\tif(text.length>=47) text=text.substring(0,44)+\"...\";\n\t\toption.innerHTML=text;\n\t});\n\treturn select;\n}",
"function makeRestrictList(restrict){\n\n\trestList = document.getElementById(restrict);\n\trestList.innerHTML = \"\";\n\n\tfor(i = 0; i < restrictOptions.length; i++){\n\t\tvar checkbox = document.createElement(\"input\");\n\t\tcheckbox.type = \"checkbox\";\n\t\tcheckbox.name = \"restriction\";\n\t\tcheckbox.id = restrictOptions[i];\n\t\tcheckbox.value = restrictOptions[i];\n\t\trestList.appendChild(checkbox);\n\n\t\tvar label = document.createElement('label');\n\t\tlabel.htmlFor = restrictOptions[i];\n\t\tlabel.appendChild(document.createTextNode(restrictOptions[i]));\n\t\trestList.appendChild(label)\n\n\t\trestList.appendChild(document.createElement('br'));\n\t}\n}",
"function crearPlayList(){\n const listado = document.createElement('ol')\n listado.setAttribute(\"id\", 'listadoMusica')\n for (let i = 0; i<canciones.length; i++){\n const item = document.createElement('li')\n const span =document.createElement('span')\n \n span.appendChild(document.createTextNode(canciones[i])) \n item.appendChild(document.createTextNode(((canciones[i]).slice(7,100).replace(\".mp3\",\"\")))) \n \n item.appendChild(span)\n item.setAttribute(\"id\", canciones.indexOf(canciones[i]))\n span.setAttribute(\"id\", canciones.indexOf(canciones[i]))\n \n listado.appendChild(item)\n }\n return listado\n \n }",
"function canonic_forms_creation(BBC_Def) {\n var Canonic;\n var lng = BBC_Def.length;\n for (t = 0; t < lng; t += 1) {\n regle = BBC_Def[t];\n nreg = regle.opening[0];\n Canonic = regle.opening[0].split('_'); \n regle.CanonicOpening = Canonic.join(''); \n Canonic = regle.closing[0].split('_');\n regle.CanonicClosing = Canonic.join('');\n }\n }",
"function creaList(list, posicion){//crea la lista de datos de la posicion solicitada\n\tvar listHTML = '';\n\t\n\t\tlistHTML += '<ul>';\n\t\tlistHTML += '<li>Nombre Buque: ' + list[posicion].nombre + '</li>'; //nos entrega el dato del buque segun la posicion que tenga en el objeto\n\t\tlistHTML += '<li>Carga Que Tiene: ' + list[posicion].carga + '</li>';\n\t\tlistHTML += '<li>Bandera: ' + list[posicion].bandera + '</li>';\n\t\n\t\t\n\t\tlistHTML += '<li>Naviera: ' + list[posicion].naviera + '</li>';\n\t\t\n\t\t\n\tlistHTML += '</ul> <br>' ;// al final del HTML se agraga un espacio en blaco que diferencia a cada buque\n\treturn listHTML; //retorna la lista listo para presentada\n}",
"generateConstituencyList () {\n\t\tObject.keys(this.UKHexMap.hexes).forEach(item => {\n\t\t\tlet onsKey = document.createElement(\"option\");\n\t\t\tonsKey.value = item;\n\t\t\t\n\t\t\tlet name = document.createElement(\"option\");\n\t\t\tname.value = this.UKHexMap.hexes[item].n;\n\t\t\t\n\t\t\tdocument.getElementById(\"constituencies\")\n\t\t\t\t.appendChild(onsKey)\n\t\t\t\t.appendChild(name);\n\t\t\t\t\n\t\t\tthis.ConstituencyList[this.UKHexMap.hexes[item].n] = item;\n\t\t\tthis.ConstituencyList[item] = this.UKHexMap.hexes[item].n;\n\t\t});\n\t}",
"function buildListeCircuits() {\n\n\t$('#liste-circuits li').remove();\n\n\t$.each(circuits, function(id, circuit) {\n\n\t\tvar li = \n\t\t'<li id=\"circuit' + circuit.id + '\" class=\"circuit\">' +\n\t \t\t'<a data-transition=\"slide\" href=\"map.html?circuit=' + circuit.id + '\" >' +\n\t \t\t\t'<h2>' + circuit.nom + '</h2>' +\n\t \t\t\t'<img src=\"' + serviceURL + \"sitlor/\" + circuit.photo + '\" />' +\n\t\t\t'</a>' +\n\t\t'</li>';\n\n\t\tvar $listeCircuits = $('#liste-circuits');\n\t\t$listeCircuits.hide();\n\t\t$listeCircuits.append(li);\n\n\t});\n}",
"function makeZoneList() {\n var str = $('[data-side=\"zones\"]').data('params');\n if (str == undefined)\n return \"\";\n\n var html= \"<form autocomplete=\\\"off\\\"> <select class=\\\"custom-select\\\" id=\\\"selectZone\\\" onchange=\\\"searchByZone(this.value)\\\"> <option value=\\\"\\\"> Select... </option>\";\n\n var sz=(Object.keys(str).length);\n for( var i=0; i< sz; i++) {\n var s = JSON.parse(str[i]);\n var abb=s['abb'];\n var name=s['name'];\n cfm_zone_list.push( {\"abb\":abb, \"name\":name } );\n html=html+\"<option value=\\\"\" + abb + \"\\\">\"+ name +\"</option>\";\n }\n return html;\n}",
"function crearContenidos(curso, nombreCurso)\n{\n \n var contenidos=\"\";\n if(curso[0].contenidos.length<10)\n { contenidos =\"<div class='row contenidos-cont'><ol>\";\n for(var i=0;i<curso[0].contenidos.length;i++)\n {\n \n contenidos+=\"<li><a class='punto' curso='\"+curso[0].nombre+\"' href='#'' data='\"+i+\"'>\"+curso[0].contenidos[i].titulo+\"</a></li>\";\n }\n contenidos+=\"</ol><div>\";\n }\n else{\n contenidos+=\"<div class='row contenidos-cont'><div class='small-4 column'><ol>\";\n for(var i=0;i<10;i++)\n {\n contenidos+=\"<li><a class='punto' curso='\"+curso[0].nombre+\"' href='#'' data='\"+i+\"'>\"+curso[0].contenidos[i].titulo+\"</a></li>\";\n }\n contenidos+=\"</ol></div><div class='small-4 column'><ol>\";\n\n for(var i=10;i<curso[0].contenidos.length;i++)\n {\n contenidos+=\"<li value='\"+i+\"'><a class='punto' curso='\"+curso[0].nombre+\"' href='#'' data='\"+i+\"'>\"+curso[0].contenidos[i].titulo+\"</a></li>\";\n }\n contenidos+=\"</ol></div></div>\";\n }\n $('#contenidos').append(contenidos);\n }",
"function makeAreaList() {\n var str = $('[data-side=\"areas\"]').data('params');\n if (str == undefined)\n return \"\";\n\n var html= \"<form autocomplete=\\\"off\\\"> <select class=\\\"custom-select\\\" id=\\\"selectArea\\\" onchange=\\\"searchByArea(this.value)\\\"> <option value=\\\"\\\"> Select...</option>\";\n\n var sz=(Object.keys(str).length);\n for( var i=0; i< sz; i++) {\n var s = JSON.parse(str[i]);\n var abb=s['abb'];\n var name=s['name'];\n cfm_area_list.push( {\"abb\":abb, \"name\":name } );\n html=html+\"<option value=\\\"\" + abb + \"\\\">\"+ name +\"</option>\";\n }\n return html;\n}",
"function loaderlist () {\n lista.forEach((cancion, indice)=>{\n //crear li\n const li =document.createElement(\"li\")\n // crear link\n const link = document.createElement(\"a\")\n //llenar link\n link.innerText= cancion.title\n link.href = \"#\"\n link.id = (aux++ + \"\")\n //capturar click\n link.addEventListener(\"click\", ()=> cargar(indice))\n //meter link dentro de li\n li.appendChild(link)\n //meter li dentro de ul\n canciones.appendChild(li)\n } \n )\n}",
"function renderContinents(c) {\n let slct = document.getElementById('name')\n let o = new Option('seleccione..', '');\n slct.appendChild(o)\n \n c.map(x => {\n let opt = new Option(x.name, x.code);\n slct.appendChild(opt)\n })\n}",
"function buildList(temp){\n\n for (var i = 0; i < temp.length; i++) {\n var crime = temp[i];\n var crimeList = document.createElement('li');\n var crimeText = document.createTextNode(crime.event_clearance_group + \": \" + crime.count);\n crimeList.appendChild(crimeText);\n document.getElementById('crimes').appendChild(crimeList);\n }\n}",
"function getAllCanvases(){\n //THERE WILL AT LEAST BE 2 CANVASES\n manifestCanvases = manifest.sequences[0].canvases;\n var forProject = detectWho();\n var properties={\"@type\" : \"sc:Canvas\", \"forProject\":forProject};\n var url=\"http://brokenbooks.org/brokenBooks/getAnnotationByPropertiesServlet\"\n var params = {\"content\" : JSON.stringify(properties)};\n $.post(url, params, function(data){\n manifestCanvases = JSON.parse(data);\n //console.log(\"got canvases\");\n getAllAnnotations();\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Distinguishes between a V1 and V2 Proxy Integration Request | function isProxyRequestContextV2(ctx) {
return ctx.version === "2.0";
} | [
"function isCommonReqEqual(url, serverInstance) {\n console.info('==> trying to get the url ', url);\n try {\n let isEqual = true;\n\n const directReqObj = serverInstance.getRequestRecord(url);\n const proxyReqObj = serverInstance.getProxyRequestRecord(url);\n\n // ensure the proxy header is correct\n isEqual = isEqual && proxyReqObj.headers['via-proxy'] === 'true';\n delete proxyReqObj.headers['via-proxy'];\n\n directReqObj.headers['content-type'] = trimFormContentType(directReqObj.headers['content-type']);\n proxyReqObj.headers['content-type'] = trimFormContentType(proxyReqObj.headers['content-type']);\n\n // avoid compare content-length header via proxy\n delete directReqObj.headers['content-length'];\n delete proxyReqObj.headers['content-length'];\n delete directReqObj.headers['transfer-encoding'];\n delete proxyReqObj.headers['transfer-encoding'];\n\n // delete the headers that should not be passed by AnyProxy\n delete directReqObj.headers.connection;\n delete proxyReqObj.headers.connection;\n\n // delete the headers related to websocket establishment\n const directHeaderKeys = Object.keys(directReqObj.headers);\n directHeaderKeys.forEach((key) => {\n // if the key matchs 'sec-websocket', delete it\n if (/sec-websocket/ig.test(key)) {\n delete directReqObj.headers[key];\n }\n });\n\n const proxyHeaderKeys = Object.keys(proxyReqObj.headers);\n proxyHeaderKeys.forEach((key) => {\n // if the key matchs 'sec-websocaket', delete it\n if (/sec-websocket/ig.test(key)) {\n delete proxyReqObj.headers[key];\n }\n });\n\n isEqual = isEqual && directReqObj.url === proxyReqObj.url;\n isEqual = isEqual && isObjectEqual(directReqObj.headers, proxyReqObj.headers, url);\n isEqual = isEqual && directReqObj.body === proxyReqObj.body;\n return isEqual;\n } catch (e) {\n console.error(e);\n }\n}",
"function distribute_req_wrap(orig_opts, cb) {\n\t\tconst base_url = t.misc.format_url(orig_opts.baseUrl);\t\t\t\t\t\t// parse for protocol + hostname + port (no path)\n\t\tlogger.debug('[sig route check] checking distribute route availability on:', base_url);\n\n\t\tconst availability_opts = {\n\t\t\tmethod: 'OPTIONS',\n\t\t\tbaseUrl: base_url,\n\t\t\turl: t.misc.url_join(['/api/v2', orig_opts.url]),\t\t// the version in this route doesn't matter, all versions go to the same place\n\t\t\theaders: {\n\t\t\t\t'Accept': 'application/json',\n\t\t\t},\n\t\t\ttimeout: (orig_opts.org && !isNaN(orig_opts.org.timeout_ms)) ? orig_opts.org.timeout_ms : 15000,\n\t\t\t_name: 'sig route check',\n\t\t};\n\t\tt.misc.retry_req(availability_opts, (error, resp) => {\n\t\t\tconst v1_route = t.misc.url_join(['/api/v1', orig_opts.url]);\t\t\t// append the v1 route\n\t\t\tconst v2_route = t.misc.url_join(['/api/v2', orig_opts.url]);\t\t\t// append the v2 route\n\t\t\torig_opts.url = v1_route;\t\t\t\t\t\t\t\t\t\t\t\t// default to using the v1 route\n\n\t\t\tif (error || t.ot_misc.is_error_code(t.ot_misc.get_code(resp))) {\t\t// error, use default\n\t\t\t\tlogger.warn('[sig route check] route availability error, defaulting to /v1/');\n\t\t\t} else {\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// success, pick route from response\n\t\t\t\tconst response = t.ot_misc.formatResponse(resp);\n\t\t\t\tif (response && response.methods && orig_opts.method) {\n\t\t\t\t\tconst orig_method_lc = orig_opts.method.toLowerCase();\n\t\t\t\t\tif (response.methods[orig_method_lc] && response.methods[orig_method_lc].routes && response.methods[orig_method_lc].routes.includes('v2')) {\n\t\t\t\t\t\tlogger.debug('[sig route check] route availability supports /v2/');\n\t\t\t\t\t\torig_opts.url = v2_route;\t\t\t\t\t\t\t\t\t// it supports v2\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.debug('[sig route check] route availability supports /v1/');\n\t\t\t\t\t\torig_opts.url = v1_route;\t\t\t\t\t\t\t\t\t// it does not support v2, use v1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\torig_opts.baseUrl = base_url;\t\t\t\t\t\t\t\t\t\t\t// replace in original options\n\t\t\thttp_distribute_req(orig_opts, (err, resp) => {\t\t\t\t\t\t\t// now do the http request w/the modified options... whew\n\t\t\t\treturn cb(err, resp);\n\t\t\t});\n\t\t});\n\t}",
"function proxy2nso(req, res) {\n var req_str = chalk.red('REQUEST ==>');\n req_str += req.body.id > 0 ? ` ${chalk.yellow(req.body.id)} -` : '';\n console.log(req_str, req.method, req.url);\n if (fPayload && req.url.startsWith('/jsonrpc/')) {\n console.dir(req.body, {depth: 4, colors: true});\n }\n\n apiProxy.web(req, res, { target: nsoTarget });\n}",
"function respondV2(req, res, next) {\n res.status(200).send('ok v2');\n}",
"testConnectMismatchedNames_v1_v1() {\n if (browser.isIE()) {\n return;\n }\n\n return checkConnectMismatchedNames(\n 1 /* innerProtocolVersion */, 1 /* outerProtocolVersion */,\n false /* reverse */);\n }",
"actionDescribeClientVpnAuthorizationRulesGet(incomingOptions, cb) {\n const AmazonEc2 = require(\"./dist\");\n let defaultClient = AmazonEc2.ApiClient.instance;\n // Configure API key authorization: hmac\n let hmac = defaultClient.authentications[\"hmac\"];\n hmac.apiKey = incomingOptions.apiKey;\n // Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n //hmac.apiKeyPrefix = 'Token';\n\n let apiInstance = new AmazonEc2.DefaultApi(); // String | The ID of the Client VPN endpoint // String | Region where you are making the request\n /*let clientVpnEndpointId = \"clientVpnEndpointId_example\";*/ /*let region = \"region_example\";*/ let opts = {\n // 'xAmzContentSha256': \"xAmzContentSha256_example\", // String |\n // 'xAmzDate': \"xAmzDate_example\", // String |\n // 'xAmzAlgorithm': \"xAmzAlgorithm_example\", // String |\n // 'xAmzCredential': \"xAmzCredential_example\", // String |\n // 'xAmzSecurityToken': \"xAmzSecurityToken_example\", // String |\n // 'xAmzSignature': \"xAmzSignature_example\", // String |\n // 'xAmzSignedHeaders': \"xAmzSignedHeaders_example\", // String |\n dryRun: false, // Boolean | Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is <code>DryRunOperation</code>. Otherwise, it is <code>UnauthorizedOperation</code>.\n // 'nextToken': \"nextToken_example\", // String | The token to retrieve the next page of results.\n filter: [\"null\"], // [String] | One or more filters. Filter names and values are case-sensitive.\n maxResults: 56, // Number | The maximum number of results to return for the request in a single page. The remaining results can be seen by sending another request with the nextToken value.\n // 'action': \"action_example\", // String |\n version: \"'2016-11-15'\" // String |\n };\n\n if (!incomingOptions.opts) delete incomingOptions.opts;\n incomingOptions.opts = Object.assign(opts, incomingOptions.opts);\n\n apiInstance.actionDescribeClientVpnAuthorizationRulesGet(\n incomingOptions.clientVpnEndpointId,\n incomingOptions.region,\n incomingOptions.opts,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n }\n );\n }",
"function proxyFIDO2ServerRequest(req, rsp, validateUsername, allowEmptyUsername) {\n\tvar bodyToSend = validateUsername ? validateSelf(req.body, req.session.username, allowEmptyUsername) : req.body;\n\n\t// the CI body is slightly different from the FIDO server spec. \n\t// instead of username (validity of which has already been checked above), \n\t// we need to provide userId which is the CI IUI for the user.\n\tif (bodyToSend.username != null) {\n\t\tdelete bodyToSend.username;\n\t\tif (req.session.userSCIMId) {\n\t\t\tbodyToSend.userId = req.session.userSCIMId;\n\t\t}\n\t}\n\n\t// when performing registrations, I want the registration \n\t// enabled immediately so insert this additional option\n\tif (req.url.endsWith(\"/attestation/result\")) {\n\t\tbodyToSend.enabled = true;\n\t}\n\n\tvar access_token = null;\n\ttm.getAccessToken(req)\n\t.then( (at) => {\n\t\taccess_token = at;\t\t\n\t\treturn rpIdTorpUuid(process.env.RPID);\n\t}).then((rpUuid) => {\n\t\tvar options = {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t\"Content-type\": \"application/json\",\n\t\t\t\t\"Accept\": \"application/json\",\n\t\t\t\t\"Authorization\": \"Bearer \" + access_token\n\t\t\t},\n\t\t\treturnAsJSON: true,\n\t\t\tbody: JSON.stringify(bodyToSend)\n\t\t};\n\t\tlogger.logWithTS(\"proxyFIDO2ServerRequest.options: \" + JSON.stringify(options));\n\t\treturn myfetch(\n\t\t\tprocess.env.CI_TENANT_ENDPOINT + \"/v2.0/factors/fido2/relyingparties/\" + rpUuid + req.url,\n\t\t\toptions\n\t\t);\n\t}).then((proxyResponse) => {\n\t\t// worked - add server spec status and error message fields\n\t\tvar rspBody = proxyResponse;\n\t\trspBody.status = \"ok\";\n\t\trspBody.errorMessage = \"\";\n\t\tlogger.logWithTS(\"proxyFIDO2ServerRequest.success: \" + JSON.stringify(rspBody));\n\t\trsp.json(rspBody);\n\t}).catch((e) => {\n\t\thandleErrorResponse(\"proxyFIDO2ServerRequest\", rsp, e, \"Unable to proxy FIDO2 request\");\n\t});\n}",
"function xrxScanV2GetInterfaceVersionRequest()\r\n{\r\n\treturn\tXRX_SOAPSTART \r\n\t\t\t+ xrxCreateTag( 'GetInterfaceVersionRequest', XRX_SCANV2_NAMESPACE, '' ) \r\n\t\t\t+ XRX_SOAPEND;\r\n}",
"function proxyFIDO2ServerRequest(req, rsp, validateUsername, allowEmptyUsername) {\n\tlet userDetails = getUserDetails(req);\n\tlet bodyToSend = validateUsername ? validateSelf(req.body, userDetails.username, allowEmptyUsername) : req.body;\n\n\t// the CI body is slightly different from the FIDO server spec. \n\t// instead of username (validity of which has already been checked above), \n\t// we need to provide userId which is the CI IUI for the user.\n\tif (bodyToSend.username != null) {\n\t\tdelete bodyToSend.username;\n\t\tif (userDetails.userSCIMId) {\n\t\t\tbodyToSend.userId = userDetails.userSCIMId;\n\t\t}\n\t}\n\n\t// when performing registrations, we want the registration \n\t// enabled immediately so insert this additional option\n\tif (req.url.endsWith(\"/attestation/result\")) {\n\t\tbodyToSend.enabled = true;\n\t}\n\n\tlet access_token = null;\n\ttm.getAccessToken(req)\n\t.then( (at) => {\n\t\taccess_token = at;\t\t\n\t\treturn rpIdTorpUuid(req, process.env.RPID);\n\t}).then((rpUuid) => {\n\t\tlet options = {\n\t\t\turl: process.env.CI_TENANT_ENDPOINT + \"/v2.0/factors/fido2/relyingparties/\" + rpUuid + req.url,\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t\"Content-type\": \"application/json\",\n\t\t\t\t\"Accept\": \"application/json\",\n\t\t\t\t\"Authorization\": \"Bearer \" + access_token\n\t\t\t},\n\t\t\tjson: true,\n\t\t\tbody: bodyToSend\n\t\t};\n\t\tlogger.logWithTS(\"proxyFIDO2ServerRequest.options: \" + JSON.stringify(options));\n\t\treturn requestp(options);\n\t}).then((proxyResponse) => {\n\t\t// worked\n\t\tlet rspBody = proxyResponse;\n\n\n\t\t// coerce CI responses to format client expects (comes from original ISAM-based implementation)\n\t\tif (req.url.endsWith(\"/attestation/result\")) {\n\t\t\treturn coerceAttestationResultToClientFormat(req, proxyResponse);\n\t\t} else if (req.url.endsWith(\"/assertion/result\")) {\n\t\t\treturn coerceAssertionResultToClientFormat(req, bodyToSend, proxyResponse);\n\t\t} else {\n\t\t\treturn rspBody;\n\t\t}\n\t}).then((rspBody) => {\n\t\t// just add server spec status and error message fields and send it\n\t\trspBody.status = \"ok\";\n\t\trspBody.errorMessage = \"\";\n\t\tlogger.logWithTS(\"proxyFIDO2ServerRequest.success: \" + JSON.stringify(rspBody));\n\t\trsp.json(rspBody);\n\t}).catch((e) => {\n\t\thandleErrorResponse(\"proxyFIDO2ServerRequest\", rsp, e, \"Unable to proxy FIDO2 request\");\n\t});\n}",
"function isCommonResHeaderEqual(directHeaders, proxyHeaders, requestUrl) {\n directHeaders = Object.assign({}, directHeaders);\n proxyHeaders = Object.assign({}, proxyHeaders);\n let isEqual = true;\n const mustEqualFileds = []; // the fileds that have to be equal, or the assert will be failed\n\n if (!/gzip/i.test(directHeaders['content-encoding'])) {\n // if the content is gzipped, proxy will unzip and remove the header\n mustEqualFileds.push('content-encoding');\n }\n mustEqualFileds.push('content-type');\n mustEqualFileds.push('cache-control');\n mustEqualFileds.push('allow');\n\n // ensure the required fileds are same\n mustEqualFileds.forEach(filedName => {\n isEqual = directHeaders[filedName] === proxyHeaders[filedName];\n delete directHeaders[filedName];\n delete proxyHeaders[filedName];\n });\n\n // remained filed are good to be same, but are allowed to be different\n // will warn out those different fileds\n for (const key in directHeaders) {\n if (!_isDeepEqual(directHeaders[key], proxyHeaders[key])) {\n printWarn(`key \"${key}\" of two response headers are different in request \"${requestUrl}\" :\n direct is: \"${directHeaders[key]}\", proxy is: \"${proxyHeaders[key]}\"`);\n }\n }\n\n return isEqual;\n}",
"static InitByAccept() {\n var removeWhitespaces = (str) => { if (typeof str === 'string') { return str.replace(/\\s/g, '') } else return '' };\n\n return (req, res, next) => {\n\n if (!req.requested_version && req && req.headers && req.headers.accept) {\n const acceptHeader = String(req.headers.accept);\n\n // First try and use method 1\n const params = acceptHeader.split(';')[1]\n const paramMap = {}\n if (params) {\n for (let i of params.split(',')) {\n const keyValue = i.split('=')\n if (typeof keyValue === 'object' && keyValue[0] && keyValue[1]) {\n paramMap[removeWhitespaces(keyValue[0]).toLowerCase()] = removeWhitespaces(keyValue[1]);\n }\n }\n req.requested_version = this.formatVersion(paramMap.version)\n }\n\n // if method 1 did not yeild results try method 2\n if (req.requested_version === undefined) {\n const header = removeWhitespaces(acceptHeader);\n let start = header.indexOf('-v');\n if (start === -1) {\n start = header.indexOf('.v');\n }\n const end = header.indexOf('+');\n if (start !== -1 && end !== -1) {\n req.requested_version = this.formatVersion(header.slice(start + 2, end));\n }\n } \n } else {\n req.requested_version = undefined;\n }\n\n next();\n }\n }",
"lineVerify(req, res){\n\t\tif(req.get(\"User-Agent\") === \"LINE-Developers/0.1\"){\n\t\t\tlet verify_token0 = \"00000000000000000000000000000000\";\n\t\t\tlet verify_token1 = \"ffffffffffffffffffffffffffffffff\";\n\t\t\tif(req.body.events[0].replyToken === verify_token0 && \n\t\t\t req.body.events[1].replyToken === verify_token1){\n\t\t\t\tres.sendStatus(200);\n\t\t\t\tconsole.log(\"Line webhook url verified.\");\n\t\t\t}\n\t\t}\n\t}",
"function selectImplementation(self, cb) {\n if (self.quotaImpl) {\n cb(undefined, self.quotaImpl);\n return;\n }\n\n if (self.apigeeQuota) {\n self.quotaImpl = new ApigeeAccessQuota(self);\n cb(undefined, self.quotaImpl);\n\n } else {\n var options = {\n url: self.options.uri + '/v2/version',\n headers: { 'x-DNA-Api-Key': self.options.key },\n json: true\n };\n if( self.options.key && self.options.secret) {\n options['auth']= {\n user: self.options.key,\n pass: self.options.secret,\n sendImmediately: true\n }\n }\n debug('version call url: %s', options.url);\n self.request.get(options, function(err, resp, body) {\n if (err) {\n debug('Error getting version: %s', err);\n if (err.code === 'ENOTFOUND') {\n err.message = 'Apigee Remote Proxy not found at: ' + self.uri + '. Check your configuration.';\n }\n return cb(err);\n }\n\n debug('version call response, statusCode: %d, body: %j', resp.statusCode, body);\n var ok = resp.statusCode / 100 === 2;\n if (resp.statusCode === 404 || (ok && !semver.satisfies(body, '>=1.1.0'))) {\n if (self.options.startTime) {\n cb(new Error('Quotas with a fixed starting time are not supported'));\n } else {\n self.quotaImpl = new ApigeeOldRemoteQuota(self);\n cb(undefined, self.quotaImpl);\n }\n } else if (ok) {\n self.quotaImpl = new ApigeeRemoteQuota(self);\n cb(undefined, self.quotaImpl);\n } else if (resp.statusCode === 401) {\n cb(new Error('Not authorized to call the remote proxy. Check the \"key\" parameter.'));\n } else {\n cb(new Error(util.format('HTTP error getting proxy version: %d. Check the \"uri\" parameter.', resp.statusCode)));\n }\n });\n }\n}",
"function setupInterceptorReplies(replies) {\n if (replies == null || replies.length <= 0) {\n return null;\n }\n var response = [];\n replies.forEach((item) => {\n var code = ``;\n itemScopeNoPort = item.scope.substring(0, item.scope.lastIndexOf(':'));\n code += `return nock('${ item.scope }')\\n`;\n // Uncomment to debug matching logic.\n //code += ` .log(console.log)\\n`;\n \n\n // Set up interceptor with some validation on properties.\n code += ` .matchHeader('content-type', '${ item.reqheaders['content-type'] }')\\n`;\n if ('content-length' in item.reqheaders) {\n code += ` .matchHeader('accept', '${ item.reqheaders.accept }')\\n`;\n }\n\n // Prepare URL\n code = prepareUrl(item, code);\n\n if (item.method.toLowerCase() == 'put') {\n code += `,\\n function(body) {\\n`;\n // Validate contents\n var recordedBody = Object.getOwnPropertyNames(item.body);\n \n //console.log('ALL PROPERTIES: ' + JSON.stringify(recordedBody, null, 1));\n var excludedProperties = ['serviceUrl', 'replyToId', 'id', 'text']; // Filter proxy-altered properties\n recordedBody.forEach(function(prop) {\n if (excludedProperties.includes(prop)) {\n return;\n }\n \n if (typeof item.body[prop] == 'string') {\n //console.log('ALL PROPERTIES: PROCESSING: ' + prop + ' - \\n' + item.body[prop]);\n code += ` console.log('PROCESSING ${ prop }.');\\n`;\n code += ` if (${ JSON.stringify(item.body[prop]) } != body.${ prop }) {\\n`;\n code += ` console.error('Body ${ prop } does not match ${ JSON.stringify(item.body[prop]) } != ' + JSON.stringify(body.${ prop }));\\n`;\n code += ` return false;\\n`;\n code += ` }\\n`;\n }\n });\n code += ` console.log('DONE PROCESSING PROPERTIES!');\\n`;\n code += ` return true;\\n`;\n code += ` })\\n`;\n code += ` .reply(${ item.status }, ${ JSON.stringify(item.response) }, ${ formatHeaders(item.rawHeaders) });\\n`;\n } else if (item.method.toLowerCase() == 'post') {\n code += `,\\n function(body) {\\n`;\n // code += ` console.log('INSIDE BODY EVALUATION!!');\\n`;\n\n // Validate body type\n if (item.body.hasOwnProperty('type')) { \n code += ` if ('${ item.body.type }' != body.type) {\\n`;\n code += ` console.log('Body type does not match ${ item.body.type } != ' + body.type);\\n`;\n code += ` return false;\\n`;\n code += ` }\\n`;\n }\n // Validate Activity\n if (item.body.hasOwnProperty('activity')) { \n code += ` if (${ item.body.activity.hasOwnProperty('type') } && '${ item.body.activity.type }' != body.activity.type) {\\n`;\n code += ` console.log('Activity type does not match ${ item.body.activity.type } != ' + body.activity.type);\\n`;\n code += ` return false;\\n`;\n code += ` }\\n`;\n // Validate Activity attachments\n if (item.body.activity.hasOwnProperty('attachments')) {\n code += ` if ('${ JSON.stringify(item.body.activity.attachments) }' != JSON.stringify(body.activity.attachments)) {\\n`;\n code += ` console.log('Activity attachments do not match ${ JSON.stringify(item.body.activity.attachments) } != ' + JSON.stringify(body.activity.attachments));\\n`;\n code += ` return false;\\n`;\n code += ` }\\n`;\n }\n }\n\n // Validate ChannelData\n if (item.body.hasOwnProperty('channelData') && item.body.channelData.hasOwnProperty('channel') \n && item.body.channelData.channel.hasOwnProperty('id')) { \n code += ` if ('${ item.body.channelData.channel.id }' != body.channelData.channel.id) {\\n`;\n code += ` console.error('Channel data/channel id does not match ${ JSON.stringify(item.body.channelData) } != ' + JSON.stringify(body.channelData));\\n`;\n code += ` return false;\\n`;\n code += ` }\\n`;\n }\n\n // Validate from.name \n if (item.body.hasOwnProperty('from') && item.body.from.hasOwnProperty('name')) { \n code += ` if ('${ item.body.from.name }' != body.from.name) {\\n`;\n code += ` console.error('From name does not match');\\n`;\n code += ` return false;\\n`;\n code += ` }\\n`;\n }\n code += ` return true;\\n`;\n code += ` })\\n`;\n code += ` .reply(${ item.status }, ${ JSON.stringify(item.response) }, ${ formatHeaders(item.rawHeaders) });\\n`;\n }\n else {\n code += `)\\n`;\n code += ` .reply(${ item.status }, ${ JSON.stringify(item.response) }, ${ formatHeaders(item.rawHeaders) })\\n`;\n }\n \n // Uncomment to see generated Interceptor code.\n if (item.method.toLowerCase() == 'put') {\n console.log('NOCK INTERCEPTOR CODE (replies count = ' + replies.length + '):\\n' + code);\n }\n var interceptor = null;\n try {\n interceptor = new Function('nock', code);\n }\n catch(ex) {\n console.error('NOCK INTERCEPTOR CODE (replies count = ' + replies.length + '):\\n' + code);\n console.error(JSON.stringify(ex, null, 1));\n \n throw ex;\n }\n response.push(interceptor(nock));\n });\n return response;\n}",
"actionAuthorizeClientVpnIngressGet(incomingOptions, cb) {\n const AmazonEc2 = require(\"./dist\");\n let defaultClient = AmazonEc2.ApiClient.instance;\n // Configure API key authorization: hmac\n let hmac = defaultClient.authentications[\"hmac\"];\n hmac.apiKey = incomingOptions.apiKey;\n // Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n //hmac.apiKeyPrefix = 'Token';\n\n let apiInstance = new AmazonEc2.DefaultApi(); // String | The ID of the Client VPN endpoint // String | The IPv4 address range, in CIDR notation, of the network for which access is being authorized // String | Region where you are making the request\n /*let clientVpnEndpointId = \"clientVpnEndpointId_example\";*/ /*let targetNetworkCidr = \"targetNetworkCidr_example\";*/ /*let region = \"region_example\";*/ let opts = {\n // 'xAmzContentSha256': \"xAmzContentSha256_example\", // String |\n // 'xAmzDate': \"xAmzDate_example\", // String |\n // 'xAmzAlgorithm': \"xAmzAlgorithm_example\", // String |\n // 'xAmzCredential': \"xAmzCredential_example\", // String |\n // 'xAmzSecurityToken': \"xAmzSecurityToken_example\", // String |\n // 'xAmzSignature': \"xAmzSignature_example\", // String |\n // 'xAmzSignedHeaders': \"xAmzSignedHeaders_example\", // String |\n // 'accessGroupId': \"accessGroupId_example\", // String | The ID of the Active Directory group to grant access.\n authorizeAllGroups: true, // Boolean | Indicates whether to grant access to all clients. Use <code>true</code> to grant all clients who successfully establish a VPN connection access to the network.\n // 'description': \"description_example\", // String | A brief description of the authorization rule.\n // 'clientToken': \"clientToken_example\", // String | Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. For more information, see <a href=\\\"https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html\\\">How to Ensure Idempotency</a>.\n dryRun: false, // Boolean | Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is <code>DryRunOperation</code>. Otherwise, it is <code>UnauthorizedOperation</code>.\n // 'action': \"action_example\", // String |\n version: \"'2016-11-15'\" // String |\n };\n\n if (!incomingOptions.opts) delete incomingOptions.opts;\n incomingOptions.opts = Object.assign(opts, incomingOptions.opts);\n\n apiInstance.actionAuthorizeClientVpnIngressGet(\n incomingOptions.clientVpnEndpointId,\n incomingOptions.targetNetworkCidr,\n incomingOptions.region,\n incomingOptions.opts,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n }\n );\n }",
"static isRequestFromEdge(req) {\n return typeof req.headers[constants_1.HTTP_HEADERS.x0Version] == 'string';\n }",
"function proxyRequest(msg) {\n return true;\n}",
"actionModifyClientVpnEndpointGet(incomingOptions, cb) {\n const AmazonEc2 = require(\"./dist\");\n let defaultClient = AmazonEc2.ApiClient.instance;\n // Configure API key authorization: hmac\n let hmac = defaultClient.authentications[\"hmac\"];\n hmac.apiKey = incomingOptions.apiKey;\n // Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n //hmac.apiKeyPrefix = 'Token';\n\n let apiInstance = new AmazonEc2.DefaultApi(); // String | The ID of the Client VPN endpoint to modify // String | Region where you are making the request\n /*let clientVpnEndpointId = \"clientVpnEndpointId_example\";*/ /*let region = \"region_example\";*/ let opts = {\n // 'xAmzContentSha256': \"xAmzContentSha256_example\", // String |\n // 'xAmzDate': \"xAmzDate_example\", // String |\n // 'xAmzAlgorithm': \"xAmzAlgorithm_example\", // String |\n // 'xAmzCredential': \"xAmzCredential_example\", // String |\n // 'xAmzSecurityToken': \"xAmzSecurityToken_example\", // String |\n // 'xAmzSignature': \"xAmzSignature_example\", // String |\n // 'xAmzSignedHeaders': \"xAmzSignedHeaders_example\", // String |\n // 'serverCertificateArn': \"serverCertificateArn_example\", // String | The ARN of the server certificate to be used. The server certificate must be provisioned in AWS Certificate Manager (ACM).\n // 'connectionLogOptionsEnabled': \"connectionLogOptionsEnabled_example\", // String | Describes the client connection logging options for the Client VPN endpoint. Indicates whether connection logging is enabled.\n // 'connectionLogOptionsCloudwatchLogGroup': \"connectionLogOptionsCloudwatchLogGroup_example\", // String | Describes the client connection logging options for the Client VPN endpoint. The name of the CloudWatch Logs log group.\n // 'connectionLogOptionsCloudwatchLogStream': \"connectionLogOptionsCloudwatchLogStream_example\", // String | Describes the client connection logging options for the Client VPN endpoint. The name of the CloudWatch Logs log stream to which the connection data is published.\n dnsServersCustomDnsServers: [\"null\"], // [String] | Information about the DNS server to be used. The IPv4 address range, in CIDR notation, of the DNS servers to be used. You can specify up to two DNS servers. Ensure that the DNS servers can be reached by the clients. The specified values overwrite the existing values.\n // 'dnsServersEnabled': \"dnsServersEnabled_example\", // String | Information about the DNS server to be used. Indicates whether DNS servers should be used. Specify <code>False</code> to delete the existing DNS servers.\n // 'description': \"description_example\", // String | A brief description of the Client VPN endpoint.\n splitTunnel: true, // Boolean | <p>Indicates whether the VPN is split-tunnel.</p> <p>For information about split-tunnel VPN endpoints, see <a href=\\\"https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/split-tunnel-vpn.html\\\">Split-Tunnel AWS Client VPN Endpoint</a> in the <i>AWS Client VPN Administrator Guide</i>.</p>\n dryRun: false, // Boolean | Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is <code>DryRunOperation</code>. Otherwise, it is <code>UnauthorizedOperation</code>.\n // 'action': \"action_example\", // String |\n version: \"'2016-11-15'\" // String |\n };\n\n if (!incomingOptions.opts) delete incomingOptions.opts;\n incomingOptions.opts = Object.assign(opts, incomingOptions.opts);\n\n apiInstance.actionModifyClientVpnEndpointGet(\n incomingOptions.clientVpnEndpointId,\n incomingOptions.region,\n incomingOptions.opts,\n (error, data, response) => {\n if (error) {\n cb(error, null, response);\n } else {\n cb(null, data, response);\n }\n }\n );\n }",
"function processV2Request (request, response) {\n // An action is a string used to identify what needs to be done in fulfillment\n let action = (request.body.queryResult.action) ? request.body.queryResult.action : 'default';\n // Parameters are any entites that Dialogflow has extracted from the request.\n let parameters = request.body.queryResult.parameters || {}; // https://dialogflow.com/docs/actions-and-parameters\n // Contexts are objects used to track and store conversation state\n let inputContexts = request.body.queryResult.contexts; // https://dialogflow.com/docs/contexts\n // Get the request source (Google Assistant, Slack, API, etc)\n let requestSource = (request.body.originalDetectIntentRequest) ? request.body.originalDetectIntentRequest.source : undefined;\n // Get the session ID to differentiate calls from different users\n let session = (request.body.session) ? request.body.session : undefined;\n // Create handlers for Dialogflow actions as well as a 'default' handler\n const actionHandlers = {\n // The default welcome intent has been matched, welcome the user (https://dialogflow.com/docs/events#default_welcome_intent)\n 'input.welcome': () => {\n sendResponse('Hello, Welcome to my Dialogflow agent!'); // Send simple response to user\n },\n // Wenn eine Frage zu einem Versicherungsthema gestellt wurde, hole die Antwort aus der Datenbank und gib sie aus\n 'input.versicherungsfrage': () => {\n let begriff = request.body.queryResult.parameters.Versicherungsthema;\n if ( begriff === '' ) {\n // Wenn in der Benutzereingabe die gesuchte Entity nicht erkannt wurde, macht die Suche in der DB keinen Sinn\n sendResponse('Diese Frage kann ich zum glück nicht beantworten :)');\n console.log('Begriff nicht vorgesehen: ' + request.body.queryResult.queryText);\n } else {\n var document = db.collection('Begriffe').doc(begriff);\n var getDoc = document.get()\n .then(doc => {\n if (doc.exists) {\n // Begriff wurde in DB gefunden, Beschreibung ausgeben\n sendResponse(doc.data().Beschreibung );\n console.log( 'Begriff gefunden: ', doc.data() );\n } else {\n // Begriff wurde nicht in DB gefunden, Meldung ausgeben\n sendResponse('Den Begriff ' + begriff + ' kann ich leider nicht erklären.');\n console.log('Begriff nicht gefunden: ' + begriff);\n }\n });\n }\n },\n 'input.kontaktdaten': () => {\n let begriff = request.body.queryResult.parameters.Kontaktmedium;\n if (begriff === '') {\n sendResponse('Bitte gebe an, welche Art von Kontaktdaten Du wissen willst.');\n } else {\n let person = 'Erkan'\n var document = db.collection('Kontaktmedien').doc(person);\n\n var getDoc = document.get()\n .then(doc => {\n if (!doc.exists) {\n sendResponse('Zu diesem Namen wurde leider nichts gefunden.');\n console.log('Document nicht gefunden: ' + person);\n } else {\n console.log('Begriff gefunden: ' + begriff);\n if (begriff === 'Mailadresse') {\n sendResponse('Die uns bekannte E-Mailadresse lautet: ' + doc.data().Mailadresse);\n } else if (begriff === 'Adresse') {\n sendResponse('Die uns bekannte Adresse lautet: ' + doc.data().Adresse);\n } else if (begriff === 'Telefon') {\n sendResponse('Die uns bekannte Rufnummer lautet: ' + doc.data().Telefon);\n }\n }\n }\n );\n }\n //sendResponse('42');\n //console.log('42');\n },\n //Wenn der Kundenname angegeben wurde, dann springe abhängig vom Alter des Kunden zu verschiedenen weiteren Intents\n // 'input.kundenname': () => {\n // let alter = '';\n // let c = request.body.queryResult.outputContexts;\n // if ( c ) {\n // for (var i=0; i<c.length; i++) {\n // if (c[i].parameters.Alter > 0) {\n // alter = c[i].parameters.Alter;\n // }\n // }\n // }\n // let event = '';\n // if ( alter >= 30 ) {\n // event = 'Event_ab_30';\n // } else {\n // event = 'Event_unter_30';\n // }\n // let res = {\n // followupEventInput: {\n // name: event,\n // languageCode: \"de\"\n // }\n // };\n // sendResponse( res );\n // },\n 'input.laufleistung_aktuell': () => {\n //Die Laufleistung des Kunden ist aktuell wir suchen nach einer anderen Lösung\n //für die Preissenkung\n let event = 'Event_laufleistung_aktuell';\n let res = {\n followupEventInput: {\n name: event,\n languageCode: \"de\"\n }\n };\n\n sendResponse( res );\n },\n // The default fallback intent has been matched, try to recover (https://dialogflow.com/docs/intents#fallback_intents)\n 'input.unknown': () => {\n // Use the Actions on Google lib to respond to Google requests; for other requests use JSON\n sendResponse('I\\'m having trouble, can you try that again?'); // Send simple response to user\n },\n // Default handler for unknown or undefined actions\n 'default': () => {\n let responseToUser = {\n //fulfillmentMessages: richResponsesV2, // Optional, uncomment to enable\n //outputContexts: [{ 'name': `${session}/contexts/weather`, 'lifespanCount': 2, 'parameters': {'city': 'Rome'} }], // Optional, uncomment to enable\n fulfillmentText: 'This is from Dialogflow\\'s Cloud Functions for Firebase editor! :---)' // displayed response\n };\n sendResponse(responseToUser);\n }\n };\n // If undefined or unknown action use the default handler\n if (!actionHandlers[action]) {\n action = 'default';\n }\n // Run the proper handler function to handle the request from Dialogflow\n actionHandlers[action]();\n // Function to send correctly formatted responses to Dialogflow which are then sent to the user\n function sendResponse (responseToUser) {\n // if the response is a string send it as a response to the user\n if (typeof responseToUser === 'string') {\n let responseJson = {fulfillmentText: responseToUser}; // displayed response\n response.json(responseJson); // Send response to Dialogflow\n } else {\n // If the response to the user includes rich responses or contexts send them to Dialogflow\n let responseJson = {};\n // ergänzt Drawehn 12.01.2018\n if (responseToUser.followupEventInput) {\n responseJson.followupEventInput = responseToUser.followupEventInput;\n }\n // Define the text response\n responseJson.fulfillmentText = responseToUser.fulfillmentText;\n // Optional: add rich messages for integrations (https://dialogflow.com/docs/rich-messages)\n if (responseToUser.fulfillmentMessages) {\n responseJson.fulfillmentMessages = responseToUser.fulfillmentMessages;\n }\n // Optional: add contexts (https://dialogflow.com/docs/contexts)\n if (responseToUser.outputContexts) {\n responseJson.outputContexts = responseToUser.outputContexts;\n }\n // Send the response to Dialogflow\n console.log('Response to Dialogflow: ' + JSON.stringify(responseJson));\n response.json(responseJson);\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all jobs associated with the given runner_id runner_id String, unique identifier for runner callback f(err, jobs). `jobs` is an array of job's UUIDs. Note `jobs` will be an array, even when empty. | function getRunnerJobs(runner_id, callback) {
client.smembers('wf_runner:' + runner_id, function (err, jobs) {
if (err) {
log.error({err: err});
return callback(new wf.BackendInternalError(err));
}
return callback(null, jobs);
});
} | [
"function runJob(uuid, runner_id, callback) {\n if (typeof (uuid) === 'undefined') {\n return callback(new wf.BackendInternalError(\n 'WorkflowRedisBackend.runJob uuid(String) required'));\n }\n var multi = client.multi();\n\n return client.lrem('wf_queued_jobs', 0, uuid, function (err, res) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n }\n\n if (res <= 0) {\n return callback(new wf.BackendPreconditionFailedError(\n 'Only queued jobs can be run'));\n }\n\n client.watch('job:' + uuid);\n multi.sadd('wf_runner:' + runner_id, uuid);\n multi.rpush('wf_running_jobs', uuid);\n multi.hset('job:' + uuid, 'execution', 'running');\n multi.hset('job:' + uuid, 'runner_id', runner_id);\n return multi.exec(function (err, replies) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n } else {\n return getJob(uuid, callback);\n }\n });\n });\n }",
"function getJobList() {\n return jobs;\n }",
"get_all_jobs() {\n var self = this;\n\n return _.values(self._jobs);\n }",
"get jobs() {\n const listConfig = {\n params: {\n pipelineId: this.id\n },\n paginate: {\n count: PAGINATE_COUNT,\n page: PAGINATE_PAGE\n }\n };\n\n // Lazy load factory dependency to prevent circular dependency issues\n // https://nodejs.org/api/modules.html#modules_cycles\n /* eslint-disable global-require */\n const JobFactory = require('./jobFactory');\n /* eslint-enable global-require */\n const factory = JobFactory.getInstance();\n\n const jobs = factory.list(listConfig);\n\n // ES6 has weird getters and setters in classes,\n // so we redefine the pipeline property here to resolve to the\n // resulting promise and not try to recreate the factory, etc.\n Object.defineProperty(this, 'jobs', {\n enumerable: true,\n value: jobs\n });\n\n return jobs;\n }",
"function runJob(uuid, runner_id, callback) {\n\n var error = null;\n var job = null;\n\n try {\n client.query('BEGIN');\n var query = 'SELECT * FROM wf_jobs WHERE uuid=$1 AND ' +\n 'runner_id IS NULL AND execution=\\'queued\\' FOR UPDATE NOWAIT';\n var vals = [uuid];\n log.debug({query: query, vals: vals});\n client.query(query, vals, function (err, res) {\n if (err) {\n log.error({err: err});\n throw new Error(err.Error);\n }\n if (res.rows.length === 0) {\n error = new wf.BackendPreconditionFailedError(sprintf(\n 'Job with uuid \\'%s\\' is not queued', uuid));\n }\n });\n\n var q2 = 'UPDATE wf_jobs SET (runner_id, execution)=($1,' +\n ' \\'running\\') WHERE uuid=$2 AND execution=\\'queued\\' ' +\n 'AND runner_id IS NULL RETURNING *';\n var v2 = [runner_id, uuid];\n log.debug({query: q2, vals: v2});\n client.query(q2, v2, function (err, res) {\n if (err) {\n log.error({err: err});\n throw err;\n }\n if (res.rows.length === 0) {\n error = new wf.BackendPreconditionFailedError(sprintf(\n 'Unable to lock job \\'%s\\'', uuid));\n } else {\n job = res.rows[0];\n }\n });\n\n return client.query('COMMIT', function () {\n if (job) {\n return callback(null, _decodeJob(job));\n } else {\n return callback(error);\n }\n });\n } catch (e) {\n error = e.message;\n return callback(new wf.BackendInternalError(error));\n }\n }",
"async getJobs(ctx) {\n\n let result = Joi.validate(ctx.query, jobQuerySchema.jobList);\n if (result.error !== null) {\n ctx.throw(400);\n }\n\n let jobs = await jobModel.\n listJobs(ctx.query.q, ctx.query.limit, ctx.query.offset, ctx.query.order)\n .catch(err => {\n ctx.throw(err);\n });\n if (!jobs) {\n ctx.throw(404);\n }\n ctx.body = { data: jobs, error: null };\n\n }",
"function findJobById (id) {\r\n return state.jobs.find(job => job.id === id);\r\n}",
"get_job(job_id) {\n var self = this;\n\n if (! _.has(self._jobs, job_id)) {\n return undefined;\n } else {\n return self._jobs[job_id];\n }\n }",
"function findAll() {\n return new Promise(function (resolve, reject) {\n let jobs = queueService.getJobList();\n resolve(jobs);\n });\n }",
"function poll_jobs(data) {\n var promises = [];\n\n if(debug) {\n console.log('Jobs data: ', data);\n }\n\n // Push promises into array\n for(var job in data) {\n var job_id = data[job].id;\n var api_url = '/job/'+job_id;\n\n if (debug) {\n console.log('Processing job: ', data[job]);\n }\n\n promises.push(new Promise(function(resolve, reject) {\n var maxRun = plugin_timeout/2;\n var timesRun = 0;\n\n // Timer function that polls the API for job results\n var pollJob = function() {\n ajaxReq = $.get(api_url);\n ajaxReq.done(function(getResponse) {\n // Verify job data\n var job_result = getResponse;\n\n if (debug) {\n console.log('Job results: ', job_result);\n }\n\n console.log(job_result);\n if(job_result.is_finished) {\n console.log('Resolving job: ', job_result);\n resolve(job_result);\n clearTimeout(timer);\n return(true);\n }\n\n if(job_result.is_failed) {\n console.log('Job failed: ', job_result);\n reject(job_result);\n clearTimeout(timer);\n return(false);\n }\n });\n\n ajaxReq.fail(function(XMLHttpRequest, textStatus, errorThrown) {\n console.log('Request Error: '+ XMLHttpRequest.responseText + ', status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText);\n reject(XMLHttpRequest.responseText);\n });\n\n // Set timeout recursively until a certain threshold is reached\n if (++timesRun == maxRun) {\n clearTimeout(timer);\n reject(\"Job polling timed out\");\n return;\n } else {\n timer = setTimeout(pollJob, 2000);\n }\n };\n\n var timer = setTimeout(pollJob, 500);\n }));\n }\n\n // Run .all() on promises array until all promises resolve\n // This is resolve() above.\n Promise.all(promises).then(function(result) {\n var success = true;\n\n for(var i=0;i<result.length;i++) {\n var r = result[i].result;\n var meta = result[i].meta;\n if (meta.mandatory) {\n if (result[i].is_finished && result[i].is_failed) {\n do_error(r.error);\n success = false;\n break;\n }\n }\n }\n\n if (success) {\n // This is for Steve...\n // Apple devices don't poll their captiveportal URL,\n // so this is for them. Android devices will do their\n // own polling and close the wifi-portal before this.\n setTimeout(do_success, 30000);\n }\n\n // This is reject() above.\n }, function(reason) {\n do_error(reason);\n });\n}",
"getJobs(){\n\t\tApiClient.get('/jobs')\n\t\t\t.then(response => {\n\t\t\t\tthis.setState({\n\t\t\t\t\t\tisLoaded: true,\n\t\t\t\t\t\tjobs: response.data,\n\t\t\t\t});\n\t\t\t})\n\t\t\t.catch(error => {\n\t\t\t\tthis.setState({\n\t\t\t\t\tisLoaded: true,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t});\n\t}",
"function getPrinterJobs(printer) {\n return printer.queue.map((jId) => Pmgr.globalState.jobs.find((j) => j.id == jId));\n}",
"static async getFilteredJobs(params) {\n let res = await this.request('jobs/', params);\n return res.jobs;\n }",
"get jobs() {\n\t\treturn this.lines.filter(line => line instanceof Cronjob);\n\t}",
"static async companyJobUsers(job_id) {\n\t\t// fetch all jobs\n\t\treturn await models.JobUser.findAll({\n\t\t\twhere: {\n\t\t\t\tjob_id,\n\t\t\t\tapproved_by_user: true\n\t\t\t},\n\t\t\tinclude: [\n\t\t\t\t{\n\t\t\t\t\tmodel: models.User,\n\t\t\t\t\tinclude: {\n\t\t\t\t\t\tmodel: models.Message,\n\t\t\t\t\t\tas: 'sender',\n\t\t\t\t\t\twhere: {\n\t\t\t\t\t\t\tjob_id,\n\t\t\t\t\t\t\tis_read: false\n\t\t\t\t\t\t},\n\t\t\t\t\t\trequired: false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t]\n\t\t})\n\t}",
"linkJobs(appId, jobs) {\n var elems = [];\n for (var i = 0; i < jobs.length; i++) {\n var jobId = jobs[i];\n var elem = (\n <span key={jobId}>\n <Link to={`/apps/${appId}/jobs/${jobId}`}>{jobId}</Link>\n <span>{(i < jobs.length - 1) ? \", \" : \"\"}</span>\n </span>\n );\n elems.push(elem);\n }\n return elems;\n }",
"function getJobs(params, callback) {\n var executions = ['queued', 'failed', 'succeeded',\n 'canceled', 'running', 'retried', 'waiting'];\n var list_name;\n var execution;\n var offset;\n var limit;\n\n if (typeof (params) === 'object') {\n execution = params.execution;\n delete params.execution;\n offset = params.offset;\n delete params.offset;\n limit = params.limit;\n delete params.limit;\n }\n\n if (typeof (params) === 'function') {\n callback = params;\n params = {};\n }\n\n if (typeof (limit) === 'undefined') {\n limit = 1000;\n }\n\n if (typeof (offset) === 'undefined') {\n offset = 0;\n }\n\n if (typeof (execution) === 'undefined') {\n return client.smembers('wf_jobs', function (err, results) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n }\n return processJobList(\n results, params, client, offset, limit, callback);\n });\n } else if (executions.indexOf(execution !== -1)) {\n list_name = 'wf_' + execution + '_jobs';\n return client.llen(list_name, function (err, res) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n }\n return client.lrange(\n list_name,\n 0,\n (res + 1),\n function (err, results) {\n if (err) {\n log.error({err: err});\n return callback(new wf.BackendInternalError(err));\n }\n return processJobList(\n results, params, client, offset, limit, callback);\n });\n });\n } else {\n return callback(new wf.BackendInvalidArgumentError(\n 'excution is required and must be one of' +\n '\"queued\", \"failed\", \"succeeded\", \"canceled\", \"running\"' +\n ', \"retried\", \"waiting\"'));\n }\n }",
"async getTrainJobsByUser(userId) {\n const data = await this._get('/train_jobs', {\n 'user_id': userId\n });\n const trainJobs = data.map((x) => this._toTrainJob(x));\n return trainJobs;\n }",
"static async getJob(id) {\n const res = await this.request(`jobs/${id}`);\n return res.job;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chapter Common Achievements, overrides the image display with any image from any chapter (related to the selected achievement) | function C999_Common_Achievements_ShowImage(ImagePath) {
C999_Common_Achievements_Image = ImagePath;
} | [
"function C999_Common_Achievements_Run() {\n BuildInteraction(C999_Common_Achievements_CurrentStage);\n if ((C999_Common_Achievements_Image !== undefined) && (C999_Common_Achievements_Image.trim() != \"\")) {\n DrawImage(C999_Common_Achievements_Image, 600, 0);\n }\n}",
"function aiImage(aichoice) {\n if (aichoice === \"rock\") {\n setAiImgChoice(aiImgChoice = rocks)\n } else if (aichoice === \"paper\") {\n setAiImgChoice(aiImgChoice = paper)\n } else {\n setAiImgChoice(aiImgChoice = scissors)\n }\n }",
"function C999_Common_Achievements_MainMenu() {\n C999_Common_Achievements_ResetImage();\n\tSetScene(\"C000_Intro\", \"ChapterSelect\");\n}",
"static paintAchievementIcon(ctx, achievement) {\n const background = GdkPixbuf.Pixbuf.new_from_resource(\n '/img/achievements/' + achievement.bgImage);\n const foreground = GdkPixbuf.Pixbuf.new_from_resource(\n '/img/achievements/' + achievement.fgImage);\n const gloss = GdkPixbuf.Pixbuf.new_from_resource('/img/achievements/gloss.png');\n\n Gdk.cairo_set_source_pixbuf(ctx, background, 0, 0);\n ctx.paint();\n\n Gdk.cairo_set_source_pixbuf(ctx, foreground, 0, 0);\n ctx.paint();\n\n Gdk.cairo_set_source_pixbuf(ctx, gloss, 0, 0);\n ctx.paint();\n }",
"function C999_Common_Achievements_ResetImage() {\n C999_Common_Achievements_Image = \"\";\n}",
"function SetAchievementsDiv( appid, achievements )\n{\n\tvar parentDiv = $('appAchievementDisplay');\n\tvar theItem;\n\tvar index;\n\tvar items = achievements;\n\tvar elt;\n\tvar eltSub;\n\tvar eltRow;\n\tvar text;\n\tvar newImg;\n\n\tparentDiv.update('');\n\n\t// crack parameter and iterate achievements/stats\n\tfor ( index = 0; index < items.length; index++ )\n\t{\n\t\ttheItem = items[ index ];\n\n\t\t// make a new container \"row\" div for the whole item\n\t\teltRow = new Element( 'div' );\n\t\tparentDiv.insert( eltRow );\n\n\t\tvar achievement = theItem;\n\n\t\t// achievement specific:\n\t\t// jam a bunch of floated-left divs in there to hold the item's fields\n\t\telt = new Element( 'div', { 'style' : 'float: left; width: 6em' } );\n\t\telt.update( achievement[ \"stat_id\" ] + \"/\" + achievement[ \"bit_id\" ] );\n\t\teltRow.insert( elt );\n\n\t\telt = new Element( 'div', { 'style' : 'float: left; width: 24em' } );\n\t\telt.update( achievement[ 'api_name' ] );\n\t\telt.insert( new Element( 'br' ) );\n\t\t// Add the achievement progress stat line\n\t\tif ( typeof achievement[ 'progress' ] === 'object' )\n\t\t{\n\t\t\t// currently only support direct stat value mapping\n\t\t\tprogressSpan = new Element( 'span' );\n\t\t\tprogressSpan.innerHTML = achievement.progress.value.operand1 + ' (' + achievement.progress.min_val + '-' + achievement.progress.max_val + ')';\n\n\t\t\telt.insert( progressSpan );\n\t\t}\n\t\teltRow.insert( elt );\n\n\n\t\telt = new Element( 'div', { 'style' : 'float: left; width: 36em' } );\n\t\tvar rgLanguageDisplay = g_rgLanguages;\n\t\tvar bPrefix = false;\n\t\tvar languages;\n\t\tif ( g_language == \"all\" )\n\t\t{\n\t\t\tlanguages = g_rgEditingLanguages;\n\t\t\tbPrefix = true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlanguages = {};\n\t\t\tlanguages[ g_language ] = 1;\n\t\t}\n\n\t\tfor ( language in languages )\n\t\t{\n\t\t\teltSub = AchievementSpan( achievement, \"display_name\", achievement.api_name + '_NAME', language );\n\t\t\tif ( bPrefix )\n\t\t\t{\n\t\t\t\teltSub.insert( { 'top' : new Element( 'span' ).update( \"[\" + rgLanguageDisplay[ language ] + \"] \") } );\n\t\t\t}\n\t\t\telt.insert( eltSub );\n\t\t}\n\n\t\t// TODO Commonify description and display name\n\t\tfor ( language in languages )\n\t\t{\n\t\t\teltSub = AchievementSpan( achievement, \"description\", achievement.api_name + '_DESC', language );\n\t\t\tif ( bPrefix )\n\t\t\t{\n\t\t\t\teltSub.insert( { 'top' : new Element( 'span' ).update( \"[\" + rgLanguageDisplay[ language ] + \"] \") } );\n\t\t\t}\n\t\t\telt.insert( eltSub );\n\t\t}\n\t\teltRow.insert( elt );\n\n\t\telt = new Element( 'div', { 'style': 'float: left; width: 5em' } );\n\t\tswitch ( achievement[ \"permission\" ] )\n\t\t{\n\t\tcase \"1\": elt.update( \"GS\" ); break;\n\t\tcase \"2\": elt.update( \"Official GS\" ); break;\n\n\t\tcase \"0\":\n\t\tdefault:\n\t\t\telt.update( \"Client\" );\n\t\t}\n\t\teltRow.insert( elt );\n\n\t\t// give this element a minimum height, since it is often empty of content and\n\t\t// would snap to zero height\n\t\telt = new Element( 'div', { 'style': 'float: left; width: 4em; height: 1em' } );\n\t\tif ( achievement[ \"hidden\" ] != 0 )\n\t\t{\n\t\t\telt.update( \"<b>\"+\"Yes\"+\"</b>\" );\n\t\t}\n\t\teltRow.insert( elt );\n\n\t\tnewImg = new Element( 'img', { 'style': 'float: left' } );\n\t\tnewImg.src = achievement[ \"icon\" ];\n\t\tnewImg.height = 64;\n\t\tnewImg.width = 64;\n\t\teltRow.insert( newImg );\n\n\t\tnewImg = new Element( 'img' );\n\t\tnewImg.src = achievement[ \"icon_gray\" ];\n\t\tnewImg.height = 64;\n\t\tnewImg.width = 64;\n\t\teltRow.insert( newImg );\n//\t\tvar btnCell = destRow.insertCell( -1 );\n//\n//\t\tvar btn = document.createElement( \"input\" );\n//\t\tbtn.type= \"submit\";\n//\t \tbtn.onclick = EditAchievementClosure( appid, achievement[ \"stat_id\" ], achievement[ \"bit_id\" ] );\n//\t\tbtn.value = \"Edit\";\n//\t\tbtnCell.appendChild( btn );\n//\n//\t\tbtnCell.appendChild( document.createElement( \"br\" ) );\n//\n//\t\tvar btn2 = document.createElement( \"input\" );\n//\t\tbtn2.type = \"submit\";\n//\t \tbtn2.onclick = DeleteAchievementClosure( appid, achievement[ \"stat_id\" ], achievement[ \"bit_id\" ] );\n//\t\tbtn2.value = \"Delete\";\n//\t\tbtnCell.appendChild( btn2 );\n//\n\t\t// all done with this row\n\t\teltRow.insert( new Element( 'div', { 'style' : 'clear: both' } ) );\n\t}\n}",
"function onAchClicked() {\n if (!gameservices.signedIn) {\n alert(\"Please sign in with Google to see achievements.\");\n return;\n }\n\n // fill in achievements screen\n var htmlv = [];\n htmlv.push(_makeAchBox(gameservices.ACHIEVEMENTS.OVUM));\n htmlv.push(_makeAchBox(gameservices.ACHIEVEMENTS.KILL_ENEMY));\n htmlv.push(_makeAchBoxV(gameservices.ACHIEVEMENTS.PRECISION));\n htmlv.push(_makeAchBoxV(gameservices.ACHIEVEMENTS.INTEGRITY));\n htmlv.push(_makeAchBoxV(gameservices.ACHIEVEMENTS.RANK));\n htmlv.push(_makeAchBoxV(gameservices.ACHIEVEMENTS.EXPERIENCE));\n htmlv.push(_makeAchBox(gameservices.ACHIEVEMENTS.FREQUENT));\n htmlv.push(_makeAchBox(gameservices.ACHIEVEMENTS.SERIOUS.id));\n $('#ach_list').html(htmlv.join(''));\n\n // show achievements screen\n $('.screen').hide();\n $('#ach_div').show();\n}",
"function loadChaplainImage() {\n\tgetWikiImage($(\"#chaplain-name\").text());\n}",
"function _makeAchBox(id) {\n var ach = gameservices.achievements[id];\n if (!ach) {\n console.log(\"BUG: achievement ID not found: \" + id);\n return \"?\";\n }\n\n // if this achievement is hidden, we obviously don't want to show it:\n if (ach.hidden) return \"\";\n\n var inc = \"\";\n if (ach.def.achievementType == \"INCREMENTAL\" && !ach.unlocked) {\n inc = \" (progress: \" + ach.currentSteps + \"/\" + ach.def.totalSteps + \")\";\n }\n\n return \"<div class='ach_list_item'><img src='\" +\n (ach.unlocked ? ach.def.unlockedIconUrl : ach.def.revealedIconUrl) +\n \"?size=32' class='ach_icon'><div class='ach_info'>\" +\n \"<span class='ach_name_\" + (ach.unlocked ? \"unlocked\" : \"locked\") + \"'>\"+\n ach.def.name + \"</span><br/><span class='ach_desc_\" +\n (ach.unlocked ? \"unlocked\" : \"locked\") + \"'>\" +\n ach.def.description + inc + \"</span></div></div>\";\n}",
"displayAchievements(achievements) {\n this.elementList.achievementDisplay.innerHTML = '<hr><h5 class=\"center-align\">Achievements</h5>';\n achievements.forEach((achievement) => {\n const opaqueness = achievement.unlocked ? '' : 'opaque';\n const tooltip = achievement.unlocked ? achievement.description : achievement.descriptionReq;\n this.elementList.achievementDisplay.innerHTML += `\n <img\n src=\"${achievement.picture}\"\n class=\"tooltipped ${opaqueness} hoverable\"\n data-position=\"top\" data-delay=\"30\"\n data-tooltip=\"${achievement.name}: ${tooltip}\"\n >`;\n });\n // initialize materialize tooltips\n $('.tooltipped').tooltip({ delay: 50 });\n }",
"function showAchievement(i) {\r\n\tvar x = achievements[i].x;\r\n\tvar y = achievements[i].y;\r\n\t\r\n\t$(\"#popup_achievement\").css(\"opacity\", \"1\");\r\n\t$(\"#achievement_display\").attr(\"style\", \"float:left;height:48px;width:48px;background:url(images/achievement_sheet.png) -\"+x+\"px -\"+y+\"px;\");\r\n\t$(\"#achievement_title\").html(achievements[i].name + \" Completed\");\r\n\t$(\"#popup_achievement\").offset({ top: ($(\"#global_achievements\").offset().top), left: ($(\"#global_achievements\").offset().left)});\r\n\t\r\n\tif (achievements[i].upgrade) {upgrades[achievements[i].upgrade].makeAvailable();}\r\n\t\r\n\tif (upgrades[205].bought) {addClockTicks(30);}\r\n}",
"function achievementDescriptions(){\n\t\tdrawText(0.2, 0.35, 0.04, \"5 in a Row\", 'black');\n\t\tdrawText(0.5, 0.35, 0.04, \"Level 4\", 'black');\n\t\tdrawText(0.8, 0.35, 0.04, \"Perfect 8\", 'black');\n\t}",
"function updateDisplayImg() {\n\t\tstate = gameState.chances;\n\t\tgameState.currentImg.src = `assets/images/hang_${state}.png`\n\t}",
"function showChampImgFromChampId(championId, classType) {\n var champion = championId;\n\n if (ChampKeys.hasOwnProperty(championId)) {\n champion = ChampKeys[championId];\n return (\n <img\n className={classType}\n src={`${ImgHostURL}/champion/${champion}.png`}\n alt={champion}\n />\n );\n }\n\n // shows if the champion cannot be found in ChampKeys\n return <img className={classType} src=\"\" alt={champion} />;\n}",
"_createAchievements() {\n\n const attributes = [\n // Translators: This is the tier 1 attribute which will be inserted for each %s\n // in the achievement titles.\n _('Novice'),\n // Translators: This is the tier 2 attribute which will be inserted for each %s\n // in the achievement titles.\n _('Capable'),\n // Translators: This is the tier 3 attribute which will be inserted for each %s\n // in the achievement titles.\n _('Skilled'),\n // Translators: This is the tier 4 attribute which will be inserted for each %s\n // in the achievement titles.\n _('Expert'),\n // Translators: This is the tier 5 attribute which will be inserted for each %s\n // in the achievement titles.\n _('Master')\n ];\n\n const numbers = [\n // Translators: This is the tier 1 number which will be inserted for each %i in\n // the achievement titles.\n _('I'),\n // Translators: This is the tier 2 number which will be inserted for each %i in\n // the achievement titles.\n _('II'),\n // Translators: This is the tier 3 number which will be inserted for each %i in\n // the achievement titles.\n _('III'),\n // Translators: This is the tier 4 number which will be inserted for each %i in\n // the achievement titles.\n _('IV'),\n // Translators: This is the tier 5 number which will be inserted for each %i in\n // the achievement titles.\n _('V')\n ];\n\n // These are the icon background images used by the five tiers.\n const bgImages =\n ['copper.png', 'bronze.png', 'silver.png', 'gold.png', 'platinum.png'];\n\n const formatName = (name, i) => {\n return name.replace('%s', attributes[i]).replace('%i', numbers[i]);\n };\n\n const achievements = new Map();\n\n for (let i = 0; i < 5; i++) {\n achievements.set('cancellor' + i, {\n // Translators: The name of the 'Abort a selection %x times.' achievement.\n name: formatName(_('%s Cancellor'), i),\n description:\n // Translators: The description of the '%s Cancellor' achievement.\n _('Abort a selection %x times.').replace('%x', BASE_RANGES[i + 1] * 2),\n bgImage: bgImages[i],\n fgImage: 'cancel.svg',\n statsKey: 'stats-abortions',\n xp: BASE_XP[i],\n range: [BASE_RANGES[i] * 2, BASE_RANGES[i + 1] * 2],\n hidden: false\n });\n }\n\n for (let i = 0; i < 5; i++) {\n achievements.set('master' + i, {\n // Translators: The name of the 'Select %x items.' achievement.\n name: formatName(_('%s Pielot'), i),\n // Translators: The description of the '%s Pielot' achievement.\n description: _('Select %x items.').replace('%x', BASE_RANGES[i + 1] * 5),\n bgImage: bgImages[i],\n fgImage: `award${i}.svg`,\n statsKey: 'stats-selections',\n xp: BASE_XP[i] * 2,\n range: [BASE_RANGES[i] * 5, BASE_RANGES[i + 1] * 5],\n hidden: false\n });\n }\n\n for (let depth = 1; depth <= 3; depth++) {\n const names = [\n // Translators: The name of the 'Select %x items at depth 1 in marking mode.'\n // achievement.\n _('%s Toplevel Gesture-Selector'),\n // Translators: The name of the 'Select %x items at depth 2 in marking mode.'\n // achievement.\n _('%s Submenu Gesture-Selector'),\n // Translators: The name of the 'Select %x items at depth 3 in marking mode.'\n // achievement.\n _('%s Subsubmenu Gesture-Selector')\n ];\n\n for (let i = 0; i < 5; i++) {\n achievements.set(`depth${depth}-gesture-selector${i}`, {\n name: formatName(names[depth - 1], i),\n // Translators: The description of the 'Gesture-Selector' achievement.\n description: _('Select %x items at depth %d in marking mode.')\n .replace('%x', BASE_RANGES[i + 1] * 2)\n .replace('%d', depth),\n bgImage: bgImages[i],\n fgImage: `gesture${depth}.svg`,\n statsKey: `stats-gesture-selections-depth${depth}`,\n xp: BASE_XP[i],\n range: [BASE_RANGES[i] * 2, BASE_RANGES[i + 1] * 2],\n hidden: false\n });\n }\n }\n\n for (let depth = 1; depth <= 3; depth++) {\n const names = [\n // Translators: The name of the 'Select %x items at depth 1 with mouse\n // clicks.' achievement.\n _('%s Toplevel Click-Selector'),\n // Translators: The name of the 'Select %x items at depth 2 with mouse\n // clicks.' achievement.\n _('%s Submenu Click-Selector'),\n // Translators: The name of the 'Select %x items at depth 3 with mouse\n // clicks.' achievement.\n _('%s Subsubmenu Click-Selector')\n ];\n\n for (let i = 0; i < 5; i++) {\n achievements.set(`depth${depth}-click-selector${i}`, {\n name: formatName(names[depth - 1], i),\n // Translators: The description of the 'Click-Selector' achievement.\n description: _('Select %x items at depth %d with mouse clicks.')\n .replace('%x', BASE_RANGES[i + 1] * 2)\n .replace('%d', depth),\n bgImage: bgImages[i],\n fgImage: `click${depth}.svg`,\n statsKey: `stats-click-selections-depth${depth}`,\n xp: BASE_XP[i],\n range: [BASE_RANGES[i] * 2, BASE_RANGES[i + 1] * 2],\n hidden: false\n });\n }\n }\n\n {\n const timeLimits = [\n [1000, 750, 500, 250, 150], [2000, 1000, 750, 500, 250],\n [3000, 2000, 1000, 750, 500]\n ];\n\n const names = [\n // Translators: The name of the 'Select %x items at depth 1 in less than %t\n // milliseconds.' achievement.\n _('%s Toplevel Selector'),\n // Translators: The name of the 'Select %x items at depth 2 in less than %t\n // milliseconds.' achievement.\n _('%s Submenu Selector'),\n // Translators: The name of the 'Select %x items at depth 3 in less than %t\n // milliseconds.' achievement.\n _('%s Subsubmenu Selector')\n ];\n\n const counts = [50, 100, 150, 200, 250];\n\n for (let depth = 1; depth <= 3; depth++) {\n for (let i = 0; i < 5; i++) {\n\n achievements.set(`depth${depth}-selector${i}`, {\n name: formatName(names[depth - 1], i),\n description:\n // Translators: The description of the 'Selector' achievement.\n _('Select %x items at depth %d in less than %t milliseconds.')\n .replace('%x', counts[i])\n .replace('%t', timeLimits[depth - 1][i])\n .replace('%d', depth),\n bgImage: bgImages[i],\n fgImage: `timer.svg`,\n statsKey: `stats-selections-${timeLimits[depth - 1][i]}ms-depth${depth}`,\n xp: BASE_XP[i],\n range: [0, counts[i]],\n hidden: i > 0,\n reveals: i < 5 ? `depth${depth}-selector${i + 1}` : null\n });\n }\n }\n }\n\n for (let i = 0; i < 5; i++) {\n achievements.set('journey' + i, {\n // Translators: The name of the 'Open the settings dialog %x times.'\n // achievement.\n name: formatName(_('The Journey Is The Reward %i'), i),\n // Translators: The description of the 'The Journey Is The Reward %i'\n // achievement.\n description: _('Open the settings dialog %x times.')\n .replace('%x', BASE_RANGES[i + 1] / 2),\n bgImage: bgImages[i],\n fgImage: 'gear.svg',\n statsKey: 'stats-settings-opened',\n xp: BASE_XP[i],\n range: [BASE_RANGES[i] / 2, BASE_RANGES[i + 1] / 2],\n hidden: false\n });\n }\n\n for (let i = 0; i < 5; i++) {\n achievements.set('nerd' + i, {\n // Translators: The name of the 'Open %x menus with the D-Bus interface.'\n // achievement.\n name: formatName(_('Nerd Alert %i'), i),\n // Translators: The description of the 'Nerd Alert %i' achievement.\n description: _('Open %x menus with the D-Bus interface.')\n .replace('%x', BASE_RANGES[i + 1]),\n bgImage: bgImages[i],\n fgImage: 'nerd.svg',\n statsKey: 'stats-dbus-menus',\n xp: BASE_XP[i],\n range: [BASE_RANGES[i], BASE_RANGES[i + 1]],\n hidden: false\n });\n }\n\n for (let i = 0; i < 5; i++) {\n achievements.set('entropie' + i, {\n // Translators: The name of the 'Generate %x random presets.' achievement.\n name: formatName(_('Entropie %i'), i),\n // Translators: The description of the 'Generate %x random presets.'\n // achievement.\n description:\n _('Generate %x random presets.').replace('%x', BASE_RANGES[i + 1] / 2),\n bgImage: bgImages[i],\n fgImage: 'chaos.svg',\n statsKey: 'stats-random-presets',\n xp: BASE_XP[i] / 2,\n range: [BASE_RANGES[i] / 2, BASE_RANGES[i + 1] / 2],\n hidden: false\n });\n }\n\n for (let i = 0; i < 5; i++) {\n achievements.set('preset-exporter' + i, {\n // Translators: The name of the 'Export %x custom presets.' achievement.\n name: formatName(_('%s Preset Exporter'), i),\n description: BASE_RANGES[i + 1] / 10 == 1 ?\n // Translators: The description of the '%s Preset Exporter' achievement if\n // only one preset needs to be exported.\n _('Export a custom preset.') :\n // Translators: The description of the '%s Preset Exporter' achievement.\n _('Export %x custom presets.').replace('%x', BASE_RANGES[i + 1] / 10),\n bgImage: bgImages[i],\n fgImage: 'export.svg',\n statsKey: 'stats-presets-exported',\n xp: BASE_XP[i] / 2,\n range: [BASE_RANGES[i] / 10, BASE_RANGES[i + 1] / 10],\n hidden: false\n });\n }\n\n for (let i = 0; i < 5; i++) {\n achievements.set('preset-importer' + i, {\n // Translators: The name of the 'Import %x custom presets.' achievement.\n name: formatName(_('%s Preset Importer'), i),\n description: BASE_RANGES[i + 1] / 10 == 1 ?\n // Translators: The description of the '%s Preset Importer' achievement if\n // only one preset needs to be imported.\n _('Import a custom preset.') :\n // Translators: The description of the '%s Preset Importer' achievement.\n _('Import %x custom presets.').replace('%x', BASE_RANGES[i + 1] / 10),\n bgImage: bgImages[i],\n fgImage: 'import.svg',\n statsKey: 'stats-presets-imported',\n xp: BASE_XP[i] / 2,\n range: [BASE_RANGES[i] / 10, BASE_RANGES[i + 1] / 10],\n hidden: false\n });\n }\n\n for (let i = 0; i < 5; i++) {\n achievements.set('menu-importer' + i, {\n // Translators: The name of the 'Import %x menu configurations.' achievement.\n name: formatName(_('%s Menu Importer'), i),\n description: BASE_RANGES[i + 1] / 10 == 1 ?\n // Translators: The description of the '%s Menu Importer' achievement if\n // only one menu needs to be imported.\n _('Import a menu configuration.') :\n // Translators: The description of the '%s Menu Importer' achievement.\n _('Import %x menu configurations.')\n .replace('%x', BASE_RANGES[i + 1] / 10),\n bgImage: bgImages[i],\n fgImage: 'export.svg',\n statsKey: 'stats-menus-imported',\n xp: BASE_XP[i] / 2,\n range: [BASE_RANGES[i] / 10, BASE_RANGES[i + 1] / 10],\n hidden: false\n });\n }\n\n for (let i = 0; i < 5; i++) {\n achievements.set('menu-exporter' + i, {\n // Translators: The name of the 'Export %x menu configurations.' achievement.\n name: formatName(_('%s Menu Exporter'), i),\n description: BASE_RANGES[i + 1] / 10 == 1 ?\n // Translators: The description of the '%s Menu Exporter' achievement if\n // only one menu needs to be exported.\n _('Export a menu configuration.') :\n // Translators: The description of the '%s Menu Exporter' achievement.\n _('Export %x menu configurations.')\n .replace('%x', BASE_RANGES[i + 1] / 10),\n bgImage: bgImages[i],\n fgImage: 'import.svg',\n statsKey: 'stats-menus-exported',\n xp: BASE_XP[i] / 2,\n range: [BASE_RANGES[i] / 10, BASE_RANGES[i + 1] / 10],\n hidden: false\n });\n }\n\n for (let i = 0; i < 5; i++) {\n achievements.set('bigmenus' + i, {\n // Translators: The name of the 'Create %x items in the menu editor.'\n // achievement.\n name: formatName(_('There Should Be No More Than Twelve Items…? %i'), i),\n // Translators: The description of the 'There Should Be No More Than Twelve\n // Items…? %i' achievement.\n description: _('Create %x items in the menu editor.')\n .replace('%x', BASE_RANGES[i + 1] / 2),\n bgImage: bgImages[i],\n fgImage: 'dots.svg',\n statsKey: 'stats-added-items',\n xp: BASE_XP[i],\n range: [BASE_RANGES[i] / 2, BASE_RANGES[i + 1] / 2],\n hidden: false\n });\n }\n\n for (let i = 0; i < 5; i++) {\n achievements.set('previewmenus' + i, {\n // Translators: The name of the 'Open a preview menu %x times.' achievement.\n name: formatName(_('%s Menu Designer'), i),\n description:\n // Translators: The description of the '%s Menu Designer' achievement.\n _('Open a preview menu %x times.').replace('%x', BASE_RANGES[i + 1] / 2),\n bgImage: bgImages[i],\n fgImage: 'eye.svg',\n statsKey: 'stats-preview-menus',\n xp: BASE_XP[i],\n range: [BASE_RANGES[i] / 2, BASE_RANGES[i + 1] / 2],\n hidden: false\n });\n }\n\n achievements.set('rookie', {\n // Translators: The name of the 'Open the tutorial menu %x times.' achievement.\n // This does not support %s and %i.\n name: _('Grumpie Rookie'),\n // Translators: The description of the 'Grumpie Rookie' achievement.\n description: _('Open the tutorial menu %x times.').replace('%x', 50),\n bgImage: 'special3.png',\n fgImage: 'grumpie.svg',\n statsKey: 'stats-tutorial-menus',\n xp: BASE_XP[0],\n range: [0, 50],\n hidden: false\n });\n\n achievements.set('bachelor', {\n // Translators: The name of the 'Get all medals of the tutorial.' achievement.\n // This does not support %s and %i.\n name: _('Bachelor Pielot'),\n // Translators: The description of the 'Bachelor Pielot' achievement.\n description: _('Get all medals of the tutorial.'),\n bgImage: 'special1.png',\n fgImage: 'scholar.svg',\n statsKey: 'stats-best-tutorial-time',\n xp: BASE_XP[1],\n range: [0, 6],\n hidden: false\n });\n\n achievements.set('goodpie', {\n // Translators: The name of the hidden 'Delete all of your menus.' achievement.\n // This does not support %s and %i.\n name: _('Say Good-Pie!'),\n // Translators: The description of the 'Say Good-Pie!' achievement.\n description: _('Delete all of your menus.'),\n bgImage: 'special2.png',\n fgImage: 'fire.svg',\n statsKey: 'stats-deleted-all-menus',\n xp: BASE_XP[2],\n range: [0, 1],\n hidden: true\n });\n\n achievements.set('sponsors', {\n // Translators: The name of the hidden 'Consider becoming a sponsor of Fly-Pie.'\n // This does not support %s and %i.\n // achievement.\n name: _('That\\'s Philanthropie!'),\n // Translators: The description of the 'That's Philanthropie!' achievement.\n description: _('Consider becoming a sponsor of Fly-Pie.'),\n bgImage: 'special3.png',\n fgImage: 'heart.svg',\n statsKey: 'stats-sponsors-viewed',\n xp: BASE_XP[1],\n range: [0, 1],\n hidden: true\n });\n\n return achievements;\n }",
"function changePageEnchantments() {\n //const mainPhoto = document.getElementById(\"mainPhoto\");\n //mainPhoto.src = \"./images/enchantments-image.jpg\";\n changeMainPhoto(\"./images/enchantments-image.jpg\");\n document.getElementById(\"hikeName\").textContent = \"THE ENCHANTMENTS\"\n \n}",
"function updateKittyInfo(index) {\r\n // TODO: Update the image with the ID \"my-banner\" with the new image. Hint: Use document.getElementById() to \r\n // get the element with the ID \"my-banner\" and use `src` property to update the `src` of the image.\r\n\r\n\r\n // TODO: Update the Title of the image here. Hint: Use `innerHTML` property instead of `src`.\r\n\r\n\r\n // TODO: Update the Like number of the image here. Hint: Use `innerHTML` property instead of `src`.\r\n\r\n}",
"updateImage() {\n //if image mode is images, set image source to svg file according to phase\n //else set image container text to text image according to phase\n if (this.imageMode) {\n this.image.src = 'i/hangman_' + this.phase + '.svg';\n } else {\n this.image.innerHTML = this.textImage[this.phase];\n }\n }",
"function displayImage(img) {\n\tdisplayBar.querySelector('img').setAttribute('src', img.getAttribute('src').replace('small', 'large'));\n\tdisplayBar.querySelector('img').setAttribute('alt', img.getAttribute('alt'));\n\tdisplayBar.querySelector('figcaption').innerHTML = img.getAttribute('alt');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates the display name paragraph. | function createDisplayNameParagraph(displayName) {
var p = document.createElement('p');
p.innerText = displayName;
return p;
} | [
"function createDisplayNameParagraph(displayName) {\n var p = document.createElement('p');\n p.innerText = displayName;\n\n return p;\n}",
"function createDisplayNameParagraph(key, displayName) {\n var p = document.createElement('p');\n if (displayName) {\n p.innerHTML = displayName;\n } else if (key) {\n p.setAttribute(\"data-i18n\", key);\n p.innerHTML = APP.translation.translateString(key);\n }\n\n return p;\n}",
"function createDisplayNameParagraph(key, displayName) {\n var p = document.createElement('p');\n if(displayName)\n p.innerText = displayName;\n else if(key)\n {\n p.setAttribute(\"data-i18n\",key);\n p.innerText = APP.translation.translateString(key);\n }\n\n return p;\n}",
"function createDisplayNameParagraph(displayName, resourceJid) {\n var a = document.createElement('p');\n // Change to revieww\n if (displayName == \"Participant\") {\n a.innerText = displayName;\n a.setAttribute(\"title\", resourceJid);\n \n }\n else {\n a.innerText = USER;\n a.setAttribute(\"title\", resourceJid);\n \n }\n return a;\n}",
"function createDisplayNameParagraph(key, displayName) {\n let p = document.createElement('p');\n if (displayName) {\n p.innerHTML = displayName;\n } else if(key) {\n p.setAttribute(\"data-i18n\",key);\n p.innerHTML = APP.translation.translateString(key);\n }\n\n return p;\n}",
"function displayName(name, career, description) {\n console.log(\"Name: \" + name.toUpperCase());\n console.log(\"Career: \" + career);\n console.log(\"Description: \" + description);\n console.log(\"\");//adds a blank space\n}",
"function familyName(getFamilyName) {\n const famName = document.createElement('p')\n famName.innerText = getFamilyName\n famName.setAttribute('id', 'family-name')\n document.querySelector('#append-plant').append(famName)\n}",
"function addNameTag(divElement,displayName){\n\tvar nameDisplay='<p align=\\'center\\'><font size=\\'4\\'>'+displayName+'</p>';\n\tdivElement.innerHTML=divElement.innerHTML + nameDisplay;\n}",
"function displayName(user) {\n const html = `<br><br>\n <h1>${user.first_name} ${user.last_name}</h1>\n `;\n const display = document.getElementById('display-name')\n display.innerHTML = html\n return html\n}",
"function appendName(identity, container) {\n const name = document.createElement(\"p\");\n name.id = `participantName-${identity}`;\n name.className = \"instructions\";\n name.textContent = identity;\n container.appendChild(name);\n}",
"function createCardTrainerName(teamAttributes) {\n const trainerNameElement = document.createElement('p');\n const trainerName = teamAttributes.name;\n const trainerNameText = document.createTextNode(`${trainerName}`);\n trainerNameElement.appendChild(trainerNameText);\n \n return trainerNameElement;\n }",
"function createName(toy, card) {\n let name = document.createElement('h2')\n name.innerText = toy.name\n card.appendChild(name)\n}",
"function displayName(p, inputVal){\n\tp.innerHTML = \"Your Name is \" + inputVal;\n}",
"function displayNameOnWebPage() {\r\n document.write(fullName);\r\n document.write(\"<br/>\");\r\n}",
"function createEditDisplayNameButton() {\n\t\tvar editButton = document.createElement('a');\n\t\teditButton.className = 'displayname';\n\t\tUtil.setTooltip(editButton,\n\t\t\t\t'Click to edit your<br/>display name',\n\t\t\t\t\"top\");\n\t\teditButton.innerHTML = '<i class=\"fa fa-pencil\"></i>';\n\n\t\treturn editButton;\n\t }",
"function displayAuthorityName(section, pla_name, pla_id) {\n var nameElement = section.querySelector(\".pla-name\");\n nameElement.textContent = pla_name;\n nameElement.dataset.plaId = pla_id;\n}",
"function insertName() {\n //Creates p element for player one, centered below 'O'\n nameDisplay1 = document.createElement('P'); \n nameDisplay1.innerText = playerOneName;\n nameDisplay1.className = 'name-position'; \n xoDisplay.appendChild(nameDisplay1);\n \n //Space between player one & two name elements.\n nameDisplaySpace = document.createElement('P'); \n nameDisplaySpace.className = 'name-position center-position'; \n xoDisplay.appendChild(nameDisplaySpace);\n \n //Creates p element for player Two, centered below 'X'\n nameDisplay2 = document.createElement('P'); \n nameDisplay2.innerText = playerTwoName;\n nameDisplay2.className = 'name-position'; \n xoDisplay.appendChild(nameDisplay2);\n gamePlay(); \n }",
"function showNickname(nickname) {\n let textContainer = document.createElement(\"p\");\n textContainer.innerText = nickname;\n document.body.appendChild(textContainer);\n}",
"function displayHeading(name,career,field,description){\n console.log(`Name: ${name.toUpperCase()} \\nCareer: ${career} / ${field} \\nDescription: ${description}`);\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers an activity event handler for the _end of conversation_ activity. | onEndOfConversation(handler) {
return this.on('EndOfConversation', handler);
} | [
"onEndOfConversationActivity(context) {\n return __awaiter(this, void 0, void 0, function* () {\n yield this.handle(context, 'EndOfConversation', this.defaultNextEvent(context));\n });\n }",
"function createEndOfConversationActivity() {\n return { type: index_1.ActivityTypes.EndOfConversation };\n }",
"function EventLogEnd() {\n\tif (!GameLogQuery(CurrentChapter, CurrentActor, \"Activity\" + EventActivityCurrent)) {\n\t\tif (EventActivityLove > 0) ActorChangeAttitude(1, 0);\n\t\tif (EventActivityLove < 0) ActorChangeAttitude(-1, 0);\n\t\tGameLogAdd(\"Activity\" + EventActivityCurrent);\n\t}\n\tEventActivityCurrent = \"\";\n}",
"setSessionEndedHandler() {\n this._alexa.setSessionEndedHandler((event) => {\n\n })\n }",
"onEnd (callback){\r\n this.onEndHandler = callback;\r\n }",
"function handleEnd(event) {\n\n var currentEventSubId = event.target.id;\n currentEventSubId = currentEventSubId.substring(currentEventSubId.indexOf(\"-\") + 1);\n\n const eventStatus = {\n \"eventSubIdToChange\": currentEventSubId,\n \"changeStatusTo\": 'end'\n };\n\n // API TO UPDATE EVENT TO SET EVENT AS ACTIVATED\n API.updateEventStatus(eventStatus)\n .then(res => {\n setEventIsActive(false);\n loadEvents();\n })\n .catch(err => console.log(err))\n }",
"endOfConversation(code) {\r\n if (code === undefined) {\r\n code = botbuilder_core_1.EndOfConversationCodes.CompletedSuccessfully;\r\n }\r\n this.add({ type: botbuilder_core_1.ActivityTypes.EndOfConversation, code: code });\r\n return this;\r\n }",
"setOnRequestEndHandlers() {\n this.setEventHandlers(\"end\", \"endHandlers\")();\n }",
"function moveEndHandler(evt) {\n _moveEndHandler(\n toolName,\n annotation,\n handle,\n options,\n interactionType,\n {\n moveHandler,\n moveEndHandler,\n },\n evt,\n doneMovingCallback\n );\n }",
"constructor(actions = [], condition) {\n super(botbuilder_1.ActivityTypes.EndOfConversation, actions, condition);\n }",
"function asEndOfConversationActivity(source) {\n return isActivity(source, index_1.ActivityTypes.EndOfConversation) ? source : null;\n }",
"endTransitionHandler(e) {\n if (this.active === true) {\n this.changeToDeactive();\n } else if (this.active === false) {\n this.transitionEndListenerOff();\n }\n }",
"onEnd(callback) {\n\t\tthis.onEndCallback = callback;\n\t}",
"function endConversation() {\n setNPCConversation('');\n}",
"endConversation() {this.outputMgr.keepConversationRunning=false}",
"function contentEndedListener() {\n videoContent.onended = null;\n if (adsLoader) {\n adsLoader.contentComplete();\n }\n}",
"function endChat() {\n\t\t\t\tlogger.debug(\"endChat\", \"...chatState=\"+chatState);\n\t\t\t\t\n\t\t\t\tif (chat && (chatState == chat.chatStates.CHATTING || chatState == chat.chatStates.RESUMING \n\t\t\t\t\t|| chatState == chat.chatStates.WAITING)) { //|| chatState == chat.chatStates.NOTFOUND\n\t\t\t\t\t\n\t\t\t\t\tvar endChatParam = {\n\t\t\t\t\t\t\t\tdisposeVisitor : true,\n\t\t\t\t\t\t\t\tcontext : myChatWiz,\n\t\t\t\t\t\t\t\tskill : skill,\n\t\t\t\t\t\t\t\terror: function(data) {\n\t\t\t\t\t\t\t\t\tlogger.debug(\"endChat.error\", data);\n\t\t\t\t\t\t\t\t\tchatWinCloseable = true;\n\t\t\t\t\t\t\t\t\tendChatHandler();\t\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t/* send endChat request and waiting for endChat event call back */\n\t\t\t\t\tvar failedRequest = chat.endChat(endChatParam);\n\t\t\t\t\t\t\t\n\t\t\t\t\tif (failedRequest && failedRequest.error) {\n\t\t\t\t\t\tlogger.debug(\"endChat.error2\", failedRequest);\n\t\t\t\t\t\tchatWinCloseable = true;\n\t\t\t\t\t\tendChatHandler();\t\n\t\t\t\t\t}\n\t\t\t\t}else if(chatState == chat.chatStates.INITIALISED){\n\t\t\t\t\tendChatHandler();\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}",
"_onEnd() {\n let tourManager = this.tourManager;\n tourManager.setIsRead(this.tourId, true);\n this.notifyPropertyChange(\"hasBeenRead\");\n\n set(this, \"status\", \"ENDED\");\n this.trigger(\"tour.end\", this._getEventData());\n }",
"function EndListener() {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
go from a document to a country location | function locateServerFromDoc(doc, cb) {
const out = {
countryName: COUNTRY_UNKNOWN.countryName,
countryCode: COUNTRY_UNKNOWN.countryCode
};
withLocationProperty(doc.rules, (err, value) => {
if(err) {
return cb(err);
}
// TODO: implement x-* field location identification
// first test for country names AND US states
const parts = value.split(",");
for(let i = 0; i < parts.length; i++) {
const test = parts[i].trim();
if(country.isCountry(test)) {
out.countryName = test;
break;
}
else if(country.isUSState(test)) {
out.countryName = "United States";
out.state = test;
break;
}
}
out.countryCode = country.codeFromName(
out.countryName);
});
// if we didn't find a country in a location field, geolocate
if(out.countryName === "Unknown") {
geolocate(doc.address, cb);
}
// otherwise return what we calculated
else {
cb(undefined, out);
}
} | [
"function addLocation(){\n collectionCountries.find().forEach(doc => {\n \n //check if country info has lat and long fields \n if(\"countryInfo\" in doc) {\n const cntryInfo = doc.countryInfo;\n // console.log(cntryInfo);\n if((\"lat\" in cntryInfo && cntryInfo.lat !== \"\") && \n (\"long\" in cntryInfo && cntryInfo.long !== \"\" )) {\n \n //create loc field\n doc.loc = {\n type: \"Point\",\n coordinates : [\n cntryInfo.long,\n cntryInfo.lat\n ]\n }\n \n //delete the old lat and long fields \n delete doc.countryInfo.lat;\n delete doc.countryInfo.long;\n\n //save document\n collectionCountries.save(doc);\n // printjson(doc);\n }\n }\n });\n }",
"function panToLocation() {\n\t// Step 2: add the basic values we know we'll need\n\tvar countryName = document.getElementById(\"country-name\").value;\n\n\t// Step 4: Let's add an error check to make sure\n\t// the person has typed something in.\n\tif(countryName === \"\") {\n\t \talert(\"You didn't enter a country name!\");\n\t \treturn;\n\t}\n\n\t// Step 3: Let's find our country's longitude and latitude!\n\t// Ask the students to find the documentation where they can\n\t// search / query for a location's information!\n\t// Once you write this, pause and ask students what next?\n\t// How do we get information from this URL. Right now it's\n\t// just a url...\n\tvar query = \"https://restcountries.eu/rest/v2/name/\"+countryName;\n\n\t// Step 2: Add the conversion from longitude and latitude\n\t// that we used for our home location!\n\tvar lon = 0.0;\n\tvar lat = 0.0;\n\tvar location = ol.proj.fromLonLat([lon, lat]);\n\n\t// Step 2: Add the animation that we used in panHome\n\t// and swap out what we pan to! Stop here and run the code.\n\t// When it errors, ask the students what they think happened.\n\t// Direct them to think about the 0, 0 of longitude and latitude\n\tview.animate({\n\t\tcenter: location, // Location\n\t\tduration: 2000 // Two seconds\n\t});\n}",
"function synthesizeDocs(boundaryCountry, result) {\n const doc = new Document('whosonfirst', result.placetype, result.id.toString());\n doc.setName('default', result.name);\n\n // only assign centroid if both lat and lon are finite numbers\n if (hasLatLon(result)) {\n doc.setCentroid( { lat: result.geom.lat, lon: result.geom.lon } );\n } else {\n logger.error(`could not parse centroid for id ${result.id}`);\n }\n\n // _.conformsTo verifies that an object property has a certain format\n if (_.conformsTo(result.geom, { 'bbox': is4CommaDelimitedNumbers } )) {\n const parsedBoundingBox = result.geom.bbox.split(',').map(_.toFinite);\n doc.setBoundingBox({\n upperLeft: {\n lat: parsedBoundingBox[3],\n lon: parsedBoundingBox[0]\n },\n lowerRight: {\n lat: parsedBoundingBox[1],\n lon: parsedBoundingBox[2]\n }\n });\n } else {\n logger.error(`could not parse bbox for id ${result.id}: ${_.get(result, 'geom.bbox')}`);\n }\n\n // set population and popularity if parseable as finite number\n if (isNonNegativeFiniteNumber(result.population)) {\n doc.setPopulation(_.toFinite(result.population));\n }\n if (isNonNegativeFiniteNumber(result.popularity)) {\n doc.setPopularity(_.toFinite(result.popularity));\n }\n\n _.defaultTo(result.lineage, [])\n // remove all lineages that don't match an explicit boundary.country\n .filter(_.partial(matchesBoundaryCountry, boundaryCountry))\n // add all the lineages to the doc\n .map((hierarchy) => {\n Object.keys(hierarchy)\n .filter(doc.isSupportedParent)\n .filter((placetype) => {\n return placetypeHasNameAndId(hierarchy[placetype]);\n })\n .forEach((placetype) => {\n doc.addParent(\n placetype,\n hierarchy[placetype].name,\n hierarchy[placetype].id.toString(),\n hierarchy[placetype].abbr);\n });\n });\n\n return buildESDoc(doc);\n\n}",
"function connectUserToLocation (userId, name, country, city, postal) {\n const locationId = idGenerator.nextLocationId();\n // log.info('graph.js location name:', name, country, city, postal);\n return cq.query(qb.connectUserToLocation(userId, locationId, name, country, city, postal))\n .then(transformer.location);\n}",
"function locationToGeoCode() {\n\n }",
"function geocodeAndSave(doc) {\n var locationNames = doc.locationName;\n var latLngs = doc.latLon; // array of strings matching order of location names\n\n locationNames.forEach((loc, i) => {\n syncPromises(function* () {\n var latlng = latLngs[i].split(','),\n lat = latlng[0],\n lng = latlng[1];\n\n // use the first result. TODO: use confidence score if available?\n var results = yield requestPromise(loc, {latitude: lat, longitude: lng});\n doc.geo = results[0]; // add geo result to original doc\n createGeoTweet(doc);\n })()\n .catch(err => {\n console.error(err);\n console.error('Removing geotweets records');\n GeoTweet.destroyAll();\n });\n });\n}",
"function nextPlace() {\n var place = businesses[step];\n geocode(place);\n}",
"function lookupPartnerLocation(request, response) {\n activeUsers.findOne({name: request.body.lookingFor}, function (err, doc) {\n if (err) {\n console.log(err);\n }\n if (doc != null) {\n var partnerLocation = doc.curLocation;\n response.send({\"location\": partnerLocation});\n }\n })\n}",
"function findCountryTable() {\n // get the body\n var body = DocumentApp.getActiveDocument().getBody();\n\n var numElems = body.getNumChildren();\n\n // find the appropriate table\n for (let i = 0; i < numElems; i++) {\n // find the paragraph with the text \"COUNTRY OF VISIT\"\n \n var nextChild = body.getChild(i);\n \n if (nextChild.getType() == DocumentApp.ElementType.PARAGRAPH) {\n if (nextChild.getText().includes(\"Countries to visit\")) {\n Logger.log(\"found table title\");\n for (let j = i; j < numElems; j++) {\n nextChild = body.getChild(j);\n Logger.log(nextChild.getType())\n if (nextChild.getType() == DocumentApp.ElementType.TABLE) {\n return j;\n }\n }\n break;\n }\n }\n }\n\n return -1; \n\n}",
"function doSaveThesaurusDoc(map) {\n var uri = map[\"uri\"];\n var doc = map[\"doc\"];\n\n thsr.insert(uri, doc);\n\n xdmp.commit();\n}",
"get location() //property getters\r\n {\r\n return \"canada\"\r\n }",
"function setLocation(loc, target, ismulti){ \n var cn = loc.substr(0, 1); \n var province = loc.substr(1, 2); \n var city = loc.substr(1, 4); \n // set the company's location \n if (!cn){\n $('#' + target).append('<span>国外</span>');\n } else {\n // in CN\n if (loc == '1000000000000000'){\n $('#' + target).append('全国');\n return;\n }\n\n var provinceid = province * 100;\n var prov_str = map_id_attr(provinces, provinceid);\n \n var city_str = '';\n\n var setCmpLocation = function(cities){ \n city_str = map_id_attr(cities, city); \n if (city_str){\n city_str = '-' + city_str;\n }\n var t = $('#' + target);\n t.append('<span>');\n if (ismulti){\n t.append('/'); \n }\n t.append(prov_str + city_str + '</span>');\n }\n\n if (cityCache.hasOwnProperty(provinceid)){\n setCmpLocation(cityCache[provinceid]);\n } else {\n setCities(provinceid, setCmpLocation);\n }\n } \n }",
"function setLocation() {\n\n var defaultLocationResult = LOOKUP_SERVICE.get('/store/lookup/common/Location.csv', [ 'Default' ] );\n if (!isEmptyOrNull(defaultLocationResult)) {\n PRODUCT.ItemPostalCode = defaultLocationResult[3];\n PRODUCT.ItemCountry = defaultLocationResult[2];\n PRODUCT.ItemLocation = defaultLocationResult[0] + \", \" + defaultLocationResult[1];\n }\n}",
"function displayLocation(city, region, country) {\n\n // Turn country code into full country name\n $.ajax({\n type: \"GET\",\n url: \"https://restcountries.eu/rest/v1/alpha?codes=\" + country,\n success: function(data) {\n\n // Print to html\n $(\"#city-state\").text((city + \", \" + region).toUpperCase());\n $(\"#country\").text((data[0].name).toUpperCase());\n }\n });\n } // end of displayLocation",
"function createNewGeoDoc(doc, translations, languages, natives) {\n\n // create new geo document\n var geo = new Geo({\n cca2: doc.cca2,\n ccn3: doc.ccn3,\n cca3: doc.cca3,\n cioc: doc.cioc,\n names: {\n official: doc.name.official,\n common: doc.name.common,\n natives: _.cloneDeep(natives)\n },\n tld: _.cloneDeep(doc.tld),\n currencies: _.cloneDeep(doc.currency),\n callingCodes: _.cloneDeep(doc.callingCode),\n capital: doc.capital,\n altSpellings: _.cloneDeep(doc.altSpellings),\n region: doc.region,\n subregion: doc.subregion,\n translations: _.cloneDeep(translations),\n languages: _.cloneDeep(languages),\n coords: _.cloneDeep(doc.latlng),\n demonym: doc.demonym,\n landlocked: doc.landlocked,\n borders: _.cloneDeep(doc.borders),\n area: doc.area\n });\n // save new geo document\n geo.save(function (err) {\n if (err) {\n console.log(err);\n return err;\n }\n });\n}",
"function searchCountry(home, destination) {\n\n getHomeCountry(home);\n getDestCountry(destination);\n displayAmountEntry();\n\n}",
"function geoip(g) {\n var redirected = getCookie('redirected_once');\n if (!redirected) {\n setCookie('redirected_once', true, 7);\n switch (g.country_code) {\n case \"UA\":\n window.location = \"https://nectarica.com\";\n break;// edit for your URL\n case \"DE\":\n window.location = \"http://nectarica.com/?lang=de\";\n break;// edit for your URL\n case \"FR\": // Redirect is visitor from Denmark\n window.location = \"http://nectarica.com/?lang=fr\";\n break;\n case \"PL\": // Redirect is visitor from Denmark\n window.location = \"http://nectarica.com/?lang=pl\";\n break;\n case \"ES\": // Redirect is visitor from Denmark\n window.location = \"http://nectarica.com/?lang=es\";\n break;\n default:\n window.location = \"http://nectarica.com/?lang=en\";\n }\n }\n\n}",
"function findLocation(location) {\r\n document.getElementById(\"originCity\").value = location;\r\n document.getElementById(\"originCity\").focus();\r\n}",
"function setCountry() {\n var id = $(this).attr(\"id\").substring(0,2);\n $(\"#join-link\").attr(\"href\", links[id]);\n adjustData(id);\n handleCountrySelect($(this));\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
PROBLEM: Longest Peak we want to find the longest peak basically the length of a consecutive incline then a consecutive decline HIGH LEVEL STRATEGY: find the peak => if i > i 1 && i < i + 1 keep expanding outwards maybe? create a left & right pointer keep moving them outwards until left < left 1 right < right + 1 save difference in maxLength right left | function longestPeak(array) {
let maxLen = 0
let len = 0
for (let i = 1; i < array.length - 1; i++) {
if (array[i] > array[i+1] && array[i] > array[i-1]) {
let left = i - 1
let right = i + 1
while (left > 0 && array[left] > array[left - 1]) {
left -= 1
}
while (right < array.length && array[right] > array[right + 1]) {
right += 1
}
len = right - left + 1
if (len > maxLen) maxLen = len
}
}
return maxLen
} | [
"function longestPeak(array) {\n // a variable to hold the running longest peak length\n let longestPeakLength = 0;\n\n // set a pointer, that starts from idx 1 (second element)\n // and goes till array.length-1 (second last)\n // this pointer will keep track of the element\n // to be checked if a peak or not\n let idx = 1;\n while (idx < array.length - 1) {\n // check if current number is a peak\n // an element is a peak if\n // it is greater than\n // left element and right elements\n const isPeak = array[idx - 1] < array[idx] && array[idx + 1] < array[idx];\n\n // if not peak, move to next element\n if (!isPeak) {\n idx++;\n continue;\n }\n\n // else if it is a peak\n // we can find the length of it\n\n // finding the length of the peak towards left:\n // for that we set left pointer\n // it can start from idx - 2 as we\n // already know idx-1 is part of the peak\n let leftIdx = idx - 2;\n\n // as far as the elements are strictly decreasing\n // we move the leftwards pointer to left\n while (leftIdx >= 0 && array[leftIdx] < array[leftIdx + 1]) {\n leftIdx--;\n }\n\n // finding the peak length rightwards:\n let rightIdx = idx + 2;\n // as far as the elements are strictly decreasing\n // keep on moving the pointer right\n while (rightIdx < array.length && array[rightIdx] < array[rightIdx - 1]) {\n rightIdx++;\n }\n\n // finding length of the current peak:\n // it is the difference of left and right pointers - 1\n // we subtract 1 since array is 0 indexed\n const currentPeakLength = rightIdx - leftIdx - 1;\n\n // if currentPeakLength is greater than running longestPeakLength\n // replace running longestPeakLength\n longestPeakLength = Math.max(currentPeakLength, longestPeakLength);\n\n // for next iteration we can start from the rightmost pointer\n // as we already know, in the range\n // idx to rightIdx, elements are strictly decreasing\n // and there isn't a peak\n idx = rightIdx;\n }\n return longestPeakLength;\n}",
"function longestPeak(array) {\r\n let maxPeak = 0\r\n let i = 1\r\n while (i < array.length - 1) {\r\n if (array[i] > array[i - 1] && array[i] > array[i + 1]) {\r\n let currentPeak = 1\r\n let left = i\r\n let right = i\r\n while (array[left] > array[left - 1] && left > 0) {\r\n currentPeak++\r\n left--\r\n }\r\n while (array[right] > array[right + 1] && right < array.length) {\r\n currentPeak++\r\n right++\r\n }\r\n if (currentPeak > maxPeak) maxPeak = currentPeak\r\n i = right // skips all numbers that cannot be peaks anyways\r\n }\r\n i++\r\n }\r\n return maxPeak\r\n}",
"function longestPeak(array) {\n let longestPeak = 0;\n let index = 1;\n while(index < array.length - 1) {\n let peak = array[index] > array[index-1] && array[index] > array[index + 1];\n if(!peak) {\n index++;\n continue;\n }\n\n let leftIndex = index - 2;\n while(leftIndex >= 0 && array[leftIndex] < array[leftIndex + 1]) \n leftIndex --;\n\n let rightIndex = index + 2;\n while(rightIndex < array.length && array[rightIndex - 1] > array[rightIndex])\n rightIndex++;\n\n let peakLength = rightIndex - leftIndex - 1;\n longestPeak = Math.max(longestPeak, peakLength);\n index = rightIndex;\n }\n return longestPeak;\n}",
"findPeak() {\r\n\r\n var differenceThreshold = 10;\r\n var max = 0;\r\n var vdLength = this.valleyData.length;\r\n for (var i = 1; i < vdLength; i++) {\r\n var seperation = 1; //How far to look for the previous valley point\r\n while (true) {\r\n if (Math.abs(this.lineDataPoints[this.valleyData[i]] - this.lineDataPoints[this.valleyData[i - seperation]]) <= differenceThreshold) { //checks to see if valley is in peak or in baseline\r\n //Since valley data is holding the index value we can find how far apart they are from one another in the oringial array\r\n var distance = this.valleyData[i] - this.valleyData[i - seperation]; //The distance between the two points\r\n if (distance > max) { //if the distance is greater replace previous information\r\n max = distance;\r\n this.peakStart = this.valleyData[i - seperation];\r\n this.peakEnd = this.valleyData[i];\r\n }\r\n break;\r\n }\r\n else {\r\n seperation++; // if the value was found inside peak then look for the next valley \r\n if (i - seperation < 0) {\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n }",
"function peak(arr){\n for(let i = 1; i < arr.length-1; i++){\n let left = (arr.slice(0,i).reduce((a,b)=> a+b));\n let right = (arr.slice(i+1).reduce((c,d)=> c+d));\n if(left === right) return i;\n }\n return -1;\n}",
"function peakFinder1D(arr) {\t\n\tfor(i=0; i<arr.length; i++) {\n\t\tif(i==0) {\n\t\t\tif (arr[i]>=arr[i+1]) {\n\t\t\t\treturn arr[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse if (i==(arr.length-1)) {\n\t\t\tif (arr[i]>=arr[i-1]) {\n\t\t\t\treturn arr[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tif ((arr[i]>=arr[i-1])&&(arr[i]>=arr[i+1])) {\n\t\t\t\treturn arr[i];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}",
"function peak(arr){\n //..\n let peak;\n arr.forEach( (num, i)=>{\n if( i > 0 && i < arr.length-1 ){\n //contains element 0 until i-1\n let leftArr = arr.slice( 0, i).reduce((a,c)=>a+c)\n // contains element i+2 until the last element in the array (arr.length-1)\n let rightArr = arr.slice( i+1, arr.length ).reduce((a,c)=>a+c)\n if(leftArr === rightArr){ peak = i}\n }\n })\n return (peak) ? peak : -1 ;\n}",
"function peak(arr){\n for(let i = 1; i < arr.length-1; i++){\n let left = arr.slice(0,i);\n let right = arr.slice(i+1);\n let sumL = left.reduce((sum, el) => sum + el, 0);\n let sumR = right.reduce((sum, el) => sum + el, 0);\n if(sumL === sumR) {\n return i;\n }\n }\n return -1;\n}",
"function joinBroadPeaks(peakList, options){\n var width = options.width;\n var broadLines=[];\n //Optimize the possible broad lines\n var max=0, maxI=0,count=1;\n var isPartOf = false;\n for(var i=peakList.length-1;i>=0;i--){\n if(peakList[i].soft){\n broadLines.push(peakList.splice(i,1)[0]);\n }\n }\n //Push a feak peak\n broadLines.push({x:Number.MAX_VALUE});\n\n var candidates = [[broadLines[0].x,\n broadLines[0].y]];\n var indexes = [0];\n\n for(var i=1;i<broadLines.length;i++){\n //console.log(broadLines[i-1].x+\" \"+broadLines[i].x);\n if(Math.abs(broadLines[i-1].x-broadLines[i].x)<width){\n candidates.push([broadLines[i].x,broadLines[i].y]);\n if(broadLines[i].y>max){\n max = broadLines[i].y;\n maxI = i;\n }\n indexes.push(i);\n count++;\n }\n else{\n if(count>2){\n var fitted = Opt.optimizeSingleLorentzian(candidates,\n {x: broadLines[maxI].x, y:max, width: Math.abs(candidates[0][0]-candidates[candidates.length-1][0])});\n peakList.push({x:fitted[0][0],y:fitted[1][0],width:fitted[2][0],soft:false});\n\n }\n else{\n //Put back the candidates to the signals list\n indexes.map(function(index){peakList.push(broadLines[index])});\n }\n candidates = [[broadLines[i].x,broadLines[i].y]];\n indexes = [i];\n max = broadLines[i].y;\n maxI = i;\n count = 1;\n }\n }\n\n peakList.sort(function (a, b) {\n return a.x - b.x;\n });\n\n return peakList;\n\n}",
"function peak(arr){\n let pos = 0;\n for (let i = 0; i < arr.length; i++) {\n if (arr.slice(0, i+1).reduce((a, b) => a+b) === arr.slice(i).reduce((a, b) => a+b))\n pos = i;\n }\n return pos === 0 ? -1 : pos;\n}",
"function pickPeak(arr) {\n let leftEdge = 0,\n rightEdge = arr.length - 1; //to start, set the left index of your window to the start of the array, and the right index of the window to the end of the array. \n while (true) {\n let mid = leftEdge + Math.floor((rightEdge - leftEdge) / 2);//find the index halfway between the left and right edges of your current 'window' and call it 'mid'\n if (arr[mid] < arr[mid - 1]) { // if your current middle number is less than its neighbor to the left, slide the right edge of your window to the current number's immediate left.\n rightEdge = mid - 1;\n }\n else if (arr[mid] < arr[mid + 1]) { // otherwise, if your current middle number is less than its neighbor to the right, slide the left edge of your window to the current number's immediate right.\n leftEdge = mid + 1;\n } else return arr[mid]; //if the current middle number is not smaller than its neighbors, you found the peak! \n } //if you haven't found the peak yet, try again with your new, smaller window!\n} //Note: this solution assumes that there are not any \"plateaus\" i.e. sequences of repeated numbers",
"function findpeak(arr, bc, ileft, iright, xmin, dx)\n{\n var x, y, i, imax = ileft, ym = -1e100;\n\n for ( i = ileft; i < iright; i++ ) {\n if ( arr[i] <= LN0 ) continue;\n x = xmin + i * dx;\n y = arr[i] - x * bc;\n if ( y > ym ) {\n ym = y;\n imax = i;\n }\n }\n return [imax, ym];\n}",
"peak(buffer) {\n var peak = 0;\n for (var i = 0, n = buffer.length; i < n; i++) {\n peak = (Math.abs(buffer[i]) > peak) ? Math.abs(buffer[i]) : peak;\n }\n return peak;\n }",
"function joinBroadPeaks(peakList, options) {\n var width = options.width;\n var broadLines = [];\n //Optimize the possible broad lines\n var max = 0, maxI = 0, count = 1;\n for (let i = peakList.length - 1; i >= 0; i--) {\n if (peakList[i].soft) {\n broadLines.push(peakList.splice(i, 1)[0]);\n }\n }\n //Push a feak peak\n broadLines.push({x: Number.MAX_VALUE});\n\n var candidates = [[broadLines[0].x,\n broadLines[0].y]];\n var indexes = [0];\n\n for (let i = 1; i < broadLines.length; i++) {\n //console.log(broadLines[i-1].x+\" \"+broadLines[i].x);\n if (Math.abs(broadLines[i - 1].x - broadLines[i].x) < width) {\n candidates.push([broadLines[i].x, broadLines[i].y]);\n if (broadLines[i].y > max) {\n max = broadLines[i].y;\n maxI = i;\n }\n indexes.push(i);\n count++;\n } else {\n if (count > 2) {\n var fitted = Opt.optimizeSingleLorentzian(candidates,\n {x: broadLines[maxI].x, y: max, width: Math.abs(candidates[0][0] - candidates[candidates.length - 1][0])});\n peakList.push({x: fitted[0][0], y: fitted[1][0], width: fitted[2][0], soft: false});\n\n } else {\n //Put back the candidates to the signals list\n indexes.map(function (index) {\n peakList.push(broadLines[index]);\n });\n }\n candidates = [[broadLines[i].x, broadLines[i].y]];\n indexes = [i];\n max = broadLines[i].y;\n maxI = i;\n count = 1;\n }\n }\n\n peakList.sort(function (a, b) {\n return a.x - b.x;\n });\n\n return peakList;\n\n}",
"function solution(A) {\n const peak = [];\n\n for(let i = 1; i < A.length; i++) {\n if(A[i - 1] < A[i] && A[i] > A[i + 1]) peak.push(i);\n }\n // console.log(peak)\n\n if(peak.length < 2) return peak.length; // [1, 3, 2] // one flag\n let dist = peak[peak.length - 1] - peak[0];\n\n const placeFlags = num => {\n let target = num;\n let start = peak[0];\n let i = 1;\n\n while(i < peak.length) {\n if(peak[i] - start >= num) {\n target--;\n if(target === 0) return true;\n }\n i++;\n }\n return false;\n }\n\n let left = 1;\n // let right = peak.length;\n let right = Math.floor(Math.sqrt(dist));\n let mid;\n\n while(left <= right) {\n mid = Math.floor((left + right) / 2) \n if(placeFlags(mid) === true) {\n left = mid + 1;\n } else {\n right = mid - 1;\n }\n }\n // console.log(left, mid, right)\n return mid;\n}",
"findPeaks() {\n this.nbPeaks = 0;\n var i = 2;\n let end = this.magnitudes.length - 2;\n\n while (i < end) {\n let mag = this.magnitudes[i];\n\n if (this.magnitudes[i - 1] >= mag || this.magnitudes[i - 2] >= mag) {\n i++;\n continue;\n }\n if (this.magnitudes[i + 1] >= mag || this.magnitudes[i + 2] >= mag) {\n i++;\n continue;\n }\n\n this.peakIndexes[this.nbPeaks] = i;\n this.nbPeaks++;\n i += 2;\n }\n }",
"function findPeakLimits(audioData, direction, peakTone) {\n\tvar peakToneBin = mapFreqToIndex(peakTone);\n\t/*\n\t * As determined by the paper\n\t */\n\tvar frequencyBinLimit = 33;\n\t/*\n\t * Determined by experimentation\n\t */\n\tvar amplitudeDropOffLimit = 0.005;\n\n\tvar boundary = 0;\n\n\t/*\n\t * No doppler shift observed in peak tone frequency - return\n\t */\n\tif (audioData[peakToneBin] == 0) {\n\t\t//console.log(\"No change\");\n\t\treturn boundary;\n\t}\n\n\twhile (++boundary <= frequencyBinLimit) {\n\t\tvar idx = peakToneBin + boundary * direction;\n\n\t\tif ((direction == -1 && idx < 0) || (direction == 1 && idx >= analyser.frequencyBinCount)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tvar ratio = audioData[idx] / audioData[peakToneBin];\n\t\t\n\t\t//console.log(peakToneBin, idx, audioData[idx], audioData[peakToneBin], ratio);\n\t\t\n\t\tif (ratio < amplitudeDropOffLimit) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (boundary > frequencyBinLimit) {\n\t\tboundary = frequencyBinLimit;\n\t}\n\n\treturn boundary;\n}",
"function peakFinder_2(array) {\n let peaks = []\n let startPeak = array[0];\n let endPeak = array[array.length - 1];\n for (var i = 0; i < array.length; i++) {\n let peak = array[i];\n if (startPeak > array[i+1]) {\n peaks.push(startPeak)\n }\n if (peak > array[i - 1] && peak > array[i+1]) {\n peaks.push(peak);\n }\n if (array[array.length - 2] < endPeak) {\n peaks.push(endPeak)\n }\n}\nreturn peaks;\n}",
"function peak(arr){\n let total = arr.reduce((a,b)=> a+b)\n let sum = 0 \n for(let i=0; i < arr.length; i++){\n if(sum === (total - arr[i])/2){\n return i\n } \n sum = sum + arr[i]\n }\n return -1\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the value at a given index and column name | getValue(index, column) {
var availableKeys = Object.keys(this.data.intervalls[0]);
if (this.contains(availableKeys,column) == true){
var value = this.data.intervalls[index][column];
return value;
}else{
throw new Error("Column name ["+column+"] is not available. Available columns are: " + availableKeys.toString());
}
} | [
"function getFromColumn(headerRow, row, columnName) {\n return row[headerRow.indexOf(columnName)];\n}",
"function getCellValue(row, index){ return $(row).children('td').eq(index).text() }",
"function getCellValue(row, index) {\n return $(row).children('td').eq(index).text()\n }",
"function getColumnValue(columnName) {\n\n if (!isEmptyOrNull(columnName)) {\n var columnNameIndex = headerColumns.indexOf(columnName);\n\n if (columnNameIndex > -1) {\n return PRODUCT_INRECORD[columnNames[columnNameIndex]];\n }\n }\n return null;\n}",
"getColumnIndex(name) {\n return this._columnNameToIndex[name];\n }",
"getColumn(name) {\n if (this._index.get(name) === undefined) reporter.fatalError('Column ' + name + ' not defined for table ' + this._name);\n\n return this._columns[this._index.get(name)];\n }",
"getCellByIndex(index) {\n return this.data[index];\n }",
"function getByName(colName, row) {\n var col = header.indexOf(colName);\n if (col != -1) {\n return table[row][col];\n }\n}",
"function getColByName(name) {\n var headers = detailed_ws.getDataRange().getValues().shift();\n var colindex = headers.indexOf(name);\n return colindex+1;\n}",
"function getColumn(sheet,name){\n var curSheet = ss.getSheetByName(sheet);\n var headers = curSheet.getRange(1,1,1,curSheet.getLastColumn()).getValues();\n var column = headers.indexOf(name)+1;\n return column\n}",
"function getCellValue(row, index){ \n \n //Returns children (cells in this case) of row equal to passed index parameter and the text in it.\n return $(row).children(\"td\").eq(index).text();\n }",
"getColumnWithIndex(x) {\n return this.dataSupplier.getColumnData(x)\n }",
"function getColumnIndex(columnName){\n// var to hold column index\nvar columnIndex;\n\n// set new index\nswitch(columnName){\n case 'Speed (mph)':\n columnIndex = 0;\n break;\n case 'Distance (mi)':\n columnIndex = 1;\n break;\n case 'Duration (mins)':\n columnIndex = 2;\n break;\n case 'Petrol Saved (L)':\n columnIndex = 3;\n break;\n case 'CO2 Saved (kg)':\n columnIndex = 4;\n break;\n default:\n columnIndex = 0;\n alert(\"Sorry, something has gone wrong with the column chart redraw\");\n}\nreturn columnIndex;\n}",
"getCell(index) {\n return this.cells[index];\n }",
"get(index) {\r\n return this._cellMap.get(this._cellOrder.get(index));\r\n }",
"getByIndex(idx) {\n if (idx >= 0) {\n if (idx < this.vals.length) return this.vals[idx];\n else return null;\n } else {\n if (-idx <= this.vals.length) return this.vals[this.vals.length + idx];\n else return null;\n }\n }",
"function get_col_value(aRow,strColName)\r\n{\r\n\tfor(var x=0;x<aRow.cells.length;x++)\r\n\t{\r\n\t\tvar dbColName = aRow.cells[x].getAttribute(\"dbname\");\r\n\t\tif((dbColName!=null)||(dbColName!=\"\"))\r\n\t\t{\r\n\t\t\tif(dbColName.toLowerCase()==strColName.toLowerCase())\r\n\t\t\t{\r\n\t\t\t\treturn aRow.cells[x].getAttribute(\"dbvalue\");\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}",
"get(index) {\n return this._cellMap.get(this._cellOrder.get(index));\n }",
"function findColumn(model, index){\n var column = null;\n for (var i=0; i<model.rows.length; i++){\n var r = model.rows[i];\n for (var j=0; j<r.columns.length; j++){\n var c = r.columns[j];\n if ( c.cid === index ){\n column = c;\n break;\n } else if (c.rows){\n column = findColumn(c, index);\n }\n }\n if (column){\n break;\n }\n }\n return column;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
=============================================================================== / The get100dData and getP100dData are responsible for fetching the data from the local JSON and displaying the right amount of kilometers in the correct div. However, this isn't the best way to do so since it would require way too many switch statements for every single condition. The logic works but it doesn't make sense to clutter the JS file with hundreds of lines of code. | async function get100dData() {
const response = await fetch(json100DPath)
const data = await response.json()
console.log(data)
switch(speed) {
case 70:
if(isAcOn === false && wheelSize === 19 && speed === 70 && temperature === -10) {
tesla100DRange.innerText = (data[0].hwy[0].kilometers)
} else if (isAcOn === true && wheelSize === 19 && speed === 70 && temperature === -10) {
tesla100DRange.innerText = (data[1].hwy[0].kilometers)
} else if (isAcOn === false && wheelSize === 21 && speed === 70 && temperature === -10) {
tesla100DRange.innerText = (data[2].hwy[0].kilometers)
} else if (isAcOn === true && wheelSize === 21 && speed === 70 && temperature === -10) {
tesla100DRange.innerText = (data[3].hwy[0].kilometers)
}
break
case 80:
if(isAcOn === false && wheelSize === 19 && speed === 80 && temperature === -10) {
tesla100DRange.innerText = (data[0].hwy[1].kilometers)
} else if (isAcOn === true && wheelSize === 19 && speed === 80 && temperature === -10) {
tesla100DRange.innerText = (data[1].hwy[1].kilometers)
} else if (isAcOn === false && wheelSize === 21 && speed === 80 && temperature === -10) {
tesla100DRange.innerText = (data[2].hwy[1].kilometers)
} else if (isAcOn === true && wheelSize === 21 && speed === 80 && temperature === -10) {
tesla100DRange.innerText = (data[3].hwy[1].kilometers)
}
break
case 90:
if(isAcOn === false && wheelSize === 19 && speed === 90 && temperature === -10) {
tesla100DRange.innerText = (data[0].hwy[2].kilometers)
} else if (isAcOn === true && wheelSize === 19 && speed === 90 && temperature === -10) {
tesla100DRange.innerText = (data[1].hwy[2].kilometers)
} else if (isAcOn === false && wheelSize === 21 && speed === 90 && temperature === -10) {
tesla100DRange.innerText = (data[2].hwy[2].kilometers)
} else if (isAcOn === true && wheelSize === 21 && speed === 90 && temperature === -10) {
tesla100DRange.innerText = (data[3].hwy[2].kilometers)
}
break
case 100:
if(isAcOn === false && wheelSize === 19 && speed === 100 && temperature === -10) {
tesla100DRange.innerText = (data[0].hwy[3].kilometers)
} else if (isAcOn === true && wheelSize === 19 && speed === 100 && temperature === -10) {
tesla100DRange.innerText = (data[1].hwy[3].kilometers)
} else if (isAcOn === false && wheelSize === 21 && speed === 100 && temperature === -10) {
tesla100DRange.innerText = (data[2].hwy[3].kilometers)
} else if (isAcOn === true && wheelSize === 21 && speed === 100 && temperature === -10) {
tesla100DRange.innerText = (data[3].hwy[3].kilometers)
}
break
case 110:
if(isAcOn === false && wheelSize === 19 && speed === 110 && temperature === -10) {
tesla100DRange.innerText = (data[0].hwy[4].kilometers)
} else if (isAcOn === true && wheelSize === 19 && speed === 110 && temperature === -10) {
tesla100DRange.innerText = (data[1].hwy[4].kilometers)
} else if (isAcOn === false && wheelSize === 21 && speed === 110 && temperature === -10) {
tesla100DRange.innerText = (data[2].hwy[4].kilometers)
} else if (isAcOn === true && wheelSize === 21 && speed === 110 && temperature === -10) {
tesla100DRange.innerText = (data[3].hwy[4].kilometers)
}
break
case 120:
if(isAcOn === false && wheelSize === 19 && speed === 120 && temperature === -10) {
tesla100DRange.innerText = (data[0].hwy[5].kilometers)
} else if (isAcOn === true && wheelSize === 19 && speed === 120 && temperature === -10) {
tesla100DRange.innerText = (data[1].hwy[5].kilometers)
} else if (isAcOn === false && wheelSize === 21 && speed === 120 && temperature === -10) {
tesla100DRange.innerText = (data[2].hwy[5].kilometers)
} else if (isAcOn === true && wheelSize === 21 && speed === 120 && temperature === -10) {
tesla100DRange.innerText = (data[3].hwy[5].kilometers)
}
break
case 130:
if(isAcOn === false && wheelSize === 19 && speed === 130 && temperature === -10) {
tesla100DRange.innerText = (data[0].hwy[6].kilometers)
} else if (isAcOn === true && wheelSize === 19 && speed === 130 && temperature === -10) {
tesla100DRange.innerText = (data[1].hwy[6].kilometers)
} else if (isAcOn === false && wheelSize === 21 && speed === 130 && temperature === -10) {
tesla100DRange.innerText = (data[2].hwy[6].kilometers)
} else if (isAcOn === true && wheelSize === 21 && speed === 130 && temperature === -10) {
tesla100DRange.innerText = (data[3].hwy[6].kilometers)
}
break
case 140:
if(isAcOn === false && wheelSize === 19 && speed === 140 && temperature === -10) {
tesla100DRange.innerText = (data[0].hwy[7].kilometers)
} else if (isAcOn === true && wheelSize === 19 && speed === 140 && temperature === -10) {
tesla100DRange.innerText = (data[1].hwy[7].kilometers)
} else if (isAcOn === false && wheelSize === 21 && speed === 140 && temperature === -10) {
tesla100DRange.innerText = (data[2].hwy[7].kilometers)
} else if (isAcOn === true && wheelSize === 21 && speed === 140 && temperature === -10) {
tesla100DRange.innerText = (data[3].hwy[7].kilometers)
}
break
}
} | [
"function gnarMeterData() {\n gnarRates = [\n 1 * multiplyer,\n 2 * multiplyer,\n 3 * multiplyer,\n 4 * multiplyer,\n 5 * multiplyer\n ];\n\n if (measurements === styleOptions.metric) {\n surfMaximum = Math.round(surfMaximum * 3.28);\n }\n\n domElements.LOCATION_NAME.innerHTML = officeName;\n domElements.OFFICE_TITLE.innerHTML = officeName + ' Office';\n\n if (beachName) {\n domElements.BEACH_TITLE.classList.remove(DISABLED);\n\n domElements.BEACH_TITLE.innerHTML = beachName;\n\n domElements.MAP_TITLE.classList.add(MAP_TITLE_TOGGLE);\n } else {\n domElements.BEACH_TITLE.classList.add(DISABLED);\n }\n\n gnarMeter();\n }",
"function getCovidData(){\n $.ajax({\n url: \"https://data.covid19india.org/v4/min/data.min.json\",\n success: function(covidData) {\n for (const stateCode in covidData){\n var stateName = stateIndex[stateCode].StateName;\n var stateLat = stateIndex[stateCode].latitude;\n var stateLong= stateIndex[stateCode].longitude;\n var dailyCovid=0;\n if(stateCode==\"TT\"){\n currState=stateName;\n document.getElementById('clickname').innerHTML=currState;\n document.getElementById('new-cases').innerHTML=covidData[stateCode].delta.confirmed.toLocaleString();\n document.getElementById('recovered').innerHTML=covidData[stateCode].delta.recovered.toLocaleString();\n document.getElementById('deaths').innerHTML=covidData[stateCode].delta.deceased.toLocaleString();\n document.getElementById('total').innerHTML=covidData[stateCode].total.confirmed.toLocaleString();\n var vax2=covidData[stateCode].total.vaccinated2;\n var vax1=covidData[stateCode].total.vaccinated1;\n var pop=covidData[stateCode].meta.population;\n var pc2=(Math.ceil((vax2/pop)*100));\n var pc1=(Math.ceil((vax1/pop)*100));\n $(\".progress\").css(\"visibility\",\"visible\");\n $(\"#vax-bar2\").css(\"width\",pc2+\"%\");\n $(\"#vax-bar1\").css(\"width\",(pc1-pc2)+\"%\");\n document.getElementById('vax-bar2').innerHTML=pc2+\"%\";\n document.getElementById('vax-bar1').innerHTML=(pc1)+\"%\";\n }\n else{\n if(covidData[stateCode].delta!=undefined && covidData[stateCode].delta.confirmed!=undefined){dailyCovid=covidData[stateCode].delta.confirmed;}\n if(stateLat!=undefined && stateLong!=undefined){var circle = L.circle([stateLat,stateLong], { color: 'red', fillColor: '#f03', fillOpacity: 0.5, radius: Math.sqrt(dailyCovid) * 2000 }).addTo(mymap);}\n }\n }\n }\n })\n}",
"function get_data_from_server(nutrient_id, nutrient_old_value, nutrient_new_value)\n {\n // Enable the Save button\n // This element can be absent if there is no food\n if (document.getElementById(\"save_current_meal_plan_button\"))\n document.getElementById(\"save_current_meal_plan_button\").disabled = false;\n \n let url = assemble_get_data_from_server_url(nutrient_id, nutrient_old_value, nutrient_new_value);\n \n fetch(url)\n .then(response => response.json())\n .then(result => {\n \n //console.log(url);\n //console.log(result.data);\n \n // Adjust upper limit of calories due to the goal\n let calories_limit = nutrient_reference_values.get(1008);\n if (calories_limit && calories_limit < 0)\n {\n console.log(`target_weight=${target_weight}, target_weight_deadline=${target_weight_deadline}`);\n if (target_weight && target_weight_deadline && result.additional_weight_info.calorie_target_intake_1w !== undefined)\n {\n let new_calorie_target;\n switch (Number(target_weight_deadline))\n {\n case 7: new_calorie_target = result.additional_weight_info.calorie_target_intake_1w; break;\n case 14: new_calorie_target = result.additional_weight_info.calorie_target_intake_2w; break;\n case 30: new_calorie_target = result.additional_weight_info.calorie_target_intake_1m; break;\n case 60: new_calorie_target = result.additional_weight_info.calorie_target_intake_2m; break;\n case 90: new_calorie_target = result.additional_weight_info.calorie_target_intake_3m; break;\n }\n \n if (new_calorie_target >= 0)\n {\n nutrient_reference_values.set(1008, -Math.round(new_calorie_target));\n document.getElementById('nutrient1008').value = -Math.round(nutrient_reference_values.get(1008));\n }\n else\n {\n let target_weight_u = (is_imperial?`${Math.round(target_weight/0.454)} lbs`:`${Math.round(target_weight)} kg`);\n // If the target is negative then this means that user's goal is unrealistic - then don't change\n // calories reference and warn the user\n if (result.additional_weight_info.calorie_target_intake_2w >= 0)\n alert(`Your goal weight ${target_weight_u} within ${target_weight_deadline} days is unrealistic. But it could be real in 2 weeks`);\n else\n if (result.additional_weight_info.calorie_target_intake_1m >= 0)\n alert(`Your goal weight ${target_weight_u} within ${target_weight_deadline} days is unrealistic. But it could be real in 1 month`);\n else\n if (result.additional_weight_info.calorie_target_intake_2m >= 0)\n alert(`Your goal weight ${target_weight_u} within ${target_weight_deadline} days is unrealistic. But it could be real in 2 months`);\n else\n if (result.additional_weight_info.calorie_target_intake_3m >= 0)\n alert(`Your goal weight ${target_weight_u} within ${target_weight_deadline} days is unrealistic. But it could be real in 3 months`);\n else\n alert(`Your goal weight ${target_weight_u} within ${target_weight_deadline} days is unrealistic event within 3 months. Please try to slightly adjust your goal weight`);\n }\n }\n }\n \n // Move sliders, change data on bubles, change data in current values and\n // change data in the food/nutrient table\n for (let x of result.data)\n {\n if (x.food_id !== undefined)\n {\n // Update the current value, the range and the bubble\n food_current_values.set(Number(x.food_id), x.food_value);\n let range = document.getElementById(\"myRange_food_\" + x.food_id);\n let range_x = range_x_by_value(x.food_value,\n food_referenece_values.get(x.food_id), 10000);\n range.stepUp(range_x - range.value);\n let bubble = document.getElementById(\"bubble_food_\" + x.food_id);\n //console.log(x.food_id, food_current_values.get(x.food_id).toFixed());\n bubble.innerHTML = display_weight_number(food_current_values.get(x.food_id), false, false);\n\n let food_weight_input = document.getElementById(\"food\" + x.food_id);\n //console.log(x.food_id, food_current_values.get(x.food_id).toFixed());\n food_weight_input.value = display_weight_number(food_current_values.get(x.food_id), true, false);\n \n // Update \"td\" with kg in 3 months\n let td = document.getElementById(\"kg_3_month_\" + x.food_id);\n let food_resp_3_month = result.weight_data[31].total_fat_gain * x.food_cal_exc_protein / result.additional_weight_info.calorie_intake;\n \n //console.log(`KG in 3 MONTHS: ${x.food_id}, ${food_resp_3_month}`);\n \n /* - result.additional_weight_info.calorie_need*/\n \n if (food_resp_3_month >= 1000)\n td.innerHTML = `${display_weight_number(food_resp_3_month, false, true)} of fat`;\n else\n td.innerHTML = \"\";\n \n // Update the best nutrient percent\n //let best_n_percent = document.getElementById(`best_${x.food_id}`).innerHTML;\n document.getElementById(`best_${x.food_id}`).innerHTML = x.food_best_nurient; //Math.round(x.food_value * best_n_percent / 100.0);\n \n // Update sCal\n document.getElementById(`scal_${x.food_id}`).innerHTML = x.food_scal;\n }\n if (x.nutrient_id !== undefined)\n {\n // Update the current value, the range and the bubble\n nutrient_current_values.set(Number(x.nutrient_id), x.nutrient_value);\n let range = document.getElementById(\"myRange_nutrient_\" + x.nutrient_id);\n let range_x = range_x_by_value(x.nutrient_value,\n Math.abs(nutrient_reference_values.get(x.nutrient_id)), 10000);\n range.stepUp(range_x - range.value);\n let bubble = document.getElementById(\"bubble_nutrient_\" + x.nutrient_id);\n bubble.innerHTML =\n (nutrient_current_values.get(x.nutrient_id) < 1.0 ?\n nutrient_current_values.get(x.nutrient_id).toFixed(1) :\n nutrient_current_values.get(x.nutrient_id).toFixed());\n //console.log(`set data: x.nutrient_id=${x.nutrient_id}, x.nutrient_value=${x.nutrient_value}, range.value=${range.value}, range_x=${range_x}`);\n\n // Change good/bad signs\n let nutrient_details = document.getElementById(\"nutrient_details_\" + x.nutrient_id);\n if (nutrient_reference_values.get(x.nutrient_id) > 0)\n {\n let ratio = Math.round(100.0*(nutrient_reference_values.get(x.nutrient_id)-x.nutrient_value)/\n nutrient_reference_values.get(x.nutrient_id));\n \n if (ratio <= 0)\n {\n // Add special warning for protein\n if (x.nutrient_id == 1003 && nutrient_reference_values.get(x.nutrient_id) > 70)\n nutrient_details.innerHTML = \"<span style=\\\"color: green;\\\"><b>GOOD</b></span>, make sure having enough physical activity for this high level of protein otherwise it goes to belly fat\";\n else\n nutrient_details.innerHTML = \"<span style=\\\"color: green;\\\"><b>GOOD</b></span>\";\n }\n else\n {\n // Add special warning for protein and fiber\n if (x.nutrient_id == 1003)\n nutrient_details.innerHTML = `<span style=\"color: red;\"><b>(${ratio} % less)</b></span> increase protein - increase satiety, increase metabolism, lose weight, look at Pro column above`;\n else\n if (x.nutrient_id == 1079)\n nutrient_details.innerHTML = `<span style=\"color: red;\"><b>(${ratio} % less)</b></span> increase fiber - increase satiety, reduce hunger, look at Fib column above`;\n else\n if (x.nutrient_id == 1162)\n nutrient_details.innerHTML = `<span style=\"color: red;\"><b>(${ratio} % less)</b></span> increase vitamin C - boost immunity, look at Vit column above`;\n else\n {\n nutrient_details.innerHTML = `<span style=\"color: red;\"><b>(${ratio} % less)</b><!--click <a href=\"JavaScript:force_autocomplete();\">here</a> to find food rich in this nutrient--></span>`;\n }\n }\n }\n else\n {\n let ratio = (100.0*(nutrient_reference_values.get(x.nutrient_id)+x.nutrient_value)/\n -nutrient_reference_values.get(x.nutrient_id)).toFixed();\n\n if (ratio <= 0)\n nutrient_details.innerHTML = \"<span style=\\\"color: green;\\\"><b>GOOD</b></span>\";\n else\n {\n\n \n // Add special warning for sugars and carbs\n if (x.nutrient_id == 2000)\n nutrient_details.innerHTML = `<span style=\"color: red;\"><b>(${ratio} % more)</b></span> cut sugars - reduce hunger (not just white powder, bakery, bread etc - look at Sug col above`;\n else\n if (x.nutrient_id == 1005)\n nutrient_details.innerHTML = `<span style=\"color: red;\"><b>(${ratio} % more)</b></span> cut carbs to reduce hunger - look at Car column above`;\n else\n if (x.nutrient_id == 1008)\n {\n let calorie_need2 = result.additional_weight_info.calorie_need2;\n console.log(calorie_need2);\n nutrient_details.innerHTML = `<span style=\"color: red;\"><b>(${ratio} % more)</b></span>, click <a href=\"javascript:void(0)\" onclick=\"get_data_from_server(1008, nutrient_current_values.get(1008), -nutrient_reference_values.get(1008));\">here</a> to rebalance. Also for equilibrium your need is <a href=\"javascript:void(0)\" onclick=\"get_data_from_server(1008, nutrient_current_values.get(1008), ${calorie_need2});\">${Number(calorie_need2).toFixed()}</a> cal, see details below`;\n }\n else\n {\n nutrient_details.innerHTML = `<span style=\"color: red;\"><b>(${ratio} % more)</b></span>`;\n }\n }\n }\n }\n if (x.food_nutrient_id !== undefined)\n {\n let td = document.getElementById(\"food_nutrient_\" + x.food_nutrient_id).innerHTML =\n x.value;\n }\n if (x.meal_group_name !== undefined)\n {\n // Determine the reference value for this meal group\n let ref_value = 0;\n for (let food_id of meal_groups.get(x.meal_group_name))\n ref_value += food_referenece_values.get(food_id);\n // Update the range and the bubble for the meal group\n let range = document.getElementById(\"myRange_meal_group_\" + x.meal_group_name);\n \n // A meal group can be empty and then there is no range and buble elements\n if (range !== undefined && range !== null)\n {\n let range_x = range_x_by_value(Number(x.meal_group_value),\n ref_value, 10000);\n //console.log(range_x, range.value, ref_value);\n \n range.stepUp(range_x - range.value);\n \n let bubble = document.getElementById(\"bubble_meal_group_name_\" + x.meal_group_name);\n //console.log(x.food_id, food_current_values.get(x.food_id).toFixed());\n bubble.innerHTML = display_weight_number(x.meal_group_value, false, false);\n }\n }\n if (x.meal_group_nutrient_id !== undefined)\n {\n // Update an item in the meal group nutrient list\n let td = document.getElementById(\"meal_group_nutrient_\" + x.meal_group_nutrient_id);\n \n // A meal group can be empty and then there is no \"td\"s with nutrient values\n if (td)\n td.innerHTML = x.value;\n }\n if (x.meal_group_scal !== undefined)\n {\n // Update an item in the meal group nutrient list\n let td = document.getElementById(\"meal_group_scal_\" + x.meal_group_scal);\n \n // A meal group can be empty and then there is no \"td\"s with nutrient values\n if (td)\n td.innerHTML = x.value;\n }\n } //for (let x of result.data)\n \n // Fill mr data\n if (result.metabolic_info !== undefined)\n {\n document.getElementById(\"in_mr_data_gender\").value = mr_data[0] = result.metabolic_info.in_mr_data_gender;\n mr_data[1] = result.metabolic_info.in_mr_data_weight;\n \n document.getElementById(\"in_mr_data_weight\").value = (is_imperial?(mr_data[1]/0.454).toFixed():mr_data[1]);\n \n mr_data[2] = result.metabolic_info.in_mr_data_height;\n if (is_imperial)\n {\n document.getElementById(\"in_mr_data_height_feet\").value = Math.trunc(mr_data[2] / 30.48);\n document.getElementById(\"in_mr_data_height_inches\").value = Math.round((mr_data[2] - Math.trunc(mr_data[2] / 30.48) * 30.48) / 2.54);\n }\n else\n document.getElementById(\"in_mr_data_height\").value = mr_data[2];\n document.getElementById(\"in_mr_data_age\").value =\n mr_data[3] = result.metabolic_info.in_mr_data_age;\n document.getElementById(\"in_mr_data_exercise\").value = mr_data[4] = result.metabolic_info.in_mr_data_exercise;\n document.getElementById(\"in_mr_data_body_type\").value = mr_data[5] = result.metabolic_info.in_mr_data_body_type;\n \n let food_thermic_effect = result.additional_weight_info.carbs_thermic_effect +\n result.additional_weight_info.protein_thermic_effect +\n result.additional_weight_info.alcohol_thermic_effect;\n \n document.getElementById(\"metabolic_rate\").innerHTML =\n `Basal metabolic rate ${result.metabolic_info.out_basal_metabolic_rate.toFixed()} cal<br>Metabolic rate ${result.metabolic_info.out_metabolic_rate.toFixed()} cal<br>Recommended protein intake ${result.metabolic_info.out_protein_max_intake.toFixed()} grams<br>Food thermic effect ${food_thermic_effect.toFixed()}<br>` +\n `Protein need above basal metabolism ${result.additional_weight_info.protein_need_above_bmr_cal.toFixed()} cal` +\n (result.additional_weight_info.protein_need_above_bmr_cal < 0 ? \", it's negative because you intake less amount of protein than your body needs\" :\"\") +\n `<br>Calorie need a day to reach equilibrium in weight ${result.additional_weight_info.calorie_need2.toFixed()} <span style=\"color: green\"><-- eat this much :-) </span><br><a target=\"_blank\" href='${assemble_get_data_from_server_url(-1)}'>raw data</a>`;\n }\n \n // Fill weight data info\n // If the chart is collapsed then just ignore this data\n if (document.getElementById(\"chart_period\"))\n if (result.weight_data !== undefined)\n {\n let week_result;\n let month_result;\n let month3_result;\n\n let chart_data1 = [['Day', 'Metabolic rate', 'Calorie surplus']];\n let chart_data2 = [['Day', (is_imperial?'Fat gain, oz':'Fat gain, g'), (is_imperial?'Muscle gain, oz':'Muscle gain, g'), (is_imperial?'Muscle loss due deficit, oz':'Muscle loss due deficit, g')]];\n let chart_data3 = [['Day', (is_imperial?'Total fat gain, lb':'Total fat gain, kg'), (is_imperial?'Total muscle gain, lb':'Total muscle gain, kg'), (is_imperial?'Total muscle loss due deficit, lb':'Total muscle loss due deficit, kg')]];\n let chart_data4 = [['Day', (is_imperial?'Weight, lb':'Weight, kg')]];\n\n for (let x of result.weight_data)\n {\n if (x.day == 7)\n week_result = x;\n if (x.day == 30)\n month_result = x;\n if (x.day == 90)\n month3_result = x;\n\n // Fill chart data\n if (x.day <= document.getElementById(\"chart_period\").value)\n {\n chart_data1.push([x.day, x.metabolism, x.calorie_surplus]);\n chart_data2.push([x.day,\n Math.round(is_imperial?x.fat_gain/28.3495:x.fat_gain),\n Math.round(is_imperial?x.muscle_gain/28.3495:x.muscle_gain),\n Math.round(is_imperial?x.muscle_loss_component_due_to_deficit/28.3495:x.muscle_loss_component_due_to_deficit)]);\n let total_fat_gain = (is_imperial?x.total_fat_gain/454:x.total_fat_gain/1000);\n let total_muscle_gain = (is_imperial?x.total_muscle_gain/454:x.total_muscle_gain/1000);\n let total_muscle_loss_due_deficit = (is_imperial?x.total_muscle_loss_due_deficit/454:x.total_muscle_loss_due_deficit/1000);\n chart_data3.push([x.day, Math.round(total_fat_gain), Math.round(total_muscle_gain), Math.round(total_muscle_loss_due_deficit)]);\n chart_data4.push([x.day, Math.round((is_imperial?mr_data[1]/0.454:mr_data[1]) + total_fat_gain + total_muscle_gain)]);\n }\n }\n\n \n\n new google.visualization.LineChart(document.getElementById('curve_chart1')).draw(google.visualization.arrayToDataTable(chart_data1), {\n title: 'Metabolism',\n curveType: 'function',\n legend: { position: 'bottom' }\n });\n \n new google.visualization.LineChart(document.getElementById('curve_chart2')).draw(google.visualization.arrayToDataTable(chart_data2), {\n title: (is_imperial?'Fat/Muscle gain per day, oz':'Fat/Muscle gain per day, grams'),\n curveType: 'function',\n legend: { position: 'bottom' }\n });\n \n new google.visualization.LineChart(document.getElementById('curve_chart3')).draw(google.visualization.arrayToDataTable(chart_data3), {\n title: (is_imperial?'Fat/Muscle gain total, lb':'Fat/Muscle gain total, kg'),\n curveType: 'function',\n legend: { position: 'bottom' }\n });\n \n new google.visualization.LineChart(document.getElementById('curve_chart4')).draw(google.visualization.arrayToDataTable(chart_data4), {\n title: (is_imperial?'Weight, lb':'Weight, kg'),\n curveType: 'function',\n legend: { position: 'bottom' }\n });\n \n \n \n function fat_to_text(gain)\n {\n if (gain/1000 < 0.1 && gain/1000 > -0.1)\n gain = 0;\n \n if (gain > 0)\n return `<span style=\"color: red;\">gain ${display_weight_number(gain, false, true)}</span>`;\n else\n return `<span style=\"color: green;\">burn ${display_weight_number(-gain, false, true)}</span>`;\n }\n\n function muscle_to_text(gain)\n {\n if (gain/1000 < 0.1 && gain/1000 > -0.1)\n gain = 0;\n \n if (gain >= 0)\n return `<span style=\"color: green;\">build ${display_weight_number(gain, false, true)}</span>`;\n else\n return `<span style=\"color: red;\">lose ${display_weight_number(-gain, false, true)}</span>`;\n }\n \n document.getElementById(\"week_gain\").innerHTML =\n `In a week you'll ${fat_to_text(week_result.total_fat_gain)} of fat and ${muscle_to_text(week_result.total_muscle_gain)} of muscle`;\n \n // If we still burn muscle but the calorie intaken as needed - then recommend\n // increase exercise\n /*console.log(week_result.total_muscle_gain, result.additional_weight_info.calorie_intake, result.additional_weight_info.calorie_need2);*/\n if (week_result.total_muscle_gain <= -100 &&\n Math.abs(result.additional_weight_info.calorie_intake - result.additional_weight_info.calorie_need2) < 5)\n {\n let txt;\n if (mr_data[4] == 0)\n txt = 'to 1-3 times/week';\n else\n if (mr_data[4] == 1)\n txt = 'to 4-5 times/week';\n else\n if (mr_data[4] == 2)\n txt = 'to daily or make it intense 3-4 times/week';\n else\n if (mr_data[4] == 3)\n txt = 'to intense exercise 6-7 times/week';\n else\n if (mr_data[4] == 4)\n txt = 'to very intense exercise daily';\n else\n txt = 'as much you can';\n document.getElementById(\"week_gain\").innerHTML +=\n `, to stop burn muscle increase your exercise ${txt}`;\n }\n \n document.getElementById(\"month_gain\").innerHTML =\n `In a month you'll ${fat_to_text(month_result.total_fat_gain)} of fat and ${muscle_to_text(month_result.total_muscle_gain)} of muscle`;\n document.getElementById(\"month3_gain\").innerHTML =\n `In 3 months you'll ${fat_to_text(month3_result.total_fat_gain)} of fat and ${muscle_to_text(month3_result.total_muscle_gain)} of muscle`;\n \n let sodium_g = result.additional_weight_info.water_retention_sodium;\n let txt = '';\n if (sodium_g > 100)\n txt += `Cut sodium - lose <span style=\"color: red;\">${display_weight_number(sodium_g, false, true)}</span> of excess water bound by sodium, look at Sod column above<br>`;\n let carbs_g = result.additional_weight_info.water_retention_carbs;\n if (carbs_g > 100)\n txt += `Cut carbs - lose <span style=\"color: red;\">${display_weight_number(carbs_g, false, true)}</span> of excess water bound by carbs, look at Car column above`;\n document.getElementById(\"carbs_n_sodium\").innerHTML = txt;\n\n // Fill diet type info\n txt = `${(100*result.additional_weight_info.calorie_intake_protein_percent).toFixed()}% of calories from protein<br>`;\n txt += `${(100*result.additional_weight_info.calorie_intake_fat_percent).toFixed()}% of calories from fat<br>`;\n txt += `${(100*result.additional_weight_info.calorie_intake_carbs_percent).toFixed()}% of calories from carbs (out of which `;\n txt += `${(100*result.additional_weight_info.calorie_intake_sugar_percent).toFixed()}% of calories from sugar)<br>`;\n txt += `${(100*result.additional_weight_info.calorie_intake_alcohol_percent).toFixed()}% of calories from alcohol<br>`;\n \n if (result.additional_weight_info.calorie_intake_sugar_percent > 0.2)\n txt += '<span style=\"color: red;\">You consume too much sugar which makes you hungry and makes you eat more</span><br>';\n if (result.additional_weight_info.calorie_intake_protein_percent < 0.1)\n txt += '<span style=\"color: red;\">You consume too little protein which is bad for your hair, nails, muscles</span><br>';\n if (result.additional_weight_info.calorie_intake_fat_percent > 0.65 &&\n result.additional_weight_info.calorie_intake_carbs_percent < 0.2)\n txt += '<span style=\"color: green;\">You are on a keto diet which is good! It reduces hunger</span><br>';\n if (result.additional_weight_info.calorie_intake_protein_percent > 0.35)\n txt += '<span style=\"color: green;\">You are on a very high protein diet! Which is good but beware you have enough exercise</span><br>';\n \n document.getElementById(\"type_of_diet\").innerHTML = txt;\n } // if (result.weight_data !== undefined)\n \n });\n } // function get_data_from_server(nutrient_id)",
"function getDemographics(location) {\n $.getJSON(\n \"https://www.broadbandmap.gov/broadbandmap/demographic/2014/\"+\n \"coordinates?latitude=\"+location.lat+\"&longitude=\"+\n location.lng+\"&format=json\", function(json) {\n console.log(json.Results);\n content=\"<h2>\"+location.name+\"</h2>\"+\n \"<h4>Area Demographics:</h4>\"+\n \"<p>Education: High School Graduate: \" +\n json.Results.educationHighSchoolGraduate.toFixed(1)+\"%</p>\"+\n \"<p>Education: Bachelor's Degree or Greater: \" +\n json.Results.educationBachelorOrGreater.toFixed(1)+\"%</p>\"+\n \"<p>Education: High School Graduate: \" +\n json.Results.educationHighSchoolGraduate.toFixed(1)+\"%</p>\"+\n \"<p>Income Below Poverty: \"+\n json.Results.incomeBelowPoverty.toFixed(1)+\"%</p>\"+\n \"<p>Income less than $25,000: \" +\n json.Results.incomeLessThan25.toFixed(1)+\"%</p>\"+\n \"<p>Income Between $25,000 and $50,000: \" +\n json.Results.incomeBetween25to50.toFixed(1)+\"%</p>\"+\n \"<p>Income Between $50,000 and $100,000: \" +\n json.Results.incomeBetween50to100.toFixed(1)+\"%</p>\"+\n \"<p>Income Between $100,000 and $200,000: \" +\n json.Results.incomeBetween100to200.toFixed(1)+\"%</p>\"+\n \"<p>Income greated than $200,000: \" +\n json.Results.incomeGreater200.toFixed(1)+\"%</p>\"+\n \"<p>Median Income: $\" +\n json.Results.medianIncome.toFixed(1)+\"</p>\";\n\n\n\n }).fail(function(jqXHR, textStatus, errorThrown) { content=\n \"<p>Failed to Retrieve Demographics Information</p>\"; })\n .always(function() {\n location.infoWindow.setContent(content);\n location.infoWindow.open(map,marker);});\n }",
"function displayKegData(){\n const selector = document.querySelectorAll(\"#active_keg_information_app .keg_container .keg\");\n let counter = 0;\n selector.forEach( () => {\n counter++\n const percentage = (((globalData.barData.taps[(counter-1)].level)/2500)*100).toFixed(0);\n document.querySelector(`#active_keg_information_app .keg_container .keg${counter} h3`).innerHTML = globalData.barData.taps[(counter-1)].beer;\n document.querySelector(`#active_keg_information_app .keg_container .keg${counter} h4`).innerHTML = `${percentage}%`; \n document.querySelector(`#active_keg_information_app .keg_container .keg${counter} div .beer`).style.height = `${((globalData.barData.taps[(counter-1)].level)/2500)*100}%`; \n document.querySelector(`#active_keg_information_app .keg_container .keg${counter} div .foam`).style.height = `${(((globalData.barData.taps[(counter-1)].level)/2500)*100)/10+2}%`; \n document.querySelector(`#active_keg_information_app .keg_container .keg${counter} img`).src = `./minified_logos/${globalData.barData.taps[(counter-1)].beer.replaceAll(\" \", \"\").toLowerCase()}.png`;\n\n if (globalData.barData.taps[(counter-1)].level === 0) {\n document.querySelector(`#active_keg_information_app .keg_container .keg${counter} div .foam`).style.height = 0;\n }\n })\n //callback makes sure the DOM is constantly updated every second after initial call.\n setTimeout(displayKegData, 1000);\n}",
"function getWindSpeed(speedUnits){\n $.getJSON(api, function(data){\n //var humidity = (data.current.humidity);\n if (speedUnits == \"kph\"){\n var speedSulfix = \" Kph\";\n var windSpeed = (data.current.wind_kph);\n }\n else if (speedUnits == \"mph\"){\n var speedSulfix = \" Mph\";\n var windSpeed = (data.current.wind_mph);\n }\n //document.getElementById(\"pHumidity\").innerHTML = humidity + \" %\";\n document.getElementById(\"pWindSpeed\").innerHTML = + windSpeed + speedSulfix;\n });\n }",
"function displayDensityData()\n{\n // make localstorage data to JavaScript object.\n var countriesList = JSON.parse(localStorage.ns);\n // get the target's value in html\n var selectedConutryName = document.getElementById('countryList').value;\n // set the target to change element\n var targetElementDensity = document.getElementById('targetDensity');\n\n var newInputDensity = \"\";\n\n // validation\n if(selectedConutryName == \"Select One\")\n {\n newInputDensity = \"<input id='populationDensityInput' value='0' disabled />\";\n }\n else\n {\n var ratioMilesKm = 2.58999;\n var selectedCountryDensity = 0;\n var selectedCountryPopulation = 0;\n var selectedCountryAreaMiles = 0;\n \n\n // find selected country's population\n for(var i = 0; i < countriesList.length; i++)\n {\n var countryElement = countriesList[i];\n if(selectedConutryName == countryElement[\"Name\"])\n {\n selectedCountryPopulation = countryElement[\"Population\"];\n }\n }\n\n //find selected country's area\n for(var i = 0; i < countriesList.length; i++)\n {\n var countryElement = countriesList[i];\n if(selectedConutryName == countryElement[\"Name\"])\n {\n selectedCountryAreaMiles = countryElement[\"Area\"];\n }\n }\n\n // if selected density type is miles, then make float number\n if(document.getElementById('mile').checked)\n {\n selectedCountryDensity = (selectedCountryPopulation / selectedCountryAreaMiles).toFixed(2);\n }\n // if selected density type is km, then make km unit using function\n if(document.getElementById('km').checked)\n {\n selectedCountryDensity = (selectedCountryPopulation / (selectedCountryAreaMiles * ratioMilesKm)).toFixed(2);\n }\n\n newInputDensity += `<input id=\"populationDensityInput\" value=\"${selectedCountryDensity}\" disabled />`;\n }\n // replace HTML element\n targetElementDensity.innerHTML = newInputDensity;\n}",
"function loadData() {\n $.ajax({\n dataType: \"json\",\n url: \"http://139.59.162.120/\" + crime + \"/\",\n mimeType: \"application/json\",\n success: function(values){\n\n var maxVal = 0;\n var maxAllVal = 0;\n\n vals = values.map(val => (parseInt(val[\"v\" + year]) ));\n allVals = values.map(function(val) {\n delete val.Name;\n for(var i = 2003; i <= 2016; i++){\n val[\"v\" + i] = parseInt(val[\"v\" + i]);\n if(val[\"v\" + i] > maxAllVal){\n maxAllVal = val[\"v\" + i];\n };\n }\n return val;\n });\n\n for(var i = 0; i < stats.length; i++)\n {\n stats[i].value = vals[i];\n if(vals[i] > maxVal){\n maxVal = vals[i];\n }\n }\n\n for(var i = 0; i < stats.length; i++)\n {\n markers[i].bindPopup(\"<b>\" + stats[i].name + \" Garda Station</b>\"\n + \"<br>County: \" + stats[i].county + \"<br>Reported Cases: \" + stats[i].value);\n }\n if($(\"input[name=max]\").is(\":checked\")) {\n hmap = {max: maxAllVal, data: stats.map(x => ({ lat: x.lat, lng: x.long, count: x.value}))};\n }\n else {\n hmap = {max: maxVal, data: stats.map(x => ({ lat: x.lat, lng: x.long, count: x.value}))};\n }\n\n if(heatmapLayer == null){\n heatmapLayer = new HeatmapOverlay(cfg);\n lCtrl = L.control.layers(null).addTo(map);\n map.addLayer(heatmapLayer);\n lCtrl.addOverlay(heatmapLayer, \"Heatmap\");\n $(\"input[name=max]\").prop('disabled', false);\n\n }\n heatmapLayer.setData(hmap);\n populateTable();\n }\n });\n}",
"function getData(response) {\n\n // get the number of rows returned by showDenominations\n var numRows = response.getDataTable().getNumberOfRows();\n \n // concatenate the results into a menu for use in HTML\n \n /**\n * open the menu\n * the fusiontabledata variable will be what's put on the page via innerHTML\n */\n var fusiontabledata = '<select onchange=\"changeMapForDenominations(this.value); showNames(this.value);\">';\n\n // add a generic option by default\n // if someone selects it, the value of 'All' will cause the map to be\n // reset in changeMapForDenominations\n fusiontabledata += \"<option value='All'>Choose...</option>\";\n \n //for each row (ie. denomination) returned by the query in showDenominations\n for (var i = 0; i < numRows; i++) {\n // place the value of the row (the denomination name) into a variable\n var denom = response.getDataTable().getValue(i, 0);\n // begin each option in the dropdown\n // put the escaped denom name as the value\n // this is used by the onchange function in <select>\n fusiontabledata += \"<option value=\\\"\" + denom + \"\\\">\";\n // then the name of the denom\n fusiontabledata += denom;\n // then close the option\n fusiontabledata += \"</option>\";\n } \n // after all options are displayed, close the menu\n fusiontabledata += \"</select>\";\n \n //display the results on the page\n document.getElementById('howomo-listofdenominations').innerHTML = fusiontabledata;\n}",
"function calculateP_02P_01Ratio() {\n if (data[\"P_02/P_01\"] === \"\") {\n if (data[\"T_021\"] !== \"\" && data[\"gamma_a\"] !== \"\" && data[\"T_01\"] !== \"\" && data[\"eta_c\"]) {\n newValueCalculated = true;\n data[\"P_02/P_01\"] = (data[\"T_021\"] * (data[\"eta_c\"] / data[\"T_01\"]) + 1) ** (data[\"gamma_a\"] / (data[\"gamma_a\"] - 1));\n } else if (data[\"P_01\"] !== \"\" && data[\"P_02\"] !== \"\") {\n newValueCalculated = true;\n data[\"P_02/P_01\"] = data[\"P_02\"] / data[\"P_01\"];\n }\n showNewData(\"P_02/P_01\")\n }\n}",
"function getData(result) {\n var ndx;\n var max = 0;\n var max2=0; var last2 =0;\n var max1=0; var last1 =0;\n if(result.length == 0) {\n\tconsole.log(\"No data\");\n }\n else if(result.length > 0 && result.length <= 8) {\n var wmax = 0;\n var wmin = 1000;\n var length; \n\tif(result.length >= 7) { length = 7;}\n else { length = result.length; }\n for(i=0; i<length; i++) {\n if(result[i].total < wmin && result[i].total != 0) {\n wmin = result[i].total;\n }\n \n if(result[i].total > wmax) {\n wmax = result[i].total;\n }\n }\n var todaysTotal = cafe1Total + cafe2Total;\n loadLiquidFillGauge(\"fillgauge1\", todaysTotal/wmax*100, config1);\n loadLiquidFillGauge(\"fillgauge2\", todaysTotal/wmin*100, config1);\n \n } else {\n cafe2Total = 0;\n cafe1Total = 0;\n \n //place samples in the correct dataset\n for (ndx = 0; ndx < result.length; ndx++) {\n var current = result[ndx];\n //add to cafe 1 dataset\n if (current.trash_can_id == \"cafe_1\") {\n if (new Date(current.timestamp).getHours() >= 6) {\n \n if (cafe1Total == 0) {\n cafe1Total = current.weight;\n max1 = current.weight;\n } else {\n if (last1 - current.weight > 5 || current.weight < .05) {\n// if(current.weight < 1) {\n max1 = current.weight;\n cafe1Total = cafe1Total + current.weight;\n // }\n } else {\n if (max1 < current.weight) {\n cafe1Total = cafe1Total - max1 + current.weight;\n max1 = current.weight;\n }\n }\n }\n last1 = current.weight;\n data.push({\n \"x\": parseTime(current.timestamp),\n \"y\": current.weight\n });\n data3.push({\n \"x\": parseTime(current.timestamp),\n \"y\": cafe1Total //current.total\n });\n }\n }\n \n //add to cafe 2 dataset\n if(current.trash_can_id == \"cafe_2\") {\n if(new Date(current.timestamp).getHours() >= 6) {\n if(cafe2Total == 0) {\n max2 = current.weight;\n cafe2Total = current.weight;\n }\n else {\n if(last2 - current.weight > 5 || current.weight < .05) {\n max2 = current.weight;\n cafe2Total = cafe2Total + current.weight;\n } else {\n if(max2 < current.weight) {\n cafe2Total = cafe2Total - max2 + current.weight;\n max2 = current.weight;\n }\n }\n }\n last2 = current.weight;\n data2.push({\n \"x\":parseTime(current.timestamp),\n \"y\":current.weight\n });\n data4.push({\n \"x\":parseTime(current.timestamp),\n \"y\":cafe2Total//current.total\n });\n }\n }\n //save max\n if( max < cafe1Total || max < cafe2Total ) {\n max = findMax(cafe1Total, cafe2Total);\n }\n }\n if(max == 0) {max = 5;}\n console.log(\"caf1 = \" +cafe1Total);\n console.log(\"caf2 = \"+cafe2Total);\n \n totalWaste = cafe2Total+cafe1Total;\n console.log(totalWaste);\n \n var start;\n \n if(data.length > 0) {\n if(data[0].x < data2[0].x) { start = data[0].x; end = data[data.length-1].x; }\n\t else { start = data2[0].x; end = data2[data2.length-1].x; }\n } else {\n start = new Date(2017,2,20);\n\t end = new Date();\n }\n \n //graph everything\n d3.selectAll(\".graph svg > *\").remove(); \t\t//remove old graphs\n\t\n graphDataMultiLine(max, start, end, [data3, data4]);\t//graph line graph of total waste\n //graph fil gauges\n if(skipWeek) {\n getWeek(\"03-03-2017\");\n } else {\n dateToDisplay = (start.getMonth()+1)+\"-\"+start.getDate()+\"-\"+start.getFullYear();\n getWeek(dateToDisplay);\n }\n \n imagery(totalWaste);\t\t\t\t//display proper number of trash bags\n \n //set timer to update everything 1 minute from now\n setTimeout(retrieveData, 60000);\n \n //reset data arrays\n data = []\n data2 = [];\n data3 = [];\n data4 = [];\n }\n}",
"function first9DartsArrayAllTime(dart1, dart2, dart3){\n all_time_heatmap_stats = myAJAX();\n var darts_hit = [];\n if ((dart1 == true && dart2 == true && dart3 == true) || (dart1 == false && dart2 == false && dart3 == false)){\n for (i = 0; i < all_time_heatmap_stats.length; i++)\n {\n if (all_time_heatmap_stats[i]['darts_in_leg'] < 9){\n darts_hit.push(all_time_heatmap_stats[i]['hit_location']);\n }\n }\n }else{\n if (dart1 == true){\n for (i = 0; i < all_time_heatmap_stats.length; i++)\n {\n if (all_time_heatmap_stats[i]['dart_number'] == \"1\" && all_time_heatmap_stats[i]['darts_in_leg'] < 9)\n {\n darts_hit.push(all_time_heatmap_stats[i]['hit_location']);\n }\n }\n }\n if (dart2 == true){\n for (i = 0; i < all_time_heatmap_stats.length; i++)\n {\n if (all_time_heatmap_stats[i]['dart_number'] == \"2\" && all_time_heatmap_stats[i]['darts_in_leg'] < 9)\n {\n darts_hit.push(all_time_heatmap_stats[i]['hit_location']);\n }\n }\n }\n if (dart3 == true){\n for (i = 0; i < all_time_heatmap_stats.length; i++)\n {\n if (all_time_heatmap_stats[i]['dart_number'] == \"3\" && all_time_heatmap_stats[i]['darts_in_leg'] < 9)\n {\n darts_hit.push(all_time_heatmap_stats[i]['hit_location']);\n }\n }\n }\n }\n return darts_hit;\n}",
"function getCalculation() {\n $.ajax({\n type: 'GET',\n url: '/type',\n success: function (response) {\n $('.viewport').text(response);\n },\n });\n}",
"function __getDiskon_penjualan(){\n var tipe_customer=$('#kd_typecustomer').val()\n $.getJSON(http+\"/spk/diskon/\"+tipe_customer,{'k':tipe_customer},function(result){\n if(result.length>0){\n $.each(result,function(e,d){\n $('#diskon').val(parseFloat(d.AMOUNT).toLocaleString()).addClass(\"text-right\");\n $('#diskon').attr('title',(d.TIPE_DISKON=='0')?'dalam persen':'dalam rupiah');\n $('#tp_diskon').val(d.TIPE_DISKON);\n })\n }\n })\n}",
"function getData() {\n $(\"#massScavengeSophie\").remove();\n URLs = [];\n $.get(URLReq, function (data) {\n for (var i = 0; i <= $(\".paged-nav-item\").length; i++) {\n //push url that belongs to scavenging page i\n URLs.push(URLReq+\"&page=\" + i);\n //get world data\n tempData = JSON.parse($(data).find('script:contains(\"ScavengeMassScreen\")').html().match(/\\{.*\\:\\{.*\\:.*\\}\\}/g)[0]);\n duration_exponent = tempData[1].duration_exponent;\n duration_factor = tempData[1].duration_factor;\n duration_initial_seconds = tempData[1].duration_initial_seconds;\n }\n console.log(URLs);\n\n })\n .done(function () {\n //here we get all the village data and make an array with it, we won't be able to parse unless we add brackets before and after the string\n arrayWithData = \"[\";\n $.getAll(URLs,\n (i, data) => {\n thisPageData = $(data).find('script:contains(\"ScavengeMassScreen\")').html().match(/\\{.*\\:\\{.*\\:.*\\}\\}/g)[2];\n arrayWithData += thisPageData + \",\";\n },\n () => {\n //on done\n arrayWithData = arrayWithData.substring(0, arrayWithData.length - 1);\n //closing bracket so we can parse the data into a useable array\n arrayWithData += \"]\";\n console.log(arrayWithData);\n scavengeInfo = JSON.parse(arrayWithData);\n // count and calculate per village how many troops per category need to be sent. \n // Once count is finished, make a new UI element, and group all the results per 200.\n // According to morty, that is the limit at which the server will accept squad pushes.\n count=0;\n for (var i = 0; i < scavengeInfo.length; i++) {\n calculateHaulCategories(scavengeInfo[i]);\n count++;\n }\n if (count == scavengeInfo.length) {\n //Post here\n console.log(\"Done\");\n //need to split all the scavenging runs per 200, server limit according to morty\n squads = {};\n per200 = 0;\n groupNumber = 0;\n squads[groupNumber] = [];\n for (var k = 0; k < squad_requests.length; k++) {\n if (per200 == 200) {\n groupNumber++;\n squads[groupNumber] = [];\n per200 = 0;\n }\n per200++;\n squads[groupNumber].push(squad_requests[k]);\n }\n //create html send screen with button per launch\n console.log(\"Creating launch options\");\n htmlWithLaunchButton=`<div id=\"massScavengeFinal\" class=\"ui-widget-content\" style=\"position:fixed;background-color:${backgroundColor};cursor:move;z-index:50;\">\n <table id=\"massScavengeSophieFinalTable\" class=\"vis\" border=\"1\" style=\"width: 100%;background-color:${backgroundColor};border-color:${borderColor}\">\n <tr>\n <td colspan=\"10\" id=\"massScavengeSophieTitle\" style=\"text-align:center; width:auto; background-color:${headerColor}\">\n <h2>\n <center style=\"margin:10px\"><u>\n <font color=\"${titleColor}\">${langShinko[7]}</font>\n </u>\n </center>\n </h2>\n </td>\n </tr>`;\n\n //add row with new button\n htmlWithLaunchButton+=`<tr id=\"sendAll\" style=\"text-align:center; width:auto; background-color:${backgroundColor}\"><td style=\"text-align:center; width:auto; background-color:${backgroundColor}\"><center><input type=\"button\" class=\"btn evt-confirm-btn btn-confirm-yes\" id=\"sendMass\" onclick=\"sendGroups()\" value=\"${langShinko[8]}\"></center></td></tr>`\n\n htmlWithLaunchButton+=\"</table></div>\"\n //appending to page\n console.log(\"Creating launch UI\");\n $(\"#contentContainer\").eq(0).prepend(htmlWithLaunchButton);\n $(\"#mobileContent\").eq(0).prepend(htmlWithLaunchButton);\n $(\"#massScavengeFinal\").draggable();\n }\n },\n (error) => {\n console.error(error);\n });\n }\n )\n}",
"function getCustom() {\n var customFrom = $('#custom-from').val()\n var customTo = $('#custom-to').val()\n // makes an AJAX call with the custom data period\n $.get('/' + username + '/statistics/' + custom + '/custom/' + customFrom + '/' + customTo)\n .done((data) => {\n switch (custom) {\n case 'profits':\n setProfits(data);\n break;\n case 'entries':\n setEntries(data)\n break;\n case 'best-asset':\n setBestAsset(data)\n break;\n case 'strategies':\n setStrategies(data.customData)\n break;\n case 'assets':\n setAssets(data.customData)\n break;\n case 'timeframes':\n setTimeframes(data.customData)\n break;\n case 'days':\n setDays(data.customData)\n break;\n case 'directionDist':\n setDirectionDist(data)\n break;\n case 'directionGraph':\n setDirectionGraph(data)\n break;\n }\n })\n .fail(() => {\n // error\n })\n}",
"function fillData(data) {\n //console.log($(\"#btcpct\").html())\n if (data.DISPLAY.BTC.USD.CHANGEPCT24HOUR > 0) {\n $(\"#BTCpct\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BTC.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#BTCprice\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BTC.USD.PRICE)\n } else {\n $(\"#BTCpct\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BTC.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#BTCprice\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BTC.USD.PRICE)\n }\n if (data.DISPLAY.ETH.USD.CHANGEPCT24HOUR > 0) {\n $(\"#ETHpct\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ETH.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#ETHprice\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ETH.USD.PRICE)\n } else {\n $(\"#ETHpct\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ETH.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#ETHprice\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ETH.USD.PRICE)\n }\n if (data.DISPLAY.XRP.USD.CHANGEPCT24HOUR > 0) {\n $(\"#XRPpct\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.XRP.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#XRPprice\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.XRP.USD.PRICE)\n } else {\n $(\"#XRPpct\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.XRP.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#XRPprice\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.XRP.USD.PRICE)\n }\n if (data.DISPLAY.BCH.USD.CHANGEPCT24HOUR > 0) {\n $(\"#BCHpct\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BCH.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#BCHprice\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BCH.USD.PRICE)\n } else {\n $(\"#BCHpct\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BCH.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#BCHprice\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BCH.USD.PRICE)\n }\n if (data.DISPLAY.LTC.USD.CHANGEPCT24HOUR > 0) {\n $(\"#LTCpct\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.LTC.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#LTCprice\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.LTC.USD.PRICE)\n } else {\n $(\"#LTCpct\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.LTC.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#LTCprice\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.LTC.USD.PRICE)\n }\n if (data.DISPLAY.XLM.USD.CHANGEPCT24HOUR > 0) {\n $(\"#XLMpct\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.XLM.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#XLMprice\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.XLM.USD.PRICE)\n } else {\n $(\"#XLMpct\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.XLM.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#XLMprice\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.XLM.USD.PRICE)\n }\n if (data.DISPLAY.ETC.USD.CHANGEPCT24HOUR > 0) {\n $(\"#ETCpct\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ETC.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#ETCprice\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ETC.USD.PRICE)\n } else {\n $(\"#ETCpct\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ETC.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#ETCprice\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ETC.USD.PRICE)\n }\n if (data.DISPLAY.BAT.USD.CHANGEPCT24HOUR > 0) {\n $(\"#BATpct\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BAT.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#BATprice\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BAT.USD.PRICE)\n } else {\n $(\"#BATpct\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BAT.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#BATprice\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.BAT.USD.PRICE)\n }\n if (data.DISPLAY.ZEC.USD.CHANGEPCT24HOUR > 0) {\n $(\"#ZECpct\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ZEC.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#ZECprice\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ZEC.USD.PRICE)\n } else {\n $(\"#ZECpct\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ZEC.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#ZECprice\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ZEC.USD.PRICE)\n }\n if (data.DISPLAY.ZRX.USD.CHANGEPCT24HOUR > 0) {\n $(\"#ZRXpct\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ZRX.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#ZRXprice\").html(\"<span class=\\\"badge badge-pill badge-success\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ZRX.USD.PRICE)\n } else {\n $(\"#ZRXpct\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><iclass=\\\"\" +\n \"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ZRX.USD.CHANGEPCT24HOUR + \"%\")\n $(\"#ZRXprice\").html(\"<span class=\\\"badge badge-pill badge-danger\\\"><i\" +\n \"class=\\\"fas fa-arrow-alt-circle-down\\\"></i></span> \" + data.DISPLAY.ZRX.USD.PRICE)\n }\n\n}",
"function calculateT_021() {\n\n if (data[\"T_021\"] === \"\") {\n if (data[\"T_01\"] !== \"\" && data[\"T_02\"] !== \"\") {\n newValueCalculated = true;\n data[\"T_021\"] = data[\"T_02\"] - data[\"T_01\"]\n\n } else if (data[\"T_01\"] !== \"\" && data[\"eta_c\"] !== \"\" && data[\"P_02/P_01\"] !== \"\" && data[\"gamma_a\"] !== \"\") {\n newValueCalculated = true;\n data[\"T_021\"] = (data[\"T_01\"] / data[\"eta_c\"]) * ((data[\"P_02/P_01\"] ** ((data[\"gamma_a\"] - 1) / data[\"gamma_a\"])) - 1);\n } else if (data[\"eta_m\"] !== \"\" && data[\"C_pg\"] !== \"\" && data[\"C_pa\"] !== \"\" && data[\"T_034\"]) {\n newValueCalculated = true;\n data[\"T_021\"] = data[\"eta_m\"] * (data[\"C_pg\"] / data[\"C_pa\"]) * data[\"T_034\"];\n }\n showNewData(\"T_021\")\n }\n\n}",
"function loadLandingPageData(){\n fetch('https://api.covidtracking.com/v1/us/current.json')\n .then(function(response){\n return response.json()\n })\n .then(function(data){\n renderLPD(data)\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find blockchain storage with count max | findLastStorage(storageInfo) {
let countMaxStorageNumber = -1;
let countMaxStorageName;
for (let storageName in storageInfo) {
if (storageInfo[storageName].storageNumber > countMaxStorageNumber) {
countMaxStorageNumber = storageInfo[storageName].storageNumber;
countMaxStorageName = storageName;
}
}
return countMaxStorageName;
} | [
"getMostUsedDestCurrency() {\n let maxCurrUsageCount = 0;\n let maxCurrCode;\n for (let curr in this.data.currencies) {\n if (maxCurrUsageCount < this.data.currencies[curr]) {\n maxCurrUsageCount = this.data.currencies[curr];\n maxCurrCode = curr;\n }\n }\n this.data.maxCurrCode = maxCurrCode\n }",
"function findHighestSize(trades) {\nlet highest = 0;\nlet arrSize = [];\n for (let i = 0; i < trades.length; i++) {\n let trade = trades[i]\n arrSize.push(trade.size)\n }\n highest = Math.max(...arrSize)\n return roundNum(highest)\n}",
"function bestContainer(list){\n var i;\n // Max store.\n var a = 0;\n \n for (i = 0; i < list.length; i++){\n // Get store count.\n var b = _.sum(list[i].store)\n if(a > b){\n // keep a\n }\n else{\n // keep b and list item\n a = b\n var fullestContainer = list[i]\n }\n }\n // Return highest store.\n return fullestContainer;\n}",
"function findHighestSize(trades) {\n // Default Value and output\n let highestSize = 0\n let current = trades[0]\n for (let i = 1; i < trades.length; i++) {\n trade = trades[i] \n trade.size > current.size ? current = trade : current;\n highestSize = roundNum(current.size)\n }\n\n return highestSize\n}",
"findBiggestUtxo (utxos) {\n try {\n let largestAmount = 0\n let largestIndex = 0\n\n for (var i = 0; i < utxos.length; i++) {\n const thisUtxo = utxos[i]\n\n if (thisUtxo.value > largestAmount) {\n largestAmount = thisUtxo.value\n largestIndex = i\n }\n }\n\n return utxos[largestIndex]\n } catch (err) {\n _this.wlogger.error('Error in wallet.js/findBiggestUtxo().')\n throw err\n }\n }",
"max() {\n let max = -100000;\n for (let a = 0; a < this.size(); a++) {\n if (this.v[a] > max) {\n max = this.v[a];\n }\n }\n return max;\n }",
"function getMax(i) {\r\n var max = 0;\r\n var max_key = \"\";\r\n var result = JSON.parse(i.network_performance)\r\n\r\n for (var i in result) {\r\n if (result[i].perc_disc_50 > max) {\r\n max = result[i].perc_disc_50;\r\n max_key = result[i].network;\r\n }\r\n }\r\n return max_key\r\n\r\n}",
"async getLargestAccounts(config) {\n const arg = { ...config,\n commitment: config && config.commitment || this.commitment\n };\n const args = arg.filter || arg.commitment ? [arg] : [];\n const unsafeRes = await this._rpcRequest('getLargestAccounts', args);\n const res = superstruct.create(unsafeRes, GetLargestAccountsRpcResult);\n\n if ('error' in res) {\n throw new Error('failed to get largest accounts: ' + res.error.message);\n }\n\n return res.result;\n }",
"function getLimit() {\n indexedDB.get(STORAGE_IDB_KEY);\n }",
"function getMaxOpAtPeer() {\n\tvar max = 0;\n\tfor(var i = 0;i<peersJSON.length;i++)\n\t{\n\t\tif(peersJSON[i].puts>max)\n\t\t{\n\t\t\tmax = peersJSON[i].puts;\n\t\t}\n\t\tif(peersJSON[i].gets>max)\n\t\t{\n\t\t\tmax = peersJSON[i].gets;\n\t\t}\n\t}\n\treturn max;\n}",
"function getMaxIndex() {\n return localStorage.getItem(\"MAXINDEX\")\n}",
"function findHolderOfHighestAmmount() {\n var highestAmmount = 0;\n var highestAmmountHolder = []\n for (account of accounts) {\n if (highestAmmount < account.amount) {\n highestAmmount = account.amount;\n highestAmmountHolder.push(account);\n }\n }\n accountHolder = highestAmmountHolder.pop();\n return accountHolder.name;\n}",
"async getLargestAccounts(config) {\n const arg = { ...config,\n commitment: config && config.commitment || this.commitment\n };\n const args = arg.filter || arg.commitment ? [arg] : [];\n const unsafeRes = await this._rpcRequest('getLargestAccounts', args);\n const res = GetLargestAccountsRpcResult(unsafeRes);\n\n if (res.error) {\n throw new Error('failed to get largest accounts: ' + res.error.message);\n }\n\n assert(typeof res.result !== 'undefined');\n res.result.value = res.result.value.map(({\n address,\n lamports\n }) => ({\n address: new PublicKey(address),\n lamports\n }));\n return res.result;\n }",
"getAccountMostTransactions(token, time) {\n let account = \"\";\n let mostTx = 0;\n \n Object.keys(this.addresses).forEach(key => {\n let address = this.addresses[key];\n let txs = address.getTransactionsByTokenId(token);\n\n if (txs.length > mostTx) {\n account = key;\n mostTx = txs.length;\n }\n });\n return account;\n }",
"function get150BiggestCurrencies() {\n let p = new Promise(function(resolve, reject) {\n if (cacheBiggestCurrencies.length == 0 || C.globalCounter % 1000 == 0) {\n fetch('https://api.coinmarketcap.com/v1/ticker/').then(function (response) {\n return response.json();\n }).then(function (json) {\n console.log(\"Coin Market Cap\");\n cacheBiggestCurrencies = json;\n resolve(json);\n }).catch(function(e){\n console.log(\"Coin Market Cap Error\"); \n logIt(e)\n resolve(cacheBiggestCurrencies);\n });\n } else {\n resolve(cacheBiggestCurrencies);\n }\n });\n return p;\n}",
"async function getHighestBlockNumber() {\n let highestBlockNumber = await models.NotificationAction.max('blocknumber')\n if (!highestBlockNumber) {\n highestBlockNumber = startBlock\n }\n const date = new Date()\n logger.info(`Highest block: ${highestBlockNumber} - ${date}`)\n return highestBlockNumber\n}",
"findBiggestUtxo(utxos) {\n let largestAmount = 0\n let largestIndex = 0\n\n for (var i = 0; i < utxos.length; i++) {\n const thisUtxo = utxos[i]\n\n if (thisUtxo.value > largestAmount) {\n largestAmount = thisUtxo.value\n largestIndex = i\n }\n }\n\n // console.log(`Largest UTXO: ${JSON.stringify(utxos[largestIndex], null, 2)}`)\n\n return utxos[largestIndex]\n }",
"async getLargestAccounts(config) {\n const arg = { ...config,\n commitment: config && config.commitment || this.commitment\n };\n const args = arg.filter || arg.commitment ? [arg] : [];\n const unsafeRes = await this._rpcRequest('getLargestAccounts', args);\n const res = create(unsafeRes, GetLargestAccountsRpcResult);\n\n if ('error' in res) {\n throw new Error('failed to get largest accounts: ' + res.error.message);\n }\n\n return res.result;\n }",
"fetchMaxSupply() {\n return 388539008;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a new SP.FieldBoolean to the collection | addBoolean(title, properties) {
const props = {
FieldTypeKind: 8,
};
return this.add(title, "SP.Field", extend(props, properties));
} | [
"static Boolean(name, def = false) { return ModelBase.Field(name, Boolean, def); }",
"function setBool(key, value) {\r var existing = isBoolSet(key);\r try {\r store(key, (value != null && Boolean(value)));\r } \r catch (e) {\r \r }\r return existing;\r}",
"function AntObject_FieldInput_Bool(fieldCls, con, options)\r\n{\r\n\tvar inp = alib.dom.createElement(\"input\");\r\n\tinp.type = \"checkbox\";\r\n\tinp.checked = (fieldCls.value) ? true : false;\r\n\tcon.inptType = \"checkbox\";\r\n\tcon.inpRef = fieldCls;\r\n\tcon.appendChild(inp);\r\n\r\n\t// Register change event\r\n\tinp.clsRef = this;\r\n\tinp.onclick = function() { \r\n\t\talib.events.triggerEvent(this.clsRef, \"change\", {value:this.checked, valueName:null});\r\n\t}\r\n}",
"function isBooleanSearchableField(searchableField){\n return (!_.isUndefined(searchableField.type) && searchableField.type.indexOf(\"Boolean\") !== -1);\n }",
"function BooleanValue() {}",
"SetBool() {}",
"function setBoolean(key, value) {\n var items = _componentToDict(_readComponent());\n items[key] = value.toString();\n _writeComponent(_dictToComponent(items));\n }",
"function BooleanType() {\n}",
"function as_bool(v) {\r\n return setType(v, 'bool');\r\n}",
"writeBoolean(value) {\n this.validateBuffer(ByteArrayBase.SIZE_OF_BOOLEAN);\n this.data.setUint8(this.position++, value ? 1 : 0);\n }",
"function addBoolAttr(name, question) {\n\t\tvar newAtt = {};\n\t newAtt.type = 1;\n\t var identer = {};\n\t identer.name = name;\n\t identer.question = question;\n\t newAtt.identifier = identer;\n\t\tif (name != \"\") {\n\t\t\texpertJSON.attributes.push(newAtt);\t\n\t\t}\n\t\t\n\t return true;\n\t}",
"writeBoolean(value){return this.writeByte(value?1:0),this}",
"function PackedBool() {\n }",
"function Boolean() {}",
"get boolean() {\n this.eval(\n this.is('boolean', this.firstOperand),\n 'Variable is not a type \\'boolean\\'', \n 'Variable is a type \\'boolean\\''\n );\n return this;\n }",
"static fromBoolean(value) {\n return new DynamoAttributeValue({ BOOL: value });\n }",
"static create(model) {\n return internal.instancehelpers.createElement(model, BooleanAttributeType);\n }",
"function db_bool(object, offset, def) {\n\t\t\tthis.key = object.key + \":flags\";\n\t\t\tthis.offset = offset;\n\t\t\tthis.def = typeof def !== 'undefined' ? def : false;\n\t\t}",
"function boolean_boolean(rule,value,callback,source,options){var errors=[];var validate=rule.required||!rule.required&&source.hasOwnProperty(rule.field);if(validate){if(isEmptyValue(value)&&!rule.required){return callback();}es_rule.required(rule,value,source,errors,options);if(value!==undefined){es_rule.type(rule,value,source,errors,options);}}callback(errors);}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
> Set Back to Default > Todo vuelve al valor inicial (Borrar la barra de input, normalmente queda lo ultimo escrito.) | function setBackToDefault() {
// console.log('set Back to Default'); // Para ver en la consola que cuando add un item , se imprime algo.
grocery.value = ''; // Input
editFlag = false; // Para el IF
editID = ''; //
submitBtn.textContent = 'submit'; // Cada vez que suceda un evento, vuelve a decir Submit
} | [
"function setBackToDefault(){\n\tconsole.log('set back to default')\n\tgrocery.value = ''\n\teditFlag = false\n\teditId = ''\n\tsubmitBtn.textContent = 'submit'\n}",
"function restore(ele) {\r\n if (ele.value == '') {\r\n ele.value = ele.defaultValue;\r\n }\r\n}",
"function undoClearInput() {\n $toDoInput.attr(\"placeholder\", \"New To Do\");\n }",
"function restoreInput(textField){\n\tif (textField.value == \"\" || isEmpty(textField.value)){\n\t\ttextField.value = textField.defaultValue;\n\t}\n}",
"restoreValue() {\n this.textInputNode.value = this.originalValue;\n }",
"function setBackToDefault() {\n $(\"input\").val(\"\");\n editFlag = false;\n expenseSubmit.html(\"Add Expense\");\n $(\".icon2\").css(\"visibility\", \"visible\");\n}",
"function limpiarBusqueda() {\n $(\"#buscador\").val('')\n agitar(0)\n mostrarBotonLimpiar()\n}",
"reset() {\n this.set(\"value\", this.initial_value);\n }",
"function backToDefault() {\n previousButton && setPreviousButton(false);\n nextButton && setNextButton(false);\n recipesPerPage.length !== 0 && setRecipesPerPage([]);\n currentPage !== 1 && setCurrentPage(1);\n }",
"function makingInputEmpty(input){\n input.value = \"\";\n}",
"function clearCurrent()\n {\n current_input = \"0\";\n displayCurrentInput();\n }",
"function resetUserInputField(){\n userInput.value='';\n userInput.setAttribute(\"placeholder\", \"Enter your guess..\")\n userInput.focus();\n }",
"function restoreInput(e, hint) {\r\n var thisInput = sourceElement(e);\r\n if (thisInput.value == \"\") {\r\n thisInput.value = hint;\r\n thisInput.className = \"emptyfield\";\r\n }\r\n}",
"function resetInput(cm, typing) {\n var minimal, selected, doc = cm.doc;\n if (cm.somethingSelected()) {\n cm.display.prevInput = \"\";\n var range = doc.sel.primary();\n minimal = hasCopyEvent &&\n (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);\n var content = minimal ? \"-\" : selected || cm.getSelection();\n cm.display.input.value = content;\n if (cm.state.focused) selectInput(cm.display.input);\n if (ie && !ie_upto8) cm.display.inputHasSelection = content;\n } else if (!typing) {\n cm.display.prevInput = cm.display.input.value = \"\";\n if (ie && !ie_upto8) cm.display.inputHasSelection = null;\n }\n cm.display.inaccurateSelection = minimal;\n }",
"function defaultVal(val, input, hideOnClick, ignore) {\r\n input.val(val);\r\n if (hideOnClick) {\r\n input.focus(function () {\r\n if (input.val() === val)\r\n input.val('').change();\r\n });\r\n }\r\n input.blur(function () {\r\n if (input.val() === '') {\r\n input.val(val).change();\r\n searchData('', '.artButton', ignore);\r\n }\r\n });\r\n }",
"function clearFunction() {\n if (input.value == null) {\n } else {\n var inputText = input.value;\n input.value = inputText.slice(0, -1);\n }\n}",
"function resetInput(cm, typing) {\n var minimal, selected, doc = cm.doc;\n if (cm.somethingSelected()) {\n cm.display.prevInput = \"\";\n var range = doc.sel.primary();\n minimal = hasCopyEvent &&\n (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);\n var content = minimal ? \"-\" : selected || cm.getSelection();\n cm.display.input.value = content;\n if (cm.state.focused) selectInput(cm.display.input);\n if (ie && ie_version >= 9) cm.display.inputHasSelection = content;\n } else if (!typing) {\n cm.display.prevInput = cm.display.input.value = \"\";\n if (ie && ie_version >= 9) cm.display.inputHasSelection = null;\n }\n cm.display.inaccurateSelection = minimal;\n }",
"function restaurarInputValue(elemento,fraseDefecto){\n if(elemento.value==\"\"){\n elemento.value=fraseDefecto;\n }\n}",
"restoreValue() {\n if (this.hasSetValue) {\n this.setValue(this.dataValue, {\n noUpdateEvent: true\n });\n }\n else {\n this.setDefaultValue();\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chapter 101 RopeGroup Player threatens amelia to try stopping her. | function C101_KinbakuClub_RopeGroup_TryStopMe() {
if (ActorGetValue(ActorSubmission) <= 0) {
C101_KinbakuClub_RopeGroup_CurrentStage = 125;
OverridenIntroText = GetText("StoppingYou");
} else LeaveIcon = "Leave";
} | [
"function C009_Library_Yuki_StopPleasure() {\n\t\n\t// Release the player\n\tC009_Library_Yuki_NoPleasure();\n\tActorSetPose(\"\");\n\tCommon_PlayerPose = \"\";\n\n\t// Yuki can fall asleep if she was drugged\n\tif (C009_Library_Yuki_SleepingPillFromPleasure) {\n\t\tOverridenIntroText = GetText(\"DizzySleep\");\n\t\tC009_Library_Yuki_CurrentStage = 400;\n\t\tActorSetPose(\"Sleepy\");\n\t}\n\t\n}",
"function C010_Revenge_AmandaSarah_StopMasturbating() {\n\tCommon_PlayerPose = \"Locker\";\n}",
"function playerInvulnerabilityStop() {\n playerInvulnerability = false; \n player.alpha = 1; \n}",
"stop() {\n throw Error(`The player it's already stopped`);\n }",
"function stopBet() {\n gameStop = true;\n}",
"function stopRacePlayer(){\n for(player of allPlayers){\n if (player.idA == this.value){\n this.textContent = startTimer.value\n this.disabled = true\n this.parentElement.nextSibling.disabled = true\n this.parentElement.nextSibling.childNodes[0].textContent = \"Course finie\"\n\n }\n }\n }",
"function stopSpel(spelerGewonnen) {\n\t\t\t\tspelActief = false; \n\t\t\t\tdocument.getElementById('game_info').innerHTML = \"De winnaar is: Speler \" + spelerGewonnen; \n\t\t\t}",
"function stop_answered(){}",
"function stopLifelinePassiveSound(){\r\n\ttry{\r\n\t\twindow.GameVariables.LifelinePassiveSound.pause();\r\n\t}\r\n\tcatch(e){\r\n\t\tconsole.log(e);\r\n\t}\r\n}",
"function EventEmergencyStop() onlyOwner() {\n halted = true;\n }",
"stopSpectate(player) {}",
"function stopPlayers() {\n\tgroupPlayer.forEach(\n\t\tfunction(player) {\n\t\t\tplayer.body.velocity.x = 0;\n\t\t\tplayer.body.velocity.y = 0;\n\t\t\tplayer.body.gravity.y = 0;\n\t\t}\n\t)\n}",
"function stop_game_over(Players_ref){\n Players_ref.off();\n}",
"function stopLongPassiveSound(){\r\n\ttry{\r\n\t\twindow.GameVariables.LongPassiveSound.pause();\r\n\t}\r\n\tcatch(e){\r\n\t\tconsole.log(e);\r\n\t}\r\n}",
"function playerLose() {\n win.cancelAnimationFrame(idFrame);\n modal.classList.toggle('is-hidden');\n title.innerHTML = `No More Lives`;\n content.innerHTML = `Don't give up. Try Again`;\n }",
"pauseTeamXP() {\n for (let battler of this.battle.battlers[CharacterKind.Hero]) {\n battler.player.pauseExperience();\n }\n }",
"function stopArtyom () {\n artyom.fatality();\n}",
"turnEnd(){\n // pokemon.applyStatus()\n this.activeMon.ticStatus();\n let healActive = this.activeOpp.secTicStatus();\n this.activeOpp.ticStatus();\n let healOpp = this.activeMon.secTicStatus();\n\n if (healActive > 0){\n this.activeMon.heal(healACtive)\n }\n if (healOpp > 0){\n this.activeOpp.heal(healOpp)\n }\n\n this.activeOpp.endProtect()\n this.activeMon.endProtect()\n \n }",
"function C012_AfterClass_Jennifer_TestPunish() {\n\n\t// The more love, the less chances the player will be punished\n\tif (EventRandomChance(\"Love\")) {\n\t\tC012_AfterClass_Jennifer_AllowLeave();\n\t} else {\n\t\tActorSetPose(\"Angry\");\n\t\tOverridenIntroText = \"\";\n\t\tC012_AfterClass_Jennifer_CurrentStage = 3900;\n\t}\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map function with 2 parameters: array.names and callbackfunction | function myMap(names, cb) {
// New empty array to store the output
var results = [];
// Loops through the array
for (var i = 0; i < names.length; i++) {
// New variable is defined as the callback function taking the item from the loop
var result = cb(names[i]);
// Push the item to the empty array
results.push(result);
}
// Return the results array
return results;
} | [
"map(callback, ...names) {\n const result = [];\n this.each(\n (path, index, value) => {\n result[index] = callback(path, index, value);\n },\n ...names,\n );\n return result;\n }",
"map(callback, ...names) {\n const result = [];\n this.each((path9, index, value) => {\n result[index] = callback(path9, index, value);\n }, ...names);\n return result;\n }",
"function myMap(array, callbackFnc){\n //WRITE CODE HERE\n // return array.map(callbackFnc); // this solution is off limits :)\n}",
"function map(array,callback){\n const results = [];\n for (let index=0; index<array.length;index++){\n results.push(callback(array[index],index));\n }\n return results; //after the transformation\n }",
"function map(array, callback) {\n var newArr = [];\n for (var i = 0; i < array.length; i++) {\n newArr.push(callback(array[i], i, array));\n }\n return newArr;\n}",
"customMap(callBack) {\n mappedArr = new Array(this.arr.length);\n for (let i = 0; i < this.arr.length; ++i) {\n mappedArr[i] = callBack(this.arr[i], i, this.arr);\n }\n return mappedArr;\n }",
"function myMap(array, callback) {\n return callback(array);\n}",
"function myMap(array, cb) {\n var newArray = []\n array.forEach(function(ele, idx, arr){\n newArray.push(cb(ele,idx));\n });\n return newArray;\n}",
"function mapArray(array, callBack) {\n let result = [];\n for (let i = 0; i < array.length; i++) {\n result.push(callBack(array[i]));\n }\n\n return \"New value: \" + result;\n}",
"mapArray(callbacks){\n\n // iterating over tiles\n this.map((tile,x,y) => {\n for(var callback of callbacks)\n callback(tile,x,y);\n })\n\n }",
"function myMap(fn, array) {\n results = [];\n for (const iterator of array) {\n results.push(fn(iterator));\n }\n return results;\n}",
"function map(list, fcn) {\n\n}",
"function map(arr, func) {\n var newArr = [];\n arr.forEach(function (curr) {\n newArr.push(func(curr));\n })\n return newArr;\n}",
"function batmap(arr,mapFunc,otherArrsArray) {\n let narr = []\n otherArrsArray = transpose(otherArrsArray)\n for(var i=0;i<arr.length;i++){\n let value = arr[i]\n let func = mapFunc\n let oargs = otherArrsArray[i]\n let ele = func(value,...oargs)\n narr.push(ele)\n }\n return(narr)\n}",
"map(arr, fn) {\n //We have to establish result outside of the for loop so that we can return it outside of the for loop\n const result = [];\n for (let i=0; i<arr.length; i++) {\n result.push(fn(arr[i], i));\n }\n return result;\n }",
"function mapForEach(arr, fn) {\n\n var newArr = [];\n for(var i =0; i< arr1.length ; i++) {\n newArr.push(\n fn(arr1[i])\n );\n };\n\n return newArr\n}",
"function myMap(func, arr) {\n let newArr = [];\n for (let i = 0; i < arr.length; i++) {\n newArr[i] = func(arr[i]);\n }\n return newArr;\n}",
"static async asyncMap(array, callback) {\n for (let i in array) array[i] = await callback(array[i])\n return array\n }",
"static map(a, fn) {\n for (let i = 0, len = a.length; i < len; i++) {\n a[i] = fn(a[i], i, a);\n }\n return a;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FUNCTION register = checks if the user is already registered if registered, returns details of individual and prompts individual for next action if not register, prompts user to input room number | function register(id) {
var user = userExists(id);
var text = 'failed';
if (Object.getOwnPropertyNames(user).length === 0) {
text =
"Welcome to Eusoff Gym Bot. You do not exist in our system yet. Let's change that." +
'\n\n' +
'<b> What is your room number? </b>';
sendText(id, text);
text =
'Please input in the format: <b> A101 </b>' +
'\n' +
'Ensure that you key in the correct room number in your first try.' +
'\n\n' +
'If not, there will be no way to reset the system unless you contact @qiiwenn, which will take 3 workings days. ' +
'\n' +
'If you are caught with inputting the wrong room without notifying @qiiwenn, you will be barred from booking the gym.' +
'\n\n' +
'Let us all do our parts to fight COVID-19 together.';
} else {
text =
'Welcome back ' +
user.firstName +
'!!' +
'\n\n' +
'Your room number is ' +
user.room +
' and you are in Zone ' +
user.zone +
'.\n\n' +
'Would you like to make a booking? /book' +
'\n' +
'Would you like to delete your booking? /delete' +
'\n' +
'Would you like to check the available timeslots? /view';
}
sendText(id, text);
} | [
"function register(id) {\n var user = userExists(id);\n var text = 'failed';\n\n if (Object.getOwnPropertyNames(user).length === 0) {\n text =\n \"Welcome to Eusoff Gym Bot. You do not exist in our system yet. Let's change that.\" +\n '\\n\\n' +\n '<b> What is your room number? </b>';\n sendText(id, text);\n text =\n 'Please input in the format: <b> A101 </b>' +\n '\\n' +\n 'Ensure that you key in the correct room number in your first try.' +\n '\\n\\n' +\n 'If not, there will be no way to reset the system unless you contact @qiiwenn, which will take 3 workings days. ' +\n '\\n' +\n 'If you are caught with inputting the wrong room without notifying @qiiwenn, you will be barred from booking the gym.' +\n '\\n\\n' +\n 'Let us all do our parts to fight COVID-19 together.';\n } else {\n text =\n 'Welcome back ' +\n user.firstName +\n '!!' +\n '\\n\\n' +\n 'Your room number is ' +\n user.room +\n ' and you are in Zone ' +\n user.zone +\n '.\\n\\n' +\n 'Would you like to make a booking? /book' +\n '\\n' +\n 'Would you like to delete your booking? /delete' +\n '\\n' +\n 'Would you like to check the available timeslots? /view';\n }\n sendText(id, text);\n}",
"function register() {\n\t\t\tif (isNormalInteger(vm.userIdField) && vm.typeField !== null) {\n\t\t\t\tif (dbService.checkId(vm.userIdField, function(exists) {\n\t\t\t\t\tif (!exists) {\n\t\t\t\t\t\tvm.userId = vm.userIdField;\n\t\t\t\t\t\tvm.type = vm.typeField;\n\t\t\t\t\t\tcommon.userId = vm.userIdField;\n\t\t\t\t\t\tcommon.type = vm.typeField;\n\n\t\t\t\t\t\tvm.message = '';\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvm.message = 'Id already exists';\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t} else {\n\t\t\t\tvm.message = 'Inputs not valid';\n\t\t\t}\n\t\t}",
"function registration (){\n credentials.id = prompt(\"Create a User Id.\")\n while (credentials.id.length < 9 || credentials.id.includes(\"$\")) {\n credentials.id = prompt(\"This User Name is less than 9 characters or contains an unapproved symbol ($).\")\n }\n //this while loop will screen the credentials.id for characters\n credentials.pass = prompt(\"Create a password.\")\n while (credentials.pass.length < 9) {\n credentials.pass = prompt(\"This password contains less than 9 characters.\")\n }\n}",
"async register (user, race) {\n try {\n if (!race.isOpen) { throw Err.notOpen }\n \n user.register(race)\n race.addRunner(user)\n\n return Say.success(Say.registered)\n } catch (error) { return Err.make(error) }\n }",
"function RegisterUser() {\n if (ValidateInput()) {\n if (CheckExisting() === false) {\n CreateUser();\n }\n }\n}",
"function exercise1(registerUser) {}",
"function askForRegistration() {\n if (!addressChosen) {\n alert(\"Please unlock your Ethereum address\");\n return;\n }\n\n if (state != 1) {\n alert(\"You can only ask for registration during the SIGNUP Phase \");\n return;\n }\n \n\t//Generate keys of the new voter\n\tvar key = ec.genKeyPair();\n\tvar x = new BigNumber(key.getPrivate().toString());\n\t\n\tvar _x = key.getPublic().x.toString();\n\tvar _y = key.getPublic().y.toString();\n\t\n\tvar personalPublicKey = [new BigNumber(_x), new BigNumber(_y)];\n\t\n\t//Get the inscription code\n\tvar inscriptionCode = document.getElementById('inscriptionCodeInput').value;\n \n var res = WaveVoteAddr.askForRegistration.call(personalPublicKey, inscriptionCode, {\n from: web3.eth.accounts[accounts_index]\n });\n\n // Submit voting key to the network\n if (res[0]) {\n \ttry {\n \t\tweb3.personal.unlockAccount(addr, password);\n \t\t\n\t WaveVoteAddr.askForRegistration.sendTransaction(personalPublicKey, inscriptionCode, {\n\t from: web3.eth.accounts[accounts_index],\n\t gas: 4200000,\n\t value: 0\n\t });\n\t \n\t var address = web3.eth.accounts[accounts_index];\n\t db.find({account: address}, function(err, docs) {\n \tif (!docs.length) {\n \t\tvar accountKey = {account: address, personalPrivateKey: key.getPrivate().toString()};\n \t\tdb.insert(accountKey);\n \t} else {\n \t\tdb.update({account: addr}, {account: address, personalPrivateKey: key.getPrivate().toString()}, {});\n \t}\n });\n\t\n\t //TODO: DUPLICATED CODE FROM CURRENTSTATE. Needs its own function.\n\t document.getElementById('inscriptionCode').setAttribute(\"hidden\",true);\n\t document.getElementById('registerbutton').setAttribute(\"hidden\",true);\n\t document.getElementById(\"registrationprogress\").removeAttribute(\"hidden\");\n\t document.getElementById(\"submitregistration\").removeAttribute(\"hidden\");\n \t} catch (e) {\n \t\tconsole.log(e);\n \t\talert(\"The transaction of your registration's demand failed...\");\n \t}\n\n } else {\n alert(res[1]);\n }\n}",
"function createRoom(){\r\n\tif (document.getElementById('roomName').value.replace(/\\s/g, '') == '') {\r\n\t\twindow.alert(\"You must specify the name of room\");\r\n\t\treturn;\r\n\t}\r\n\troomId = document.getElementById('roomName').value.replace(/\\s/g, '');\r\n\t//a room name must be saved with the sessionStorage so\r\n\t//we know that we are creator of the room\r\n\t\r\n\tif(inArray(roomId, rooms)){\r\n\t \r\n return;\r\n\t }else {\r\n\t sessionStorage.setItem(\"name\", roomId);\r\n\t var message = {\r\n\t\tid : 'registerRoom',\r\n\t\tname : roomId\r\n\t};\r\n\t\r\n\t sendMessage(message);\r\n\t }\r\n\t\r\n\t\r\n}",
"function requestCreateRoom() {\r\n if (inputRoomName.value()) {\r\n socket.emit(\"createRoomRequest\", inputRoomName.value(), (response) => {\r\n if(!response){\r\n errorNameUsed(inputRoomName.value());\r\n } else{\r\n createUserRoom(inputRoomName.value());\r\n }\r\n });\r\n currentRoom = inputRoomName.value();\r\n }\r\n}",
"function register() {\r\n\tvar val = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\r\n\temail = document.getElementById('registerEmail').value;\r\n\tpassword1 = document.getElementById('registerPassword').value;\r\n\tpassword2 = document.getElementById('registerPasswordAgain').value;\r\n\t\r\n\tif(email == '' || password1 == '' || password2 == '') {\r\n\t\tindexModal('Please fill out the form boxes');\r\n\t} else if (val.test(String(email).toLowerCase()) == false) {\r\n\t\tindexModal('Invalid email');\r\n\t} else if(email in loginCredentials) {\r\n\t\tindexModal('Email already taken');\r\n\t} else if(password1 == password2) {\r\n\t\tloginCredentials[email] = password1;\r\n\t\tindexModal('Account created');\r\n\t} else {\r\n\t\tindexModal('Passwords do not match!');\r\n\t}\t\r\n}",
"function registerUser(socket, name, start) {\n\n var role = null;\n logger (\"registering user \" + name + \" connid = \" + connectionID(socket));\n\n if (findMasterRecord() == null) {\n role = 'master';\n logger (\"REGISTERED MASTER : \" + connectionID(socket));\n } else {\n role = 'slave';\n logger (\"REGISTERED SLAVE : \" + connectionID(socket));\n }\n\n CONNECTS[connectionID(socket)].role = role;\n CONNECTS[connectionID(socket)].userID = name;\n\n //\n // TODO: need to validate that we receive messages from the master within \n // a short period of time, otherwise we demote the master (if others are avail)\n //\n if (start) {\n socket.emit(\"startGame\", {role: role, id: connectionID(socket)});\n } \n logger(CONNECTS);\n\n}",
"function register(username, new_id) {\n return web3.eth.personal.newAccount(default_password).then(address => {\n console.log(\">> Account created: \" + address);\n return address;\n }).then(address => ShiftCoin.methods.register(address, username, new_id).send({ from: owner_account, gas: 6721974 })\n .on(\"receipt\", receipt => {\n if (!receipt.status) {\n console.log(\">> Failed to register user. - transaction failed\");\n return Promise.reject(\"registration failed.\");\n }\n }).on(\"error\", err => {\n console.log(\">> Failed to register user. - transaction error\");\n console.log(err.message);\n })\n );\n}",
"function registration(accountInfo)\n{\n\tif (!accountInfo.register)\n\t{\n\t\tconsole.log(\"Register not found\");\n\t\treturn;\n\t}\n\t/*check info validation */\n\tif(validate(accountInfo) == \"fill\" || validate(accountInfo) == \"email\")\n\t{\n\t\tconsole.log(\"Validation failed:\");\n\t\treturn validate(accountInfo); //return str\n\t}\n\n\t/*check if the same email exist in database*/\n\tvar data = fs.readFileSync(\"database.txt\"); //read data from database\n\tdata = data.toString().split(\";\"); //split into an array of json obj string\n\tfor(var i = 0; i < data.length; i++)\n\t{\n\t\tvar dbaseAccount = JSON.parse(data[i]); //parse the json object\n\t\tif(dbaseAccount.email == accountInfo.email)\n\t\t{\n\t\t\tconsole.log(\"Account already existed\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\treturn accountInfo; //return account object\n}",
"function register(){\n\t\tif(websocket){\n\t\t\twebsocket.send(\"game.inbound.GameRegistrationMessage\",{\n\t\t\t\t\t\ttransactionId:new Date().getTime(),\n\t\t\t\t\t\tuserSessionId:SESSION_ID,\n\t\t\t\t\t\tuserType:\"USER_TYPE_PLAYER\"\n\t\t\t\t\t});\n\t\t}\n\t}",
"function registerNewUser() {\n USER_NAME = buildNewName();\n USER_PWD = buildNewPassword();\n register(USER_NAME, USER_PWD);\n}",
"function registerUser() {\n if(!firstName || !lastName || !username || !password || !email || !ssn) { //check if all required fields are filled\n setErrormsg(\"Please fill in all required fields\")\n return\n }\n\n let data = ({\n role: 2,\n firstName: firstName,\n lastName: lastName,\n username: username,\n password: password,\n email: email,\n ssn: ssn,\n update: updateExisting\n })\n\n fetch('/user/register', {\n method: 'POST', \n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(data)\n }).then(response => {\n console.log(response)\n if(response.status === 201) { // user is registered \n window.location = \"/\" \n }\n else if(response.status === 200) { // ok request\n response.json().then(result => setErrormsg(result.statusMessage))\n } \n else if(response.status === 400) { // bad request\n setErrormsg(response.statusText)\n }\n else if(response.status === 500) { // internal error\n setErrormsg(response.statusText)\n } \n })\n }",
"function register(){\n\t\telement(by.id('accname')).sendKeys('testusername')\n\t\telement(by.id('emailaddr')).sendKeys('test@rice.edu')\n\t\telement(by.id('phonenum')).sendKeys('1234567890')\n\t\telement(by.id('birthday')).sendKeys('05282011')\n\t\telement(by.id('zip')).sendKeys('12345')\n\t\telement(by.id('pwd')).sendKeys('abcde')\n\t\telement(by.id('pwdConfirm')).sendKeys('abcde')\n\t\telement(by.id('registerBtn')).click()\n\t}",
"function register() {\n vm.working = true;\n var promise = accountService.register(vm.registerRequest);\n promise.then(registerSucceeded, registerFailed);\n }",
"function registerUser() {\n\n\tvar registerData = {\n\t devicetype : userName,\n\t username : userName\n\t};\n\tvar options = {\n\t body : JSON.stringify(registerData),\n\t timeout: 10000,\n\t url : url\n\t};\n\t\n\thttp.post(options, function(response) {\n\t var rsp = JSON.parse(response.body);\n\t //console.log(\"Response \" + JSON.stringify(response));\n\t if (isNonEmptyArray(rsp) && rsp[0].error) {\n\t \n\t var description = rsp[0].error.description;\n\n\t if (description.match(\"link button not pressed\")) {\n\t //repeat registration attempt unless registerTimeout has been reached.\n\t console.log(\"Please push the link button on the Hue bridge.\");\n\t registerAttempts++;\n\t if ((registerAttempts * registerInterval) > registerTimeout) {\n\t throw \"Failed to create user after \" + registerTimeout/1000 +\n\t \"s.\";\n\t }\n\t handleRegisterUser = setTimeout(registerUser, registerInterval);\n\t return;\n\t } else {\n\t throw description;\n\t }\n\t } else if ((isNonEmptyArray(rsp) && rsp[0].success)) {\n\t if (handleRegisterUser !== null) {\n\t clearTimeout(handleRegisterUser);\n\t }\n\t\t// contact the bridge and find the available lights\n\t\tcontactBridge();\n\t } else {\n\t //console.log(\"Response \" + JSON.stringify(response));\n\t console.log(JSON.stringify(JSON.parse(response.body)[0].success));\n\t throw \"Unknown error registering new user\";\n\t }\n\t});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
extract cell reference formula arguments | function getFormulaArgs(formula) {
var args = formula.match(/=\w+\((.*)\)/i)[1].split(getDelimiter());
for (var i = 0; i < args.length; i++) {
var arg = args[i].trim().split('!')
arg[0] = arg[0].replace(/'/g, '')
args[i] = arg.join('!');
}
return args;
} | [
"function returnFormulaArgs(formula) {\n var args = formula.match(/=\\w+\\((.*)\\)/i)[1].split(getDelimiter());\n for (i = 0; i < args.length; i++) {\n var arg = args[i].trim().split('!')\n arg[0] = arg[0].replace(/'/g, '')\n args[i] = arg.join('!');\n }\n return args;\n}",
"function extractFormulaParams(module, formula) {\n const base_regex = \"=.*BINANCE[R]?\\\\s*\\\\(\\\\s*\\\"\"+module.tag()+\"\\\"\\\\s*,\\\\s*\";\n let [range_or_cell, options] = [\"\", \"\"];\n\n // 3 params formula with string 2nd param\n let regex_formula = base_regex+\"\\\"(.*)\\\"\\\\s*,\\\\s*\\\"(.*)\\\"\";\n let extracted = new RegExp(regex_formula, \"ig\").exec(formula);\n if (extracted && extracted[1] && extracted[2]) {\n range_or_cell = extracted[1];\n options = extracted[2];\n } else {\n // 3 params formula with NOT-string 2nd param\n regex_formula = base_regex+\"(.*)\\\\s*,\\\\s*\\\"(.*)\\\"\";\n extracted = new RegExp(regex_formula, \"ig\").exec(formula);\n if (extracted && extracted[1] && extracted[2]) {\n range_or_cell = extracted[1];\n options = extracted[2];\n } else {\n // 2 params formula\n regex_formula = base_regex+\"(.*)\\\\s*\\\\)\";\n extracted = new RegExp(regex_formula, \"ig\").exec(formula);\n if (extracted && extracted[1]) {\n range_or_cell = extracted[1];\n }\n }\n }\n\n if (DEBUG) {\n Logger.log(\"FORMULA: \"+JSON.stringify(formula));\n if (extracted) {\n extracted.map(function(val) {\n Logger.log(\"REGEXP VAL: \"+val);\n });\n }\n Logger.log(\"RANGE OR CELL: \"+JSON.stringify(range_or_cell));\n Logger.log(\"OPTIONS: \"+JSON.stringify(options));\n }\n\n return [range_or_cell, parseOptions(options)];\n }",
"function getReferences(formula) {\r\n var match = formula.match(FORMULA_REFERENCES);\r\n return match\r\n ? match.map(function (substr) {\r\n var _a = __read(hotFormulaParser.extractLabel(substr), 2), row = _a[0], column = _a[1];\r\n return { row: row.index, column: column.index };\r\n })\r\n : [];\r\n}",
"function parse_XLSBParsedFormula(data,length,opts){var cce=data.read_shift(4);var rgce=parse_Rgce(data,cce,opts);var cb=data.read_shift(4);var rgcb=cb>0?parse_RgbExtra(data,cb,rgce,opts):null;return[rgce,rgcb];}",
"evaluateFormula(formula, cellRef) {\n const assocData = { cellRef };\n return withAssociatedParserData(assocData, this.parser, () => {\n const formulaValue = this.parser.parse(formula);\n if ( formulaValue.error ) {\n // TODO\n return formulaValue.error;\n }\n\n return formulaValue.result;\n });\n }",
"function parseFormula(formula, rangeStart, rangeEnd, hColumn, csheet){\r\n\r\n\r\n // For ABS ( SUM () ) \r\n var formulaName = formula.split(\"(\");\r\n var additionalformula = formula.split(\")\");\r\n\r\n var formulaMinusEqual = formulaName[0].split(\"=\"); // Will contain ABS \r\n var innerFormula = formulaName[1]; // Will contain SUM \r\n\r\n var innerAdditionalFormula = additionalformula[1];\r\n var outerAdditionalFormula = additionalformula[2];\r\n\r\n var chunkRange1 = csheet.getRange(rangeStart, hColumn).offset(0,1);\r\n var chunkRange2 = csheet.getRange(rangeEnd, hColumn).offset(0,1);\r\n\r\n var chunkRange01 = chunkRange1.getA1Notation();\r\n var chunkRange02 = chunkRange2.getA1Notation();\r\n\r\n\r\n var formula;\r\n if(formula.indexOf(\"(\") != formula.lastIndexOf(\"(\"))\r\n {\r\n formula = innerFormula + \"(\" + chunkRange01 + \":\" + chunkRange02 + \")\" + innerAdditionalFormula;\r\n formula = formulaMinusEqual[1] + \"(\" + formula + \")\" + outerAdditionalFormula;\r\n }\r\n else\r\n {\r\n formula = formulaMinusEqual[1] + \"(\" + chunkRange01 + \":\" + chunkRange02 + \")\" + innerAdditionalFormula;\r\n }\r\n\r\n\r\n return formula;\r\n}",
"function refSheetCell(a, b, c, d) {\n\t if (a.type == \"sym\" &&\n\t b.type == \"punc\" && b.value == \"!\" &&\n\t (c.type == \"sym\" || c.type == \"rc\" || (c.type == \"num\" && c.value == c.value|0)) &&\n\t !(d.type == \"punc\" && d.value == \"(\" && !c.space))\n\t {\n\t skip(3);\n\t var x = toCell(c);\n\t if (!x || !isFinite(x.row)) {\n\t x = new NameRef(c.value);\n\t }\n\t return addPos(x.setSheet(a.value, true), a, c);\n\t }\n\t }",
"function parse_XLSBParsedFormula(data, length, opts) {\n\t\t\tvar end = data.l + length;\n\t\t\tvar cce = data.read_shift(4);\n\t\t\tvar rgce = parse_Rgce(data, cce, opts);\n\t\t\tvar cb = data.read_shift(4);\n\t\t\tvar rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;\n\t\t\treturn [rgce, rgcb];\n\t\t}",
"function parse_XLSBParsedFormula(data, length, opts) {\n\t\tvar end = data.l + length;\n\t\tvar cce = data.read_shift(4);\n\t\tvar rgce = parse_Rgce(data, cce, opts);\n\t\tvar cb = data.read_shift(4);\n\t\tvar rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;\n\t\treturn [rgce, rgcb];\n\t}",
"enterCell_reference_options(ctx) {\n\t}",
"function parse_CellParsedFormula(data, length) {\n\tvar cce = data.read_shift(4);\n\treturn parsenoop(data, length-4);\n}",
"function parseCellRef(ref) {\n var rowDigitOff = 0;\n for (var i = 0, size = ref.length; i < size; i++) {\n var ch = ref.charCodeAt(i);\n if (ch <= charCode9 && ch >= charCode0) {\n rowDigitOff = i;\n break;\n }\n }\n var columnName = ref.substr(0, rowDigitOff);\n var col = columnNameToIndex(columnName);\n var row = parseInt(ref.substr(rowDigitOff));\n return { col: col, row: row };\n }",
"function parse_XLSBParsedFormula(data, length, opts) {\n var cce = data.read_shift(4);\n var rgce = parse_Rgce(data, cce, opts);\n var cb = data.read_shift(4);\n var rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;\n return [rgce, rgcb];\n }",
"function parse_XLSBParsedFormula(data, length, opts) {\n\tvar end = data.l + length;\n\tvar cce = data.read_shift(4);\n\tvar rgce = parse_Rgce(data, cce, opts);\n\tvar cb = data.read_shift(4);\n\tvar rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;\n\treturn [rgce, rgcb];\n}",
"function parse_XLSBParsedFormula(data, length, opts) {\n var cce = data.read_shift(4);\n var rgce = parse_Rgce(data, cce, opts);\n var cb = data.read_shift(4);\n var rgcb = cb > 0 ? parse_RgbExtra(data, cb, rgce, opts) : null;\n return [rgce, rgcb];\n }",
"function getCellByAliases (tabenv, tabloAlias, headerAlias, numLine) {\n\tvar tablo = tabenv.tablos.get(tabloAlias);\n\tvar header = getHeader(tablo, headerAlias);\n\treturn getCell(tablo, header, numLine);\n}",
"function parse_XLSBCellParsedFormula(data, length) {\n var cce = data.read_shift(4);\n return parsenoop(data, length - 4);\n }",
"function parse_XLSBCellParsedFormula(data, length) {\n\t\tvar cce = data.read_shift(4);\n\t\treturn parsenoop(data, length-4);\n\t}",
"function execute(cell,token_list){\n var state = '',\n intend=0,\n m,\n i,\n token,\n previous,\n current,\n next,\n subtokens= new TokenList(),\n result_tokens= new TokenList();\n\n while (token_list.moveNext()) {\n token = token_list.current();\n\n\n if (token===null){\n continue;\n }\n if ( (token.type===keywords.type.function) && (token.subtype===keywords.subtype.start)){\n intend+=1;\n }\n if ( (token.type===keywords.type.subexpression) && (token.subtype===keywords.subtype.start)){\n intend+=1;\n }\n\n if (intend>0){\n subtokens.add(token.value,token.type,token.subtype);\n }else{\n if (\n (token.type===keywords.type.literal) &&\n (token.subtype===keywords.subtype.range) // change here to support, strings and so on ...\n ){\n try{\n var c2 = cell.worksheet.getCell(token.value);\n result_tokens.add(c2.value,\"literal\",keywords.subtype.number);\n }catch(error){\n //console.log(error);\n return '#REF!'; /*could not fine that cell*/\n }\n }else if (\n (token.type===keywords.type.literal) &&\n (token.subtype===keywords.subtype.number) // change here to support, strings and so on ...\n ){\n result_tokens.add(token.value,keywords.type.literal,keywords.subtype.number);\n }else{\n result_tokens.add(token.value,token.type,token.subtype);\n }\n }\n\n if ( (token.type===keywords.type.subexpression) && (token.subtype===keywords.subtype.stop)){\n intend-=1;\n if (intend===0){\n subtokens.shrink();\n var calculated_value=execute(cell,subtokens);\n if (isNaN(calculated_value)){\n if (errorRegEx.test(calculated_value)){\n return calculated_value;\n }\n }\n subtokens= new TokenList();\n result_tokens.add(calculated_value,keywords.type.literal,keywords.subtype.number);\n }\n }\n\n if ( (token.type===keywords.type.function) && (token.subtype===keywords.subtype.stop)){\n intend-=1;\n if (intend===0){\n calculated_value = executeFunction(cell,subtokens);\n subtokens= new TokenList();\n result_tokens.add(calculated_value,keywords.type.literal,keywords.subtype.number);\n }\n }\n\n\n }\n\n\n\n result_tokens.reset();\n while(result_tokens.moveNext()){\n previous = result_tokens.previous();\n current = result_tokens.current();\n next = result_tokens.next();\n if (\n (previous!=null) ||\n (current!=null) || // should never be null!\n (next!=null)\n ){\n if ( \n (current.type === keywords.type.operand) &&\n (current.subtype === keywords.subtype.math)\n ){\n switch(current.value){\n case '*': \n if (previous.value==''){\n previous.value=0;\n }\n if (next.value==''){\n next.value=0;\n }\n if (isNaN(next.value)){\n return '#VALUE!';\n }\n result_tokens.replaceTripple(new Token(previous.value * next.value,keywords.type.literal,keywords.subtype.number));\n break;\n case '/': \n if (previous.value==''){\n previous.value=0;\n }\n if (next.value==''){\n next.value=0;\n }\n if (next.value===0){\n return '#DIV/0!';\n }\n if (isNaN(next.value)){\n return '#VALUE!';\n }\n result_tokens.replaceTripple(new Token(previous.value / next.value,keywords.type.literal,keywords.subtype.number));\n break;\n }\n }\n }\n\n }\n result_tokens.reset();\n while(result_tokens.moveNext()){\n previous = result_tokens.previous();\n current = result_tokens.current();\n next = result_tokens.next();\n if (\n (previous!=null) ||\n (current!=null) || // should never be null!\n (next!=null)\n ){\n if ( \n (current.type === keywords.type.operand) &&\n (current.subtype === keywords.subtype.math)\n ){\n switch(current.value){\n case '+': \n if (next.value==''){\n next.value=0;\n }\n if (previous.value==''){\n previous.value=0;\n }\n if (isNaN(next.value)){\n return '#VALUE!';\n }\n result_tokens.replaceTripple(new Token(1*previous.value + 1*next.value,keywords.type.literal,keywords.subtype.number));\n break;\n case '-': \n if (next.value==''){\n next.value=0;\n }\n if (previous.value==''){\n previous.value=0;\n }\n if (isNaN(next.value)){\n return '#VALUE!';\n }\n result_tokens.replaceTripple(new Token(1*previous.value - 1*next.value,keywords.type.literal,keywords.subtype.number));\n\n break;\n default:\n console.log('not supported math type '+current.value);\n return '#N/A';\n break;\n }\n }\n\n if ( \n (current.type === keywords.type.operand) &&\n (current.subtype === keywords.subtype.concat)\n ){\n switch(current.value){\n case '&': \n\n result_tokens.replaceTripple(new Token( previous.value +''+ next.value,keywords.type.literal,keywords.subtype.string));\n break;\n default:\n console.log('not supported conact type '+current.value);\n return '#N/A';\n break;\n }\n }\n\n if ( \n (current.type === keywords.type.operand) &&\n (current.subtype === keywords.subtype.logical)\n ){\n switch(current.value){\n case '>': \n result_tokens.replaceTripple(new Token( previous.value > next.value,keywords.type.literal,keywords.subtype.logical));\n break;\n case '<': \n result_tokens.replaceTripple(new Token( previous.value < next.value,keywords.type.literal,keywords.subtype.logical));\n break;\n case '<>': \n result_tokens.replaceTripple(new Token( previous.value != next.value,keywords.type.literal,keywords.subtype.logical));\n break;\n case '=': \n result_tokens.replaceTripple(new Token( previous.value == next.value,keywords.type.literal,keywords.subtype.logical));\n break;\n default:\n console.log('not supported logical type '+current.value);\n return '#N/A';\n break;\n }\n }\n }\n\n }\n //console.log(result_tokens._items);\n if (result_tokens._bol() && result_tokens._eol()){\n current = result_tokens.current();\n if (current===null){\n return '#N/A';\n }\n return current.value;\n }\n return '#N/A';\n //console.log('calculate result_tokens');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates and stores the gauge for the wind direction. | static createWindDirectionGauge() {
var gauge = new RadialGauge(this.createWindDirectionOptions('windDirectionCanvas'));
LivewindStore.storeGauge('windDirection', gauge);
gauge.draw();
} | [
"static createWindSpeedGauge() {\r\n var gauge = new RadialGauge(this.createWindSpeedOptions('windSpeedCanvas'));\r\n LivewindStore.storeGauge('windSpeed', gauge);\r\n gauge.draw();\r\n }",
"static createWindSpeedGustsGauge() {\r\n var gauge = new RadialGauge(this.createWindSpeedOptions('windSpeedGustsCanvas'));\r\n LivewindStore.storeGauge('windSpeedGusts', gauge);\r\n gauge.draw();\r\n }",
"static createWindchillTemperatureGauge() {\r\n var gauge = new LinearGauge(this.createTemperatureGaugeOpts('windchillTemperatureCanvas'));\r\n LivewindStore.storeGauge('windchillTemperature', gauge);\r\n gauge.draw();\r\n }",
"static createWaterTemperatureGauge() {\r\n var gauge = new LinearGauge(this.createTemperatureGaugeOpts('waterTemperatureCanvas'));\r\n LivewindStore.storeGauge('waterTemperature', gauge);\r\n gauge.draw();\r\n }",
"function drawGauge() {\n // https://developers.google.com/chart/interactive/docs/gallery/gauge\n\n // Instantiate and draw the Gauge.\n if (gauge === null) {\n gauge = new google.visualization.Gauge(document.getElementById('gaugeDiv'));\n\n // Data with init values.\n gaugeData = new google.visualization.arrayToDataTable([\n ['Label', 'Value'],\n ['\\xB0C', 0]\n ]);\n\n // Event listener\n google.visualization.events.addOneTimeListener(gauge, 'ready', function () {\n gaugeData = new google.visualization.arrayToDataTable([\n ['Label', 'Value'],\n ['°C', 0]\n ]);\n gauge.draw(gaugeData, gaugeOptions);\n });\n\n } else {\n\n // Update data with new value (when already initiated).\n gaugeData = new google.visualization.arrayToDataTable([\n ['Label', 'Value'],\n ['°C', temperature]\n ]);\n }\n\n gauge.draw(gaugeData,gaugeOptions)\n}",
"static createDailyRainGauge() {\r\n var gauge = new LinearGauge(this.createRainGaugeOpts('dailyRainCanvas'));\r\n LivewindStore.storeGauge('dailyRain', gauge);\r\n gauge.draw();\r\n }",
"static createAirTemperatureGauge() {\r\n var gauge = new LinearGauge(this.createTemperatureGaugeOpts('airTemperatureCanvas'));\r\n LivewindStore.storeGauge('airTemperature', gauge);\r\n gauge.draw();\r\n }",
"function buildGauge(wfreq) {\n console.log(wfreq);\n // Enter the washing frequency between 0 and 180\n var level = parseFloat(wfreq)/5;\n \n // Trig to calc meter point\n var degrees = 180 - level;\n var radius = 0.5;\n var radians = (degrees * Math.PI) / 180;\n var x = radius * Math.cos(radians);\n var y = radius * Math.sin(radians);\n console.log(degrees);\n // Path: may have to change to create a better triangle\n var mainPath = \"M -.0 -0.05 L .0 0.05 L \";\n var pathX = String(x);\n var space = \" \";\n var pathY = String(y);\n var pathEnd = \" Z\";\n var path = mainPath.concat(pathX, space, pathY, pathEnd);\n \n var data = [\n {\n type: \"scatter\",\n x: [0],\n y: [0],\n marker: { size: 12, color: \"850000\" },\n showlegend: false,\n name: \"Calories\",\n text: level*5,\n hoverinfo: \"text+name\"\n },\n {\n values: [50 / 9, 50 / 9, 50 / 9, 50 / 9, 50 / 9, 50 / 9, 50 / 9, 50 / 9, 50 / 9, 50],\n rotation: 90,\n text: [\"800-900\", \"700-800\", \"600-700\", \"500-600\", \"400-500\", \"300-400\", \"200-300\", \"100-200\", \"0-100\", \"\"],\n textinfo: \"text\",\n textposition: \"inside\",\n marker: {\n colors: [\n \"rgba(160, 50, 50, .5)\",\n \"rgba(170, 70, 70, .5)\",\n \"rgba(180, 90, 90, .5)\",\n \"rgba(190, 110, 110, .5)\",\n \"rgba(200, 130, 130, .5)\",\n \"rgba(210, 150, 150, .5)\",\n \"rgba(220, 170, 170, .5)\",\n \"rgba(230, 195, 195, .5)\",\n \"rgba(240, 210, 210, .5)\",\n \"rgba(255, 255, 255, 0)\"\n ]\n },\n labels: [\"800-900\", \"700-800\", \"600-700\", \"500-600\", \"400-500\", \"300-400\", \"200-300\", \"100-200\", \"0-100\", \"\"],\n hoverinfo: \"label\",\n hole: 0.5,\n type: \"pie\",\n showlegend: false\n }\n ];\n \n var layout = {\n shapes: [\n {\n type: \"path\",\n startAngle:(-90 * (Math.PI/180)),\n endAngle:(90 * (Math.PI/180)),\n path: path,\n fillcolor: \"850000\",\n line: {\n color: \"850000\"\n }\n }\n ],\n title: \"<b>Calories</b> <br> Per 100 gram\",\n height: 500,\n width: 500,\n xaxis: {\n zeroline: false,\n showticklabels: false,\n showgrid: false,\n range: [-1, 1]\n },\n yaxis: {\n zeroline: false,\n showticklabels: false,\n showgrid: false,\n range: [-1, 1]\n }\n };\n \n var GAUGE = document.getElementById(\"bubble2\");\n Plotly.newPlot(GAUGE, data, layout);\n }",
"function createGauge(container, current) {\n return new Highcharts.chart({\n exporting: { enabled: false },\n chart: {\n type: 'solidgauge',\n renderTo: container,\n height: 220\n },\n title: null,\n pane: {\n center: ['50%', '85%'],\n size: '100%',\n startAngle: -90,\n endAngle: 90,\n background: {\n backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || '#EEE',\n innerRadius: '30%',\n outerRadius: '100%',\n shape: 'arc'\n }\n },\n tooltip: {\n enabled: false\n },\n // the value axis\n yAxis: {\n stops: [\n [0.1, '#55BF3B'], // green\n [0.5, '#DDDF0D'], // yellow\n [0.9, '#DF5353'] // red\n ],\n labels: {\n y: 0\n },\n min: 0,\n max: 50\n },\n\n plotOptions: {\n solidgauge: {\n dataLabels: {\n y: 40,\n borderWidth: 0,\n useHTML: true\n }\n }\n },\n credits: {\n enabled: false\n },\n series: [{\n data: [current],\n dataLabels: {\n format: '<div style=\"text-align:center\"><span style=\"font-size:20px;color:' +\n ((Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black') + '\">{y}</span>' +\n '<span style=\"font-size:12px;color:silver\"> m/s</span></div>'\n }\n }]\n });\n}",
"function buildGauge(data){\n \n}",
"function gaugeChart(wfreq) {\n console.log('gaugeChart function will now build a gauge chart for the wfreq passed to it.');\n var data = [\n {\n domain: { x: [0, 1], y: [0, 1] },\n value: wfreq,\n title: { text: \"Weekly Washing Frequency\" },\n type: \"indicator\",\n mode: \"gauge+number\",\n gauge: {\n axis: { range: [null, 9], tickwidth: 1, tickcolor: \"#000082\" },\n steps: [\n { range: [0, 1], color: \"#fff4ed\" },\n { range: [1, 2], color: \"#ffddc6\" },\n { range: [2, 3], color: \"#ffc59f\" },\n { range: [3, 4], color: \"#ffae78\" },\n { range: [4, 5], color: \"#ff9650\" },\n { range: [5, 6], color: \"#ff7e29\" },\n { range: [6, 7], color: \"#ff6702\" },\n { range: [7, 8], color: \"#ed5f00\" },\n { range: [8, 9], color: \"#c64800\" },\n ],\n threshold: {\n line: { color: \"red\", width: 4 },\n thickness: 0.75,\n value: 490,\n },\n },\n },\n ];\n\n var layout = { width: 450, height: 338, margin: { t: 0, b: 0 } };\n Plotly.newPlot(\"gauge\", data, layout);\n}",
"function buildGauge(WFREQ) {\n // Trig to calc gauge meter point\n // var degrees = 170 - (WFREQ * 18), //convert WREQ to degrees make 10 ranges for each number 0-9 and want to place marker at mid-pt of each range\n // radius = .5;\n let degrees = 170 - (WFREQ * 18); //convert WREQ to degrees make 10 ranges for each number 0-9 and want to place marker at mid-pt of each range\n // console.log(degrees)\n let radius = .5;\n // console.log(radius)\n var radians = degrees * Math.PI / 180;\n var x = radius * Math.cos(radians);\n var y = radius * Math.sin(radians);\n // console.log(x, y)\n\n // Path of the triangular gauge meter\n var mainPath = 'M0 -0.025 L0 0.025 L';\n var pathX = String(x);\n var space = ' ';\n var pathY = String(y);\n var pathEnd = ' Z';\n var path = mainPath.concat(pathX, space, pathY, pathEnd);\n // console.log(path)\n\n var data = [{\n type: 'scatter',\n x: [0], y: [0],\n marker: { size: 28, color: '850000' },\n showlegend: false,\n name: 'Wash Frequency',\n text: WFREQ,\n hoverinfo: 'text+name'\n },\n\n {\n values: [50 / 10, 50 / 10, 50 / 10, 50 / 10, 50 / 10, 50 / 10, 50 / 10, 50 / 10, 50 / 10, 50 / 10, 50],\n rotation: 72, //first pie slice starts verticaly and goes to right, so already rotated 18 deg and need to rotate another 72 to get it all flat\n sort: false, //including this prevented a weird chrome mis-rendering that re-arranged the order incorrectly\n text: ['9', '8', '7', '6', '5', '4', '3', '2', '1', '0', ''],\n textinfo: 'text',\n textposition: 'inside',\n marker: {\n colors: ['rgba(0, 115, 0, .5)',\n 'rgba(14, 127, 12.5, .5)', 'rgba(41,139,25, .5)',\n 'rgba(69,152,51, .5)', 'rgba(96,164,76, .5)',\n 'rgba(123,177,101, .5)', 'rgba(150,189,126, .5)',\n 'rgba(178,201,152, .5)', 'rgba(205,214,177, .5)',\n 'rgba(232,226,202, .5)', 'rgba(255, 255, 255, 0)']\n },\n labels: ['9', '8', '7', '6', '5', '4', '3', '2', '1', '0', ' '],\n hoverinfo: 'label',\n hole: .5,\n type: 'pie',\n showlegend: false\n }];\n\n //use jquery to identify the inner width of the bootstrap column where the gauge div is located\n //will use this variable to constrain the height to be equal to this so that aspect ratio stays 1:1\n //and location of gauge marker geometry works correclty no longer how website scaled\n var colWidth = $( \"#gauge\" ).innerWidth();\n // console.log(colWidth)\n\n var layout = {\n shapes: [{\n type: 'path',\n path: path,\n fillcolor: '850000',\n line: {\n color: '850000'\n }\n }],\n title: \"<b>Belly Button Washing Frequency <br> Scrubs per Week</b>\",\n height: colWidth,\n xaxis: {\n zeroline: false, showticklabels: false,\n showgrid: false, range: [-1, 1]\n },\n yaxis: {\n zeroline: false, showticklabels: false,\n showgrid: false, range: [-1, 1]\n }\n };\n\n Plotly.newPlot('gauge', data, layout);\n}",
"function buildGaugeAdvanced(wfreq) {\n // Enter the washing frequency between 0 and 180\n var level = parseFloat(wfreq) * 20;\n\n // Trig to calc meter point\n var degrees = 180 - level;\n var radius = 0.5;\n var radians = (degrees * Math.PI) / 180;\n var x = radius * Math.cos(radians);\n var y = radius * Math.sin(radians);\n\n // Path: may have to change to create a better triangle\n var mainPath = \"M -.0 -0.05 L .0 0.05 L \";\n var pathX = String(x);\n var space = \" \";\n var pathY = String(y);\n var pathEnd = \" Z\";\n var path = mainPath.concat(pathX, space, pathY, pathEnd);\n\n var data = [\n {\n type: \"scatter\",\n x: [0],\n y: [0],\n marker: { size: 12, color: \"850000\" },\n showlegend: false,\n name: \"Freq\",\n text: level,\n hoverinfo: \"text+name\"\n },\n {\n values: [50 / 9, 50 / 9, 50 / 9, 50 / 9, 50 / 9, 50 / 9, 50 / 9, 50 / 9, 50 / 9, 50],\n rotation: 90,\n text: [\"8-9\", \"7-8\", \"6-7\", \"5-6\", \"4-5\", \"3-4\", \"2-3\", \"1-2\", \"0-1\", \"\"],\n textinfo: \"text\",\n textposition: \"inside\",\n marker: {\n colors: [\n \"rgba(0, 105, 11, .5)\",\n \"rgba(10, 120, 22, .5)\",\n \"rgba(14, 127, 0, .5)\",\n \"rgba(110, 154, 22, .5)\",\n \"rgba(170, 202, 42, .5)\",\n \"rgba(202, 209, 95, .5)\",\n \"rgba(210, 206, 145, .5)\",\n \"rgba(232, 226, 202, .5)\",\n \"rgba(240, 230, 215, .5)\",\n \"rgba(255, 255, 255, 0)\"\n ]\n },\n labels: [\"8-9\", \"7-8\", \"6-7\", \"5-6\", \"4-5\", \"3-4\", \"2-3\", \"1-2\", \"0-1\", \"\"],\n hoverinfo: \"label\",\n hole: 0.5,\n type: \"pie\",\n showlegend: false\n }\n ];\n\n var layout = {\n shapes: [\n {\n type: \"path\",\n path: path,\n fillcolor: \"850000\",\n line: {\n color: \"850000\"\n }\n }\n ],\n title: \"<b>Belly Button Washing Frequency</b> <br> Scrubs per Week\",\n height: 500,\n width: 500,\n xaxis: {\n zeroline: false,\n showticklabels: false,\n showgrid: false,\n range: [-1, 1]\n },\n yaxis: {\n zeroline: false,\n showticklabels: false,\n showgrid: false,\n range: [-1, 1]\n }\n };\n\n var GAUGE = document.getElementById(\"gauge\");\n Plotly.newPlot(GAUGE, data, layout);\n}",
"function windDirection() {\n if(data.wind.deg == undefined) {\n data.wind.deg = 'Unavailable';\n } else if(data.wind.deg > 349 && data.wind.deg < 11) {\n data.wind.deg = 'N';\n } else if(data.wind.deg > 11 && data.wind.deg < 34) {\n data.wind.deg = 'NNE';\n } else if(data.wind.deg > 34 && data.wind.deg < 56) {\n data.wind.deg = 'NE';\n } else if(data.wind.deg > 56 && data.wind.deg < 79) {\n data.wind.deg = 'ENE';\n } else if(data.wind.deg > 79 && data.wind.deg < 101) {\n data.wind.deg = 'E';\n } else if(data.wind.deg > 101 && data.wind.deg < 124) {\n data.wind.deg = 'ESE';\n } else if(data.wind.deg > 124 && data.wind.deg < 146) {\n data.wind.deg = 'SE';\n } else if(data.wind.deg > 146 && data.wind.deg < 169) {\n data.wind.deg = 'SSE';\n } else if(data.wind.deg > 169 && data.wind.deg < 191) {\n data.wind.deg = 'S';\n } else if(data.wind.deg > 191 && data.wind.deg < 214) {\n data.wind.deg = 'SSW';\n } else if(data.wind.deg > 214 && data.wind.deg < 236) {\n data.wind.deg = 'SW';\n } else if(data.wind.deg > 336 && data.wind.deg < 259) {\n data.wind.deg = 'WSW';\n } else if(data.wind.deg > 259 && data.wind.deg < 281) {\n data.wind.deg = 'W';\n } else if(data.wind.deg > 281 && data.wind.deg < 304) {\n data.wind.deg = 'WNW';\n } else if(data.wind.deg > 304 && data.wind.deg < 326) {\n data.wind.deg = 'NW';\n } else if(data.wind.deg > 326 && data.wind.deg < 349) {\n data.wind.deg = 'NNW';\n }\n return data.wind.deg;\n }",
"function buildGuage(bbWashFreq) {\n console.log(bbWashFreq);\n\n var trace = {\n domain: { x: [0, 1], y: [0, 1] },\n value: bbWashFreq,\n title: { text: \"Belly Button Washing Frequency\" },\n type: \"indicator\",\n mode: \"gauge+number\",\n gauge: {\n axis: {\n range: [null, 9],\n tickwidth: 3,\n tickcolor: \"black\",\n tick0: 0,\n dtick: 1,\n },\n steps: [{ range: [0, 9], color: \"Teal\" }],\n threshold: {\n line: { color: \"purple\", width: 8 },\n thickness: 0.75,\n value: bbWashFreq,\n },\n },\n };\n\n var data = [trace];\n\n var layout = {\n width: 600,\n height: 500,\n margin: { t: 0, b: 0 },\n };\n\n Plotly.newPlot(\"gauge\", data, layout);\n}",
"buildGauge() {\n this.setGaugeSizeToCanvas();\n this.drawGauge();\n if (this.props.animate) this.startAnimation();\n }",
"function updateGauge(wfreq){\n console.log(wfreq);\n data = [\n {\n type: \"indicator\",\n mode: \"gauge+number\",\n value: parseFloat(wfreq), \n title: { text: \"Belly Button Washing Frequency \\n Scrubs per Week\", font: { size: 16 } },\n gauge: {\n axis: { range: [null, 9], tickwidth: 1, tickcolor: \"darkblue\" },\n bar: { color: \"#696969\" },\n bgcolor: \"white\",\n borderwidth: 2,\n bordercolor: \"#696969\",\n steps: [\n { range: [0, 1], color: 'rgb(8, 29, 88)' },\n { range: [1, 2], color: 'rgb(37, 52, 148)' },\n { range: [2, 3], color: 'rgb(34, 94, 168)' },\n { range: [3, 4], color: 'rgb(29, 145, 192)' },\n { range: [4, 5], color: 'rgb(65, 182, 196)' },\n { range: [5, 6], color: 'rgb(127, 205, 187)' },\n { range: [6, 7], color: 'rgb(99, 233, 180)' },\n { range: [7, 8], color: 'rgb(237, 248, 217)' },\n { range: [8, 9], color: 'rgb(255, 225, 217)' },\n ],\n }\n }\n ];\n \n layout = {\n width: 500,\n height: 400,\n margin: { t: 25, r: 25, l: 25, b: 25 },\n paper_bgcolor: \"white\",\n font: { color: \"#696969\", family: \"Arial\" }\n };\n \n Plotly.newPlot('gauge', data, layout);\n}",
"function updateGauge(targetDemographic) {\n // Restyle the plot\n Plotly.restyle(\"gauge\", \"value\", [targetDemographic.wfreq]);\n}",
"generateWind() {\n\t\tconst noiseValue = Noise.noiseMap[this.coords[1]][this.coords[0]];\n\t\tthis.windSpeed = 7*(Math.pow(noiseValue, 5) + Math.pow(noiseValue, 3)/3 + 2*noiseValue) + 3.5;\n\n\t\tif (this.windSpeed < 0) {\n\t\t\tthis.windSpeed = 0;\n\t\t} else if (this.windSpeed > 35) {\n\t\t\tthis.windSpeed = 35;\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switch to the given tab in a browser and focus the browser window | function focusTab(tab) {
let browserWindow = tab.ownerDocument.defaultView;
browserWindow.focus();
browserWindow.gBrowser.selectedTab = tab;
} | [
"switchFocus() {\n browser.switchWindow(this.pageTitle);\n }",
"function SelectBrowserTab(/**string*/partOfUrl)\r\n{\r\n\tvar iter = 10;\r\n\twhile(iter>0)\r\n\t{\r\n\t\tvar url = Navigator.GetUrl();\r\n\t\tLog(\"Url: \"+url);\r\n if (!url)\r\n {\r\n break;\r\n }\r\n\t\tif(url.indexOf(partOfUrl)>=0)\r\n\t\t{\r\n\t\t\t// Attach to current tab\r\n\t\t\tTester.Assert('Attaching to Tab: '+url, true);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tGlobal.DoSendKeys(\"^{TAB}\");\r\n\t\tGlobal.DoSleep(500);\r\n\t\tNavigator.Detach();\r\n\t\tNavigator.Open();\r\n\t\titer--;\r\n\t}\r\n\tTester.Assert('Unable to find browser tab: '+partOfUrl, false);\r\n\treturn false;\r\n}",
"function openChrome() {\r\n robot.moveMouseSmooth(59,704);\r\n setTimeout(function() {\r\n robot.mouseClick();\r\n robot.typeString(\"chrome\");\r\n robot.keyTap(\"enter\");\r\n \r\n setTimeout(openTabs,2000);\r\n },2000);\r\n}",
"async function focus_menu_tab()\n {\n const tab = await browser.tabs.get(menu_tab_id);\n\n await browser.tabs.update(tab.id, { active: true });\n await browser.windows.update(tab.windowId, { focused: true });\n }",
"async function focus_menu_tab()\n {\n const tab = await browser.tabs.get(menu_tab_id);\n\n browser.tabs.update(tab.id, { active: true });\n browser.windows.update(tab.windowId, { focused: true });\n }",
"function openTabOrWindow(url)\n{\n try {\n var gBrowser = window.opener.getBrowser();\n gBrowser.selectedTab = gBrowser.addTab(url);\n }\n catch (e) {\n window.open(url);\n }\n}",
"showAndFocusWindow(windowName = 'main') {\n const browserWindow = this.windows[windowName];\n if (browserWindow) {\n browserWindow.show();\n browserWindow.focus();\n }\n }",
"function activateTab(window_id, tab_id) {\n chrome.tabs.update(tab_id, {active: true});\n chrome.windows.update(window_id, {focused: true});\n\n}",
"function openInNewTab(url) {\n var win = window.open(url, '_blank');\n win.focus();\n }",
"open(options = {}) {\n\n // If name window in open tab, reuse that tab. Otherwise, open new window.\n const named = options.name && this.find(options.name.toString());\n if (named) {\n // Select this as the currently open tab. Changing the location would then\n // select a different window.\n this._current = named;\n if (options.url) this._current.location = options.url;\n return this._current;\n }\n\n // When window changes we need to change tab slot. We can't keep the index\n // around, since tab order changes, so we look up the currently known\n // active window and switch that around.\n let active = null;\n const open = createHistory(this._browser, window => {\n // Focus changes to different window, make it the active window\n if (!Tabs.sameWindow(window, active)) {\n const index = this._indexOf(active);\n if (index >= 0) this[index] = window;\n this.current = active = window;\n }\n if (window) this._browser._eventLoop.setActiveWindow(window);\n });\n\n const name = options.name === '_blank' ? '' : options.name || '';\n options.name = name;\n const window = open(options);\n this.push(window);\n if (name && (this.propertyIsEnumerable(name) || !this[name])) this[name] = window;\n // Select this as the currently open tab\n this.current = active = window;\n return window;\n }",
"function openInNewTab(url) {\n var win = window.open(url, '_blank');\n win.focus();\n}",
"function switchTo(tabName) {\n tabView.switchTo(tabName);\n }",
"function openTab() {\n var dashboard = getSelectedDashboard();\n var url = (dashboard == false) ? '/options.html' : HOME_URL + '/dashboard/' + dashboard.name;\n browser.tabs.query({currentWindow: true}, function(tabs) {\n var founded = false;\n for (i = 0; i < tabs.length; i++) {\n var tab = tabs[i];\n if (!founded && tab.url.match(HOME_URL + '/([a-z]{2}$|signin|signup|dashboard/' + (dashboard.name || '')+ ')')) {\n founded = true;\n var data = {active: true };\n if (!tab.url.match('^' + url)) {\n data.url = url;\n }\n browser.tabs.update(tab.id, data);\n }\n }\n if (!founded) browser.tabs.create({active: true, url: url});\n });\n}",
"function CFOpenNewTab(url) {\n\tvar win = window.open(url, '_blank');\n\twin.focus();\n}",
"function focusCurrentServer() {\n\tcurrentWindow.send('focus-webview-with-id', webContentsId);\n}",
"function focusCurrentServer() {\n\tcurrentWindow.send('focus-webview-with-id', webContentsId)\n}",
"function openUrlInCurrentTab(url){\r\n BRW_openUrlInCurrentTab(redirectModification(url));\r\n }",
"function openTab(input){\n openURL(input, false);\n}",
"function Tab() {\n\tvar items = document.querySelectorAll( '.js-focus-me' );\n\tvar loop = 0;\n\n\treturn setInterval( function() {\n\t\tif( loop >= items.length ) {\n\t\t\tStopTab( interval, document.querySelector( '.js-tabbing-switch' ) );\n\t\t}\n\n\t\titems[ loop ].focus();\n\n\t\tloop ++;\n\t}, 500 );\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this will blur and darken the elements defined in brackets (e.g. everything except the active step): | function backgroundBlur(allExcept) {
allExcept.forEach(
element => element.style.filter = "blur(0.6vmin) brightness(40%)"
);
} | [
"blur() {\n this.foreground.blut();\n }",
"function applyBlur()\n\t\t\t\t{\n\t\t\t\t TweenMax.set($('.main-img'), {webkitFilter:'blur('+ blurElement.a + 'px)'}); \n\t\t\t\t}",
"function addBlurDarken() {\n\tworkHistorySection.find(\".timeline-icon\").addClass(\"blur-and-darken\");\n\tworkHistorySection.find(\".timeline-line\").addClass(\"blur-and-darken\");\n\t$(\".work-history-heading\").addClass(\"blur-and-darken\");\n\t$(\".timeline-instruction-tap-click\").addClass(\"blur-and-darken\");\n\t$(\".timeline-instruction-hover-focus\").addClass(\"blur-and-darken\");\n\t$(\".end-of-timeline\").addClass(\"blur-and-darken\");\n\t$(\".arrow-down-history-to-skills\").addClass(\"blur-and-darken\");\n}",
"visualizeBlur() {\n dom.removeCssClass(this.container, \"ace_focus\");\n }",
"function removeBlurDarken() {\n\tworkHistorySection.find(\".timeline-icon\").removeClass(\"blur-and-darken\");\n\tworkHistorySection.find(\".timeline-line\").removeClass(\"blur-and-darken\");\n\t$(\".work-history-heading\").removeClass(\"blur-and-darken\");\n\t$(\".timeline-instruction-tap-click\").removeClass(\"blur-and-darken\");\n\t$(\".timeline-instruction-hover-focus\").removeClass(\"blur-and-darken\");\n\t$(\".end-of-timeline\").removeClass(\"blur-and-darken\");\n\t$(\".arrow-down-history-to-skills\").removeClass(\"blur-and-darken\");\n}",
"function onBlur() {\n processUnprocessedNodes();\n }",
"function blurBG() {\n\t$('.BG').css(\"filter\", \"blur(5px) brightness(75%)\");\n}",
"clearBlur () {\n this.ctx.filter = `blur(0px)`;\n }",
"blur(isPermanent = false) {\n this.isPermanentFocus = isPermanent ? false : this.isPermanentFocus;\n removeClass(this.border, style['inset-focus']);\n this.drawBorder();\n Object.keys(this.indicator).forEach((id) => {\n this.renderIndicator(id);\n });\n if (!this.isScaledUp) this.originBlur();\n this.drawLeaderLine();\n this.removeImgListeners();\n }",
"function softBlur() {\n let matriz = {\n valores:\n [\n 0.0, 0.2, 0.0,\n 0.2, 0.2, 0.2,\n 0.0, 0.2, 0.0\n ],\n tamano_n: 3, tamano_m: 3\n }\n\n convolucion(matriz);\n}",
"function backgroundblur(i = true) {\n var c = $('.custom-carousel_blur');\n if(c.length > 0 ) {\n u = c.find('.up');\n d = c.find('.down');\n f = c.find('.item-first');\n c = c.add(u).add(d).add(f);\n c.mouseover(function() {\n f.addClass('custom-carousel_blured');\n });\n c.mouseout(function() {\n f.removeClass('custom-carousel_blured');\n });\n if(i && !f.hasClass('custom-carousel_blured')){\n f.addClass('custom-carousel_blured');\n }\n }\n }",
"function blur() {\n let matriz = {\n valores:\n [\n 0, 0, 1 / 13, 0, 0,\n 0, 1 / 13, 1 / 13, 1 / 13, 0,\n 1 / 13, 1 / 13, 1 / 13, 1 / 13, 1 / 13,\n 0, 1 / 13, 1 / 13, 1 / 13, 0,\n 0, 0, 1 / 13, 0, 0\n ],\n tamano_n: 5, tamano_m: 5\n }\n\n convolucion(matriz);\n}",
"function blurOut(docElement) {\n docElement.setAttribute('style', \"-webkit-filter: blur(2px); -moz-filter: blur(2px); -o-filter: blur(2px); -ms-filter: blur(2px); filter: blur(2px);\");\n}",
"function imgblur(img){\t\r\n\tvar away = axisaway(img); \r\n\tif(away.toString() != \"false\"){\r\n\t\tvar opa = 0.2 + 0.8 * away;\r\n\t\timg.style.opacity = opa; \r\n\t}\r\n}",
"function makeAllBlur() {\n\n\t// Set the opacity of each mascot image to 0.2\n\tdocument.getElementById(DOMstrings.oyster_div).style.opacity = '0.2';\n\tdocument.getElementById(DOMstrings.cat_div).style.opacity = '0.2';\n\tdocument.getElementById(DOMstrings.whale_div).style.opacity = '0.2';\n\tdocument.getElementById(DOMstrings.elephant_div).style.opacity = '0.2';\n\tdocument.getElementById(DOMstrings.fish_div).style.opacity = '0.2';\n\tdocument.getElementById(DOMstrings.goose_div).style.opacity = '0.2';\n}",
"function removeBlur(docElement) {\n docElement.setAttribute('style', \"-webkit-filter: ''; -moz-filter: ''; -o-filter: ''; -ms-filter: ''; filter: '';\");\n}",
"function set_blur(){\nvar blur_val=document.getElementById(\"blur_tool\").valueAsNumber;\nobj.blur=blur_val;\ndocument.getElementById('output_image').style.filter=\"contrast(\"+obj.contrast+\"%) blur(\"+obj.blur+\"px) opacity(\"+obj.opacity+\"%) grayscale(\"+obj.gscale+\"%) brightness(\"+obj.bright+\"%) saturate(\"+obj.saturate+\")\";\n\n// console.log(obj.blur);\n}",
"_blur(cubeUVRenderTarget,lodIn,lodOut,sigma,poleAxis){const pingPongRenderTarget=this._pingPongRenderTarget;this._halfBlur(cubeUVRenderTarget,pingPongRenderTarget,lodIn,lodOut,sigma,'latitudinal',poleAxis);this._halfBlur(pingPongRenderTarget,cubeUVRenderTarget,lodOut,lodOut,sigma,'longitudinal',poleAxis);}",
"function blurSliderHide() {\r\n document.querySelector('.blurbuttonwrapper').style.visibility = \"hidden\"\r\n document.querySelector('#background').style.filter = \"blur(\" + (document.querySelector(\"#blurSlider\").value / 10) + \"px)\"\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the System tokens from the database and stores the results in a system_token_request map | function system_token_request() {
var MongoClient = require('mongodb').MongoClient, format = require('util').format;
MongoClient.connect(require('util').format('mongodb://%s:%s/%s', config.mongodb.host, config.mongodb.port, config.mongodb.database), function (err, db) {
if (err) throw err;
var collection = db.collection('tokens');
collection.count(function (err, count) {
console.log("Loaded " + count + " system tokens from the collection.");
});
collection.find().toArray(function (err, results) {
tokens = results;
exports.tokens = results;
db.close();
});
})
} | [
"static loadTokensList() {\n const { availableTokens, network, walletAddress } = store.getState();\n\n if (network !== 'mainnet') return Promise.resolve();\n\n const availableTokensAddresses = availableTokens\n .filter(token => token.symbol !== 'ETH')\n .map(token => token.contractAddress);\n\n return fetch(\n `https://api.ethplorer.io/getAddressInfo/${walletAddress}?apiKey=freekey`,\n )\n .then(response => response.json())\n .then(data => {\n if (!data.tokens) {\n return Promise.resolve();\n }\n\n return data.tokens\n .filter(\n token =>\n !availableTokensAddresses.includes(token.tokenInfo.address),\n )\n .forEach(token => {\n store.dispatch({\n type: ADD_TOKEN,\n token: {\n contractAddress: token.tokenInfo.address,\n decimals: parseInt(token.tokenInfo.decimals, 10),\n name: token.tokenInfo.name,\n symbol: token.tokenInfo.symbol,\n },\n });\n });\n });\n }",
"async loadTokensList() {\n if( this.tokens.length > 0) return this.tokens;\n\n const url = `https://blockscout.com/eth/ropsten/api?module=account&action=tokenlist&address=${this.getAddress()}`;\n return fetch(url)\n .then(response => response.json())\n .then(data => {\n if (!data.result) {\n return;\n }\n\n const tokens = data.result.map(token => {\n const tokenDecimal = parseInt(token.decimals, 10);\n const balance = parseFloat(new BigNumber(token.balance).div(new BigNumber(10).pow( tokenDecimal )).toString());\n return new Token(\n token.contractAddress,\n tokenDecimal,\n token.name,\n token.symbol,\n `https://raw.githubusercontent.com/TrustWallet/tokens/master/images/${token.contractAddress}.png`,\n {},\n balance,\n new BigNumber(token.balance)\n )\n });\n\n const coin = defaultTokens[0];\n coin.balance = this.balance;\n this.tokens = tokens;\n\n console.log('tokens', tokens)\n return this.tokens;\n });\n }",
"function getTokens(callback) {\n chrome.enterprise.platformKeys.getTokens(function(tokens) {\n var userToken = null;\n var systemToken = null;\n for (var i = 0; i < tokens.length; i++) {\n if (tokens[i].id == 'user')\n userToken = tokens[i];\n else if (tokens[i].id == 'system')\n systemToken = tokens[i];\n }\n callback(userToken, systemToken);\n });\n}",
"async loadTokensList() {\n if (this.tokens.length > 0) return this.tokens;\n\n const url = `https://blockscout.com/eth/ropsten/api?module=account&action=tokenlist&address=${this.getAddress()}`;\n return fetch(url)\n .then(response => response.json())\n .then((data) => {\n if (!data.result) {\n return;\n }\n\n const tokens = data.result.map((token) => {\n const tokenDecimal = parseInt(token.decimals, 10);\n const balance = parseFloat(new BigNumber(token.balance).div(new BigNumber(10).pow(tokenDecimal)).toString());\n return new Token(\n token.contractAddress,\n tokenDecimal,\n token.name,\n token.symbol,\n `https://raw.githubusercontent.com/TrustWallet/tokens/master/images/${token.contractAddress}.png`,\n {},\n balance,\n new BigNumber(token.balance),\n );\n });\n\n const coin = defaultTokens[0];\n coin.balance = this.balance;\n this.tokens = tokens;\n\n // console.log('tokens', tokens);\n return this.tokens;\n });\n }",
"async loadTokens() {\n this.APIClient._authentication._tokensFile = '.tokens.json';\n try {\n const data = await this.readFileAsync(this.name, 'tokens.json');\n // @ts-expect-error\n this.APIClient._authentication._tokens.oauth = JSON.parse(data.file);\n this.log.info('Successfully loaded token');\n }\n catch (e) {\n this.log.debug(`No tokens to load: ${this.errorToText(e)}`);\n }\n }",
"function loadTokens() {\n const storedJSON = get(STORAGE_KEY_TOKENS);\n if (storedJSON == null) {\n return null;\n }\n\n let usableTokens = [];\n const storedTokens = JSON.parse(storedJSON);\n for (var i = 0; i < storedTokens.length; i++) {\n let t = storedTokens[i];\n let usablePoint = decodeStorablePoint(t.point);\n let usableBlind = new sjcl.bn(t.blind);\n usableTokens[i] = { data: t.data, point: usablePoint, blind: usableBlind };\n }\n return usableTokens;\n}",
"async getTokens() {\n let ctx = this.ctx;\n\n const keysRule = {\n address: 'string',\n limit: {\n type: 'int',\n required: false,\n allowEmpty: true,\n max: 100,\n min: 0\n },\n page: {\n type: 'int',\n required: false,\n allowEmpty: true,\n min: 0\n },\n contract_address: {\n type: 'string',\n required: false,\n allowEmpty: true,\n min: 0\n },\n all: {\n type: 'bool',\n required: false,\n allowEmpty: true\n }\n };\n\n try {\n let {\n address,\n limit,\n page,\n contract_address,\n symbol,\n all,\n } = ctx.request.query;\n let options = {\n address,\n limit: limit ? parseInt(limit, 0) : 0,\n page: page ? parseInt(page, 0) : 0,\n contract_address: contract_address || '',\n symbol: symbol || '',\n all: all === 'true',\n };\n\n ctx.validate(keysRule, options);\n\n let nodesInfo;\n let tokenInfo;\n if (options.all) {\n nodesInfo = await ctx.service.address.getMultiTokensInfo(options);\n tokenInfo = nodesInfo;\n } else {\n const getNodesInfo = ctx.curl(\n apiServerProvider\n + `/api/address/tokens?address=${address}&nodes_info=1&limit=${limit}&page=${page}`, {\n dataType: 'json'\n }\n );\n const getTokenInfo = ctx.service.address.getMultiTokensInfo({});\n\n const result = await Promise.all([getNodesInfo, getTokenInfo]);\n nodesInfo = result[0].data;\n tokenInfo = result[1];\n }\n\n const tokenInfoFormatted = {};\n tokenInfo.forEach(item => {\n tokenInfoFormatted[item.symbol] = item;\n });\n\n if (contract_address) {\n if (!nodesInfo.length) {\n const getNodesInfoResult = await ctx.curl(\n apiServerProvider\n + `/api/nodes/info`, {\n dataType: 'json'\n }\n );\n const getTokensResult = await ctx.curl(\n apiServerProvider\n + `/api/contract/detail?contract_address=${contract_address}`, {\n dataType: 'json'\n }\n );\n const tokensInfo = getTokensResult.data;\n\n nodesInfo = getNodesInfoResult.data.list;\n nodesInfo = tokensInfo.map(tokenItem => {\n const nodeInfo = nodesInfo.find(nodeItem => {\n return nodeItem.contract_address === tokenItem.contract_address;\n });\n return {\n ...tokenItem,\n ...nodeInfo\n }\n });\n }\n\n nodesInfo = [nodesInfo.find(item => {\n if (item.contract_address === contract_address\n && item.symbol === symbol) {\n return true;\n }\n })];\n }\n\n let result = [];\n if (nodesInfo.length) {\n result = await ctx.service.address.getTokens(options, nodesInfo, tokenInfoFormatted);\n }\n\n this.formatOutput('get', result);\n }\n catch (error) {\n this.formatOutput('error', error, 422);\n }\n }",
"async getTokens() {\n let web3 = window.web3;\n if (!web3) {\n alert(\"You need to install & unlock metamask to do that\");\n return;\n }\n const metamaskProvider = new eth.providers.Web3Provider(web3.currentProvider);\n const metamask = metamaskProvider.getSigner();\n const address = (await metamask.provider.listAccounts())[0];\n if (!address) {\n alert(\"You need to install & unlock metamask to do that\");\n return;\n }\n\n const tokenContract = new eth.Contract(tokenAddress, humanTokenAbi, metamaskProvider);\n const token = tokenContract.connect(metamask);\n\n let tokens = eth.utils.bigNumberify(\"1000000000000000000\");\n console.log(`Sending ${tokens} tokens to ${this.state.address}`);\n let approveTx = await token.functions.transfer(this.state.address, tokens);\n console.log(approveTx);\n }",
"async tokens() {\n\t\tif (tokens.length > 0) {\n\t\t\treturn tokens;\n\t\t}\n\t\tconst data = await fetch(tokenLists.honeyswap, {\n\t\t\tmethods: 'GET',\n\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t}).then(response => {\n\t\t\treturn response.json();\n\t\t});\n\n\t\ttokens = data.tokens;\n\t\treturn tokens;\n\t}",
"async _getTokens () {\n const body = {\n user_key: this.options.user_key,\n user_secret: this.options.user_secret\n }\n\n const res = await this.request('POST', { url: '/authenticate', body })\n this.access_token = res.access_token\n this.refresh_token = res.refresh_token\n }",
"generateTokensTable() {\n this.writeData(\n 'TOKENS',\n this._toRustHashMap(this._tokens, 'string', 'number'),\n );\n }",
"async function get_systems_stats(req) {\n const sys_stats = _.cloneDeep(SYSTEM_STATS_DEFAULTS);\n sys_stats.agent_version = process.env.AGENT_VERSION || 'Unknown';\n sys_stats.count = system_store.data.systems.length;\n sys_stats.os_release = (await fs.promises.readFile('/etc/redhat-release').catch(fs_utils.ignore_enoent) || 'unkonwn').toString();\n sys_stats.platform = process.env.PLATFORM;\n const cluster = system_store.data.clusters[0];\n if (cluster && cluster.cluster_id) {\n sys_stats.clusterid = cluster.cluster_id;\n }\n\n try {\n sys_stats.systems = await P.all(_.map(system_store.data.systems, async system => {\n const new_req = _.defaults({\n system: system\n }, req);\n\n const res = await system_server.read_system(new_req);\n // Means that if we do not have any systems, the version number won't be sent\n sys_stats.version = res.version || process.env.CURRENT_VERSION;\n const buckets_config = _aggregate_buckets_config(res);\n const has_dns_name = system.system_address.some(addr =>\n addr.api === 'mgmt' && !net_utils.is_ip(addr.hostnames)\n );\n\n return _.defaults({\n roles: res.roles.length,\n tiers: res.tiers.length,\n buckets: res.buckets.length,\n buckets_config: buckets_config,\n objects: res.objects,\n allocated_space: res.storage.alloc,\n used_space: res.storage.used,\n total_space: res.storage.total,\n free_space: res.storage.free,\n associated_nodes: {\n on: res.nodes.online,\n off: res.nodes.count - res.nodes.online,\n },\n owner: res.owner.email,\n configuration: {\n dns_servers: res.cluster.shards[0].servers[0].dns_servers.length,\n dns_name: has_dns_name,\n },\n cluster: {\n members: res.cluster.shards[0].servers.length\n },\n }, SINGLE_SYS_DEFAULTS);\n }));\n\n sys_stats.version_history = await HistoryDataStore.instance().get_system_version_history();\n\n return sys_stats;\n } catch (err) {\n dbg.warn('Error in collecting systems stats,',\n 'skipping current sampling point', err.stack || err);\n throw err;\n }\n}",
"async function getM2Mtoken() {\n return m2m.getMachineToken(config.AUTH0_CLIENT_ID, config.AUTH0_CLIENT_SECRET)\n}",
"_loadTokens() {\n const Group = require('./token/Group'),\n GroupEnd = require('./token/GroupEnd'),\n Picture = require('./token/command/Picture'),\n Command = require('./token/Command'),\n Escape = require('./token/Escape');\n\n this.tokens = [\n new Group(),\n new GroupEnd(),\n new Picture(),\n new Command()\n ];\n\n // It's important to put Escape token at the end as it's the last one that should be used.\n this.tokens.push(new Escape());\n }",
"async storeTokensFromRedirect() {\n const {\n tokens\n } = await this.token.parseFromUrl();\n this.tokenManager.setTokens(tokens);\n }",
"static get tokenMap() {\n var _tm=`{\n \"a\": \"score\",\n \"b\": \"layout\",\n \"c\": \"leftMargin\",\n \"d\": \"rightMargin\",\n \"e\": \"topMargin\",\n \"f\": \"bottomMargin\",\n \"g\": \"pageWidth\",\n \"h\": \"pageHeight\",\n \"i\": \"orientation\",\n \"j\": \"interGap\",\n \"k\": \"intraGap\",\n \"l\": \"svgScale\",\n \"m\": \"zoomScale\",\n \"n\": \"zoomMode\",\n \"o\": \"pages\",\n \"p\": \"pageSize\",\n \"q\": \"startIndex\",\n \"r\": \"renumberingMap\",\n \"s\": \"staves\",\n \"t\": \"staffId\",\n \"u\": \"staffX\",\n \"v\": \"staffY\",\n \"w\": \"adjY\",\n \"x\": \"staffWidth\",\n \"y\": \"staffHeight\",\n \"z\": \"keySignatureMap\",\n \"aa\": \"instrumentInfo\",\n \"ba\": \"instrumentName\",\n \"ca\": \"keyOffset\",\n \"da\": \"clef\",\n \"ea\": \"modifiers\",\n \"fa\": \"startSelector\",\n \"ga\": \"staff\",\n \"ha\": \"measure\",\n \"ia\": \"voice\",\n \"ja\": \"tick\",\n \"ka\": \"pitches\",\n \"la\": \"endSelector\",\n \"ma\": \"xOffset\",\n \"na\": \"cp1y\",\n \"oa\": \"cp2y\",\n \"pa\": \"attrs\",\n \"qa\": \"id\",\n \"ra\": \"type\",\n \"sa\": \"ctor\",\n \"ta\": \"yOffset\",\n \"ua\": \"position\",\n \"va\": \"measures\",\n \"wa\": \"timeSignature\",\n \"xa\": \"keySignature\",\n \"ya\": \"measureNumber\",\n \"za\": \"measureIndex\",\n \"ab\": \"systemIndex\",\n \"bb\": \"adjX\",\n \"cb\": \"tuplets\",\n \"db\": \"voices\",\n \"eb\": \"notes\",\n \"fb\": \"ticks\",\n \"gb\": \"numerator\",\n \"hb\": \"denominator\",\n \"ib\": \"remainder\",\n \"jb\": \"letter\",\n \"kb\": \"octave\",\n \"lb\": \"accidental\",\n \"mb\": \"symbol\",\n \"nb\": \"bpm\",\n \"ob\": \"display\",\n \"pb\": \"beatDuration\",\n \"qb\": \"beamBeats\",\n \"rb\": \"endBeam\",\n \"sb\": \"textModifiers\",\n \"tb\": \"text\",\n \"ub\": \"endChar\",\n \"vb\": \"fontInfo\",\n \"wb\": \"size\",\n \"xb\": \"family\",\n \"yb\": \"style\",\n \"zb\": \"weight\",\n \"ac\": \"classes\",\n \"bc\": \"verse\",\n \"cc\": \"fill\",\n \"dc\": \"scaleX\",\n \"ec\": \"scaleY\",\n \"fc\": \"translateX\",\n \"gc\": \"translateY\",\n \"hc\": \"selector\",\n \"ic\": \"renderedBox\",\n \"jc\": \"x\",\n \"kc\": \"y\",\n \"lc\": \"width\",\n \"mc\": \"height\",\n \"nc\": \"logicalBox\",\n \"oc\": \"noteType\",\n \"pc\": \"cautionary\",\n \"qc\": \"articulations\",\n \"rc\": \"articulation\",\n \"sc\": \"activeVoice\",\n \"tc\": \"flagState\",\n \"uc\": \"invert\",\n \"vc\": \"fontSize\",\n \"wc\": \"yOffsetLine\",\n \"xc\": \"yOffsetPixels\",\n \"yc\": \"scoreText\",\n \"zc\": \"backup\",\n \"ad\": \"edited\",\n \"bd\": \"pagination\",\n \"cd\": \"boxModel\",\n \"dd\": \"justification\",\n \"ed\": \"autoLayout\",\n \"fd\": \"ornaments\",\n \"gd\": \"offset\",\n \"hd\": \"ornament\",\n \"id\": \"tempoMode\",\n \"jd\": \"tempoText\",\n \"kd\": \"barline\",\n \"ld\": \"systemBreak\",\n \"md\": \"graceNotes\",\n \"nd\": \"tones\",\n \"od\": \"tuplet\",\n \"pd\": \"beam_group\",\n \"qd\": \"renderId\",\n \"rd\": \"numNotes\",\n \"sd\": \"totalTicks\",\n \"td\": \"stemTicks\",\n \"ud\": \"durationMap\",\n \"vd\": \"bracketed\",\n \"wd\": \"ratioed\",\n \"xd\": \"location\",\n \"yd\": \"systemGroups\",\n \"zd\": \"leftConnector\",\n \"ae\": \"padLeft\",\n \"be\": \"customStretch\",\n \"ce\": \"engravingFont\",\n \"de\": \"customProportion\",\n \"ee\": \"columnAttributeMap\",\n \"fe\": \"tempo\"\n }`\n ;\n return JSON.parse(_tm);\n }",
"function requestTokenBatchAnn(){\n return new Promise(resolve => {\n //get current datetime in Europe/Rome GMT\n let date = new Date(new Date().toLocaleString(\"it-IT\", {timeZone: \"Europe/Rome\"})); // IMPORTANT using Europe/Rome here and also in the backend storage\n let d = date.getDate();\n if(+d < 10)\n d = '0' + d;\n let h = date.getHours();\n if(+h < 10)\n h = '0' + h;\n\n let secret = d + 'cogni' + h; // secret pwd to pass to our backend storage in order to get a token\n //console.log('Requesting token to ' + backendStorage + 'getTokenBatchAnn.php?secret=' + secret ); // debugging purpose\n\n fetch(backendStorage + 'getTokenBatchAnn.php?secret=' + secret)\n .then(php_response => {\n php_response.json().then(php_JSONresp =>{\n //console.log('Received from the server the following json obj for token'); // debugging purpose\n //console.log(php_JSONresp); // debugging purpose\n resolve(php_JSONresp['btoken']);\n });\n });\n });\n}",
"function populateTrashedSystemUsers() {\n\tvar searchSystemUser = $(\"#id_input_search_deleted_system_user\").val();\n\trequest_url = SYSTEM_USERS_URL;\n\trequest_params = ACTION_TYPE + \"=\" + ACTION_QUERY + \"&\" + SEARCH_KEY + \"=\"\n\t\t\t+ searchSystemUser;\n\trequest_intent = INTENT_QUERY_DELETED_SYSTEM_USERS;\n\tsendPOSTHttpRequest(request_url, request_params, request_intent);\n}",
"function populateSystemUsers() {\n\tvar searchSystemUser = $(\"#id_input_search_system_user\").val();\n\trequest_url = SYSTEM_USERS_URL;\n\trequest_params = ACTION_TYPE + \"=\" + ACTION_QUERY + \"&\" + SEARCH_KEY + \"=\"\n\t\t\t+ searchSystemUser + \"&\" + RESULT_FORMAT + \"=\"\n\t\t\t+ RESULT_FORMAT_TABLE_ROWS;\n\trequest_intent = INTENT_QUERY_SYSTEM_USERS;\n\tsendPOSTHttpRequest(request_url, request_params, request_intent);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function // ajax post call, delete existing image, called if chosen from saveObject function. edit case; | function removeExistingImage(id, which) {
$.ajax({
url: 'Controllers/existEditor/' + which + 'Controller.php',
type: "POST",
data: {id: id, removeExistingImage: true},
success: function (response) {
//no need to response in this case.
},
});
} | [
"function doDeletePhoto(x) {\n let data = { cmd:'delete', PRID: propData.PRID, idx: x };\n var dat = JSON.stringify(data);\n var url = '/v1/propertyphotodelete/' + propData.PRID + '/' + x;\n\n return $.post(url, dat, null, \"json\")\n .done(function(data) {\n // if (data.status === \"success\") {\n // }\n if (data.status === \"error\") {\n w2ui.propertyGrid.error('ERROR: '+ data.message);\n return;\n }\n var id = \"phototable\" + x;\n var image = document.getElementById(id);\n if (image == null) {\n console.log('ERROR: could not find image: ' + id);\n return;\n }\n image.src = '/static/html/images/building-100.png';\n image.width = 100;\n w2ui.propertyForm.record[\"Img\"+x] = \"\";\n })\n .fail(function(data){\n w2ui.propertyGrid.error(\"Save RentableLeaseStatus failed. \" + data);\n });\n}",
"function delete_image(image_id){\n console.log(image_id)\n $.ajax({\n url: '/jb/ajax/delete-image/',\n data:{\n 'image_id':image_id,\n },\n dataType:'json',\n success:function(data){\n if (data.result){\n location.reload();\n console.log(data.result)\n }\n },\n error: function(XMLHttpRequest, textStatus, errorThrown) {\n alert(\"Status: \" + textStatus); alert(\"Error: \" + errorThrown);\n }\n\n });\n }",
"function del() {\n\t\tif( $( '#img' ).data( 'pngPath' ) !== undefined ) {\n\t\t\t$.post( \"delete.php\", { path: $( '#img' ).data( 'path' ), pngPath : $( '#img' ).data( 'pngPath' ) } ); \n\t\t}\n\t\telse {\n\t\t\t$.post( \"delete.php\", { path: $( '#img' ).data( 'path' ) } ); \n\t\t}\n\t}",
"function deleteImage(imgPath, name)\n{\n $.ajax({\n type: \"POST\",\n url: \"index.php\",\n data: {delimg: imgPath},\n cache: false,\n success: function(result){\n document.getElementById(name).remove();\n document.getElementById(\"mainImageForm\").reset();\n }\n });\n}",
"function deleteAltImgById(e, id) {\n $(e.currentTarget).parent('.pip').remove();\n $.ajax({\n method: 'POST',\n url: window.delete_alt_img_by_id,\n data: {\n _token: $('meta[name=\"csrf-token\"]').attr('content'),\n id: id,\n },\n success: function (result) {\n One.helpers('notify', {type: 'success', icon: 'fa fa-check mr-1', message: result})\n },\n });\n}",
"function deleteImgPost(){\r\n\t\tpost_selected_img.setAttribute(\"src\", \"\");\r\n\t\tpost_img. files = null;\r\n\t}",
"function delete_image_for_event(event_id, image_id, callback) {\n var url = \"/events/\" + event_id + \"/images/\"+image_id;\n $.ajax_delete(url, callback);\n}",
"function deleteImage (url, imageId) {\n $.ajax({\n type: 'POST',\n url: url,\n data: { imageId: imageId },\n success: function (response) {\n $('#image-' + imageId).remove();\n },\n error: function (response) {\n alert(\"Failed to delete image: \\n\" + response.responseJSON.message);\n }\n });\n }",
"function deletePreview(btn){\n try{\n var id = $(btn).attr('id-img');\n //delete image preview\n $(btn).parents('.item-img').remove();\n //delete image crop\n $('.crop-item' + id).remove();\n //if not have file then reset\n if($('.item-img').length == 0){\n $('.div-upload').removeClass('had-file');\n $('.file').val('');\n $('#title-thumb').addClass('hidden');\n }\n //delete info of file\n for(var i = 0, length = mainImg.length; i < length; i++){\n if(mainImg[i].id + '' == id){\n mainImg.splice(i, 1);\n break;\n }\n }\n }\n catch(e){\n alert('deletePreview: ' + e.message);\n }\n}",
"function deleteCoverPhoto(element)\n{\n\t$('div#cover_photo').append('<img class=\"cover_photo_loading\" style=\"position: absolute;top:100px; left:400px; z-index:4;\" src=\"'+IMAGE_PATH+'/loading_medium_purple.gif\"/>');\n\t$('ul.cover_photo_menu').hide();\n\t\n\tvar cover_img_name = $('div#cover_photo').children('img').attr('rel1');\n\t$(element).attr('rel','');\n\tjQuery.ajax\n\t({\n url: \"/\" + PROJECT_NAME + \"profile/delete-cover-photo\",\n type: \"POST\",\n dataType: \"json\",\n data : { 'cover_img_name':cover_img_name },\n success: function(jsonData) \n {\n \t$('img.cover_photo_loading').hide();\n \t\t$('div#cover_photo img.cvr_img#cvr_photo_img').attr('src',IMAGE_PATH+'/cover-female-default.png');\t\n \t\t$('div#cover_photo img.cvr_img#cvr_photo_img').attr('rel1','');\t\n \t\t$('div#cover_photo img.cvr_img').removeClass('my_cover_photo');\t\t\n \t\t$('div#cover_photo img.cvr_img').addClass('my_default_cover_photo');\n \t\t//Dragging disabled.\n \t\t$('div#cover_photo img#cvr_photo_img').draggable( 'disable' );\n \t\t\n \t\t//default cover photo css.\n \t\t$('div#cover_photo img.cvr_img').css('top','0');\t\n \t\t$('div#cover_photo img.cvr_img').css('left','0');\t\n \t\t$('div#cover_photo img.cvr_img').css('opacity','1');\t\n \t\t$('div#cover_photo img.cvr_img').css('min-height','202px');\t\n }\n \n\t});\n}",
"function removeImage(){\n\tvar filepath=$(\"#remImg\").val();\n\t$('#dvLoading').show();\n\t$.ajax({\n\t\turl : \"/\" + PROJECT_NAME + \"profile/remove-image\",\n\t\tmethod : \"POST\",\n\t\tdata : \"filepath=\"+filepath,\n\t\ttype : \"post\",\n\t\tdataType : \"json\",\n\t\tsuccess : function(jsonData) {\n\t\t\tif(jsonData){\n\t\t\t\t$(\"#profileimg\").html(\"Upload\");\n\t\t\t\t$(\"#sremid\").hide();\n\t\t\t\t$(\"#profileLogo\").attr(\"src\",\"/\" + PROJECT_NAME + \"public/images/profile/\"+jsonData.image);\n\t\t\t\t$(\"#profileLogo_small\").attr(\"src\",\"/\" + PROJECT_NAME + \"public/images/profile/\"+jsonData.smallImage);\n\t\t\t\t$('#dvLoading').hide();\n\t\t\t\t$(\"#remImg\").val(\"\");\t\n\t\t\t\t$(\".alert-box\").remove();\n\t\t\t\tshowDefaultMsg( \"Profile image successfully removed.\", 1 );\n\t\t\t\t$(\".profile-img-closed\").removeClass(\"profileImg\");\n \t$(\".profile-img\").removeClass(\"profileImg\");\n \tclickForImagePreview();\n\t\t\t}\n\t\t}\n\t});\n}",
"function deleteImage(id) {\n $.ajax({\n method: \"DELETE\",\n url: \"/api/images/\" + id\n }).then(function() {\n getImages();\n });\n }",
"function deletePhoto(id) {\n\turl = \"deletePhoto.php?id=\" + id;\n\tdoAjaxCall(url, \"updateMain\", \"GET\", true);\n}",
"function deleteImage(imageId) {\n $(imageId).attr('src', 'CSS/itemimage/deleted.jpg');\n}",
"function deletePreview(btn){\n try{\n var id = $(btn).attr('id-img');\n\n //delete image preview\n $(btn).parents('.item-img').remove();\n\n //delete image crop\n $('.crop-item' + id).remove();\n\n //if not have file then reset\n if($('.item-img').length == 0){\n $('.div-upload').removeClass('had-file');\n $('.upload_file_event_detail').val('');\n $('#title-thumb').addClass('hidden');\n }\n\n //delete info of file\n for(var i = 0, length = mainImg.length; i < length; i++){\n if(mainImg[i].id + '' == id){\n mainImg.splice(i, 1);\n break;\n }\n }\n } catch(e){\n console.log('deletePreview: ' + e.message);\n }\n}",
"function deleteImage() {\n $(\"#redact-image-quest\").children().remove();\n questRedactImage = null;\n}",
"function handleImageDelete() {\n console.log(this);\n var currentImage = $(this)\n .parent()\n .data(\"image\");\n deleteImage(currentImage.id);\n }",
"function deleteImage(url) {\r\n\t\tclearError();\r\n\t\t//check if url is valid\r\n\t\tif(isValidUrl(url)) {\r\n\t\t\t//check if url is on planning area\r\n\t\t\tif($(url)) {\r\n\t\t\t\t//delete the object\r\n\t\t\t\t$(url).remove();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t//add an error to the error text\r\n\t\t\t\t$(\"error\").innerHTML = \"Error image with specified url is not in planning area\";\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\t//add an error to the error text\r\n\t\t\t$(\"error\").innerHTML = \"Error url invalid\";\r\n\t\t}\r\n\t\t\r\n\t\t\r\n\t}",
"function deleteSingleThumb(object) {\n\n //the deletedImgNum corresponds to the arrayIndex of the image in currentAlbum.images\n var deletedImgNum = (object.id.substring(11))*1;\n\n //user deletes the current image in the single image view from the multi image view\n if(deletedImgNum===currentImgNum) {\n\n console.log(\"This is a problem\");\n }\n\n //delete image from the array of images\n currentAlbum.images.splice([deletedImgNum],1);\n\n //**********************************************************************************************************\n //********************* make server call to remove the image from the database *****************************\n //**********************************************************************************************************\n\n //remove the thumb from the DOM\n $('#thumb' + deletedImgNum).fadeOut('slow', function(){\n $('#thumb' + deletedImgNum).remove();\n\n //redraw the thumbs\n createImageThumbs();\n\n //update the length of the album\n $(\"#numImages\").html(currentAlbum.images.length);\n\n //set slider values\n setSliderValues(slide, (currentAlbum.images.length-1), currentImgNum, currentAlbum.images[currentImgNum].time);\n });\n\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The cell typically contains a threerow table: order heading, description, and organization information. | function createOrderInfo(oiCell) {
var rows = oiCell.firstChild.rows,
ordInfo = rows.item(0),
descInfo = rows.item(1),
orgInfo = rows.item(2),
order = {},
a;
// Order heading
if(ordInfo) {
order.title = ordInfo.textContent.replace(/\xA0/g, ' ');
}
// Order description
if(descInfo) {
a = descInfo.querySelector('a');
if(a) {
order.detail = {url: a.href, title: a.text};
}
}
// Organization info
if(orgInfo) {
a = orgInfo.querySelector('a');
if(a) {
order.org = {url: a.href, title: a.text};
}
}
return order;
} | [
"function formatExpandableShortOrders ( rowData ) {\n return '<table class=\"inner-table\">'+\n '<tr>'+\n '<td class=\"column-one\"></td>'+\n '<td class=\"order-sumbmitted-column\"><div class=\"label-text\">Submitted</div> <div class=\"data-text\">'+rowData[2]+'</div></td>'+\n '</tr>'+\n '</table>';\n}",
"function cell() {\n\t\tvar td = $(\"<td>\");\n\t\trow.append(td);\n\t\treturn td;\n\t}",
"function addCells(row,tidx,tend,textLines,change){if(tidx < tend){row.appendChild(telt(\"th\",(tidx + 1).toString()));row.appendChild(ctelt(\"td\",change,textLines[tidx].replace(/\\t/g,' ')));return tidx + 1;}else {row.appendChild(document.createElement(\"th\"));row.appendChild(celt(\"td\",\"empty\"));return tidx;}}",
"function renderCell(cell, align, isHeader) {\n var type = isHeader ? 'th' : 'td';\n var tag = align\n ? '<' + type + ' style=\"text-align:' + align + '\">'\n : '<' + type + '>';\n\n var content = MarkupIt.JSONUtils.decode(cell.content);\n var innerHTML = MarkupIt.render(cellSyntax, content);\n\n return tag + innerHTML + '</' + type + '>\\n';\n}",
"function addElementInCell(obj,type,data,parent,key)\n{\n var cellName;\n if(data.cellAttributes.cellName)\n {\n cellName=data.cellAttributes.cellName;\n }\n else\n {\n cellName=\"cell\";\n }\n addElement(obj,\"td\",data.cellAttributes,parent,cellName);\n addElement(obj,type,data,obj.cell,key);\n}",
"function renderOrderTable(order) {\n const tableBody = renderTableBody(order);\n return `<table class=\"demo-content--full demo-content--separated mdl-data-table mdl-shadow--2dp mdl-color--white\">\n ${TABLE_HEAD}\n ${tableBody}\n </table>`;\n}",
"_renderCellInfo($$) {\n const {index, format} = this.props.meta\n const {header} = this.props\n const node = this.props.node\n if (!index && !format && node.rowspan < 2 && node.colspan < 2) {\n return null\n }\n\n const cellInfo = []\n const rowspan = node.rowspan || 1\n const colspan = node.colspan || 1\n\n if(rowspan > 1 || colspan > 1) {\n cellInfo.push(`${colspan}x${rowspan}`)\n }\n if(header) {\n cellInfo.push(format, index ? '*' : '')\n }\n\n return $$('div', {class: `cell-info`}, cellInfo.join(' '))\n }",
"function parseTableCellLine(elt) {\n var th = '';\n var argdelims = {TABLEROW:true,TABLEEND:true,PIPE:true,CPIPE:true,BANG:true,BANG2:true,PIPE2:true};\n var celldelims = {TABLEROW:true,TABLEEND:true,CPIPE:true,BANG:true,BANG2:true,PIPE2:true};\n var celltokensFirst = cloneTokens(outerTokensFirst);\n celltokensFirst[PRE] = false; // don't recognize leading spaces\n\n do {\n th += '<'+elt;\n var s = trimHTML(parseP(argdelims,celltokensFirst,outerTokensNext));\n // if we stopped at a pipe then we parsed arguments,\n // otherwise we parsed an entire cell content\n // and are at the table/row end or one of the\n // next cell markers\n if (nextToken==PIPE) {\n th += ' ' + trim(s);\n // the cell itself is then everything up to\n // either a celldiv on the same line, or a\n // pipe on a new line\n s = trimHTML(parseP(celldelims,celltokensFirst,outerTokensNext));\n }\n // finish constructing cell\n th += '>'+s+'</'+elt+'>';\n\n // and keep parsing cells while we're still hitting\n // celldivs\n } while (nextToken==BANG2 || nextToken==PIPE2);\n\n return th;\n}",
"function CellText() {}",
"function generateFormattedCell(job) {\n var td = _td_.cloneNode(false);\n\n if (job && job.lastCompletedBuild) {\n // last build time and status\n var info = _span_.cloneNode(false);\n info.setAttribute('class', job.lastCompletedBuild.result.toLowerCase());\n var lastCompletedBuildDate = new Date(job.lastCompletedBuild.timestamp);\n info.appendChild(document.createTextNode([\n lastCompletedBuildDate.getUTCFullYear(),\n twoDigits(lastCompletedBuildDate.getUTCMonth() + 1),\n twoDigits(lastCompletedBuildDate.getUTCDate())\n ].join('-')));\n info.appendChild(_br_.cloneNode(false));\n info.appendChild(document.createTextNode(\n twoDigits(lastCompletedBuildDate.getUTCHours()) + ':' +\n twoDigits(lastCompletedBuildDate.getUTCMinutes()) + ' UTC'\n ));\n td.appendChild(info);\n td.appendChild(_br_.cloneNode(false));\n\n // Git hash\n var commit = document.createElement('i');\n commit.appendChild(document.createTextNode(shortHash(job.lastCompletedBuild.description) || 'unknown commit'));\n td.appendChild(commit);\n td.appendChild(_br_.cloneNode(false));\n\n // link to full jenkins job detail\n var links = _span_.cloneNode(false);\n links.setAttribute('class', 'tiny');\n var href = document.createElement('a');\n href.setAttribute('href', job.lastCompletedBuild.url);\n href.appendChild(document.createTextNode('details'));\n links.appendChild(href);\n td.appendChild(links);\n td.appendChild(_br_.cloneNode(false));\n\n // check if the last completed build result is not 'SUCCESS'\n if (job.lastCompletedBuild.result !== 'SUCCESS') {\n var fail_url = '', failingSinceNumber = '1', fail_since_hash = 'n/a';\n if (job.lastCompletedBuild.result === 'FAILURE')\n failingSinceNumber = (job.lastSuccessfulBuild ? job.lastSuccessfulBuild.number + 1: '1').toString();\n else if (job.lastCompletedBuild.result === 'UNSTABLE')\n failingSinceNumber = (Math.max(job.lastStableBuild ? job.lastStableBuild.number : 0, job.lastFailedBuild ? job.lastFailedBuild.number : 0) + 1).toString();\n fail_url = '/job/' + job.name + '/' + failingSinceNumber + '/api/json?tree=description';\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", \"https://ci.FreeBSD.org\" + fail_url, false);\n xhr.send();\n if (xhr.status === 200)\n fail_since_hash = JSON.parse(xhr.responseText).description;\n else\n throw new Error(\"Failed to fetch data from \" + fail_url + \". Status: \" + xhr.status);\n\n var failingSince = document.createElement('i');\n failingSince.appendChild(document.createTextNode(\n '(failing since ' + (fail_since_hash === '<html>' ? 'unknown commit' : shortHash(fail_since_hash)) + ')'\n ));\n td.appendChild(failingSince);\n td.appendChild(_br_.cloneNode(false));\n var links = _span_.cloneNode(false);\n links.setAttribute('class', 'tiny');\n var lastSuccessful = document.createElement('a');\n lastSuccessful.setAttribute('href', 'https://ci.FreeBSD.org' + fail_url.split('api')[0]);\n lastSuccessful.appendChild(document.createTextNode('details'));\n links.appendChild(lastSuccessful);\n td.appendChild(links);\n }\n } else {\n td.appendChild(document.createTextNode('-'));\n }\n\n return td;\n}",
"function TableCell(type, value) {\n this.divUID = Math.random().toString().slice(2); // random UID\n this.rdfType = type; // 'literal' or actual type like 'http://xmlns.com/foaf/0.1/Person'\n this.value = value; // '45.5' or 'http://g-node.org/0.1#BrainRegion:1'\n this.directObjProperties = {}; // {'gnode:isAboutAnimal': 'gnode:Preparation', ...}\n this.reverseObjProperties = {}; // {'gnode:isAboutAnimal': 'gnode:Preparation', ...}\n\n this.hasRelations = function() {\n return Object.keys(this.directObjProperties).length > 0 || Object.keys(this.reverseObjProperties).length > 0;\n }\n}",
"function UnderlinedCell(inner) {\n this.inner = inner\n}",
"get cellTagName() {\n return 'div';\n }",
"function addTableHeading() {\n// make subheading title visible\n msnTableHdrObj.setAttribute(\"class\",\"\");\n\n// insert the table headings into the first row\n let row = msnTableObj.insertRow();\n msnTableObj.appendChild(row);\n\n let rowStatus = row.insertCell();\n rowStatus.outerHTML = \"<th>Status</th>\";\n\n let launchTsp = row.insertCell();\n launchTsp.outerHTML = \"<th>Launch Time (UTC)</th>\";\n\n let lspAbbrev = row.insertCell();\n lspAbbrev.outerHTML = \"<th>Provider</th>\";\n\n let launchNm = row.insertCell();\n launchNm.outerHTML = \"<th>Description</th>\";\n\n let launchID = row.insertCell();\n launchID.outerHTML = \"<th class='hidden'>ID</th>\";\n}",
"get tableHTML() {\n return (`\n <tr>\n <td class=\"item-name\" data-id=\"${this.id}\" data-type=\"name\"> ${this.name} </td>\n <td class=\"item-price\" data-id=\"${this.id}\" data-type=\"price\">${\"$\" + this.price.toFixed(2)} </td>\n <td class=\"item-quantity\" data-id=\"${this.id}\" data-type=\"quantity\"> ${this.quantity} </td>\n <td class=\"item-category\" data-id=\"${this.id}\" data-type=\"category\"> ${this.category} </td>\n </tr>\n `)\n }",
"function insertColumnHeadingsRow(theResultsTable) {\r\n\t\r\n theResultsTable.innerHTML = \"<tr><th>Item Number</th><th>Item Description</th><th>Item Stock Amount</th></tr>\";\r\n}",
"generateCell(parent, data, cell) {\n const tableCellEl = document.createElement('td');\n tableCellEl.className = 'currency-table-cell';\n if (cell !== 'name') tableCellEl.classList.add('align-right');\n const text = document.createTextNode(data);\n tableCellEl.appendChild(text);\n parent.appendChild(tableCellEl);\n }",
"makeTableBody() {\n var rows = [];\n for (var row = 1; row <= 9; row++) {\n \n // Each row consists of array of cells\n var cells = [];\n \n // The first cell of the row is the header\n cells.push(<Cell key={row+'.'+0} isHeader={true} rowId={row} mouseLoc={this.state.highlight} onMouseEnterCell={this.onMouseEnterCell.bind(this)} onMouseLeaveCell={this.onMouseLeaveCell.bind(this)}/>)\n\n // Make the rest of the cells of the row\n for (var col = 1; col <= 9; col++) {\n cells.push(<Cell key={row+'.'+col} rowId={row} colId={col} mouseLoc={this.state.highlight} onMouseEnterCell={this.onMouseEnterCell.bind(this)} onMouseLeaveCell={this.onMouseLeaveCell.bind(this)}/>)\n }\n\n rows.push(<tr key={\"row\"+row}>{cells}</tr>);\n }\n\n return <tbody>{rows}</tbody>;\n }",
"function createTableCell(cellData, position) {\n switch (position) {\n case \"thead\":\n return `<th>${cellData}</th>`;\n break;\n default:\n return `<td>${cellData}</td>`;\n break;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable selection of marker pages already in coordinates' table. Page selector is an Asm select. | function disableMarkerPagesSelection() {
var $imCoordinatesTables = $('div.image_marker_main_wrapper table.InputfieldImageMarkers');
$imCoordinatesTables.each(function () {
var $table = $(this);
var $parent = $table.parents('div.image_marker_main_wrapper');
var $allSelected = $table.find("input.marker_info").map(function () {
return $(this).val();
}).get();
$parent.find(".marker_add_infopages option:not(:selected):not([value='0'])").each(function () {
if ($.inArray($(this).val(), $allSelected) != -1) $(this).attr('selected', true);
// @note: this will cause newly deleted items to be sent also as newly added since in $this, they will be marked as 'selected'
// we deal with that server-side
});
});
} | [
"function disable_selection_mode() {\n $('#add-annotation').show();\n $('#cancel-annotation').hide();\n $('.docviewer-annotations').show();\n $('.docviewer-pages').css('overflow', 'auto');\n $('.docviewer-cover').css('cursor', '-webkit-grab');\n $('.docviewer-cover').die('mousedown');\n $('.docviewer-cover').die('drag');\n $('.docviewer-cover').die('mouseup');\n $('#annotation-area').remove();\n $('#form-annotation').hide();\n mydocviewer.dragReporter.setBinding();\n }",
"function disablePointSelection(){\r\n\taddPointMode = false;\r\n}",
"function fix_selection_on_page_change (data_table) {\n data_table.on('page', function (event) {\n var oTT = TableTools.fnGetInstance(data_table.get()[0]);\n oTT.fnSelectNone();\n });\n}",
"skipToDirectSelectCallback() {\n const { draw: { drawInstance: draw } } = this.get('map');\n const mode = draw.getMode();\n const [selectedID] = draw.getSelectedIds();\n const { features: [{ geometry: { type } = {} } = {}] } = draw.getSelected();\n\n // can't direct select a point\n if (selectedID && type !== 'Point' && mode === 'simple_select') {\n draw.changeMode(this.get('directSelectMode'), { featureId: selectedID });\n }\n\n this.set('tool', mode);\n }",
"function disableSelection(){\n\tif(window.getSelection){\n\t\tif(navigator.userAgent.indexOf('AppleWebKit/') > -1){\n\t\t\tif(window.devicePixelRatio) {\n\t\t\t\twindow.getSelection().removeAllRanges();\n\t\t\t} else {\n\t\t\t\twindow.getSelection().collapse();\n\t\t\t}\n\t\t}else{\n\t\t\twindow.getSelection().removeAllRanges();\n\t\t}\n\t}else if(document.selection){\n\t\tif(document.selection.empty){\n\t\t\tdocument.selection.empty();\n\t\t}else if(document.selection.clear){\n\t\t\tdocument.selection.clear();\n\t\t}\n\t}\n\n\tvar element = document.body;\n\tif(navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1){\n\t\telement.style.MozUserSelect = \"none\";\n\t}else if(navigator.userAgent.indexOf('AppleWebKit/') > -1){\n\t\telement.style.KhtmlUserSelect = \"none\"; \n\t}else if(!!(window.attachEvent && !window.opera)){\n\t\telement.unselectable = \"on\";\n\t\telement.onselectstart = function() {\n\t\t return false;\n\t\t};\n\t}\n}",
"function deselectMarkers() {\n\t\t\t\td3.select(container).selectAll('circle.measure-marker')\n\t\t\t\t\t.attr('fill', function(d) { return colour(d.measure[measureIdx].name); })\n\t\t\t\t\t.classed('selected', false);\n\t\t\t}",
"function enable_selection_mode() {\n $('#add-annotation').hide();\n $('#cancel-annotation').show();\n $('.docviewer-annotations').hide();\n mydocviewer.dragReporter.unBind();\n bind_mouse_events();\n }",
"function removeSelectionHighlight() {\r\n hideSelectionRect();\r\n hideRotIndicator();\r\n }",
"function disable_point_searching() {\n\tsobekcm_map.disable_point_search();\n}",
"function deselectMarkers() {\n\t\t\t\td3.select(container).selectAll('circle.measure-marker')\n .transition().duration(200)\n\t\t\t\t\t.attr('fill', function(d) { return getColour(d); })\n .attr('r', function(d) {\n return (columnMap.measure.length > 0 ? size(+d.measure[measureIdx].value) : size(0));\n })\n .attr('stroke-width', config.stroke)\n .attr('fill-opacity', config.opacity);\n\t\t\t\td3.select(container).selectAll('circle.measure-marker').classed('selected', false);\n tooltip.hide();\n\t\t\t}",
"function unblockTextSelection() {\n global_document__WEBPACK_IMPORTED_MODULE_7___default.a.onselectstart = function () {\n return true;\n };\n}",
"function unblockTextSelection(){global_document__WEBPACK_IMPORTED_MODULE_1___default.a.onselectstart=function(){return true;};}",
"removeNavigationFromMap() {\n this.map.dragRotate.disable();\n this.map.dragPan.disable();\n this.map.touchZoomRotate.disable();\n this.map.doubleClickZoom.disable();\n this.map.scrollZoom.disable();\n }",
"function disable_text_selection() {\n \n if ( typeof document.body.onselectstart != 'undefined' ){\n document.body.onselectstart = function(){ return false; };\n } else if ( typeof document.body.style.MozUserSelect != 'undefined' ) {\n document.body.style.MozUserSelect = 'none';\n } else if ( typeof document.body.style.webkitUserSelect != 'undefined' ) {\n document.body.style.webkitUserSelect = 'none';\n } else {\n document.body.onmousedown = function(){ return false; };\n }\n\n document.body.style.cursor = 'default';\n \n }",
"function unselectByClick() {\n var points = this.getSelectedPoints();\n if (points.length > 0) {\n points.forEach((point) => {\n point.select(false);\n });\n }\n }",
"static resetCurrentlySelecting() {\n const manager = TextNavigationManager.instance;\n manager.currentlySelecting_ = false;\n manager.manageNavigationListener_(false /** Removing listener */);\n manager.selectionStartIndex_ = TextNavigationManager.NO_SELECT_INDEX;\n manager.selectionEndIndex_ = TextNavigationManager.NO_SELECT_INDEX;\n if (manager.currentlySelecting_) {\n manager.setupDynamicSelection_(true /* resetCursor */);\n }\n EventGenerator.sendKeyPress(KeyCode.DOWN);\n }",
"function disablePen(){if(!_enabled){return;}_enabled=false;document.removeEventListener('mousedown',handleDocumentMousedown);document.removeEventListener('keyup',handleDocumentKeyup);(0,_utils.enableUserSelect)();}",
"function deselect() {\n\tfor (var i=1;i<cellNumber+1;i++) {currentSelectedCells[i]=false;}\n\tpaintAll();\n\tdisplay();\n}",
"function clearSelection() {\r\n map.deselectCountry();\r\n pc1.deselectLine();\r\n donut.deselectPie();\r\n sp1.deselectDot();\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts a new line in the console. | function _insertNewLine()
{
$(_consoleSelector).val($(_consoleSelector).val() + '\n' + _hostAndPrompt);
// Set the limit for erasing the conosole to the beginning of the newline.
_eraseLimit = $(_consoleSelector).val().length;
} | [
"function newLine () {\n console.log('\\n');\n}",
"insertLinebreak() {\n this.insertText('\\n');\n }",
"function insertLine( text ) {\n document.writeln( text );\n }",
"insertLinebreak() {\n let promptCell = this.promptCell;\n if (!promptCell) {\n return;\n }\n promptCell.editor.newIndentedLine();\n }",
"newLine(line) {\r\n if (this.active) {\r\n this.line++;\r\n this.word=0;\r\n this.syllable=0;\r\n this.output(\"► Line \" + this.line + \": \" + line);\r\n }\r\n }",
"function insertLineBreak() {\n lineWidths.push(lineWidth);\n poem = poem.concat(\"\\n\");\n lineWidth = width/2 + 20;\n period();\n}",
"newIndentedLine() {\n this.execCommand('newlineAndIndent');\n }",
"function InsertLine() {\r\n var range = RTE.Cursor.get_range();\r\n range.deleteContent();\r\n var selection = range.parentElement();\r\n if (!selection) {\r\n return;\r\n }\r\n var line = selection.ownerDocument.createElement('hr');\r\n range.insertNode(line);\r\n RTE.Cursor.get_range().moveToNode(line);\r\n RTE.Cursor.update();\r\n}",
"function newPromptLine() {\n let t = document.createTextNode(`${user}@${host}:${dir.getName()}$ `);\n let br = document.createElement(\"br\");\n curr_line = \"\";\n element.appendChild(br);\n element.appendChild(t);\n updateScroll();\n}",
"logLine() {\n this.log.apply(console, arguments);\n this.log('\\n');\n }",
"function addEmptyLine() {\n outputEditor.session.insert({\n row: outputEditor.session.getLength(),\n column: 0\n }, '\\n');\n}",
"function newline(line, column) {\n\tlog(`insert newline at (${line}, ${column})`)\n\tlet content = lines[line]\n\tlet left = content.slice(0, column)\n\tlet right = content.slice(column, content.length)\n\tlines[line] = left\n\tlines.splice(line + 1, 0, right)\n\n\tcursor.x = 0\n\tcursor.y++\n}",
"function putline() {\n document.write(\"<br/>\");\n}",
"function add_terminal_line(msg, type) {\n\n // create and append the output line\n let line = document.createElement(\"div\");\n line.innerHTML = msg;\n line.setAttribute(\"class\", `terminal-line ${type}`);\n let th = document.getElementById(\"terminal-history\");\n th.appendChild(line);\n\n // auto-scroll\n document.body.scrollTop = document.body.scrollHeight;\n}",
"function addDottedLine() {\n BluetoothPrintManager.addToPrintBuffer(\"-------------------------------\", { addLF: true });\n}",
"function addLine() {\n _createLine()\n}",
"insertLine(text) {\n let position;\n\n if (this._codeMirror.hasFocus()) {\n const cursor = this._codeMirror.getCursor();\n const line = this._codeMirror.getLine(cursor.line);\n position = CodeMirror.Pos(cursor.line, line.length - 1);\n\n if (line.length !== 0) {\n /*\n * If the current line has some content, insert the new text on\n * the line after it.\n */\n text = '\\n' + text;\n }\n\n if (!text.endsWith('\\n')) {\n text += '\\n';\n }\n } else {\n position = CodeMirror.Pos(this._codeMirror.lastLine());\n text = '\\n' + text;\n }\n\n this._codeMirror.replaceRange(text, position);\n }",
"function newLine(){\n $(settings.el).delay(settings.speed).queue(function (next){\n var currTextNoCurr = $(this).html().substring(0, $(this).html().length - 1);\n $(this).html(currTextNoCurr + '<br>');\n next();\n\n // we are done, remove from queue\n settings.queue = settings.queue - 1;\n $(settings.mainel).trigger('typewriteNewLine');\n });\n }",
"insertLine(text) {\n if (this._editor) {\n this._editor.insertLine(text);\n } else {\n if (this._value.endsWith('\\n')) {\n this._value += text + '\\n';\n } else {\n this._value += '\\n' + text;\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removing objects outside of reachable map and those whose should be destroyed according to game logic | function deleteNotNeededGameObjects() {
bulletInfos = bulletInfos.filter(bi => bi.bullet.damage > 0 && !isOutsideOfReachableMap(bi.location));
playerInfos = playerInfos.filter(pi => pi.player.hp > 0 && !isOutsideOfReachableMap(pi.location));
barrierInfos = barrierInfos.filter(bi => bi.barrier.hp > 0 && !isOutsideOfReachableMap(bi.location));
} | [
"function editorDestroyAllMapObjects() {\n edPlayerStart.destroy();\n edPlayerStart = null;\n edExit.destroy();\n edExit = null;\n edTiles.forEach(o => {\n o.forEach(s => s.destroy());\n });\n edTiles = [];\n edEnemies.forEach(o => { if (o) o.destroy(); });\n edEnemies = [];\n edPickups.forEach(o => { if (o) o.destroy(); });\n edPickups = [];\n edSigns.forEach(o => { if (o) o.destroy(); });\n edSigns = [];\n}",
"function cleanWarpObjects() {\n left_bar.set(0.0);\n right_bar.set(0.0);\n\n scene.children.forEach( (object) => {\n // if(object.name == 'sphere_scene') {\n // // console.log('removed sphere');\n // scene.remove(object);\n // }\n\n if(object instanceof THREE.Group) {\n object.userData.touched = false;\n object.visible = false;\n // scene.remove(object);\n }\n });\n\n // for (let i = scene.children.length - 1; i >= 0 ; i--) {\n // if(scene.children[i] instanceof THREE.Group) {\n // var object = scene.children[i];\n // object.visible = false;\n // // scene.remove(object);\n // }\n // }\n}",
"function deleteObjects() {\n clearObjects();\n mapObjects = [];\n}",
"function removeOutOfBoundObj() {\n gameState.enemies.getChildren().forEach(enemy => {\n if (enemy.x > config.width + HALF_OBJ_PIXEL || enemy.x < -HALF_OBJ_PIXEL) {\n gameState.enemies.remove(enemy);\n }\n });\n gameState.platformsEven.getChildren().forEach(platform => {\n if (platform.x > config.width + HALF_OBJ_PIXEL * 2 || platform.x < -HALF_OBJ_PIXEL * 2) {\n gameState.platformsEven.remove(platform);\n }\n });\n gameState.platformsOdd.getChildren().forEach(platform => {\n if (platform.x > config.width + HALF_OBJ_PIXEL * 2 || platform.x < -HALF_OBJ_PIXEL * 2) {\n gameState.platformsOdd.remove(platform);\n }\n });\n}",
"function cleanOffscreenObjects() {\n for (let [k,v] of objects.entries()) {\n if ((v.y > GAME_HEIGHT) || (v.x < 0) || (v.x > GAME_WIDTH)) {\n objects.delete(k)\n }\n }\n }",
"function removeObjects(){\n\tfor(var n=0; n<gameData.planes.length;n++){\n\t\tvar curAirplane = gameData.planes[n];\n\t\tif(curAirplane.destroy){\n\t\t\tgameData.planes.splice(n,1);\n\t\t\tn = gameData.planes.length;\n\t\t}\n\t}\t\n}",
"function cleanMap() {\n mapObjects.forEach(function(item) {\n item.setMap(null);\n });\n mapObjects = [];\n}",
"pruneMaps() {\n this.featureToCesiumMap = objectUtils.prune(this.featureToCesiumMap);\n this.geometryToCesiumMap = objectUtils.prune(this.geometryToCesiumMap);\n this.geometryToLabelMap = objectUtils.prune(this.geometryToLabelMap);\n this.featureToShownMap = objectUtils.prune(this.featureToShownMap);\n\n this.scene.context.cleanupPickIds();\n }",
"function removeCubeMap(){\r\n scene.remove(cubeMapOBJ);\r\n}",
"function deleteMapObjects() {\n\tfor (var i = 0; i < deleteOnReclick.length; i++) {\n\t\tdeleteOnReclick[i].setMap(null);\n\t}\n\tdeleteOnReclick=[];\n}",
"function removeVehicles() {\n Object.keys(vehicles).map(function(k) {\n vehicles[k].setMap(null);\n });\n has_vehicles = false;\n vehicles = {};\n }",
"remove() {\n __objects = __objects.filter(obj => obj.object != this);\n this.sprite.destroy();\n }",
"async clearWorld() {\n this.worldObjects = {};\n this.loadedObjects = [];\n let children_to_remove = [];\n\n this.scene.traverse(function(child){\n if(child.type === \"Group\"){\n children_to_remove.push(child);\n }\n });\n\n for (let child of children_to_remove) {\n if (child.name !== \"island\") {\n this.scene.remove(child);\n }\n }\n }",
"function clearMap() {\n\tvic.destroy();\n\tkerr.destroy();\n\tlake.destroy();\n\teng.destroy();\n\tslc.destroy();\n\tbridge.destroy();\n\tclassroom.destroy();\n}",
"function UnspawnAll(){\n\t\tfor(var i = 0; i < all.Count; i++){\n\t\t\tvar obj : GameObject = all[i] as GameObject;\n\t\t\tif(obj!=null && obj.active)\n\t\t\t\tUnspawn(obj);\n\t\t}\n\t}",
"function UnspawnAll()\n{\n\tfor(var obj : Object in all)\n\t{\n\t\tif((obj as GameObject).active)\n\t\t{\n\t\t\tUnspawn(obj as GameObject);\n\t\t}\n\t}\n}",
"function removeAllObj() {\n $(\"#obj-list .remove-button\").click();\n chosenStations = [];\n chosenCounties = [];\n chosenFriction = [];\n markedStations = [];\n for(let i = 0; i < drawnRectLayers.length; i++){\n map.removeLayer(drawnRectLayers[i]);\n }\n for(let i = 0; i < drawnCircleLayers.length; i++){\n map.removeLayer(drawnCircleLayers[i]);\n }\n warningFlag = true;\n}",
"destroy() {\n this._destroyed = true;\n\n if (typeof this.freeFromPool === 'function') {\n this.freeFromPool();\n }\n\n if (this.currentMap) {\n this.currentMap.removeObject(this);\n } else if (this.currentScene) {\n this.currentScene.removeObject(this);\n }\n\n this.children.forEach((child) => {\n child.destroy();\n });\n }",
"destroy() {\n this.map.setTarget(null);\n this.map = null;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
_endEvent( event ) Properly terminates a DOM event | function _endEvent ( event )
{
if ( event.stopPropagation )
{
event.stopPropagation();
}
else
{
event.cancelBubble = true;
}
event.preventDefault(); // prevents weirdness
return false;
} | [
"function _endEvent ( event )\n\t{\n\t\tif ( event.stopPropagation )\n\t\t{\n\t\t\tevent.stopPropagation();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tevent.cancelBubble = true;\n\t\t}\n\t\tevent.preventDefault(); // prevents weirdness\n\t\treturn false;\n\t}",
"function finishEvent() {\r\n\tcancelEvent();\t\r\n}",
"exitEventTarget(ctx) {\n\t}",
"function EndListener() {}",
"function dragEndEvent(e) {\n\t\teventNoticeNode.innerHTML = \n\t\t\tsprintf(\"<strong>%s</strong>: Drag Event stopped.<br />%s\", \n\t\t\t\tnew Date(), eventNoticeNode.innerHTML);\n\t\t\t\t\n\t\tdragEventNoticeNode.innerHTML = \"Dragging stopped.\"\n\t}",
"function ie_quitarEvento(elemento, evento, mifuncion){\r\n //////var fx = function(){\r\n ////// mifuncion.call(elemento); \r\n //////};\r\n\t\t\t//////if (event.srcElement.readyState != \"complete\") { return; }\r\n elemento.detachEvent('on' + evento, fx);\r\n }",
"function handleEnd(event) {\n\n var currentEventSubId = event.target.id;\n currentEventSubId = currentEventSubId.substring(currentEventSubId.indexOf(\"-\") + 1);\n\n const eventStatus = {\n \"eventSubIdToChange\": currentEventSubId,\n \"changeStatusTo\": 'end'\n };\n\n // API TO UPDATE EVENT TO SET EVENT AS ACTIVATED\n API.updateEventStatus(eventStatus)\n .then(res => {\n setEventIsActive(false);\n loadEvents();\n })\n .catch(err => console.log(err))\n }",
"function resendEvent (event) {\n _eventCallback(event);\n }",
"function gestureEnd(ev) {\n if (!pointer || !typesMatch(ev, pointer)) return;\n\n updatePointerState(ev, pointer);\n pointer.endTime = +Date.now();\n\n runHandlers('end', ev);\n\n lastPointer = pointer;\n pointer = null;\n }",
"function gestureEnd(ev) {\r\n if (!pointer || !typesMatch(ev, pointer)) return;\r\n\r\n updatePointerState(ev, pointer);\r\n pointer.endTime = +Date.now();\r\n\r\n runHandlers('end', ev);\r\n\r\n lastPointer = pointer;\r\n pointer = null;\r\n }",
"function ExitEvent() {\n\n}",
"function gestureEnd(ev) {\n if (!pointer || !typesMatch(ev, pointer)) return;\n\n updatePointerState(ev, pointer);\n pointer.endTime = +Date.now();\n\n runHandlers('end', ev);\n\n lastPointer = pointer;\n pointer = null;\n }",
"function gestureEnd(ev) {\n if (!pointer || !typesMatch(ev, pointer)) return;\n\n updatePointerState(ev, pointer);\n pointer.endTime = +Date.now();\n\n runHandlers('end', ev);\n\n lastPointer = pointer;\n pointer = null;\n }",
"function gestureEnd(ev) { // 1664\n if (!pointer || !typesMatch(ev, pointer)) return; // 1665\n // 1666\n updatePointerState(ev, pointer); // 1667\n pointer.endTime = +Date.now(); // 1668\n // 1669\n runHandlers('end', ev); // 1670\n // 1671\n lastPointer = pointer; // 1672\n pointer = null; // 1673\n }",
"onEnd () {}",
"_pointerEnd(event) {\n if (!this._triggerPointerEnd(new Pointer(event), event))\n return;\n if (isPointerEvent(event)) {\n if (this.currentPointers.length)\n return;\n this._element.removeEventListener('pointermove', this._move);\n this._element.removeEventListener('pointerup', this._pointerEnd);\n }\n else { // MouseEvent\n window.removeEventListener('mousemove', this._move);\n window.removeEventListener('mouseup', this._pointerEnd);\n }\n }",
"end() {\n this.cancel();\n this.callback();\n }",
"function onTouchEndCaptured( tracker, event ) {\n\t handleTouchEnd( tracker, event );\n\t $.stopEvent( event );\n\t }",
"function onTouchEndCaptured( tracker, event ) {\n handleTouchEnd( tracker, event );\n $.stopEvent( event );\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create Aemet request options | function createAemetOptionsForRequest(url) {
return {
method: 'GET',
qs: {
'api_key': APIKeys.aemet_api_key
},
url: url,
headers: {
'Accept': 'application/json;charset=UTF-8', // Responde text/plain;charset=ISO-8859-15, Aemet debe corregirlo
'Accept-Charset': 'UTF-8',
'cache-control': 'no-cache'
}
};
} | [
"function genBaseOptions() {\n const options = {\n method: 'GET',\n headers: {\n Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'User-Agent': _.sample(agents),\n Referer: _.sample(referers),\n },\n timeout: MAX_REQUEST_TIMEOUT,\n }\n return options\n}",
"static createDefault() {\n JuspayEnvironment.init();\n return new RequestOptions();\n }",
"static get aotOptions() {}",
"function getOptions(request) {\n\n // Helper function to see if a string starts with a given string.\n var startsWith = function(source, str) {\n return (source.match(\"^\"+str) == str);\n };\n\n // Retrieves the HTTP status code from the request path.\n var getStatus = function(u) {\n var status = parseInt(u.pathname.substring(1));\n if (isNaN(status)) {\n status = 200;\n }\n return status;\n };\n\n // This is dangerous, but hey, this server should only be used for testing.\n function getCondition(condition) {\n condition = condition || true;\n return new Function('r', 'return ' + condition + ';');\n }\n\n var u = require('url').parse(request.url);\n var qs = require('querystring').parse(u.query);\n var options = {};\n\n // Load any options in a serialized json object.\n if (qs.json) {\n options = JSON.parse(qs.json);\n }\n\n // If this is an array, all details must be in the array.\n if (typeOf(options) == 'array') {\n for (var i = 0; i < options.length; i++) {\n // Set certain defaults on each object.\n options[i].condition = getCondition(options[i].condition);\n options[i].statusCode = options[i].statusCode || getStatus(u);\n }\n return options;\n }\n\n // Load any options that are in the query string\n for (var name in qs) {\n if (!qs.hasOwnProperty(name) || name == 'json') {\n continue;\n }\n var headerValue = qs[name];\n var splitName = name.split('.');\n var part = options;\n for (var i = 0; i < splitName.length; i++) {\n var partName = splitName[i];\n if (i == splitName.length - 1) {\n // We're at the last element, set the value.\n part[partName] = headerValue;\n } else {\n if (!part[partName]) {\n part[partName] = {};\n }\n part = part[partName];\n }\n }\n }\n\n // Add the status code to the response.\n options.statusCode = getStatus(u);\n\n options.condition = getCondition(options.condition);\n\n return [options];\n}",
"setRequestOptions(options) {\n if (!isObject(options)) {\n throw new TypeError('request options should be of type \"object\"')\n }\n this.reqOptions = _.pick(options, ['agent', 'ca', 'cert', 'ciphers', 'clientCertEngine', 'crl', 'dhparam', 'ecdhCurve', 'honorCipherOrder', 'key', 'passphrase', 'pfx', 'rejectUnauthorized', 'secureOptions', 'secureProtocol', 'servername', 'sessionIdContext'])\n }",
"function RequestOptions() {\n return {\n 'method': 'GET',\n 'hostname': 'api.schiphol.nl',\n 'port': null,\n 'headers': {\n 'resourceversion': 'v3',\n 'content-type': 'application/json',\n },\n addPath: function (base, params) {\n this.path = base + querystring.stringify(params);\n },\n changeVersion: function () {\n this.headers.resourceversion = 'v1';\n }\n };\n}",
"__generateScrapeOptions(url, method) {\n\t\tif (!url) {\n\t\t\turl = '/';\n\t\t}\n\n\t\treturn {\n\t\t\theaders: {\n\t\t\t\t'cookie': this.identity.oauthSecret,\n\t\t\t\t'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36'\n\t\t\t},\n\t\t\thost: FACEBOOK_MOBILE_HOST,\n\t\t\tmethod: 'GET',\n\t\t\tpath: url\n\t\t};\n\t}",
"function makeOptions(ctx, path, method, headers, contentLength) {\n var options = {\n hostname: ctx.url.host, port: ctx.url.port, path: normalize(ctx.url.path) + path,\n method: method,\n agent: createAgent(ctx.url.protocol == \"https\", ctx.httpProxy),\n headers: {\n 'X-Kii-AppID': ctx.appID, 'X-Kii-AppKey': ctx.appKey,\n 'Authorization': 'Bearer ' + ctx.token\n }\n };\n\n if (contentLength) {\n options.headers['Content-Length'] = contentLength\n }\n for (var k in headers) {\n options.headers[k] = headers[k];\n }\n\n return options;\n}",
"getRequestOptions(opts) {\n var method = opts.method\n var region = opts.region\n var bucketName = opts.bucketName\n var objectName = opts.objectName\n var headers = opts.headers\n var query = opts.query\n\n var reqOptions = {method}\n reqOptions.headers = {}\n\n // Verify if virtual host supported.\n var virtualHostStyle\n if (bucketName) {\n virtualHostStyle = isVirtualHostStyle(this.host,\n this.protocol,\n bucketName)\n }\n\n if (this.port) reqOptions.port = this.port\n reqOptions.protocol = this.protocol\n\n if (objectName) {\n objectName = `${uriResourceEscape(objectName)}`\n }\n\n reqOptions.path = '/'\n\n // Save host.\n reqOptions.host = this.host\n // For Amazon S3 endpoint, get endpoint based on region.\n if (isAmazonEndpoint(reqOptions.host)) {\n reqOptions.host = getS3Endpoint(region)\n }\n\n if (virtualHostStyle && !opts.pathStyle) {\n // For all hosts which support virtual host style, `bucketName`\n // is part of the hostname in the following format:\n //\n // var host = 'bucketName.example.com'\n //\n if (bucketName) reqOptions.host = `${bucketName}.${reqOptions.host}`\n if (objectName) reqOptions.path = `/${objectName}`\n } else {\n // For all S3 compatible storage services we will fallback to\n // path style requests, where `bucketName` is part of the URI\n // path.\n if (bucketName) reqOptions.path = `/${bucketName}`\n if (objectName) reqOptions.path = `/${bucketName}/${objectName}`\n }\n\n if (query) reqOptions.path += `?${query}`\n reqOptions.headers.host = reqOptions.host\n if ((reqOptions.protocol === 'http:' && reqOptions.port !== 80) ||\n (reqOptions.protocol === 'https:' && reqOptions.port !== 443)) {\n reqOptions.headers.host = `${reqOptions.host}:${reqOptions.port}`\n }\n reqOptions.headers['user-agent'] = this.userAgent\n reqOptions.headers['user-agent'] = this.userAgent\n if (headers) {\n // have all header keys in lower case - to make signing easy\n _.map(headers, (v, k) => reqOptions.headers[k.toLowerCase()] = v)\n }\n\n // Use any request option specified in StorageClient.setRequestOptions()\n reqOptions = Object.assign({}, this.reqOptions, reqOptions)\n\n return reqOptions\n }",
"computeOptions(parameters) {\n let options = {\n timeout: 30000,\n headers: {},\n encoding: null,\n followAllRedirects: true,\n followRedirect: true,\n time: true\n };\n\n options.method = parameters.method;\n options.url = parameters.url;\n\n if (parameters.request_parameters) {\n let requestParameters = parameters.request_parameters;\n\n if (requestParameters.headers) {\n options.headers = JSON.parse(\n JSON.stringify(requestParameters.headers).toLowerCase()\n );\n }\n\n if (requestParameters.hasOwnProperty(\"follow_redirect\")) {\n options.followRedirect = requestParameters.follow_redirect;\n options.followAllRedirects = requestParameters.follow_redirect;\n }\n\n if (requestParameters.payload) {\n options.body = requestParameters.payload;\n\n options.headers[\"content-length\"] = Buffer.byteLength(\n requestParameters.payload\n );\n\n if (!options.headers[\"content-type\"]) {\n console.log(\n \"You need to send Content-Type in headers to identify the body content of this request.\"\n );\n }\n }\n }\n\n if (!options.headers.hasOwnProperty(\"accept\")) {\n options.headers[\"accept\"] = \"*/*\";\n } else if (options.headers[\"accept\"] == \"\") {\n delete options.headers[\"accept\"];\n }\n\n if (!options.headers.hasOwnProperty(\"user-agent\")) {\n options.headers[\"user-agent\"] = this.userAgent;\n } else if (options.headers[\"user-agent\"] == \"\") {\n delete options.headers[\"user-agent\"];\n }\n\n return options;\n }",
"getRequestOptions() {\n\n let githubApiRequestOptions = {\n url: this.gitUrl,\n headers: {\n 'User-Agent': 'request'\n },\n time: true,\n resolveWithFullResponse: true\n }\n\n // provide your github personal access token incase of limit reached by api hits from same machine\n // UnAuthenticated = 60 per hour and Authenticated = 5000 per hour\n // For more info, please visit: https://developer.github.com/v3/#rate-limiting\n const PERSONAL_GIT_ACCESS_TOKEN = process.env.GIT_PERSONAL_ACCESS_TOEKEN || '';\n if (!!PERSONAL_GIT_ACCESS_TOKEN) {\n githubApiRequestOptions.headers['Authorization'] = `token ${PERSONAL_GIT_ACCESS_TOKEN}`;\n }\n\n return githubApiRequestOptions;\n }",
"function genRequestOptions(url, method, token, data){\n var options = {\n 'url': url,\n 'method': method,\n 'headers': {\n 'Authorization': 'bearer ' + token,\n 'Content-Type': 'application/json'\n }\n };\n if(method === 'POST'){\n options.json = data;\n }\n else{ // query for GET\n options.qs = data;\n }\n return options;\n}",
"function generateHttpOptions() {\n var self = this;\n var port = getPort.call(this);\n var path = URL.format({\n 'pathname': self.parameters.path,\n 'query': self.parameters.query\n });\n var options = {\n 'hostname': self.parameters.host,\n 'port': port,\n 'path': path,\n 'headers': self.parameters.headers,\n 'auth': self.parameters.auth,\n };\n options.headers['user-agent'] = self.parameters.userAgent;\n return options;\n}",
"static set aotOptions(value) {}",
"options(url, options = {}) {\n return this.request('OPTIONS', url, options);\n }",
"function getRequestOptions() {\n var requestOptions = url.parse(ENDPOINT);\n requestOptions.auth = 'api:' + settings.key;\n requestOptions.method = 'POST';\n\n return requestOptions;\n }",
"function genOptions(name) {\n var url = `https://raw.githubusercontent.com/adumbz/faceapijs/master/${reformat(name)}/001.jpg`\n var options = {\n 'method':'POST',\n 'url':'http://facexapi.com/get_face_vec?face_det=1',\n 'headers':{\n 'user_id':'5def6cea6ea12f126fdd4ce1'\n },\n formData: {\n 'img':url\n }\n }\n return options\n}",
"async function getFormOptions(req, res) {\n const omisMarketOptions = await getOptions(req, 'omis-market')\n const regionOptions = await getOptions(req, 'uk-region')\n const sectorOptions = await getOptions(req, 'sector', {\n queryString: '?level__lte=0',\n })\n return {\n omisMarketOptions,\n regionOptions,\n sectorOptions,\n userAgent: res.locals.userAgent,\n }\n}",
"function setOptions(request){\n var options = request.options || request,\n server_options;\n\n try{\n server_options = JSON.parse( getItem('server_options') );\n }catch(e){\n server_options = {};\n }\n \n options = CommonFn.apply( options, server_options );\n setItem(\"options\", JSON.stringify( options ));\n \n return options;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function should update the inner html of the dropdown label to be the current value stored in the `semester` variable. | function updateDropdownLabel() {
// code goes here
semesterDropLabel.innerHTML = semester
} | [
"function updateDropdownLabel() {\n // code goes here\n drop_label.innerHTML = semester;\n}",
"function updateDropdownLabel() {\n // code goes here\n dropDownBarLabel.innerHTML = semester\n}",
"function updateSemester() {\n $(\"#semester\")\n .text(\"Year \" + sem.acadYear + \" SEM\" + sem.semester);\n }",
"function updateSemester(clicked) {\n // code goes here\n semester = clicked.innerHTML\n}",
"changeSemesterName () {\n var sem = napolyApiModule.state.currentSemesterId - 1 // Note that our API for some reason starts arrays ar 1...\n var year = napolyApiModule.state.semesters.data[sem].semesterYear\n sem = napolyApiModule.state.semesters.data[sem].semesterHalf === 1 ? 'FS ' : 'HS '\n napolyApiModule.state.currentSemesterName = sem + year\n }",
"function updateDropdownLabel() {\n // code goes here\n}",
"function update_dropdown_label()\r\n {\r\n\r\n $(dropdown).html('');\r\n\r\n $('#' +$(dropdown).attr('data-id') + ' :selected').each(function(){\r\n\r\n $(dropdown).append($(this).html() + ', ') ;\r\n });\r\n\r\n var content = $(dropdown).html();\r\n\r\n if(content.length > 2)\r\n {\r\n $(dropdown).html(content.substr(0, content.length - 2));\r\n }\r\n }",
"updateSelectedSemester(selection) {\n this.setState({ selectedSemester: selection });\n }",
"function changeDropdownLabel(newValue, newLabel, isPlaceholder) {\n dropdownLabel.textContent = newLabel;\n dropdownLabel.setAttribute(\"data-value\", newValue);\n dropdownLabel.classList.toggle(\"is-placeholder\", isPlaceholder === true);\n }",
"function updatePeriod() {\n //gets the selected start year and current selected time span\n var in_start_yr = document.getElementById(\"start_year\").value;\n var curPeriod = document.getElementById(\"period\").value;\n //the new maximumtime span\n var period = 2014 - in_start_yr + 1;\n //the html write to be done\n var out = \"\";\n //for all eyars in time span\n for (var i = 1; i < period; i++) {\n //create and option for this year\n out += \"<option value=\" + i;\n out += \">\" + i;\n out += \" Year<\" + \"/option>\";\n }\n //change the innerhtml to match\n document.getElementById(\"period\").innerHTML = out;\n //if the previoudly selected period is less then the current period then leave that choice selected\n if (curPeriod <= period) {\n document.getElementById(\"period\").value = curPeriod;\n // if not then set default to 1 year\n }else{\n document.getElementById(\"period\").value = 1;\n }\n}",
"function bindSemesterChange() {\n $('#term').on('change', function (event, params) {\n var label = void 0,\n semesters = void 0,\n semester = void 0,\n block = void 0,\n idx = void 0;\n label = $('label[for=\"term-block\"]');\n semesters = GlobalUtils.getSemesters();\n\n if (!params) {\n // params is undefined when you deselect a semester.\n $('#term-block').chosen('destroy');\n label.addClass('hidden');\n return;\n }\n\n for (idx in semesters) {\n if (!semesters.hasOwnProperty(idx)) {\n continue;\n }\n\n semester = semesters[idx];\n if (semester.id != params.selected) {\n continue;\n }\n\n block = $('#term-block');\n // If there are other options in the term-block selector, remove them.\n block.find('option[value]').remove();\n block.show();\n\n // Show the label.\n label.removeClass('hidden');\n\n // Fill the term-block selector.\n fillSelect('#term-block', semester.blocks, 'Full Semester');\n }\n\n addColorPicker('term-block');\n });\n\n $('#term-block').on('chosen:ready', function () {\n var block = $(this);\n\n setTimeout(function () {\n $('#term').trigger('chosen:close');\n block.trigger('chosen:activate');\n }, 25);\n });\n }",
"setSemester(aSemester) {\n this.semester = aSemester;\n }",
"updateYear() {\n O('year-label').innerHTML = this.year;\n }",
"function changeSelectedYear() {\n let y = $('#year').attr('value');\n let options = yearSelection(y);\n\n // clear options and update\n $('#residence').html('');\n $.each(options, (i, o) => { $('<div class=\"dropdown-item\" value=\"' + o + '\">' + o +'</div>').appendTo( $('#residence') ); });\n \n if ( $('.residence .dropdown-selected').length == 0 ) {\n $('.residence').children(':first-child').before('<span class=\"dropdown-selected\">Choose one...</span>');\n }\n \n $('.residence .dropdown-selected').click( dropdownClick );\n $('.residence .dropdown-item').click( dropdownItemClick );\n $('#residence').children().not('.dropdown-selected').click(changeSelectedResidence);\n $('.residence').show().css('display', 'inline-block');\n}",
"function render_year(){\n let yearformat = \"\";\n for(let i = min_year; i <= max_year; i++){\n yearformat += `<option value=\"${i}\">${i}</option>`;\n year.innerHTML = yearformat;\n }\n}",
"function updateYearSelectorComponent(value) {\n document.getElementById(\"selectedyear\").value = value;\n document.getElementById(\"yearselector\").value = value;\n}",
"function updateDropdown(dprogData, showBreadCrumb)\n{\n\t// The data structure is as follows:\n\t// {dprogData:\n\t// \t\tstrategy:DROPDOWN,\t\n\t//\t\tauditRequestDegreeLabel,\n\t//\t\tcurrentDisplay,\t\n\t//\t\tcurrentValue,\t\t\n\t//\t\twhatIfDegreeProgram,\n\t//\t\t{dprogOptions:\n\t//\t\t\t[{option:\n\t//\t\t\t\t{name, label}\n\t//\t\t\t}]\n\t//\t\t}}\n\t// }\n\tvar htmlBuffer = [];\n\tif (showBreadCrumb) {\n\t\thtmlBuffer.push('<input type=\"hidden\" name=\"previousWhatIfDegreeProgram\" value=\"' + dprogData.currentValue + '\" />');\n\t\thtmlBuffer.push('<input type=\"hidden\" id=\"whatIfDegreeProgram\" name=\"whatIfDegreeProgram\" value=\"' + dprogData.whatIfDegreeProgram + '\" />');\n\t\thtmlBuffer.push('<input type=\"hidden\" name=\"auditRequest.wifBreadcrumb.whatIfDegreeProgram.currentDisplay\" value=\"' +\n\t\t\t\tdprogData.currentDisplay + '\" />');\n\t\thtmlBuffer.push('<span class=\"marker\">' + dprogData.currentDisplay + '</span>')\n\t} else {\n\t\tif (dprogData.dprogOptions.length == 0) {\n\t\t\thtmlBuffer.push('<p class=\"notice\">No degree programs found for this school.</p>');\n\t\t} else if (dprogData.dprogOptions.length == 1) {\n\t\t\thtmlBuffer.push('<input type=\"hidden\" name=\"whatIfDegreeProgram\" id=\"whatIfDegreeProgram\" value=\"' +\n\t\t\t\t\tdprogData.whatIfDegreeProgram + '\" />');\n\t\t\thtmlBuffer.push('<span class=\"marker\">' + dprogData.currentDisplay + '</span>');\n\t\t} else {\n\t\t\tif ( dprogData.whatIfDegreeProgram != \"\" ) {\n\t\t\t\thtmlBuffer.push('<input type=\"hidden\" name=\"previousWhatIfDegreeProgram\" value=\"' + dprogData.whatIfDegreeProgram + '\" />');\n\t\t\t}\n\t\t\thtmlBuffer.push('<select class=\"form-control maxWidth\" name=\"whatIfDegreeProgram\" id=\"whatIfDegreeProgram\" ' + \n\t\t\t\t\t'onchange=\"setDegreeProgram()\" >');\n\t\t\thtmlBuffer.push('<option value=\"\">-</option>');\n\t\t\tfor (var i = 0; i < dprogData.dprogOptions.length; i++) {\n\t\t\t\thtmlBuffer.push('<option value=\"' + dprogData.dprogOptions[i].option.name + '\" ');\n\t\t\t\tif (dprogData.dprogOptions[i].option.name == dprogData.whatIfDegreeProgram) {\n\t\t\t\t\thtmlBuffer.push('selected=\"selected\"');\n\t\t\t\t}\n\t\t\t\thtmlBuffer.push('>' + dprogData.dprogOptions[i].option.label + '</option>');\n\t\t\t}\n\t\t\thtmlBuffer.push('</select><span id=\"whatIfDegreeProgram\"> </span>');\n\t\t}\n\t}\n\treturn htmlBuffer.join('');\n}",
"function updateHorseOptions() {\n var temp = \"<label for=\\\"betHorse\\\">Select a horse to bet on (up to 3)</label><select name=\\\"betHorse\\\" id=\\\"betHorse\\\">\";\n\n for (l = 0; l < horsesInRace.length; l++) {\n if (l === 0) {\n temp += \"<option selected = \\\"selected\\\">\" + horsesInRace[l][0] + \"</option>\";\n } else {\n temp += \"<option>\" + horsesInRace[l][0] + \"</option>\";\n }\n\n }\n $(\"#horse-options\").html(temp);\n makeSelectMenu();\n }",
"function update(){\n\tdata = {\n\t\t'programme' : $(\"#programme\").val(),\n\t\t'branch' : $(\"#branch\").val(),\n\t}\n\t$.post(update_url, data, function(data, textStatus, jqXHR){\n\t\t// Remove all old names from the student list\n\t\t$('#student').children('option').remove();\n\t\t// Add all new names\n\t\tfor (i = 0; i < data.length; i++) {\n\t\t\tto_append = '<option value=\"' + data[i].id + '\">' + data[i].name + '</option>'\n\t\t\t$(\"#student\").append(to_append);\n\t\t}\n\t}, \"json\");\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a password for the current page. Will try to find the username too. | function generate_password() {
base.emit("generate-password", {
url: document.location.toString(),
username: find_username(),
});
} | [
"function generatePassword() {\n var pw = mainForm.master.value,\n sh = mainForm.siteHost.value;\n\n // Don't show error message until needed\n hide(mainForm.pwIncorrect);\n\n // Only generate if a master password has been entered\n if (pw !== '') {\n if (settings.rememberPassword) {\n verifyPassword(pw, correct => {\n if (!correct) {\n // Master password is incorrect so show a warning\n show(mainForm.pwIncorrect);\n mainForm.master.select();\n }\n });\n }\n\n // Only generate if a site has been entered\n if (sh !== '') {\n mainForm.pwResult.value = '';\n mainForm.pwResult.placeholder = 'Generating...';\n\n // Generate a password to use, regardless of correct password\n uniquify(pw, sh, unique => {\n mainForm.pwResult.value = unique;\n mainForm.pwResult.placeholder = '';\n mainForm.pwResult.select();\n }, settings);\n }\n }\n }",
"function generatePassword() {\n // set the criteria conditions\n setConditions();\n // randomize the password\n randomize();\n // return the generated password\n return password.pwd;\n}",
"function makePassword() {\n createPassword()\n return genPassword;\n}",
"function Generate()\n{\n var uri = document.hashform.domain.value;\n var domain = (new SPH_DomainExtractor()).extractDomain(uri);\n var size = SPH_kPasswordPrefix.length;\n var data = document.hashform.sitePassword.value;\n if (data.substring(0, size) == SPH_kPasswordPrefix)\n data = data.substring(size);\n var result = new String(new SPH_HashedPassword(data, domain));\n return result;\n}",
"function generatePassword() {\n let password = \"\";\n\n // Reset the passwordDetails object to a \"clean slate\" for the current password generation attempt.\n initializePasswordDetails();\n\n // Gather user input, including criteria and desired password length.\n if (getUserInput()) {\n // If we have valid criteria and desired password length, construct the new password one character at a time.\n while (passwordDetails.desiredPasswordLength > 0) {\n password += getNextPasswordCharacter();\n passwordDetails.desiredPasswordLength--;\n }\n }\n\n // Return the new password.\n return password;\n}",
"function PasswordInputScraper() {}",
"function finalPasswordGen() {\n finalPwd += randomIndexFucnt(potentialPwdCharLib);\n return finalPwd\n}",
"static generatePassword() {\n return\n\n Math.floor(Math.random() * 10000);\n }",
"function GetPassword()\r\n{\r\n var html = window.top.document.getElementsByName('charpane')[0].contentDocument.documentElement.innerHTML;\r\n return StringBetween(html.substr(html.indexOf(\"pwdhash\"), 100), \"\\\"\", \"\\\"\");\r\n}",
"function PasswordInputScraper() {\n }",
"function generatePassword() {\n var pass = createRandomPassword();\n _dom.mainInput.value = pass;\n if (_dom.clearInput) {\n _dom.clearInput.value = pass;\n }\n triggerEvent(\"generated\", pass);\n toggleMasking(false);\n\n if (_validateTimer) {\n clearTimeout(_validateTimer);\n _validateTimer = null;\n }\n validatePassword();\n\n if (_dom.placeholder) {\n _dom.placeholder.style.display = \"none\";\n }\n }",
"function generatePassword() {\n password_generated = \"\";\n for (let i = 0; i < pass_length; i++) {\n password_generated = password_generated + password_options[randomGen(string_length)];\n }\n }",
"function generate () {\n var masterPassword = document.getElementById('master').value\n var output = document.getElementById('output')\n\n var p = new PretzelPass()\n p.setSalt(salt)\n p.setOptions(JSON.parse(localStorage['options' + domain] || localStorage['options'] || '{}'))\n\n var generatedPassword = p.generatePassword(masterPassword, domain)\n\n output.value = generatedPassword\n }",
"function generatePassword() {\n for (var i = 0; i < pwLength; i++)\n password = password + passwordPossibles.charAt(Math.floor(Math.random() * passwordPossibles.length));\n}",
"function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n }",
"function writePassword() {\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n }",
"function writePassword() {\n var password = generatePassword(charset, chosenLength);\n var passwordText = document.querySelector(\"#password\");\n passwordText.value = password;\n}",
"function createPassword () {\n var newpassword = \"\";\n newpassword = generatePassword();\n var passwordtext = document.querySelector ('#password');\n passwordtext.value = newpassword;\n\n}",
"function writePassword() {\n passwordUserCriteriaCheck();\n var password = generatePassword();\n var passwordText = document.querySelector(\"#password\");\n\n passwordText.value = password;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
default config for an insert button group: image | get insertButtonGroup() {
return {
type: "button-group",
subtype: "insert-button-group",
buttons: [this.imageButton, this.symbolButton],
};
} | [
"static defaultButton(img, lnk)\n\t{\n\t\tvar button = document.createElement('div');\n\t\tbutton.setAttribute('class', 'poll-builer-add-button');\n\t\tbutton.innerHTML = 'Add to Poll';\n\t\tbutton.addEventListener('click', function(evt){ evt.preventDefault(); });\n\t\tvar s = button.style;\n\t\ts.cursor = 'pointer';\n\t\ts.padding = '4px 10px';\n\t\ts.transition = 'opacity 0.4s';\n\t\ts.opacity = '0';\n\t\ts.pointerEvents = 'none';\n\t\ts.fontSize = '14px';\n\t\ts.color = '#fff';\n\t\ts.background = '#000';\n\t\ts.whiteSpace = 'nowrap';\n\t\t\n\t\tif (img && lnk)\n\t\t\tPollBuilderInject.addDataElement(button, img, lnk);\n\t\t\n\t\treturn button;\n\t}",
"get imageButton() {\n return {\n type: \"rich-text-editor-image\",\n };\n }",
"function setImage(){\n\t\tbtn.backgroundImage = btn.value ? btn.imageOn : btn.imageOff;\n\t}",
"initDefaultConfig_img(){\n\t\t// add image min extension.\n\t\tconst Imagemin = require('../extensions/mix-imagemin/Imagemin');\n\t\tthis.mix.extend('imagemin', new Imagemin());\n\n\t\tconst sourceRep = 'img'\n\t\tconst match = MixEasyConfMatch.get(sourceRep);\n\t\tconst imageConfig = new MixEasyStructureConfig(sourceRep)\n\t\t\t.setMixCallbackName(match.callback)\n\t\t\t.setExtension(match.extension)\n\t\t\t.setDestinationRep(match.destination)\n\t\t\t.setOutputExtension(match.extension)\n\t\t\t.setMixOptions(match.mixOptions)\n\t\t\t.allFilesAreEntryPoints();\n\t\t\n\t\timageConfig.getMixExtensionSecondParameter = (processConfig) => {\n\t\t\tconst patternData = processConfig.getPattern()[0].split('/')\n\t\t\treturn {\n\t\t\t\tpatterns: [\n\t\t\t\t\t{\n\t\t\t\t\t\tfrom: patternData.slice(1).join('/'),\n\t\t\t\t\t\tto: this.destinationRoot+'/'+(patternData[0]===sourceRep?sourceRep:''),\n\t\t\t\t\t\tcontext:patternData[0]+\"/\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\n\t\tthis.addProcessConfig(imageConfig);\n\n\t\treturn imageConfig;\n\t}",
"addImage() {\n }",
"function addDefaultImg(src){\n src = src.replace('ressources/', '');\n myDiagram.model.startTransaction(\"modified img\");\n var selection = myDiagram.selection.first();\n if(selection != null) {\n var img = selection.data.img;\n myDiagram.model.setDataProperty(selection.data, \"img\", src);\n myDiagram.model.setDataProperty(selection.data, \"userupdate\", userid);\n myDiagram.model.setDataProperty(selection.data, \"timemodified\", time());\n myDiagram.model.commitTransaction(\"modified img\");\n }\n else{\n return false;\n }\n\n}",
"function setImageNamePrefixTemplate() {\n var functionName = lodash.get(ctrl.version, 'metadata.name');\n var imageNamePrefixTemplate = lodash.get(ConfigService, 'nuclio.imageNamePrefixTemplate', '');\n var parameters = {\n '{{ .FunctionName }}': functionName,\n '{{ .ProjectName }}': lodash.get(ctrl.project, 'metadata.name')\n };\n var imageNamePrefix = fillTemplate(imageNamePrefixTemplate, parameters);\n var defaultImageName = lodash.isEmpty(imageNamePrefixTemplate) ? 'processor-' + functionName : imageNamePrefix + 'processor';\n\n lodash.assign(ctrl.version.ui, {\n defaultImageName: defaultImageName,\n imageNamePrefix: imageNamePrefix\n });\n }",
"get imageButton() {\n return {\n ...super.imageButton,\n label: this.t.imageButton,\n };\n }",
"get defaultConfig() {\n return [\n this.historyButtonGroup,\n this.basicInlineButtonGroup,\n this.linkButtonGroup,\n this.clipboardButtonGroup,\n this.scriptButtonGroup,\n this.insertButtonGroup,\n this.listIndentButtonGroup,\n ];\n }",
"insertImage() {\r\n\t\t\t\ttextInserter.insertText(codemirror, \"![]()\", 1);\r\n\t\t\t}",
"function createImagesBtn(recipe, key) {\r\n\r\n // Create View as Images button\r\n \r\n var displayBtn = $(\"<button>\");\r\n var buttonText;\r\n \r\n if (key == \"text\") {\r\n buttonText = \"View as Images\";\r\n displayBtn.attr(\"data-displayType\", \"text\");\r\n }\r\n else {\r\n buttonText = \"View as Text\";\r\n displayBtn.attr(\"data-displayType\", \"images\");\r\n }\r\n \r\n displayBtn.text(buttonText);\r\n displayBtn.attr(\"id\", \"changeDisplayType\");\r\n displayBtn.attr(\"data-localStorageId\", recipe.localStorageId);\r\n //console.log(button);\r\n \r\n return displayBtn;\r\n }",
"static get addPostImage() { return require('snapshindig/assets/add.png') }",
"function editImages(){\n //Show additional edit buttons\n jQuery('.button-remove-image').show();\n jQuery('.isDefault').show();\n }",
"function createImageButton(parent, src, id, tooltip, specialClass) {\n var button = document.createElement('button');\n var buttonImage = document.createElement('img');\n buttonImage.setAttribute('src', src);\n buttonImage.setAttribute('height', 30);\n buttonImage.setAttribute('width', 30);\n button.appendChild(buttonImage);\n button.id = id;\n button.className = 'interactor';\n if(specialClass){\n button.className = specialClass;\n }\n parent.appendChild(button);\n return button;\n }",
"static get definition() {\n return {\n icon: '',\n i18n: {\n default: 'Image'\n }\n };\n }",
"get miniConfig() {\n return [\n {\n type: \"button-group\",\n buttons: [\n this.boldButton,\n this.italicButton,\n this.removeFormatButton,\n ],\n },\n this.linkButtonGroup,\n this.scriptButtonGroup,\n {\n type: \"button-group\",\n buttons: [this.orderedListButton, this.unorderedListButton],\n },\n ];\n }",
"function MASH_ImageButton(tmpID, tmpLeft, tmpTop, tmpWidth, tmpHeight, tmpZIndex, tmpStyle,\n tmpName, tmpValue,\n tmpSrc\n ) {\n \n this.base = MASH_Input;\n this.base(tmpID, tmpLeft, tmpTop, tmpWidth, tmpHeight, tmpZIndex, tmpStyle,\n MASH_Input.TYPE_IMAGE, tmpName, tmpValue\n );\n \n this.src = tmpSrc;\n \n}",
"function configGalleryButtons() {\n\t\tvar galleryId = $(\"#galleryId\").val();\n\t\tif (!isEmpty(galleryId)) {\n\t\t\t$(\"#btnUpdateGallery\").val (\"Atualizar Galeria\");\n\t\t\t$(\"#lblUsernameGallery\").show();\n\t\t\t$(\"#txtUsernameGallery\").show();\n\t\t\t$(\"#container-form-fields\").hide();\n\t\t\t$(\"#btnAddImages\").show();\t\t\t\n\t\t\t$(\"#container-uploaded-files\").show();\n\t\t\t$(\"#tab-4\").css(\"height\", \"auto\");\t\t\t\n\t\t\t$(\"#lblCreationDate\").show();\n\t\t\t$(\"#txtCreationDate\").show();\n\t\t\t$(\"#lblLastUpdateDate\").show();\n\t\t\t$(\"#txtLastUpdateDate\").show();\n\t\t\t$(\"#btnDeleteGallery\").show();\t\t\t\n\t\t} else {\n\t\t\t$(\"#btnUpdateGallery\").val (\"Adicionar Galeria\");\n\t\t\t$(\"#lblUsernameGallery\").hide();\n\t\t\t$(\"#txtUsernameGallery\").hide();\n\t\t\t$(\"#container-form-fields\").show();\n\t\t\t$(\"#btnAddImages\").hide();\n\t\t\t$(\"#container-uploaded-files\").hide();\n\t\t\t$(\"#tab-4\").css(\"height\", \"814px\");\n\t\t\t$(\"#lblCreationDate\").hide();\n\t\t\t$(\"#txtCreationDate\").hide();\n\t\t\t$(\"#lblLastUpdateDate\").hide();\n\t\t\t$(\"#txtLastUpdateDate\").hide();\n\t\t\t$(\"#btnDeleteGallery\").hide();\n\t\t}\n\t}",
"function uploadTileImage() {\n BinaryUpload.Uploader().Upload(\"/images/l_Sliderx96.png\", \"/SiteAssets/l_Sliderx96.png\");\n //setImageUrl();\n createConfigList();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function will check to see if there are any more pictures before or after the image that is currently being viewed. if there are no images after, it turns the right arrow off if there are no images before, it turns the left arrow off | function check_ends(img){
// check for pictures before
if (img.parent().prev().children().length <= 0){
$('img#arrow-left').addClass('arrow-hide');
} else {
$('img#arrow-left').removeClass('arrow-hide');
}
// check before pictures after
if (img.parent().next().children().length <= 0){
$('img#arrow-right').addClass('arrow-hide');
} else {
$('img#arrow-right').removeClass('arrow-hide');
}
} | [
"function checkArrows(i) {\n if (i == 0) {\n $('#leftArrow').css('display', 'none');\n $('#rightArrow').css('display', 'inline');\n } else if (i == images.length - 1) {\n $('#rightArrow').css('display', 'none');\n $('#leftArrow').css('display', 'inline');\n } else {\n $('#rightArrow').css('display', 'inline');\n $('#leftArrow').css('display', 'inline');\n } \n }",
"function checkPreviousImg(direction, addrs){\n if (imgs[currentImg + -1]) {\n currentImg--\n addrs.src = imgs[currentImg]\n getExif()\n }\n}",
"function imageIsLast() {\n let current_image_index = parseInt($('.fs-image')[0].id);\n if (current_image_index == 1) {\n left_btn.classList.add('opacity')\n left_btn.classList.add('unclickable')\n } else if (current_image_index == total - 1) {\n right_btn.classList.add('opacity')\n right_btn.classList.add('unclickable')\n } else {\n left_btn.classList.remove('opacity')\n right_btn.classList.remove('opacity')\n left_btn.classList.remove('unclickable')\n right_btn.classList.remove('unclickable')\n }\n }",
"function prev() {\n\t\t\tgoToImage((curImage-1 < 0 ? numImages-1 : curImage-1), next ,true);\n\t\t}",
"function left_img() {\n if(img_number > 0) {\n $images.eq(img_number - 1).addClass(\"left_img\")\n } else {\n $images.eq($images_amount).addClass(\"left_img\")\n }\n styling_left_right()\n}",
"function showThumbArrows() {\r\n\tvar lastVisible = allImages.index($('.sml-img').not('.no-display').last());\r\n\tvar firstVisible = allImages.index($('.sml-img').not('.no-display').first());\r\n\t\r\n\t$('.arr').each(function(){\r\n\t\t$(this).removeClass('no-display');\r\n\t})\r\n\r\n\tif (lastVisible === allImages.length-1) {\r\n\t\t$('.fa-angle-double-right').addClass('no-display');\r\n\t}\r\n\r\n\tif (firstVisible === 0) {\r\n\t\t$('.fa-angle-double-left').addClass('no-display');\r\n\t}\r\n}",
"function prevImg(){\r\n\t\tif(counter === 0){\r\n\t\t\treturn counter;\r\n\t\t}\r\n\t\telse{\r\n\t\t\tcounter--;\r\n\t\t\tdocument.getElementById('photo1').src = gallery[counter];\r\n\t\t\tdisplayArrows()\r\n\t\t}\r\n\t}",
"function _updateThumbnailNavigation() {\n\t\tvar\n\t\t\tdiff = _safeWidth(thumbs.parent()) - _safeWidth(thumbs),\n\t\t\tpos = _getRTLPosition(thumbs);\n\t\tbtnScrollBack.toggleClass(CLASS_HIDDEN, pos >= 0);\n\t\tbtnScrollForward.toggleClass(CLASS_HIDDEN, diff > 0 || pos <= diff);\n\t}",
"function showPrevImage2() {\n // change imageNum\n imageNum2--;\n // how many pixels from the left should imageRow now be?\n if (imageNum2>= 0) {\n checkControls2();\n let pixelsLeft2= -1*carouselWidth*(imageNum2);\n // change css for imageRow\n pixelsLeft2= pixelsLeft2 + \"px\";\n imageRow2.style.left = pixelsLeft2;\n }\n}",
"function goRight() {\n checkActive();\n\n if (indexImage > thumbnailImgs.length - 2) {\n indexImage = thumbnailImgs.length - 1;\n updateImageOnArrow(indexImage);\n\n } else {\n indexImage = indexImage + 1;\n updateImageOnArrow(indexImage);\n }\n\n }",
"function showPrevImage() {\n // change imageNum\n imageNum = imageNum - 1;\n // how many pixels from the left should imageRow now be?\n var currentWidth = carouselWidth * imageNum;\n // change css for imageRow\n imageRow.style.left = -currentWidth;\n checkControls();\n}",
"function prevImage() {\n\tif (imageIndex === 0) {\n\t\timageIndex = imageCount-1;\n\t}\n\telse {\n\t\timageIndex--;\n\t}\n\tshowImage(imageIndex);\n}",
"function prevImage() {\n\timageCounter -=1;\n\t\n\tif ( imageCounter < 0 ) {\n\t\timageCounter = imagesNumber - 1;\n\t}\n\tshowImage();\n}",
"function handle_recentlists_arrow_visibility()\n{\n var\n $left = $('.recentlist_arrow.arrow_left', modERLi.$container),\n $right = $('.recentlist_arrow.arrow_right', modERLi.$container);\n\n\n // left arrow\n if ( modERLi.$slider.find('.lasttop:first').is('.active') ) {\n\n $left.filter(':visible').fadeOut(modERLi.fadingTime);\n } else {\n $left.filter(':hidden').fadeIn(modERLi.fadingTime);\n }\n\n\n // right arrow\n if ( !modERLi.remaining.length\n && modERLi.$slider.find('.lasttop:last').is('.active') ) {\n\n $right.filter(':visible').fadeOut(modERLi.fadingTime);\n } else {\n $right.filter(':hidden').fadeIn(modERLi.fadingTime);\n }\n}",
"function showPrevImage() {\n // change imageNum\n imageNum--;\n // how many pixels from the left should imageRow now be?\n if (imageNum>= 0) {\n checkControls();\n let pixelsLeft= -1*carouselWidth*(imageNum);\n // change css for imageRow\n pixelsLeft= pixelsLeft + \"px\";\n imageRow.style.left = pixelsLeft;\n }\n}",
"function prev() {\r\n --current;\r\n showImage('l');\r\n }",
"function leftButton() {\n if (!firstActivityRowImages[0].classList.contains(\"hide\")) {\n fadeOutImages()\n fadeInImages(thirdActivityRowImages)\n return\n }\n if (!secondActivityRowImages[0].classList.contains(\"hide\")) {\n fadeOutImages()\n fadeInImages(firstActivityRowImages)\n return\n }\n if (!thirdActivityRowImages[0].classList.contains(\"hide\")) {\n fadeOutImages()\n fadeInImages(secondActivityRowImages)\n return\n }\n }",
"function showPrevImage() {\n\t// change imageNum\n\timageNum -= 1;\n\tcheckControls();\n\t// how many pixels from the left should imageRow now be?\n\tlet pixelsFromLeft = -carouselWidth * imageNum;\n\t// change css for imageRow\n\timageRow.style.left = pixelsFromLeft + \"px\";\n}",
"cycleLeft() {\n this.imgList[this.index].style.display = \"none\";\n //index can't be negative one, it has to loop fully through. so if index is zero, then set the index\n //equal to the LAST photo in the imgList collect. That means we need its length!\n\n if (this.index === 0) {\n this.index = this.imgList.length - 1;\n } else {\n //else set the index equal to this.index minus one (or decrement)\n this.index--;\n }\n //set image at new index to display:block\n this.imgList[this.index].style.display = \"block\";\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Procedure/Functie: toevoegen_tabs_in_grid() Beschrijving: 'Deze functie voegt elke card tab aan de daarvoor bestemde grid' | function toevoegen_card_tabs_in_grid() {
card_tabs_data__arr.map( (card_tab__obj, idx) => {
$x('.grid_' + eval(idx + 1)).append( aanmaken_card_tabs(idx))
})
} | [
"function aanmaken_card_tabs(idx)\n {\n var v_card_tab__html = ''; // deze variable zal de volledige tab structuur bevatten\n var v_card_tab_pgnaam__html = ''; // deze variable bevat de html voor de tab pagina namen\n var v_card_tab_pgcnt__html = ''; // deze variable bevat de html voor de tab content\n var v_card_tab_naam__str = card_tabs_data__arr[idx].card_tab_naam__str; // hier wordt de card tabnaam opgeslagen\n \t var v_card_tab_nr__str = idx + 1;\n\n card_tabs_data__arr[idx].card_tab_pg__arr.map((card_tab_pg__obj, idx2) => {\n\n var titel = card_tab_pg__obj.card_tab_pg_data__obj.titel;\n var viz = card_tab_pg__obj.card_tab_pg_data__obj.visualisatie;\n var info = card_tab_pg__obj.card_tab_pg_data__obj.info;\n\t var iframe_ref = (typeof card_tab_pg__obj.card_tab_pg_data__obj.iframe_ref !== 'undefined') ? card_tab_pg__obj.card_tab_pg_data__obj.iframe_ref : '';\n\n var v_card_tab_pgnr__str = idx2 + 1;\n // deze variable bevat de volledige prmt groepen structuur uit de aanmaken_prmt_groep functie\n\t\tif (typeof card_tab_pg__obj.card_tab_pg_naam__str !== 'undefined') {\n\t\t\tv_card_tab_pgnaam__html += `<li class='${v_card_tab_naam__str}_${v_card_tab_pgnr__str}_pgnaam'><a href=\"#\" class=\"${iframe_ref}\">${card_tab_pg__obj.card_tab_pg_naam__str}</a></li>`;\n\t\t}\n \tv_card_tab_pgcnt__html += `<li class=\"${v_card_tab_naam__str}_${v_card_tab_pgnr__str}_pgcnt\">${card_struct(v_card_tab_nr__str, viz(v_card_tab_nr__str, iframe_ref), titel, info)}</li>`;\n })\n // dit is de volledige tab structuur\n v_card_tab__html += `<div class='${v_card_tab_naam__str}_cnt' style='padding:10px;'><ul class='${v_card_tab_naam__str}_pgnaam' style=\"${v_card_tab_pgnaam__html ? '' : 'display:none;'}\" uk-tab>${v_card_tab_pgnaam__html ? v_card_tab_pgnaam__html : '<li><div></div></li>'}</ul><ul class='uk-switcher ${v_card_tab_naam__str}_pgcnt'>${v_card_tab_pgcnt__html}</ul></div>`;\n return v_card_tab__html; // geeft als resultaat de tab structuur terug\n }",
"function AfficherTab(){\n\n //vider le tableau actuel avant de le refaire\n var table = document.getElementById(\"TabPieces\");\n while(table.rows.length > 1) {\n table.deleteRow(1);\n }\n\n //vider le tableau actuel avant de le refaire\n var table2 = document.getElementById(\"TabSections\");\n while(table2.rows.length > 1) {\n table2.deleteRow(1);\n }\n\n //Ajout des pieces\n var ArrayPrincipal = GetArrayHidden();\n ArrayPrincipal.sort(function(a,b){ return a[0].toString() > b[0].toString(); });\n\n //ajout des pieces\n for(i=0;i<ArrayPrincipal.length;i++){\n\n var nom = ArrayPrincipal[i][0];\n var qte = ArrayPrincipal[i][1];\n var Description = ArrayPrincipal[i][3];\n var Prix = (parseFloat(ArrayPrincipal[i][4]).toFixed(2)).toString() + \"$\";\n var QteInv = ArrayPrincipal[i][2];\n\n var MainTab = document.getElementById(\"TabPieces\");\n\n var tr_0 = document.createElement('tr');\n tr_0.id = nom;\n\n var td_0 = document.createElement('td');\n td_0.appendChild( document.createTextNode(nom) );\n td_0.id = nom+\"td\";\n tr_0.appendChild( td_0 );\n\n var td_1 = document.createElement('td');\n td_1.appendChild( document.createTextNode(qte + \"/\" + QteInv) );\n tr_0.appendChild( td_1 );\n\n\n var td_2 = document.createElement('td');\n td_2.appendChild( document.createTextNode(Prix) );\n tr_0.appendChild( td_2 );\n\n\n var td_3 = document.createElement('td');\n td_3.appendChild( document.createTextNode(Description) );\n tr_0.appendChild( td_3 );\n\n\n MainTab.appendChild( tr_0 );\n\n //compare les 2 quantitées\n if(parseInt(qte) > parseInt(QteInv)){td_0.style.color = \"red\";}else{td_0.style.color = \"black\";}\n }\n\n //Ajout des sections\n var ArrayPrincipal = GetArrayHiddenSection();\n for(i=0;i<ArrayPrincipal.length;i++){\n\n var Longueur = ArrayPrincipal[i][0];\n var Type = ArrayPrincipal[i][1];\n var Hauteur = ArrayPrincipal[i][2];\n var ID = ArrayPrincipal[i][3];\n\n var MainTab = document.getElementById(\"TabSections\");\n\n var tr_0 = document.createElement('tr');\n tr_0.id = ID;\n if(Type == \"simple\" || Type == \"double\"){\n var td_0 = document.createElement('td');\n td_0.appendChild( document.createTextNode(Longueur + \"po\") );\n tr_0.appendChild( td_0 );\n }else{\n var td_0 = document.createElement('td');\n td_0.appendChild( document.createTextNode(Longueur + \"ft\") );\n tr_0.appendChild( td_0 );\n }\n\n if(Type == \"simple\" || Type == \"double\"){\n var td_1 = document.createElement('td');\n td_1.appendChild( document.createTextNode(\"Barrière \" + Type) );\n tr_0.appendChild( td_1 );\n }else{\n var td_1 = document.createElement('td');\n td_1.appendChild( document.createTextNode( Type) );\n tr_0.appendChild( td_1 );\n }\n\n var td_2 = document.createElement('td');\n td_2.appendChild( document.createTextNode(Hauteur+\"ft\") );\n tr_0.appendChild( td_2 );\n\n\n var td_4 = document.createElement('td');\n\n var button_0 = document.createElement('button');\n button_0.value = ID;\n button_0.appendChild( document.createTextNode(\"Retirer\") );\n button_0.className = \"StyleBtn bgred\";\n button_0.addEventListener('click', function(){ RetirerRowSection(this.value);}, false);\n td_4.appendChild( button_0 );\n\n tr_0.appendChild( td_4 );\n\n MainTab.appendChild( tr_0 );\n }\n\n CalculPrix();\n}",
"function mm_open_card_grid (modal_id) {\n var $modal = $('.mm-modal--' + modal_id),\n $mm_tabs = $('.mm-tabs', $modal);\n\n $mm_tabs.each(function () {\n var $this = $(this),\n group_id = $this.data('group-id'),\n tab_grid = $('.mm-tabs--'+group_id, $modal).data('grid'),\n $new_tab = $('.mm-tabs--'+group_id+'>div>.mm-tabs__tab--new', $modal),\n $tab_first = $('.mm-tabs--grid.mm-tabs--'+group_id+'>div>.mm-tabs__tab--1', $modal);\n\n if (tab_grid !== void 0 && tab_grid > 1) {\n for (var i=2; i<=tab_grid; i++) {\n var $tab_i = $('.mm-tabs--'+group_id+'>div>.mm-tabs__tab--'+i, $modal);\n\n if (!$tab_i.length) {\n // console.log(i, tab_grid);\n $new_tab.trigger('click');\n }\n }\n }\n\n $tab_first.trigger('click');\n });\n }",
"function createGrid() {\n let list = shuffle(gameData.symbols);\n for (item of list) {\n $('.deck').append('<li class=\"card\"> <i class=\"fa fa-' + item + '\"></i> </li>')\n }\n $('.card').on('click', showCard);\n }",
"_createColumnElementsTabs(siblingColumns, parent, container, tabs) {\n const that = this,\n id = that.id,\n gridTemplateColumns = [],\n columnFractions = [];\n\n siblingColumns.forEach((column, index) => {\n const columnElement = document.createElement('div');\n let innerHTML =\n `<div class=\"smart-kanban-column-contentAAA\" role=\"presentation\">\n <smart-scroll-viewer class=\"smart-kanban-column-content-tasks\"${that._rtlAttr}${that._tabindex} role=\"list\"></smart-scroll-viewer>BBB\n </div>`;\n\n if (column.columns) {\n innerHTML = innerHTML.replace('AAA', '');\n innerHTML = innerHTML.replace('BBB', '<div class=\"smart-kanban-column-content-columns has-tabs\" role=\"presentation\"></div>');\n }\n else {\n innerHTML = innerHTML.replace('AAA', ' no-sub-columns');\n innerHTML = innerHTML.replace('BBB', '');\n }\n\n columnElement.className = 'smart-kanban-column';\n columnElement.setAttribute('orientation', column.orientation);\n\n if (column.collapsible) {\n columnElement.setAttribute('collapsible', '');\n }\n\n if (column.addNewButton) {\n columnElement.setAttribute('add-new-button', '');\n }\n\n if (tabs) {\n const tab = document.createElement('div'),\n tabId = `${id}Tab${column.dataField}`,\n columnElementId = `${id}Column${column.dataField}`;\n\n tab.id = tabId;\n tab.className = 'smart-kanban-tab';\n\n if (!that.disabled && !that.unfocusable) {\n tab.tabIndex = 0;\n }\n\n tab.setAttribute('role', 'tab');\n tab.setAttribute('aria-controls', columnElementId);\n tab.innerHTML = `<div class=\"smart-kanban-tab-label\">${column.label}</div>`;\n tab.columnElement = columnElement;\n columnElement.id = columnElementId;\n columnElement.setAttribute('role', 'tabpanel');\n columnElement.setAttribute('aria-labelledby', tabId);\n columnElement.tab = tab;\n tabs.appendChild(tab);\n\n if (column.selected) {\n tab.classList.add('selected');\n }\n else {\n columnElement.classList.add('smart-hidden');\n }\n\n tab.setAttribute('aria-selected', column.selected);\n }\n else {\n innerHTML = that._getColumnHeader(column, index < siblingColumns.length - 1) + innerHTML;\n columnElement.setAttribute('role', 'group');\n columnElement.setAttribute('aria-labelledby', `${id}ColumnHeaderLabel${column.dataField}`);\n }\n\n columnElement.innerHTML = innerHTML;\n columnElement.siblingColumns = siblingColumns;\n\n parent.appendChild(columnElement);\n\n columnElement.column = column;\n columnElement.index = index;\n\n that._columnToElement.set(column, columnElement);\n\n if (column.columns) {\n const innerColumnContainer = columnElement.querySelector('.smart-kanban-column-content-columns'),\n ownTabs = document.createElement('div');\n\n ownTabs.className = 'smart-kanban-tab-strip';\n ownTabs.setAttribute('role', 'tablist');\n innerColumnContainer.appendChild(ownTabs);\n that._createColumnElementsTabs(column.columns, innerColumnContainer, innerColumnContainer, ownTabs);\n }\n\n if (!tabs) {\n if (column.collapsed) {\n columnElement.classList.add('collapsed');\n gridTemplateColumns.push('auto');\n }\n else {\n gridTemplateColumns.push('1fr');\n }\n\n columnFractions.push('1fr');\n }\n\n that._allColumns.push(column);\n });\n\n if (!tabs) {\n container.style.gridTemplateColumns = gridTemplateColumns.join(' ');\n container.fractions = columnFractions;\n that._columnContainers.push(container);\n }\n }",
"function g_tab(testoh1,elenco_task,color_class)\r\n{\r\n // a) modifico testo in <h1>\r\n const titoloh1= document.getElementById('titolo_tabella'); //id elemento h1\r\n titoloh1.innerText = testoh1; \r\n\r\n // b) Cancello contenuto Tabella\r\n initTable();\r\n\r\n // c) Inserisco nuove righe in tabella\r\n fillTaskTable(elenco_task);\r\n \r\n // d) Modifico stile elenco a sinistra (aside)\r\n //seleziono tutti gli elementi a, dentro al div, dentro all'elemento con id= left-sidebar -> per ognuno degli elementi a, gli rimuovo la classe active, che era quella che lo rendeva in evidenza\r\n //n.b. solo uno dei bottoni aveva la classe active, ma non posso sapere quale, così provo a toglierla a tutti\r\n document.querySelectorAll('#left-sidebar div a ').forEach( node => node.classList.remove('active'));\r\n document.getElementById(color_class).classList.add('active');\r\n //Aggiugno la classe active, solo al bottone che ho appena cliccato: corrisponde a quello sto vedendo in tabella\r\n\r\n}",
"function showTabBeers()\n{\n showTab('beer-results');\n}",
"function addTab(title) {\n var tab_title = (title.length==0)?'Graph '+tab_counter:title;\n var panelId = 'graphTab'+tab_counter++;\n\n var tabsLength = $(common.mustache(templates.graphTab, {\n title: tab_title,\n href: panelId\n }))\n .appendTo($graphTabs.find('.ui-tabs-nav'))\n .find('li').length;\n $graphTabs.append(common.mustache(templates.graphDiv, {\n panelId: panelId\n }));\n $graphTabs\n .tabs(\"refresh\")\n .tabs( \"option\", \"active\", tabsLength-1)\n .find('li.graph-tab span.ui-icon-close').off().click(removeTab);\n\n //this causes problem when deleting tabs\n $graphTabs.find( \".ui-tabs-nav\" ).sortable({ axis: \"x\", distance: 10 });\n $(\".ui-tabs-selected a\").each(function(){$(this).attr(\"title\", $(this).html())});\n resizeCanvas();\n\n //in revised layout, show only if graph tabs and search tables are shown $(\"#show-hide-pickers\").show();\n $('#graph-tabs a:last').click(function(){\n hideGraphEditor()\n });\n return panelId;\n}",
"function mm_open_card_grid_by_parent ($parent) {\n var $modal = $parent,\n $mm_tabs = $('.mm-tabs.mm-tabs--grid', $parent);\n\n $mm_tabs.each(function () {\n var $this = $(this),\n group_id = $this.data('group-id'),\n tab_grid = $('.mm-tabs--'+group_id, $modal).data('grid'),\n $new_tab = $('.mm-tabs--'+group_id+'>div>.mm-tabs__tab--new', $modal),\n $tab_first = $('.mm-tabs--grid.mm-tabs--'+group_id+'>div>.mm-tabs__tab--1', $modal);\n\n if (tab_grid !== void 0 && tab_grid > 1) {\n for (var i=2; i<=tab_grid; i++) {\n var $tab_i = $('.mm-tabs--'+group_id+'>div>.mm-tabs__tab--'+i, $modal);\n\n if (!$tab_i.length) {\n $new_tab.trigger('click');\n }\n }\n }\n\n $tab_first.trigger('click');\n });\n }",
"function CrearTablaSeguridadSocial(myJson) {\n\n var tabla = new grid(\"oTabla\");\n var j = 0;\n\n var obj = JSON.parse(myJson);\n deleteLastRow(\"oTabla\");\n //alert(obj.length);\n \n for (j = 0; j <= (obj.length - 1); j++)\n {\n //alert(obj[j].Descripcion);\n var row = tabla.AddRowTable(j + 1);\n\n \n var celda = tabla.AddRowCellText(row, 0, obj[j].id);\n celda.setAttribute('hidden', 'true'); // ocultar la columna ID\n tabla.AddRowCellText(row, 1, obj[j].fecha);\n tabla.AddRowCellText(row, 2, obj[j].concepto);\n tabla.AddRowCellNumber(row, 3, obj[j].LocaleImporte);\n tabla.AddRowCellText(row, 4,\n '<ul class=\"table-controls\">'+\n '<li ><a onclick=\"IngresoSeguridad('+(j+1)+');\" class=\"btn tip\" title=\"Pagar Nómina\"> <i class=\"icon-money\"> </i> </a></li>'+\n '<li ><a onclick=\"UpdateSeguridad('+(j+1)+');\" class=\"btn tip\" title=\"Editar Cargo Nómina\"> <i class=\"icon-pencil\"> </i> </a></li></ul>');\n \n }\n \n obj=null;\n\n}",
"function reload_grid(grid_id)\n{ \n if ($(\"#\" + grid_id).data(\"tab_id\"))\n {\n reload_tab_grid(grid_id);\n return;\n }\n\n reload_grid_by_id(grid_id);\n}",
"function changeActiveTab(sender, e) {\n var activeTab = sender.get_activeTabIndex();\n\n if (activeTab == 0) grdScrips.refresh();\n if (activeTab == 2) grdSupps.refresh();\n if (activeTab == 1) grdHist.refresh();\n if (activeTab == 3) grdHistSupp.refresh();\n}",
"function showDiv2() {\r\n document.getElementById('neworder').style.display = \"grid\";\r\n document.getElementsByClassName(\"tablinks1\")[0].className=\"tablinks1 active\";\r\n document.getElementsByClassName(\"tablinks1\")[1].className=\"tablinks1\";\r\n document.getElementById('removeorder').style.display = \"none\";\r\n }",
"function load_homeroom_tab(){\n\t$(\"homeroom_new_bt\").onclick = function(){\n\t\t$(\"homeroom_list\").hide();\n\t\t$(\"homeroom_new\").show();\t\n\t}\n\t/*$(\"homeroom_edit_bt\").onclick = function(){\n\t\t$(\"homeroom_list\").hide();\n\t\t$(\"homeroom_new\").show();\t\n\t}*/\n\t $$(\".homeroom_detail\").each(function(item){\n\t\titem.onclick = function(){\n\t\t\t$(\"homeroom_list\").hide();\n\t\t\t$(\"homeroom_detail\").show();\n\t\t\t};\n\t\t})\n\t $(\"homeroom_detail_cancel\").onclick = function(){\n\t\t$(\"homeroom_list\").show();\n\t\t$(\"homeroom_detail\").hide()\t\n\t}\n\t$(\"homeroom_new_cancel\").onclick = function(){\n\t\t$(\"homeroom_list\").show();\n\t\t$(\"homeroom_new\").hide()\t\n\t}\n}",
"function table_view_mode(){\n\n var _mode_btn = $('.card-header .mode_btn'),\n _table_mode = $('.table_mode');\n\n _mode_btn.on('click',function(){\n\n var a = $(this).attr('mode-id');\n\n var target = '.' + a;\n\n $(target).addClass('open').siblings('.table_mode').removeClass('open');\n\n $(this).addClass('open').siblings('.mode_btn').removeClass('open');\n\n //\n if ( a == 'gd_mode' ) {\n\n $('.grid_mode .frame').scrollbar({});\n\n calculate_grid();\n\n $(window).resize(function(){\n calculate_grid();\n });\n \n }\n\n });\n\n}",
"function addGridItems(grid) {}",
"generateGrid() {\n this.insertBlocks();\n this.insertWeapons();\n this.insertPlayers();\n this.displayGrid();\n }",
"function stampaTabArgomenti(argomenti) {\n let riga, colonna;\n let codHtml = \"\";\n\n if (argomenti.length > 0) {\n $(\"#sezNoArgomenti\").hide();\n $(\"#sezElArgomenti\").show();\n $(\"#corpoTabArgomenti\").html(\"\");\n $(\"#voceNavArgomenti\").addClass(\"active\");\n argomenti.forEach(argomento => {\n riga = $(\"<tr></tr>\");\n riga.attr(\"id\", \"argomento_\" + argomento[\"_id\"]);\n colonna = $(\"<td></td>\");\n colonna.html(argomento[\"descrizione\"]);\n riga.append(colonna);\n colonna = $(\"<td></td>\");\n colonna.html(argomento[\"matArgomento\"][0][\"descrizione\"]);\n riga.append(colonna);\n colonna = $(\"<td></td>\");\n colonna.html('<button type=\"button\" id=\"btnElimina_' + argomento[\"_id\"] + '\" class=\"btn btn-danger\" onclick=\"gestEliminaArgomento(this);\"><i class=\"fa fa-trash\" aria-hidden=\"true\"></i></button>');\n riga.append(colonna);\n $(\"#corpoTabArgomenti\").append(riga);\n });\n } else {\n codHtml = '<div class=\"col-sm-12 col-md-12 col-lg-12 mx-auto\">';\n codHtml += '<div class=\"section_tittle text-center\">';\n codHtml += '<h2>Nessuna argomento moderato</h2>';\n codHtml += '<p><a href=\"areaPersonale.html\">Torna all\\' area personale</a></p>';\n codHtml += '</div>';\n codHtml += '</div>';\n $(\"#contNoArgomenti\").html(codHtml);\n $(\"#sezNoArgomenti\").show();\n $(\"#sezElArgomenti\").hide();\n }\n}",
"function changeTab(){\n\n\t// Hide all tabs\n\tfor( var i=0; i<allSections.length; i++){\n\t\tallSections[i].style.display = \"none\";\n\n\n\t}\n\n\t//Switch based on the id of the button clicked\n\tswitch( this.id ){\n\n\t\tcase \"button-one\":\n\t\t\tallSections[0].style.display = \"block\";\n\t\tbreak;\n\n\t\tcase \"button-two\":\n\t\t\tallSections[1].style.display = \"block\";\n\n\t\tbreak;\n\n\t\tcase \"button-three\":\n\t\t\tallSections[2].style.display = \"block\";\n\n\t\tbreak;\n\n\t\tcase \"button-four\":\n\t\t\tallSections[3].style.display = \"block\";\n\n\t\tbreak;\n\n\t\tcase \"button-five\":\n\t\t\tallSections[4].style.display = \"block\";\n\n\t\tbreak;\n\n\t}\n\n\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a circular doubly linked list from polygon points in the specified winding order | function linkedList(data, start, end, dim, clockwise) {
var sum = 0,
i, j, last;
// calculate original winding order of a polygon ring
for (i = start, j = end - dim; i < end; i += dim) {
sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
j = i;
}
// link points into circular doubly-linked list in the specified winding order
if (clockwise === (sum > 0)) {
for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
} else {
for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
}
return last;
} | [
"function linkedList(points, clockwise) {\n var sum = 0,\n len = points.length,\n i, j, last;\n\n // calculate original winding order of a polygon ring\n for (i = 0, j = len - 1; i < len; j = i++) {\n var p1 = points[i],\n p2 = points[j];\n sum += (p2[0] - p1[0]) * (p1[1] + p2[1]);\n }\n\n // link points into circular doubly-linked list in the specified winding order\n if (clockwise === (sum > 0)) {\n for (i = 0; i < len; i++) last = insertNode(points[i], last);\n } else {\n for (i = len - 1; i >= 0; i--) last = insertNode(points[i], last);\n }\n\n return last;\n }",
"function linkedList(data, start, end, dim, clockwise) {\n var sum = 0,\n i, j, last;\n\n // calculate original winding order of a polygon ring\n for (i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n\n // link points into circular doubly-linked list in the specified winding order\n if (clockwise === (sum > 0)) {\n for (i = start; i < end; i += dim) last = insertNode(i, last);\n } else {\n for (i = end - dim; i >= start; i -= dim) last = insertNode(i, last);\n }\n\n return last;\n}",
"function linkedList(data, start, end, dim, clockwise) {\n var sum = 0,\n i, j, last;\n\n // calculate original winding order of a polygon ring\n for (i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n\n // link points into circular doubly-linked list in the specified winding order\n if (clockwise === (sum > 0)) {\n for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);\n } else {\n for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);\n }\n\n return last;\n}",
"function linkedList ( data, start, end, dim, clockwise, oclockwise )\r\n {\r\n var i,\r\n j,\r\n last;\r\n\r\n // link points into circular doubly-linked list in the specified winding order\r\n if ( clockwise === oclockwise )\r\n {\r\n for ( i = start; i < end; i += dim ) {last = insertNode( i, data[ i ], data[ i + 1 ], last );}\r\n }\r\n else\r\n {\r\n for ( i = end - dim; i >= start; i -= dim ) {last = insertNode( i, data[ i ], data[ i + 1 ], last );}\r\n }\r\n\r\n return last;\r\n }",
"makeCCW() {\n let br = 0,\n v = this.vertices;\n // find bottom right point\n for (let i = 1; i < this.vertices.length; ++i) {\n if (v[i][1] < v[br][1] || (v[i][1] == v[br][1] && v[i][0] > v[br][0])) {\n br = i;\n }\n }\n // reverse poly if clockwise\n if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) {\n this.reverse();\n }\n }",
"function linkedList(data,start,end,dim,clockwise){var i,last;if(clockwise===signedArea(data,start,end,dim)>0){for(i=start;i<end;i+=dim){last=insertNode(i,data[i],data[i+1],last);}}else{for(i=end-dim;i>=start;i-=dim){last=insertNode(i,data[i],data[i+1],last);}}if(last&&equals(last,last.next)){removeNode(last);last=last.next;}return last;}// eliminate colinear or duplicate points",
"radianSweep(polyList, middlePixel) {\n var firstQuadrant = [];\n var secondQuadrant = [];\n var thirdQuadrant = [];\n var fourthQuadrant = [];\n var orderedList = [];\n \n for (var i=0; i<polyList.length; i++) {\n if (polyList[i].x > middlePixel.x && polyList[i].y > middlePixel.y) {\n fourthQuadrant.push(this.calculateRadians(polyList[i], middlePixel));\n } else if (polyList[i].x < middlePixel.x && polyList[i].y > middlePixel.y) {\n thirdQuadrant.push(this.calculateRadians(polyList[i], middlePixel));\n } else if (polyList[i].x < middlePixel.x && polyList[i].y < middlePixel.y) {\n secondQuadrant.push(this.calculateRadians(polyList[i], middlePixel));\n } else if (polyList[i].x > middlePixel.x && polyList[i].y < middlePixel.y) {\n firstQuadrant.push(this.calculateRadians(polyList[i], middlePixel));\n };\n \n };\n \n orderedList.push(this.orderQuadrants(fourthQuadrant, thirdQuadrant, secondQuadrant, firstQuadrant));\n return orderedList;\n \n }",
"function polygon(start, end, sides) {\n var full = Vector.subtract(end, start);\n var angle = 180 - (sides - 2) * 180 / sides;\n var length = full.magnitude();\n var recursive = length / 5 > 2;\n\n for (var i = 0; i < sides; i++) {\n if (i > 0) {\n start = end;\n end = Vector.add(end, Vector.rotate(full, degToRad(angle * i)));\n }\n\n drawLine(start, end);\n \n if (recursive) {\n var part = Vector.multiply(full, 1 / 5);\n var permEnd = Vector.add(end, Vector.rotate(part, degToRad(angle * (i+1))));\n polygon(end, permEnd, sides);\n }\n }\n}",
"function createSOR(){ \r\n for (var angle=10; angle<=360; angle+=10){\r\n var theta = ((angle * Math.PI) / 180);\r\n var currentLine = shape[0];\r\n polyLine = [];\r\n\r\n for (var i = 0; i < currentLine.length; i++) {\r\n var coordIterator = currentLine[i];\r\n var x = (Math.cos(theta) * coordIterator.x) - (Math.sin(theta) * coordIterator.z);\r\n var y = coordIterator.y;\r\n var z = (Math.cos(theta) * coordIterator.z) + (Math.sin(theta) * coordIterator.x);\r\n polyLine.push(new coord(x, y, z));\r\n }\r\n shape.push(polyLine);\r\n }\r\n}",
"buildPointList () {\n var transBack = math.matrix.createTranslationMatrix(math.point.getPointX(this.pos) + this.width / 2,\n math.point.getPointY(this.pos) + this.height / 2)\n var pos = math.matrix.matmulVec(math.matrix.createTranslationMatrix(-math.point.getPointX(this.pos) - this.width / 2,\n -math.point.getPointY(this.pos) - this.height / 2), this.pos)\n\n var tl = math.matrix.matmulVec(transBack, math.matrix.matmulVec(this.rotationMtx, pos))\n var tr = math.matrix.matmulVec(transBack, math.matrix.matmulVec(this.rotationMtx, math.point.add(pos, math.point.createPoint(this.width, 0, 0))))\n var br = math.matrix.matmulVec(transBack, math.matrix.matmulVec(this.rotationMtx, math.point.add(pos, math.point.createPoint(this.width, this.height, 0))))\n var bl = math.matrix.matmulVec(transBack, math.matrix.matmulVec(this.rotationMtx, math.point.add(pos, math.point.createPoint(0, this.height, 0))))\n\n this.setPolyPoints([tl, tr, br, bl, tl])\n }",
"build(polygons) {\n if (!polygons || !polygons.length) {\n return;\n }\n\n if (!this.plane) {\n // TODO: Find a better plane\n //this.plane = polygons[0].plane.clone();\n this.plane = findSplittingPlane(polygons[0].plane, polygons);\n }\n\n let front = [];\n let back = [];\n polygons.forEach(p => this.plane.splitPolygon(p, this.polygons, this.polygons, front, back));\n\n if (front.length) {\n if (!this.front) {\n this.front = new BspNode();\n }\n\n this.front.build(front);\n }\n\n if (back.length) {\n if (!this.back) {\n this.back = new BspNode();\n }\n this.back.build(back);\n }\n }",
"function generatePolygon() {\n let vertices = document.getElementById(\"vertices\");\n\n if (vertices.value < 9 && vertices.value > 2) {\n n_points = vertices.value;\n points = [];\n \n // Push points to array\n for (var i = 0; i < n_points; i++) {\n points.push({\n x: Math.random() * canvas.width,\n y: Math.random() * canvas.height,\n connected: [],\n radius: 4\n });\n }\n } else {\n alert(\"Número inválido de pontos!\");\n }\n\n draw();\n}",
"function setupTriangles() {\r\n var p = setupPoints();\r\n return [\r\n //top\r\n p[0], p[4], p[1],\r\n p[1], p[4], p[5],\r\n p[1], p[5], p[2],\r\n p[2], p[5], p[6],\r\n p[2], p[6], p[3],\r\n p[3], p[6], p[7],\r\n \r\n //middle\r\n p[5], p[9], p[6],\r\n p[6], p[9], p[10],\r\n \r\n //bottom\r\n p[8], p[12], p[9],\r\n p[9], p[12], p[13],\r\n p[9], p[13], p[10],\r\n p[10], p[13], p[14],\r\n p[10], p[14], p[11],\r\n p[11], p[14], p[15]\r\n ];\r\n}",
"function createSharpCornerCpLoops(shape, sharpCornersArray) {\n let contactPointsPerLoop = [];\n let comparator = (a, b) => contact_point_1.default.compare(a.item, b.item);\n for (let k = 0; k < sharpCornersArray.length; k++) {\n let sharpCorners = sharpCornersArray[k];\n let cpLoop = new linked_loop_1.default([], comparator, k);\n let prevNode = undefined;\n for (let i = 0; i < sharpCorners.length; i++) {\n let pos = sharpCorners[i];\n let cp = new contact_point_1.default(pos, undefined);\n prevNode = cpLoop.insert(cp, prevNode, undefined);\n let mCircle = mat_circle_1.default.create(point_on_shape_1.default.getOsculatingCircle(pos), [prevNode]);\n prevNode.prevOnCircle = prevNode; // Trivial loop\n prevNode.nextOnCircle = prevNode; // ...\n }\n contactPointsPerLoop.push(cpLoop);\n }\n return contactPointsPerLoop;\n}",
"function polygon(centerX, centerY, nSides, radius) {\n push();\n translate(centerX, centerY); \n beginShape();\n for (let i=0; i < nSides; i++) {\n let angle = map(i, 0, nSides, 0, TWO_PI); \n let x = cos(angle) * radius; \n let y = sin(angle) * radius; \n vertex(x, y); \n }\n endShape(CLOSE); \n pop();\n}",
"function makeCouples() {\n // all the points on the curve are on the last gArrayAnim[gArrayAnim.length - 1]\n // the points array are sorted relative to polar angle (they follow the curve)\n\n // my last segment with all points on the curve\n var ptsOnCurve = gArrayAnim[gArrayAnim.length - 1];\n\n // If .fl = 1 I have a connection\n for (var i = 0; i < ptsOnCurve.length; i++) {\n ptsOnCurve[i].fl = 0;\n }\n\n // 0 --> it is a ghost; 1 --> it is a ghostbuster\n for (var i = 1; i < ptsOnCurve.length; i++) {\n if (ptsOnCurve[i - 1][2] != ptsOnCurve[i][2]) {\n // I find a couple\n gLineConnection.push([ptsOnCurve[i - 1].id, ptsOnCurve[i].id]);\n gLineConnection[gLineConnection.length - 1].fl = 1; // I put a flag = 1 --> just connected\n // I flag the 2 points\n ptsOnCurve[i - 1].fl = 1;\n ptsOnCurve[i].fl = 1;\n\n // I keep only the id of the point, the coords are in gArrayPoints\n // the coord of point with id = 3 are in gArrayPoints[3]\n i++;// not necessary to test the same point\n }\n }\n\n // Important: if the first point and the last point on the curve are not married and are different\n if ((ptsOnCurve[0].fl == 0 && ptsOnCurve[ptsOnCurve.length - 1].fl == 0) && (ptsOnCurve[0][2] != ptsOnCurve[ptsOnCurve.length - 1][2])) {\n // I find a couple\n gLineConnection.push([ptsOnCurve[0].id, ptsOnCurve[ptsOnCurve.length - 1].id]);\n gLineConnection[gLineConnection.length - 1].fl = 1; // I put a flag = 1 --> just connected\n\n // I flag the 2 points\n ptsOnCurve[0].fl = 1;\n ptsOnCurve[ptsOnCurve.length - 1].fl = 1;\n }\n\n // animation of the connections\n game.time.events.add(gDelay, drawLastCouple, this);\n }",
"function polygon(x,y,r,s){\r\n var a = Math.PI/(n+1);\r\n var points = [];\r\n var sides = [];\r\n ctx.beginPath();\r\n for(var i=0; i<=s; i++){\r\n var px = x + r*Math.cos(a), py= y + r*Math.sin(a);\r\n if(i===0){\r\n ctx.moveTo(px,py);\r\n }\r\n else{\r\n ctx.lineTo(px,py);\r\n sides.push([{x: points[i-1].x, y: points[i-1].y},{x: px,y: py}])\r\n }\r\n points.push({x: px, y:py});\r\n a += Math.PI*2/s;\r\n }\r\n points.pop(); //remove overlapping first and last points\r\n ctx.strokeStyle = color;\r\n ctx.lineWidth = 1;\r\n ctx.stroke();\r\n return {p:points, s:sides};\r\n}",
"build(polygons) {\r\n if (!polygons.length) {\r\n return;\r\n }\r\n if (!this.plane) {\r\n this.plane = polygons[0].plane.clone();\r\n }\r\n const front = [];\r\n const back = [];\r\n for (const polygon of polygons) {\r\n this.plane.splitPolygon(polygon, this.polygons, this.polygons, front, back);\r\n }\r\n if (front.length) {\r\n if (!this.front) {\r\n this.front = new Node();\r\n }\r\n this.front.build(front);\r\n }\r\n if (back.length) {\r\n if (!this.back) {\r\n this.back = new Node();\r\n }\r\n this.back.build(back);\r\n }\r\n }",
"function makeWinding(polygon, direction) {\n var winding = getWinding(polygon);\n return (winding === direction) ? polygon : polygon.reverse();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
UPDATING INFO If they chose to update employee role... | function directUserFromUpdateInfo () {
if (nextStep == "The role for an existing employee") {
updateEmployeeRole();
}
} | [
"function updateEmployeeRole() {\n console.log(\"employee role updated\"); \n\n}",
"function updateRole() {\n\n}",
"function updateEmployeeRole() {\n inquirer.prompt([\n {\n type: \"list\",\n message: \"Which employee's role would you like to update?\",\n name: \"employeeId\",\n choices: employeeList\n },\n {\n type: \"list\",\n message: \"What is the employee's new role?\",\n name: \"roleId\",\n choices: roleList\n }\n ]).then(function (response) {\n connection.query(`UPDATE employee SET role_id = ${response.roleId} WHERE id = ${response.employeeId}`)\n startProgram();\n })\n}",
"function updateEmployeeRole(employee, newRole){\n connection.query(`UPDATE employees SET role_id = ${newRole} WHERE id = ${employee};`, function(err, res) {\n if (err) {\n throw err;\n }\n else{\n console.log(`${res.affectedRows} record(s) updated`);\n populateEmployees();\n }\n });\n return;\n}",
"async updateRole(e) {\n let employee_id = await this.db.query(`SELECT id FROM employees WHERE CONCAT(first_name, \" \", last_name)=\"${e.employee_name}\"`);\n employee_id = Object.values(employee_id[0][0])[0];\n\n let role_id = await this.db.query(`SELECT id FROM employee_roles WHERE title=\"${e.employee_role}\"`);\n role_id = Object.values(role_id[0][0])[0];\n\n await this.db.query(`UPDATE employees SET role_id = ${role_id} WHERE id = ${employee_id}`);\n console.log(`>>> Role of ${e.employee_name} successfully changed to ${e.employee_role}. \\n`);\n }",
"function employeeRoleUpdate(employees) {\n connection.query(\n `SELECT * FROM role;`,\n (err, res) => {\n if (err) throw err;\n let question1 = {\n type: 'rawlist',\n name: 'role_list',\n message: 'Select which role you want to update with',\n choices() {\n let roleArr = [];\n for(i=0;i<res.length; i++) {\n roleArr.push(res[i].title);\n }\n return roleArr;\n }\n };\n inquirer.prompt(question1).then(answer => {\n let roleId;\n for(i=0;i<res.length; i++) {\n if(answer.role_list === res[i].title) {\n roleId = res[i].id;\n }\n };\n connection.query(\n 'UPDATE employee SET ? WHERE ?',\n [\n {\n role_id: roleId,\n },\n {\n id:employeeId,\n },\n ],\n (err) => {\n if(err) throw err;\n console.log('\\x1b[36m',`The current employee with the following last name: ${employees}, had their role successfully updated to: ${answer.role_list}.`,'\\x1b[0m');\n init();\n }\n );\n });\n }\n );\n }",
"async function updateEmployeeRole() {\n const employees = await db.allEmployees();\n\n\n const employeeChoices = employees.map(({ id, first_name, last_name }) => ({\n name: `${first_name} ${last_name}`,\n value: id\n }));\n\n const { employeeId } = await prompt(\n Questions.getTableChoice(\n \"list\",\n \"employeeId\",\n \"Select an employee\",\n employeeChoices\n )\n );\n\n const roles = await db.findAllRoles();\n\n const roleChoices = roles.map(({ id, title }) => ({\n name: title,\n value: id\n }));\n\n const { roleId } = await prompt(\n Questions.getTableChoice(\"list\", \"roleId\", \"Select a role\", roleChoices)\n );\n\n await db.updateEmployeeRole(employeeId, roleId);\n\n console.log(\"Employee's role has been updated successfully.\");\n\n displayPrompts();\n}",
"function updateEmployeeRole() {\n db.Employee.getEmployees(employees => {\n db.Role.getRoles(roles => {\n console.log(\"Select an employee\");\n promptSelectEmployee(employees).then(function (employeeid) {\n promptSelectRole(roles).then(function (roleid) {\n db.Employee.updateEmployeeRole(employeeid, roleid, employee => {\n mainMenu();\n });\n });\n });\n })\n })\n}",
"function updateEmployee() {\n\tinquirer\n\t\t.prompt([\n\t\t\t{\n\t\t\t\tname: \"id\",\n\t\t\t\ttype: \"input\",\n\t\t\t\tmessage: \"What's the ID number of the employee whose role you'd like to update?\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"new\",\n\t\t\t\ttype: \"input\",\n\t\t\t\tmessage: \"What's the new role ID for this employee?\",\n\t\t\t},\n\t\t])\n\t\t.then((answer) => {\n\t\t\tconst query = \"UPDATE employees SET role_id=? WHERE id=?\";\n\n\t\t\tconnection.query(query, [answer.new, answer.id], (error, response) => {\n\t\t\t\tif (error) throw error;\n\n\t\t\t\treturn response;\n\t\t\t});\n\t\t\tview(\"employees\");\n\t\t});\n}",
"function replaceRoleForEmployee() {\n connection.query(\n `UPDATE employee SET role_id = ${roleNumForRoleChange} WHERE id = ${employeeNumForRoleChange}`,\n\n function (err, res) {\n if (err) throw err;\n console.log(\"Role Updated!\");\n console.log(\n `UPDATE employee SET role_id = ${roleNumForRoleChange} WHERE id = ${employeeNumForRoleChange}`\n );\n mainMenu();\n }\n );\n}",
"function updateEmployeeRolePrompt () {\n return inquirer.prompt ([\n {\n type: \"list\",\n name: \"EmployeeToUpdate\",\n message: \"For which employee do you wish to update a role for?\",\n choices: currentEmployeeNames\n \n },\n {\n type: \"list\",\n name: \"EmployeeUpdatedRole\",\n message: \"Which role would you like to assign for this employee? (If you do not see the role listed here, please be sure to add a new role from the main menu before completing this step).\",\n choices: currentRoleNames\n }\n ])\n }",
"updateRole(employeeId, roleId) {\n return this.connection.query(\n `UPDATE employee e SET e.role_id = ${roleId} WHERE e.id = ${employeeId};`\n );\n }",
"updateRole(employeeId, roleId) {\n return this.connection.query(\n \"UPDATE employee SET role_id = ? WHERE id = ? ;\", [roleId, employeeId]\n );\n }",
"function employeeRole(employeeChoice) {\n var query = `SELECT title AS name, id FROM roles`\n\n connection.query(query, function (err, res) {\n if (err) throw err;\n\n const updateRoles = res.map(({ name, id }) => ({\n name: name, \n value: id\n }));\n\n updateEmployee(employeeChoice, updateRoles)\n })\n}",
"toggleRole() {\n if(this.role == 'Manager') {\n this.role = 'Employee';\n this.employee = this.tempEmployee;\n this.editEmployee = this.employee;\n } else {\n this.role = 'Manager';\n }\n }",
"updateEmployeeRole(employeeId, roleId) {\n return this.connection.query(\n \"UPDATE employee SET role_id = ? WHERE id = ?\", [roleId, employeeId]\n );\n }",
"updateEmployeeRole(employeeId, roleId) {\n return this.connection.query(\n \"UPDATE employee SET role_id = ? WHERE id = ?\",\n [roleId, employeeId]\n );\n }",
"function employeeRole(employeeChoice) {\n var query = \"SELECT title AS name, id FROM role\"\n\n connection.query(query, function (err, res) {\n if (err) throw err;\n\n const updatesRoles = res.map(({ name, id }) => ({\n name: name,\n value: id\n }));\n\n updateRole(employeeChoice, updatesRoles);\n });\n}",
"function updateEmployeeByID (req, res, next) {\n var empID = req.swagger.params.emp_id.value\n var userID = req.swagger.params.user_id.value\n var updateObject = req.swagger.params.body.value\n\n helper.isManager(userID).then(() => {\n return helper.checkChangedRole(updateObject)\n }).then(() => {\n updateObject.updated_at = moment().format(RFC2822)\n return repo.updateByID(empID, updateObject, 'users')\n }).then(result => {\n res.status(200).send({'successMessage': `User ${empID} has been updated`})\n }).catch(err => {\n res.status(400).send(err.stack)\n })\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For Updating cart item | function update_cart_item(cart_id){
showHint('quote-item.jsp?cart_id='+cart_id+'&update_cartitem=yes',cart_id,'quote_item');
} | [
"function update_cart_item(cart_id){\r\n showHint('bill-item.jsp?cart_id='+cart_id+'&update_cartitem=yes',cart_id,'bill_item');\r\n}",
"async updateCart_Of_User(){\n }",
"function updateCart(){\n\t\tstorage(['items', 'subtotal'], function(err, col){\n\t\t\t//console.log(\"Cart Collection - \" + JSON.stringify(col));\n\n\t\t\t//items = col[0];\n\t\t\t//subtotal = col[1];\n\n\t\t\tif(console) console.log(\"Items in Cart: \" + items);\n\t\t\tif(console) console.log(\"Subtotal of Cart: \" + subtotal);\n\t\t\t\n\t\t\t// update DOM Here\n\t\t\tdocument.getElementById( _options.itemsEleId ).innerHTML = items;\n\t\t\tdocument.getElementById( _options.subtotalEleId ).value = \"$\" + subtotal.toFixed(2);\n\n\t\t\t// reset default quantity input fields of products\n\t\t\tPRODUCTS.updateProducts();\n\t\t});\n\t}",
"function updateCart() {\n\n}",
"function doUpdateCart($button) {\n var pid = $button.attr('data-cart-pid');\n $.ajax({\n url: Drupal.settings.basePath + Drupal.settings.pathPrefix + 'cart/ajax',\n type: 'POST',\n data: {\n pid: pid\n },\n dataType: 'json',\n success: cartResponse\n });\n }",
"updateCartItemQuantity(itemId,skuId,name,price,quantity)\n { \n axios.put(this.cartJsonBoxUrl+\"/\"+itemId,{\n \"skuId\" : skuId,\n \"name\" : name,\n \"price\" : price,\n \"quantity\" : quantity\n }); \n return 1; \n }",
"static async updateItem(cart_id, data) {\n try {\n const cartItem = await CartItem.update(cart_id, data);\n\n return cartItem;\n } catch (err) {\n throw new Error(err);\n }\n }",
"updateCart(itemIndex, quantity) {\n let cart = []\n if (typeof window !== \"undefined\") {\n if (localStorage.getItem('cart')) {\n cart = JSON.parse(localStorage.getItem('cart'))\n }\n cart[itemIndex].quantity = quantity\n localStorage.setItem('cart', JSON.stringify(cart))\n }\n }",
"function updateQty(e) {\n\t\t\t'use strict';\n\t\t\tif (typeof e == 'undefined') var e = window.event;\n\t\t\t// Declare variables used in function\n\t\t\t var target = e.target || e.srcElement;\n\t\t\t var id = target.id;\n\t\t\t var newQty = getCart();\t\t\t\n\t\t\t\t\n\t\t\t\tfor(var x = 0; x < newQty.length; x++){\n\t\t\t\t\tvar newItemAmount = newQty[x].price;\n\t\t\t\t\tvar changedQty = U.$(id).value;\n\t\t\t\t\t\n\t\t\t\t\t if(id == newQty[x].id){\n\t\t\t\t\t\tvar updateCurrentPrice = changedQty * newItemAmount; \n\t\t\t\t\t\tnewQty[x].totalPrice = updateCurrentPrice; \n\t\t\t\t\t\tnewQty[x].qtyOrdered = changedQty; \t\t\t\t\n\t\t\t\t\t }\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\talert('Quantity has been updated');\n\t\t\t\tsessionStorage.setItem('usersCart', JSON.stringify(newQty));\n\t\t\t\t\n\t\t\tdisplayCart();\t\t\t\t\t\n\t\t} // end of update function */",
"function updateCart() {\n let cart = userCartData[\"cart\"];\n \n apiView(cart);\n\n let cartKeys = Object.keys(cart);\n let totalQuantity = 0;\n for (itemName of cartKeys) {\n totalQuantity += cart[itemName][\"quantity\"];\n }\n userCartData[\"total_quantity\"] = totalQuantity;\n\n localStorage.setItem(\"user_cart_data\", JSON.stringify(userCartData));\n document.getElementById(\"quantity\").innerHTML = totalQuantity;\n}",
"async update({commit, dispatch, getters}, item) {\n // const { data: {id, code} } = await this.$axios.put(\n // `/api/cart/${getters.getCode}`,\n // request\n // )\n\n commit(CART_MUTATIONS.UPDATE_CART_ITEM, item)\n }",
"function handleUpdate(e) {\n\tfor (let name in updatedQuantity) { // sample updatedQuantity: {usmc fitness book: \"20\", usmc pt shirt 1: \"9\"}\n\t\tcart.updateCart(name, +updatedQuantity[name])\n\t}\n\treRenderTableBody();\n\trenderCartTotal();\n}",
"function cartUpdated() {\n $('.change-cart-item-quantity').on('click', function(evt){\n evt.preventDefault();\n var $button = $(this);\n var $item = $button.closest('.cart-item');\n var id = $item.data('id');\n var quantity = $(`#update-quantity-${id}`).val();\n updateItem(id, quantity);\n renderCart();\n });\n $('.remove-cart-item').on('click', function(evt){\n evt.preventDefault();\n var $button = $(this);\n var $item = $button.closest('.cart-item');\n var id = $item.data('id');\n removeItem(id);\n renderCart();\n });\n}",
"function updateOneItem(cart, item) {\n\tconsole.log('in update helper');\n\tconst { itemID, name, quantity } = item;\n\tlet itemIndex = cart.inventory.findIndex((p) => p.itemID == itemID);\n\tif (itemIndex > -1) {\n\t\t//item exists in the inventory, update the quantity\n\t\tlet newItem = cart.inventory[itemIndex];\n\t\tnewItem.quantity += quantity;\n\t\tif (newItem.quantity <= 0) {\n\t\t\tconsole.log('index: ' + itemIndex);\n\t\t\tif (itemIndex == 0) {\n\t\t\t\tcart.inventory.splice(itemIndex, itemIndex + 1);\n\t\t\t} else {\n\t\t\t\tcart.inventory.splice(itemIndex, itemIndex);\n\t\t\t}\n\t\t} else {\n\t\t\tcart.inventory[itemIndex] = newItem;\n\t\t}\n\t} else {\n\t\t//item does not exists in inventory, add new item\n\t\tcart.inventory.push({ itemID, name, quantity });\n\t}\n}",
"increaseQty(cartItem){\n cartItem.product.inStock--\n cartItem.quantity++\n }",
"updateQuantity(event) {\n // event.value return string that check if true then true else return false\n this.flag = (event.target.value == 'true')\n axios.put('/api/cart', {\n increase: this.flag,\n productId: event.target.id\n }).then((res) => {\n // new cart response with updated data\n this.cart = res.data\n this.totalAmount = 0\n // set total amount\n for (var item of this.cart) {\n this.totalAmount += item.amount\n }\n }).catch((err) => {\n alert(err.response.data.error)\n })\n }",
"function updateProduct(quantity) {\n}",
"function updatedCartItem(itemsInCart, index, newQty, productDiscount, globalDiscount, client, uuid) {\n\n var data = caclSubtotal(itemsInCart[index].product, newQty, productDiscount, globalDiscount, client);\n\n return {\n uuid: uuid,\n product: itemsInCart[index].product,\n discountCurrency: data.discountCurrency,\n qty: newQty,\n discount: productDiscount,\n subTotalNoDiscount: data.subTotalNoDiscount,\n subtotal: data.subtotal,\n totalWithIv: data.totalWithIv,\n lote: itemsInCart[index].lote,\n priceToUse: data.priceToUse\n };\n}",
"function updateCart (name, qty) {\n for (let i = 0; i < cart.length; i += 1) {\n if (cart[i].name === name) {\n cart[i].qty = qty\n showItems()\n return\n }\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function: getCurrentFileOrDefault Description: This function will see if TaskPaper is already running. If it is, then it will return the file it has open. Otherwise, it will return the last saved TaskPaper file location. Inputs: | function getCurrentFileOrDefault() {
var pFile = LaunchBar.executeAppleScript('if application "TaskPaper" is running then',
'tell application id (id of application "TaskPaper")',
' set a to file of the front document',
' return POSIX path of a',
'end tell',
'else',
' return ""',
'end if').trim();
if (pFile == "") {
if(File.exists(LaunchBar.homeDirectory + "/.tpProjectFile"))
pFile = File.readText(LaunchBar.homeDirectory + "/.tpProjectFile");
} else {
//
// Save the path to the ~/.tpProjectFile location.
//
File.writeText(pFile, LaunchBar.homeDirectory + "/.tpProjectFile");
}
//
// Return the project file location.
//
return (pFile);
} | [
"function getActiveFile() {\n return activeFile;\n }",
"function getActiveFile() {\n var active = getActiveTab();\n if(!active) {\n return false;\n }\n return lt.objs.tabs.__GT_path(active);\n }",
"function getFilePath()\n{\n\ttry\n\t{\n\t\tatom.workspace.getActiveTextEditor().buffer.save()\n\t\tvar filePath = atom.\n\t\tworkspace.\n\t\tgetActiveTextEditor().\n\t\tbuffer.\n\t\tfile.\n\t\tpath;\n\t}\n\t// If the file is not saved, it will throw a TypeError since there is\n\t//\tneither a directory or filename\n\tcatch(TypeError)\n\t{\n\t\tconsole.log('ERROR: Could not find the path to the current file, please make sure it is saved');\n\t\treturn 0;\n\t}\n\tif (filePath == undefined)\n\t{\n\t\tconsole.log('ERROR: Cannot read filepath, is the file saved?');\n\t\treturn 0;\n\t}\n\telse if (filePath.endsWith('.py') || filePath.endsWith('.pyw'))\n\t{\n\t\tconsole.log(filePath);\n\t\treturn filePath;\n\t} else {\n\t\tconsole.log('ERROR: This is not a valid filetype');\n\t\treturn 0;\n\t}\n}",
"getCurrentFilePath() {\n return atom.workspace.getActiveTextEditor().buffer.file.path;\n }",
"getCurrentFilePath() \n {\n return this.context.document.fileURL().path().replace(/\\.sketch$/, '')\n }",
"file () {\n try {\n const file = this.currentFile()\n\n if (!file) throw createError({ code: 'ENOENT', message: 'No file selected' })\n return file\n } catch (e) {\n throw new Error(e)\n }\n }",
"_getSelectedFile(): ?string {\n\t\tconst i = this._normalizedSelectionIndex();\n\t\tconst result = this.state.fileResults[i];\n\t\tif (!result.isDirectory) return result.name;\n\t\treturn null;\n\t}",
"getFile() {\n const at = vscode.window.activeTextEditor;\n if (!at) {\n return null;\n }\n const cursor = at.selection.active;\n if (cursor.line < 1) {\n return null;\n }\n return this._files[cursor.line - 1]; // 1 means direpath on top;\n }",
"function PINT_GetDefaultFile()\r\n\t{\r\n\tif( typeof( defaultFile ) == 'undefined' )\t\r\n\t\treturn \"\";\r\n\telse\r\n\t\treturn defaultFile;\r\n\t}",
"async _current() {\n Logger.info(\"Looking for the current PR...\");\n const stagedBranchSha = await GH.getReference(Config.stagingBranchPath());\n const stagedBranchCommit = await GH.getCommit(stagedBranchSha);\n Logger.info(\"Staged branch head sha: \" + stagedBranchCommit.sha);\n const prNum = Util.ParsePrNumber(stagedBranchCommit.message);\n if (prNum === null) {\n Logger.info(\"Could not track a PR by the staged branch.\");\n } else {\n const pr = await GH.getPR(prNum, false);\n if (pr.state === 'open') {\n Logger.info(\"PR\" + prNum + \" is the current\");\n return pr;\n }\n Logger.info(\"Tracked PR\" + prNum + \" by the staged branch but it is already closed.\");\n }\n Logger.info(\"No current PR found.\");\n return null;\n }",
"getPath () {\n // Get the path of the current active item\n const projectPaths = atom.project.getPaths()\n if (projectPaths.length === 1) return projectPaths[0]\n\n // If there are multiple projects, get the path based on the current active item\n let activePath\n try {\n const activeItem = atom.workspace.getCenter().getActivePaneItem()\n activePath = activeItem.buffer.file.path\n } catch (e) {\n return null\n }\n\n // Check which project path the file is located in\n const projectPath = projectPaths.find((path) => activePath.indexOf(activePath) !== -1)\n\n return projectPath\n }",
"function getEdittingFilePath() {\n return currentEdittingFile;\n}",
"getLastSessionProjectPath() {\n const lastProject = this.data.lastOpenedProject['filePath'];\n return lastProject ? lastProject : null;\n }",
"function getTodoFile() {\n\t\ttodoFile = todoFile || getProjectRoot() + '.todo';\n\t\t\n\t\treturn todoFile;\n\t}",
"function getDisplayCurrentBackgroundFile() {\r\n return localStorage.getItem(\"display-current-background-file\");\r\n }",
"function getCurrentDateForFileName () {\r\n return DateTimeHelper.getCurrentDateForFileName();\r\n }",
"function CURRENT_TASK() {\n return GLOBAL_TASKS[0];\n}",
"function getCurrentIfAny() {\n if (!currentProject) {\n console.error(types.errors.CALLED_WHEN_NO_ACTIVE_PROJECT_GLOBAL);\n throw new Error(types.errors.CALLED_WHEN_NO_ACTIVE_PROJECT_GLOBAL);\n }\n return currentProject;\n }",
"function getFileInput() {\n return _currentFileInput;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check for changes in the settings | function checkForSettingChanges()
{
var changesDetected = false;
g_settingChanges.forEach(function(element)
{
if (element.hasChanged() == true)
{
changesDetected = true;
}
}, this);
var applyButton = document.getElementById('apply_setting_changes');
if (changesDetected == true)
{
applyButton.removeAttribute('disabled');
}
else
{
applyButton.setAttribute('disabled', 'disabled');
}
} | [
"_settings_changed() {\n \tif (!this.settings_already_changed) {\n \t\tMain.notify(\"Please restart BaBar extension to apply changes.\");\n \t\tthis.settings_already_changed = true;\n \t}\n }",
"settingsChanged() {\n var lastChecksum = this._stateManager.getAtomSettingsChecksum()\n var checksum = this.getAtomSettingsChecksum()\n return lastChecksum && checksum != lastChecksum\n }",
"function hasChanges() {\n for (const key of Object.keys(originalSettings)) {\n if (originalSettings[key] !== curSettings[key])\n return true;\n }\n return false;\n}",
"function onSettingChanged() {\n\t\t\tlogDebug(\"Settings have changed!\");\n\t\t\tbrowser.storage.local.get([\"suspended\", \"sites\", \"filter\"])\n\t\t\t.then(function(pref) {\n\t\t\t\tlogDebug(pref);\n\t\t\t\tg_isSuspended = pref.suspended || false;\n\t\t\t\tcheckSiteStatus(pref.sites);\n\n\t\t\t\tg_filter = pref.filter || \"\";\n\t\t\t\tif (g_filter == \"\") g_isSuspended = true;\n\n\t\t\t}, onError);\n\t\t}",
"function checkSettings () {\n// If no setting found\n settings.defaultSettings(true)\n // Apply them\n applySettings()\n // Set theme\n setTheme(settings.mobySettings.Theme)\n}",
"function _settingsChanged(ev) {}",
"handleSettingsChange() {}",
"function onSettingsChange(){\r\n\t\t\r\n\t\tif(g_objInputUpdate)\r\n\t\t\tupdateValuesInput();\r\n\t}",
"function checkConfigChange(){\r\n\r\n\tReadConfigSettings = undefined;\r\n\tFileConfigs = Object.keys(PP_config);\r\n\tConfigSettings.configs = [];\r\n\r\n\tif(localStorage.getItem('PP_Config_settings_' + ConfigName)){\r\n\t\tReadConfigSettings = JSON.parse(localStorage.getItem('PP_Config_settings_' + ConfigName));\r\n\t}\r\n\tif(ReadConfigSettings){\r\n\t\t// array intersection to find which elements are in both\r\n\t\tlet inBoth = ReadConfigSettings.configs.filter( x => FileConfigs.includes(x));\r\n\t\tif(inBoth.length>0){\r\n\t\t\t//alert(\"in Both => check versions: \"+JSON.stringify(inBoth));\r\n\t\t\tfor(const config of inBoth){\r\n\t\t\t\tcompareVersions(config);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// array difference to find which ones add\r\n\t\tlet inConfigFile = FileConfigs.filter( x => !ReadConfigSettings.configs.includes(x));\r\n\t\tif (inConfigFile.length>0){\r\n\t\t\t//alert(\"only in config file NOT in local storage => add \"+JSON.stringify(inConfigFile));\r\n\t\t\tfor(const config of inConfigFile){\r\n\t\t\t\taddConfig(config);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// array difference to find which ones remove\r\n\t\t/*\r\n\t\t// don't need to handle remove since compare only copies the ones in both and removes superfluous ones from local storage in that go \r\n\t\tlet inLocalStorage = ReadConfigSettings.configs.filter( x => !FileConfigs.includes(x));\r\n\t\tif(inLocalStorage.length > 0){\r\n\t\t\t//alert(\"only in local storage NOT in file any more => remove \"+JSON.stringify(inLocalStorage));\r\n\t\t}\r\n\t\t*/\t\r\n\t}else{\r\n\t\t// if I don't have any settings they all need to be added\r\n\t\t//alert(\"initialize all\")\r\n\t\tfor(const config of Object.keys(PP_config)){\r\n\t\t\taddConfig(config);\r\n\t\t}\r\n\t}\r\n\r\n\t// Now at last save settings to local storage\r\n\tlocalStorage.setItem('PP_Config_settings_' + ConfigName,JSON.stringify(ConfigSettings));\r\n\t//alert(JSON.stringify(ConfigSettings));\r\n\r\n\t// need to populate the lookup table which convertes the uniqueID of each puzzle - for social media sharing - to config/pano value\r\n\t// doing this so a shared link still points to the correct panorama even if the configuration has changed\r\n\t// if a uniqueID does NOT exist any more - meaning this puzzle has been removed from the configuration a message should pop up and lead you to the newest puzzle in this config.\r\n\tcreateShareLinkLookup();\r\n\r\n}",
"async onSettings({ oldSettings, newSettings, changedKeys }) {\n await this.checkCapabilities(newSettings);\n }",
"settingsHaveChanged() {\n const { currentSettings } = this.state;\n const { settings } = this.props;\n let changed = false;\n let settingsByType = currentSettings;\n\n if (settings.toggled === 'citySettings') {\n settingsByType = {\n helsinki: currentSettings.helsinki,\n espoo: currentSettings.espoo,\n vantaa: currentSettings.vantaa,\n kauniainen: currentSettings.kauniainen,\n };\n } else if (settings.toggled === 'mapSettings') {\n settingsByType = {\n mapType: currentSettings.mapType,\n };\n } else if (settings.toggled === 'accessibilitySettings') {\n settingsByType = {\n colorblind: currentSettings.colorblind,\n hearingAid: currentSettings.hearingAid,\n mobility: currentSettings.mobility,\n visuallyImpaired: currentSettings.visuallyImpaired,\n };\n }\n\n Object.keys(settingsByType).forEach((key) => {\n if (changed) {\n return;\n }\n\n const settingsHasKey = Object.prototype.hasOwnProperty.call(settings, key);\n const currentHasKey = Object.prototype.hasOwnProperty.call(settingsByType, key);\n if (settingsHasKey && currentHasKey) {\n const a = settings[key];\n let b = settingsByType[key];\n // Handle comparison with no mobility settings set\n if (key === 'mobility' && b === 'none') {\n b = null;\n }\n\n if (a !== b) {\n changed = true;\n }\n }\n });\n\n return changed;\n }",
"function _check_if_exist_change(){\n try{\n return _is_make_changed;\n }catch(err){\n self.process_simple_error_message(err,window_source+' - _check_if_exist_change');\n return false; \n } \n }",
"function updateSettings () {\n if (identifier !== 'pomo' || startButton.textContent === 'Start') {\n console.log('Updating settings')\n for (const [key, cbv] of Object.entries(outdatedSettings)) {\n console.log('Update:', key)\n // Callback(newValue)\n cbv[0](cbv[1])\n\n delete outdatedSettings[key]\n }\n } else {\n console.log('Delaying settings update until we are not in progressing')\n }\n}",
"function checkStoredSettings(storedSettings) {\n\tvar temp = storedSettings.configs;\n\tbrowser.storage.local.set({\n\t\tconfigs : configs\n\t});\n\tif(temp){\n\t\tbrowser.storage.local.set({\n\t\t\tconfigs : temp\n\t\t});\n\t}\n}",
"function checkSettingsRetrieved()\n{\n\tif (highlightedVideos != null && showRpScore != null)\n\t{\n\t\tonSettingsRetrieved();\n\t}\n\telse\n\t{\n\t\tsetTimeout(function () { checkSettingsRetrieved(); }, 40);\n\t}\n}",
"scanSettingsChange_() {\n // The user can only change scan settings when the app is in READY state. If\n // a setting is changed while the app's in a non-READY state, that change\n // was triggered by the scanner's capabilities loading so it's not counted.\n if (this.appState_ !== AppState.READY) {\n return;\n }\n\n ++this.numScanSettingChanges_;\n }",
"function checkSettings() {\n if (typeof(settings)==\"undefined\") return false;\n return (settings.version == expected_settings_version);\n}",
"function checkSettings() {\n setupDone = localStorage.getItem(\"setup_done\");\n if (!setupDone) {\n $(\"#settings_text\").text(\"Please change settings if needed, and Save.\");\n updateStatus(\"Please change settings if needed, and Save.\")\n $(\"#settingsModal\").slideDown(\"slow\");\n }\n else {\n //Set prompt text for the settings modal message area (jQuery)\n $(\"#settings_text\").css('color', '#3aafa9');\n $(\"#settings_text\").text(\"Blink interval = 0 for no blink of green marker\");\n getStoredSettings();\n updateStatus('Loaded settings..');\n }\n\n //Initialise the search location to default position if set\n if (defaultLocationLat && (defaultLocationLng)) {\n search_position = new google.maps.LatLng({\n lat: parseFloat(defaultLocationLat),\n lng: parseFloat(defaultLocationLng)\n });\n\n }\n}",
"function autoUpdateCheck(){\n\t//get the auto update value\n\tconst auto_update = settings.get('auto_update');\n\tif(auto_update === true){\n\t\tconsole.log(\"Checking for updates with auto updater\");\n\t\tpullUpdate();\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if response has success and data fields | function hasSuccessAndData(res) {
assert(res.body.success, "response should have success field");
assert(res.body.data, "response should have data field");
} | [
"function checkData(res) {\n assert.equal(res.body.success, \"true\", \"success should be true\");\n assert.equal(res.body.data, testData.note.data, \"request and response data should be equal\");\n }",
"validateResponse (data) {\n\t\tAssert.deepStrictEqual(data, {}, 'empty response not returned');\n\t}",
"validateResponse (data) {\n\t\t// the response will be empty, since there is no change\n\t\tAssert.deepEqual(data, { }, 'expected empty response');\n\t}",
"validResponse(response) {\n return (response != null && !response.isError && response.success);\n }",
"function checkResp(body) {\n assert.containsAllKeys(body, ['data']);\n}",
"function isSuccessResp (resp) {\n return resp.data.code === 0;\n}",
"function checkResponse() {\n response = JSON.parse(this.response);\n if (this.status == 200) {\n flash(response.status);\n } else {\n flash(response.status, true);\n }\n}",
"function IsSuccess(p_Response)\n{\n if (p_Response.success == \"true\" || p_Response.success == \"1\")\n {\n return true;\n }\n\n return false;\n}",
"validateResponse (data) {\n\t\tthis.validateDisposition(data);\n\t\tthis.validateVersionInfo(data);\n\t\tthis.validateAgentInfo(data);\n\t\tthis.validateAssetUrl(data);\n\t}",
"function IsAjaxResult(data) {\n return (data.Status && data.Message);\n}",
"function validateReserveResponseData(data) {\n if(!data.hasOwnProperty('status')) console.error(\"Reserve response should have a 'status' key\");\n if(!data.hasOwnProperty('message')) console.error(\"Reserve response should have a 'message' key\");\n }",
"validateResponse (data) {\n\t\tAssert(data.codeError.modifiedAt >= this.modifiedAfter, 'modifiedAt is not greater than before the code error was updated');\n\t\tthis.expectedCodeError.modifiedAt = data.codeError.modifiedAt;\n\t\t// verify what we fetch is what we got back in the response\n\t\tAssert.deepEqual(data.codeError, this.expectedCodeError, 'fetched code error does not match');\n\t}",
"function validResponse(response) {\n\tif (typeof response != 'undefined' && response != null) {\n\t\tif (typeof response['results'] != 'undefined' && response['results'] != null) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}",
"function checkResponse(response) {\n if (response.code === 200) {\n console.log('Okay ', response.code);\n } else {\n console.log('There was an error: ', response.code);\n }\n }",
"checkResponse(res) {\n // Variables\n const regexFail = /2\\d+/;\n // Check Response Formed Well\n if (res) {\n // Get Data\n const transportCode = res.status.transport.code;\n const commandCode = res.status.command.code;\n // Check Response Body\n if (regexFail.test(transportCode)) {\n return 2;\n } else if (regexFail.test(commandCode)) {\n return 1;\n } else {\n return 0;\n }\n } else {\n return 3;\n }\n }",
"function isSuccess(request) {\n if (request.kind === \"success\") {\n return request.result;\n }\n return null;\n}",
"validateResponse (data) {\n\t\tconst emailProp = `email: '${this.currentUser.user.email}'`;\t\t\n\t\tconst teamProp = `'Team Name': '${this.team.name}'`;\n\t\tconst identifyCall = 'window.analytics.identify';\n\t\tAssert.notEqual(data.indexOf(emailProp), -1, 'did not get expected email in the html response');\t\t\n\t\tAssert.notEqual(data.indexOf(teamProp), -1, 'did not get expected team name in the html response');\n\t\tAssert.notEqual(data.indexOf(identifyCall), -1, 'did not get expected identify call in the html response');\n\t\tsuper.validateResponse(data);\n\t}",
"function HasValidResponse(){\n\treturn !(RequestInProgress || typeof(RawResponse) === 'undefined' || RawResponse == null || IsErrorResponse(RawResponse));\n}",
"isOk() {\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get Argo server namespace | getArgoServerNS() {
return client.query({ query: Query.argoServerNS })
} | [
"async getNamespace(request) {\n return doFetch(request,\"NamespaceService\",\"GetNamespace\")\n\t}",
"async namespace() {\n return this.release.namespaces.get(this.typePrefix);\n }",
"get namespace() {\n return this.extractNamespace(this.options);\n }",
"function getNamespace() {\n\tvar ns = '';\n\tvar fileExists = fs.existsSync(path.dirname(require.main.filename) + '/package.json');\n\tif(fileExists) {\n\t\tvar projectName = require(path.dirname(require.main.filename) + '/package.json').name;\n\t\tif(projectName.indexOf('-') !== -1) {\n\t\t\tvar splitName = projectName.split('-');\n\t\t\tvar len = splitName.length >= 3 ? 3 : splitName.length;\n\t\t\tfor(var i = 0; i < len; i++) {\n\t\t\t\t\tns += splitName[i][0];\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tns = projectName.slice(0, 3);\n\t\t}\n\t}\n\telse {\n\t\tns = 'app'\n\t}\n\treturn ns.toUpperCase();\n}",
"get serverNamespace() {\n return this._prefs.get(\"documentServerNamespace\", \"metrics\");\n }",
"function GetNamespace(mn, inScopeNamespaces) {\n _awayfl_swf_loader__WEBPACK_IMPORTED_MODULE_2__[\"release\"] || Object(_awayjs_graphics__WEBPACK_IMPORTED_MODULE_1__[\"assert\"])(mn.isQName());\n var uri = mn.uri;\n for (var i = 0; inScopeNamespaces && i < inScopeNamespaces.length; i++) {\n if (uri === inScopeNamespaces[i].uri) {\n return inScopeNamespaces[i];\n }\n }\n return mn.namespaces[0];\n}",
"function getNamespace() {\n var namespace=\"\", argument;\n for(var i=0; i<arguments.length; i++){\n if(typeof arguments[i] !== \"string\") continue;\n\n argument = arguments[i].split(\":\")[0];\n\n if(argument.charAt(0) === \".\") {\n namespace = argument.substring(1);\n }\n else if(namespace !== \"\"){\n namespace += \".\"+argument;\n }\n else {\n namespace = argument;\n }\n }\n return namespace;\n}",
"function getSpawnerNamespaces(){\n return getCacheData('/xapi/spawner/namespaces');\n }",
"get fullyQualifiedNamespace() {\n return this._context.fullyQualifiedNamespace;\n }",
"apiGetNamespaces() {\n return this._apiGet('namespaces')\n }",
"get namespaceURL()\n\t{\n\t\treturn this.namespace && this.namespace.url;\n\t}",
"function GetDefaultNamespace() {\n\t\t// TODO\n\t\treturn DefaultNamespace;\n\t}",
"function getClassNamespace() {\n return NS;\n}",
"function fetchNamespaces() {\n return services_k8s.getNamespaces().done(function (namespaceDataArray) {\n src_reactor[\"a\" /* default */].dispatch(SITE_RECEIVE_NAMESPACES, namespaceDataArray);\n });\n}",
"function findNameSpace(uri){\n\tvar ns = new Object();\n\tns.nspace = uri.replace(/(\\/|#)[^#\\/]*$/, \"$1\");\n\tns.name = uri.replace (ns.nspace, \"\");\n\n\treturn ns;\n}",
"function getEventMeshNamespace() {\n try {\n if (eventMeshSecretFilePath === '') {\n return undefined;\n }\n const eventMeshSecret = JSON.parse(fs.readFileSync(eventMeshSecretFilePath, {encoding: 'utf8'}));\n return '/' + eventMeshSecret['namespace'];\n } catch (e) {\n console.error(e);\n return undefined;\n }\n}",
"function protocolNamespace(protocol) {\n if (protocol.namespace) {\n return protocol.namespace;\n }\n var match = /^(.*)\\.[^.]+$/.exec(protocol.protocol);\n return match ? match[1] : undefined;\n}",
"function GetNamespace(mn, inScopeNamespaces) {\n release || assert(mn.isQName());\n var uri = mn.uri;\n for (var i = 0; inScopeNamespaces && i < inScopeNamespaces.length; i++) {\n if (uri === inScopeNamespaces[i].uri) {\n return inScopeNamespaces[i];\n }\n }\n return mn.namespaces[0];\n }",
"async putNamespace(request) {\n return doFetch(request,\"NamespaceService\",\"PutNamespace\")\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find deep value diff between frames | valDiff(toUpdate) {
let res = {};
toUpdate.forEach((entity) => {
res[entity.id] = {};
Object.keys(entity).forEach((key) => {
if (this.frameNew[entity.id][key] === undefined ||
this.frameOld[entity.id][key] === undefined) {
res[entity.id][key] = 0;
} else {
res[entity.id][key] = this.frameNew[entity.id][key] - this.frameOld[entity.id][key];
}
});
});
return res;
} | [
"refDiff() {\n let res = {\n toAdd: [],\n toRemove: [],\n toUpdate: [],\n };\n Object.keys(this.frameNew).forEach((key) => {\n !this.frameOld[key] && res.toAdd.push(this.frameNew[key]);\n this.frameOld[key] && res.toUpdate.push(this.frameNew[key]);\n });\n Object.keys(this.frameOld).forEach((key) => {\n !this.frameNew[key] && res.toRemove.push(this.frameOld[key]);\n });\n return res;\n }",
"frameDiff(prev, curr) {\n if (prev == null || curr == null) { return false;};\n\n let avgP, avgC, diff, j, i;\n const p = prev.data;\n const c = curr.data;\n const thresh = this.makeThresh(this.pixelDiffThreshold);\n\n // thresholding function\n const pixels = new Uint8ClampedArray(p.length);\n\n let count = 0;\n\n // for each pixel, find if average excees thresh\n i = 0;\n while (i < p.length / 4) {\n j = i * 4;\n\n avgC = 0.2126 * c[j] + 0.7152 * c[j + 1] + 0.0722 * c[j + 2];\n avgP = 0.2126 * p[j] + 0.7152 * p[j + 1] + 0.0722 * p[j + 2];\n\n diff = thresh(avgC - avgP);\n\n pixels[j + 3] = diff;\n\n // if there is a difference, update bounds\n if (diff) {\n pixels[j] = diff;\n\n // count pix movement\n count++;\n }\n\n i++;\n }\n\n return {\n count: count,\n imageData: new ImageData(pixels, this.workingSize.x), };\n }",
"function modelElementDifference(source,target,depth) {\n \n //init the depth to one = checking references\n var depth = depth==undefined? 1 : depth;\n \n if(target!==undefined && source!==undefined) {\n var diffObject = [];\n //precond : source / target !== undefined\n var attributeKeys = Object.keys(source.conformsTo().getAllAttributes());\n //var targetKeys = Object.keys(source.conformsTo().getAllAttributes());\n\n //do the same for references\n var referenceKeys = Object.keys(source.conformsTo().getAllReferences());\n //var referenceTargetKeys = Object.keys(source.conformsTo().getAllReferences());\n\n _.each(attributeKeys,function(attName){\n //console.log(attName, \" : \",source[attName], \"vs\", target[attName]);\n if(!(_.isEqual(source[attName],target[attName]))){\n diffObject.push({name:attName,\n targetValue:target[attName],\n sourceValue:source[attName],\n type:\"attribute\"\n });\n }\n\n });\n //do not go to deep in the object comparisons\n if(depth > 0) {\n _.each(referenceKeys, function(refName) {\n const refSource = source[refName];\n const refTarget = target[refName];\n if(refSource.length!=0) {\n\n //TODO: check the targetted types\n //Compare elements one by one\n var Msource = new Model();\n var Mtarget = new Model();\n \n Msource.add(refSource);\n Mtarget.add(refTarget);\n \n var oID= orderIndependentDiff(Msource,Mtarget,depth-1);\n \n //See if relevant to have same card or not?\n if(!(refSource.length==refTarget.length)) {\n // console.log('Different effective cardinalities', refTarget.length);\n \n // console.log('oid',oID);\n var diffref = _.reject(oID,{type:'same'});\n diffObject.push({name:refName,src:source,tgt:target, diff:diffref, type:\"reference\"})\n //remplace the smaller one by place holder/undefined -> use the orderIndependentDiff\n //\n } else {\n //check the elements targetted \n //console.log('Same cardinality');\n //console.log(\"oid2 \",oID); \n var diffref = _.reject(oID,{type:'same'});\n if(diffref.length!=0){\n diffObject.push({name:refName,src:source,tgt:target, diff:diffref, type:\"reference\"}) \n }\n } \n } //endif : if source[refName] is defined\n });\n } //endif check reference (depth !== 0)\n }\n return diffObject;\n}",
"function test() {\n var b1, b2, prev = null, prevdiff = null;\n\n var res = [];\n\n for (b1 = 0; b1 < 256; b1++) {\n for (b2 = 0; b2 < 256; b2++) {\n var data = new Uint8Array([ 0xf9, b1, b2 ]).buffer;\n var val = CBOR.decode(data);\n var obj = { input: Duktape.enc('hex', data), value: val };\n if (prev !== null && Number.isNaN(prev) && Number.isNaN(val)) {\n obj.diff = 0;\n } else if (prev !== null && Number.isFinite(prev) && Number.isFinite(val)) {\n obj.diff = val - prev;\n }\n prev = val;\n res.push(obj);\n }\n }\n\n var diff_printed = false;\n for (i = 0; i < res.length; i++) {\n var prev = (i > 0 ? res[i - 1] : {});\n var curr = res[i];\n if (prev.diff === curr.diff && typeof curr.diff === 'number') {\n if (diff_printed) {\n } else {\n print(' diff: ' + prev.diff);\n diff_printed = true;\n }\n } else {\n print(curr.input, Duktape.enc('jx', curr.value));\n diff_printed = false;\n }\n }\n}",
"function diffingChange(){\r\n var changedPixels = 0;\r\n var imgData1 = ctxPrev.getImageData(0, 0, width, height);\r\n var imgData2 = ctxCurr.getImageData(0, 0, width, height);\r\n var imgDataDiff = ctxDiff.createImageData(imgData1);\r\n var i;\r\n for (i = 0; i<imgDataDiff.data.length; i+=4){\r\n imgDataDiff.data[i] = Math.abs(imgData1.data[i] - imgData2.data[i]);\r\n imgDataDiff.data[i+1] = Math.abs(imgData1.data[i+1] - imgData2.data[i+1]);\r\n imgDataDiff.data[i+2] = Math.abs(imgData1.data[i+2] - imgData2.data[i+2]);\r\n imgDataDiff.data[i+3] = 255;\r\n }\r\n ctxDiff.putImageData(imgDataDiff,0,0);\r\n\r\n for (i = 0; i<imgDataDiff.data.length; i+=4){\r\n let rgbSum = 0;\r\n rgbSum += imgDataDiff.data[i];\r\n rgbSum += imgDataDiff.data[i+1];\r\n rgbSum += imgDataDiff.data[i+2];\r\n if(rgbSum>=diffChangePixelMotionConstant){\r\n changedPixels++;\r\n }\r\n }\r\n updateChange3(changedPixels);\r\n }",
"function getReachableAncestorReferenceFrames(frame, time, result) {\n if (result === void 0) {\n result = [];\n }\n var frames = result;\n frames.length = 0;\n var f = frame;\n var isValid = false;\n do {\n var position = f.position;\n var orientation = f && f.orientation;\n f = position && position.referenceFrame;\n var hasParentFrame = defined(f);\n var pValue = hasParentFrame && position && position.getValueInReferenceFrame(time, f, scratchAncestorCartesian);\n var oValue = hasParentFrame && pValue && orientation && orientation.getValue(time, scratchAncestorQuaternion);\n isValid = pValue && oValue;\n if (isValid) frames.unshift(f);\n } while (isValid);\n return frames;\n }",
"getChanges(diff) {\n if (diff == null) {\n return this.hasChanged() ? ObjectExt.cloneDeep(this.changed) : null;\n }\n const old = this.changing ? this.previous : this.data;\n const changed = {};\n let hasChanged;\n // eslint-disable-next-line\n for (const key in diff) {\n const val = diff[key];\n if (!ObjectExt.isEqual(old[key], val)) {\n changed[key] = val;\n hasChanged = true;\n }\n }\n return hasChanged ? ObjectExt.cloneDeep(changed) : null;\n }",
"diff() {\n return diff(this.stored, this.settings);\n }",
"getChanges(diff) {\n if (diff == null) {\n return this.hasChanged() ? _util__WEBPACK_IMPORTED_MODULE_1__.ObjectExt.cloneDeep(this.changed) : null;\n }\n const old = this.changing ? this.previous : this.data;\n const changed = {};\n let hasChanged;\n // eslint-disable-next-line\n for (const key in diff) {\n const val = diff[key];\n if (!_util__WEBPACK_IMPORTED_MODULE_1__.ObjectExt.isEqual(old[key], val)) {\n changed[key] = val;\n hasChanged = true;\n }\n }\n return hasChanged ? _util__WEBPACK_IMPORTED_MODULE_1__.ObjectExt.cloneDeep(changed) : null;\n }",
"diff() {\n const changes = this.currentState.diff(this.previousState);\n \n if (this.classModel.auditable) {\n if (!changes.$set) {\n changes.$set = {};\n }\n changes.$set.revision = this.revision + 1;\n }\n\n return changes;\n }",
"function getDeltaFrame(window) {\n window = window || Window.focused();\n if (!window) {\n return;\n }\n\n const frame = window.frame();\n const screen = getScreenFrame(window);\n\n return {\n x: screen.x - frame.x,\n y: screen.y - frame.y,\n width: screen.width - frame.width,\n height: screen.height - frame.height,\n };\n}",
"function jsonDiff(){\n \n //Returns object class (date,array,regexp)\n var getClass = function(val) {\n return Object.prototype.toString.call(val).match(/^\\[object\\s(.*)\\]$/)[1]\n }\n\n //Get descriptive data type\n var getType = function(val){\n //Null is typeof object... but lets keep this simple\n if(val === undefined || val === null){\n return val\n }\n\n if(typeof val === 'object'){\n return getClass(val).toLowerCase()\n }\n return typeof val\n }\n\n //Check only if there any changes in values\n var isEqual = {\n object : function(path,oldObj,newObj){\n var changes = []\n var keys = Object.keys(oldObj)\n //Check all updated and remove actions\n for (var i = keys.length - 1; i >= 0; i--) {\n var k = keys[i]\n var newPath=path+\".\"+k\n var checkAttrDiff = diffObj(newPath,oldObj[k],newObj[k])\n if(checkAttrDiff !== false){\n changes.push(checkAttrDiff)\n }\n }\n //Check only new values on the right side\n var newKeys = _.difference(Object.keys(newObj),keys)\n for (var i = newKeys.length - 1; i >= 0; i--) {\n var k = newKeys[i]\n var newPath=path+\".\"+k\n changes.push(output(newPath,undefined,newObj[k]))\n }\n return (!changes.length)?false:changes\n },\n array : function(path,oldObj,newObj){\n var changes = []\n //In case any add/remove consider the all array as change\n if(oldObj.length !== newObj.length){\n return output(path,oldObj,newObj)\n }\n\n //Simple position checking, in order to detect unorder, or push or pop\n for (var i = oldObj.length - 1; i >= 0; i--) {\n var newPath=path+\"[\"+i+\"]\"\n var checkAttrDiff = diffObj(newPath,oldObj[i],newObj[i]);\n if(checkAttrDiff !== false){\n changes.push(checkAttrDiff)\n }\n }\n return (!changes.length)?false:changes\n },\n date : function(path,oldObj,newObj){\n if(oldObj.getTime() === newObj.getTime()){\n return false\n }\n return output(path,oldObj,newObj)\n },\n regexp : function(path,oldObj,newObj){\n if(oldObj.toString() === newObj.toString()){\n return false\n }\n return output(path,oldObj,newObj)\n }\n }\n\n //Output format\n var output = function(path,x,y){\n if(path[0] === '.'){\n path = path.substring(1)\n }\n return {\n \"field\":path,\n \"old\":x,\n \"new\":y\n }\n }\n //Function to be called recursive to navigate throw objects\n var diffObj = function(path,x,y){\n var xType = getType(x)\n var yType = getType(y)\n\n if (xType === yType){\n //Same type\n if (isEqual.hasOwnProperty(xType)){\n return isEqual[xType](path, x, y)\n } else if(x !== y){\n return output(path,x,y)\n }\n //In case it equals return false\n return false\n }\n //Other type\n return output(path,x,y)\n }\n\n return {\n typeof : function(val){\n //Only for test purposes\n return getType(val)\n },\n diff : function(oldObj,newObj,ignoreFields){\n /*Deep nested diff function over json object\n data types handled:\n Primitive:\n undefined, null, Boolean,Number,String ( comparing by value)\n Non-Primitive :\n object (deep comparasing),\n array(position comparsing,ignoring order),\n RegExp(converstion to string),\n Date (converstion to timestamp)\n Will ignore type function, since they dont represen data at all\n */\n if(getType(oldObj) !== 'object' && getType(newObj)!=='object'){\n throw new Error(\"please diff only valid json objects\")\n }\n //Strip object from fields to ignore (\"ex:_timestamp\")\n if(ignoreFields !== undefined){\n oldObj = _.omit(oldObj,ignoreFields)\n newObj = _.omit(newObj,ignoreFields)\n }\n return _.flatten(diffObj(\"\",oldObj,newObj))\n }\n }\n}",
"function calcDifferences(diff, imageA, imageB){ \n var imgA = imageA.getImageData(0, 0, canvas.width, canvas.height),\n imgB = imageB.getImageData(0, 0, canvas.width, canvas.height);\n \n pixelmatch(imgA.data, imgB.data, diff.data, canvas.width, canvas.height, {threshold: 0.1});\n return diff\n }",
"generateDiffFrames_() {\n var diffFrames = [];\n for (var i = 0; i < this.frames.length; i++) {\n diffFrames.push(this.getFrame_(this.frames[i]));\n\n if (diffFrames.length > 1) {\n // diff'd frames will be modified directly, so make two copies of each frame past the first. the first\n // copy is compared against the previous frame, and the second copy is compared against the next frame.\n diffFrames.push(this.getFrame_(this.frames[i]));\n }\n }\n\n // clear out the original frames\n this.frames.length = 0;\n\n // add the first frame as-is\n this.gifFrames_.push(diffFrames[0]);\n\n // for the rest of the frames, add the diff from the previous\n for (var i = 0; i < diffFrames.length - 1; i += 2) {\n this.gifFrames_.push(this.doDiff_(diffFrames[i], diffFrames[i + 1]));\n }\n }",
"lastDiff() {\n return this.convolveTail([1, 0, -1]);\n }",
"function compareFrame(img1) {\n // just compare if there are two pictures\n if ( img2 != null ) {\n var res=[0,0,0,0];\n var ObjR=10;\n\n try {\n \t\t// compare the two pictures, the given threshold helps to ignore noise\n \t\tres = compare(img1, img2, shipX, shipY, 10, ObjR); \n \t}\n catch(e) {\n \t\t// errors can happen if the pictures were corrupted during transfer\n \t\t// instead of giving up, just proceed\n \t}\n \n var md_ctx = md_canvas.getContext(\"2d\");\n if ((res[0]>400)||(res[1]>400)||(res[2]>400)||(res[3]>400)){\n res[0]=0;res[1]=0;res[2]=0;res[3]=0;\n \t}\n \n\thit=res[0]+res[1]+res[2]+res[3];\n \n\t}\n\t// copy reference of img1 to img2\n\timg2 = img1;\n}",
"function deepCompare() {\n // ...\n}",
"diff (imgA, imgB) {\n debug('diff...')\n // all 3 images must be the same size, so take the smallest size\n // (though they should be the same)\n const w = Math.min(imgA.width, imgB.width)\n const h = Math.min(imgA.height, imgB.height)\n // create the png for putting the diff image\n const diff = new PNG({width: w, height: h})\n // initialize the statistics\n const stats = {\n total: w * h,\n differences: 0\n }\n\n // compute difference image and get number of different pixels\n stats.differences = pixelmatch(imgA.data, imgB.data, diff.data, w, h, {threshold: 0})\n\n // different pixels as a percent of the total\n stats.percentage = (stats.differences / stats.total) * 100\n\n return {png: diff, stats}\n }",
"get differenceCount() {\n return Object.values(this.propertyUpdates).length\n + Object.values(this.otherChanges).length;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a program URL from the site, extract its program ID. If the input does not match the known URL patterns, it is assumed to be a program ID. | function isolateProgramID(programUrl) {
var match = KA_PROGRAM_URL.exec(programUrl);
if (match) {
programUrl = match[1];
}
return programUrl;
} | [
"function isolateProgramID(programUrl) {\n var match = KA_PROGRAM_URL.exec(programUrl);\n if (match) {\n programUrl = match[1];\n }\n\n return programUrl;\n}",
"function isolateProgramID(programUrl) {\n var match = KA_PROGRAM_URL.exec(programUrl);\n\n if (match) {\n programUrl = match[1];\n }\n\n return programUrl;\n}",
"function getFleetID(fleeturl){\r\n\t\tif(fleeturl.indexOf(\"?\") > 0){\r\n\t\t\turllength = fleeturl.length+1;\r\n\t\t\tfleetstart = fleeturl.indexOf(\"fleet=\")+6;\r\n\t\t\tsubs = fleetstart+1;\r\n\t\t\tfleetnum = 0;\r\n\t\t\twhile(Number(fleetnum) != null){\r\n\t\t\t\tfleetnum = fleeturl.substring(fleetstart,subs)\r\n\t\t\t\tsubs++;\r\n\t\t\t\tif(subs == urllength){\r\n\t\t\t\t\treturn fleetnum;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"getEvidenceId(url) {\n let matches = url.match(/\\/(\\w+?)$/);\n // logger.debug('Matches: ', matches[1]);\n return matches[1];\n }",
"function extractIdFromUrl( url ) {\n if ( !url ) {\n return;\n }\n \n var matches = urlRegex.exec( url ); \n\n // Return id, which comes after first equals sign\n return matches ? matches[1] : \"\";\n }",
"function extractIdFromUrl( url ) {\n if ( !url ) {\n return;\n }\n\n var matches = urlRegex.exec( url );\n\n // Return id, which comes after first equals sign\n return matches ? matches[1] : \"\";\n }",
"function getID(url) {\n // We can use API to fetch the ID by passing Slug as a argument\n var arrayURL = url.split(\"-\");\n var id = arrayURL[arrayURL.length - 1];\n return id;\n}",
"function extractJamendoId(url) {\r\n if (result = url.match(/\\d+/)) return result[0];\r\n return null;\r\n}",
"function stationIdFromURL() {\n var path = window.location.pathname;\n var elements = path.split('/')\n return parseInt(elements[elements.length -1]);\n}",
"function getUrlId() {\n\tlet url = getUrlString();\n\tlet id = url.slice(url.length - 1, url.length);\n\treturn id;\n}",
"function get_id(url) {\r\n var ui = url_parse(url);\r\n\r\n // if ((ui.host == \"www.ebay.co.uk\" || ui.host == \"ebay.co.uk\") && ui.path.startsWith(\"/itm/\")) {\r\n if (ui.subdomain == \"www\" && ui.dirs[0] == \"itm\") {\r\n return parseInt(ui.file);\r\n }\r\n //else if (ui.host == \"cgi.ebay.co.uk\" && ui.path.startsWith(\"/ws/\")) {\r\n else if (ui.subdomain == \"cgi\" && ui.dirs[0] == \"ws\") {\r\n return parseInt(ui.keys.item);\r\n }\r\n return null;\r\n }",
"function getPageIdFromUrl() {\n let pageId = 0;\n let url = window.location.href;\n\n if (url.indexOf(\"pageId\") != -1) {\n let urlSplit = url.split(\"?\");\n\n if (urlSplit[1].indexOf(\"&\") == -1) {\n let parameterSplit = urlSplit[1].split(\"=\");\n pageId = parameterSplit[1];\n } else {\n\n\n let urlParameters = urlSplit[1].split(\"&\");\n for (let i = 0; i < urlParameters.length; i++) {\n\n if (urlParameters[i].substring(0, 6) == \"pageId\") {\n let pageIdSplit = urlParameters[i].split(\"=\");\n pageId = pageIdSplit[1];\n break;\n }\n }\n }\n }\n return pageId;\n}",
"function _getGameIdFromURL(URL)\n{\n let strSplit = URL.split('/#match-details/')[1].split('/')\n\n if (strSplit.length < 2)\n {\n throw 'Error: Match history URL is not correct.'\n }\n\n return strSplit[1]\n}",
"function YouTubeGetID(url){\n var ID = '';\n url = url.replace(/(>|<)/gi,'').split(/(vi\\/|v=|\\/v\\/|youtu\\.be\\/|\\/embed\\/)/);\n if(url[2] !== undefined) {\n ID = url[2].split(/[^0-9a-z_\\-]/i);\n ID = ID[0];\n }\n else {\n ID = url;\n }\n return ID;\n }",
"idFromUrl() {\n let idFromUrl = null;\n let matches = browser.getUrl().match(uuidRegexp());\n if (matches) {\n idFromUrl = matches[0];\n }\n return idFromUrl;\n }",
"function YouTubeGetID(url){\n var ID = '';\n url = url.replace(/(>|<)/gi,'').split(/(vi\\/|v=|\\/v\\/|youtu\\.be\\/|\\/embed\\/)/);\n if(url[2] !== undefined) {\n ID = url[2].split(/[^0-9a-z_\\-]/i);\n ID = ID[0];\n }\n else {\n ID = url;\n }\n return ID;\n}",
"function YouTubeGetID(url){\n var ID = '';\n url = url.replace(/(>|<)/gi,'').split(/(vi\\/|v=|\\/v\\/|youtu\\.be\\/|\\/embed\\/)/);\n if(url[2] !== undefined) {\n ID = url[2].split(/[^0-9a-z_-]/i);\n ID = ID[0];\n }\n else {\n ID = url;\n }\n return ID;\n}",
"function getSiteID(){\r\n\r\n var tempLocation = location.href; \r\n \r\n var elem = tempLocation.split('/');\r\n \r\n if(elem != null){\r\n return elem[3];\r\n }else{\r\n return \"\"\r\n }\r\n\r\n}",
"function mapManifestUrlToId(manifest) {\n if (manifest) {\n var sourceManifest = \"\";\n var sourceManifestSplit = manifest.split(\"//\");\n\n if (sourceManifestSplit.length > 1) {\n for (var i = 1; i < sourceManifestSplit.length; i++) {\n if (i > 1) {\n sourceManifest += \"//\";\n }\n sourceManifest += sourceManifestSplit[i]\n }\n } else {\n sourceManifest = manifest;\n }\n\n if (sourceManifest.match(/.ism\\/manifest/i)) {\n sourceManifest = sourceManifest.split(/.ism\\/manifest/i)[0] + \".ism/manifest\";\n }\n }\n return sourceManifest || \"unknown\";\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
OnClickEventHandlers Method for Handling The Loan Application by User, If they don't have exsisting loan then they can get a loan up too double of current bank account balance. If they have a loan then it will reject by displaying a prompt saying that you can't have more then one loan. | function applyLoan() {
// Check Whether User Has Loan
if (hasActiveLoan === false) {
// How Much Loan Do User Want
const amountUserWant = prompt("What is your name?");
console.log(amountUserWant)
// Reject if Asked Amount is more then Double Current Bank Account Balance with Prompt
if (amountUserWant > currentBalance.innerText * 2) {
alert("Asked Amout Is More Than Current Balance Times 2")
} else {
// Grant Loan and Make Owned Amount and RePay button Visable to User
loanAmount.innerText = amountUserWant;
loanDownPayment.style.display = 'flex';
downPaymentButton.style.display = 'unset';
currentBalance.innerText = Number(currentBalance.innerText) + Number(amountUserWant);
hasActiveLoan = true;
}
} else {
alert("You can not have more than one active loans!")
}
} | [
"function takeLoan() {\n loanSum = 0\n //Loan must be paid back before getting another!\n //only one loan before buying computer\n if (outstandingLoan > 0) {\n alert(\"You already have an unpaid loan\")\n } else if (loanCount > laptopsBought) {\n alert(\"You can't take another loan until you've used it to buy something\")\n } else {\n //prompt popup box asking how much\n loanSum = prompt(\"State the size of the loan you want. Maximum amount allowed is \" + bankBalance / 2 + \"€\");\n //max loan = balance/2\n if (loanSum > (bankBalance / 2) || loanSum < 1) {\n alert(\"Invalid sum\")\n } else {\n loanCount++\n outstandingLoan = loanSum\n //unary helps...\n bankBalance = +bankBalance + +loanSum\n toggleVisibility(\"loan\")\n toggleVisibility(\"loanTitle\")\n toggleVisibility(\"outstandingLoan\")\n toggleVisibility(\"repay\")\n }\n }\n refreshValues()\n}",
"function loanRequest (e) {\n e.preventDefault();\n const loanAmount = Number(inputLoanAmount.value);\n if (loanAmount <= 0) return;\n const require = 10;\n\n const isEligible = currentUser.movements.some( (mov) => {\n return mov >= (require * loanAmount)/100;\n });\n\n if (isEligible) {\n depositeMoney(currentUser, loanAmount);\n // add new transaction in history \n newTransaction(loanAmount, 1);\n // re calculate summury ( in, out, interest )\n calcDisplaySummary(currentUser.movements);\n // re-calculate total balance\n calcBalances();\n // add timestamp of this new Transaction to current user\n currentUser.movementsDates.push(new Date().toISOString());\n console.log('loan approved');\n }\n else console.log('You are not eligible for this loan amount');\n\n inputLoanAmount.value = '';\n\n}",
"function getLoan() {\n\n if(hasLoan) { alert(\"You already have a loan, pay it off first\");}\n\n let amount = prompt(\"How much would you like to loan?\", 0);\n if(amount < (balance * 2)) {\n balance += Number.parseInt(amount);\n balanceHTML.innerText = balance.toString();\n hasLoan = true;\n loanAmount = amount;\n loanAmountHTML.innerHTML = loanAmount;\n btnRepayLoan.style.display = \"block\";\n return;\n } else {\n window.alert(\"Thats more than double of your current money, work harder!\");\n return;\n }\n}",
"function loanMoney() {\n amount = prompt(\"Amount to loan:\");\n if (\n amount != null &&\n amount != \"\" &&\n amount <= balanceElement.innerHTML * 2 &&\n loan != true &&\n loanRepaid === true\n ) {\n balanceElement.innerHTML = Number(balance) + Number(amount);\n balance = Number(balanceElement.innerHTML);\n loan = true;\n loanRepaid = false;\n loanAmount = amount;\n hidePayBackBtn();\n showOutstandingLoan();\n outstandingLoanUpdate();\n alert(\"Loan amount: \" + amount + \", Granted\");\n } else if (amount > balanceElement.innerText * 2) {\n alert(\"Max loan Amount: Balance * 2\");\n }else {\n alert(\"Loan must be repaid and PC must be bought before more money can be loaned\")\n }\n}",
"function repayLoanToBank() {\n \n //Do you even loan bro...\n if (bModel.getLoan() > 0) {\n \n if (model.getPay() > bModel.getLoan() ) {\n \n do {\n \n let toTransfer = model.getPay() - bModel.getLoan() ;\n bpresenter.getView().payOffLoan(clamp(bModel.getLoan() - toTransfer, 0, bModel.getLoan()) )\n presenter.getView().transferPay(toTransfer)\n \n \n } while (bModel.getLoan() > 0);\n return;\n }\n alert(\"A loane can only be paied in full\\n and you need to have an available amount in cash\")\n\n }\n\n }",
"function payLoan() {\n deductLoan(1);\n outstandingLoanUpdate();\n}",
"function repayLoan() {\n if (outstandingLoan > pay) {\n outstandingLoan = outstandingLoan - pay\n pay = 0\n } else {\n pay = pay - outstandingLoan\n outstandingLoan = 0\n }\n\n if (outstandingLoan == 0) {\n\n toggleVisibility(\"outstandingLoan\")\n toggleVisibility(\"loanTitle\")\n toggleVisibility(\"repay\")\n toggleVisibility(\"loan\")\n }\n refreshValues();\n}",
"function checkBtnHandler() {\n if (cashGiven > 0 && billAmt > 0) {\n if (Number.isInteger(cashGiven)) {\n if (cashGiven >= billAmt) {\n if (cashGiven == billAmt) {\n setOutputDisplay(\"none\");\n setErrorDisplay([\"block\", \"No amount should be returned\"]);\n return;\n }\n setErrorDisplay([\"none\", \"\"]);\n setOutputDisplay(\"block\");\n calculateNotes(cashGiven, billAmt);\n return;\n } else {\n setOutputDisplay(\"none\");\n setErrorDisplay([\n \"block\",\n \"Cash is less than bill, please enter right amount\"\n ]);\n return;\n }\n }\n } else {\n setOutputDisplay(\"none\");\n setErrorDisplay([\n \"block\",\n \"Enter valid bill amount and cash given to continue\"\n ]);\n }\n }",
"function Loan(pay, amount){\n if(!pay){ debt += amount; money += amount; }\n if (pay && money >= debt) { money -= debt; debt = 0; }\n updateInvent(null);\n}",
"function deductLoan(val) {\n if (loanAmount > (pay * val)) {\n loanAmount = loanAmount - (pay * val);\n if (val < 1) {\n pay= (pay * (1-val));\n } else {\n loanAmount = loanAmount - pay;\n }\n } else {\n pay = pay - loanAmount;\n currentPay.innerText = pay;\n loanRepaid = true;\n loanAmount = 0;\n hidePayBackBtn();\n }\n}",
"function makeDownPayment() {\n \n // Check Whether User Has Loan\n if (hasActiveLoan) {\n let toTransfere = Number(workAccountBalance.innerText);\n\n // Transfere the Fund Towards the Down-payment of Loan and reset Work Account \n loanAmount.innerText = Number(loanAmount.innerText) - toTransfere;\n workAccountBalance.innerText = 0;\n\n // Make Sure We Don't Pay Too Much on the Loan\n paidToMuch(currentBalance);\n } else {\n alert(\"No Active Loans Please use the Bank Button\")\n }\n}",
"function formToLoan() {\n const form = $(\"#payingLoanInputModal\");\n\n const name = form\n .find(\"#name\")\n .val()\n .replace(\" \", \"_\");\n const balance = Math.abs(parseFloat(form.find(\"#balance\").val()));\n const rate = Math.abs(parseFloat(form.find(\"#rate\").val()));\n const dailyRate = rate / 36525;\n const minPmt = Math.abs(parseFloat(form.find(\"#minPmt\").val()));\n const previousPayDate = new Date(\n sanitizeDate(form.find(\"#previousPayDate\").val())\n );\n const dueOn = previousPayDate.getDate();\n const beginRepaymentDate = new Date(\n previousPayDate.getFullYear(),\n previousPayDate.getMonth() + 1,\n previousPayDate.getDate()\n );\n const principal = determinePrincipal(balance, dailyRate, previousPayDate);\n const interest = interestTillNextPayment(\n principal,\n dailyRate,\n previousPayDate,\n beginRepaymentDate\n );\n\n const loanElement = `\n <div id=\"loan-${name}\" class=\"loanDisplay\">\n <div class=\"row\">\n <div class=\"col-sm-4\">\n <span class=\"show bold\">${name}</span>\n <span class=\"show\">$${balance} at ${rate}%</span>\n </div>\n <div class=\"col-sm-4 float-left\">\n <button class=\"btn btn-primary disabled\" title=\"View Payments\"><i class=\"fas fa-calendar\"></i></button>\n <button class=\"btn btn-primary\" title=\"Edit Loan\" onclick=\"editLoan('loan-${name}')\"><i class=\"fas fa-edit\"></i></button>\n <button class=\"btn btn-primary\" title=\"Delete Loan\" onclick=\"deleteLoan('loan-${name}')\"><i class=\"fas fa-trash\"></i></button>\n </div>\n <ul class=\"loan\">\n <li class=\"name hidden\">${name}</li>\n <li class=\"principal hidden\">${principal}</li>\n <li class=\"interest hidden\">${interest}</li>\n <li class=\"minPmt hidden\">${minPmt}</li>\n <li class=\"rate hidden\">${rate}</li>\n <li class=\"lastPaid hidden\">${previousPayDate}</li>\n <li class=\"dueOn hidden\">${dueOn}</li>\n <li class=\"beginRepaymentDate hidden\">${beginRepaymentDate}</li>\n <li class=\"loanType hidden\">current</li>\n </ul>\n </div>\n `;\n\n existingLoan = document.getElementById(`loan-${name}`);\n\n if (!existingLoan) {\n $(\"#loansList\").append(loanElement);\n } else {\n existingLoan.parentNode.removeChild(existingLoan);\n $(\"#loansList\").append(loanElement);\n }\n}",
"function fastForwardLoan() {\n const form = $(\"#borrowingLoanInputModal\");\n\n const name = form.find(\"#name\").val();\n const borrowAmt = Math.abs(parseFloat(form.find(\"#amount\").val()));\n const borrowRate = Math.abs(parseFloat(form.find(\"#rate\").val()));\n const borrowDecimalRate = borrowRate / 100;\n const borrowDailyRate = borrowDecimalRate / 365.25;\n const firstDisbDate = new Date(\n sanitizeDate(form.find(\"#firstDisbDate\").val())\n );\n const secondDisbDate = new Date(\n sanitizeDate(form.find(\"#secondDisbDate\").val())\n );\n const subsidized = form.find(\"#subsidized\").prop(\"checked\");\n const gradDate = new Date(sanitizeDate(form.find(\"#gradDate\").val()));\n const autopay = form.find(\"#autopay\").prop(\"checked\");\n const beginRepaymentDate = determineBeginRepaymentDate(gradDate);\n const dueOn = beginRepaymentDate.getDate();\n\n const paymentRate = autopay ? borrowRate - 0.25 : borrowRate;\n const balanceAtRepayment = calculateBalanceAtBeginRepayment(\n subsidized,\n beginRepaymentDate,\n firstDisbDate,\n secondDisbDate,\n borrowAmt,\n borrowDailyRate\n );\n\n // const minPmt = calculateMinPmt();\n\n const loanElement = `\n <div id=\"loan-${name}\" class=\"loanDisplay\">\n <div class=\"row\">\n <div class=\"col-sm-4\">\n <span class=\"show bold\">${name}</span>\n <span class=\"show\">$${balanceAtRepayment.toFixed(\n 2\n )} at ${paymentRate}%</span>\n </div>\n <div class=\"col-sm-4 float-left\">\n <button class=\"btn btn-primary disabled\" title=\"View Payments\"><i class=\"fas fa-calendar\"></i></button>\n <button class=\"btn btn-primary\" title=\"Edit Loan\" onclick=\"editLoan('loan-${name}')\"><i class=\"fas fa-edit\"></i></button>\n <button class=\"btn btn-primary\" title=\"Delete Loan\" onclick=\"deleteLoan('loan-${name}')\"><i class=\"fas fa-trash\"></i></button>\n </div>\n <ul class=\"loan\">\n <li class=\"name hidden\">${name}</li>\n <li class=\"principal hidden\">${balanceAtRepayment}</li>\n <li class=\"interest hidden\">0</li>\n <li class=\"minPmt hidden\">0</li>\n <li class=\"rate hidden\">${paymentRate}</li>\n <li class=\"dueOn hidden\">${dueOn}</li>\n <li class=\"beginRepaymentDate hidden\">${beginRepaymentDate}</li>\n <li class=\"loanType hidden\">future</li>\n </ul>\n </div>\n </div>\n `;\n\n existingLoan = document.getElementById(`loan-${name}`);\n\n if (!existingLoan) {\n $(\"#loansList\").append(loanElement);\n } else {\n existingLoan.parentNode.removeChild(existingLoan);\n $(\"#loansList\").append(loanElement);\n }\n}",
"function canGetLoan(requestedLoan) {\n if (requestedLoan <= 0) {\n alert(\"Cannot get loan: requested loan has to be above 0!\");\n return false;\n }\n if (laptopBuy.getOwnedComputers().length === 0) {\n alert(\"Cannot get loan: you must buy at least one laptop!\");\n return false;\n }\n if (currentLoan > 0) {\n alert(\"Cannot get loan: current loan must be paid back!\");\n return false;\n }\n if (requestedLoan > balance * 2) {\n alert(\"Cannot get loan: requested cannot be above double your balance!\");\n return false;\n }\n return true;\n }",
"function transferToBank() {\n\n if(hasLoan) {\n loanAmount -= (pay / 10);\n if(loanAmount <= 0) { \n loanAmount = 0;\n hasLoan = false;\n btnRepayLoan.style.display = \"none\";\n }\n\n loanAmountHTML.innerText = loanAmount.toString();\n\n balance += (pay * 0.9);\n balanceHTML.innerText = balance.toString();\n\n pay = 0;\n payHTML.innerText = pay.toString();\n } else {\n balance += pay;\n pay = 0;\n payHTML.innerText = pay.toString();\n balanceHTML.innerText = balance.toString();\n }\n}",
"function paidToMuch(bounceBackAccount) {\n if (Number(loanAmount.innerText) <= 0) {\n bounceBackAccount.innerText = Number(bounceBackAccount.innerText) + (Number(loanAmount.innerText) * -1);\n loanAmount.innerText = 0;\n hasActiveLoan = false;\n loanDownPayment.style.display = 'none';\n downPaymentButton.style.display = 'none';\n }\n}",
"function repayLoan(amount, user, loanContractAddress) {\n const amt = web3.toWei(amount);\n web3.eth.sendTransaction({\n to: loanContractAddress,\n from: user,\n value: amt\n }, function(err, res) {\n console.log(res);\n if (!err) {\n // var xhr = new XMLHttpRequest();\n // xhr.open(\"POST\", absolute_url + '/borrower/loanRepayEvent', true);\n // xhr.setRequestHeader('Content-Type', 'application/json');\n // xhr.send(JSON.stringify({\n // from: user,\n // to: loanContractAddress,\n // txnId: res,\n // loanId: loanId\n // }));\n } else {\n Snackbar.show({\n pos: 'top-center',\n text: \"Transaction Was Cancelled\"\n });\n }\n });\n}",
"function salaryPayout() {\n \n // Check Whether User Has Loan\n if (hasActiveLoan) { \n let toTransfere = Number(workAccountBalance.innerText);\n const toDownPayment = toTransfere * 0.1;\n\n // Transfere to Fund to Bank Account With 10% Towards the Loan\n loanAmount.innerText = Number(loanAmount.innerText) - toDownPayment;\n workAccountBalance.innerText = 0;\n currentBalance.innerText = Number(currentBalance.innerText) + (toTransfere - toDownPayment);\n\n // Make Sure We Don't Pay Too Much on the Loan\n paidToMuch(currentBalance);\n } else {\n\n // If Employee is Debt Free then Transfere the Funds and Reset the Work Account to 0.\n currentBalance.innerText = Number(currentBalance.innerText) + Number(workAccountBalance.innerText);\n workAccountBalance.innerText = 0;\n }\n}",
"_approveLoan(value) {\n return true;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The first element 10 is the product of all array's elements except the first element 1 The second element 2 is the product of all array's elements except the second element 5 The Third element 5 is the product of all array's elements except the Third element 2. | function productArray(numbers){
let result = []
numbers.forEach((number, index) => {
let res = 1;
numbers.forEach((subNumber, subIndex) => {
if(index !== subIndex) {
res *= subNumber
}
})
result.push(res)
})
return result
} | [
"function productOfArrElements(array){\n return array.reduce(function(preVal, el, i, arr){\n return preVal * el;\n });\n}",
"function productReduce(array) {\n return array.reduce((total, n) => { return total *= n});\n}",
"function productOfAllElements(arr) {\n return arr.reduce(function (total, elem, i, arr) {\n return total * elem;\n }, 1);\n}",
"function productOfArray(arr) {\n \n}",
"function product(arr) {\n let sumTotal = 1;\n for (i = 0; i < arr.length; ++i) {\n sumTotal *= arr[i]; \n }\n return sumTotal;\n}",
"function arrayProduct(array) {\n return array.reduce((product, factor) => {\n return product *= factor;\n },1);\n}",
"function findProduct(arr) {\n const sumWithoutNumAtIndex = currArr => currArr.reduce((acc, n) => acc * n)\n const removeNumAtIndex = n => arr.filter(x => x !== n)\n\n return arr.map(int => pipeWith(int, removeNumAtIndex, sumWithoutNumAtIndex))\n}",
"function multiplyAll(arr) {\r\n var product = 1;\r\n for (var i = 0; i < arr.length; i++) {\r\n for (var j = 0; j < arr[i].length; j++) {\r\n product = product * arr[i][j];\r\n }\r\n }\r\n return product;\r\n }",
"function product(numbers){\n //calculate product of array\n\tfor(var i = 0; i < numbers.length; i++){\n //return product;\n\t numbers[i] * numbers[i];\n\t}\n}",
"function printArrayProduct(arrayOfNumbers) {\n console.log(Array\n .from(arrayOfNumbers)\n .reduce((previous, current) =>\n previous *= current)\n )\n}",
"function multiplyAll(arr) {\n var product = 1;\n for (var i =0; i< arr.length; i++) {\n for(var j = 0; j < arr[i].length; j++) {\n product *= arr[i][j];\n }\n }\n return product;\n}",
"function multiplyBy10(array) {\n\n}",
"function multiplyAll(arr){\n var product = 1;\n\n for(var i = 0; i < arr.length; i++){\n for(var j = 0; i < arr[i].length; j++){\n product *=arr[i][j];\n }\n }\n}",
"function productOfAll(arr) {\n var final = 1;\n for(var i=0;i<arr.length;i++) {\n final *= arr[i];\n }\n return final;\n}",
"function arrayProd(pArray)\n{\n return pArray.reduce(function(tot,item){return tot*=item},1,this)\n}",
"function products(arr) {\n let totalProduct = 1;\n\n for (let i = 0; i < arr.length; i++) {\n totalProduct *= arr[i];\n }\n\n for (let i = 0; i < arr.length; i++) {\n arr[i] = totalProduct / arr[i];\n }\n return arr;\n}",
"function productBy(array) {\n var total = 1;\n each(array, function(num) {\n total *= num;\n });\n return total;\n}",
"function computeProductOfAllElements(arr) {\n var output = 0;\n if (arr.length > 0){\n output = 1;\n for (var i = 0; i < arr.length; i++){\n output *= arr[i];\n }\n }\n return output;\n}",
"function arrayOfProducts(array) {\n let left_products = Array(array.length).fill(1); \n let right_products = Array(array.length).fill(1); \n let result_products = Array(array.length).fill(1); \n \n let left_running_prod = 1; \n for(let i = 0; i < array.length; i++) {\n left_products[i] = left_running_prod; \n left_running_prod *= array[i]; \n }\n\n let right_running_prod = 1; \n for (let i = array.length - 1; i >= 0; i--) {\n right_products[i] = right_running_prod; \n right_running_prod *= array[i]; \n }\n\n for(let i = 0; i < array.length; i++) {\n result_products[i] = left_products[i] * right_products[i]; \n }\n\n return result_products; \n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
clear the new task row | function clearNewTaskRow(obj)
{
const kids = obj.children();
const taskNameBox = $(kids[2]);
const taskNameInput = $(taskNameBox.children()[1]);
clearVal(taskNameInput);
const spoon = kids.filter(".spoon");
for (let i = 0; i < spoon.length; i++) {
let spoonBox = $(spoon[i]);
let spoonForm = $(spoonBox.children()[1]);
setVal(spoonForm,"blank");
}
} | [
"function clearTaskTable() {\n for (let ii = taskTable.rows.length - 1; ii >= 2; ii--) {\n taskTable.deleteRow(ii);\n }\n rowIndex = 2;\n}",
"function clearTaskTable () {\n\t$('#taskDisplay').find('#taskTable').find('tr:not(.head)').remove();\n}",
"static clearField() {\n taskId.value = '';\n newTask.value = '';\n }",
"function clearTaskTable() {\n $('#taskDisplay').find('#taskTable').find('tr:not(.head)').remove();\n}",
"function clearTaskTable () {\n\t$('#taskTable > tbody').children('tr:not(.head)').remove();\n}",
"function clear() {\n var data = getData();\n\n if (data.uncompleted) {\n data.uncompleted = [];\n setData(data);\n displayError(\"All pending tasks cleared\");\n } else {\n displayError(\"No tasks present!!\");\n }\n\n}",
"function removeTaskRow(input) {\n document.getElementById('taskContent').removeChild( input.parentNode );\n}",
"static resetAddTaskValues () {\n $('#inputNewTask').val('');\n $('#inputTaskDate').val('');\n $('#inputTaskTime').val('');\n $('#inputDateLabel').val('0');\n $('#inputColor').val('0');\n $('select').material_select();\n }",
"function clearAndAddSingleRowTask(msg) {\n $('#taskTable > tbody').children('tr:not(.head)').remove();\n\n let placeHolder = document.createElement('tr');\n let listDetails0 = document.createElement('td');\n let listDetails1 = document.createElement('td');\n let listDetails2 = document.createElement('td');\n let listDetails3 = document.createElement('td');\n let listDetails4 = document.createElement('td');\n let listDetails5 = document.createElement('td');\n let listDetails6 = document.createElement('td');\n let listDetails7 = document.createElement('td');\n\n listDetails0.innerHTML = msg;\n\n $(placeHolder).append(listDetails0);\n $(placeHolder).append(listDetails1);\n $(placeHolder).append(listDetails2);\n $(placeHolder).append(listDetails3);\n $(placeHolder).append(listDetails4);\n $(placeHolder).append(listDetails5);\n $(placeHolder).append(listDetails6);\n $(placeHolder).append(listDetails7);\n\n $('#taskTable > tbody').append(placeHolder);\n}",
"clearCurrentTask() {\r\n\t\tthis.currentTaskName = null;\r\n\t\tthis.currentTaskMax = -1;\r\n\t\tthis.currentTaskValue = -1;\r\n\t\tthis.updateCurrentTask();\r\n\t}",
"function _resetRow(task) {\n let newRow = createElement(\"tr\");\n let row = _findRow(task);\n row.parentNode.replaceChild(newRow, row);\n return newRow;\n }",
"clear() {\n this._tasks = [];\n }",
"function clearAndAddSingleRowTask(msg) {\n\t$('#taskTable > tbody').children('tr:not(.head)').remove();\n\t\n\tlet placeHolder = document.createElement('tr');\n\tlet listDetails0 = document.createElement('td');\n\tlet listDetails1 = document.createElement('td');\n\tlet listDetails2 = document.createElement('td');\t\n\tlet listDetails3 = document.createElement('td');\n\tlet listDetails4 = document.createElement('td');\n\tlet listDetails5 = document.createElement('td');\n\n\t\n\tlistDetails0.innerHTML = msg;\n\t\n\t$(placeHolder).append(listDetails0);\n\t$(placeHolder).append(listDetails1);\n\t$(placeHolder).append(listDetails2);\n\t$(placeHolder).append(listDetails3);\n\t$(placeHolder).append(listDetails4);\n\t$(placeHolder).append(listDetails5);\n\t\n\t$('#taskTable > tbody').append(placeHolder);\n}",
"function emptyTrash() {\n /* Clear tasks from 'Trash' column */\n document.getElementById(\"trash\").innerHTML = \"\";\n}",
"_undoDeleteTaskById(id) {\n var task = this._getDataById(id);\n task.deleted = false;\n this._renderItems();\n }",
"function clearTaskEntry(e) {\n e.preventDefault();\n [\"taskName\", \"taskText\"].forEach(i => {\n let x = document.getElementById(i);\n x.value = '';\n x.style.color = \"snow\";\n });\n document.getElementById(\"dueDate\").value = '';\n document.getElementById(\"btnColorPick\").style.background = '';\n}",
"function resetTask() {\n $scope.task.name = \"\";\n }",
"function deleteTask() {\n this.parentNode.parentNode.removeChild(this.parentNode);\n }",
"function clearDone() {\n var data = getData();\n\n if (data.completed) {\n data.completed = [];\n setData(data);\n displayError(\"All completed tasks cleared\");\n } else {\n displayError(\"No tasks present!!\");\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the name of LDAP attribute which holds user password | function getPasswordAttributeName(){
return 'userPassword';
} | [
"get passwordData() {\n return this.getStringAttribute('password_data');\n }",
"get password() {\n return this.hasAttribute('password');\n }",
"function CFDataSourceMenu_getPassword()\r\n{\r\n var retVal = \"\";\r\n \r\n var connRec = MMDB.getConnection(this.getValue());\r\n if (connRec)\r\n {\r\n retVal = connRec.password;\r\n }\r\n \r\n return retVal;\r\n}",
"function getPassword() {\n var data = getRecord()\n blob = bin2String(Utilities.base64Decode(data[COL_PASSWORD]));\n return blob;\n}",
"getPassword() {\n return super.getAsNullableString(\"password\") || super.getAsNullableString(\"pass\");\n }",
"function YNetwork_get_userPassword()\n { var json_val = this._getAttr('userPassword');\n return (json_val == null ? Y_USERPASSWORD_INVALID : json_val);\n }",
"function getAttributeName(phyAttribName, logAttribName){\n\tlet attribName = '';\n if (logAttribName !== ''){\n \tattribName = logAttribName;\n }else{\n \tattribName = phyAttribName;\n }\n return attribName;\n}",
"function getPassword() {\n var password = context.get(Scope.REQUEST, \"urn:ibm:security:asf:request:parameter\", \"password\");\n return jsString(password);\n}",
"getPassword() {\n\t\treturn this.password\n\t}",
"get password() { return this._password;}",
"getPasswordTemplateField() {\n const templateField = klona(self.apos.user.schema.find(field => field.name === 'password'));\n delete templateField.moduleName;\n delete templateField.group;\n delete templateField.name;\n delete templateField.label;\n return templateField;\n }",
"getPassword() {\n return this.password;\n }",
"get password() {\n return this._password;\n }",
"set password(val) {\n this._setAttributes(val,'password')\n }",
"function YNetwork_get_adminPassword()\n { var json_val = this._getAttr('adminPassword');\n return (json_val == null ? Y_ADMINPASSWORD_INVALID : json_val);\n }",
"get password() {\n return this._password;\n }",
"addPassword (password) {\n return new ldap.Change({\n operation: 'add',\n modification: {\n unicodePwd: encodePassword(password)\n }\n })\n }",
"replacePassword (password) {\n return new ldap.Change({\n operation: 'replace',\n modification: {\n unicodePwd: encodePassword(password)\n }\n })\n }",
"function printDuoAttr()\n {\n var k = Object.keys(window.duo.user.attributes);\n for (var key of k)\n {\n console.log(key);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
============================================================= Parse text blob for receipt properties ============================================================= | function parseReceipt(text, callback) {
var receipt = {};
receipt.title = find.title(text);
receipt.total = find.total(text);
receipt.date = find.date(text);
receipt.fullText = text;
return callback(null, receipt);
} | [
"function getLineProperties(wtext, lineNum) {\n var line = wtext.getLine(lineNum);\n for (var key in lineTypes) {\n var type = lineTypes[key];\n var prefix = type.prefix;\n if (wtext.lineHasPrefix(lineNum, prefix)) {\n var fullPrefix = line.text.match(prefixRegex)[0];\n return { prefix:fullPrefix, text:line.text.substring(prefix, line.text.length) };\n }\n }\n return { prefix:'', text:line.text };\n }",
"getNMT() {\r\n let unparseNMT = this.#rawtext[0].split(\"\\n\");\r\n this.productsLength = parseFloat(unparseNMT[0].split('\\t')[1]);\r\n this.maintenanceTime = parseFloat(unparseNMT[1].split('\\t')[1]);\r\n this.timeForMaintenance = parseFloat(unparseNMT[2].split('\\t')[1]);\r\n }",
"function parseVCF(text) {\n var lines = U.reject(text.split('\\n'), function(line) {\n return line === '';\n });\n\n var partitions = U.partition(lines, function(line) {\n return line[0] === '#';\n });\n\n var header = parseHeader(partitions[0]),\n records = U.map(partitions[1], function(line) {\n return new Record(line, header);\n });\n\n return {header: header, records: records};\n }",
"parseXMLContents(source) {\r\n let data = {lines: [], extra: {}};\r\n let lines = source.split(/\\n/);\r\n for (let li = 0; li < lines.length; li++) {\r\n let line = lines[li];\r\n let regExp = /([^=\\s]*[^\\s])=(.*)/g;\r\n let match = regExp.exec(line);\r\n // It is a key=value pair\r\n if (match) {\r\n // TODO: process whitespace during regex\r\n data.extra[match[1].trim()] = match[2];\r\n // It is text\r\n } else {\r\n data.lines.push(line);\r\n }\r\n }\r\n return data;\r\n }",
"function receipt(imagePath, callback) {\n var config = { preserveLineBreaks: true };\n\n textract(imagePath, config, function(err, text) {\n if (err) { callback(err, null); }\n\n parseReceipt(text, function (err, receipt) {\n if (err) { callback(err, null); }\n\n callback(null, receipt);\n });\n });\n}",
"parseContents(source) {\r\n let data = {lines: [], extra: {}};\r\n let lines = source.split(/\\n/);\r\n for (let li = 0; li < lines.length; li++) {\r\n let line = lines[li];\r\n let regExp = /([^=]*)=(.*)/g;\r\n let match = regExp.exec(line);\r\n // It is a key=value pair\r\n if (match) {\r\n // TODO: process whitespace during regex\r\n data.extra[match[1].trim()] = match[2];\r\n // It is text\r\n } else {\r\n data.lines.push(line);\r\n }\r\n }\r\n return data;\r\n }",
"parsePoemFromString(str) {\n let lines = str.split(\"\\n\");\n // meta\n this.title = lines?.[0].match(/(?:\"[^\"]*\"|^[^\"]*$)/)[0].replace(/\"/g, \"\");\n this.author = lines?.[1]?.slice(4);\n // stanza 1\n this.l1 = lines?.[0 + 3];\n this.l3 = lines?.[2 + 3];\n this.l5 = lines?.[4 + 3];\n this.l6 = lines?.[5 + 3];\n // stanza 2\n this.l7 = lines?.[7 + 3];\n this.l9 = lines?.[9 + 3];\n this.l11 = lines?.[11 + 3];\n this.l12 = lines?.[12 + 3];\n // stanza 3\n this.l13 = lines?.[14 + 3];\n this.l15 = lines?.[16 + 3];\n this.l17 = lines?.[18 + 3];\n this.l18 = lines?.[19 + 3];\n // stanza 4\n this.l19 = lines?.[21 + 3];\n this.l20 = lines?.[22 + 3];\n this.l21 = lines?.[23 + 3];\n this.l22 = lines?.[24 + 3];\n this.l23 = lines?.[25 + 3];\n this.l24 = lines?.[26 + 3];\n }",
"static parse(txt) {\n const items = txt.match(/^[a-z]+\\s+.+$/gm), rawData = {\n info: [],\n common: [],\n page: [],\n char: [],\n chars: [],\n kerning: [],\n kernings: [],\n distanceField: []\n };\n for (const i2 in items) {\n const name = items[i2].match(/^[a-z]+/gm)[0], attributeList = items[i2].match(/[a-zA-Z]+=([^\\s\"']+|\"([^\"]*)\")/gm), itemData = {};\n for (const i22 in attributeList) {\n const split = attributeList[i22].split(\"=\"), key = split[0], strValue = split[1].replace(/\"/gm, \"\"), floatValue = parseFloat(strValue), value = isNaN(floatValue) ? strValue : floatValue;\n itemData[key] = value;\n }\n rawData[name].push(itemData);\n }\n const font = new BitmapFontData();\n return rawData.info.forEach((info) => font.info.push({\n face: info.face,\n size: parseInt(info.size, 10)\n })), rawData.common.forEach((common) => font.common.push({\n lineHeight: parseInt(common.lineHeight, 10)\n })), rawData.page.forEach((page) => font.page.push({\n id: parseInt(page.id, 10),\n file: page.file\n })), rawData.char.forEach((char) => font.char.push({\n id: parseInt(char.id, 10),\n page: parseInt(char.page, 10),\n x: parseInt(char.x, 10),\n y: parseInt(char.y, 10),\n width: parseInt(char.width, 10),\n height: parseInt(char.height, 10),\n xoffset: parseInt(char.xoffset, 10),\n yoffset: parseInt(char.yoffset, 10),\n xadvance: parseInt(char.xadvance, 10)\n })), rawData.kerning.forEach((kerning) => font.kerning.push({\n first: parseInt(kerning.first, 10),\n second: parseInt(kerning.second, 10),\n amount: parseInt(kerning.amount, 10)\n })), rawData.distanceField.forEach((df) => font.distanceField.push({\n distanceRange: parseInt(df.distanceRange, 10),\n fieldType: df.fieldType\n })), font;\n }",
"function readProp() {\n\n\t// Work on a per-line basis so that we never surpass a line and read stuff \n\t// from another property by accident.\n\tlet index = val.indexOf('\\n');\n\tlet line = val.slice(0, index);\n\tadvance(index);\n\n\tlet temp = val;\n\tval = line;\n\n\tlet id = readHex();\n\tuntil(':');\n\n\t// Read a potential comment.\n\tws();\n\tlet comment = readComment();\n\n\t// Read the values.\n\tuntil('=');\n\n\t// Read the type.\n\tindex = val.indexOf(':');\n\tlet type = val.slice(0, index);\n\tadvance(index+1);\n\n\t// Read the resp.\n\tindex = val.indexOf(':');\n\tlet reps = Number(val.slice(0, index));\n\tadvance(index+1);\n\n\tlet value = readValue(type, reps);\n\n\t// Restore.\n\tval = temp;\n\n\t// Consume trailing whitespace.\n\tws();\n\n\treturn {\n\t\t\"id\": id,\n\t\t\"comment\": comment,\n\t\t\"type\": type,\n\t\t\"value\": value\n\t};\n\n}",
"function parseDataAttributes(note) {\n var o = {};\n var parts;\n if (note) {\n parts = note.split(/[\\r\\n;,]+/);\n for (var i = 0; i < parts.length; i++) {\n parseKeyValueString(parts[i], o);\n }\n }\n return o;\n}",
"_processText(text) {\n // Get an appropriate name/description for an arbitrary blob of text\n let desc, name;\n if (/[\\r\\n]/.test(text)) {\n // If the text contains a newline, then use the first line as the name\n const [, firstLine] = Array.from(\n new RegExp(`\\\n^\\\n\\\\s*\\\n([^\\\\r\\\\n]+)\\\n`).exec(text),\n );\n\n name = truncate(firstLine, 256);\n desc = text;\n } else {\n name = truncate(text, 256);\n // If the name got clipped or contains a URL (which wouldn't be clickable)\n // then also put the text into the description\n if (name !== text || containsUrl(text)) {\n desc = text;\n } else {\n desc = '';\n }\n }\n\n return { name, desc };\n }",
"function extractText() {\n if (!checkPassword(decPwd.value)) return;\n var bytes = mp3.extractText();\n if (decPwd.value) {\n bytes = decryptText(bytes);\n }\n message2.value = decodeUTF8(bytes);\n}",
"extractFieldData( string )\n {\n let tx = string;\n\t if( tx && string.substr( 0, 13 ) == '<!--BASE64-->' )\n\t {\n\t \ttx = tx.substr( 13, tx.length - 13 );\n\t \ttx = Base64.decode( tx );\n\t }\n\t return tx;\n }",
"function extractOrder(text) {\n var idxS = text.search('TVE:');\n var idxE = text.search(':EVT');\n if(idxS > -1 && idxE > -1 && idxS + 4 < text.length) {\n try {\n var order = JSON.parse(text.slice(idxS + 4, idxE));\n console.debug(order);\n return order;\n } catch(e) {\n console.error(\"Error parsing order text: \" + e);\n }\n } else {\n console.error(\"Could not find TVE:/:EVT bounds in text: \" + text);\n }\n return null;\n}",
"function extract_metadata(contents) {\n var metadata = undefined;\n \n if (contents && contents.substring(0,metadata_tag.length) == metadata_tag) {\n var end = contents.indexOf('\\n');\n if (end != -1) {\n metadata = JSON.parse(contents.substring(metadata_tag.length,end));\n contents = contents.substring(end+1,contents.length);\n }\n }\n\n return {contents: contents, metadata: metadata };\n }",
"function parseBlockProperties(text, caseSensitive = false) {\n if (!text.trim()) return null;\n let properties = {}\n try {\n eval(`properties = {${text}}`);\n } catch(err) {\n console.log(`Trouble parsing properties: \"${text}\"`);\n if (err instanceof ReferenceError) {\n console.log('Did you remember to put quotation marks around ' +\n 'your string and commas between properties?');\n } else if (err instanceof SyntaxError) {\n console.log('Did you remember to add quotation marks?');\n }\n return null;\n }\n if (caseSensitive) return properties;\n // all property keys must be converted to lowercase\n let lower = {};\n for (let property in properties) {\n lower[property.toLowerCase()] = properties[property];\n }\n return lower;\n}",
"parseTextChunks() {\n\t\tlet textChunks = this.metaChunks.filter(info => info.type === TEXT)\n\t\tfor (let seg of textChunks) {\n\t\t\tlet [key, val] = this.file.getString(seg.start, seg.size).split('\\0')\n\t\t\tthis.injectKeyValToIhdr(key, val)\n\t\t}\n\t}",
"function splitLineofType1(ver_info_obj,arrayString){\n\t\t\t//// splits string (should be a single line from the LAS text) by \":\", takes the first item of the resulting array, and then replaces any \" \" with \"\".\n\t\t\tvar vers_line_1half = arrayString.split(\":\")[0].replace(\" \",\"\");\n\t\t\t//// splits the previous string variable by \".\" into an array of strings.\n\t\t\tvar vers_line_1half_array = vers_line_1half.split(\".\")\n\t\t\t//// trimming this so I get \"UWI\" instead of \"UWI \"\n\t\t\tver_info_obj[\"MNEM\"] = vers_line_1half_array[0].trim()\n\t\t\tvar unit_and_data = vers_line_1half_array.slice(1,vers_line_1half_array.length);\n\t\t\tvar unit_and_data_str = \" \";\n\t\t\tif (unit_and_data.length > 1){\n\t\t\t\tunit_and_data_str = unit_and_data[0].toString()+\".\"+unit_and_data[1].toString();\n\t\t\t}\n\t\t\telse{\n\t\t\t\tunit_and_data_str = unit_and_data.toString()\n\t\t\t}\n\t\t\tvar unit = unit_and_data_str[0,5].trim();\n\t\t\tvar data = unit_and_data_str.substring(5,unit_and_data_str.length).trim();\n\t\t\tver_info_obj[\"DATA\"] = data\n\t \t\tver_info_obj[\"UNIT\"] = unit\n\t \t\t//// \n\t \t\tif(arrayString.split(\":\")[1].indexOf(\"-\") !== -1){\n\t \t\t\tver_info_obj[\"DESCRIPTION OF MNEMONIC 1\"] = arrayString.split(\":\")[1].split(\"-\")[0].trim()\n\t \t\t\tver_info_obj[\"DESCRIPTION OF MNEMONIC 2\"] = arrayString.split(\":\")[1].split(\"-\")[1].replace(\"\\r\",\"\").trim()\n\t \t\t}\n\t \t\telse{\n\t \t\t\tver_info_obj[\"DESCRIPTION OF MNEMONIC 1\"] = arrayString.split(\":\")[1].replace(\"\\r\",\"\").trim()\n\t \t\t\tver_info_obj[\"DESCRIPTION OF MNEMONIC 2\"] = \"\"\n\t \t\t}\n\t \t\treturn ver_info_obj\n\t\t}",
"function GetPropsFromFile(text) {\r\n let result1 = this.GetMyLine(text);\r\n return this.GetProps(result1);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to create the GSM Alarm | function createAlarm (alarmName, description, alarmType, alarmPath) {
return gsm.addAlarm(prefixURI+"/"+alarmName, //alarmURI
description, //alarmName
alarmPath, //path
"Motorola IRD4500", //deviceClass
prefixURI, //deviceURI
alarmType ); //type
} | [
"function alarmSendCode() {\n var cmd = \"2001\" + alarmPassword + \"00\";\n cmd = appendChecksum(cmd);\n sendToSerial(cmd);\n}",
"function alarmArm() {\n var cmd = \"0331\" + alarmPassword + \"00\";\n cmd = appendChecksum(cmd);\n sendToSerial(cmd);\n}",
"function alarmArmAway() {\n var cmd = \"0301\";\n cmd = appendChecksum(cmd);\n sendToSerial(cmd);\n}",
"function setAlarm(){\n\t\t tizen.alarm.removeAll(); //Removing all Alarms\n\t\t var date = new Date(new Date().getFullYear(),new Date().getMonth(), new Date().getDate(), 23, 59,59);\n\t\t var alarm1 = new tizen.AlarmAbsolute(date) ;\n\t\t var appControl = new window.tizen.ApplicationControl(\"http://tizen.org/appcontrol/operation/viewAlarm\");\n\t\t window.tizen.alarm.add(alarm1, tizen.application.getCurrentApplication().appInfo.id, appControl);\n\t\t \n\t\t var date2 = new Date(new Date().getFullYear(),new Date().getMonth(), new Date().getDate(),23, 59,59);\n\t\t date2.setDate(new Date().getDate()+1);\n\t\t var appControl2 = new window.tizen.ApplicationControl(\"http://tizen.org/appcontrol/operation/viewAlarm\");\n\t\t window.tizen.alarm.add(alarm12, tizen.application.getCurrentApplication().appInfo.id, appControl2);\n\t\t }",
"function alarmArmStay() {\n var cmd = \"0321\";\n cmd = appendChecksum(cmd);\n sendToSerial(cmd);\n}",
"function createChromeAlarm(text, time){\n\tvar repeatCheck = document.getElementById(\"loopCheck\").checked;\n\t// we have a repeating alarm\n\tif(repeatCheck){\n\t\tchrome.alarms.create(text,{\n\t\t\tdelayInMinutes : time, \n\t\t\tperiodInMinutes : time\n\t\t});\t\n\t} // else we have a non-repeating alarm\n\telse {\n\t\tchrome.alarms.create(text,{delayInMinutes : time});\n\t}\n\tconsole.log(\"alarm created \" + text + \": \" + time );\n}",
"function alarmDisarm() {\n var cmd = \"0401\" + alarmPassword + \"00\";\n cmd = appendChecksum(cmd);\n sendToSerial(cmd);\n}",
"async function createAlarmSound() {\n // SSML, or \"Speech Synthesis Markup Language\", is a way of specifying how text should\n // be converted to speech. Here, we use it to include a bugle sound along with \n // a spoken message (\"It's time to wake up...\")\n const ssml = `\n <speak>\n <audio src=\"https://actions.google.com/sounds/v1/alarms/bugle_tune.ogg\"></audio>\n This is your alarm. It's time to wake up.\n </speak>`;\n return await tts(ssml);\n}",
"function createAlarm(eventObject) {\n\tvar eDate = new Date(eventObject.time);\n\tconsole.log(\"eDate original: \" + eDate);\n\tvar now = new Date();\n\tvar eDay = eDate.getDay(); \n\t\n\t// extract reminder times and convert into date format\n\tvar eDates = new Array();\n\tfor(var i = 0; i < eventObject.remind.length; i++) {\n\t\t\n\t\tvar tempDate = new Date(eDate);\n\t\tvar hours = eventObject.remind[i].split(\":\");\n\t\ttempDate.setHours(hours[0]);\n\t\ttempDate.setMinutes(hours[1]);\n\t\teDates.push(tempDate);\n\t\tconsole.log(\"tempDate = \" + tempDate);\n\t}\n\tconsole.log(\"eDates = \" + eDates);\n\t// create alerts for no repeating event\n\tif(eventObject.repeat.length < 1) { \n\t\tfor(var i = 0; i < eDates.length; i++) {\n\t\t\tconsole.log(\"eDates[i] = \" + eDates[i]);\n\t\t\tvar timeDifference = eDates[i].getTime() - now.getTime();\n\t\t\tconsole.log(\"timeDifference = \" + timeDifference);\n\t\t\tchrome.alarms.create(eventObject.text + \"__\" + i, {\n\t\t\t\twhen: Number(now) + timeDifference\n\t\t\t});\n\t\t\tconsole.log(\"when = \" + Number(now) + timeDifference);\n\t\t\tconsole.log(\"alarm created\" + eventObject.text + \"__\" + i);\n\t\t}\n\t\treturn;\n\t}\n\n\t// create alerts for repeating event\n\tfor(var i = 0; i < eventObject.repeat.length; i++) {\n\t\tfor(var j = 0; j < eDates.length; j++) {\n\t\t\t// which weekday to repeat\n\t\t\tvar day;\n\t\t\tif (eDay == eventObject.repeat[i]) day = 0;\n\t\t\telse if (eDay > eventObject.repeat[i]) day = 7 - (eDay - eventObject.repeat[i]);\n\t\t\telse day = eventObject.repeat[i] - eDay;\n\t\t\t\n\t\t\tvar d = new Date(eDates[j]);\n\t\t\tif(day > 0){\n\t\t\t\td.setDate(eDates[j].getDate() + day);\n\t\t\t}\n\t\t\tvar timeDifference = (d.getTime() - now.getTime())/1000;\n\t\t\ttimeDifference /= 60;\n\t\t\tchrome.alarms.create(eventObject.text + \"__\" + i + j, {\n\t\t\t\tdelayInMinutes: Math.abs(Math.round(timeDifference)),\n\t\t\t\tperiodInMinutes: 10080 \n\t\t\t});\n\t\t\tchrome.alarms.get(eventObject.text + \"__\" + i + j, function(alarm) {\n\t\t\t\tconsole.log(\"alarm created: \" + alarm.name);\n\t\t\t});\n\t\t}\t\n\t}\n}",
"function Start_Gsm() {\n answer=\"OK\";\n console.log(\"GSM Starting..\");\n pinMode(C0,\"output\");\n digitalPulse(C0,1,2000);\n Send_Command(\"AT\\r\\n\",500,function(){Set_SMS_Mode();\n });\n}",
"function alarm() {\n\n /* set new status */\n status();\n\n /* send new msg */\n send();\n }",
"createAlarm(name, alarmInfo) {\n chrome.alarms.create(name, alarmInfo);\n const json = JSON.stringify(alarmInfo, null, 2).replace(/\\s+/g, ' ');\n this.logMessage(`Created \"${name}\"\\n${json}`);\n this.refreshDisplay();\n }",
"function alarmSendBreak() {\n var cmd = \"070^\";\n cmd = appendChecksum(cmd);\n sendToSerial(cmd);\n}",
"function createAlarm(e) {\r\n if (e.keyCode !== 13)\r\n return;\r\n input = document.getElementById(\"alarmCreate\").value;\r\n var duration = parseFloat(input);\r\n if (isNaN(duration))\r\n alert(\"Invalid time duration entered!\");\r\n else {\r\n var name = \"Alarm \" + Date.now(); // Generate unique alarm name\r\n chrome.alarms.create(name, { delayInMinutes: duration });\r\n console.log(\"Alarm set. (\" + duration + \" minutes)\");\r\n }\r\n}",
"function almTrigger( timeStamp, duration, condString, alarms2, series1, config ) {\r\n \r\n //utils.log( timeStamp + \" - Alarm Trigger test...\" );\r\n \r\n var retVal = {\r\n trigger: false,\r\n timeStamp: timeStamp \r\n };\r\n var timeNow = new Date();\r\n\r\n //If timestamp is 0, add current time and return false, else evaluate time difference\r\n if (timeStamp === 0) {\r\n retVal.timeStamp = timeNow;\r\n retVal.trigger = false;\r\n } else {\r\n var elapsed = utils.minutesElapsed( timeStamp, timeNow );\r\n //utils.log( 'timeStamp: ' + Date.parse(timeStamp) + ' timeNow: ' + Date.parse(timeNow) + ' elapsed: ' + elapsed );\r\n if ( elapsed >= duration ) {\r\n\r\n //Mark which series is affected for plotting annotations \r\n // 0=DHT_T1, 1=DHT_H1, 2=DHT_T2, 3=DHT_H2, 4=OW1, 5=OW2, 6=Amps, 7=Door1, 8=Door2 \r\n alarms2.alarmSeries = series1;\r\n\r\n //Send info to utils\r\n utils.log( timeStamp + ' - Alarm activated: ' + condString );\r\n \r\n //Activate hardware buzzer, if available\r\n\r\n //Place condition into alarms2.alarmString along with timestamp\r\n alarms2.alarmString = condString + ' (' + timeStamp + ')';\r\n \r\n //Update alarms.json\r\n alarms2 = updateAlms( alarms2, 'update', config );\r\n \r\n //Update client with alarm.\r\n alarms2.alarmSocket = 'trigger';\r\n\r\n //Send email \r\n if ( alarms2.emailAddr1 !== '' ) {\r\n var emService = alarms2.mailService;\r\n var emUser = alarms2.mailUser;\r\n var emPassword = alarms2.mailPass;\r\n var emAddresses = (alarms2.emailAddr2 !=='') ? \r\n ( alarms2.emailAddr1 + ', ' + alarms2.emailAddr2) : ( alarms2.emailAddr1);\r\n var emSubject = 'CellarWarden Alarm Notification';\r\n var emText = timeStamp + ' - ALARM Activated!\\n' +\r\n config.configTitle + ': ' + condString; \r\n sendEmail( emService, emUser, emPassword, emAddresses, emSubject, emText );\r\n }; \r\n\r\n //Prevent retriggering alarm by setting condition time to 0.\r\n retVal.timeStamp = 0; \r\n \r\n //Suppress multiple emails. \r\n if( alarms2.suppress ) {\r\n // Turn off alarm checking to prevent multiple emails. Must be reactivated manually. \r\n alarms2.alarmsOn = false;\r\n //almClearAll( alarms ); \r\n };\r\n \r\n //Return true to show that alarm has been triggered.\r\n retVal.trigger = true;\r\n } else {\r\n retVal.trigger = false;\r\n };\r\n };\r\n return retVal;\r\n}",
"function alarmSetDate() {\n \n var date = new Date();\n var hour = date.getHours().toString();\n if(hour.length == 1){\n hour = \"0\"+hour\n }\n var minute = date.getMinutes().toString();\n if(minute.length == 1){\n minute = \"0\"+minute\n }\n var month = date.getMonth()+1;\n var monthstr = month.toString();\n if(monthstr.length == 1){\n monthstr = \"0\"+monthstr\n }\n var day = date.getDate().toString();\n if(day.length == 1){\n day = \"0\"+day\n }\n var year = date.getFullYear().toString().substring(2,4);\n var timedate = hour+minute+monthstr+day+year;\n logger(\"AlarmSetDate\",\"SetDate: \"+timedate);\n var cmd = \"010\" + timedate;\n cmd = appendChecksum(cmd);\n sendToSerial(cmd);\n}",
"function setAlarm(time) {\n console.log(\"Setting an alarm for: \" + time);\n var timeWithoutAmPm = time;\n\n // Format string for speaking back to the user\n if (time.includes('.')) {\n var timeWithoutAmPm = time.replace('.', '');\n timeWithoutAmPm = timeWithoutAmPm.replace('.', '');\n }\n\n \n var timeArray = time.split(\":\");\n //alert(timeArray[0]);\n //alert(timeArray[1]);\n\n\n // No minutes included (ex. '11 o'clock' or '11 pm')\n if (timeArray[1] == null) {\n\n var hour = timeArray[0][0] + timeArray[0][1];\n var origHour = hour;\n\n if (origHour[1] == \" \") {\n origHour = origHour[0];\n }\n\n // Special case: \"12 o'clock\"\n if (hour == \"12\") {\n if (timeArray[0].includes(\"a.m.\")) {\n hour = \"00\";\n }\n else {\n hour = \"12\";\n }\n }\n else {\n // Switch to military time\n if (timeArray[0].includes(\"p.m.\")) {\n hour = parseInt(hour) + 12;\n }\n\n // Concatenate the \"0\" before it if it's in the single digits\n if (hour < 10) {\n hour = \"0\" + hour[0];\n }\n }\n\n // Set values\n document.getElementById(\"hour\").value = hour;\n document.getElementById(\"min\").value = \"00\";\n document.getElementById(\"sec\").value = \"00\";\n\n var amOrPm = \"PM\";\n if (hour < 12) {\n amOrPm = \"AM\";\n }\n // Tell the user that the alarm has been set\n responsiveVoice.speak(\"Ok, I have set an alarm for \" + origHour + \":00 \" + amOrPm);\n\n // Click to set the alarm\n document.getElementById(\"submitbutton\").click();\n\n // Indicate that the alarm has been set\n alarmIsSet = true;\n displayAlarm(origHour + \":00 \" + amOrPm);\n }\n else {\n var hour = parseInt(timeArray[0]);\n var origHour = hour;\n\n // Special case: \"12 o'clock\"\n if (hour == 12) {\n if (timeArray[1].includes(\"a.m.\")) {\n hour = \"00\";\n }\n else {\n hour = \"12\";\n }\n }\n else {\n // Switch to military time\n if (timeArray[1].includes(\"p.m.\") && (parseInt(timeArray[0]) != 12)) {\n hour = hour + 12;\n }\n\n // Concatenate the \"0\" before it if it's in the single digits\n if (hour < 10) {\n hour = \"0\" + hour;\n }\n }\n\n // if (isInt(hour)) {\n // alert('Was not an Int');\n // }\n\n // Set values\n document.getElementById(\"hour\").value = hour;\n document.getElementById(\"min\").value = timeArray[1][0] + timeArray[1][1];\n document.getElementById(\"sec\").value = \"00\";\n\n var amOrPm = \"PM\";\n if (hour < 12) {\n amOrPm = \"AM\";\n }\n\n // Tell the user that the alarm has been set\n responsiveVoice.speak(\"Ok, I have set an alarm for \" + origHour + \":\" + timeArray[1][0] + timeArray[1][1] + \" \" + amOrPm);\n\n // Click to set the alarm\n document.getElementById(\"submitbutton\").click();\n\n // Indicate that the alarm has been set\n alarmIsSet = true;\n displayAlarm(origHour + \":\" + timeArray[1][0] + timeArray[1][1] + \" \" + amOrPm);\n }\n}",
"function setAlarm() {\n resetAlarmBtn.disabled = false;\n alarmTime = `${hours.value}:${minutes.value} ${AMorPM.value}`;\n window.alert(`Alarm set for ${alarmTime}`);\n document.getElementById(\"alarm-time\").innerText = `Alarm set for ${alarmTime}`;\n}",
"function Appointment() { }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Controller for the Taxonomy Page. To allow the viewers and the functionality to be reused | function vjD3TaxonomyControl(viewer){
var originalurl = "http://?cmd=ionTaxDownInfo&taxid=1&level=2&raw=1";
vjDS.add("","dsTaxTree","http://?cmd=ionTaxDownInfo&taxid=1&level=2&raw=1");
vjDS.add("", "dsRecord", "http://?cmd=ionTaxInfo&taxid=&raw=1")
vjDS.add("","dsTreeViewerSpec","static://type_id,name,title,type,parent,role,is_key_fg,is_readonly_fg,is_optional_fg,is_multi_fg,is_hidden_fg,is_brief_fg,is_summary_fg,order,default_value,constraint,constraint_data,description\n"
+"taxonomy,name_list,Names,list,,,0,1,0,0,0,0,0,,,,,\n"
+"taxonomy,taxName,Tax-name,string,name_list,,0,1,1,1,0,0,0,,,,,\n"
+"taxonomy,taxid,Taxonomy ID,integer,,,0,1,0,0,0,0,0,,,,,\n"
+"taxonomy,parentid,Parent,integer,,,0,1,0,0,0,0,0,,,,,\n"
+"taxonomy,path,Ancestry,string,,,0,1,0,0,0,0,0,,,,,\n"
+"taxonomy,rank,Rank,string,,,0,1,0,0,0,0,0,,,,,\n"
+"taxonomy,bioprojectID,BioProjectID,integer,,,0,1,0,0,0,0,0,,,,,\n");
vjDS.add("", "dsTreeChildren", "static://");
vjDS.dsTaxTree.register_callback(function (viewer, content){
vjDS.dsTreeChildren.reload("static://" + content, true);
});
vjDS.add("", "dsSearch", "static://");
vjDS["dsSearch"].register_callback(onSearchResults);
if (viewer.taxIds){
var tt = "";
this.taxIds = verarr(viewer.taxIds);
tt += this.taxIds[0];
for (var i = 1; i < this.taxIds.length; i++){
tt += "," + this.taxIds[i];
}
vjDS.dsTaxTree.reload("http://?cmd=ionTaxParent&taxid=" + tt + "&commonParent=true&raw=1", true);
origianalurl = "http://?cmd=ionTaxParent&taxid=" + tt + "&commonParent=true&raw=1";
}
else
vjDS.dsTaxTree.reload("http://?cmd=ionTaxDownInfo&taxid=1&level=2&raw=1", true);
var graphViewer=new vjD3JS_TreeView({
data: 'dsTreeChildren',
height: 800,
taxTree:true,
openLevels:-1,
downloadFileName: "blah",
idElem: "taxid",
comparator: "taxid",
onClickCallback: onClickCircle,
onClickTextPostUpdateCallback: onLoadChildren,
onClickTextCallback: updateNodeInfo,
colorOnSelect: true,
onFinishUpdate: onFinishCallback
});
var panel = new vjPanelView({
data: ["dsVoid"],
formObject: document.forms[viewer.formName],
prevSearch:"",
onKeyPressCallback: smartSearchFunc,
iconSize: 24
});
var recViewer = new vjRecordView({
data: ["dsTreeViewerSpec", "dsRecord"],
name:'details',
formObject: document.forms[viewer.formName],
showRoot: false,
hideViewerToggle:true,
autoStatus: 3,
autoDescription: false,
implementSaveButton: false,
implementTreeButton: false,
showReadonlyInNonReadonlyMode: true,
constructAllNonOptionField: true,
implementSetStatusButton: false
});
lastNodeController = 0;
var nodeToUrl={}; //maps the node name to the last url submitted;
function onClickCircle (dElement){
if (!dElement.children || (dElement.children.length <= 0 && dElement.totalChidren != 0))
updateNodeInfo(dElement);
lastNodeController = dElement;
//onLoadChildren();
}
function updateNodeInfo (dElement){
lastNodeController = dElement;
var val = 10;
if (nodeToUrl[lastNodeController.taxid]) val = nodeToUrl[lastNodeController.taxid].cnt;
//updating the right hand side
var url = vjDS["dsRecord"].url;
url = urlExchangeParameter(url, "taxid", dElement.taxid);
vjDS["dsRecord"].reload(url, true);
if (dElement.totalChildren && parseInt(dElement.totalChildren) < 1){
panel.rows = [
{ name : 'refresh', icon: "refresh", order: 0, align:"left", description: "Refresh to original", url: onRefresh}
];
panel.rebuildTree();
panel.redrawMenuView();
}
else{
var options = [0, 10,20,50,100,1000];
var actualOptions = [];
for (var i = 1; i < options.length; i++){
if (options[i-1] <= dElement.totalChildren && dElement.totalChildren <= options[i]){
actualOptions.push([dElement.totalChildren, dElement.totalChildren]);
break;
}
actualOptions.push([options[i], options[i]]);
}
panel.rows = [
{ name : 'refresh', icon: "refresh", order: 0, align:"left", description: "Refresh to original", url: onRefresh},
//{ name : 'loadChildren', align : 'left', order : '1', description : 'Load Children', title : 'Load Children', url: onLoadChildren },
{ name : 'prev', icon: "previous", order: 1, align:"right", url: onPage},
{ name : 'ppager', align:'right', order:1, title:'at a time', description: 'Select Number of Children to Load' , type:'select', options: actualOptions, value:val, onChangeCallback: onPage, url: onPage},
{ name : 'next', icon: "next", order: 2, align:"right", url: onPage},
{ name : 'serachType', type : 'select', options:[[0, "Attach to Root"], [1, "Generate New Root"]/*, [2, "Multiple Search"]*/], order:3, align:"right", description : 'Select way to search for node', title:"Search Option", onChangeCallback: onChngSrch},
{ name : 'search', type : 'text', rgxpOff: true, align : 'right', size: 32, order : 4, description : 'Search', url: onSearch, path: "/search" }
];
panel.rebuildTree();
//panel.redrawMenuView();
panel.refresh();
}
//checking if there are any more nodes, loading any children
};
function onLoadChildren (viewer, node, a,b,c){
if(!lastNodeController || lastNodeController.totalChildren == 0) return;
var dsName = "dsTreeChildren" + Math.round(Math.random()*1000);
var tmpUrl;
if (nodeToUrl[lastNodeController.taxid])
tmpUrl = nodeToUrl[lastNodeController.taxid].url;
else{
tmpUrl = "http://?cmd=ionTaxDownInfo&taxid=" + lastNodeController.taxid + "&cnt=10";
nodeToUrl[lastNodeController.taxid] = {url: tmpUrl, cnt:10};
}
if (!lastNodeController.parent){
var dsName1 = "dsTreeChildren" + Math.round(Math.random()*1000);
vjDS.add("", dsName1, "http://?cmd=ionTaxDownInfo&taxid="+lastNodeController.parentTax+"&level=1&raw=1");
vjDS[dsName1].register_callback(onTreeParentLoaded);
vjDS[dsName1].load();
}
vjDS.add("", dsName, tmpUrl);
vjDS[dsName].register_callback(onTreeChildrenLoaded);
vjDS[dsName].load();
};
function onTreeChildrenLoaded(viewer, content){
vjDS["dsTreeChildren"].reload(vjDS["dsTreeChildren"].url + content, true);
};
function onTreeParentLoaded(viewer, content){
var tmp = vjDS["dsTreeChildren"].url.substring(9);
vjDS["dsTreeChildren"].reload("static://" + content + tmp, true);
};
function appendAllChildren (appendTo, node){
if (!node) return;
if (!appendTo.children) appendTo.children = [];
for (var i = 0; i < node.children.length; i++){
appendTo.children.push(node.children[i]);
appendAllChildren(node.children[i]);
}
};
//resets all of the parameters and the entire tree to default, 2 first levels from the root
function onRefresh (viewer, node){
vjDS["dsTaxTree"].reload("http://?cmd=ionTaxDownInfo&taxid=1&level=2&raw=1", true);
};
//controlls the paging of the tree
function onPage (viewer, node){
console.log(node);
/*
* If selected previous:
* check that not at the very 1st node. if not, just change the counter to the appropriate one and reload the tree.
* If changed the counter option:
* change the URL
* If clicked next:
* remember old state, change the start node, number of nodes to show. add that to the tree info
* */
if (node.name == "prev"){
var cnt = viewer.tree.root.children[3].value;
var actCnt, actStart;
if (!graphViewer.pagedNodeInfo[lastNodeController.taxid]) return;
if (graphViewer.pagedNodeInfo[lastNodeController.taxid].start - cnt < 0){
actCnt = graphViewer.pagedNodeInfo[lastNodeController.taxid].start;
actStart = 0;
}
else{
actCnt = cnt;
actStart = graphViewer.pagedNodeInfo[lastNodeController.taxid].start - cnt;
}
graphViewer.pagedNodeInfo[lastNodeController.taxid].end = graphViewer.pagedNodeInfo[lastNodeController.taxid].start;
graphViewer.pagedNodeInfo[lastNodeController.taxid].start = actStart;
graphViewer.pagedNodeInfo[lastNodeController.taxid].cnt = actCnt;
vjDS["dsTreeChildren"].reload(vjDS["dsTreeChildren"].url, true);
}else if (node.name == "ppager"){
var info = nodeToUrl[lastNodeController.taxid];
var nUrl;
if (!graphViewer.pagedNodeInfo[lastNode.taxid]){
if (info){
if (info.cnt == node.value) return;
nUrl = info.url;
nUrl = urlExchangeParameter(nUrl, "cnt", node.value);
info.url = nUrl;
info.cnt = node.value;
}
else{
nUrl = "http://?cmd=ionTaxDownInfo&taxid=" + lastNodeController.taxid + "&cnt=" + node.value;
nodeToUrl[lastNodeController.taxid] = {url: nUrl, cnt: node.value};
}
}
else{
var nodeInfo = graphViewer.pagedNodeInfo[lastNodeController.taxid];
nodeInfo.cnt = node.value;
if (nodeInfo.start + nodeInfo.cnt > lastNodeController.totalChildren)
nodeInfo.end = lastNodeController.totalChildren;
else
nodeInfo.end = nodeInfo.start + nodeInfo.cnt;
nUrl = "http://?cmd=ionTaxDownInfo&taxid=" + lastNodeController.taxid + "&cnt=" + nodeInfo.cnt + "&start=" + nodeInfo.start;
}
var dsName = "dsTreeChildren" + Math.round(Math.random()*1000);
vjDS.add("", dsName, nUrl);
vjDS[dsName].register_callback(onTreeChildrenLoaded);
vjDS[dsName].load();
}else if (node.name == "next"){
var cnt = viewer.tree.root.children[3].value;
var actEnd, actCnt, actStart;
if (cnt >= lastNodeController.totalChildren) return;
if (graphViewer.pagedNodeInfo[lastNodeController.taxid]){
var node = graphViewer.pagedNodeInfo[lastNodeController.taxid];
if (node.end == lastNodeController.totalChildren) return;
actCnt = cnt;
actStart = node.start + node.cnt;
if (actStart + node.cnt > lastNodeController.totalChildren-1){
actEnd = lastNodeController.totalChildren;
}
else
actEnd = actStart + node.cnt;
}else{
actCnt = cnt;
graphViewer.pagedNodeInfo[lastNodeController.taxid] = {};
if (2*cnt > lastNodeController.totalChildren-1){
actEnd = lastNodeController.totalChildren;
actStart = cnt;
actCnt = actEnd - actStart;
}
else{
actEnd = 2*cnt;
actStart = cnt;
}
}
graphViewer.pagedNodeInfo[lastNodeController.taxid].start = actStart;
graphViewer.pagedNodeInfo[lastNodeController.taxid].cnt = actCnt;
graphViewer.pagedNodeInfo[lastNodeController.taxid].end = actEnd;
if (graphViewer.pagedNodeInfo[lastNodeController.taxid].totalLoaded >= actEnd)
return;
var dsName = "dsTreeChildren" + Math.round(Math.random()*1000);
vjDS.add("", dsName, "http://?cmd=ionTaxDownInfo&taxid=" + lastNodeController.taxid + "&cnt=" + actCnt + "&start=" + actStart);
vjDS[dsName].register_callback(onTreeChildrenLoaded);
vjDS[dsName].load();
}
};
var searchOption = 0;
function onChngSrch (viewer, node){
searchOption = parseInt(node.value);
}
function onSearch (viewer, node, irow){
viewer.tree.root.children[6].value = node.taxID;
viewer.rebuildTree();
if (isNaN(parseInt(viewer.tree.root.children[6].value)) && searchOption == 2){
if(!lastNodeController) return;
var dsName = "dsTreeChildren" + Math.round(Math.random()*1000);
var tmpUrl = "http://?cmd=ionTaxParent&parent=" + lastNodeController.taxid + "&name=" + vjDS.escapeQueryLanguage(viewer.tree.root.children[6].value) + "&raw=1";
vjDS.add("", dsName, tmpUrl);
vjDS[dsName].register_callback(onTreeChildrenLoaded);
vjDS[dsName].load();
panel.rebuildTree();
panel.redrawMenuView();
return;
}
//if the attach to root option is selected
if (searchOption == 0){
if(!lastNodeController) return;
var dsName = "dsTreeChildren" + Math.round(Math.random()*1000);
var tmpUrl = "http://?cmd=ionTaxParent&parent=" + lastNodeController.taxid + "&taxid=" + node.taxID + "&raw=1";
vjDS.add("", dsName, tmpUrl);
vjDS[dsName].register_callback(onTreeChildrenLoaded);
vjDS[dsName].load();
}
else if (searchOption == 1){ //just reload and bring the first 2 levels if available.
vjDS["dsTaxTree"].reload("http://?cmd=ionTaxDownInfo&taxid=" + node.taxID + "&level=2&raw=1", true);
}
panel.rows.splice(1);
panel.rebuildTree();
panel.redrawMenuView();
};
function onFinishCallback (viewer){
if (lastNodeController)
$("#"+lastNodeController.taxid).click();
};
function smartSearchFunc (container, e, nodepath, elname){
var node = this.tree.findByPath(nodepath);
var el = this.findElement(node.name, container);
if (el.value && el.value.length >= 3){
var nUrl = "http:// ?cmd=ionTaxidByName&limit=20&name="+el.value + String.fromCharCode(e.which) +"&parent=" + lastNodeController.taxid + "&raw=1";
searchVal = el.value + String.fromCharCode(e.which);
vjDS["dsSearch"].reload(nUrl, true);
}
};
var searchVal;
function onSearchResults (viewer, content, requestInfo){
var table = new vjTable (content);
panel.rows.splice(7);
panel.rows[5].value = searchOption;
panel.rows[6].value = searchVal;
for(var i = 1; i < table.rows.length; i++){
panel.rows.push({name:table.rows[i].cols[1].replace(/[_\W]+/g, "-"), order:i ,title: table.rows[i].cols[1], isSubmitable: true, path: "/search/"+table.rows[i].cols[1].replace(/[_\W]+/g, "-"), taxID: table.rows[i].cols[0], url:onSearch});
}
panel.rebuildTree();
panel.redrawMenuView();
};
return [graphViewer, panel, recViewer];
} | [
"function BaseTaxonomiesController($rootScope, $scope, $translate, $location, TaxonomyResource, TaxonomiesResource, ngObibaMicaSearch, RqlQueryUtils, $cacheFactory, VocabularyService) {\n $scope.options = ngObibaMicaSearch.getOptions();\n $scope.RqlQueryUtils = RqlQueryUtils;\n $scope.metaTaxonomy = TaxonomyResource.get({\n target: 'taxonomy',\n taxonomy: 'Mica_taxonomy'\n });\n $scope.taxonomies = {\n all: [],\n search: {\n text: null,\n active: false\n },\n target: $scope.target || 'variable',\n taxonomy: null,\n vocabulary: null\n };\n $rootScope.$on('$translateChangeSuccess', function () {\n if ($scope.taxonomies && $scope.taxonomies.vocabulary) {\n VocabularyService.sortVocabularyTerms($scope.taxonomies.vocabulary, $translate.use());\n }\n });\n // vocabulary (or term) will appear in navigation iff it doesn't have the 'showNavigate' attribute\n $scope.canNavigate = function (vocabulary) {\n if ($scope.options.hideNavigate.indexOf(vocabulary.name) > -1) {\n return false;\n }\n return (vocabulary.attributes || []).filter(function (attr) { return attr.key === 'showNavigate'; }).length === 0;\n };\n this.navigateTaxonomy = function (taxonomy, vocabulary, term) {\n $scope.taxonomies.term = term;\n if ($scope.isHistoryEnabled) {\n var search = $location.search();\n search.taxonomy = taxonomy ? taxonomy.name : null;\n if (vocabulary && search.vocabulary !== vocabulary.name) {\n VocabularyService.sortVocabularyTerms(vocabulary, $scope.lang);\n search.vocabulary = vocabulary.name;\n }\n else {\n search.vocabulary = null;\n }\n $location.search(search);\n }\n else {\n $scope.taxonomies.taxonomy = taxonomy;\n if (!$scope.taxonomies.vocabulary || $scope.taxonomies.vocabulary.name !== vocabulary.name) {\n VocabularyService.sortVocabularyTerms(vocabulary, $scope.lang);\n }\n $scope.taxonomies.vocabulary = vocabulary;\n }\n };\n this.updateStateFromLocation = function () {\n var search = $location.search();\n var taxonomyName = search.taxonomy, vocabularyName = search.vocabulary, taxonomy = null, vocabulary = null;\n if (!$scope.taxonomies.all) { //page loading\n return;\n }\n $scope.taxonomies.all.forEach(function (t) {\n if (t.name === taxonomyName) {\n taxonomy = t;\n t.vocabularies.forEach(function (v) {\n if (v.name === vocabularyName) {\n vocabulary = v;\n }\n });\n }\n });\n if (!angular.equals($scope.taxonomies.taxonomy, taxonomy) || !angular.equals($scope.taxonomies.vocabulary, vocabulary)) {\n $scope.taxonomies.taxonomy = taxonomy;\n if (vocabulary) {\n VocabularyService.sortVocabularyTerms(vocabulary, $scope.lang);\n }\n $scope.taxonomies.vocabulary = vocabulary;\n }\n };\n this.selectTerm = function (target, taxonomy, vocabulary, args) {\n $scope.onSelectTerm(target, taxonomy, vocabulary, args);\n };\n this.clearCache = function () {\n var taxonomyResourceCache = $cacheFactory.get('taxonomyResource');\n if (taxonomyResourceCache) {\n taxonomyResourceCache.removeAll();\n }\n };\n var self = this;\n $scope.$on('$locationChangeSuccess', function () {\n if ($scope.isHistoryEnabled) {\n self.updateStateFromLocation();\n }\n });\n $scope.$watch('taxonomies.vocabulary', function (value) {\n if (RqlQueryUtils && value) {\n $scope.taxonomies.isNumericVocabulary = VocabularyService.isNumericVocabulary($scope.taxonomies.vocabulary);\n $scope.taxonomies.isMatchVocabulary = VocabularyService.isMatchVocabulary($scope.taxonomies.vocabulary);\n }\n else {\n $scope.taxonomies.isNumericVocabulary = null;\n $scope.taxonomies.isMatchVocabulary = null;\n }\n });\n $scope.navigateTaxonomy = this.navigateTaxonomy;\n $scope.selectTerm = this.selectTerm;\n $scope.clearCache = this.clearCache;\n}",
"function BaseTaxonomiesController($rootScope, $scope, $translate, $location, MetaTaxonomyResource, MetaTaxonomyMoveResource, MetaTaxonomyAttributeResource, ngObibaMicaSearch, VocabularyService) {\n $scope.options = ngObibaMicaSearch.getOptions();\n $scope.metaTaxonomy = MetaTaxonomyResource.get();\n $scope.taxonomies = {\n all: [],\n search: {\n text: null,\n active: false\n },\n target: $scope.target || 'variable',\n taxonomy: null,\n vocabulary: null\n };\n $rootScope.$on('$translateChangeSuccess', function () {\n if ($scope.taxonomies && $scope.taxonomies.vocabulary) {\n VocabularyService.sortVocabularyTerms($scope.taxonomies.vocabulary, $translate.use());\n }\n });\n // vocabulary (or term) will appear in navigation iff it doesn't have the 'showNavigate' attribute\n $scope.canNavigate = function (vocabulary) {\n return (vocabulary.attributes || []).filter(function (attr) { return attr.key === 'showNavigate'; }).length === 0;\n };\n this.navigateTaxonomy = function (taxonomy, vocabulary, term) {\n $scope.taxonomies.term = term;\n if ($scope.isHistoryEnabled) {\n var search = $location.search();\n search.taxonomy = taxonomy ? taxonomy.name : null;\n if (vocabulary && search.vocabulary !== vocabulary.name) {\n VocabularyService.sortVocabularyTerms(vocabulary, $scope.lang);\n search.vocabulary = vocabulary.name;\n }\n else {\n search.vocabulary = null;\n }\n $location.search(search);\n }\n else {\n $scope.taxonomies.taxonomy = taxonomy;\n if (!$scope.taxonomies.vocabulary || $scope.taxonomies.vocabulary.name !== vocabulary.name) {\n VocabularyService.sortVocabularyTerms(vocabulary, $scope.lang);\n }\n $scope.taxonomies.vocabulary = vocabulary;\n }\n };\n this.moveTaxonomyUp = function (taxonomy) {\n MetaTaxonomyMoveResource.put({\n target: $scope.target,\n taxonomy: taxonomy.name,\n dir: 'up'\n }).$promise.then(function () {\n $scope.metaTaxonomy = MetaTaxonomyResource.get();\n });\n };\n this.moveTaxonomyDown = function (taxonomy) {\n MetaTaxonomyMoveResource.put({\n target: $scope.target,\n taxonomy: taxonomy.name,\n dir: 'down'\n }).$promise.then(function () {\n $scope.metaTaxonomy = MetaTaxonomyResource.get();\n });\n };\n this.isTaxonomyHidden = function (taxonomy) {\n if (taxonomy.attributes) {\n var attr = taxonomy.attributes.filter(function (attr) { return attr.key === 'hidden'; }).pop();\n return attr && attr.value === 'true';\n }\n return false;\n };\n this.hideTaxonomy = function (taxonomy) {\n MetaTaxonomyAttributeResource.put({\n target: $scope.target,\n taxonomy: taxonomy.name,\n name: 'hidden',\n value: 'true'\n }).$promise.then(function () {\n $scope.metaTaxonomy = MetaTaxonomyResource.get();\n });\n };\n this.showTaxonomy = function (taxonomy) {\n MetaTaxonomyAttributeResource.put({\n target: $scope.target,\n taxonomy: taxonomy.name,\n name: 'hidden',\n value: 'false'\n }).$promise.then(function () {\n $scope.metaTaxonomy = MetaTaxonomyResource.get();\n });\n };\n this.updateStateFromLocation = function () {\n var search = $location.search();\n var taxonomyName = search.taxonomy, vocabularyName = search.vocabulary, taxonomy = null, vocabulary = null;\n if (!$scope.taxonomies.all) { //page loading\n return;\n }\n $scope.taxonomies.all.forEach(function (t) {\n if (t.name === taxonomyName) {\n taxonomy = t;\n t.vocabularies.forEach(function (v) {\n if (v.name === vocabularyName) {\n vocabulary = v;\n }\n });\n }\n });\n if (!angular.equals($scope.taxonomies.taxonomy, taxonomy) || !angular.equals($scope.taxonomies.vocabulary, vocabulary)) {\n $scope.taxonomies.taxonomy = taxonomy;\n if (vocabulary) {\n VocabularyService.sortVocabularyTerms(vocabulary, $scope.lang);\n }\n $scope.taxonomies.vocabulary = vocabulary;\n }\n };\n this.selectTerm = function (target, taxonomy, vocabulary, args) {\n $scope.onSelectTerm(target, taxonomy, vocabulary, args);\n };\n var self = this;\n $scope.$on('$locationChangeSuccess', function () {\n if ($scope.isHistoryEnabled) {\n self.updateStateFromLocation();\n }\n });\n $scope.navigateTaxonomy = this.navigateTaxonomy;\n $scope.moveTaxonomyUp = this.moveTaxonomyUp;\n $scope.moveTaxonomyDown = this.moveTaxonomyDown;\n $scope.hideTaxonomy = this.hideTaxonomy;\n $scope.showTaxonomy = this.showTaxonomy;\n $scope.selectTerm = this.selectTerm;\n}",
"function BaseTaxonomiesController($rootScope,\n $scope,\n $translate,\n $location,\n TaxonomyResource,\n TaxonomiesResource,\n ngObibaMicaSearch,\n RqlQueryUtils,\n $cacheFactory) {\n\n $scope.options = ngObibaMicaSearch.getOptions();\n $scope.RqlQueryUtils = RqlQueryUtils;\n $scope.metaTaxonomy = TaxonomyResource.get({\n target: 'taxonomy',\n taxonomy: 'Mica_taxonomy'\n });\n\n $scope.taxonomies = {\n all: [],\n search: {\n text: null,\n active: false\n },\n target: $scope.target || 'variable',\n taxonomy: null,\n vocabulary: null\n };\n\n $rootScope.$on('$translateChangeSuccess', function () {\n if ($scope.taxonomies && $scope.taxonomies.vocabulary) {\n RqlQueryUtils.sortVocabularyTerms($scope.taxonomies.vocabulary, $translate.use());\n }\n });\n\n // vocabulary (or term) will appear in navigation iff it doesn't have the 'showNavigate' attribute\n $scope.canNavigate = function(vocabulary) {\n if ($scope.options.hideNavigate.indexOf(vocabulary.name) > -1) {\n return false;\n }\n\n return (vocabulary.attributes || []).filter(function (attr) { return attr.key === 'showNavigate'; }).length === 0;\n };\n\n this.navigateTaxonomy = function (taxonomy, vocabulary, term) {\n $scope.taxonomies.term = term;\n\n if ($scope.isHistoryEnabled) {\n var search = $location.search();\n search.taxonomy = taxonomy ? taxonomy.name : null;\n\n if (vocabulary && search.vocabulary !== vocabulary.name) {\n RqlQueryUtils.sortVocabularyTerms(vocabulary, $scope.lang);\n search.vocabulary = vocabulary.name;\n } else {\n search.vocabulary = null;\n }\n\n $location.search(search);\n } else {\n $scope.taxonomies.taxonomy = taxonomy;\n\n if (!$scope.taxonomies.vocabulary || $scope.taxonomies.vocabulary.name !== vocabulary.name) {\n RqlQueryUtils.sortVocabularyTerms(vocabulary, $scope.lang);\n }\n\n $scope.taxonomies.vocabulary = vocabulary;\n }\n };\n\n this.updateStateFromLocation = function () {\n var search = $location.search();\n var taxonomyName = search.taxonomy,\n vocabularyName = search.vocabulary, taxonomy = null, vocabulary = null;\n\n if (!$scope.taxonomies.all) { //page loading\n return;\n }\n\n $scope.taxonomies.all.forEach(function (t) {\n if (t.name === taxonomyName) {\n taxonomy = t;\n t.vocabularies.forEach(function (v) {\n if (v.name === vocabularyName) {\n vocabulary = v;\n }\n });\n }\n });\n\n if (!angular.equals($scope.taxonomies.taxonomy, taxonomy) || !angular.equals($scope.taxonomies.vocabulary, vocabulary)) {\n $scope.taxonomies.taxonomy = taxonomy;\n\n if(vocabulary) {\n RqlQueryUtils.sortVocabularyTerms(vocabulary, $scope.lang);\n }\n\n $scope.taxonomies.vocabulary = vocabulary;\n }\n };\n\n this.selectTerm = function (target, taxonomy, vocabulary, args) {\n $scope.onSelectTerm(target, taxonomy, vocabulary, args);\n };\n\n this.clearCache = function () {\n var taxonomyResourceCache = $cacheFactory.get('taxonomyResource');\n if (taxonomyResourceCache) {\n taxonomyResourceCache.removeAll();\n }\n };\n\n var self = this;\n\n $scope.$on('$locationChangeSuccess', function () {\n if ($scope.isHistoryEnabled) {\n self.updateStateFromLocation();\n }\n });\n $scope.$watch('taxonomies.vocabulary', function(value) {\n if(RqlQueryUtils && value) {\n $scope.taxonomies.isNumericVocabulary = RqlQueryUtils.isNumericVocabulary($scope.taxonomies.vocabulary);\n $scope.taxonomies.isMatchVocabulary = RqlQueryUtils.isMatchVocabulary($scope.taxonomies.vocabulary);\n } else {\n $scope.taxonomies.isNumericVocabulary = null;\n $scope.taxonomies.isMatchVocabulary = null;\n }\n });\n\n $scope.navigateTaxonomy = this.navigateTaxonomy;\n $scope.selectTerm = this.selectTerm;\n $scope.clearCache = this.clearCache;\n}",
"function taxonomyCtrller($scope, taxonomyFact){\n\n /*\n * Global variables\n * \n * */\n var alfaNumericRegExpr = new RegExp(\"[A-Za-z]|[0-9]\");\n\n \n /*\n * Operations Functions\n * \n * */\n /* clear errors of the form */\n $scope.clearErrorsTaxonomyForm = function(){\n $scope.taxonomyModel.nameHasError = false;\n $scope.taxonomyModel.nameErrorClass = '';\n\n $scope.taxonomyModel.urlSlugHasError = false;\n $scope.taxonomyModel.urlSlugErrorClass = '';\n }\n \n /* clear form values */\n $scope.clearTaxonomyForm = function(){\n $scope.taxonomyModel.name = null;\n $scope.taxonomyModel.url_slug = null;\n $scope.taxonomyModel.parent_id = null;\n $scope.taxonomyModel.selected_parent = null;\n }\n \n /* create taxonomies */\n $scope.createTaxonomy = function()\n {\n if($scope.taxonomyModel.canCreateTaxonomy == true)\n {\n $scope.taxonomyModel.createAction = true;\n $scope.showTaxonomyForm();\n }\n }\n\n /* delete taxonomy */\n $scope.deleteTaxonomy = function(taxonomy_id)\n {\n var proceed = true;\n if(typeof taxonomy_id == 'string' && !$scope.taxonomyModel.canDeleteTaxonomy){\n proceed = false;\n }\n if(proceed){\n swal({\n title: \"Confirme \",\n text: \"Si confirma no será capaz de recuperar estos datos.\",\n type: \"warning\",\n showCancelButton: true,\n confirmButtonColor: \"#F3565D\",\n cancelButtonColor: \"#E5E5E5 !important\",\n confirmButtonText: \"Confirmar\",\n cancelButtonText: \"Cancelar\",\n closeOnConfirm: true,\n closeOnCancel: true\n },\n function (isConfirm) {\n if (isConfirm)\n {\n $scope.taxonomyModel.createAction = false;\n var taxonomiesIdCollection = [];\n if(typeof taxonomy_id == 'string'){\n if($scope.taxonomyModel.taxonomiesCollection.length > 0){\n for(var i=0; i<$scope.taxonomyModel.taxonomiesCollection.length; i++){\n if($scope.taxonomyModel.taxonomiesCollection[i].selected != undefined &&\n $scope.taxonomyModel.taxonomiesCollection[i].selected == true)\n {\n taxonomiesIdCollection.push($scope.taxonomyModel.taxonomiesCollection[i].id);\n }\n }\n }\n }\n else{\n taxonomiesIdCollection.push(taxonomy_id);\n }\n var data = {\n taxonomiesId: taxonomiesIdCollection\n };\n taxonomyFact.DeleteTaxonomies($scope, data);\n }\n });\n }\n }\n\n /* edit taxonomy */\n $scope.editTaxonomy = function(taxonomy)\n {\n $scope.taxonomyModel.createAction = false;\n $scope.taxonomyModel.selectedTaxonomy = taxonomy;\n $scope.showTaxonomyForm();\n }\n\n /* change the view mode of the taxonomies data */\n $scope.changeViewMode = function(option)\n {\n $scope.taxonomyModel.taxonomiesCollection = [];\n $scope.taxonomyModel.activeView = option;\n $scope.getTaxonomies();\n }\n\n /* get the Taxonomies Collection */\n $scope.getTaxonomies = function()\n {\n $scope.toggleDataLoader();\n var searchParametersCollection = {};\n if($scope.taxonomyModel.generalSearchValue != null){\n if(alfaNumericRegExpr.test($scope.taxonomyModel.generalSearchValue) &&\n $scope.taxonomyModel.showTaxonomyForm == false){\n searchParametersCollection.generalSearchValue = $scope.taxonomyModel.generalSearchValue;\n }\n }\n if($scope.taxonomyModel.selectedType != null)\n {\n searchParametersCollection.taxonomyTypeTreeSlug = $scope.taxonomyModel.selectedType.tree_slug;\n }\n if($scope.taxonomyModel.showTaxonomyForm == true){\n searchParametersCollection.returnDataInTree = true;\n }\n else{\n searchParametersCollection.returnDataInTree = $scope.taxonomyModel.activeView == 'tree' ? true : false;\n }\n taxonomyFact.getTaxonomiesData($scope,searchParametersCollection);\n }\n\n /* function on scope for go ahead to top */\n $scope.goToTop = function()\n {\n var pageHeading = $('.navbar-fixed-top');/*#go-to-top-anchor*/\n $('html, body').animate({scrollTop: pageHeading.height()}, 1000);\n }\n\n /* disabled options for CRUD operations */\n $scope.handleCrudOperations = function(option)\n {\n /* when option is 'disable' */\n if(option == 'disable'){\n $scope.taxonomyModel.canCreateTaxonomy = false;\n $scope.taxonomyModel.canEditTaxonomy = false;\n $scope.taxonomyModel.canDeleteTaxonomy = false;\n }\n else{/* else if 'reset'*/\n $scope.taxonomyModel.canCreateTaxonomy = true;\n $scope.taxonomyModel.canEditTaxonomy = false;\n $scope.taxonomyModel.canDeleteTaxonomy = false;\n $scope.taxonomyModel.allTaxonomiesSelected = false;\n /*$scope.taxonomyModel.selectedTaxonomy = null;*/\n }\n\n }\n\n /* handle key events triggered from input events in the CRUD form */\n $scope.handleFormInputKeyEvents = function(event, field)\n {\n /* key events from input 'taxonomy_name' */\n if(event.currentTarget.id == 'taxonomy_name'){\n if(event.type == 'keyup' && $scope.taxonomyModel.name.length > 0){\n $scope.taxonomyModel.url_slug = slugify($scope.taxonomyModel.name);\n }\n else if($scope.taxonomyModel.name.length == 0){\n $scope.taxonomyModel.url_slug = null;\n }\n }\n }\n\n /* Hide the CRUD form */\n $scope.hideTaxonomyForm = function()\n {\n $scope.taxonomyModel.showTaxonomyForm = false;\n $scope.handleCrudOperations('reset');\n $scope.getTaxonomies();\n\n $scope.goToTop();\n }\n\n /* reset the page size to default value 1 */\n $scope.resetPaginationPages = function()\n {\n $scope.taxonomyModel.taxonomiesCurrentPage = 1;\n $scope.taxonomyModel.taxonomiesPagesCollection = [];\n $scope.taxonomyModel.taxonomiesPagesCollection.push(1);\n $scope.taxonomyModel.taxonomiesCurrentResultStart = 0;\n $scope.taxonomyModel.taxonomiesCurrentResultLimit = 0;\n\n $scope.updatePaginationValues();\n }\n \n /* save taxonomy data */\n $scope.saveTaxonomyData = function(option)\n {\n $scope.toggleDataLoader();\n var canProceed = true;\n $scope.clearErrorsTaxonomyForm();\n var taxonomyData = {};\n taxonomyData.name = $scope.taxonomyModel.name;\n taxonomyData.url_slug = $scope.taxonomyModel.url_slug;\n taxonomyData.type_id = $scope.taxonomyModel.selectedType.id;\n taxonomyData.parent_id = null;\n if( $scope.taxonomyModel.selectedType.tree_slug != 'tag' && $scope.taxonomyModel.selected_parent != null){\n taxonomyData.parent_id = $scope.taxonomyModel.selected_parent.id;\n }\n if(taxonomyData.name == null || !alfaNumericRegExpr.test(taxonomyData.name) ||\n taxonomyData.url_slug == null || !alfaNumericRegExpr.test(taxonomyData.url_slug)){\n canProceed = false;\n if(taxonomyData.name == null || !alfaNumericRegExpr.test(taxonomyData.name)){\n $scope.taxonomyModel.nameHasError = true;\n $scope.taxonomyModel.nameErrorClass = 'has-error';\n }\n if(taxonomyData.url_slug == null || !alfaNumericRegExpr.test(taxonomyData.url_slug)){\n $scope.taxonomyModel.urlSlugHasError = true;\n $scope.taxonomyModel.urlSlugErrorClass = 'has-error';\n }\n }\n\n if(canProceed){\n if($scope.taxonomyModel.createAction == false){\n taxonomyData.taxonomy_id = $scope.taxonomyModel.selectedTaxonomy.id\n }\n var taxonomyData = {taxonomyData: taxonomyData};\n var action = $scope.taxonomyModel.createAction == true ? 'create' : 'edit';\n\n taxonomyFact.SaveTaxonomyData($scope, taxonomyData, option, action);\n }\n else{\n $scope.toggleDataLoader();\n toastr.options.timeOut = 3000;\n toastr.error(\"El formulario tiene valores incorrectos o en blanco.\",\"¡Error!\");\n }\n }\n\n /* search Taxonomies through Search Input Field */\n $scope.searchTaxonomies = function($event)\n {\n /*when ENTER key are press OR input value are empty */\n if(($event.keyCode == 13 && alfaNumericRegExpr.test($scope.taxonomyModel.generalSearchValue)) \n || !alfaNumericRegExpr.test($scope.taxonomyModel.generalSearchValue)){\n $scope.getTaxonomies();\n }/*when ESCAPE key are press*/\n else if($event.keyCode == 27){\n $scope.taxonomyModel.generalSearchValue = null;\n $scope.getTaxonomies();\n }\n }\n\n /* selecting/deselecting all taxonomies */\n $scope.SelectAllTaxonomies = function(event){\n var canDeleteAll = true;\n $scope.taxonomyModel.allTaxonomiesSelected = !$scope.taxonomyModel.allTaxonomiesSelected;\n if(!$scope.taxonomyModel.allTaxonomiesSelected){\n canDeleteAll = false;\n }\n for(var i= 0; i<$scope.taxonomyModel.taxonomiesCollection.length; i++){\n $scope.taxonomyModel.taxonomiesCollection[i].selected = $scope.taxonomyModel.allTaxonomiesSelected;\n if($scope.taxonomyModel.allTaxonomiesSelected == true && $scope.taxonomyModel.taxonomiesCollection[i].canDelete == 0){\n canDeleteAll = false;\n }\n }\n\n $scope.taxonomyModel.canDeleteTaxonomy = canDeleteAll;\n }\n\n /*selecting/deselecting taxonomy */\n $scope.SelectTaxonomy= function(event,taxonomy){\n var canDeleteAll = true;\n var canEditAll = true;\n var totalTaxonomiesSelected = 1;\n taxonomy.selected = !taxonomy.selected;\n if($scope.taxonomyModel.taxonomiesCollection.length == 1){\n if(taxonomy.selected == false){\n canDeleteAll = false;\n canEditAll = false;\n totalTaxonomiesSelected = 0;\n }\n if(taxonomy.canDelete == 0){\n canDeleteAll = false;\n }\n if(taxonomy.canDelete == 0){\n canEditAll = false;\n }\n }\n else if($scope.taxonomyModel.taxonomiesCollection.length > 1){\n totalTaxonomiesSelected = 0;\n for(var i=0; i<$scope.taxonomyModel.taxonomiesCollection.length; i++){\n var taxonomy = $scope.taxonomyModel.taxonomiesCollection[i];\n if(taxonomy.selected == true){\n totalTaxonomiesSelected++;\n if(taxonomy.canDelete == 0){\n canDeleteAll = false;\n }\n if(taxonomy.canEdit == 0){\n canEditAll = false;\n }\n }\n }\n }\n\n if(totalTaxonomiesSelected > 0)\n {\n if(canDeleteAll == true){\n $scope.taxonomyModel.canDeleteTaxonomy = true;\n if(totalTaxonomiesSelected == $scope.taxonomyModel.taxonomiesCollection.length){\n $scope.taxonomyModel.allTaxonomiesSelected = true;\n }\n else{\n $scope.taxonomyModel.allTaxonomiesSelected = false;\n }\n }\n if(totalTaxonomiesSelected == 1 && canEditAll == true){\n $scope.taxonomyModel.canEditTaxonomy = true;\n }\n else{\n $scope.taxonomyModel.canEditTaxonomy = false;\n }\n }\n else{\n $scope.taxonomyModel.canEditTaxonomy = false;\n $scope.taxonomyModel.canDeleteTaxonomy = false;\n $scope.taxonomyModel.allTaxonomiesSelected = false;\n }\n }\n\n /* select the taxonomy parent */\n $scope.selectTaxonomyParent = function()\n {\n if($scope.taxonomyModel.taxonomiesCollection.length > 0){\n var isParentSelected = false;\n for(var i=0; i<$scope.taxonomyModel.taxonomiesCollection.length; i++){\n var taxonomy = $scope.taxonomyModel.taxonomiesCollection[i];\n if(taxonomy.selected != undefined && taxonomy.selected == true){\n isParentSelected = true;\n $scope.taxonomyModel.selected_parent = taxonomy;\n break;\n }\n else if(taxonomy.childs.length > 0){\n for(var j=0; j<taxonomy.childs.length; j++){\n var child = taxonomy.childs[j];\n if(child.selected != undefined && child.selected == true){\n isParentSelected = true;\n $scope.taxonomyModel.selected_parent = child;\n break;\n }\n else if(child.childs.length > 0){\n for(var k=0; k<child.childs.length; k++){\n var grandChild = child.childs[k];\n if(grandChild.selected != undefined && grandChild.selected == true){\n isParentSelected = true;\n $scope.taxonomyModel.selected_parent = grandChild;\n break;\n }\n }\n }\n }\n }\n }\n if(isParentSelected == false){\n $scope.taxonomyModel.selected_parent = null;\n }\n\n $('#taxonomy-parents-modal-selector').modal('hide');\n }\n }\n\n /* show parents selector */\n $scope.showParentsSelector = function(){\n $scope.taxonomyModel.taxonomiesCollection = [];\n $('#taxonomy-parents-modal-selector').modal('show');\n $scope.getTaxonomies();\n }\n\n /* show the form to Create/Edit Taxonomies */\n $scope.showTaxonomyForm = function()\n {\n $scope.taxonomyModel.taxonomyFormTitle = ($scope.taxonomyModel.createAction ? 'Nueva ' : 'Editar ')\n + $scope.taxonomyModel.selectedType.name_es;\n $scope.handleCrudOperations('disable');\n $scope.clearErrorsTaxonomyForm();\n $scope.clearTaxonomyForm();\n if($scope.taxonomyModel.createAction){\n\n }\n else{\n $scope.taxonomyModel.name = $scope.taxonomyModel.selectedTaxonomy.name_es;\n $scope.taxonomyModel.url_slug = $scope.taxonomyModel.selectedTaxonomy.url_slug_es;\n if($scope.taxonomyModel.selectedTaxonomy.parent_id != null){\n $scope.taxonomyModel.selected_parent = {\n id: $scope.taxonomyModel.selectedTaxonomy.parent_id,\n name_es:$scope.taxonomyModel.selectedTaxonomy.parent_name\n };\n }\n }\n $scope.taxonomyModel.showTaxonomyForm = true;\n $scope.goToTop();\n }\n\n /* slugify text */\n function slugify(textToSlugify){\n var slugifiedText = textToSlugify.toString().toLowerCase()\n .replace(/\\s+/g, '-')\n .replace(/[^\\w\\\\-]+/g, '')\n .replace(/\\\\-\\\\-+/g, '-')\n .replace(/^-+/, '')\n .replace(/-+$/, '');\n\n return slugifiedText;\n }\n\n /* toggle data-loading message */\n $scope.toggleDataLoader = function()\n {\n $scope.taxonomyModel.loadingData = !$scope.taxonomyModel.loadingData;\n }\n\n /* update the styles of the I-checks components(radio or checkbox) */\n $scope.updateICheckStyles = function(event, icheckType, suffix, identifierClass){\n\n var eventType = null;\n /*ensuring the event comes from the view action*/\n if(typeof event == 'object'){\n if(event == null){eventType = 'click';}\n else{eventType = event.type;}\n }\n else{eventType = event;}\n\n /*if event is 'mouseover'*/\n if(eventType == 'mouseover'){\n if(identifierClass != null){\n $('.'+identifierClass).find('.i'+icheckType+'_square-blue').addClass('hover');\n }\n else{\n $('.'+suffix).addClass('hover');\n }\n\n }\n else if(eventType == 'mouseleave'){\n if(identifierClass != null){\n $('.'+identifierClass).find('.i'+icheckType+'_square-blue').removeClass('hover');\n }\n else{\n $('.'+suffix).removeClass('hover');\n }\n }\n else{/* event is 'click'*/\n $('.'+identifierClass).find('.i'+icheckType+'_square-blue').addClass('checked');\n $('.'+suffix+'-icheck').each(function(){\n if(icheckType == 'radio'){\n if(!$(this).hasClass(identifierClass) && $(this).find('.i'+icheckType+'_square-blue').hasClass('checked')){\n $(this).find('.i'+icheckType+'_square-blue').removeClass('checked');\n }\n }\n });\n\n\n if(suffix == 'taxonomy-type'){\n $('#taxonomy-types-modal-selector').modal('hide');\n }\n }\n\n }\n \n /* update the Selected Taxonomy Type value */\n $scope.updateSelectedTaxonomyType = function(event, taxonomyType){\n $scope.taxonomyModel.selectedType = taxonomyType;\n $scope.updateICheckStyles(event, 'radio', 'taxonomy-type', 'label-'+taxonomyType.tree_slug);\n $scope.getTaxonomies();\n }\n\n /* update values of the pagination options */\n $scope.updatePaginationValues = function(){\n $scope.taxonomyModel.taxonomiesCurrentResultStart = 0;\n $scope.taxonomyModel.taxonomiesCurrentResultLimit = 0;\n $scope.taxonomyModel.taxonomiesCurrentPage = ($scope.taxonomyModel.taxonomiesCurrentPage*1);\n $scope.taxonomyModel.taxonomiesCurrentPageSize = ($scope.taxonomyModel.taxonomiesCurrentPageSize*1);\n\n if($scope.taxonomyModel.taxonomiesCollection.length > 0){\n $scope.taxonomyModel.taxonomiesCurrentResultStart = ($scope.taxonomyModel.taxonomiesCurrentPage - 1) * $scope.taxonomyModel.taxonomiesCurrentPageSize + 1;\n $scope.taxonomyModel.taxonomiesCurrentResultLimit = ($scope.taxonomyModel.taxonomiesCurrentPageSize * $scope.taxonomyModel.taxonomiesCurrentPage);\n if($scope.taxonomyModel.taxonomiesCollection.length < ($scope.taxonomyModel.taxonomiesCurrentPageSize * $scope.taxonomyModel.taxonomiesCurrentPage)){\n\n $scope.taxonomyModel.taxonomiesCurrentResultLimit = $scope.taxonomyModel.taxonomiesCollection.length;\n }\n\n var totalPages = Math.ceil($scope.taxonomyModel.taxonomiesCollection.length / $scope.taxonomyModel.taxonomiesCurrentPageSize);\n $scope.taxonomyModel.taxonomiesPagesCollection = [];\n if(totalPages > 0){\n for(var i=1; i<=totalPages; i++){\n $scope.taxonomyModel.taxonomiesPagesCollection.push(i);\n }\n }\n else{\n $scope.taxonomyModel.taxonomiesPagesCollection.push(1);\n }\n }\n\n $scope.handleCrudOperations('reset');\n }\n\n \n\n\n /*\n * Initialization Functions\n * \n * */\n $scope.initVisualization = function (crudOperationOption){\n /*list view variables*/\n $scope.taxonomyModel.createAction = null;\n if(crudOperationOption == undefined){\n crudOperationOption = 'reset';\n }\n $scope.handleCrudOperations(crudOperationOption);\n $scope.taxonomyModel.allTaxonomiesSelected = false;\n $scope.taxonomyModel.loadingData = false;\n $scope.taxonomyModel.activeView = 'list';\n if($scope.taxonomyModel.taxonomyTypesCollection.length > 0){\n $scope.taxonomyModel.type = $scope.taxonomyModel.taxonomyTypesCollection[0].tree_slug;\n $scope.taxonomyModel.selectedType = $scope.taxonomyModel.taxonomyTypesCollection[0];\n setTimeout(function(){\n $scope.updateICheckStyles(null, 'radio', 'taxonomy-type', 'label-'+$scope.taxonomyModel.selectedType.tree_slug);\n },1000);\n }\n /*form view variables*/\n $scope.taxonomyModel.showTaxonomyForm = false;\n $scope.taxonomyModel.processingData = false;\n\n $scope.updatePaginationValues();\n $scope.clearErrorsTaxonomyForm();\n }\n function initValues(){\n /*generals variables*/\n $scope.taxonomyModel = {};\n $scope.success = false;\n $scope.error = false;\n /*list view variables*/\n $scope.taxonomyModel.taxonomiesCollection = [];\n $scope.taxonomyModel.taxonomyTypesCollection = [];\n $scope.taxonomyModel.taxonomySelectedCounter = 0;\n $scope.taxonomyModel.generalSearchValue = null;\n $scope.taxonomyModel.selectedType = null;\n $scope.taxonomyModel.selectedTaxonomy = null;\n /*pagination*/\n $scope.taxonomyModel.entriesSizesCollection = [];\n $scope.taxonomyModel.entriesSizesCollection = [5,10,20,50,100,150,200];\n $scope.taxonomyModel.taxonomiesCurrentPageSize = 20;\n $scope.taxonomyModel.taxonomiesCurrentPage = 1;\n $scope.taxonomyModel.taxonomiesPagesCollection = [];\n $scope.taxonomyModel.taxonomiesPagesCollection.push(1);\n $scope.taxonomyModel.taxonomiesCurrentResultStart = 0;\n $scope.taxonomyModel.taxonomiesCurrentResultLimit = 0;\n /*form view variables*/\n $scope.taxonomyModel.parentsCollection = [];\n $scope.taxonomyModel.taxonomyFormTitle = '';\n \n $scope.clearTaxonomyForm();\n var searchParametersCollection = {};\n taxonomyFact.loadInitialsData($scope,searchParametersCollection);\n }\n function init(){\n initValues();\n }\n init();\n\n }",
"function taxonomyFact($http) {\n var factory = {};\n toastr.options.timeOut = 1000;\n\n factory.loadInitialsData = function($scope,searchParametersCollection){\n $http({\n method: \"post\",\n url: Routing.generate('taxonomies_view_initials_data'),\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded'\n }\n }).then(function successCallback(response) {\n\n $scope.taxonomyModel.taxonomiesCollection = response.data.initialsData.taxonomiesDataCollection;\n $scope.taxonomyModel.taxonomyTypesCollection = response.data.initialsData.taxonomyTypesDataCollection;\n var showTaxonomyForm = response.data.initialsData.showTaxonomyForm;\n\n\n $scope.initVisualization('disable');\n if(showTaxonomyForm == true){\n $scope.createTaxonomy();\n }\n\n }, function errorCallback(response) {\n toastr.options.timeOut = 16000;\n if(response.data && response.data.message){\n toastr.error(response.data.message,\"Error\");\n }\n else{\n toastr.options.timeOut = 5000;\n toastr.error(\"Ha ocurrido un error, por favor intente nuevamente en unos minutos.\" +\n \" Si al intentar nuevamente persiste esta notificación de ERROR, asegúrese de que no sea debido \" +\n \"a la conexión o falla en servidores. De lo contrario contacte a los DESARROLLADORES.\");\n }\n });\n }\n\n factory.getTaxonomiesData = function($scope,searchParametersCollection, fnCallBack){\n $http({\n method: \"post\",\n url: Routing.generate('taxonomies_data'),\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n data:$.param(searchParametersCollection)\n }).then(function successCallback(response) {\n $scope.toggleDataLoader();\n if(fnCallBack != undefined && typeof fnCallBack == 'function'){\n fnCallBack(response);\n }\n else{\n $scope.taxonomyModel.taxonomiesCollection = response.data.taxonomiesDataCollection;\n $scope.updatePaginationValues();\n }\n\n }, function errorCallback(response) {\n $scope.updatePaginationValues();\n $scope.toggleDataLoader();\n toastr.options.timeOut = 16000;\n if(response.data && response.data.message){\n toastr.error(response.data.message,\"Error\");\n }\n else{\n toastr.options.timeOut = 5000;\n toastr.error(\"Ha ocurrido un error, por favor intente nuevamente en unos minutos.\" +\n \" Si al intentar nuevamente persiste esta notificación de ERROR, asegúrese de que no sea debido \" +\n \"a la conexión o falla en servidores. De lo contrario contacte a los DESARROLLADORES.\");\n }\n });\n }\n\n factory.SaveTaxonomyData = function($scope, data, option, action){\n $http({\n method: \"post\",\n url: Routing.generate('taxonomies_'+action),\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n data:$.param(data)\n }).then(function successCallback(response) {\n $scope.toggleDataLoader();\n if(response.data.success == 0){\n toastr.options.timeOut = 5000;\n toastr.error(response.data.message,\"Error\");\n }\n else{\n $scope.clearErrorsTaxonomyForm();\n if(option == 'clear'){\n $scope.clearTaxonomyForm();\n }\n else if(option == 'close'){\n $scope.clearTaxonomyForm();\n $scope.hideTaxonomyForm();\n }\n //toastr.options.timeOut = 3000;\n toastr.success(response.data.message,\"¡Hecho!\");\n }\n\n $scope.goToTop();\n\n }, function errorCallback(response) {\n $scope.toggleDataLoader();\n toastr.options.timeOut = 5000;\n if(response.data && response.data.message){\n toastr.error(response.data.message,\"¡Error!\");\n }\n else{\n toastr.error(\"Esta operación no ha podido ejecutarse.\",\"¡Error!\");\n }\n });\n\n }\n\n factory.DeleteTaxonomies = function($scope, data){\n\n $http({\n method: \"post\",\n url: Routing.generate('taxonomies_delete'),\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded'\n },\n data:$.param(data)\n }).then(function successCallback(response)\n {\n if(response.data.success == 0){\n toastr.options.timeOut = 5000;\n toastr.error(response.data.message,\"Error\");\n }\n else{\n toastr.success(response.data.message,\"¡Hecho!\");\n }\n\n $scope.getTaxonomies();\n\n }, function errorCallback(response) {\n toastr.options.timeOut = 5000;\n if(response.data && response.data.message){\n toastr.error(response.data.message,\"¡Error!\");\n }\n else{\n toastr.error(\"Esta operación no ha podido ejecutarse.\",\"¡Error!\");\n }\n });\n\n\n }\n\n return factory;\n }",
"async index({ request }) {\n\t\tconst filters = request.all();\n\n\t\treturn Taxonomy.query()\n\t\t\t.with('terms')\n\t\t\t.withFilters(filters)\n\t\t\t.withParams(request, { skipRelationships: ['terms'] });\n\t}",
"async show({ request }) {\n\t\tconst filters = request.all();\n\n\t\treturn Taxonomy.query()\n\t\t\t.getTaxonomy(request.params.id)\n\t\t\t.withFilters(filters)\n\t\t\t.withParams(request);\n\t}",
"function post_taxonomies_PostTaxonomies() {\n return Object(react[\"createElement\"])(post_taxonomies_check, null, Object(react[\"createElement\"])(post_taxonomies, {\n taxonomyWrapper: function taxonomyWrapper(content, taxonomy) {\n return Object(react[\"createElement\"])(taxonomy_panel, {\n taxonomy: taxonomy\n }, content);\n }\n }));\n}",
"function setTaxonomies() {\n if (service.activity.id) {\n // loop through the serivce taxonomies\n _.each(service.taxonomies, function (taxonomy) {\n // get the activity's assignments for the taxonomy\n var assignments = _.filter(service.activity.taxonomy, function (t) { return t.taxonomy_id == taxonomy.taxonomy_id; });\n // loop through the taxonomy's classifications\n _.each(taxonomy.classifications, function (classification) {\n var assignment = _.find(assignments, function (a) { return a.classification_id == classification.id; });\n if (assignment) {\n classification.active = true;\n if (taxonomy.single) {\n taxonomy.selected = classification.id;\n }\n }\n });\n });\n }\n }",
"static init () {\n new Taxonomy().binds();\n }",
"function StructureTermGroupController() {\r\n}",
"function StructureTermController() {\r\n}",
"async showTerms({ request, params }) {\n\t\tconst filters = request.all();\n\t\t// using getTaxonomy to yield errors if taxonomy does not exist\n\t\tconst taxonomy = await Taxonomy.getTaxonomy(params.id);\n\t\tfilters.taxonomy = taxonomy.id;\n\n\t\treturn Term.query()\n\t\t\t.withFilters(filters)\n\t\t\t.withParams(request, { filterById: false });\n\t}",
"function smpl_select_taxonomies(){\n\t$j(\"#smpl_sel\").click(function (){\n\t\tvisible = $j(\"select#smpl_sel_tax\").css('display');\n\t\tif(visible == \"none\"){\n\t\t\tvar url = smpl.ajax + \"/taxes/\";\n\t\t\t$j.get(url, function (data){\n\t\t\t\t$j(\"select#smpl_sel_tax\").html(data)\n\t\t\t\t$j(\"select#smpl_sel_tax\").show();\n\t\t\t});\n\t\t}else{\n\t\t\t$j(\"select#smpl_sel_tax\").hide();\n\t\t}\n\t});\n}",
"function taxonomy( n )\n{\n\twith( document )\n\t{\n\t\tchapter() ;\n\t\twrite( \".\" ) ;\n\t\twrite( n ) ;\n\t}\n}",
"function doNewTax() {\n var listparams = { // Full path -> /tax_load_structure/Text/Images/Custom\n tagPaths: ['/tax_load_structure/Text'],\n contentTypes: ['Text','c_Types']\n };\n var params = {\n renderType: 'taxonomy'\n };\n var renderingRequest = {\n listParameters: listparams,\n parameters: params,\n layoutsForTaxonomy: [['TextBlock'],['SmallBlockWithImage'],['new_t_written']], // [Text/Images]\n requestFlags: {}\n };\n var response; // Used to get the JSON Object Response from action\n var data = {\n service: 'OrchestraRenderingAPI',\n action: 'getRenderedContent',\n renderingRequest: JSON.stringify(renderingRequest),\n apiVersion: '5.0'\n };\n // Handle response of successful ajax call\n var callBackHandler = function(json, Success) {\n console.log(\"New Taxonomy Attempt: doNewTax(): \");\n console.log(json);\n response = JSON.parse(json);\n console.log(\"The response only object is as follows: ---------------\");\n console.log(response.responseObject);\n }\n var options = {\n cb: callBackHandler,\n cbHandlerOnComplete: function(textStatus) { console.log(\"Complete\"); // Handle response on complete\n console.log(\"-------------------------------------\");},\n readonly: true\n };\n doServiceRequest(data, options);\n}",
"function doTaxonomy() {\n\n var listparams = {\n tagPaths: ['/Taxonomy_Testimonials/level1'], // determines where to start looking for content\n contentTypes: ['c_Types'] // If using multiple types : ['c_Types,anotherType']\n };\n var params = {\n renderType: 'taxonomy'\n };\n var renderingRequest = {\n listParameters: listparams,\n parameters: params,\n layoutsForTaxonomy: [['Testimonials_t_written']],\n requestFlags: {}\n };\n var response; // Used to get the JSON Object Response from action\n var tdata = {\n service: 'OrchestraRenderingAPI',\n action: 'getRenderedContent',\n renderingRequest: JSON.stringify(renderingRequest),\n apiVersion: '5.0'\n };\n // Handle response of successful ajax call\n var callBackHandler = function(json, Success) {\n\n var placeholder = document.getElementsByClassName(\"taxonomyWrapper\");\n var taxDiv = placeholder[0]; // Find the div we are pushing the content into\n\n console.log(\"Rendering api initial attempt: doTaxonomy(): \");\n console.log(json);\n response = JSON.parse(json);\n var nResponse = JSON.parse(response.responseObject);\n\n var numItems = nResponse.renderings.length; // Get the number of items found\n for(var i = 0; i < numItems; i++) {\n // Grab each piece of content 1 at a time then push onto the page\n var anotherResp = nResponse.renderings[i].renderMap;\n var finalResp = anotherResp.Testimonials_t_written; // layout used in call\n taxDiv.innerHTML += finalResp;\n }\n }\n var toptions = {\n cb: callBackHandler,\n cbHandlerOnComplete: function(textStatus) { console.log(\"Complete\"); // Handle response on complete\n console.log(\"-------------------------------------\");},\n readonly: true\n };\n doServiceRequest(tdata, toptions);\n}",
"function get_tax_terms(tax){\n var placement = $('#tax-terms-container');\n placement.html(\"<p class='loading'>Fetching Terms...</p>\");\n\t\t$.ajax({\n\t\t\ttype: 'GET',\n\t\t\turl: window.parent.ewpq_admin_localize.ajax_admin_url,\n\t\t\tdata: {\n\t\t\t\taction: 'ewpq_get_tax_terms',\n\t\t\t\ttaxonomy: tax,\n\t\t\t\tnonce: window.parent.ewpq_admin_localize.ewpq_admin_nonce,\n\t\t\t},\n\t\t\tdataType: \"html\",\n\t\t\tsuccess: function(data) {\t\n\t\t\t\tplacement.html(data);\n\t\t\t},\n\t\t\terror: function(xhr, status, error) {\n\t\t\t\tresponseText.html('<p>Error - Something went wrong and the terms could not be retrieved.');\n\t\t\t}\n\t\t});\n\t}",
"function smpl_new_taxonomy(){\n\t$j(\"div.smpl_new_tax\").click(function(){\n\t\tdb = $j(\"div.smpl_tax_del\").length;\n\t\tsmpl_tax_max++;\n\t\tvar new_row = $j(\"div#smpl_new_row\").html();\t\t\n\t\tvar row = new_row.replace(/{{stid}}/g,smpl_tax_max);\n\t\trow = row.replace(/<!--/g,\"\");\n\t\trow = row.replace(/-->/g,\"\");\t\t\n\n\t\tvisible = $j(\"select#smpl_sel_tax\").css('display');\n\t\ttax = \"\";\n\t\tdesc = \"\";\n\t\tif(visible !== \"none\"){\n\t\t\t_tax = $j(\"#smpl_sel_tax option:selected\").text();\n\t\t\ttid = $j(\"#smpl_sel_tax option:selected\").val();\n\t\t\tif(tid > 0 ){\t\t\t\n\t\t\t\tt = _tax.split(\"|\");\n\t\t\t\ttax = t[0];\n\t\t\t\tdesc = t[1];\n\t\t\t}\n\t\t\trow = row.replace(\"{{tid}}\", tid);\n\t\t}else{\n\t\t\trow = row.replace(\"{{tid}}\", \"n\");\n\t\t}\t\t\n\t\trow = row.replace(\"{{tax}}\",tax);\n\t\trow = row.replace(\"{{desc}}\",desc);\n\t\t\n\t\t$j(\"table#SmplTaxonomyTable >tbody:last\").append(row);\n\t\tsmpl_delete_taxonomy();\t\t//defined in smpl.js\n\t});\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
/ Returns a list of movies that fit the specified params. callback(error, data) On success, gets the filtered list as JSON On fail, gets the error. | function getFilteredMovies(filter, callback) {
var options = {
method: 'GET',
endpoint:'movies5s',
qs: {ql:""}
};
// Build query from params specified
if (filter.name != '') {
if (options.qs.ql != "") // For multiple parameters
options.qs.ql += ",";
options.qs.ql += "name = '"+ filter.name +"'";
}
if (filter.year != '') {
if (options.qs.ql != "") // For multiple parameters
options.qs.ql += ",";
options.qs.ql += "year='"+ filter.year +"'";
}
// Send the request
/* client.request() options:
* `method` - http method (GET, POST, PUT, or DELETE), defaults to GET
* `qs` - object containing querystring values to be appended to the uri
* `body` - object containing entity body for POST and PUT requests
* `endpoint` - API endpoint, for example 'users/fred'
* `mQuery` - boolean, set to true if running management query, defaults to false
*/
sharedVars.client.request(options, function(getError, data) {
if (!getError) { // If successful, filter based on actor
if (filter.actor != '')
filterActor(data.entities, filter.actor);
}
callback(getError, data);
});
} | [
"function filterMovies(movies, callback) {\n logger.log(`filterMovies: incoming movies: ${movies.length}`);\n\n // pull values from the config\n const topMoviesIndex = config.movieFilter.topMoviesIndex;\n const minUserScore = config.movieFilter.minUserScore;\n const minCriticScore = config.movieFilter.minCriticScore;\n const minUserCriticScore = config.movieFilter.minUserCriticScore;\n\n // filter the movies...\n const filteredMovies = _(movies)\n .filter((movie, index) => {\n // take the first set of movies configured (no matter what)\n if (index < topMoviesIndex) {\n logger.log(`filterMovies: keeping ${movie.title} because of index`);\n return true;\n }\n\n // if a movie has a user score above the required amount, include it\n if (movie.userScore >= minUserScore) {\n logger.log(`filterMovies: keeping ${movie.title} because of user score`);\n return true;\n }\n\n // if a movie has a critic score above the required amount, include it\n if (movie.criticScore >= minCriticScore) {\n logger.log(`filterMovies: keeping ${movie.title} because of critic score`);\n return true;\n }\n\n // if a movie has both a user and critic score above required amount, include it\n if ((movie.userScore >= minUserCriticScore) &&\n (movie.criticScore >= minUserCriticScore)) {\n logger.log(`filterMovies: keeping ${movie.title} because of user and critic score`);\n return true;\n }\n\n // else no match\n return false;\n })\n .value();\n\n logger.log(`filterMovies: after filtering, returning ${filteredMovies.length} movies`);\n\n return callback(null, filteredMovies);\n}",
"function movieFilter(req, res) {\n let response = movieListSmall;\n if (req.query.name) {\n console.log('name ran')\n response = response.filter(movie => \n movie.film_title.toLowerCase().includes(req.query.name.toLowerCase())\n )\n }\n // submit feedback for number 1.2 in assignment\n else {\n console.log('type ran')\n let responseArr = [];\n response.forEach(movie => {\n // genre\n if (movie.genre.toLowerCase() === req.query.type.toLowerCase()) {\n responseArr.push(movie)\n }\n // country\n else if (movie.country.toLowerCase() === req.query.type.toLowerCase()) {\n responseArr.push(movie)\n }\n // avg_vote\n else {\n let numOfType = Number(req.query.type)\n if (numOfType <= movie.avg_vote) {\n responseArr.push(movie)\n } \n }})\n response = responseArr\n }\n res.json(response)\n}",
"function getMovieListFromSearch(name){\n requesting = true;\n $.ajax({\n type : 'POST',\n url : '/api/ps',\n dataType : 'json',\n data : {\n q: name\n },\n success : function(data){\n $(\"#movie_name_results\").html('');\n if($(\"#movie_name\").val().length <=2){\n $(\"#movie_name_results\").stop().animate({opacity: '0.0'},300); \n requesting = false;\n return;\n }\n $(\"#movie_name_results\").css({'display':'block'});\n $(\"#movie_name_results\").stop().animate({opacity: '1.0'},400);\n \n // Iterate through each result and append to list. Maintain information\n // on movie name, if, and year.\n for(var i = 0; i < data.length; i++){\n var item = \"\";\n item = '<li id=\"'+data[i]['id']+'\" rel=\"'+data[i]['title']+'\">'+data[i]['title']\n if(data[i]['year'] != \"-1\"){\n item = item + ' ('+data[i]['year']+')'\n }\n item = item + '</li>';\n $(\"#movie_name_results\").append(item);\n if(i > 200){i = data.length;}\n loadListeners();\n }\n requesting = false;\n },\n error : function(XMLHttpRequest, textStatus, errorThrown){\n requesting = false;\n }\n });\n\n}",
"function searchMovies(query, callback) {\n $.ajax({\n url: api.root + \"/search/movie\",\n data: {\n api_key: api.token,\n query: query\n },\n success: function(response) {\n model.browseItems = response.results;\n callback(response);\n }\n });\n}",
"function discoverMovies(callback) {\n $.ajax({\n url: api.root + \"/discover/movie\",\n data: {\n api_key: api.token\n },\n success: function(response) {\n model.browseItems = response.results;\n callback(response);\n }\n });\n}",
"function searchMovies(req, res, next) {\n // Filter movies by actor\n fetch(`${netflixURL}actor=${req.query.show_cast}`)\n .then(r => r.json())\n .then((results) => {\n res.movies = results;\n // console.log(res.movies);\n next();\n })\n .catch((err) => {\n res.err = err;\n next();\n });\n}",
"function discoverMovies(data, callback) {\n // DONE \n $.ajax({\n url: api.root + \"/discover/movie\",\n data: data,\n success: function(response) {\n model.browseItems = response.results;\n callback(response);\n },\n fail: function() {\n console.log(\"discover failed\");\n }\n });\n}",
"function getMovies() {\n // Get selections values\n const category = UICtrl.getSelectionValues().category;\n const director = UICtrl.getSelectionValues().director;\n\n // Get all stored movies in DataCtrl\n const data = DataCtrl.getStoredData();\n\n // Clear previous results\n UICtrl.clearResults();\n\n // Create an array that contains movies without rebeating\n const unique = [];\n\n // Make sure there is no repeating\n $.each(data.movies, function (i, el) {\n if (el.type === category || el.director === director) {\n if ($.inArray(el, unique) === -1) {\n UICtrl.displayResults(el);\n unique.push(el);\n }\n }\n });\n }",
"searchMovie( name, callback ) {\n let url = this._getUrl( '/search/movie', { query: name } );\n this._fetchData( url, callback );\n }",
"function movieSearch(userInput) {\n\n // this resets the list everytime we do a search\n potentialMovies = []; // list of movies that the user may be trying to select\n potentialIds = []; // list of correlating ID movie codes that the user may be trying to select\n movieDates = []; // list of release dates that correspond with the movie\n $('#selectionList').empty();\n\n var encoded = encodeURI(userInput); //encoded URI this api does not just take strings but only encodedURI\n var movieUrl = \"https://api.themoviedb.org/3/search/movie?api_key=e57e846268be194f276bcd176242c9a4&query=\" + encoded;\n\n $.ajax({\n url: movieUrl,\n method: \"GET\"\n }).then(function (data) {\n console.log(data.results);\n if (data.results == 0) {\n $(\"#alertmessage\").text(\"Invalid Movie! Try again!\");\n } else {\n var p = \"<p>paragraph 1</p>\";\n $(\"#alertmessage\").text(\"\");\n }\n for (let i = 0; i < data.results.length; i++) {\n potentialMovies.push(data.results[i].original_title); //potential movies added to a list\n potentialIds.push(data.results[i].id); // potential movies' ID added to a list\n movieDates.push(data.results[i].release_date); // the release date for all the money\n var movie = $('<li>').text(data.results[i].original_title + \" \" + data.results[i].release_date);\n var movie_link = $('<a onclick=\"return recommend(' + data.results[i].id + ')\">').append(movie);\n $(\"#selectionList\").append(movie_link);\n \n }\n }\n )\n}",
"getFilteredMovies () {\n let filteredMovies = moviesFilterService.getFilteredMoviesByRating(this.data.movies);\n filteredMovies = moviesFilterService.getFilteredMoviesByGenres(filteredMovies);\n\n return filteredMovies;\n }",
"function discoverMovies(callback) {\n $.ajax({\n url: api.root + \"/discover/movie\",\n data: {\n api_key: api.token\n },\n success: function(response) {\n model.browseItems = response.results;\n callback(response);\n //console.log(response);\n }\n });\n}",
"function getWatchedMovieList(callbackFn) {\n $.ajax({\n url: apiUrl + '/users/watched',\n type: 'GET',\n success: function(data) {\n callbackFn(data);\n },\n error: function(err) {\n throw err;\n }\n });\n }",
"function movieSearch(searchString) {\n var settings = {\n \"url\": \"https://api.themoviedb.org/3/search/movie?query=\" + encodeURIComponent(searchString) + \"&api_key=\" + user.apiKey,\n // \"url\": \"https://sleepy-dusk-13496.herokuapp.com/api/movies\",\n \"method\": \"GET\"\n };\n $.ajax(settings).done(function(response) {\n console.log(response);\n $('.topTwentyBox').html('');\n response.results.forEach(function(movie) {\n var newMovie = new MovieDetails(movie);\n newMovie.addToList();\n });\n });\n}",
"function collectRatings( movies, callback ){\n var result = []\n\n if ( movies !== undefined ) {\n if(Array.isArray(movies)) {\n var maxRequests = movies.length\n var reqCount = 0\n\n if( maxRequests === 0 )\n callback( [] )\n else {\n movies.forEach(function(movie) {\n var titles = {\n \"ID\": movie.ID,\n \"Title\": movie.Title,\n \"OriginalTitle\": movie.OriginalTitle\n }\n getRating( titles, add2Results )\n\n function add2Results(movie){\n result.push(movie)\n reqCount ++\n //All movie requests have been received\n if (reqCount === maxRequests)\n sortRatings( result, callback )\n }\n })\n }\n } else {\n var titles = {\n \"ID\": movies.ID,\n \"Title\": movies.Title,\n \"OriginalTitle\": movies.OriginalTitle\n }\n getRating( titles, handleMovie )\n\n function handleMovie( movie ){\n result.push( movie )\n callback( result )\n }\n }\n }\n}",
"function searchSimilarMovies(movieID) {\n let queryURL =\n \"https://api.themoviedb.org/3/movie/\" +\n movieID +\n \"/similar?api_key=\" +\n API_KEY +\n \"&language=en-US\";\n\n $.ajax({\n url: queryURL,\n method: \"GET\",\n }).then(function(response) {\n console.log(response);\n let similarMovies = [];\n for (let i = 0; i < response.results.length; i++) {\n similarMovies.push(response.results[i].title);\n }\n console.log(similarMovies);\n return similarMovies;\n });\n}",
"function searchMovie() {\n\tvar value = process.argv[3] || \"Mr. Nobody\"; //Default if nothing put in\n\tvar options = { \n\t\turl: 'http://www.omdbapi.com/',\n\t\tqs: {\n\t\t\tt: value,\n\t\t\tplot: 'short',\n\t\t\tr: 'json',\n\t\t\ttomatoes: true\n\t\t}\n\t}\n\trequest(options, function(err, response, body) {\n\tif (!err && response.statusCode == 200) {\n\t\tbody = JSON.parse(body);\n \t\tconsole.log(\"*\" + \"*\" + \"OMDB Results\" + \"*\" + \"*\")\n\t\tconsole.log(\"---Title: \" + body.Title);\n\t\tconsole.log(\"---Year: \" + body.Year);\n\t\tconsole.log(\"---IMDB Rating: \" + body.imdbRating);\n\t\tconsole.log(\"---Country: \" + body.Country);\n\t\tconsole.log(\"---Language: \" + body.Language);\n\t\tconsole.log(\"---Plot: \" + body.Plot);\n\t\tconsole.log(\"---Actors :\" + body.Actors);\n\t\tconsole.log(\"---Rotten Tomatoes Rating: \" + body.tomatoRating);\n\t\tconsole.log(\"---Rotten Tomatoes URL: \" + body.tomatoURL);\n\t\tlogData = {Title: body.Title, Year: body.Year, ImdbRating: body.imdbRating, Country: body.Country, Language: body.Language, Plot: body.Plot, Actors: body.Actors, rottenTomatoesRating: body.tomatoRating, rottenTomatoesUrl: body.tomatoURL};\n\t\twriteLog();\n\t}\n})\n}",
"function searchMovies(searchQuery, year = \"\") {\n \treturn $http.get(generateApiUrl('/search/movie', setSearchParams(searchQuery, year)));\n }",
"function searchMovie(value) {\n\n const path = '/search/movie';\n\n const url = generateUrl(path) + '&query=' + value;\n\n const render = renderMovies.bind({title: 'Results'});\n\n sectionMovies(url, render, handleError);\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tracks the pointer X position changes and calculates the "endFrame" for the image slider frame animation. This function only runs if the application is ready and the user really is dragging the pointer; this way we can avoid unnecessary calculations and CPU usage. | function trackPointer(event) {
var userDragging = ready && dragging ? true : false;
var demoDragging = demoMode;
if(userDragging || demoDragging) {
// Stores the last x position of the pointer
pointerEndPosX = userDragging ? getPointerEvent(event).pageX : fakePointer.x;
// Checks if there is enough time past between this and the last time period of tracking
if(monitorStartTime < new Date().getTime() - monitorInt) {
// Calculates the distance between the pointer starting and ending position during the last tracking time period
pointerDistance = pointerEndPosX - pointerStartPosX;
// Calculates the endFrame using the distance between the pointer X starting and ending positions and the "speedMultiplier" values
endFrame = currentFrame + Math.ceil((totalFrames - 1) * speedMultiplier * (pointerDistance / $container.width()));
// Updates the image slider frame animation
refresh();
// restarts counting the pointer tracking period
monitorStartTime = new Date().getTime();
// Stores the the pointer X position as the starting position (because we started a new tracking period)
pointerStartPosX = userDragging ? getPointerEvent(event).pageX : fakePointer.x;
}
} else {
return;
}
} | [
"_updateDragPosition() {\r\n // Current position + the amount of drag happened since the last rAF.\r\n const newPosition = this._wrapperTranslateX +\r\n this._pointerCurrentX - this._pointerLastX;\r\n \r\n // Get the slide that we're dragging onto.\r\n let slideIndex;\r\n let slidePosition;\r\n this._slides.forEach((slideObj, index) => {\r\n if (slideObj.position >= newPosition &&\r\n (isUndefined(slidePosition) || slideObj.position < slidePosition)) {\r\n slidePosition = slideObj.position;\r\n slideIndex = index;\r\n }\r\n });\r\n \r\n if (this._infiniteLoop) {\r\n let firstLayoutIndex;\r\n \r\n // Sometimes there's no slide to the left of the current one - in that\r\n // case, slideIndex would be undefined.\r\n if (isUndefined(slideIndex)) {\r\n // Get the leftmost slide - the one we just left to the pointer's right.\r\n const leftMostSlide = this._slides.slice(0)\r\n .sort((a, b) => a.layoutIndex > b.layoutIndex)[0];\r\n // Compute the slideIndex as a valid index for this._slides.\r\n slideIndex = leftMostSlide.layoutIndex - 1;\r\n while (slideIndex < 0) {\r\n slideIndex += this._slides.length;\r\n }\r\n slideIndex = slideIndex % this._slides.length;\r\n // Compute firstLayoutIndex.\r\n firstLayoutIndex = leftMostSlide.layoutIndex - 2;\r\n } else {\r\n // If slideIndex is defined, firstLayoutIndex is easy to compute.\r\n firstLayoutIndex = this._slides[slideIndex].layoutIndex - 1;\r\n }\r\n \r\n // Updated (shift) slides.\r\n const slidesToShift = [];\r\n const lastLayoutIndex = firstLayoutIndex + this.slidesPerView + 2;\r\n for (let i = firstLayoutIndex; i < lastLayoutIndex; i++) {\r\n slidesToShift.push(i);\r\n }\r\n this._shiftSlides(slidesToShift);\r\n } else {\r\n // When _infiniteLoop is disabled, if we drag to the left of the first\r\n // slide, the algorithm can't find a value for slideIndex (as indexes\r\n // don't go negative in that case).\r\n slideIndex = slideIndex || 0;\r\n }\r\n \r\n this._lastDraggedLayoutIndex = this._slides[slideIndex].layoutIndex;\r\n \r\n this._setWrapperTranslateX(newPosition);\r\n \r\n this._pointerLastX = this._pointerCurrentX;\r\n this._pointerLastY = this._pointerCurrentY;\r\n this._dragTicking = false;\r\n }",
"function setupImgFrameDragging() { \n var attrs = {\n isDragged: false, \n left: 0,\n top: 0,\n drag: { left: 0, top: 0 },\n start: { left: 0, top: 0 },\n };\n \n imgFrame.bind({\n mousedown: function(event) { \n if (!event) { event = window.event; } // required for IE\n \n attrs.drag.left = event.clientX;\n attrs.drag.top = event.clientY;\n attrs.start.left = imgFrame.position().left;\n attrs.start.top = imgFrame.position().top;\n attrs.isDragged = true; \n\n imgFrame.css({ 'cursor': 'default', 'cursor': '-moz-grabbing', 'cursor': '-webkit-grabbing' });\n \n return false;\n },\n \n mousemove: function(event) {\n if (!event) { event = window.event; } // required for IE\n \n if (attrs.isDragged) {\n attrs.left = attrs.start.left + (event.clientX - attrs.drag.left); \n attrs.top = attrs.start.top + (event.clientY - attrs.drag.top);\n \n imgFrame.css({\n 'left': attrs.left + 'px',\n 'top': attrs.top + 'px'\n });\n \n showTiles(); \n } \n } \n });\n\n imgFrame.ondragstart = function() { return false; } // for IE \n $(document).mouseup(function() { stopImgFrameMove(); });\n\n function stopImgFrameMove() {\n attrs.isDragged = false; \n imgFrame.css({ 'cursor': '' });\n } \n }",
"function dragOrResizeStart (){\n lastChangeX = 0, lastChangeY = 0;\n isDraggingOrResizing = true;\n }",
"function mousemove(evt) {\n // console.log('mousemove', evt);\n const x = evt.screenX;\n const dx = lastX - x;\n lastX = x;\n // console.log('mousemove', dx);\n observerAngle += dx * dAngledX;\n const {imageIndex, offsetAngle} = getImageAndAngle(observerAngle);\n setView({imageIndex, offsetAngle});\n}",
"function onFrame() {\n\n\t\t\t\t// Frame arrived\n\t\t\t\tisFrameRequested = false;\n\n\t\t\t\tif (!index && index !== 0)\n\t\t\t\t\tindex = getIndexOffset(self.index);\n\n\t\t\t\ttime = time || 0;\n\n\t\t\t\t// Move using CSS transition\n\t\t\t\tif (isCSS && config.isCarousel) {\n\n\t\t\t\t\ttouchX = touchX || 0;\n\n\t\t\t\t\t// Callback when complete\n\t\t\t\t\tif (time && complete)\n\t\t\t\t\t\tstrip.one(prefix.toLowerCase() + 'TransitionEnd transitionend', complete);\n\n\t\t\t\t\t// Move using CSS animation\n\t\t\t\t\tstyle[prefix + 'Transition'] = (time)? time / 1000 + 's' : '';\n\t\t\t\t\tstyle[prefix + 'Transform'] = 'translateX(' + (getTransitionX(index, true) - touchX) * -1 + '%)';\n\n\t\t\t\t\t// No transition time, run callback immediately\n\t\t\t\t\tif (!time && complete)\n\t\t\t\t\t\tcomplete();\n\t\t\t\t}\n\n\t\t\t\t// Move using jQuery\n\t\t\t\telse strip.stop(true, true).animate({ left: getTransitionX(index) + '%' }, time, complete);\n\t\t\t}",
"_sliderDrag(e){\n console.log(\"Dragging\");\n switch(e.detail.state){\n case 'track':\n this.sliderPos = Math.min(Math.max(15, e.detail.x - this._getBoundaryPos()), (this.width-20));\n break;\n }\n }",
"updateAfterDrag() {\n const movement = (this.slider.rtl ? -1 : 1) * (this.drag.endX - this.drag.startX);\n const movementDistance = Math.abs(movement);\n const howManySliderToSlide = this.slider.perPage;\n\n const slideToNegativeClone = movement > 0 && this.slider.currentSlide - howManySliderToSlide < 0;\n const slideToPositiveClone = movement < 0 && this.slider.currentSlide + howManySliderToSlide > this.slider.slength - this.slider.perPage;\n\n if (movement > 0 && movementDistance > this.slider.threshold && this.slider.slength > this.slider.perPage) {\n this.slider.prev(howManySliderToSlide);\n } else if (movement < 0 && movementDistance > this.slider.threshold && this.slider.slength > this.slider.perPage) {\n this.slider.next(howManySliderToSlide);\n }\n this.ui.toggle(false);\n this.slider.slideToCurrent(true); // slideToNegativeClone || slideToPositiveClone\n }",
"function handleSliderDrag(event){\n\t\t\n\t\tvar diff = g_temp.lastMouseX - g_temp.startMouseX;\n\t\t\n\t\tif(diff == 0)\n\t\t\treturn(true);\n\t\t\n\t\tvar direction = (diff < 0) ? \"left\":\"right\";\n\t\t\n\t\tvar objZoomSlider = g_parent.getObjZoom();\n\t\t\n\t\t//don't drag if the zoom panning enabled\n\t\t//store init position after image zoom pan end\n\t\tif(objZoomSlider){\n\t\t\t\n\t\t\tvar isPanEnabled = objZoomSlider.isPanEnabled(event,direction);\n\t\t\t\t\t\t\n\t\t\tif(isPanEnabled == true){\n\t\t\t\tg_temp.isInitDataValid = false;\n\t\t\t\treturn(true);\t\t\t\t\n\t\t\t}else{\n\t\t\t\t\n\t\t\t\tif(g_temp.isInitDataValid == false){\n\t\t\t\t\tstoreInitTouchData(event);\n\t\t\t\t\treturn(true);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t\t\n\t\t//set inner div position\n\t\tvar currentPosx = g_temp.startPosx + diff;\n\t\t\n\t\t//check out of borders and slow down the motion:\n\t\tif(diff > 0 && currentPosx > 0)\n\t\t\tcurrentPosx = currentPosx / 3;\t\t\n\t\t\n\t\telse if(diff < 0 ){\n\t\t\t\n\t\t\tvar innerEnd = currentPosx + g_objInner.width();\n\t\t\tvar sliderWidth = g_objSlider.width();\n\t\t\t\n\t\t\tif( innerEnd < sliderWidth ){\n\t\t\t\tcurrentPosx = g_temp.startPosx + diff/3;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(g_temp.isDragging == false){\n\t\t\tg_temp.isDragging = true;\n\t\t\tg_objParent.trigger(g_parent.events.START_DRAG);\n\t\t}\n\t\t\t\t\n\t\tg_objInner.css(\"left\", currentPosx+\"px\");\n\t\t\n\t\t//drag video\n\t\tif(g_temp.isDragVideo == true){\n\t\t\tvar posDiff = currentPosx - g_temp.startPosx;\n\t\t\tvar videoPosX = g_temp.videoStartX + posDiff;\n\t\t\t\n\t\t\tg_temp.videoObject.css(\"left\", videoPosX);\n\t\t}\n\t\t\n\t}",
"function updatePosition(event){\n\t// no position updates if animation is paused\n\tif(!running)\n\t\treturn;\n\t\n\t// calculate the position offset of the Canvas on the web page\n //changed clientX to offsetX\n\tvar mouseX = event.offsetX;\n\tvar mouseY = event.offsetY;\n\n\t// update the cursor's x and y position\n\txPos = Math.floor(mouseX);\n // xPos = xPos-320;\n\tyPos = Math.floor(mouseY);\n \n console.log(xPos, yPos);\n\n}",
"_checkVisualizationPosition(){\n const x = Number.parseInt(this._senderWindow.getAttribute(\"x\"));\n if(x + this._windowSize * 100 >= this._visualizationWidth - this._slidingViewX)\n this._move((x + this._slidingViewX) / 100 - INITIAL_POSITION);\n }",
"mouseReleased() {\n if (this.dragging) {\n //after its done dragging we calculate the dif in the starting mousex vs. current mousex,\n //in relation to time\n let offsetX = mouseX - this.startX;\n let offsetY = mouseY - this.startY;\n let timeOffset = (millis() - this.startTime) / 24;\n this.decelX = offsetX / timeOffset;\n this.decelY = offsetY / timeOffset;\n this.decelerating = true;\n this.dragging = false;\n }\n }",
"function endPositionChange( slider )\n{\n\tslider.setAttribute(\"onmousemove\",\"\");\n\tslider.setAttribute(\"changing\",\"false\");\n\tvar pos = slider.getAttribute(\"curpos\") / 100;\n\tplayer.setNewPosition( pos );\n}",
"function drag(e){ //function called from nonogramMakerCanvas.js file\n\t//deal with horizontal shifting\n\tvar prev_xOffset = xOffset;\n\txOffset += e.movementX;\n\t\n\t\t//update display\n\tif(e.movementX > 0){\n\t\tvar pic = ctx.getImageData(0,0,window.innerWidth-e.movementX,window.innerHeight);\n\t\tctx.clearRect(0,0,canvas.width,canvas.height);\n\t\tctx.putImageData(pic,e.movementX,0);\n\t\tdrawGridlines(\"lightblue\",{xMin:0, xMax:e.movementX, yMin:0, yMax:canvas.height});\n\t} else if(e.movementX < 0){\n\t\tvar pic = ctx.getImageData(-e.movementX,0,window.innerWidth+e.movementX,window.innerHeight);\n\t\tctx.clearRect(0,0,canvas.width,canvas.height);\n\t\tctx.putImageData(pic,0,0);\n\t\tdrawGridlines(\"lightblue\",{xMin:canvas.width+e.movementX, xMax:canvas.width, yMin:0, yMax:canvas.height});\n\t} //if e.movementX === 0, don't need to do anything\n\t\n\t\n\t\n\t\n\t//deal with vertical shifting\n\tvar prev_yOffset = yOffset;\n\tyOffset += e.movementY;\n\t\n\t\t//update display\n\tif(e.movementY > 0){\n\t\tvar pic = ctx.getImageData(0,0,window.innerWidth,window.innerHeight-e.movementY);\n\t\tctx.clearRect(0,0,canvas.width,canvas.height);\n\t\tctx.putImageData(pic,0,e.movementY);\n\t\tdrawGridlines(\"lightblue\",{xMin:0, xMax:canvas.width, yMin:0, yMax:e.movementY});\n\t} else if(e.movementY < 0){\n\t\tvar pic = ctx.getImageData(0,-e.movementY,window.innerWidth,window.innerHeight+e.movementY);\n\t\tctx.clearRect(0,0,canvas.width,canvas.height);\n\t\tctx.putImageData(pic,0,0);\n\t\tdrawGridlines(\"lightblue\",{xMin:0, xMax:canvas.width, yMin:canvas.height+e.movementY, yMax:canvas.height});\n\t} //if e.movementY === 0, don't need to do anything\n\t\n\t\n\t\n\t//draw all squares - function found in utilities.js\n\tctx.fillStyle = \"black\";\n\tdrawData(minX,minY);\n\t\n}",
"_update_slider () {\n let x = this.clock / TIMER_MAX_DURATION;\n let y = (Math.log(x * (Math.pow(2, 10) - 1) +1)) / Math.log(2) / 10;\n\n this.slider.value = y;\n if (this.fullscreen.is_open) this.fullscreen.slider.value = y;\n }",
"_updatePosition() {\n if (this.stopped) {\n return;\n }\n const now = Date.now();\n const timePassed = (now - this.lastUpdate) / 1000; // in seconds\n this.lastUpdate = now;\n this.x += (this.increase * timePassed);\n if (this.x > 505) {\n this.x = -101;\n }\n }",
"function startPositionChange( slider )\n{\n\tslider.setAttribute(\"changing\",\"true\");\n\tplayer.startPositionChange();\n\tif( player.player.track ){\n\t\ttrackDuration = player.player.track.getDuration();\n\t\tslider.setAttribute(\"onmousemove\",\"onPositionChange(this);\");\n\t}\n}",
"function drive_left() {\n\tcurrent_loc = (prev_loc - img_width);\n\tif (current_loc > 0) {\n\t\tcurrent_loc = current_loc * -1;\n\t}\n\tchange_bg_x(current_loc);\n\tprev_loc = current_loc;\n\tshould_change = false;\n}",
"function updateAnimationFrames() {\n\tdragon1 = document.getElementById('dragon1');\n\tdragon2 = document.getElementById('dragon2');\n\tdragon1.innerHTML = \"<img src='img/d1\" + state1 + x + \".svg'/>\";\n\tdragon2.innerHTML = \"<img src='img/d2\" + state2 + x + \".svg'/>\";\n\tif (r == false && x < 9) {\n\t\tx++;\n\t}\n\tif (r == true && x >= 0) {\n\t\tx--;\n\t}\n\tif (x == 9 ) {\n\t\tr = true;\n\t}\n\tif (x == 0) {\n\t\tr = false;\n\t}\n}",
"function updatePointerState(ev,pointer){var point=getEventPoint(ev);var x=pointer.x=point.pageX;var y=pointer.y=point.pageY;pointer.distanceX=x-pointer.startX;pointer.distanceY=y-pointer.startY;pointer.distance=Math.sqrt(pointer.distanceX*pointer.distanceX+pointer.distanceY*pointer.distanceY);pointer.directionX=pointer.distanceX>0?'right':pointer.distanceX<0?'left':'';pointer.directionY=pointer.distanceY>0?'down':pointer.distanceY<0?'up':'';pointer.duration=+Date.now()-pointer.startTime;pointer.velocityX=pointer.distanceX/pointer.duration;pointer.velocityY=pointer.distanceY/pointer.duration;}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates the span element that holds the total amount to pay for the activities. | function createTotalSpan()
{
const span = createAppendElement(activitesFieldset, 'span', 'id', 'subtotal');
span.style.display = 'none';
} | [
"function createTotal() {\n var total = document.createElement(\"label\");\n total.innerHTML = \"Total: $0\";\n total.setAttribute(\"id\",\"total\");\n total.style.fontSize =\"1.2em\";\n total.style.fontWeight =\"400\";\n\n document.getElementsByClassName(\"activities\")[0].appendChild(total);\n document.getElementById(\"total\").classList.add(\"is-hidden\");\n }",
"function displayTotalDollars() {\n let totalCostDiv = document.createElement('Div');\n let totalCostText = document.createTextNode('Total : $');\n totalCostDiv.appendChild(totalCostText);\n totalCostDiv.id = 'activityTotalCost';\n registerForActivities.parentNode.insertBefore(totalCostDiv, registerForActivities.nextSibling);\n}",
"function createTotalProductAmountNode() {\n var div = document.createElement(\"div\")\n div.setAttribute(\"class\", \"totalProductAmount\")\n var span = document.createElement(\"span\")\n span.appendChild(document.createTextNode(\"$0.00\"))\n div.appendChild(span)\n return div\n}",
"function createIndividualPrice(){\n // create wrapper with proper classes\n var priceWrapper = createDivWrapper(\"item-total-wrapper inner-product-wrapper\");\n\n // create spans\n var dollarSignSpan = createSpan(\"dollar-symbol\", \"$\");\n var initialAmount = createSpan(\"total-individual-price\");\n initialAmount.innerHTML = \"0.00\";\n\n // insert spans into wrapper\n priceWrapper.appendChild(dollarSignSpan);\n priceWrapper.appendChild(initialAmount);\n\n // return individual price node\n return priceWrapper;\n}",
"function createHTMLTotalPrice(){\n const totalPrice = getBasketPrice();\n const totalPriceHTML = document.createElement(\"div\");\n totalPriceHTML.innerHTML = \"<div class='card-text'>\" + totalPrice + \"€\" + \"</div>\"\n return totalPriceHTML;\n}",
"function calculateAndSetTotalSumm() {\n let totalPriceSpan = document.querySelector(\"span.totalPrice\");\n totalPriceSpan.innerText = calculateTotalSummInCart();\n}",
"function updateCost(amount) {\n activityCost += amount;\n document.getElementById(\"total\").innerHTML = \"Amount due: $\" + activityCost;\n}",
"function totalCost (totalText) {\n $('.total').remove();\n $('.activities').append(totalText);\n}",
"function addProdperRess(production)\r\n{\r\n var resscost = collectionToArray($$(\"#contract .showCosts\", true).getElementsByTagName(\"span\"));\r\n\r\n var einheit = 0;\r\n for (var x = 0; x < resscost.length - 2; x++)\r\n {\r\n einheit += parseInt(resscost[x].textContent);\r\n }\r\n einheit = einheit / 4;\r\n if (einheit > 10000) einheit = 10000;\r\n else if (einheit > 1000) einheit = 1000;\r\n else if (einheit > 100) einheit = 100;\r\n else einheit = 10;\r\n \r\n var newSpan = document.createElement(\"span\");\r\n newSpan.className = \"none\";\r\n newSpan.textContent = \" (Ress per Production)\";\r\n $$(\"#contract .contractText\", true).appendChild(newSpan);\r\n\r\n for (var x = 0; x < resscost.length - 2; x++)\r\n {\r\n var newSpan = document.createElement(\"span\");\r\n newSpan.className = \"none\";\r\n newSpan.textContent = \"(\" + (parseInt(resscost[x].textContent) / production ).toFixed(1) + \")\";\r\n resscost[x].appendChild(newSpan);\r\n }\r\n var newSpan = document.createElement(\"span\");\r\n newSpan.className = \"none\";\r\n newSpan.textContent = \"(\" + (parseInt(resscost[4].textContent) / production).toFixed(1) + \")\";\r\n resscost[4].appendChild(newSpan);\r\n \r\n}",
"function pricingDiv (total) {\n let pricingDivHtml = '';\n pricingDivHtml = document.createElement('div');\n pricingDivHtml.id = 'totalPrice';\n let pricingDivHtmlSpan = document.createElement('strong');\n pricingDivHtmlSpan.id = 'totalPriceAmount';\n pricingDivHtml.appendChild(pricingDivHtmlSpan);\n pricingDivHtmlSpan.textContent = 'Total: $'+total; \n \n if(total > 0) {\n if (!document.getElementById('totalPrice')) { \n activitiesFieldset.appendChild(pricingDivHtml);\n } else {\n document.getElementById('totalPriceAmount').textContent = 'Total: $'+total; \n }\n } else {\n activitiesFieldset.removeChild(document.getElementById('totalPrice'));\n }\n}",
"function updateSpanText(newAmount, id) {\n document.getElementById(id).innerText = parseFloat(document.getElementById(id).innerText) + newAmount;\n}",
"function addExpenceToTotal() {\n // Read value from inputAmount\n const textAmount = inputElement.value\n\n // Read value from inputDesc\n const textDesc = inputDescEl.value\n \n // Convert it to number\n const inputAmount = parseInt(textAmount)\n\n // Initializing expense\n const expense = {}\n expense.description = textDesc\n expense.amount = inputAmount\n expense.moment = new Date()\n\n // Add that value to totalExpense\n totalExpense = totalExpense + inputAmount\n // console.log(\"Your total expense\",totalExpense)\n\n // Adding expense to allExpense\n allExpense.push(expense)\n // console.table(allExpense)\n\n // Set the headingTotal element equal to totalExpense\n headingEl.textContent = `Total Expense: ${totalExpense}`\n \n // To renderList to Document\n renderList(allExpense)\n\n // Reset the inputElement to empty\n inputDescEl.value = \"\"\n inputElement.value = \"\"\n}",
"function pmtAmt() {\n totalDue.className = \"\";\n var total = 0; \n for(var i = 0; i < activities.children.length; i++){\n if(activities.children[i].nodeName == \"LABEL\"){\n if(activities.children[i].childNodes[0].checked){\n var splitOne = activities.children[i].textContent.split(\"$\");\n var amount = parseFloat(splitOne[1],10);\n total+=amount; \n }\n }\n }\n //Sets the amount and field styling\n totalDue.placeholder = \"Total Due: $\"+total;\n if(amount > 0){\n totalDue.className = \"total\";\n }\n}",
"function appendPrice(total) {\n if (document.getElementById(\"appendPrice\")) {\n document.getElementById(\"appendPrice\").textContent = \"Total cost of selected activities: $\" + total;\n }\n else {\n const price = document.createElement('legend');\n price.textContent = \"Total cost of selected activities: $\" + total;\n price.id = \"appendPrice\"\n schedule.appendChild(price);\n }\n}",
"function addSpentText(pnode,total,income,transacts) {\n var x = document.createElement('p');\n pnode.parentNode.appendChild(x);\n\n var link=document.createElement('a');\n x = document.createTextNode('Total spent: '+makeThousands(String(total))+' Meat ');\n link.appendChild(x);\n link.setAttribute(\"title\", 'over '+transacts+' transaction'+((transacts==1)? '': 's'));\n pnode.parentNode.appendChild(link);\n var link=document.createElement('a');\n link.addEventListener(\"click\", resetSpent, true);\n link.setAttribute(\"total\", total);\n link.setAttribute(\"title\", 'wipe history and set spent amount');\n x = document.createTextNode('[reset]');\n link.appendChild(x);\n pnode.parentNode.appendChild(link);\n\n x = document.createTextNode(' ');\n pnode.parentNode.appendChild(x);\n link=document.createElement('a');\n link.addEventListener(\"click\", addSpent, true);\n link.setAttribute(\"title\", 'add an additional expense');\n x = document.createTextNode('[add]');\n link.appendChild(x);\n pnode.parentNode.appendChild(link);\n\n x = document.createTextNode(' ');\n pnode.parentNode.appendChild(x);\n link=document.createElement('a');\n link.addEventListener(\"click\", removeSpent, true);\n link.setAttribute(\"title\", 'remove the last added expense');\n x = document.createTextNode('[remove]');\n link.appendChild(x);\n pnode.parentNode.appendChild(link);\n\n //figure out profit\n var profit = income-total;\n // figure out ratio\n var ratio = (total==0) ? 0 : profit*100/total;\n if (ratio==0)\n ratio=' Meat';\n else\n ratio=' Meat ('+ratio.toFixed(1)+'%)';\n\n x = document.createElement('p');\n pnode.parentNode.appendChild(x);\n x = document.createTextNode('Profit: ');\n pnode.parentNode.appendChild(x);\n\n x = document.createElement('b');\n if (profit<0) {\n profit=makeThousands(String(-profit));\n x.appendChild(document.createTextNode('-'+profit+ratio));\n var y = document.createElement('font');\n y.setAttribute('color','red');\n y.appendChild(x);\n x=y;\n } else {\n profit=makeThousands(String(profit));\n x.appendChild(document.createTextNode(profit+ratio));\n }\n pnode.parentNode.appendChild(x);\n}",
"function updateActivityCost(activity) {\n $('.activities').append('<span id=\"total-cost\"></span>')\n if (activity.attr('name') != 'all') {\n if (activity.is(':checked')) {\n totalCost += 100;\n } else {\n totalCost -= 100;\n }\n } else if (activity.attr('name') === 'all') {\n if (activity.is(':checked')) {\n totalCost += 200;\n } else {\n totalCost -= 200;\n }\n }\n return totalCost\n}",
"function totalTicketAmount(){\n const subTotalAmount = TicketName('firstClass') * 150 + TicketName('economy') * 100;\n document.getElementById('subtotal').innerText ='$' + subTotalAmount;\n const totalTaxAmount = Math.round(subTotalAmount * 0.1);\n document.getElementById('tax-amount').innerText ='$' + totalTaxAmount;\n const totalBookingCost = subTotalAmount + totalTaxAmount;\n document.getElementById('total-cost').innerText ='$' + totalBookingCost;\n}",
"function appendTotalCost() {\n if (!$(\".activities\").find('#totalCost').length) {\n $('.activities').append(totalCostText);\n }\n }",
"function addBudgetToDom(budget) {\n\n // add budget\n const div = document.querySelector('#total')\n div.innerHTML = budget\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate config from bindings / istanbul ignore next: not easy to test | function makeConfig(binding) {
var config = {};
// If Argument, assume element ID
if (binding.arg) {
// Element ID specified as arg. We must pre-pend #
config.element = '#' + binding.arg;
}
// Process modifiers
Object(__WEBPACK_IMPORTED_MODULE_1__utils_object__["e" /* keys */])(binding.modifiers).forEach(function (mod) {
if (/^\d+$/.test(mod)) {
// Offest value
config.offset = parseInt(mod, 10);
} else if (/^(auto|position|offset)$/.test(mod)) {
// Offset method
config.method = mod;
}
});
// Process value
if (typeof binding.value === 'string') {
// Value is a CSS ID or selector
config.element = binding.value;
} else if (typeof binding.value === 'number') {
// Value is offset
config.offset = Math.round(binding.value);
} else if (_typeof(binding.value) === 'object') {
// Value is config object
// Filter the object based on our supported config options
Object(__WEBPACK_IMPORTED_MODULE_1__utils_object__["e" /* keys */])(binding.value).filter(function (k) {
return Boolean(__WEBPACK_IMPORTED_MODULE_0__scrollspy_class__["a" /* default */].DefaultType[k]);
}).forEach(function (k) {
config[k] = binding.value[k];
});
}
return config;
} | [
"function makeConfig(binding) {\n var config = {};\n\n // If Argument, assume element ID\n if (binding.arg) {\n // Element ID specified as arg. We must pre-pend #\n config.element = '#' + binding.arg;\n }\n\n // Process modifiers\n __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_object__[\"b\" /* keys */])(binding.modifiers).forEach(function (mod) {\n if (/^\\d+$/.test(mod)) {\n // Offest value\n config.offset = parseInt(mod, 10);\n } else if (/^(auto|position|offset)$/.test(mod)) {\n // Offset method\n config.method = mod;\n }\n });\n\n // Process value\n if (typeof binding.value === 'string') {\n // Value is a CSS ID or selector\n config.element = binding.value;\n } else if (typeof binding.value === 'number') {\n // Value is offset\n config.offset = Math.round(binding.value);\n } else if (_typeof(binding.value) === 'object') {\n // Value is config object\n // Filter the object based on our supported config options\n __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__utils_object__[\"b\" /* keys */])(binding.value).filter(function (k) {\n return Boolean(__WEBPACK_IMPORTED_MODULE_0__scrollspy_class__[\"a\" /* default */].DefaultType[k]);\n }).forEach(function (k) {\n config[k] = binding.value[k];\n });\n }\n\n return config;\n}",
"function makeConfig(binding) {\n var config = {};\n\n // If Argument, assume element ID\n if (binding.arg) {\n // Element ID specified as arg. We must pre-pend #\n config.element = '#' + binding.arg;\n }\n\n // Process modifiers\n Object(_utils_object__WEBPACK_IMPORTED_MODULE_1__[\"keys\"])(binding.modifiers).forEach(function (mod) {\n if (/^\\d+$/.test(mod)) {\n // Offest value\n config.offset = parseInt(mod, 10);\n } else if (/^(auto|position|offset)$/.test(mod)) {\n // Offset method\n config.method = mod;\n }\n });\n\n // Process value\n if (typeof binding.value === 'string') {\n // Value is a CSS ID or selector\n config.element = binding.value;\n } else if (typeof binding.value === 'number') {\n // Value is offset\n config.offset = Math.round(binding.value);\n } else if (_typeof(binding.value) === 'object') {\n // Value is config object\n // Filter the object based on our supported config options\n Object(_utils_object__WEBPACK_IMPORTED_MODULE_1__[\"keys\"])(binding.value).filter(function (k) {\n return Boolean(_scrollspy_class__WEBPACK_IMPORTED_MODULE_0__[\"default\"].DefaultType[k]);\n }).forEach(function (k) {\n config[k] = binding.value[k];\n });\n }\n\n return config;\n}",
"function makeConfig(dir) {\n return {\n input: dir + '/main.js',\n plugins: [\n json(),\n resolve(),\n ],\n output: {\n file: dir + '/main.min.js',\n format: 'iife',\n name: 'app',\n }\n };\n}",
"function parseBindings(bindings) {\n\n // We start out with a blank config\n var config = {};\n\n // Process bindings.value\n if (typeof bindings.value === 'string') {\n // Value is tooltip content (html optionally supported)\n config.title = bindings.value;\n } else if (typeof bindings.value === 'function') {\n // Title generator function\n config.title = bindings.value;\n } else if (_typeof(bindings.value) === 'object') {\n // Value is config object, so merge\n config = assign(bindings.value);\n }\n\n // If Argument, assume element ID of container element\n if (bindings.arg) {\n // Element ID specified as arg. We must prepend '#' to become a CSS selector\n config.container = '#' + bindings.arg;\n }\n\n // Process modifiers\n keys(bindings.modifiers).forEach(function (mod) {\n if (/^html$/.test(mod)) {\n // Title allows HTML\n config.html = true;\n } else if (/^nofade$/.test(mod)) {\n // no animation\n config.animation = false;\n } else if (/^(auto|top(left|right)?|bottom(left|right)?|left(top|bottom)?|right(top|bottom)?)$/.test(mod)) {\n // placement of tooltip\n config.placement = mod;\n } else if (/^d\\d+$/.test(mod)) {\n // delay value\n var delay = parseInt(mod.slice(1), 10) || 0;\n if (delay) {\n config.delay = delay;\n }\n } else if (/^o-?\\d+$/.test(mod)) {\n // offset value. Negative allowed\n var offset = parseInt(mod.slice(1), 10) || 0;\n if (offset) {\n config.offset = offset;\n }\n }\n });\n\n // Special handling of event trigger modifiers Trigger is a space separated list\n var selectedTriggers = {};\n\n // parse current config object trigger\n var triggers = typeof config.trigger === 'string' ? config.trigger.trim().split(/\\s+/) : [];\n triggers.forEach(function (trigger) {\n if (validTriggers[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n\n // Parse Modifiers for triggers\n keys(validTriggers).forEach(function (trigger) {\n if (bindings.modifiers[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n\n // Sanitize triggers\n config.trigger = keys(selectedTriggers).join(' ');\n if (config.trigger === 'blur') {\n // Blur by itself is useless, so convert it to 'focus'\n config.trigger = 'focus';\n }\n if (!config.trigger) {\n // remove trigger config\n delete config.trigger;\n }\n\n return config;\n}",
"bindPaths() {\n Object.entries(this.resolvePaths()).forEach(([key, value]) => {\n const name = this.stringHelper.singular(key);\n this.app.configurePaths({\n [name]: value\n });\n });\n Object.entries(this.resolveSourcePaths()).forEach(([key, value]) => {\n const name = this.stringHelper.singular(key);\n this.app.configurePaths({\n [`src.${name}`]: value\n });\n });\n }",
"get configs(){\n let configValues = null;\n let _configs = ReadGlob(`${this[rootDir]}/*-binder.config.js`);\n if (_configs && _configs.length > 0){\n if (_configs.length > 1){\n throw new Error(`Only one (1) model binder.config file, should be in ${this[rootDir]}`); \n } \n _configs.forEach((configSchema) => {\n configValues = require(configSchema).configs; \n });\n } else {\n const SEED_ROOT_DIR = `${this[rootDir]}/seeds`;\n configValues = {\n files: [{ include: \"./**/*.js\", ignore: IGNORE_FILES }],\n seed: {\n rootDir: SEED_ROOT_DIR,\n isSeed: true\n }\n };\n }\n return configValues;\n }",
"function genTsconfigJson() {\n return `{\n \"extends\": \"../../tsconfig.json\",\n \"compilerOptions\": {\n \"composite\": true,\n \"rootDir\": \"./\"\n },\n \"include\": [\"**/*.ts\"]\n }`;\n}",
"get composing() {\n return {\n composing() {\n const subGenerators = ['../server', '../client'];\n const context = { ...this.context };\n // forward the config obtained in the prompts\n utils.copyConfig(this, context, [constants.CONFIG_KEY_ENDPOINT, constants.CONFIG_KEY_SCHEMA_LOCATION]);\n subGenerators.forEach(gen =>\n this.composeWith(require.resolve(gen), {\n context,\n skipInstall: this.options.skipInstall,\n fromCli: true,\n force: this.options.force,\n debug: this.configOptions.isDebugEnabled\n })\n );\n }\n };\n }",
"function generateConfig() {\n var options = {\n \"$schema\": \"./node_modules/ng-translation-gen/ng-translation-gen-schema.json\"\n };\n if (args.input) {\n options.input = args.input;\n }\n if (args.output) {\n options.output = args.output;\n }\n if (args.mapping) {\n options.mapping = args.mapping;\n }\n if (args.separator) {\n options.separator = args.separator;\n }\n setDefaults(options, schema);\n\n var json = JSON.stringify(options, null, 2);\n fse.writeFileSync(CONFIG, json, { encoding: \"utf8\" });\n console.info(\"Wrote configuration file \" + CONFIG);\n}",
"function EndpointConfig() {}",
"function parseBindings$1(bindings) {\n\n // We start out with a blank config\n var config = {};\n\n // Process bindings.value\n if (typeof bindings.value === 'string') {\n // Value is popover content (html optionally supported)\n config.content = bindings.value;\n } else if (typeof bindings.value === 'function') {\n // Content generator function\n config.content = bindings.value;\n } else if (_typeof(bindings.value) === 'object') {\n // Value is config object, so merge\n config = assign(bindings.value);\n }\n\n // If Argument, assume element ID of container element\n if (bindings.arg) {\n // Element ID specified as arg. We must prepend '#' to become a CSS selector\n config.container = '#' + bindings.arg;\n }\n\n // Process modifiers\n keys(bindings.modifiers).forEach(function (mod) {\n if (/^html$/.test(mod)) {\n // Title allows HTML\n config.html = true;\n } else if (/^nofade$/.test(mod)) {\n // no animation\n config.animation = false;\n } else if (/^(auto|top(left|right)?|bottom(left|right)?|left(top|bottom)?|right(top|bottom)?)$/.test(mod)) {\n // placement of popover\n config.placement = mod;\n } else if (/^d\\d+$/.test(mod)) {\n // delay value\n var delay = parseInt(mod.slice(1), 10) || 0;\n if (delay) {\n config.delay = delay;\n }\n } else if (/^o-?\\d+$/.test(mod)) {\n // offset value (negative allowed)\n var offset = parseInt(mod.slice(1), 10) || 0;\n if (offset) {\n config.offset = offset;\n }\n }\n });\n\n // Special handling of event trigger modifiers Trigger is a space separated list\n var selectedTriggers = {};\n\n // parse current config object trigger\n var triggers = typeof config.trigger === 'string' ? config.trigger.trim().split(/\\s+/) : [];\n triggers.forEach(function (trigger) {\n if (validTriggers$1[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n\n // Parse Modifiers for triggers\n keys(validTriggers$1).forEach(function (trigger) {\n if (bindings.modifiers[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n\n // Sanitize triggers\n config.trigger = keys(selectedTriggers).join(' ');\n if (config.trigger === 'blur') {\n // Blur by itself is useless, so convert it to focus\n config.trigger = 'focus';\n }\n if (!config.trigger) {\n // remove trigger config\n delete config.trigger;\n }\n\n return config;\n}",
"createFromConnectionConfig(config) {\n ConnectionConfig.validate(config, { isEntityPathRequired: true });\n config.getManagementAudience = () => {\n return `${config.endpoint}${config.entityPath}/$management`;\n };\n config.getManagementAddress = () => {\n return `${config.entityPath}/$management`;\n };\n config.getSenderAudience = (partitionId) => {\n if (partitionId != undefined) {\n return `${config.endpoint}${config.entityPath}/Partitions/${partitionId}`;\n }\n else {\n return `${config.endpoint}${config.entityPath}`;\n }\n };\n config.getSenderAddress = (partitionId) => {\n if (partitionId != undefined) {\n return `${config.entityPath}/Partitions/${partitionId}`;\n }\n else {\n return `${config.entityPath}`;\n }\n };\n config.getReceiverAudience = (partitionId, consumergroup) => {\n if (!consumergroup)\n consumergroup = \"$default\";\n return (`${config.endpoint}${config.entityPath}/ConsumerGroups/${consumergroup}/` +\n `Partitions/${partitionId}`);\n };\n config.getReceiverAddress = (partitionId, consumergroup) => {\n if (!consumergroup)\n consumergroup = \"$default\";\n return `${config.entityPath}/ConsumerGroups/${consumergroup}/Partitions/${partitionId}`;\n };\n return config;\n }",
"static ParseBindingss(bindings) {\n // We start out with a basic config\n const NAME = 'BTooltip';\n let config = {\n delay: getComponentConfig(NAME, 'delay'),\n boundary: String(getComponentConfig(NAME, 'boundary')),\n boundaryPadding: parseInt(getComponentConfig(NAME, 'boundaryPadding'), 10) || 0\n };\n // Process bindings.value\n if (isString(bindings.value)) {\n // Value is tooltip content (html optionally supported)\n config.title = bindings.value;\n }\n else if (isFunction(bindings.value)) {\n // Title generator function\n config.title = bindings.value;\n }\n else if (isObject$1(bindings.value)) {\n // Value is config object, so merge\n config = Object.assign({}, config, bindings.value);\n }\n // If argument, assume element ID of container element\n if (bindings.arg) {\n // Element ID specified as arg\n // We must prepend '#' to become a CSS selector\n config.container = `#${bindings.arg}`;\n }\n // Process modifiers\n keys$1(bindings.modifiers).forEach(mod => {\n if (/^html$/.test(mod)) {\n // Title allows HTML\n config.html = true;\n }\n else if (/^nofade$/.test(mod)) {\n // No animation\n config.animation = false;\n }\n else if (/^(auto|top(left|right)?|bottom(left|right)?|left(top|bottom)?|right(top|bottom)?)$/.test(mod)) {\n // Placement of tooltip\n config.placement = mod;\n }\n else if (/^(window|viewport|scrollParent)$/.test(mod)) {\n // Boundary of tooltip\n config.boundary = mod;\n }\n else if (/^d\\d+$/.test(mod)) {\n // Delay value\n const delay = parseInt(mod.slice(1), 10) || 0;\n if (delay) {\n config.delay = delay;\n }\n }\n else if (/^o-?\\d+$/.test(mod)) {\n // Offset value, negative allowed\n const offset = parseInt(mod.slice(1), 10) || 0;\n if (offset) {\n config.offset = offset;\n }\n }\n });\n // Special handling of event trigger modifiers trigger is\n // a space separated list\n const selectedTriggers = {};\n // Parse current config object trigger\n let triggers = isString(config.trigger) ? config.trigger.trim().split(/\\s+/) : [];\n triggers.forEach(trigger => {\n if (validTriggers[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n // Parse modifiers for triggers\n keys$1(validTriggers).forEach(trigger => {\n if (bindings.modifiers[trigger]) {\n selectedTriggers[trigger] = true;\n }\n });\n // Sanitize triggers\n config.trigger = keys$1(selectedTriggers).join(' ');\n if (config.trigger === 'blur') {\n // Blur by itself is useless, so convert it to 'focus'\n config.trigger = 'focus';\n }\n if (!config.trigger) {\n // Remove trigger config\n delete config.trigger;\n }\n return config;\n }",
"function bind(gelf) {\n\n\tvar allConfig = {};\n\n\n\t/**\n\t * Get configuration for a named module.\n\t */\n\tfunction getConfig(name, merge) {\n\n\t\tvar extend = require('extend');\n\n\t\tvar configurators = (allConfig[name] || []).concat([\n\t\t\trequire('./config/from-system')(name),\n\t\t\trequire('./config/from-args')(name),\n\t\t\tmerge,\n\t\t]);\n\n\t\treturn configurators.reduce(function(config, current) {\n\n\t\t\tif (current == null) {\n\t\t\t\treturn config;\n\t\t\t}\n\n\t\t\tif (typeof current === 'function') {\n\t\t\t\tlet result = current.call(null, config, getConfig);\n\t\t\t\treturn (result != null) ? result : config;\n\t\t\t}\n\n\t\t\tif (typeof current === 'object') {\n\t\t\t\treturn (typeof config === 'object') ? extend(true, config, current) : current;\n\t\t\t}\n\n\t\t\treturn current;\n\n\t\t}, null);\n\n\t}\n\n\n\t/**\n\t * Get configuration for all modules.\n\t */\n\tfunction getAll() {\n\n\t\tvar out = {};\n\n\t\tObject.keys(allConfig).map(function(name) {\n\t\t\tout[name] = getConfig(name);\n\t\t});\n\n\t\treturn out;\n\n\t}\n\n\n\t/**\n\t * Set configuration for a named module.\n\t */\n\tfunction setConfig(name, config) {\n\n\t\tif (allConfig[name] == null) {\n\t\t\tallConfig[name] = [];\n\t\t}\n\n\t\tallConfig[name].push(config);\n\n\t}\n\n\n\t/**\n\t * Get configuration.\n\t */\n\tfunction get(name, config) {\n\n\t\t// Signature: config()\n\t\t// Get all config\n\t\tif (arguments.length === 0) {\n\t\t\treturn getAll();\n\t\t}\n\n\t\t// Signature: config(name)\n\t\t// Get config for the named module\n\t\tif (arguments.length === 1) {\n\t\t\treturn getConfig(name);\n\t\t}\n\n\t\t// Signature: config(name, config)\n\t\t// Set configuration data for a named module\n\t\tsetConfig(name, config);\n\n\t};\n\n\n\t// Public API\n\treturn get;\n\n}",
"buildPolymerConfig() {\n this.logger.info('Creating configuration for Polymer builder...');\n const cnf = {\n entrypoint: this.conf.importFile,\n fragments: [],\n sources: ['bower.json'],\n extraDependencies: this.conf.extraDependencies,\n lint: {\n rules: ['polymer-2']\n },\n builds: this.conf.builds,\n root: this.workingDir\n };\n this.projectConfig = cnf;\n }",
"function givenBindings() {\n bindings = [\n __1.Binding.bind('logger1').tag({ [phaseTagName]: 'log' }),\n __1.Binding.bind('auth1').tag({ [phaseTagName]: 'auth' }),\n __1.Binding.bind('auth2').tag({ [phaseTagName]: 'auth' }),\n __1.Binding.bind('logger2').tag({ [phaseTagName]: 'log' }),\n __1.Binding.bind('metrics').tag({ [phaseTagName]: 'metrics' }),\n __1.Binding.bind('rateLimit').tag({ [phaseTagName]: 'rateLimit' }),\n __1.Binding.bind('validator1'),\n __1.Binding.bind('validator2'),\n __1.Binding.bind('final').tag({ [phaseTagName]: FINAL }),\n ];\n }",
"bindConfigGrammar() {\n this.app.singleton('config.grammar', _ConfigGrammar.default);\n }",
"_scaffoldConfigFile() {\n const config_files = {\n rollup: \"rollup.config.js\",\n webpack: \"webpack.config.js\",\n babel: \"babel.config.js\"\n };\n // copy config file if the bundler exist\n if (config_files[this.bundler]) {\n return ncpp(\n path.resolve(\n `${this.templateLanguageFolder}/${this.bundler}/${this.linter}/${\n config_files[this.bundler]\n }`\n ),\n `${this.CURR_DIR}/${config_files[this.bundler]}`\n );\n }\n }",
"createConfigHelper() {\n\t\tthis.engine.views.helpers('config', (...parameters) => {\n\t\t\treturn this.app.make('config').get(...parameters);\n\t\t});\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
funcion que verifica si las animaciones estan corriendo o estan en pausa y redirige a otra funcion | function verificarEstadoAnimacion() {
if (animacionCirculoA.playState === "running") {
modificarEstadoAnimacion("running");
cambiarIcono("fa-pause-circle", "fa-play-circle");
} else {
modificarEstadoAnimacion("paused");
cambiarIcono("fa-play-circle", "fa-pause-circle");
}
} | [
"function CheckAnims(ent){\n if(ent.animationcontroller.GetAvailableAnimations().length > 0){\n EnableAnims();\n }else\n frame.DelayedExecute(1.0).Triggered.connect(EnableAnims);\n}",
"function checkAnimationComplete(){\t\n\tvar targetName = '';\n\tfor(n=0;n<animation_arr.length;n++){\n\t\tif($.pukiAnimation[animation_arr[n].name].visible){\n\t\t\ttargetName = animation_arr[n].name;\n\t\t}\n\t}\n\t\n\tvar _currentframe = $.pukiAnimation[targetName].currentFrame;\n\tvar _lastframes = $.pukiData[targetName].getAnimation($.pukiAnimation[targetName].currentAnimation).frames;\n\t_lastframes = _lastframes[_lastframes.length-1];\n\t\n\tif(_currentframe == _lastframes){\n\t\treturn true;\t\n\t}else{\n\t\treturn false;\t\n\t}\n}",
"function doneAnimation(){\n\tfor(var i = 0; i < 4; i++){\n\t\tfor(var j = 0; j < 4; j++){\n\t\t\tif(board[i][j] != null){\n\t\t\t\tif(board[i][j].cX != board[i][j].tX || board[i][j].cY != board[i][j].tY){\n\t\t\t\t\treturn false;\n\t\t\t\t}\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\treturn true;\n}",
"isAnimating() {\n return animationFrame > 1;\n }",
"function testAnimation(element) {\n if ( !element.hasClass('anim-running') &&\n Utils.isInView(element, {topoffset: offset})) {\n element\n .addClass('anim-running');\n\n setTimeout(function() {\n element\n .addClass('anim-done')\n .animo( { animation: animation, duration: 0.7} );\n }, delay);\n\n }\n }",
"function testAnimation(element) {\n if (!element.hasClass('anim-running') &&\n Utils.isInView(element, {topoffset: offset})) {\n element.addClass('anim-running');\n\n setTimeout(function () {\n element\n .addClass('anim-done')\n .animo({animation: animation, duration: 0.7});\n }, delay);\n }\n }",
"function CheckAnims(enti){\n var ent = scene.GetEntity(enti);\n this.enti=ent;\n if(ent.animationcontroller.GetAvailableAnimations().length > 0){\n EnableAnims();\n }else\n frame.DelayedExecute(1.0).Triggered.connect(EnableAnims);\n}",
"function testAnimation(element) {\n if ( !element.hasClass('anim-running') &&\n $.Utils.isInView(element, {topoffset: offset})) {\n element\n .addClass('anim-running');\n\n setTimeout(function() {\n element\n .addClass('anim-done')\n .animo( { animation: animation, duration: 0.7} );\n }, delay);\n\n }\n }",
"function animacionGiro(){\n limpiarCanvas();\n crearBordeNaranja();\n //console.log(nuevoAngulo);\n angulo = angulo - 0.01;\n girar();\n triangulo();\n}",
"function pokreni_animaciju () {\n\n\t// popunjavanje ready queue s vrijednostima do kraja simulacije\n\tpopuni_ready_queue();\n\t\n\n\tfor (jz=1; jz<=podaci_o_procesima.ukupan_broj_procesa; jz++) {\n\t\t//stvori novi timeline za svaki proces\n\t\twindow[\"anim\" + proba] = new TimelineMax({paused:true});\n\t\t\n\t\t\n\t\t\n\t\tfor (i=0; i<=podaci_o_procesima.broj_zahtjeva[jz]; i++) {\n\t\t\t// dohvacanje imena iz DOM za potrebne animacije\t\n\t\t\tdohvati_imena_elemenata();\n\t\t\t\n\t\t\t\n\t\t\t// OVO SE IZVRŠAVA AKO NEMA PRISTUPA MEMORIJI\n\t\t\tif (podaci_o_procesima.broj_zahtjeva[jz] == 0) {\n\t\t\t\tlabela = \"label\" + i;\n\t\t\t\tvrijeme_proc = podaci_o_procesima.procesi_vremena[jz][0];\n\t\t\t\tlijevo = \"+=\" + vrijeme_proc * 20 + \"px\";\n\t\t\t\twindow[\"anim\" + proba].to(selektor_proces, vrijeme_proc, {left: lijevo}, labela);\n\t\t\t\t// animacija loading kruga\n\t\t\t\twindow[\"anim\" + proba].to(selektor_gif, vrijeme_proc, {left: lijevo, visibility: \"visible\"}, labela);\n\t\t\t\t// animacija loading kruga - nestajanje\n\t\t\t\twindow[\"anim\" + proba].to(selektor_gif, 0, {visibility: \"hidden\"});\n\t\t\t\t// animacija crnog kruga\n\t\t\t\twindow[\"anim\" + proba].to (selektor_crni_krug, 0, {left: lijevo, visibility: 'visible', onComplete: nastavi});\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t// OVO SE IZVRŠAVA AKO IMA PRISTUPA MEMORIJI\n\t\t\telse {\n\t\t\t\tpovecani_i = i+1;\n\t\t\t\t\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t// stavljanje procesa u procesor\n\t\t\t\tvrijeme_proc = podaci_o_procesima.procesi_vremena[jz][povecani_i];\n\t\t\t\tlijevo = \"+=\" + vrijeme_proc * 20 + \"px\";\n\t\t\t\tlabela = \"label\" + i;\n\t\t\t\t// animacija loading kruga\n\t\t\t\twindow[\"anim\" + proba].to(selektor_gif, 0, {visibility: \"visible\"}, labela);\n\t\t\t\t// animacija procesa\n\t\t\t\twindow[\"anim\" + proba].to (selektor_proces, vrijeme_proc, {left: lijevo, onComplete: nastavi}, labela);\t\t\n\t\t\t\t// animacija loading kruga\n\t\t\t\twindow[\"anim\" + proba].to(selektor_gif, vrijeme_proc, {left: lijevo}, labela);\n\t\t\t\t//animacija narančastog kruga\n\t\t\t\twindow[\"anim\" + proba].to (selektor_nar_krug, 0, {left: lijevo}, labela);\n\t\t\t\t//animacija zelenog kruga\n\t\t\t\twindow[\"anim\" + proba].to (selektor_zel_krug, 0, {left: lijevo, visibility: \"hidden\"}, labela);\n\t\t\t\t//animacija crnog kruga\n\t\t\t\twindow[\"anim\" + proba].to (selektor_crni_krug, 0, {left: lijevo}, labela);\n\t\t\t\t\n\t\t\t\tif (i<podaci_o_procesima.broj_zahtjeva[jz]) {\n\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_crni_krug, 0, {visibility: 'visible'});\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tlabela1 = \"label1\" + i;\n\t\t\t\t\n\t\t\t\t// animacija loading kruga\n\t\t\t\twindow[\"anim\" + proba].to(selektor_gif, 0, {visibility: \"hidden\"}, labela1);\n\t\t\t\t\n\t\t\t\t// stavljanje procesa u waiting queue\n\t\t\t\t\n\t\t\t\tif (povecani_i<=podaci_o_procesima.broj_zahtjeva[jz]) {\n\t\t\t\t\t//animacija narančastog kruga\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_nar_krug, 0, {visibility: \"visible\"}, labela1);\n\t\t\t\t\t// animacija procesa\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_proces, 0.5, {left: \"+=20px\"}, labela1);\n\t\t\t\t\t//animacija narančastog kruga\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_nar_krug, 0.5, {left: \"+=20px\"}, labela1);\n\t\t\t\t\t// animacija loading kruga\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_gif, 0, {left: \"+=20px\"}, labela1);\n\t\t\t\t\t//animacija zelenog kruga\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_zel_krug, 0, {left: \"+=20px\"}, labela1);\n\t\t\t\t\t// animacija crnog kruga\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_crni_krug, 0, {left: \"+=20px\"}, labela1);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\twindow[\"anim\" + proba].to(selektor_gif, 0, {visibility: \"hidden\"});\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tlabela3 = \"label3\" + i;\n\t\t\t\t\n\t\t\t\t// stavljanje procesa u ready queue\n\t\t\t\tif (povecani_i<=podaci_o_procesima.broj_zahtjeva[jz]) {\t\n\t\t\t\t\t// ovo je za delay koji se koristi da simulira zadrzavanje procesa u waiting queue\n\t\t\t\t\tvrijeme_mem = podaci_o_procesima.procesi_memorija[jz][povecani_i];\n\t\t\t\t\t// animacija procesa\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_proces, 0.5, {left: \"+=20px\", delay: vrijeme_mem}, labela3);\n\t\t\t\t\t//animacija zelenog kruga\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_zel_krug, 0.5, {left: \"+=20px\", visibility: \"visible\", delay: vrijeme_mem}, labela3);\n\t\t\t\t\t// animacija loading kruga\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_gif, 0, {left: \"+=20px\"}, labela3);\n\t\t\t\t\t//animacija narančastog kruga\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_nar_krug, 0, {left: \"+=20px\", visibility: \"hidden\", delay: vrijeme_mem}, labela3);\n\t\t\t\t\t// animacija crnog kruga\n\t\t\t\t\twindow[\"anim\" + proba].to (selektor_crni_krug, 0, {left: \"+=20px\"}, labela3);\n\t\t\t\t}\t\t\n\t\t\t\t\n\t\t\t\twindow[\"anim\" + proba].call(pauseTL, [proba]);\n\t\t\t}\n\t\t}\n\tproba++;\n\t}\t\n\n\tanim1.play();\n}",
"function monAnimation(){\n // REGLAGE VITESSE\n setTimeout(function() {\n // MAJ COORDONNEES PANDA\n monObjetPanda.haut = $('#monPanda').position().top;\n monObjetPanda.droite = $('#monPanda').position().left + $('#monPanda').width();\n monObjetPanda.bas = $('#monPanda').position().top + $('#monPanda').height();\n monObjetPanda.gauche = $('#monPanda').position().left;\n // SI PANDA BOUSCULE TONNEAU DE DEPART : CREATION DUN NOUVEAU TONNEAU + DEPLACEMENT VERS LA GAUCHE\n if(monObjetPanda.droite > $('#tonneauDepart').position().left){\n tonneaux.nouveauTonneau(); // ligne pour désactiver la fabrication de tonneaux\n monObjetPanda.vitesseDeplacementHorizontal = -5;\n };\n // VERIFIE SI PANDA SORT DU JEU CHANGEMENT DEPLACEMENT VERS LA DROITE\n if (monObjetPanda.gauche < airDeJeux.gauche) {\n monObjetPanda.vitesseDeplacementHorizontal = 5;\n };\n // MOUVEMENT DU PANDA\n $('#monPanda').css({ width: monObjetPanda.frameDeplacement.containerLargeur[i] + 'px',\n height: monObjetPanda.frameDeplacement.containerHauteur[i] + 'px',\n left: monObjetPanda.gauche + monObjetPanda.vitesseDeplacementHorizontal + 'px' });\n // MOUVEMENT IMAGE PANDA\n $('#imagePanda').css({ top: monObjetPanda.frameDeplacement.imageHauteur[i] + 'px',\n left: monObjetPanda.frameDeplacement.imageLargeur[i] + 'px' });\n i++; // maj compteur frames\n if(i == monObjetPanda.frameDeplacement.containerLargeur.length) { // boucle frames\n i = 0; // RAZ compteur frame\n };\n // BOUCLE ANIMATION\n window.requestAnimationFrame(function() {\n monAnimation();\n });\n }, 1000/framesParSeconde);// fin setTimeout\n }",
"function checkAnimation() {\n\t\tvar $elem = $('.progressi');\n\n\t\t// If the animation has already been started\n\t\tif ($elem.hasClass('start')) return;\n\n\t\tif (isElementInViewport($elem)) {\n\t\t\t// Start the animation\n\t\t\tconsole.log('ciao');\n\t\t}\n\t}",
"function perder(){\n turnoJugador=false;\n sonido=false;\n //TODO: animacion al perder\n iluminar(0);\n iluminar(1);\n iluminar(2);\n iluminar(3);\n iluminar(2);\n iluminar(1);\n iluminar(0);\n sonido=true;\n reiniciar();\n}",
"function atualizaPosicoes()\n{\n if(contadorDeFrames % NUMERO_DE_FRAMES_ATE_ATUALIZAR == 0)\n {\n var coordXInicial, coordYInicial,\n coordXFinal, coordYFinal, flag, comeu;\n\n\n //\n //Movimento das peças brancas \n //\n if(contadorDeFramesLocal % 2 == 0)\n {\n\n //os castling nao precisamos das variaveis x e y, inicial e final\n flag = PGN[global_jogada][0];\n\n // Por isso testamos sempre pra saber se temos um castling\n if(flag < 7)\n {\n //transformamos as letras em coordenadas numericas e pegamos a flag, para sabermos qual peça\n // sera deslocada\n coordXInicial = PGN[global_jogada][1].charCodeAt(0) - \"a\".charCodeAt(0) + 1;\n coordYInicial = parseInt(PGN[global_jogada][1][1]);\n coordXFinal = PGN[global_jogada][1].charCodeAt(3) - \"a\".charCodeAt(0) + 1;\n coordYFinal = parseInt(PGN[global_jogada][1][4]);\n if(PGN[global_jogada][1][2] == \"-\") comeu = false;\n else \n {\n comeu = true;\n // DEPURACAO console.log(\"comeu: \" + comeu);\n }\n }\n\n // DEPURAÇAO console.log(\"x0, y0: \" + coordXInicial + \", \" + coordYInicial + \", x, y: \" + coordXFinal + \", \" + coordYFinal);\n\n //o parametro 0 e enviado para a funcao quando a movimentacao e de pecas brancas \n procuraPecaEAtualizaPosicao(coordXInicial, coordYInicial, coordXFinal, coordYFinal, flag, 0, comeu);\n\n contadorDeFramesLocal++;\n\n } else { //\n //Movimentacao das pecas pretas \n //\n\n //os castling nao precisamos das variaveis x e y, inicial e final\n flag = PGN[global_jogada][2];\n // Por isso testamos sempre pra saber se temos um castling\n if(flag < 7)\n {\n //transformamos as letras em coordenadas numericas e pegamos a flag, para sabermos qual peça\n // sera deslocada\n coordXInicial = PGN[global_jogada][3].charCodeAt(0) - \"a\".charCodeAt(0) + 1;\n coordYInicial = parseInt(PGN[global_jogada][3][1]);\n coordXFinal = PGN[global_jogada][3].charCodeAt(3) - \"a\".charCodeAt(0) + 1;\n coordYFinal = parseInt(PGN[global_jogada][3][4]);\n // DEPURACAO console.log(\" era pra ser um x: \" + PGN[global_jogada][3][2]);\n if(PGN[global_jogada][3][2] == \"-\") comeu = false;\n else \n {\n comeu = true;\n // DEPURACAO console.log(\"comeu: \" + comeu);\n }\n\n }\n\n // DEPURAÇAO console.log(\"x0, y0: \" + coordXInicial + \", \" + coordYInicial + \", x, y: \" + coordXFinal + \", \" + coordYFinal);\n\n //o parametro 1 e enviado para a funcao quando a movimentacao e de pecas pretas\n procuraPecaEAtualizaPosicao(coordXInicial, coordYInicial, coordXFinal, coordYFinal, flag, 1, comeu);\n\n contadorDeFramesLocal++;\n global_jogada++;\n\n }\n }\n\n}",
"isAnimationDone() {\n\t\treturn (this.animation.elapsedTime + this.game.clockTick) >= this.animation.totalTime;\n\t}",
"function animatePuki(frame){\n\tif(curAnimate!=frame){\n\t\tif(frame == 'scare'){\n\t\t\tplaySound('soundScare');\n\t\t}else if(frame == 'jump'){\n\t\t\tplaySound('soundJump');\t\n\t\t}\n\t\t\n\t\tif(frame == 'spacesuit'){\n\t\t\tplaySoundLoop('soundSpacesuit');\n\t\t}else{\n\t\t\tstopSoundLoop('soundSpacesuit');\t\n\t\t}\n\t\t\n\t\tif(frame == 'run'){\n\t\t\tplaySoundLoop('soundRun');\n\t\t}else{\n\t\t\tstopSoundLoop('soundRun');\n\t\t}\n\t\t\n\t\tif(frame == 'walk'){\n\t\t\tplaySoundLoop('soundWalk');\n\t\t}else{\n\t\t\tstopSoundLoop('soundWalk');\n\t\t}\n\t\t\n\t\tif(frame == 'sleep'){\n\t\t\tplaySoundLoop('soundSnork');\n\t\t}else{\n\t\t\tstopSoundLoop('soundSnork');\n\t\t}\n\t\tcurAnimate = frame;\n\t\t\n\t\tfor(n=0;n<animation_arr.length;n++){\n\t\t\t$.pukiAnimation[animation_arr[n].name].visible=false;\n\t\t}\n\t\t\n\t\tcurPukiAnimation = $.pukiAnimation[frame];\n\t\tcurPukiAnimation.visible=true;\n\t\tcurPukiAnimation.x = puki_arr.x;\n\t\tcurPukiAnimation.y = puki_arr.y;\n\t\tcurPukiAnimation.scaleX = puki_arr.scaleX;\n\t\tcurPukiAnimation.rotation = puki_arr.rotation;\n\t\tcurPukiAnimation.gotoAndPlay(frame);\n\t}\n}",
"inAnimationComplete(){}",
"readyToAnimate(){\n return this.animation === null;\n }",
"function animateIntro() {\n // Declarando las constantes para seleccion en el dom los elementos (La forma especifica de declarar es por la libreria, se declara con selectores de CSS)\n\n // Primera fila\n const boxTop = '.box-top .box';\n // Segunda fila\n const boxMiddle = '.box-middle .box';\n // Tercera fila\n const boxBottom = '.box-bottom .box';\n\n\n// Poner las constantes dentro de un array para poder hacer un loop\n let boxArray = [boxTop, boxMiddle, boxBottom];\n\n// Declaro un counter para poder incrementar la difencia en que se deben ejecutar las animaciones entre las filas\n let counter = 0;\n\n// El translate value es la distancia vertical hasta donde va la animacion\n let TranslateValue = -300;\n\n// Loop para cambiar los tiempos de cada pieza al hacer la animacion\n for (let pos in boxArray) {\n setTimeout(() => {\n anime({\n targets: boxArray[pos],\n opacity: 0,\n translateY: [\n {value: TranslateValue, duration: 500}\n ],\n rotate: {\n value: '1turn',\n easing: 'easeInOutSine'\n },\n backgroundColor: '#ffb840',\n borderRadius: ['0', '50px'],\n easing: 'easeInOutQuad',\n delay: function(el, i, l){return i * 400},\n autoplay:true\n });\n } , counter);\n\n counter += 1000;\n TranslateValue += -130;\n };\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load a specific version of a Planta into the studio | function loadVersion(versionId) {
// perform ajax request
$.ajax({
type: 'POST',
url: '/planta/' + plantaID + '/loadVersion',
crossDomain: true,
data: {'versao': versionId},
dataType: 'json',
async: true,
success: function (response) {
resetStudio();
cables = response['cables'];
floors = response['floors'];
size = response['size'];
insertNodes(response['nodes']);
insertLinks(response['links']);
insertTubes(response['tubes']);
updateMatrix();
scalePlanta(0);
restart();
panZoom.resetZoom();
},
error: function (response, status, error) {
logErrors(response, status, error, 'Ocorreu um erro ao carregar a versão do projeto.');
},
complete: function () {
closeModal();
}
});
} | [
"function loadRev() {\n // TODO: implement\n }",
"function load(){\n\tvar prog = programSelect.value;\n\tif(prog == \"Load from file\"){\n\t\tfilePicker.click(); //The filePicker has registered on change to call loadProgramFromDisk with the selected files\n\t}\n\telse if(prog == \"Custom\"){\n\t\tta.value = customProg[\"Custom\"];\n\t}\n\telse if(prog.startsWith(\"LOCAL:\")){\n\t\tloadProgramFromDisk(lastFile);\n\t}\n\telse{\n\t\tloadProgramFromPreset(prog+\".txt\");\n\t}\n}",
"function loadForEditing(version) {\n $rootScope.item = $scope.item;\n $rootScope.version = version;\n\n //$location.path(\"/contribute\");\n $location.path(\"/create\");\n }",
"function loadFormVersion( itcb ) {\n function onVersionLoaded( err, result ) {\n if ( err ) { return itcb( err ); }\n if ( 0 === result.length ) { return itcb( Y.doccirrus.errors.rest( 404, 'Form version not found', true ) ); }\n\n pack.template = result[0];\n itcb( null );\n }\n\n Y.doccirrus.mongodb.runDb( {\n 'user': user,\n 'model': 'formtemplate',\n 'query': { _id: formId },\n 'callback': onVersionLoaded\n } );\n }",
"loadVersion(options){\n let that = this;\n return Promise.resolve().then(function(){\n let versions = that._versions = that._versions || {};\n let info = versions[options.versionId];\n return info;\n });\n }",
"async function loadProject(name) {\n if (name in boardNames) {\n let location = 'parts/'+name+'.json';\n let partConfig = await loadJSON(location);\n return new Project(partConfig, {\n defaultHumanName: partConfig.humanName,\n code: examples[partConfig.example],\n parts: {\n main: {\n location: location,\n x: 0,\n y: 0,\n },\n },\n wires: [],\n });\n }\n return await new Promise((resolve, reject) => {\n let transaction = db.transaction(['projects'], 'readonly');\n transaction.objectStore('projects').get(name).onsuccess = async function(e) {\n if (e.target.result === undefined) {\n reject('loadProject: project does not exist in DB');\n }\n let data = e.target.result;\n if (data.target) {\n // Upgrade old data format.\n data.parts = {\n main: {\n location: 'parts/'+data.target+'.json',\n x: 0,\n y: 0,\n },\n };\n delete data.target;\n }\n if (!data.wires) {\n data.wires = [];\n }\n let mainPartConfig = await loadJSON(data.parts.main.location);\n if (!data.defaultHumanName) {\n // Upgrade old data format.\n data.defaultHumanName = mainPartConfig.humanName;\n }\n resolve(new Project(mainPartConfig, data));\n };\n });\n}",
"loadVPK() {\n this.vpkDir = new vpk(this.config.directory + '/pak01_dir.vpk');\n this.vpkDir.load();\n\n this.vpkFiles = this.vpkDir.files.filter((f) => f.startsWith('resource/flash/econ/stickers'));\n }",
"function loadProgramFromPreset(program){\n\tta.value = \"Loading...\";\n\tvar xhttp = new XMLHttpRequest();\n\t\n\txhttp.onreadystatechange = function() {\n\t\t//console.log(\"Response here, state: \" + this.readyState);\n\t\tif (this.readyState == 4 && this.status == 200) {\n\t\t\tta.value = this.responseText;\n\t\t\thandleCustomProgram(); //Saves locally the newly loaded data\n\t\t}\n\t\telse if(this.readyState == 4 && this.status == 404){\n\t\t\tta.value = \"Error loading from the preset folder!\";\n\t\t\tconsole.log(\"Error loading from the preset folder!\");\n\t\t}\n\t};\n\t\n\txhttp.onerror = function() {\n\t\tta.value = \"Error loading from the preset folder, no internet connection!\";\n\t\tconsole.log(\"Error loading from the preset folder, no internet connection!\");\n\t};\n\t\n\txhttp.open(\"GET\", programPath+program, true);\n\txhttp.send();\n}",
"function pickAsset(){\n var assetName =\"\";\n var assetGUID='';\n $(\"#js-assets_select_menu option:selected\").each(function (){\n assetGUID = $(this).val();\n assetName = $(this).text();\n });\n lapi.getActiveScene().addAssets([{name: assetName, datatype : assets[assetGUID],version_guid: assetGUID}]);\n }",
"function onloadPedagogieScene(scene){\n\t\n\tdocument.getElementById(\"PatchName\").textContent = \"Scène de \" + document.getElementById(\"nameTag\").value;\n\tdocument.getElementById(\"PatchName\").style.cssText = \"color:white\";\n\tdocument.body.style.background = \"url('\"+ window.baseImg + \"body-bkg.gif') 0 0 repeat\";\n\tsetGeneralDragAndDrop();\n\tchangeSceneToolTip(1);\n\tscene.unmuteScene();\n\t\n\t\n// TU PEUX TESTER LE RAPPEL DE LA SCENE ICI\n// \tvar json = '{\"1\":[{\"x\":\"174\"},{\"y\":\"164\"},{\"name\":\"bruitblanc\"},{\"code\":\"process = vgroup(\\\\\"bruitblanc\\\\\",environment{random = +(12345)~*(1103515245);\\\\nnoise = random/2147483647.0;\\\\n\\\\nprocess = noise * vslider(\\\\\"Volume[style:knob]\\\\\", 0, 0, 1, 0.1);\\\\n}.process);\"},{\"outputs\":[{\"dst\":\"2\"},{\"dst\":\"3\"}]},{\"params\":[{\"path\":\"/bruitblanc/Volume\"},{\"value\":\"0\"}]}],\"2\":[{\"x\":\"639\"},{\"y\":\"101\"},{\"name\":\"echo\"},{\"code\":\"process = vgroup(\\\\\"echo\\\\\",environment{declare name \\\\t\\\\t\\\\\"echo\\\\\";\\\\ndeclare version \\\\t\\\\\"1.0\\\\\";\\\\ndeclare author \\\\t\\\\t\\\\\"Grame\\\\\";\\\\ndeclare license \\\\t\\\\\"BSD\\\\\";\\\\ndeclare copyright \\\\t\\\\\"(c)GRAME 2006\\\\\";\\\\n//-----------------------------------------------\\\\n// \\\\t\\\\t\\\\t\\\\tA Simple Echo\\\\n//-----------------------------------------------\\\\n\\\\nimport(\\\\\"music.lib\\\\\");\\\\n\\\\nprocess = vgroup(\\\\\"echosimple\\\\\", echo1s);\\\\n}.process);\"},{\"inputs\":[{\"src\":\"1\"}]},{\"outputs\":[{\"dst\":\"0\"}]},{\"params\":[{\"path\":\"/echo/echosimple/echo__1000/feedback\"},{\"value\":\"81.4000015258789\"},{\"path\":\"/echo/echosimple/echo__1000/millisecond\"},{\"value\":\"464.29998779296875\"}]}],\"3\":[{\"x\":\"491\"},{\"y\":\"189\"},{\"name\":\"reverb\"},{\"code\":\"process = vgroup(\\\\\"reverb\\\\\",environment{//======================================================\\\\n//\\\\n// Freeverb\\\\n// Faster version using fixed delays (20% gain)\\\\n//\\\\n//======================================================\\\\n\\\\n// Constant Parameters\\\\n\\\\n//--------------------\\\\ndeclare name \\\\t\\\\t\\\\\"freeverb\\\\\";\\\\ndeclare version \\\\t\\\\\"1.0\\\\\";\\\\ndeclare author \\\\t\\\\t\\\\\"Grame\\\\\";\\\\n\\\\n\\\\n\\\\ndeclare license \\\\t\\\\\"BSD\\\\\";\\\\ndeclare copyright \\\\t\\\\\"(c)GRAME 2006\\\\\";\\\\n\\\\n\\\\nfixedgain = 0.015; //value of the gain of fxctrl\\\\nscalewet = 3.0;\\\\nscaledry = 2.0;\\\\nscaledamp = 0.4;\\\\nscaleroom = 0.28;\\\\noffsetroom = 0.7;\\\\ninitialroom = 0.5;\\\\ninitialdamp = 0.5;\\\\ninitialwet = 1.0/scalewet;\\\\ninitialdry = 0;\\\\ninitialwidth= 1.0;\\\\ninitialmode = 0.0;\\\\nfreezemode = 0.5;\\\\nstereospread= 23;\\\\nallpassfeed = 0.5; //feedback of the delays used in allpass filters\\\\n\\\\n\\\\n// Filter Parameters\\\\n//------------------\\\\n\\\\ncombtuningL1 = 1116;\\\\ncombtuningL2 = 1188;\\\\ncombtuningL3 = 1277;\\\\ncombtuningL4 = 1356;\\\\ncombtuningL5 = 1422;\\\\ncombtuningL6 = 1491;\\\\ncombtuningL7 = 1557;\\\\ncombtuningL8 = 1617;\\\\n\\\\nallpasstuningL1 = 556;\\\\nallpasstuningL2 = 441;\\\\nallpasstuningL3 = 341;\\\\nallpasstuningL4 = 225;\\\\n\\\\n\\\\n// Control Sliders\\\\n//--------------------\\\\n// Damp : filters the high frequencies of the echoes (especially active for great values of RoomSize)\\\\n// RoomSize : size of the reverberation room\\\\n// Dry : original signal\\\\n// Wet : reverberated signal\\\\n\\\\ndampSlider = hslider(\\\\\"Amortissement\\\\\",0.5, 0, 1, 0.025)*scaledamp;\\\\nroomsizeSlider = hslider(\\\\\"TailleDeLaPiece\\\\\", 0.5, 0, 1, 0.025)*scaleroom + offsetroom;\\\\nwetSlider = hslider(\\\\\"TauxReverberation\\\\\", 0.3333, 0, 1, 0.025);\\\\ncombfeed = roomsizeSlider;\\\\n\\\\n\\\\n// Comb and Allpass filters\\\\n//-------------------------\\\\n\\\\nallpass(dt,fb) = (_,_ <: (*(fb),_:+:@(dt)), -) ~ _ : (!,_);\\\\n\\\\ncomb(dt, fb, damp) = (+:@(dt)) ~ (*(1-damp) : (+ ~ *(damp)) : *(fb));\\\\n\\\\n\\\\n// Reverb components\\\\n//------------------\\\\n\\\\nmonoReverb(fb1, fb2, damp, spread)\\\\n = _ <: comb(combtuningL1+spread, fb1, damp),\\\\n comb(combtuningL2+spread, fb1, damp),\\\\n comb(combtuningL3+spread, fb1, damp),\\\\n comb(combtuningL4+spread, fb1, damp),\\\\n comb(combtuningL5+spread, fb1, damp),\\\\n comb(combtuningL6+spread, fb1, damp),\\\\n comb(combtuningL7+spread, fb1, damp),\\\\n comb(combtuningL8+spread, fb1, damp)\\\\n +>\\\\n allpass (allpasstuningL1+spread, fb2)\\\\n : allpass (allpasstuningL2+spread, fb2)\\\\n : allpass (allpasstuningL3+spread, fb2)\\\\n : allpass (allpasstuningL4+spread, fb2)\\\\n ;\\\\n\\\\nstereoReverb(fb1, fb2, damp, spread)\\\\n = + <: monoReverb(fb1, fb2, damp, 0), monoReverb(fb1, fb2, damp, spread);\\\\n\\\\n\\\\n// fxctrl : add an input gain and a wet-dry control to a stereo FX\\\\n//----------------------------------------------------------------\\\\n\\\\nfxctrl(g,w,Fx) = _,_ <: (*(g),*(g) : Fx : *(w),*(w)), *(1-w), *(1-w) +> _,_;\\\\n\\\\n// Freeverb\\\\n//---------\\\\n\\\\nfreeverb = vgroup(\\\\\"Reverb1\\\\\", fxctrl(fixedgain, wetSlider, stereoReverb(combfeed, allpassfeed, dampSlider, stereospread)));\\\\n\\\\nprocess = freeverb;\\\\n}.process);\"},{\"inputs\":[{\"src\":\"1\"}]},{\"outputs\":[{\"dst\":\"0\"}]},{\"params\":[{\"path\":\"/reverb/Reverb1/Amortissement\"},{\"value\":\"0.125\"},{\"path\":\"/reverb/Reverb1/TailleDeLaPiece\"},{\"value\":\"0.800000011920929\"},{\"path\":\"/reverb/Reverb1/TauxReverberation\"},{\"value\":\"0.7250000238418579\"}]}]}';\n// \trecallScene(json);\n}",
"function UILoadProgram (event) {\n let file = event.target.files[0];\n let reader = new FileReader();\n reader.onload = (event) => {\n const program = utility.removeArtefacts(event.target.result);\n engineState = engine.prepare(engine.initialize(), program);\n UIUpdate();\n };\n reader.readAsText(file);\n }",
"static async import(name) {\n\t\t// Load the configuration from the corresponding JSON file.\n\t\tlet response = await fetch('assets/levels/' + name + '.json');\n\n\t\t// Return a new level constructed from the configuration.\n\t\treturn new LevelView(await response.json());\n\t}",
"function loadVersionData() {\n let filePath = path.join(__dirname, \"../config/appversion.json\");\n let readdata = fs.readFileSync(filePath, { encoding: \"utf-8\" });\n exports.data = JSON.parse(readdata);\n Object.freeze(exports.data);\n}",
"function loadTool(name) {\n\t\tlog(LOG_TRACE, 'utils.loadTool', name);\n\t\treturn localforage.getItem(name);\n\t}",
"function loadPacker() {\n console.log(`Current File Name Is ${page}`)\n}",
"do_versions(datalib, blocks, version)\r\n {\r\n if (version <= 0.02) {\r\n //subsurf flag moved from view3d.editor to object\r\n console.log(\"---doing version 0.02->0.03 changes---\");\r\n for (var b of blocks) {\r\n if (b.type != \"SCRN\") continue;\r\n \r\n var screen = b.data;\r\n for (var scr of screen.areas) {\r\n console.log(\"-------->\", scr);\r\n if (!(scr.area instanceof View3DHandler)) continue;\r\n console.log(scr.area.use_subsurf);\r\n if (!scr.area.use_subsurf && !scr.area.editor.use_subsurf) continue;\r\n \r\n if (scr.area.use_subsurf)\r\n delete scr.area.use_subsurf;\r\n if (scr.area.editor.use_subsurf)\r\n delete scr.area.editor.use_subsurf;\r\n \r\n var sce = datalib.get_active(DataTypes.SCENE);\r\n var ob = sce.objects.active;\r\n \r\n if (ob == undefined && sce.objects.length > 0) {\r\n ob = sce.objects[0];\r\n }\r\n \r\n ob = datalib.get(ob[0]);\r\n ob.subsurf = true;\r\n }\r\n }\r\n }\r\n \r\n if (version <= 0.03) {\r\n //rebuild scene graph from scratch\r\n for (var sce of datalib.scenes) {\r\n sce.graph = undefined;\r\n }\r\n }\r\n \r\n console.log(\"VERSION FILE LOAD\", version);\r\n if (version < 0.041) {\r\n for (var sce of datalib.scenes) {\r\n //rebuild scene graph. . .\r\n sce.graph = undefined;\r\n }\r\n }\r\n }",
"function loadedPlan(planName,version,planData)\n {\n\n if (typeof planData == 'undefined')\n {\n planData = [];\n version = \"2\";\n }\n\n if (typeof version == 'undefined')\n {\n version = \"2\";\n }\n\n if (typeof mainEventHandler == 'function')\n {\n mainEventHandler('loaded-plan',{planName:planName, version:version, planData:planData});\n }\n\n }",
"function load()\n{\n dashcode.setupParts();\n doInit();\n}",
"function loadForEdition(params) {\n if (typeof(params) === undefined) {\n return \n }\n if (!(\"id\" in params)) {\n return\n }\n console.log(\"will load for \"+params[\"id\"]+\" edition\")\n currentEdition[\"id\"] = network.body.nodes[params[\"id\"]].id\n currentEdition[\"title\"] = network.body.nodes[params[\"id\"]].options.label\n // currentEdition[\"body\"] = fetch from server\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the two inputted coordinates are approximately equivalent | function coordinatesAreEquivalent(coord1, coord2) {
return (Math.abs(coord1 - coord2) < 0.000001);
} | [
"function coordinatesAreEquivalent(coord1, coord2) {\n return (Math.abs(coord1 - coord2) < 0.000001);\n }",
"function equalCoord (a, b) {\n return (a[0] == b[0] && a[1] == b[1]) ? true : false \n}",
"function isEqualCoord(p1, p2){\r\n return p1[0] == p2[0] && p1[1] == p1[1];\r\n}",
"equal() {\n const {x, y} = getPointArguments(arguments)\n return (this._x === x && this._y === y)\n }",
"function areEqual(pos1, pos2) {\n if (pos1 && pos1.length >= 2 && pos2 && pos2.length >= 2) {\n var offset = 1000000;\n return (Math.round(pos1[0] * offset) / offset) === (Math.round(pos2[0] * offset) / offset) &&\n (Math.round(pos1[1] * offset) / offset) === (Math.round(pos2[1] * offset) / offset);\n }\n return false;\n }",
"function equpos(pos1, pos2){\n\treturn pos1.y == pos2.y && pos1.x == pos2.x;\n}",
"function equalPoints(point1, point2) {\r\n\treturn (point1.x == point2.x) && (point1.y == point2.y)\r\n}",
"ifInBound(currentPos, coordinates1, coordinates2){\n \n //check for inverted squares\n if(coordinates1.latitude < coordinates2.latitude){\n //swap\n var temp = coordinates1\n coordinates1 = coordinates2\n coordinates2 = temp\n }\n else{\n\n }\n console.log(\"====ALL MY COORDINATES ==== \")\n console.log(currentPos)\n console.log(coordinates1)\n console.log(coordinates2)\n\n if((currentPos.coords.latitude <= coordinates1.latitude) && (currentPos.coords.latitude >= coordinates2.latitude)){\n console.log(\"latitude inbound\")\n if((currentPos.coords.longitude >= coordinates1.longitude) && (currentPos.coords.longitude <= coordinates2.longitude)){\n console.log(\"longitude inbound\")\n return true\n }\n }\n return false\n\n }",
"function sameCoordinates(space_a, space_b){\n console.log('>--Entering sameCoordinates()');\n if(space_a.x == space_b.x && space_a.y == space_b.y){\n ('<--Exiting sameCoordinates() = TRUE');\n return true;\n }\n\n console.log('<--Exiting sameCoordinates() = FALSE');\n return false;\n}",
"isPositionsEqual(first, second) {\n return first.x === second.x && first.y === second.y;\n }",
"function pointsEqual(p1, p2)\n{\n return (p1.x == p2.x && p1.z == p2.z);\n}",
"function samePoint(point1, point2, epsilon) {\r\n\treturn (game.math.fuzzyEqual(point1.x, point2.x, epsilon) && game.math.fuzzyEqual(point1.y, point2.y, epsilon));\r\n}",
"equivalent(point,epsilon) {return new M.XY(this.x,this.y).equivalent(point,epsilon);}",
"function equalsApproximately(a, b) {\n return Math.abs(a - b) <= exports.EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));\n}",
"equals(anotherCoord) {\n return this.x === anotherCoord.x && this.y === anotherCoord.y;\n }",
"function samePoint(point1, point2, epsilon) {\n\treturn (game.math.fuzzyEqual(point1.x, point2.x, epsilon) && game.math.fuzzyEqual(point1.y, point2.y, epsilon));\n}",
"function compareCoord(c1, c2) {\n // return c1.equals(c2);\n var dist = c1.distanceTo(c2);\n console.log(\"DISTANCE: \", dist);\n return dist < 50;\n}",
"equals(...args) \r\n {\r\n let a, b;\r\n if (args[0] instanceof Vector2D) \r\n {\r\n a = args[0].x || 0;\r\n b = args[0].y || 0;\r\n } \r\n else if (args[0] instanceof Array) \r\n {\r\n a = args[0][0] || 0;\r\n b = args[0][1] || 0;\r\n } \r\n else \r\n {\r\n a = args[0] || 0;\r\n b = args[1] || 0;\r\n }\r\n return this.x === a && this.y === b;\r\n }",
"function areCoordsEqual(offsetA, offsetB) {\n if (!offsetA && !offsetB) {\n return true;\n } else if (!offsetA || !offsetB) {\n return false;\n } else {\n return offsetA.x === offsetB.x && offsetA.y === offsetB.y;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The DraggableDrawable allows a drawable object to become draggable. This class provides additional functionality to a drawable object without subclassing it and is considered to be a much easier approach when new features are needed to an object without altering the existing base code. | function DraggableDrawable(drawable) {
/**
* A reference to this object.
*
* @typedef {DraggableDrawable}
* @private
*/
var self = this;
/**
* Initialize the DraggableDrawable.
*
* @param {cardmaker.Drawable} drawable The drawable to decorate.
*/
function init(drawable) {
// call parent constructor.
cardmaker.DrawableDecorator.call(self, drawable);
}
init(drawable);
} | [
"function Component_Draggable() {\n\n /**\n * Mouse/Pointer x coordinate\n * @property mx\n * @type number\n */\n this.mx = 0;\n\n /**\n * Mouse/Pointer y coordinate\n * @property my\n * @type number\n */\n this.my = 0;\n\n /**\n * Stepping in pixels.\n * @property stepSize\n * @type gs.Point\n */\n this.stepSize = {\n x: 0,\n y: 0\n };\n\n /**\n * Drag Area\n * @property rect\n * @type gs.Rect\n */\n this.rect = null;\n }",
"function Drag(dynlayer) {\n\tthis.element = dynlayer\n\tthis.obj = null\n\tthis.array = new Array()\n\tthis.active = false\n\tthis.offsetX = 0\n\tthis.offsetY = 0\n\tthis.zIndex = 0\n\tthis.resort = true\n\tthis.add = DragAdd\n\tthis.remove = DragRemove\n\tthis.setGrab = DragSetGrab\n\tthis.mouseDown = DragMouseDown\n\tthis.mouseMove = DragMouseMove\n\tthis.mouseUp = DragMouseUp\n}",
"function Draggable(gfx, options) {\n\n options = _.extend({\n threshold: DEFAULT_THRESHOLD,\n payload: {},\n }, options || {});\n\n\n function isThresholdReached(delta) {\n return Math.abs(delta.x) > options.threshold ||\n Math.abs(delta.y) > options.threshold;\n }\n\n var self = this;\n\n var externalEvents;\n\n var dragContext;\n\n function emit(name, event, raw) {\n\n var locals = _.extend({ dragContext: dragContext }, raw ? {} : options.payload || {});\n var dragEvent = _.extend({}, event, locals);\n\n self.emit(name, dragEvent);\n\n return dragEvent;\n }\n\n function dragOver(event) {\n var dragEvent = emit('dragover', event, true);\n\n if (!dragEvent.isDefaultPrevented()) {\n dragContext.hoverGfx = dragEvent.gfx;\n }\n }\n\n function dragOut(event) {\n if (dragContext.hoverGfx === event.gfx) {\n emit('dragout', event, true);\n }\n\n delete dragContext.hoverGfx;\n }\n\n function dragStart(x, y, event) {\n\n dragContext = _.extend({\n start: { x: x, y: y }\n }, options.payload);\n }\n\n function dragMove(dx, dy, x, y, event) {\n\n if (!dragContext) {\n return;\n }\n\n var graphics = dragContext.gfx;\n\n // update delta(x, y)\n _.extend(dragContext, {\n delta: { x: dx, y: dy }\n });\n\n // drag start\n if (!dragContext.dragging && isThresholdReached(dragContext.delta)) {\n\n if (externalEvents) {\n externalEvents.on('shape.hover', dragOver);\n externalEvents.on('shape.out', dragOut);\n }\n\n dragContext.dragging = true;\n\n emit('dragstart', event);\n }\n\n // drag move\n if (dragContext.dragging) {\n\n _.extend(dragContext, {\n delta: { x: dx, y: dy }\n });\n\n emit('drag', event);\n }\n }\n\n function dragEnd(x, y, event) {\n\n if (externalEvents) {\n externalEvents.off('shape.hover', dragOver);\n externalEvents.off('shape.out', dragOut);\n }\n\n if (dragContext && dragContext.dragging) {\n emit('dragend', event);\n }\n\n dragContext = null;\n }\n\n gfx.drag(dragMove, dragStart, dragEnd);\n\n /**\n * Detect drag over based on the given event stream\n * @param {EventEmitter} events\n */\n this.withDragOver = function(events) {\n externalEvents = events;\n return this;\n };\n\n /**\n * Cancel the drag operation, if it is in progress.\n */\n this.cancelDrag = function() {\n\n if (dragContext && dragContext.dragging) {\n emit('dragcanceled', {});\n }\n\n dragContext = null;\n };\n\n}",
"function Drawable() {\n\t//init method allows us to set the x & y position of object\n\tthis.init = function(x, y, width, height) {\n\t\t//Default variables\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t}\n\tthis.speed = 0;\n\tthis.canvasWidth = 0;\n\tthis.canvasHeight = 0;\n\n\t//Define abstract function to be implemented in child objects\n\tthis.draw = function() {\n\t};\n}",
"function Drawable(){\n\tthis.init = function(x, y){\n\t\tthis.x = x\n\t\tthis.y = y\n\t}\n\n\tthis.speed = 0\n\tthis.canvasWidth = 0\n\tthis.canvasHeight = 0\n\n\t//define abstract function to be implemented in child objects\n\tthis.draw = function(){ \n \n\t}\n}",
"function Drawable() {\n\tthis.init = function(x, y) {\n\t\t// Default variables\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\tthis.speed = 0;\n\tthis.canvasWidth = 0;\n\tthis.canvasHeight = 0;\n\t// Define abstract function to be implemented in child objects\n\tthis.draw = function() {\n\t};\n}",
"function Drawable() {\n this.init = function (x, y, width, height) {\n // Defualt variables\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n\n this.speed = 0;\n this.canvasWidth = 0;\n this.canvasHeight = 0;\n\n // Define abstract function to be implemented in child objects\n this.draw = function () {\n };\n this.move = function () {\n };\n}",
"function Drawable() {\n\tthis.init = function(x, y) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\tthis.canvasWidth = 0;\n\tthis.canvasHeight = 0;\n\n\tthis.draw = function() {};\n}",
"function Drawable() {\n this.init = function (x, y, width, height) {\n // Default variables\n this.x = x;\n this.y = y;\n this.width = width;\n this.height = height;\n }\n this.speed = 0;\n this.canvasWidth = 0;\n this.canvasHeight = 0;\n // Define abstract function to be implemented in child objects\n this.draw = function () {};\n}",
"function Drawable() {\r\n\tthis.init = function(x, y) {\r\n\t\t// Default variables\r\n\t\tthis.x = x;\r\n\t\tthis.y = y;\r\n\t}\r\n\tthis.speed = 0;\r\n\tthis.canvasWidth = 0;\r\n\tthis.canvasHeight = 0;\r\n\t// Define abstract function to be implemented in child objects\r\n\tthis.draw = function() {\r\n\t};\r\n}",
"function drag_able(obj){\n obj.draggable({\n cancel: 'a.ui-icon',// clicking an icon won't initiate dragging\n revert: 'invalid', // when not dropped, the item will revert back to its initial position\n containment: 'document',\n helper: 'clone',\n cursor: 'move'\n });\n }",
"function DragObject(name, x, y, width, height, eImage, move, type, offX, offY) {\n Entity.call(this, name, x, y, width, height, eImage, staticDraw, emptyFunc, emptyFunc, draggingInteract, draggingMove);\n this.tags.push(\"dragObject\");\n this.tags = $.merge(this.tags, type);\n\n this.offX = offX;\n this.offY = offY;\n }",
"function Drawable() {\n var bounds = new Rect(0, 0, 0, 0);\n var callback = null;\n\n /**\n * Draw in its bounds (set via setBounds) respecting optional effects such\n * as alpha (set via setAlpha) and color filter (set via setColorFilter).\n *\n * @method draw\n * @param {canvas} canvas The canvas to draw into.\n */\n this.draw = function(canvas) {\n };\n\n /**\n * Return the drawable's bounds Rect.\n *\n * @method getBounds\n * @return {Rect} The bounds of the drawable.\n */\n this.getBounds = function() {\n return bounds;\n };\n\n /**\n * Specify a bounding rectangle for the Drawable. This is where the drawable\n * will draw when its draw() method is called.\n *\n * @method setBounds\n */\n this.setBounds = function(l, t, r, b) {\n if (bounds.left != l || bounds.top != t || bounds.right != r || bounds.bottom != b) {\n bounds.set(l, t, r, b);\n }\n };\n\n /**\n * Bind a object to this Drawable. Required for clients\n * that want to support animated drawables.\n *\n * @method setCallback\n * @param {cb} cb The client's Callback implementation.\n */\n this.setCallback = function(cb) {\n callback = cb;\n };\n\n /**\n * Use the current implementation to have this Drawable\n * redrawn. Does nothing if there is no Callback attached to the\n * Drawable.\n *\n * @method invalidateSelf\n */\n this.invalidateSelf = function() {\n if (callback != null) {\n callback.invalidateDrawable(this);\n }\n };\n\n /**\n * Specify a set of states for the drawable. These are use-case specific,\n * so see the relevant documentation.\n *\n * @method setState\n * @param {int[]} s The new set of states to be displayed.\n */\n this.setState = function(s) {\n this.onStateChange(s);\n };\n\n /**\n * Override this in your subclass to change appearance if you recognize the\n * specified state.\n *\n * @method onStateChange\n * @param {int[]} s The new set of states to be displayed.\n * @return {boolean} Returns true if the state change has caused the appearance of\n * the Drawable to change (that is, it needs to be drawn), else false\n * if it looks the same and there is no need to redraw it since its\n * last state.\n */\n this.onStateChange = function(s) {\n };\n\n /**\n * Return the intrinsic width of the underlying drawable object.\n * @method getIntrinsicWidth\n * @return {int} Returns -1 if it has no intrinsic width, such as with a solid color.\n */\n this.getIntrinsicWidth = function() {\n return -1;\n };\n\n /**\n * Return the intrinsic height of the underlying drawable object.\n * @method getIntrinsicHeight\n * @return {int} Returns -1 if it has no intrinsic height, such as with a solid color.\n */\n this.getIntrinsicHeight = function() {\n return -1;\n };\n}",
"function _IG_Drag() {\n\n // \"public\" read-and-write properties\n\n this.surrogateOffsetX = 1;\n this.surrogateOffsetY = 1;\n\n this.leftMargin = 2;\n this.rightMargin = 2;\n this.topMargin = 2;\n this.bottomMargin = 2;\n\n this.xMapper = null;\n this.yMapper = null;\n\n // \"public\" read-only properties (external calls should not change these)\n\n this.surrogateInitialX = 0;\n this.surrogateInitialY = 0;\n this.surrogate = null;\n this.curSource = null;\n this.curTargetId = null;\n this.isDragging = false;\n this.hasDragged = false;\n this.isRightButton = false;\n\n // \"private\" properties (external calls should not even look at these)\n\n this.source_ = {}; // maps string ids to source objects.\n this.sourcePreviousOnMouseDown_ = {}; // maps string ids to source\n this.sourcePreviousStyleCursor_ = {}; // maps string ids to source\n this.target_ = {}; // maps string ids to target objects.\n this.targetPriority_ = {}; // maps string ids to target priorities.\n this.documentPreviousOnMouseMove = null;\n this.documentPreviousOnMouseUp = null;\n\n // other initialization lines\n\n this.makeCallbackFunctions();\n}",
"function DraggableManager(_ref) {\n var _this = this;\n\n var getBounds = _ref.getBounds,\n tag = _ref.tag,\n _ref$resetBoundsOnRes = _ref.resetBoundsOnResize,\n resetBoundsOnResize = _ref$resetBoundsOnRes === undefined ? true : _ref$resetBoundsOnRes,\n rest = _objectWithoutProperties(_ref, ['getBounds', 'tag', 'resetBoundsOnResize']);\n\n _classCallCheck(this, DraggableManager);\n\n this.resetBounds = function () {\n _this._bounds = undefined;\n };\n\n this._handleMinorMouseEvent = function (event) {\n var button = event.button,\n clientX = event.clientX,\n eventType = event.type;\n\n if (_this._isDragging || button !== LEFT_MOUSE_BUTTON) {\n return;\n }\n var type = '';\n var handler = void 0;\n if (eventType === 'mouseenter') {\n type = _updateTypes2.default.MOUSE_ENTER;\n handler = _this._onMouseEnter;\n } else if (eventType === 'mouseleave') {\n type = _updateTypes2.default.MOUSE_LEAVE;\n handler = _this._onMouseLeave;\n } else if (eventType === 'mousemove') {\n type = _updateTypes2.default.MOUSE_MOVE;\n handler = _this._onMouseMove;\n } else {\n throw new Error('invalid event type: ' + eventType);\n }\n if (!handler) {\n return;\n }\n\n var _getPosition2 = _this._getPosition(clientX),\n value = _getPosition2.value,\n x = _getPosition2.x;\n\n handler({\n event: event,\n type: type,\n value: value,\n x: x,\n manager: _this,\n tag: _this.tag\n });\n };\n\n this._handleDragEvent = function (event) {\n var button = event.button,\n clientX = event.clientX,\n eventType = event.type;\n\n var type = '';\n var handler = void 0;\n if (eventType === 'mousedown') {\n if (_this._isDragging || button !== LEFT_MOUSE_BUTTON) {\n return;\n }\n window.addEventListener('mousemove', _this._handleDragEvent);\n window.addEventListener('mouseup', _this._handleDragEvent);\n var style = (0, _get3.default)(document, 'body.style');\n if (style) {\n style.userSelect = 'none';\n }\n _this._isDragging = true;\n\n type = _updateTypes2.default.DRAG_START;\n handler = _this._onDragStart;\n } else if (eventType === 'mousemove') {\n if (!_this._isDragging) {\n return;\n }\n type = _updateTypes2.default.DRAG_MOVE;\n handler = _this._onDragMove;\n } else if (eventType === 'mouseup') {\n if (!_this._isDragging) {\n return;\n }\n _this._stopDragging();\n type = _updateTypes2.default.DRAG_END;\n handler = _this._onDragEnd;\n } else {\n throw new Error('invalid event type: ' + eventType);\n }\n if (!handler) {\n return;\n }\n\n var _getPosition3 = _this._getPosition(clientX),\n value = _getPosition3.value,\n x = _getPosition3.x;\n\n handler({\n event: event,\n type: type,\n value: value,\n x: x,\n manager: _this,\n tag: _this.tag\n });\n };\n\n this.handleMouseDown = this._handleDragEvent;\n this.handleMouseEnter = this._handleMinorMouseEvent;\n this.handleMouseMove = this._handleMinorMouseEvent;\n this.handleMouseLeave = this._handleMinorMouseEvent;\n\n this.getBounds = getBounds;\n this.tag = tag;\n this._isDragging = false;\n this._bounds = undefined;\n this._resetBoundsOnResize = Boolean(resetBoundsOnResize);\n if (this._resetBoundsOnResize) {\n window.addEventListener('resize', this.resetBounds);\n }\n this._onMouseEnter = rest.onMouseEnter;\n this._onMouseLeave = rest.onMouseLeave;\n this._onMouseMove = rest.onMouseMove;\n this._onDragStart = rest.onDragStart;\n this._onDragMove = rest.onDragMove;\n this._onDragEnd = rest.onDragEnd;\n }",
"dragObject(){\n this.x = mouseX;\n this.y = mouseY;\n }",
"function Drawable() {\n\n\t\tthis.clear = function(canvas) {\n\t\t\tcanvas.context.clearRect(0, 0, canvas.w, canvas.h);\n\t\t};\n\n\t\tthis.draw = function(canvas) {\n\t\t\tcanvas.drawImage(this.image, this.x, this.y, this.w, this.h);\n\t\t};\n\t}",
"function Draggable (element, options) {\n\n var me = this,\n start = util.bind(me.start, me),\n drag = util.bind(me.drag, me),\n stop = util.bind(me.stop, me);\n\n // sanity check\n if (!isElement(element)) {\n throw new TypeError('Draggable expects argument 0 to be an Element');\n }\n\n options = util.assign({}, defaults, options);\n\n // set instance properties\n util.assign(me, {\n\n // DOM element\n element: element,\n handle: (options.handle && isElement(options.handle))\n ? options.handle\n : element,\n\n // DOM event handlers\n handlers: {\n start: {\n mousedown: start,\n touchstart: start\n },\n move: {\n mousemove: drag,\n mouseup: stop,\n touchmove: drag,\n touchend: stop\n }\n },\n\n // options\n options: options\n\n });\n\n // initialize\n me.initialize();\n\n }",
"function Draggable(options) {\n var self = this;\n self.grid = null; // set upon calling Draggable.init\n self.options = $.extend({}, defaults, options);\n self.rowMoveManager = null; // Initialized in init\n // The current drag target\n self._folderTarget = null;\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.