query
stringlengths 9
34k
| document
stringlengths 8
5.39M
| negatives
sequencelengths 19
20
| metadata
dict |
---|---|---|---|
A convenience method for reducing by count. | function reduceCount() {
return reduce(crossfilter_reduceIncrement, crossfilter_reduceDecrement, crossfilter_zero);
} | [
"function mapFilterAndReduce(arr){\n return arr.map(val => val.firstName).filter(val => val.length < 5).reduce((acc,next) => \n\t{acc[next] = next.length;\n\treturn acc;}, {})\n}",
"function _multiCount(){\n //n is integer, no less than 0\n var mC=function(n){\n //n is integer, no less than 0\n if(+n<0){throw new Error('n<0');}\n mC.c[n]=(mC.c[n]!==undefined)?mC.c[n]+1:1;\n return mC.c;\n };\n mC.c=[];\n mC.reset=function(n){\n //n is integer, no less than 0\n if(+n<0){throw new Error('n<0');}\n mC.c[n]=0;\n return mC.c;\n };\n return mC;\n}",
"function reduce(wordAndOccurence){\n\tvar word; // used to store the word\n\tvar occurence = 0;// used to store the occurence of the word\n\t\n\tfor (var key in wordAndOccurence){ // we loop on \"wordAndOccurence\"\n\t\tword = key; // we know that it's only one word so we get it for later\n\t\t/*var numberOccurence = wordAndOccurence[key]; // we store the array of the occurences to be used in the following loop\n\t\tfor (var i=0, l=numberOccurence.length; i<l; i++){\n\t\t\toccurence += numberOccurence[i]; //we add every occurence into the final result\n\t\t}*/\n\t\t\n\t\t// after edit, the previous commented part was my vision of the 'normal' function, but now i didn't manage to get an array of occurences\n\t\t// the way i did it in shuffleAndSort, so basically i only have {word: occurence} and not {word: [occurence]}\n\t\toccurence += wordAndOccurence[key]; \n\t}\n\t\n\toutputWriter(word, occurence); //call the output writer to display the results\n}",
"function lenR(x, count = 0) {\n //return x.length\n if (!x[count]) return count;\n count++;\n return lenR(x, count);\n}",
"function reducer (normalized, old = Map(), n = 0) {\n const reduced = normalized.reduce(\n (acc, instance) => acc.mergeWith((prev, next) => prev + next, instance),\n old\n );\n const newCount = n + normalized.size;\n\n // Filter out zero-valued props\n const filtered = reduced.filter(val => val > 0);\n\n return List.of(filtered, newCount);\n}",
"function reducer2(a, e) {\n var summ = 0;\n if (typeof a == \"string\") { // this handles the initial case where the first element is used\n summ = a.length; // as the starting value.\n }\n else {\n summ = a;\n }\n return summ + countLetters(e);\n}",
"_reduceCart(cartArray) {\n console.log(cartArray)\n let reducedCart = []\n cartArray.forEach((currentItem) => {\n let thisItem = reducedCart.find(reducedCartItem => reducedCartItem.name === currentItem.name)\n if (!thisItem) {\n currentItem.quantity = 1;\n reducedCart.push(currentItem)\n } else {\n thisItem.quantity++\n }\n })\n return reducedCart\n }",
"function sortAndLimit(input){\n const result = input.sort((countA, countB) => countA.count < countB.count ? 1: -1).slice(0,5);\n return result;\n}",
"function getCombinations (collection, count) {\r\n if (count >= collection.length) {\r\n return [collection]\r\n }\r\n\r\n let all = []\r\n\r\n void function recursion (arr, size, result) {\r\n for (let i = 0; i < arr.length; i++) {\r\n let newResult = [...result, arr[i]]\r\n\r\n if (size === 1) {\r\n all.push(newResult)\r\n } else {\r\n let newArr = [...arr].slice(i + 1)\r\n recursion(newArr, size - 1, newResult)\r\n }\r\n }\r\n }(collection, count, [])\r\n\r\n return all\r\n}",
"function reduce(arr, fn, initial) {\n console.log(`\\narr ${arr}`);\n console.log(`\\nfn ${fn}`);\n console.log(`\\ninitial ${initial}`);\n\n // what is the end condition?\n\n // your reduce implementation to execute our solution to the previous problem\n // my version of reduce.js\n\n return arr.reduce(fn, initial);\n // fn: Function to use as the reduction step.\n // Like regular Array#reduce,\n // this function must be passed previousValue, currentValue, index\n // and the array we're iterating over.\n\n // will return an object containing the counts\n // for each word found in the array.\n}",
"static reduce(array, reducer, initialValue) {\n\t\tif (typeof reducer !== 'function') {\n\t\t\tthrow new Error('Second arg must be a reducer function')\n\t\t}\n\n\t\tconst numItems = array.length\n\n\t\treturn new P((resolve, reject) => {\n\t\t\tfunction processItem({ accum, index }) {\n\t\t\t\tconst item = array[index]\n\n\t\t\t\treducer(accum, item)\n\t\t\t\t\t.then(newResult => {\n\t\t\t\t\t\tif (index === numItems - 1) {\n\t\t\t\t\t\t\tresolve(newResult)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tprocessItem({ accum: newResult, index: index + 1 })\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.catch(error => {\n\t\t\t\t\t\treject(error)\n\t\t\t\t\t})\n\t\t\t}\n\n\t\t\tprocessItem({ accum: initialValue, index: 0 })\n\t\t})\n\t}",
"getCount(callback) {\n let count = {\n active: 0,\n completed: 0,\n total: 0\n }\n\n this.items.forEach(item => {\n if(item.completed) {\n count.completed++\n } else {\n count.active++\n }\n count.total++\n })\n\n if(typeof callback === 'function') {\n callback(count)\n }\n\n return count\n }",
"function decrementCount(key) {\n if (counts[key] < 2) {\n delete counts[key];\n } else {\n counts[key] -= 1;\n }\n }",
"function reductions(source, xf, initial) {\n var reduction = initial;\n\n return accumulatable(function accumulateReductions(next, initial) {\n // Define a `next` function for accumulation.\n function nextReduction(accumulated, item) {\n reduction = xf(reduction, item);\n\n return item === end ?\n next(accumulated, end) :\n // If item is not `end`, pass accumulated value to next along with\n // reduction created by `xf`.\n next(accumulated, reduction);\n }\n\n accumulate(source, nextReduction, initial);\n });\n}",
"function finalizeCount() {\n return 0;\n}",
"incrementCount() {\n _count.set(this, _count.get(this) + 1);\n _price.set(this, Number(_price.get(this)) + Number(_product.get(this).getPrice()));\n }",
"setResultCount (count = 0) {\n this.resultCount = count;\n }",
"function reduceShortlist(acc, crt) {\n if (crt.id.pubchem.length > 1) {\n acc.tmi.push(crt);\n return acc;\n };\n acc.req.push(crt.id.pubchem[0]);\n return acc;\n}",
"crotonTripsCounter(state) {\n var crotonTrips = 0;\n for (var i = 0; i < state.recordsList.length; i++) {\n if (state.recordsList[i].reservoir === \"Croton\") {\n crotonTrips++;\n }\n }\n return crotonTrips;\n }",
"countDecrease(item) {\n if (item.count <= 1) {\n this.msg2;\n }\n else {\n item.count = item.count - 1;\n this.isErrorMsg = false;\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert snap distance in pixels into buffer in degres, for searching around mouse It changes at each zoom change. | function computeBuffer() {
this._buffer = map.layerPointToLatLng(new L.Point(0,0)).lat -
map.layerPointToLatLng(new L.Point(this.options.snapDistance, 0)).lat;
} | [
"toPixels(arr){\n let scaled = [];\n arr.forEach(index =>\n scaled.push({\n origin: {x: index.origin.x/this.state.scale, y: index.origin.y/this.state.scale},\n dest: {x: index.destination.x/this.state.scale, y: index.destination.y/this.state.scale},\n dist: index.distance})\n );\n return scaled;\n }",
"snappingEdgeData(point) {\n // build a list of edges (in RWU) available for snapping\n // deep copy all vertices on the current story\n let snappableEdges = [...this.currentStoryGeometry.edges];\n\n // TODO: conditionally combine this list with edges from the next story down if it is visible\n if (this.previousStoryGeometry) {\n snappableEdges = snappableEdges.concat(this.previousStoryGeometry.edges.map(e => ({\n ...e,\n previous_story: true,\n })));\n }\n\n if (snappableEdges.length === 0) { return []; }\n\n // find the edge closest to the point being tested\n const distyEdges = _.map(\n snappableEdges, (edge) => {\n const\n aStoryGeometry = edge.previous_story ? this.previousStoryGeometry : this.currentStoryGeometry,\n // look up vertices associated with edges\n aV1 = geometryHelpers.vertexForId(edge.v1, aStoryGeometry),\n aV2 = geometryHelpers.vertexForId(edge.v2, aStoryGeometry),\n // project point being tested to each edge\n aProjection = projectionOfPointToLine(point, { p1: aV1, p2: aV2 }),\n\n // look up distance between projection and point being tested\n aDist = distanceBetweenPoints(aProjection, point);\n return {\n ...edge,\n projection: aProjection,\n dist: aDist,\n v1Coords: aV1,\n V2Coords: aV2,\n };\n });\n const nearestEdge = _.minBy(distyEdges, 'dist');\n\n // // look up vertices associated with nearest edge\n // const nearestEdgeStoryGeometry = nearestEdge.previous_story ? this.previousStoryGeometry : this.currentStoryGeometry;\n // const nearestEdgeV1 = geometryHelpers.vertexForId(nearestEdge.v1, nearestEdgeStoryGeometry);\n // const nearestEdgeV2 = geometryHelpers.vertexForId(nearestEdge.v2, nearestEdgeStoryGeometry);\n // // take the projection of the cursor to the edge\n // // check if the angle of the segment defined by the cursor and projection is < the angle snap tolerance\n // const snappableAngles = [-180, -90, 0, 90, 180];\n // // angle between projection and mouse (degrees)\n // const thetaDeg = Math.atan2(point.y - nearestEdge.projection.y, point.x - nearestEdge.projection.x)\n // * (180 / Math.PI);\n\n // // if the original projection is within the snap tolerance of one of the snapping angles\n // // adjust the projection so that it is exactly at the snap angle\n // // snap to -180, -90, 0, 90, 180\n // snappableAngles.some((angle) => {\n // // if the original projection is within the snap tolerance of one of the snapping angles\n // // adjust the projection so that it is exactly at the snap angle\n // if (Math.abs(thetaDeg - angle) < this.$store.getters['project/angleTolerance']) {\n // // infer a line defining the desired projection\n // var adjustedProjectionP1;\n // var adjustedProjectionP2;\n // if (angle === 180 || angle === 0 || angle === -180) {\n // adjustedProjectionP1 = { x: point.x - (2 * nearestEdge.dist), y: point.y }\n // adjustedProjectionP2 = { x: point.x + (2 * nearestEdge.dist), y: point.y }\n // } else if (angle === 90 || angle === -90) {\n // adjustedProjectionP1 = { x: point.x, y: point.y - (2 * nearestEdge.dist) }\n // adjustedProjectionP2 = { x: point.x, y: point.y + (2 * nearestEdge.dist) }\n // }\n // // adjust the projection to be the intersection of the desired projection line and the nearest edge\n // if (geometryHelpers.ptsAreCollinear(adjustedProjectionP1, nearestEdgeV1, adjustedProjectionP2)) {\n // projection = nearestEdgeV1;\n // } else if (geometryHelpers.ptsAreCollinear(adjustedProjectionP1, nearestEdgeV2, adjustedProjectionP2)) {\n // projection = nearestEdgeV2;\n // } else {\n // projection = geometryHelpers.intersectionOfLines(adjustedProjectionP1, adjustedProjectionP2, nearestEdgeV1, nearestEdgeV2);\n // }\n // return true;\n // }\n // return false;\n // });\n\n // return data for the edge if the projection is within the snap tolerance of the point\n if (nearestEdge.dist < this.$store.getters['project/snapTolerance']) {\n return [{\n snappingEdge: nearestEdge,\n dist: nearestEdge.dist,\n type: 'edge',\n // projection and snapping edge vertices translated into grid coordinates (to display snapping point and highlight edges)\n projection: nearestEdge.projection,\n v1GridCoords: nearestEdge.v1Coords,\n v2GridCoords: nearestEdge.V2Coords,\n x: nearestEdge.projection.x,\n y: nearestEdge.projection.y,\n }];\n }\n return [];\n }",
"function FindClippingScanner( ) { }",
"function measure_pinch() {\n var x0 = touches[0].x;\n var x1 = x0;\n var y0 = touches[0].y;\n var y1 = y0;\n\n for (var i = 1; i < touches.length; i++) {\n if (touches[i].x < x0) x0 = touches[i].x;\n if (touches[i].x > x1) x1 = touches[i].x;\n if (touches[i].y < y0) y0 = touches[i].y;\n if (touches[i].y > y1) y1 = touches[i].y;\n }\n\n return {\n 'distance': Math.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)),\n 'x': (x0 + x1) / 2,\n 'y': (y0 + y1) / 2\n };\n}",
"calculatePinchZoom() {\n let distance_1 = Math.sqrt(Math.pow(this.finger_1.start.x - this.finger_2.start.x, 2) + Math.pow(this.finger_1.start.y - this.finger_2.start.y, 2));\n\t\tlet distance_2 = Math.sqrt(Math.pow(this.finger_1.end.x - this.finger_2.end.x, 2) + Math.pow(this.finger_1.end.y - this.finger_2.end.y, 2));\n\t\tif (distance_1 && distance_2) {\n \t\t\tthis.ratio = (distance_2 / distance_1);\n \n \t\t\t\n \t\t\tlet new_scale = this.scale * this.ratio;\n\t\t \n\t\t if ((new_scale > this.scale && new_scale < this.settings.maxZoom) || (new_scale < this.scale && new_scale > this.settings.minZoom)) { \n \t\t\t\n\t \t\t\tlet focal_point = {\n\t \t\t\t\tx: (this.finger_1.start.x + this.finger_2.start.x) / 2, \n\t \t\t\t\ty: (this.finger_1.start.y + this.finger_2.start.y) / 2 \n\t \t\t\t};\n\t \t\t\t\n\t \t\t\tthis.translate(this.originX, this.originY)\n\t \t\t\t\n\t \t\t\tlet originx = focal_point.x/(new_scale) - focal_point.x/this.scale;\n\t \t\t\tlet originy = focal_point.y/(new_scale) - focal_point.y/this.scale;\n\t \t\t\t\n\t \t\t\tthis.originX -= originx;\n\t \t\t \tthis.originY -= originy;\n\t \t\t\tthis.context.scale(this.ratio, this.ratio);\n\t \t\t\t\n\t \t\t\tthis.translate(-this.originX, -this.originY)\n\t \t\t\t\n\t \t\t\tthis.scale = new_scale; // redraw the empty rectangle at proper scaled size to avoid multiple instances of the image on the canvas\n \t\t\t\n\t\t }\n\t\t}\n }",
"function buffer1(geometry) {\n return geometry.buffer(5000);\n}",
"function pixelDistance(lat1, lon1, lat2, lon2, zoom)\n{\n x1 = lonToX(lon1);\n y1 = latToY(lat1);\n\n x2 = lonToX(lon2);\n y2 = latToY(lat2);\n \n\tvar test =0;\n\n\ttest = Math.sqrt( Math.pow((x1-x2),2) + Math.pow((y1-y2),2)) >> (21 - zoom);\n\n\treturn test;\n}",
"function findDistances (img) {\n img.get = imgGet\n img.set = imgSet\n var view = new DataView(img.data.buffer)\n var nx = img.width\n var ny = img.height\n\n function distance (g, x, y, i) {\n return ((y - i) * (y - i) + g[i][x] * g[i][x])\n }\n\n function intersection (g, x, y0, y1) {\n return ((g[y0][x] * g[y0][x] - g[y1][x] * g[y1][x] + y0 * y0 - y1 * y1) / (2.0 * (y0 - y1)))\n }\n //\n // allocate arrays\n //\n var g = []\n for (var y = 0; y < ny; ++y) { g[y] = new Uint32Array(nx) }\n var h = []\n for (var y = 0; y < ny; ++y) { h[y] = new Uint32Array(nx) }\n var distances = []\n for (var y = 0; y < ny; ++y) { distances[y] = new Uint32Array(nx) }\n var starts = new Uint32Array(ny)\n var minimums = new Uint32Array(ny)\n //\n // column scan\n //\n for (var y = 0; y < ny; ++y) {\n //\n // right pass\n //\n var closest = -nx\n for (var x = 0; x < nx; ++x) {\n if (img.get(y, x, STATE) & INTERIOR) {\n g[y][x] = 0\n closest = x\n } else { g[y][x] = (x - closest) }\n }\n //\n // left pass\n //\n closest = 2 * nx\n for (var x = (nx - 1); x >= 0; --x) {\n if (img.get(y, x, STATE) & INTERIOR) { closest = x } else {\n var d = (closest - x)\n if (d < g[y][x]) { g[y][x] = d }\n }\n }\n }\n //\n // row scan\n //\n for (var x = 0; x < nx; ++x) {\n var segment = 0\n starts[0] = 0\n minimums[0] = 0\n //\n // down\n //\n for (var y = 1; y < ny; ++y) {\n while ((segment >= 0) &&\n (distance(g, x, starts[segment], minimums[segment]) > distance(g, x, starts[segment], y))) { segment -= 1 }\n if (segment < 0) {\n segment = 0\n minimums[0] = y\n } else {\n newstart = 1 + intersection(g, x, minimums[segment], y)\n if (newstart < ny) {\n segment += 1\n minimums[segment] = y\n starts[segment] = newstart\n }\n }\n }\n //\n // up\n //\n for (var y = (ny - 1); y >= 0; --y) {\n var d = Math.sqrt(distance(g, x, y, minimums[segment]))\n view.setUint32((img.height - 1 - y) * 4 * img.width + x * 4, d)\n if (y === starts[segment]) { segment -= 1 }\n }\n }\n}",
"function DownSample4x (source : RenderTexture, dest : RenderTexture){\n var off : float = 1.0f;\n Graphics.BlitMultiTap (source, dest, material,\n new Vector2(-off, -off),\n new Vector2(-off, off),\n new Vector2( off, off),\n new Vector2( off, -off)\n );\n}",
"function convertScreenToGrid(x, y) {\n const a = (((x - gridX - offsetY) / zoom) / (tileWidth / 2)) / 2\n const b = (((y - gridY - offsetX) / zoom) / (tileHeight / 2)) / 2\n return { x: Math.floor(b - a), y: Math.floor(a + b) }\n}",
"findSnapTarget(gridPoint, options = {}) {\n const { edge_component: snapOnlyToEdges } = options;\n // translate grid point to real world units to check for snapping targets\n const rwuPoint = {\n x: this.gridToRWU(gridPoint.x, 'x'),\n y: this.gridToRWU(gridPoint.y, 'y'),\n };\n if (this.snapMode === 'grid-strict') {\n return this.strictSnapTargets(rwuPoint)[0];\n }\n\n if (this.snapMode === 'grid-verts-edges') {\n const realPoint = this.gridPointToRWU(gridPoint);\n const targets = [\n ...vertexSnapTargets(this.currentStoryGeometry.vertices, this.spacing, realPoint),\n ...this.snappingEdgeData(realPoint),\n ...gridSnapTargets(this.spacing, realPoint),\n ...this.polygonOriginPoint(),\n ].map(\n (target) => {\n const penaltyFactor = (\n target.type === 'edge' ? 1.4 : 1.0\n );\n return ({\n ...target,\n dist: penaltyFactor * distanceBetweenPoints(target, realPoint),\n dx: realPoint.x - target.x,\n dy: realPoint.y - target.y,\n });\n });\n\n const orderedTargets = _.orderBy(targets, ['dist', 'origin', 'type'], ['asc', 'asc', 'desc']);\n return orderedTargets[0] || {\n type: 'gridpoint',\n ...realPoint,\n };\n }\n // if snapping only to edges (placing edge components, return either the snapping edge or original point)\n if (snapOnlyToEdges) {\n const snappingEdge = this.snappingEdgeData(rwuPoint);\n return snappingEdge[0] || {\n type: 'gridpoint',\n ...rwuPoint,\n };\n }\n // if a snappable vertex exists, don't check for edges\n const snappingVertex = this.snappingVertexData(rwuPoint);\n if (snappingVertex) { return snappingVertex; }\n\n const snappingEdge = this.snappingEdgeData(rwuPoint);\n if (snappingEdge.length > 0) { return snappingEdge[0]; }\n\n // grid is active and no vertices or edges are within snapping range, calculate the closest grid point to snap to\n if (this.gridVisible) {\n // spacing between ticks in grid units\n const xTickSpacing = this.rwuToGrid(this.spacing + this.min_x, 'x'),\n // yTickSpacing = this.rwuToGrid(this.spacing + this.min_y, 'y');\n yTickSpacing = this.rwuToGrid(this.max_y - this.spacing, 'y'); // inverted y axis\n\n // round point RWU coordinates to nearest gridline, adjust by grid offset, add 0.5 grid units to account for width of gridlines\n const snapTarget = {\n type: 'gridpoint',\n x: this.round(gridPoint.x, xTickSpacing) - 0.5,\n y: this.round(gridPoint.y, yTickSpacing) - 0.5,\n };\n\n // pick closest point\n snapTarget.x = Math.abs(gridPoint.x - (snapTarget.x - xTickSpacing)) > Math.abs(gridPoint.x - snapTarget.x) ? snapTarget.x : snapTarget.x - xTickSpacing;\n snapTarget.y = Math.abs(gridPoint.y - (snapTarget.y - yTickSpacing)) > Math.abs(gridPoint.y - snapTarget.y) ? snapTarget.y : snapTarget.y - yTickSpacing;\n\n return snapTarget;\n }\n // if grid is not active, check if we can snap to an angle\n else if (this.points.length) {\n const snappableAngles = [-180, -90, 0, 90, 180];\n const lastPoint = this.points[this.points.length - 1];\n // angle between last point drawn and mouse (degrees)\n const thetaDeg = Math.atan2(lastPoint.y - gridPoint.y, lastPoint.x - gridPoint.x)\n * (180 / Math.PI);\n\n // snap to -180, -90, 0, 90, 180\n var snapCoords;\n snappableAngles.some((angle) => {\n // check if gridpoint is within snap tolerance of a vertical or horizontal angle\n if (Math.abs(thetaDeg - angle) < this.$store.getters['project/angleTolerance']) {\n // only take the x or y value from the rotated point\n // we don't want to preserve the original radius\n if (angle === -180 || angle === 0 || angle === 180) {\n // horizontal snap - use original x value and adjust y\n return {\n x: gridPoint.x,\n y: this.rotatePoint(lastPoint, gridPoint, angle - thetaDeg).y,\n };\n } else if (angle === -90 || angle === 90) {\n // vertical snap - use original y value and adjust x\n return {\n x: this.rotatePoint(lastPoint, gridPoint, angle - thetaDeg).x,\n y: gridPoint.y,\n };\n }\n }\n });\n\n if (snapCoords) {\n return {\n type: 'gridpoint',\n ...snapCoords,\n };\n }\n }\n\n // nothing to snap to, just return the location of the point\n return {\n type: 'gridpoint',\n ...gridPoint\n };\n }",
"snappingVertexData(point) {\n // build a list of vertices (in RWU) available for snapping\n // deep copy all vertices on the current story\n let snappableVertices = [...this.currentStoryGeometry.vertices];\n\n // TODO: conditionally combine this list with vertices from the next story down if it is visible\n if (this.previousStoryGeometry) {\n snappableVertices = snappableVertices.concat(JSON.parse(JSON.stringify(this.previousStoryGeometry.vertices)));\n }\n\n // if the polygon tool is active and the polygon being drawn has at least 3 existing points allow snapping to the origin of the polygon\n if (this.points.length >= 3 && this.currentTool === 'Polygon') {\n // convert the polygon origin from grid units to real world units before adding it as a snappable vertex\n snappableVertices.push({\n ...this.points[0],\n origin: true, // set a flag to mark the origin\n });\n }\n\n if (this.points.length === 1 && this.currentTool === 'Rectangle') {\n snappableVertices = snappableVertices.concat(\n geometryHelpers.syntheticRectangleSnaps(\n snappableVertices,\n this.points[0],\n point),\n );\n }\n\n if (!snappableVertices.length) { return null; }\n\n // find the vertex closest to the point being tested\n const nearestVertex = snappableVertices.reduce((a, b) => {\n const aDist = this.distanceBetweenPoints(a, point);\n const bDist = this.distanceBetweenPoints(b, point);\n return aDist < bDist ? a : b;\n });\n\n // return the nearest vertex if it is within the snap tolerance of the point\n if (this.distanceBetweenPoints(nearestVertex, point) < this.$store.getters['project/snapTolerance']) {\n return {\n ...nearestVertex,\n type: 'vertex',\n };\n }\n }",
"neighboringPoint (sourceX, sourceY, towards) {\n if (towards === North) return [sourceX, sourceY + this.ySpacing()]\n if (towards === South) return [sourceX, sourceY - this.ySpacing()]\n if (towards === East) return [sourceX + this.xSpacing(), sourceY]\n if (towards === West) return [sourceX - this.xSpacing(), sourceY]\n if (towards === NorthEast) return [sourceX + this.xSpacing(), sourceY + this.ySpacing()]\n if (towards === SouthEast) return [sourceX + this.xSpacing(), sourceY - this.ySpacing()]\n if (towards === NorthWest) return [sourceX - this.xSpacing(), sourceY + this.ySpacing()]\n if (towards === SouthWest) return [sourceX - this.xSpacing(), sourceY - this.ySpacing()]\n }",
"distPx2Volume(dist, distanceThreshold = 1) {\n // Scale to normalize px distance depending on threshold\n const distPx2Normalized = d3_scaleLinear()\n .domain([0, this.maxDistancePx * distanceThreshold])\n .range([0, 1])\n .clamp(true);\n const distNormal = distPx2Normalized(dist);\n const distPow = Math.pow(distNormal, 2);\n return distPow * MIN_VOLUME + (1 - this.zoomNormal) * MIN_VOLUME;\n }",
"screenCoordToRatio(x, y) {\n x = x / this.canvas.width;\n y = y / this.canvas.height;\n return {x:x, y:y};\n }",
"function snapAngle(dx, dy) {\n var angle = Math.atan2(dy, dx);\n if (angle < 0) {\n angle += Math.TAU;\n }\n // snap to 8 directions, 0=E, 1=SE, 2=S, 3=SW, etc.\n // TODO: hysteresis based on the direction you're dragging in\n var direction = (Math.floor(((angle-(Math.TAU/16)) / Math.TAU) * 8) + 1)%8;\n angle = direction * (Math.TAU/8);\n return [angle, direction];\n }",
"function pixelOffset(){\n if(xoffset*cellSize < pixeloffx){\n pixeloffx = 0\n }\n if(yoffset*cellSize < pixeloffy){\n pixeloffy = 0\n }\n while(pixeloffx > 0){\n pixeloffx -= cellSize\n xoffset--\n }\n while(pixeloffy > 0){\n pixeloffy -= cellSize\n yoffset--\n }\n\n while(pixeloffx < -cellSize){\n pixeloffx += cellSize\n xoffset++\n }\n while(pixeloffy < -cellSize){\n pixeloffy += cellSize\n yoffset++\n }\n\n $(\"#coordinates\").text(`${xoffset},${yoffset}`)\n}",
"function toggleSnap() {\n if (snapping == 'on') {\n snapping = 'off'\n }\n else {\n snapping = 'on'\n }\n}",
"function dip2px(dips) {\n return parseInt(dips * ctx.getResources().getDisplayMetrics().density + 0.5);\n}",
"function calcMouseCoords() {\n var xMid = canvasW / 2;\n var yMid = canvasH / 2;\n\n //var game0x = (xMid - camx * camzoom); (diff from 0x, then just scale mouse diff)\n gameMouseX = (rawMouseX - (xMid - camx * camzoom)) / camzoom; // + (rawMouseX)\n gameMouseY = (rawMouseY - (yMid - camy * camzoom)) / camzoom; //(rawMouseY) / camzoom;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether the given properties match those of a `LambdaConflictHandlerConfigProperty` | function CfnResolver_LambdaConflictHandlerConfigPropertyValidator(properties) {
if (!cdk.canInspect(properties)) {
return cdk.VALIDATION_SUCCESS;
}
const errors = new cdk.ValidationResults();
if (typeof properties !== 'object') {
errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));
}
errors.collect(cdk.propertyValidator('lambdaConflictHandlerArn', cdk.validateString)(properties.lambdaConflictHandlerArn));
return errors.wrap('supplied properties not correct for "LambdaConflictHandlerConfigProperty"');
} | [
"function CfnBucket_LambdaConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('event', cdk.requiredValidator)(properties.event));\n errors.collect(cdk.propertyValidator('event', cdk.validateString)(properties.event));\n errors.collect(cdk.propertyValidator('filter', CfnBucket_NotificationFilterPropertyValidator)(properties.filter));\n errors.collect(cdk.propertyValidator('function', cdk.requiredValidator)(properties.function));\n errors.collect(cdk.propertyValidator('function', cdk.validateString)(properties.function));\n return errors.wrap('supplied properties not correct for \"LambdaConfigurationProperty\"');\n}",
"function CfnBucket_NotificationConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('eventBridgeConfiguration', CfnBucket_EventBridgeConfigurationPropertyValidator)(properties.eventBridgeConfiguration));\n errors.collect(cdk.propertyValidator('lambdaConfigurations', cdk.listValidator(CfnBucket_LambdaConfigurationPropertyValidator))(properties.lambdaConfigurations));\n errors.collect(cdk.propertyValidator('queueConfigurations', cdk.listValidator(CfnBucket_QueueConfigurationPropertyValidator))(properties.queueConfigurations));\n errors.collect(cdk.propertyValidator('topicConfigurations', cdk.listValidator(CfnBucket_TopicConfigurationPropertyValidator))(properties.topicConfigurations));\n return errors.wrap('supplied properties not correct for \"NotificationConfigurationProperty\"');\n}",
"function CfnBucket_VersioningConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('status', cdk.requiredValidator)(properties.status));\n errors.collect(cdk.propertyValidator('status', cdk.validateString)(properties.status));\n return errors.wrap('supplied properties not correct for \"VersioningConfigurationProperty\"');\n}",
"function CfnBucket_EventBridgeConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('eventBridgeEnabled', cdk.validateBoolean)(properties.eventBridgeEnabled));\n return errors.wrap('supplied properties not correct for \"EventBridgeConfigurationProperty\"');\n}",
"function CfnAnomalyDetector_CloudwatchConfigPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('roleArn', cdk.requiredValidator)(properties.roleArn));\n errors.collect(cdk.propertyValidator('roleArn', cdk.validateString)(properties.roleArn));\n return errors.wrap('supplied properties not correct for \"CloudwatchConfigProperty\"');\n}",
"function CfnGatewayRoute_HttpGatewayRouteHeaderMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"HttpGatewayRouteHeaderMatchProperty\"');\n}",
"function CfnGatewayRoute_GatewayRouteMetadataMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('prefix', cdk.validateString)(properties.prefix));\n errors.collect(cdk.propertyValidator('range', CfnGatewayRoute_GatewayRouteRangeMatchPropertyValidator)(properties.range));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GatewayRouteMetadataMatchProperty\"');\n}",
"function CfnBucket_LoggingConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('destinationBucketName', cdk.validateString)(properties.destinationBucketName));\n errors.collect(cdk.propertyValidator('logFilePrefix', cdk.validateString)(properties.logFilePrefix));\n return errors.wrap('supplied properties not correct for \"LoggingConfigurationProperty\"');\n}",
"function CfnBucket_QueueConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('event', cdk.requiredValidator)(properties.event));\n errors.collect(cdk.propertyValidator('event', cdk.validateString)(properties.event));\n errors.collect(cdk.propertyValidator('filter', CfnBucket_NotificationFilterPropertyValidator)(properties.filter));\n errors.collect(cdk.propertyValidator('queue', cdk.requiredValidator)(properties.queue));\n errors.collect(cdk.propertyValidator('queue', cdk.validateString)(properties.queue));\n return errors.wrap('supplied properties not correct for \"QueueConfigurationProperty\"');\n}",
"function CfnDataSource_EventBridgeConfigPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('eventBusArn', cdk.requiredValidator)(properties.eventBusArn));\n errors.collect(cdk.propertyValidator('eventBusArn', cdk.validateString)(properties.eventBusArn));\n return errors.wrap('supplied properties not correct for \"EventBridgeConfigProperty\"');\n}",
"function CfnBucket_CorsConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('corsRules', cdk.requiredValidator)(properties.corsRules));\n errors.collect(cdk.propertyValidator('corsRules', cdk.listValidator(CfnBucket_CorsRulePropertyValidator))(properties.corsRules));\n return errors.wrap('supplied properties not correct for \"CorsConfigurationProperty\"');\n}",
"function CfnGatewayRoute_GatewayRouteHostnameMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('suffix', cdk.validateString)(properties.suffix));\n return errors.wrap('supplied properties not correct for \"GatewayRouteHostnameMatchProperty\"');\n}",
"function CfnGatewayRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}",
"function CfnBucket_NotificationFilterPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('s3Key', cdk.requiredValidator)(properties.s3Key));\n errors.collect(cdk.propertyValidator('s3Key', CfnBucket_S3KeyFilterPropertyValidator)(properties.s3Key));\n return errors.wrap('supplied properties not correct for \"NotificationFilterProperty\"');\n}",
"function CfnRoute_HttpPathMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n errors.collect(cdk.propertyValidator('regex', cdk.validateString)(properties.regex));\n return errors.wrap('supplied properties not correct for \"HttpPathMatchProperty\"');\n}",
"function CfnRoute_HttpQueryParameterMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n return errors.wrap('supplied properties not correct for \"HttpQueryParameterMatchProperty\"');\n}",
"function CfnGatewayRoute_HttpQueryParameterMatchPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('exact', cdk.validateString)(properties.exact));\n return errors.wrap('supplied properties not correct for \"HttpQueryParameterMatchProperty\"');\n}",
"function CfnAnomalyDetector_AnomalyDetectorConfigPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('anomalyDetectorFrequency', cdk.requiredValidator)(properties.anomalyDetectorFrequency));\n errors.collect(cdk.propertyValidator('anomalyDetectorFrequency', cdk.validateString)(properties.anomalyDetectorFrequency));\n return errors.wrap('supplied properties not correct for \"AnomalyDetectorConfigProperty\"');\n}",
"function CfnAnomalyDetector_S3SourceConfigPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('fileFormatDescriptor', cdk.requiredValidator)(properties.fileFormatDescriptor));\n errors.collect(cdk.propertyValidator('fileFormatDescriptor', CfnAnomalyDetector_FileFormatDescriptorPropertyValidator)(properties.fileFormatDescriptor));\n errors.collect(cdk.propertyValidator('historicalDataPathList', cdk.listValidator(cdk.validateString))(properties.historicalDataPathList));\n errors.collect(cdk.propertyValidator('roleArn', cdk.requiredValidator)(properties.roleArn));\n errors.collect(cdk.propertyValidator('roleArn', cdk.validateString)(properties.roleArn));\n errors.collect(cdk.propertyValidator('templatedPathList', cdk.listValidator(cdk.validateString))(properties.templatedPathList));\n return errors.wrap('supplied properties not correct for \"S3SourceConfigProperty\"');\n}",
"function CfnBucket_ObjectLockConfigurationPropertyValidator(properties) {\n if (!cdk.canInspect(properties)) {\n return cdk.VALIDATION_SUCCESS;\n }\n const errors = new cdk.ValidationResults();\n if (typeof properties !== 'object') {\n errors.collect(new cdk.ValidationResult('Expected an object, but received: ' + JSON.stringify(properties)));\n }\n errors.collect(cdk.propertyValidator('objectLockEnabled', cdk.validateString)(properties.objectLockEnabled));\n errors.collect(cdk.propertyValidator('rule', CfnBucket_ObjectLockRulePropertyValidator)(properties.rule));\n return errors.wrap('supplied properties not correct for \"ObjectLockConfigurationProperty\"');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the specified domain type's regular expression for matching field names. | function getFieldNameRegExp(domainType) {
if (angular.isUndefined(domainType.$fieldNameRegexp)) {
domainType.$fieldNameRegexp = getRegExp(domainType.fieldNamePattern, domainType.fieldNameFlags);
}
return domainType.$fieldNameRegexp;
} | [
"function getSampleDataRegExp(domainType) {\n if (angular.isUndefined(domainType.$regexp)) {\n domainType.$regexp = getRegExp(domainType.regexPattern, domainType.regexFlags);\n }\n return domainType.$regexp;\n }",
"function generateRegExp() {\n\n\tvar str = '';\n\tvar arr = [];\n\tvar tmp = \"@(types)\";\n\t\n\tfor (type in corpus) {\n\t\tarr.push(type);\n\t}\n\t\n\tvar exp = tmp.replace(\"types\", arr.join('|'));\n\t\n\treturn new RegExp(exp, \"ig\");\n}",
"function generateRegExp() {\n\n\tvar str = '';\n\tvar arr = [];\n\tvar tmp = \"@(types)\";\n\t\n\t// Get all the replaceable keywords from corpus, stick them into an array\n\tfor(type in corpus) {\n\t\tarr.push(type);\n\t}\n\t\n\t// Construct regular expression in the form of '@(keyword1,keyword2,keyword3,...)'\n\tvar exp = tmp.replace(\"types\", arr.join('|'));\n\t\n\treturn new RegExp(exp, \"ig\");\n}",
"function compileRegExp(lexer, str) {\n if (typeof (str) !== 'string') {\n return null;\n }\n var n = 0;\n while (str.indexOf('@') >= 0 && n < 5) { // at most 5 expansions\n n++;\n str = str.replace(/@(\\w+)/g, function (s, attr) {\n var sub = '';\n if (typeof (lexer[attr]) === 'string') {\n sub = lexer[attr];\n }\n else if (lexer[attr] && lexer[attr] instanceof RegExp) {\n sub = lexer[attr].source;\n }\n else {\n if (lexer[attr] === undefined) {\n _monarchCommon_js__WEBPACK_IMPORTED_MODULE_1__[\"throwError\"](lexer, 'language definition does not contain attribute \\'' + attr + '\\', used at: ' + str);\n }\n else {\n _monarchCommon_js__WEBPACK_IMPORTED_MODULE_1__[\"throwError\"](lexer, 'attribute reference \\'' + attr + '\\' must be a string, used at: ' + str);\n }\n }\n return (_monarchCommon_js__WEBPACK_IMPORTED_MODULE_1__[\"empty\"](sub) ? '' : '(?:' + sub + ')');\n });\n }\n return new RegExp(str, (lexer.ignoreCase ? 'i' : ''));\n}",
"function parseRegExp(node) {\n const evaluated = (0, util_1.getStaticValue)(node, globalScope);\n if (evaluated == null || !(evaluated.value instanceof RegExp)) {\n return null;\n }\n const { source, flags } = evaluated.value;\n const isStartsWith = source.startsWith('^');\n const isEndsWith = source.endsWith('$');\n if (isStartsWith === isEndsWith ||\n flags.includes('i') ||\n flags.includes('m')) {\n return null;\n }\n const text = parseRegExpText(source, flags.includes('u'));\n if (text == null) {\n return null;\n }\n return { isEndsWith, isStartsWith, text };\n }",
"function getRegExp(pattern, flags) {\n var safeFlags = angular.isString(flags) ? flags : \"\";\n return (angular.isString(pattern) && pattern.length > 0) ? new RegExp(pattern, safeFlags) : null;\n }",
"function regenerateRegExp(){\r\n\t\tpseudoRE = new RegExp('::?(' + Object.keys(pseudos).join('|') + ')(\\\\\\\\[0-9]+)?');\r\n\t}",
"function regexpFrom(string, flags) {\n return new RegExp(core.escapeRegExp(string), flags);\n }",
"function validateFieldRegEx(elementId, fieldValue) {\n var elementObj = billerCredElements[elementId];\n /* Creating the regular expression */\n var regExpr = new RegExp(\"^\" + elementObj.exprCharacters + elementObj.exprLength + \"$\");\n if (!addBill) {\n var isSecure = billerCredElements[elementId].securedFlag;\n if (isSecure) {\n var asterisk = new RegExp(\"^[\\\\*]*$\");\n if (asterisk.test(fieldValue)) {\n return true;\n }\n\n if (fieldValue === getValueFromKey(parseInt(elementId))) {\n return true;\n }\n }\n }\n /* Checking for PHONE and DATE box type and getting only number from the input field */\n if (elementObj.elementType === \"PHONE_BOX\" || elementObj.elementType === \"DATE_BOX\") {\n \tif(elementObj.elementType === \"DATE_BOX\"){\n \t\tvar regexOfDateBox = /^(0[1-9]|1[0-2])\\/(0[1-9]|1\\d|2\\d|3[01])\\/(19|20)\\d{2}$/;\n \t\t if(!regexOfDateBox.test(fieldValue)){\n \t\t\t return regexOfDateBox.test(fieldValue); \n \t\t }\n \t}\n \t fieldValue = getNumberFromString(fieldValue);\n }\n return regExpr.test(fieldValue);\n}",
"function matchSearchFuncEngRegex (searchTerm) {\n return function(element) {\n var re = \".*\" + searchTerm + \".*\";\n if (element.definition.match(re)) {\n return true;\n } else {\n return false;\n }\n }\n }",
"function regExBuilder(options){\n var re = options.regex ? options.find : w.escapeRegExp(options.find),\n reOptions = \"g\" + (options.insensitive ? \"i\" : \"\");\n return new RegExp(re, reOptions);\n}",
"function AttrRegex(attr) {\r\n return new RegExp(attr + \"=\" + bracketsRegexText);\r\n}",
"function _globalize($regexp) {\n return new RegExp(String($regexp).slice(1, -1), \"g\");\n }",
"getLookupFieldName(fieldName) {\n let lookupFieldName = fieldName;\n if (fieldName) {\n let lowercaseFieldName = fieldName.toLowerCase();\n if (lowercaseFieldName.endsWith(\"id\")) {\n // standard fields are same name but without 'Id' suffix\n lookupFieldName = fieldName.slice(0, -2);\n } else if (lowercaseFieldName.endsWith(\"__c\")) {\n // custom fields have __r suffix instead of __c suffix\n lookupFieldName = fieldName.slice(0, -1) + \"r\";\n }\n }\n return lookupFieldName;\n }",
"function dishNameRe(name){\n //for parenthesis\n name = name.replace(/([()[{*+.$^\\|?])/g, '\\\\$1');\n //select exact\n name = '^' + name + '$';\n return name;\n }",
"function validateTextBoxRegex(controls, regex) {\n\tvar errorsFound = _.filter(controls + \"[type=text]\", function(element){\n\t\treturn regex.test(element.value);\n\t});\n\n\treturn getElementNames(errorsFound);\n}",
"async _getFieldInputType(dataType){\n switch(dataType.toLowerCase()) {\n case 'text':\n return FIELDS.TEXT.type;\n case 'textarea':\n return FIELDS.TEXT_AREA.type;\n case 'number':\n return FIELDS.NUMBER.type;\n case 'address':\n return FIELDS.ADDRESS.type;\n case 'money-gbp':\n return FIELDS.MONEY_GBP.type;\n case 'date':\n return FIELDS.DATE.type;\n case 'document':\n return FIELDS.DOCUMENT.type;\n case 'email':\n return FIELDS.EMAIL.type;\n case 'fixed-list':\n return FIELDS.FIXED_LIST.type;\n case 'phone-uk':\n return FIELDS.PHONE_NUMBER.type;\n case 'yes-no':\n return FIELDS.YES_NO.type;\n case 'collection':\n return FIELDS.COLLECTION.type;\n case 'complex':\n return FIELDS.COMPLEX_TYPE.type;\n case 'multi-select':\n return FIELDS.MULTI_SELECT.type;\n default:\n throw new CustomError(`could not find a data type called '${dataType}'`)\n }\n }",
"function regExBuilder (find, regex, insensitive) {\n if (find) {\n var re = regex ? find : s.escapeRegExp(find)\n var reOptions = 'g' + (insensitive ? 'i' : '')\n return new RegExp(re, reOptions)\n }\n}",
"function matchSearchFuncMoroRegex (searchTerm) {\n return function(element) {\n return findMoroWordInArrayMoroRegex(element.moroword, searchTerm)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the value of a frequency in the current units | _frequencyToUnits(freq) {
return freq;
} | [
"function getFreq(name,un_name) //get frequncy in Hz\n{\n\tvar x=getVar(name);\n\tvar unit=getVtext(un_name);\n\tif(\"GHz\"==unit) return x*=1e9;\n\tif(\"MHz\"==unit) return x*=1e6;\n\tif(\"kHz\"==unit) return x*=1e3;\n\treturn x;\n}",
"toFrequency() {\n return (0, _Conversions.mtof)(this.toMidi());\n }",
"function getFrequency(value) {\n\tif (!ctx) {\n\t\treturn 0;\n\t}\n\t// get frequency by passing number from 0 to 1\n\t// Clamp the frequency between the minimum value (40 Hz) and half of the\n\t// sampling rate.\n\tvar minValue = 40;\n\tvar maxValue = ctx.sampleRate / 2;\n\t// Logarithm (base 2) to compute how many octaves fall in the range.\n\tvar numberOfOctaves = Math.log(maxValue / minValue) / Math.LN2;\n\t// Compute a multiplier from 0 to 1 based on an exponential scale.\n\tvar multiplier = Math.pow(2, numberOfOctaves * (value - 1.0));\n\t// Get back to the frequency value between min and max.\n\treturn maxValue * multiplier;\n}",
"function Frequency(value, units) {\n return new FrequencyClass((0, _Global.getContext)(), value, units);\n}",
"function determineFrequency(f) {\n var qstate = new jsqubits.QState(numInBits + numOutBits).hadamard(inputBits);\n qstate = qstate.applyFunction(inputBits, outBits, f);\n // We do not need to measure the outBits, but it does speed up the simulation.\n qstate = qstate.measure(outBits).newState;\n return qstate.qft(inputBits)\n .measure(inputBits).result;\n }",
"function getFrequencyToIndex(freq) {\n\t// Get the Nyquist frequency, 1/2 of the smapling rate.\n\tvar nyquistFrequency = audioContext.sampleRate / 2;\n\t// Map the frequency to the correct bucket.\n\tvar index = Math.round(freq / nyquistFrequency * analyser.frequencyBinCount);\n\n\t// Return the correspoding bucket.\n\treturn index;\n}",
"updateFrequency() {\n const freq = this.channel.frequencyHz;\n const block = this.channel.block;\n const fnum = this.channel.fnumber;\n // key scaling (page 29 YM2608J translated)\n const f11 = fnum.bit(10), f10 = fnum.bit(9), f9 = fnum.bit(8), f8 = fnum.bit(7);\n const n4 = f11;\n const n3 = f11 & (f10 | f9 | f8) | !f11 & f10 & f9 & f8;\n const division = n4 << 1 | n3;\n\n // YM2608 page 26\n if (this.freqMultiple === 0) {\n this.frequency = freq / 2;\n } else {\n this.frequency = freq * this.freqMultiple;\n }\n\n this.keyScalingNote = block << 2 | division;\n\n const FD = this.freqDetune & 3;\n const detune = DETUNE_TABLE[this.keyScalingNote][FD] * MEGADRIVE_FREQUENCY / 8000000;\n if (this.freqDetune & 4) {\n this.frequency -= detune;\n } else {\n this.frequency += detune;\n }\n }",
"function part1() {\n let frequency = 0\n changes.map(change => {\n frequency += parseInt(change)\n })\n return frequency\n}",
"function setFrequency(value) {\n var minValue = 40;\n var maxValue = AUDIO.sampleRate / 2;\n var numberOfOctaves = Math.log(maxValue / minValue) / Math.LN2;\n var multiplier = Math.pow(2, numberOfOctaves * (value - 1.0));\n filterNode.frequency.value = maxValue * multiplier;\n}",
"function audiofreq2fftindex(freq) {\n\n var indx = freq * AudBuffSiz / AudSampleRate;\n return(Math.floor(indx));\n\n}",
"function FrequencyToHighestBeatFrequency(f){\n return 20;\n }",
"function setFrequency(){\n radio.frequency = (radio.range.high + radio.range.low)/2\n}",
"calculateTotalFreqByState() {\n\t\tconst self = this;\n\n\t\tvar tF = ['low', 'mid', 'high'].map(function(d) {\n\t\t\treturn {\n\t\t\t\ttype: d,\n\t\t\t\tfreq: d3array.sum(self.filteredData.map(function(t) {\n\t\t\t\t\treturn t.freq[d];\n\t\t\t\t}))\n\t\t\t};\n\t\t});\n\n\t\treturn tF;\n\t}",
"function getPollingFreq() {\n\treturn pollingFreq;\n}",
"function setFrequency() {\n radio.frequency = (radio.range.low + radio.range.high) / 2;\n}",
"function TAU() {\n return τ;\n}",
"function getPaymentFrequencyNumber(paymentFrequency,baseOn365Days){\r\n\tif(paymentFrequency === PAYMENT_FREQUENCY_ANNUAL){\r\n\t\treturn 1;\r\n\t}else if(paymentFrequency === PAYMENT_FREQUENCY_MONTHLY){\r\n\t\treturn 12;\r\n\t}else if(paymentFrequency === PAYMENT_FREQUENCY_SEMI_MONTHLY){\r\n\t\treturn 24;\r\n\t}else if(paymentFrequency === PAYMENT_FREQUENCY_BI_WEEKLY || paymentFrequency === PAYMENT_FREQUENCY_ACCELERATED_BI_WEEKLY){\r\n\t\tif(baseOn365Days){\r\n\t\t\treturn 365/14;\r\n\t\t}\r\n\t\treturn 26;\r\n\t}else if(paymentFrequency === PAYMENT_FREQUENCY_WEEKLY || paymentFrequency === PAYMENT_FREQUENCY_ACCELERATED_WEEKLY){\r\n\t\tif(baseOn365Days){\r\n\t\t\treturn 365/7;\r\n\t\t}\r\n\t\treturn 52;\r\n\t}\r\n\treturn 0;\r\n}",
"function countSinus(x) {\r\n return Math.sin(x)\r\n}",
"get sampleRate() {\n if (this._buffer) {\n return this._buffer.sampleRate;\n } else {\n return (0, _Global.getContext)().sampleRate;\n }\n }",
"function getNoiseValue(x, y, frequency) {\n\treturn Math.abs(noise.perlin2(x / frequency, y / frequency));\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if entry is valid | function isValid(entry) {
if (entry.status && entry.lastName && entry.dateKey) {return true}
else {return false}
} | [
"function isMetadataValid(item) {\n if ($scope.isList) {\n return true;\n }\n if (!item.metadata) {\n $scope.error = {\n message: \"Resource is missing metadata field.\"\n };\n return false;\n }\n if (!item.metadata.name) {\n $scope.error = {\n message: \"Resource name is missing in metadata field.\"\n };\n return false;\n }\n if (item.metadata.namespace && item.metadata.namespace !== $scope.input.selectedProject.metadata.name) {\n $scope.error = {\n message: item.kind + \" \" + item.metadata.name + \" can't be created in project \" + item.metadata.namespace + \". Can't create resource in different projects.\"\n };\n return false;\n }\n return true;\n }",
"function validateRun (data, command) {\n // no additional validation necessary\n return true;\n }",
"static async check (entryInfo) {\n const {exShort, exLong, exitTarget, pairName} = entryInfo;\n const tShort = exShort.tickers[pairName];\n const tLong = exLong.tickers[pairName];\n const bid = tLong.bid;\n const ask = tShort.ask;\n\n if (!ask && !bid) {\n return false;\n }\n\n const spread = (ask - bid) / bid;\n\n logger.info(`[${exShort.id} - ${exLong.id}] spread exit for ${pairName}: ${spread}`);\n\n if (TradingUtils.STATISTICS) {\n await Spread.create({\n spread,\n exShort,\n exLong,\n pairName\n });\n await History.create({\n spread,\n exShort,\n exLong,\n pairName\n });\n return false;\n }\n\n if (spread < 0) {\n logger.path(`Negative spread for [${exShort.id} - ${exLong.id}] and pair ${pairName}: ${spread.toFixed(\n 4)}.`);\n }\n\n if (TrailingManager.exit({\n shortId: exShort.id,\n longId: exLong.id,\n spread,\n exitTarget,\n pairName\n })) {\n return Object.assign(entryInfo, {\n priceLongOut: ask,\n priceShortOut: bid\n });\n }\n }",
"function isKindValid(item) {\n if (!item.kind) {\n $scope.error = {\n message: \"Resource is missing kind field.\"\n };\n return false;\n }\n return true;\n }",
"isGameFieldValid() {\n\t\tlet self = this;\n\t\tlet isValid = true;\n\t\tthis.birds.forEach(function(bird) {\n\t\t\tlet h = bird.getHeight();\n\t\t\tlet location = bird.getLocation();\n\t\t\tlet x = location.x;\n\t\t\tlet y = location.y;\n\t\t\tisValid = self.fieldSize.isWithinField(h, x, y);\n\t\t\tif (!isValid) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n\t\treturn isValid;\n\t}",
"_validate (entry = [], queries = {}) {\n return this.getLogicalOperator(queries.operator).fn.call(queries.list, (_query) => {\n if (this.isLogicalOperator(queries.operator)) {\n return this._validate(entry, _query);\n } else {\n return this.getQueryOperator(_query[1]).fn.apply(this, [\n (_query[0] ? entry[1][_query[0]] : entry[1]), // Entry value\n _query[2], // Test value\n _query[0], // Test key\n entry // Entry [<Key>, <Value>]\n ]);\n }\n });\n }",
"function validateEditInfoByAdminDormer()\n{\n\tvar box, i;\n\tvar form=document.editInfoDormer;\n\t\n\tfor(i=0; i<7; i++)\n\t{\n\t\tbox=form.elements[i];\n\t\t//if it encountered a box without a value, an alert box would appear informing the user\n\t\tif(!box.value)\n\t\t{\n\t\t\t$().toastmessage({position:'middle-center', stayTime:2000});\n\t\t\t$().toastmessage('showErrorToast', \"You haven't filled in the \"+box.name+\".\");\n\t\t\tbox.focus();\n\t\t\treturn false;\n\t\t}\n\t}\n\t//return true if the form is complete\n\treturn true;\n}",
"checkValidityProblems() {\n\t\t//Check whether there are any unnamed items or items without prices\n\t\tlet problems = false;\n\t\tif(this.state.albumName === \"\") {\n\t\t\tproblems = true;\n\t\t}\n\t\tfor (let item of this.state.items) {\n\t\t\tif(item.itemName === \"\" || (this.state.isISO && item.description === \"\") || (!this.state.isISO && (item.price === \"\" || item.pic === null)) ) {\n\t\t\t\tproblems = true;\n\t\t\t}\n\t\t}\n\t\tif (problems) {\n\t\t\tlet items = this.state.items;\n\t\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\t\titems[i].highlighted = true;\n\t\t\t}\n\t\t\tthis.setState({\n\t\t\t\tshowMissingFieldsPopup: true,\n\t\t\t\thighlighted: true,\n\t\t\t\titems: items\n\t\t\t})\n\t\t}\n\t\treturn(problems);\n\t}",
"function hasValidPoint(data) {\n return (typeof data.latitude != \"undefined\" && data.longitude != \"undefined\" && data.latitude != null && data.longitude != null && !isNaN(data.latitude) && !isNaN(data.longitude));\n }",
"function isKeyPressedValid(e) {\n return (e.keyCode == 8 || e.keyCode == 46) || // backspace and delete keys\n (e.keyCode > 47 && e.keyCode < 58) || // number keys\n (e.keyCode == 32) || // spacebar & return key(s)\n (e.keyCode > 64 && e.keyCode < 91) || // letter keys\n (e.keyCode > 95 && e.keyCode < 112) || // numpad keys\n (e.keyCode > 180); // ;=,-./ etc...`\n }",
"function isMetaDataValid(){\r\n\torgUnit_id_metadata = metaDataArray[0].OrgUnitId;\r\n\tconsole.log(\"org unit id excel: \" + orgUnit_id_metadata);\r\n\tconsole.log(\"org unit id form: \" + org_unit_id);\r\n\t\r\n\tprogram_id_metadata = metaDataArray[0].ProgramId;\r\n\tconsole.log(\"program id excel: \" + program_id_metadata);\r\n\t\t\t\t\r\n\t//get the id of the selected program\r\n\tvar program_id_form=$(\"#programList\").val();\r\n\tconsole.log(\"program id form: \" + program_id_form);\r\n\t//get the id of the selected org unit: org_unit_id\r\n\t\r\n\t//test if the ids of program and org unit match with metadata in third sheet\r\n\tif(!(program_id_metadata === program_id_form)){\r\n\t\tadd(\"Error! The selected program id: \"+program_id_form+\" does not match the id in the spreadsheet: \" +program_id_metadata+\" !\", 4);\r\n\t\tconsole.log(\"Error! The selected program id: \"+program_id_form+\" does not match the id in the spreadsheet: \" +program_id_metadata+\" !\");\r\n\t\treturn false;\r\n\t}\r\n\tif(!(orgUnit_id_metadata === org_unit_id)){\r\n\t\tadd(\"Error! The selected org unit id: \"+org_unit_id+\" does not match the id in the spreadsheet: \" +orgUnit_id_metadata+\" !\", 4);\r\n\t\tconsole.log(\"Error! The selected org unit id: \"+org_unit_id+\" does not match the id in the spreadsheet: \" +orgUnit_id_metadata+\" !\");\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}",
"function validFlexValue() {\n\t\t\tvar list = [];\n\t\t\tfor (var i = 0; i < storeEdit.getCount(); i++) {\n\t\t\t\tvar flexValue = storeEdit.getAt(i);\n\t\t\t\tif (Ext.isEmpty(flexValue.get('name'))) {\n\t\t\t\t\tshowErrMessage('名称不能为空!');\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (flexValue.get('name').trim() == '') {\n\t\t\t\t\tshowErrMessage('名称不能为空格!');\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}",
"validateInputs() {\n\t\tif(isNaN(this.billAmount) || this.billAmount <= 0 || this.totalPerson == 0) return false;\n\t\treturn true;\n\t}",
"validateInput(data, callback) {\n const value = this.getInputFromData(data);\n const result = value === undefined\n || value === null\n || typeof value === 'string'\n || (typeof value === 'object' && (typeof value.first === 'string'\n || value.first === null\n || typeof value.last === 'string'\n || value.last === null));\n utils.defer(callback, result);\n }",
"function control_infos(infos)\n {\n //For this purpose use regular expressions\n var exp_string = new RegExp(/[a-z]/i);\n var exp_datum = new RegExp(/\\d{2}\\/\\d{2}\\/\\d{4}/i);\n if (!exp_string.test(infos.vorname))\n {\n Ext.Msg.alert('The added Vorname is not valid');\n return false;\n }\n if (!exp_string.test(infos.name))\n {\n Ext.Msg.alert('The added Name is not valid');\n return false;\n }\n if (!exp_datum.test(infos.datum))\n {\n Ext.Msg.alert('The added Geburtsdatum is not valid');\n return false;\n }\n return ( (exp_string.test(infos.vorname)) && (exp_string.test(infos.name))\n && (exp_datum.test(infos.datum)) );\n }",
"function validCueFields(cue, ts) {\n const err = domCache['cuePointError'];\n\n if (!ts.value || !cue.value) {\n if (!ts.value) {\n ts.classList.add('error');\n }\n\n if (!cue.value) {\n cue.classList.add('error');\n }\n\n err.innerHTML = 'add a valid cuePoint text and timestamp.';\n err.classList.remove('hide');\n return false;\n }\n\n if (!state.player) {\n err.innerHTML = 'no video is loaded.';\n err.classList.remove('hide');\n return false;\n }\n\n const duration = state.videos[state.currentVideo.index].duration || 0;\n if (ts.value > duration) {\n err.innerHTML = `cuePoint must be from 0 - duration (${duration.toFixed(2)}).`;\n err.classList.remove('hide');\n return false;\n }\n\n return true;\n }",
"function checkInput(input) {\n var essentialColumns = input.name && input.x && input.y;\n if (essentialColumns === undefined) {\n console.error(\"X or Y or Z Column cannot be empty.\");\n return false;\n }\n input.name = parseName(input.name);\n input.x = parseX(input.x);\n input.y = parseY(input.y);\n\n var constraints = null, viz = null, processe = null, z = null;\n if (input.z !== undefined) {\n input.z = parseZ(input.z);\n }\n if (input.constraints !== undefined) {\n if (0 === input.constraints.length)\n {\n input.constraints = undefined;\n }\n //input.constraints = input.constraints //parseConstraints(input.constraints);\n }\n if (input.viz !== undefined) {\n input.viz = parseViz(input.viz);\n }\n return (name && x && y && z && constraints && viz) !== undefined;\n}",
"static isValid(make) {\n return make != null && make !== '';\n }",
"validar() { }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
redirect upon clicking itinerary card to itinerary | function view_itin(link, own) {
window.location.href = "../itinerary_detail/itinerary_details.html?id=" + link;
} | [
"goToCardIntake() {\n let url;\n if (Auth.get(this).user.role === 'corporate-admin') {\n url = 'main.corporate.customer.intake-revised';\n } else {\n url = 'main.employee.customer.intake-revised';\n }\n if (this.displayData.rejectionTotal) {\n url = url + '.denials';\n }\n state.get(this).go(url, {customerId: this.displayData.selectedCustomer._id});\n }",
"function handleClickCard (item){\n // move to \"ground\" screen\n props.navigation.navigate(\"Ground\", {data: item});\n }",
"function cardDetail() {\n\n $('.image').click((event) => {\n let id = event.target.id;\n window.location.hash = '#cardDetail/' + id;\n });\n}",
"goToReceipt(receipt) {\n const {user, goToReceipt} = this.props;\n const userRole = user.get('role');\n goToReceipt(receipt.get('_id'), userRole);\n }",
"function goodreadsClick(bid){\n location.href=\"https://www.goodreads.com/book/show/\"+bid;\n}",
"async IndustryCard(context) {\n const card = CardFactory.heroCard(\n 'Main Business Details',\n 'Find more about Industry Details.....',\n ['https://3er1viui9wo30pkxh1v2nh4w-wpengine.netdna-ssl.com/wp-content/uploads/prod/sites/43/2020/06/Fortude-AI4A-Sri-Lanka.jpg'],\n [\n {\n type: ActionTypes.OpenUrl,\n title: 'Fashion',\n value: 'https://fortude.co/infor-fashion/'\n },\n {\n type: ActionTypes.OpenUrl,\n title: 'Food & Beverage',\n value: 'https://fortude.co/food-beverage-erp-solutions/'\n },\n {\n type: ActionTypes.OpenUrl,\n title: 'Manufacturing & Distribution',\n value: 'https://fortude.co/infor-manufacturing/'\n },\n {\n type: ActionTypes.OpenUrl,\n title: 'Healthcare',\n value: 'https://fortude.co/healthcare/'\n }\n ]\n );\n \n await context.sendActivity({ attachments: [card] });\n }",
"function setupNextCardLink(){\n $(\"a:contains('Next Card')\").click(function(event){\n event.preventDefault();\n showCard();\n card = new RandomCard();\n preloadCardImage();\n });\n}",
"function handleRecipeEdit() {\n var currentRecipe = $(this)\n .parent()\n .parent()\n .data(\"recipe\");\n window.location.href = \"/recipe?userId=\" + data.userId + \"&recipeId=\" + recipe.id;\n }",
"function goToEdit() {\n\thideCardContainer();\n\thideArrows();\n\thideFlashcard();\n\thideInput();\n\thideScoreboard();\n\n\tdisplayEditContainer();\n\tdisplayEditControls();\n\tupdateEditTable();\n\tupdateDeckName();\n}",
"changeStep() {\n window.location.assign('#/eventmgmt/shop');\n }",
"function goStudy() { \n if( tags != undefined ) {\n window.location = \"../Study_Card.html?tags=\" + tags;\n }\n else {\n window.location = \"../Study_Card.html?deck=\" + deckid;\n }\n}",
"function Getwish() {\n alert(\"inside wish \" + loginidd);\n url = \"wishlist.html\";\n document.location.href = url;\n\n}",
"function continueShopping() {\n\tsaveFormChanges();\n\twindow.location.href = thisSiteFullurl + backURL;\n}",
"function enrol() {\n console.log(\"In enrol(): \" + tournament.id);\n window.location.href = \"../enrolment/enrolment.html\";\n}",
"function gotToCheckout() {\n\tlocation.href = \"checkout.php\";\n}",
"function goToDetails(id){\n localStorage.setItem(\"movieId\",`${id}`); // Save the id in localStorage\n window.location.href = \"movieDetails.html\"; // Go to new page\n }",
"goToCustomerDenials(customer) {\n state.get(this).go('main.corporate.customer-denials', {customerId: customer.customerId});\n }",
"function online_course() {\n window.location.href = \"../onlineCourses/online_courses.html\";\n}",
"clickCard(index) {\n\t\t let flipped = this.flipped(this.state.cards);\n if (flipped.length < 2) {\n this.channel.push(\"click\", { state: this.state, card: index })\n .receive(\"ok\", this.newView);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if the post is there in the users favorite posts return true | isPostIsFavorite(postId){
if(this.favorites.posts.indexOf(postId)>=0)
{
return true;
}
return false;
} | [
"function storyIsFavorite(story) {\n if (currentUser) {\n let favoriteIds = currentUser.favorites.map(story => story.storyId); \n return favoriteIds.includes(story.storyId);\n }\n }",
"function isFavorite(story) {\n // start with an empty set of favorite story ids\n let favoriteStoryIds = new Set();\n\n if (currentUser) {\n favoriteStoryIds = new Set(\n currentUser.favorites.map((story) => story.storyId)\n );\n }\n isFave = favoriteStoryIds.has(story.storyId);\n // return true or false\n return isFave;\n }",
"isFavorite (serie) {\n\t\treturn this.favorites.find(item => item.id === serie.id)\n\t}",
"function isRemoveFromFavoriets(req,res)\n{\n return checkTable(req,'favorites')\n}",
"function checkForFavs() {\n for(let favStory of $(user.favorites)){\n let favStoryID = favStory.storyId;\n\n $(`#${favStoryID}`).find(\".fa-heart\").toggleClass(\"far fas\");\n }\n }",
"function checkOwnFavs(){\n if( ! conf.ownFavs || ! tweet.favorited ){\n return checkFinal();\n }\n checkOwnFavourite( tweet.id_str, function( favourited ){\n if( favourited ){\n console.log('Keeping tweet favourited by self');\n return nextTweet();\n }\n checkFinal();\n } );\n }",
"function checkIfFavourite() {\n const url = '/albumFavourite';\n // Since this is a GET request, simply call fetch on the URL\n fetch(url)\n .then((res) => {\n if (res.status === 200) {\n // return a promise that resolves with the JSON body\n return res.json()\n } else {\n }\n })\n .then((favouriteAlbum) => { // the resolved promise with the JSON body\n for( let i = 0; i < favouriteAlbum.length; i++ )\n {\n if(favouriteAlbum[i]._id == album._id )\n {\n isFavourite = true\n }\n }\n styleFavouriteButton();\n }).catch((error) => {\n })\n}",
"function checkFavorites() {\n if (localStorage.getItem(\"favorites\") == null) {\n favoritesArray = [];\n localStorage.setItem(\"favorites\", JSON.stringify(favoritesArray));\n } else {\n favoritesArray = JSON.parse(localStorage.getItem(\"favorites\"));\n }\n }",
"getFavorite(cardId) {\n if(this.user==false)return false;\n for(const card of this.user.savedCards){\n //console.log(card.cardID+\" vs \"+cardId);\n if(card.cardID == cardId)return card.favorited;\n\n }\n return false;\n }",
"function checkIfDuplicate(favList,checkPokemon){\n var check = false;\n favList.forEach(function (pokemon) {\n if(pokemon.id == checkPokemon.id){\n check = true;\n }\n });\n return check;\n }",
"function checkFavouriteProjects(projects, favouriteProjects) {\n angular.forEach(projects, function(p) {\n p.isFavourite = false;\n var index = favouriteProjects.indexOf(p._id);\n if (index !== -1) {\n p.isFavourite = true\n }\n });\n }",
"function checkNumFavs(){\n if( conf.minFavs && tweet.favorited && conf.minFavs <= tweet.favorite_count ){\n console.log('Keeping tweet favourited '+tweet.favorite_count+' times');\n return nextTweet();\n }\n checkTags();\n }",
"function checkPostsDisplay(){\n\tif($('#posts').children().length == 0){\n\t\t$('#posts').hide();\n\t}else{\n\t\t$('#posts').show();\n\t}\n}",
"function getFavoriteMovies() {\n\t\tlet movieId = $('.movie-id').val();\n\n\t\t$.ajax({\n\t\t\turl: \"/favorites/all\",\n\t\t\tmethod: \"GET\",\n\t\t\tcontentType: \"application/json\",\n\t\t\tdataType: 'json',\n\n\t\t\tcomplete : function(data){ \t\n\t\t\t\tjQuery.each(data.responseJSON, function(index, item) {\n\t\t\t\t\t//favoriteMovies(item.movieId, item.user.id);\n\n\t\t\t\t\tif (item.movieId == movieId && item.user.id == myId) {\n\t\t\t\t\t\t$('.add-to-favorite').addClass(\"is-favorite\")\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},fail : function(){\n\t\t\t\tconsole.log(\"Failed getting favorite movies\");\n\t\t\t}\n\t\t});\n\t}",
"async function checkTweetIsLikedByUser (id, user) {\n // get the likes\n const likes = await getTweetLikes(id)\n // look for the user among the likes\n return !!likes.find(likeUserName => likeUserName === user)\n }",
"function checkTags(){\n var keep = false,\n tags = tweet.entities && tweet.entities.hashtags;\n if( tags && tags.length && conf.hashTags && conf.hashTags.length ){\n var terms = [];\n tags.forEach( function( tag ){\n tag.text && terms.push( tag.text );\n } );\n conf.hashTags.forEach( function( term, i ){\n if( -1 !== terms.indexOf(term) ){\n console.log('Keeping tweet tagged #'+term);\n keep = true;\n }\n } );\n }\n keep ? nextTweet() : checkOwnFavs();\n }",
"function topicsExists(userInput){\n\t\tfor(var i = 0; i < topics.length; i++){\n\t\t\tif(userInput === topics[i]){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"function filterFavoritesIfAppliable() {\n const favs = $('#favs');\n if (favs.text().localeCompare('My favorites') == 0) {\n const favorites = User.getFavoritesText();\n $('#fixtures tr').filter(function() {\n // The league and teams infos are only on the 3 first tds\n const arrayOfDisplayed = $(this).children('td').slice(0, 3).map(function() { // eslint-disable-line no-invalid-this\n return $(this).text().trim(); // eslint-disable-line no-invalid-this\n }).get();\n $(this).toggle(favorites.some((element) => arrayOfDisplayed.includes(element))); // eslint-disable-line no-invalid-this\n });\n } else {\n $('#fixtures tr').toggle(true);\n }\n}",
"existsAnyImages_for_selectedFoot(footIndex) {\n try {\n if (this.state.toeData.feet[footIndex].toes !== undefined) {\n for (let i = 0; i < 5; i++) {//5 toes\n if (this.state.toeData.feet[footIndex].toes[i].images.length > 0)\n return true;\n }\n }\n } catch {\n return false;\n }\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
show either line or grid | showGrid(){
this.Grid = true;
this.Line = false
} | [
"function toggleGridLines() {\n drawLines = !drawLines;\n draw();\n }",
"checkBetLinesShow () {\n if (this.getService(\"LinesService\").getWinLines().length > 0){\n linesManager.disableMouseOverForLabels();\n } else {\n linesManager.enableMouseOverForLabels();\n }\n }",
"function renderGridLines()\n{\n // SET THE PROPER COLOR\n canvas2D.strokeStyle = GRID_LINES_COLOR;\n\n // VERTICAL LINES\n for (var i = 0; i < gridWidth; i++)\n {\n var x1 = i * cellLength;\n var y1 = 0;\n var x2 = x1;\n var y2 = canvasHeight;\n canvas2D.beginPath();\n canvas2D.moveTo(x1, y1);\n canvas2D.lineTo(x2, y2);\n canvas2D.stroke();\n }\n \n // HORIZONTAL LINES\n for (var j = 0; j < gridHeight; j++)\n {\n var x1 = 0;\n var y1 = j * cellLength;\n var x2 = canvasWidth;\n var y2 = y1;\n canvas2D.moveTo(x1, y1);\n canvas2D.lineTo(x2, y2);\n canvas2D.stroke(); \n }\n}",
"function onCheckboxGridLinesClicked(e) {\n\tDisplayCanvas.drawGridLines = ViewController.checkboxGridLines.checked;\t\n}",
"showLastLine() {\n this.el.style.transform = 'translatey(-' + ( ( this.lines.length * this.lineHeight ) - ( this.lineHeight * this.opts.rows ) ) + 'px )';\n this.overlay.style.transform = 'translatey(-' + ( ( this.lines.length * this.lineHeight ) - ( this.lineHeight * this.opts.rows ) ) + 'px )';\n }",
"function showGridOne() {\n if (!gridOneVisible) {\n gridOne.style.display = \"inline\";\n gridTwo.style.display = \"none\";\n gridOneVisible = true;\n gridTwoVisible = false;\n }\n return null;\n}",
"function renderGrid(ctx) {\n drawGridLines(ctx);\n drawGridCells(ctx, minesweeper.cells );\n}",
"function displayLine(lineName)\r\n{\r\n\tvar displayLine = System.Gadget.Settings.read(lineName);\r\n\tif (displayLine === false)\r\n\t{\r\n\t\t$(lineName).style.display = 'none';\r\n\t}\r\n\telse\r\n\t{\r\n\t\t$(lineName).style.display = 'block';\r\n\t}\r\n}",
"showRuler() {\n if (!this.mRulerEnabled)\n this.mSceneController.scene.add(this.mRulerLine);\n this.mRulerEnabled = true;\n }",
"function ToggleLineDisplay( done ){\n\n var active = done.active ? false : true;\n var opacity = active ? 0 : 1;\n d3.select( '#line_' + done.key ).style( 'opacity', opacity );\n done.active = active;\n\n}",
"function show_line(){\n var lines=Array.from(document.getElementsByClassName(\"line\"));\n lines.forEach(each=>{\n each.classList.remove(\"line_hide\");\n if(Math.random()<0.5){\n each.classList.add(\"line_animate\");\n }\n });\n document.getElementsByClassName(\"output_neuron_layer\")[0].children[0].classList.add(\"output_number\")\n}",
"draw() {\n push();\n translate(GSIZE / 2, GSIZE / 2);\n // Ordered drawing allows for the disks to appear to fall behind the grid borders\n this.el_list.forEach(cell => cell.drawDisk());\n this.el_list.forEach(cell => cell.drawBorder());\n this.el_list.filter(cell => cell.highlight)\n .forEach(cell => cell.drawHighlight());\n pop();\n }",
"function drawControlLines() {\n\tif(!showControlLines) return;\n\tfor(let i=0; i<controlPts.length; i++) {\n\t\tlet pt = controlPts[i];\n\t\tdrawRectangle(pt.x-dotSize, pt.y-dotSize, 2*dotSize, 2*dotSize, 'rgb(255,0,0)');\n\t}\n\tfor(let i=0; i<controlPts.length-1; i++) {\n\t\tlet pt1 = controlPts[i];\n\t\tlet pt2 = controlPts[i+1];\n\t\tdrawLine(pt1.x, pt1.y, pt2.x, pt2.y, 'rgb(32,32,255)');\n\t}\n\tif(curveType==Hermite) {\n\t\tfor(let i=0; i<controlPts.length; i++) {\n\t\t\tlet pt = controlPts[i];\n\t\t\tdrawCircle(pt.x+pt.dx, pt.y+pt.dy, dotSize, 'rgb(255,160,0)');\n\t\t\tdrawLine(pt.x, pt.y, pt.x+pt.dx, pt.y+pt.dy, 'rgb(255,160,0)');\n\t\t}\t\t\n\t}\n}",
"display() {\n //set the color\n stroke(this.element*255) ;\n //draw the point\n point(this.identity.x,this.identity.y)\n }",
"function groupLineToggle() {\n groupLines *= -1;\n\tdrawBoard();\n}",
"display() {\n this.draw(this.points.length);\n }",
"show() {\n stroke(0);\n push();\n translate(this.pos.x, this.pos.y);\n rotate(this.heading);\n if (this.best == true) {\n image(bestcarImg, -this.w, -this.h / 4);\n } else image(carImg, -this.w, -this.h / 4);\n pop();\n\n if (showSensorsCheckBox.checked && !this.dead) {\n stroke(50);\n for (let i = 0; i < this.sensors.length; i++) {\n line(\n this.frontPos.x,\n this.frontPos.y,\n this.frontPos.x + cos(this.sensors[i] + this.heading) * this.sensorsLength[i],\n this.frontPos.y + sin(this.sensors[i] + this.heading) * this.sensorsLength[i]\n );\n }\n }\n }",
"function showCell (evt) {\n evt.target.className = evt.target.className.replace(\"hidden\", \"\");\n if (evt.target.classList.contains(\"mine\")) {\n showAllMines();\n playBomb();\n reset();\n return;\n }\n showSurrounding(evt.target);\n checkForWin();\n}",
"function drawCanvasGrid(node){\n\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
normalizeArabic removes tashkeel, tatweel, and removes punctuation from 'str'. | normalizeArabic(str="") {
return (
str
// Trim Whitespace
.trim()
// Remove tashkeel
.replace(/ّ|َ|ً|ُ|ٌ|ِ|ٍ|ْ/g, "")
// Remove tatweel
.replace(/ـ/g, "")
);
} | [
"function norm(str){\n return str\n .toLowerCase()\n .replace(/Á|á/,'azzz').replace(/É|é/,'ezzz').replace(/Í|í/,'izzz')\n .replace(/Ð|ð/,'dzzz').replace(/Ó|ó/,'ozzz').replace(/Ú|ú/,'uzzz')\n .replace(/Ý|ý/,'yzzz').replace(/Þ|þ/,'zz').replace(/Æ|æ/,'zzz').replace(/Ö|ö/,'zzzz');\n }",
"function normalize(w) {\n w = w.toLowerCase();\n var c = has(w);\n while (c != \"\") { //keep getting rid of punctuation as long as it has it\n var index = w.indexOf(c);\n if (index == 0) w = w.substring(1, w.length);\n else if (index == w.length - 1) w = w.substring(0, w.length - 1);\n else w = w.substring(0, index) + w.substring(index + 1, w.length);\n c = has(w);\n }\n return w;\n\n}",
"function _normalize(phrase) {\n\n // Lower case it\n phrase = phrase.toLocaleLowerCase();\n\n // Normalize special characters by using the characters in the charMap hash\n phrase = phrase.replace(/[,./!?àáâãāçćčèéêëēėęîïíīįìłñńňôòóōõřśšťûüùúūůÿýžżŻź]/g, function(ch) {\n return charMap[ch] || ch;\n });\n\n return phrase;\n }",
"function normalize(word) {\n\n return stem(word.toLowerCase()).replace(/[^a-z]/g, '');\n\n}",
"static cleanText (inputText) {\r\n let cleanText = inputText.toLowerCase().trim();\r\n\r\n cleanText = cleanText.replaceAll(\"à\",\"a\");\r\n cleanText = cleanText.replaceAll(\"â\",\"a\");\r\n cleanText = cleanText.replaceAll(\"è\",\"e\");\r\n cleanText = cleanText.replaceAll(\"é\",\"e\");\r\n cleanText = cleanText.replaceAll(\"ê\",\"e\");\r\n cleanText = cleanText.replaceAll(\"ë\",\"e\");\r\n cleanText = cleanText.replaceAll(\"ç\",\"c\");\r\n cleanText = cleanText.replaceAll(\"ï\",\"i\");\r\n cleanText = cleanText.replaceAll(/ {2,}/g,\" \");\r\n \r\n return cleanText;\r\n }",
"function CheckArabicword(field) {\n\tif(isEmpty(field)){\n\t\treturn true;\n\t}\n\tvar string = field.value;\n\tfor (i = 0; i < string.length; i++) {\n\t\tvar c = string.charAt(i);\n\t\tif (!isArabic(c) && c != ' ') {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}",
"function removeSpecialChars(str) {\n let transliterated = transliterate(str)\n return transliterated.replace(/[-\\/' ]/ig, '').toLowerCase();\n}",
"function trimWordLowerCase(word) {\n // Remove some zero-width unicode characters (esp. = u00A0)\n var pattern = /[\\u200B-\\u200D\\uFEFF\\u00A0]/g;\n word = word.replace(pattern,\"\");\n\n // Clear out any remaining whitespace surrounding the word\n pattern = /^[\\s]+|[\\s]+$/g;\n word = word.replace(pattern,\"\");\n\n // Remove any punctionation surrounding the word\n // List derived from NON_WORD_CHARS array in Annotext 3.0\n pattern = /^[.,!¡?¿:;\\/|\\\\'\"“”‘’‚„«»‹›()\\[\\]\\-_]+|[.,!¡?¿:;\\/|\\\\'\"“”‘’‚„«»‹›()\\[\\]\\-_]+$/g;\n word = word.replace(pattern,\"\");\n \n word = word.toLowerCase();\n\n return word;\n}",
"function normalize(ruleStr)\r\n{\r\n\tvar retVal = ruleStr.toLowerCase() ;\r\n\tvar re = /,(\\w)/;\r\n\tretVal = retVal.replace(re,\", $1\");\r\n\treturn retVal;\r\n}",
"function stringTransformer(str) {\n // Your code here\n return str.split(' ').reverse().join(' ').split('').map((el)=> {\n if (el == el.toUpperCase()) return el.toLowerCase()\n else if (el == el.toLowerCase()) return el.toUpperCase()\n }).join('')\n}",
"function sentensify(str) {\n // Add your code below this line\n var splitStr = str.split(/\\W/);\n var newSplitStr = splitStr.join(\" \");\n \n return newSplitStr;\n\n // Add your code above this line\n }",
"function getLinkRewriteFromString(str)\n\t{\n\t\tstr = str.toUpperCase();\n\t\tstr = str.toLowerCase();\n\t\t\n\t\t/* Lowercase */\n\t\tstr = str.replace(/[\\u00E0\\u00E1\\u00E2\\u00E3\\u00E4\\u00E5\\u0101\\u0103\\u0105\\u0430]/g, 'a');\n str = str.replace(/[\\u0431]/g, 'b');\n\t\tstr = str.replace(/[\\u00E7\\u0107\\u0109\\u010D\\u0446]/g, 'c');\n\t\tstr = str.replace(/[\\u010F\\u0111\\u0434]/g, 'd');\n\t\tstr = str.replace(/[\\u00E8\\u00E9\\u00EA\\u00EB\\u0113\\u0115\\u0117\\u0119\\u011B\\u0435\\u044D]/g, 'e');\n str = str.replace(/[\\u0444]/g, 'f');\n\t\tstr = str.replace(/[\\u011F\\u0121\\u0123\\u0433\\u0491]/g, 'g');\n\t\tstr = str.replace(/[\\u0125\\u0127]/g, 'h');\n\t\tstr = str.replace(/[\\u00EC\\u00ED\\u00EE\\u00EF\\u0129\\u012B\\u012D\\u012F\\u0131\\u0438\\u0456]/g, 'i');\n\t\tstr = str.replace(/[\\u0135\\u0439]/g, 'j');\n\t\tstr = str.replace(/[\\u0137\\u0138\\u043A]/g, 'k');\n\t\tstr = str.replace(/[\\u013A\\u013C\\u013E\\u0140\\u0142\\u043B]/g, 'l');\n str = str.replace(/[\\u043C]/g, 'm');\n\t\tstr = str.replace(/[\\u00F1\\u0144\\u0146\\u0148\\u0149\\u014B\\u043D]/g, 'n');\n\t\tstr = str.replace(/[\\u00F2\\u00F3\\u00F4\\u00F5\\u00F6\\u00F8\\u014D\\u014F\\u0151\\u043E]/g, 'o');\n str = str.replace(/[\\u043F]/g, 'p');\n\t\tstr = str.replace(/[\\u0155\\u0157\\u0159\\u0440]/g, 'r');\n\t\tstr = str.replace(/[\\u015B\\u015D\\u015F\\u0161\\u0441]/g, 's');\n\t\tstr = str.replace(/[\\u00DF]/g, 'ss');\n\t\tstr = str.replace(/[\\u0163\\u0165\\u0167\\u0442]/g, 't');\n\t\tstr = str.replace(/[\\u00F9\\u00FA\\u00FB\\u00FC\\u0169\\u016B\\u016D\\u016F\\u0171\\u0173\\u0443]/g, 'u');\n str = str.replace(/[\\u0432]/g, 'v');\n\t\tstr = str.replace(/[\\u0175]/g, 'w');\n\t\tstr = str.replace(/[\\u00FF\\u0177\\u00FD\\u044B]/g, 'y');\n\t\tstr = str.replace(/[\\u017A\\u017C\\u017E\\u0437]/g, 'z');\n\t\tstr = str.replace(/[\\u00E6]/g, 'ae');\n str = str.replace(/[\\u0447]/g, 'ch');\n str = str.replace(/[\\u0445]/g, 'kh');\n\t\tstr = str.replace(/[\\u0153]/g, 'oe');\n str = str.replace(/[\\u0448]/g, 'sh');\n str = str.replace(/[\\u0449]/g, 'ssh');\n str = str.replace(/[\\u044F]/g, 'ya');\n str = str.replace(/[\\u0454]/g, 'ye');\n str = str.replace(/[\\u0457]/g, 'yi');\n str = str.replace(/[\\u0451]/g, 'yo');\n str = str.replace(/[\\u044E]/g, 'yu');\n str = str.replace(/[\\u0436]/g, 'zh');\n\n\t\t/* Uppercase */\n\t\tstr = str.replace(/[\\u0100\\u0102\\u0104\\u00C0\\u00C1\\u00C2\\u00C3\\u00C4\\u00C5\\u0410]/g, 'A');\n str = str.replace(/[\\u0411]/g, 'B');\n\t\tstr = str.replace(/[\\u00C7\\u0106\\u0108\\u010A\\u010C\\u0426]/g, 'C');\n\t\tstr = str.replace(/[\\u010E\\u0110\\u0414]/g, 'D');\n\t\tstr = str.replace(/[\\u00C8\\u00C9\\u00CA\\u00CB\\u0112\\u0114\\u0116\\u0118\\u011A\\u0415\\u042D]/g, 'E');\n str = str.replace(/[\\u0424]/g, 'F');\n\t\tstr = str.replace(/[\\u011C\\u011E\\u0120\\u0122\\u0413\\u0490]/g, 'G');\n\t\tstr = str.replace(/[\\u0124\\u0126]/g, 'H');\n\t\tstr = str.replace(/[\\u0128\\u012A\\u012C\\u012E\\u0130\\u0418\\u0406]/g, 'I');\n\t\tstr = str.replace(/[\\u0134\\u0419]/g, 'J');\n\t\tstr = str.replace(/[\\u0136\\u041A]/g, 'K');\n\t\tstr = str.replace(/[\\u0139\\u013B\\u013D\\u0139\\u0141\\u041B]/g, 'L');\n str = str.replace(/[\\u041C]/g, 'M');\n\t\tstr = str.replace(/[\\u00D1\\u0143\\u0145\\u0147\\u014A\\u041D]/g, 'N');\n\t\tstr = str.replace(/[\\u00D3\\u014C\\u014E\\u0150\\u041E]/g, 'O');\n str = str.replace(/[\\u041F]/g, 'P');\n\t\tstr = str.replace(/[\\u0154\\u0156\\u0158\\u0420]/g, 'R');\n\t\tstr = str.replace(/[\\u015A\\u015C\\u015E\\u0160\\u0421]/g, 'S');\n\t\tstr = str.replace(/[\\u0162\\u0164\\u0166\\u0422]/g, 'T');\n\t\tstr = str.replace(/[\\u00D9\\u00DA\\u00DB\\u00DC\\u0168\\u016A\\u016C\\u016E\\u0170\\u0172\\u0423]/g, 'U');\n str = str.replace(/[\\u0412]/g, 'V');\n\t\tstr = str.replace(/[\\u0174]/g, 'W');\n\t\tstr = str.replace(/[\\u0176\\u042B]/g, 'Y');\n\t\tstr = str.replace(/[\\u0179\\u017B\\u017D\\u0417]/g, 'Z');\n\t\tstr = str.replace(/[\\u00C6]/g, 'AE');\n str = str.replace(/[\\u0427]/g, 'CH');\n str = str.replace(/[\\u0425]/g, 'KH');\n\t\tstr = str.replace(/[\\u0152]/g, 'OE');\n str = str.replace(/[\\u0428]/g, 'SH');\n str = str.replace(/[\\u0429]/g, 'SHH');\n str = str.replace(/[\\u042F]/g, 'YA');\n str = str.replace(/[\\u0404]/g, 'YE');\n str = str.replace(/[\\u0407]/g, 'YI');\n str = str.replace(/[\\u0401]/g, 'YO');\n str = str.replace(/[\\u042E]/g, 'YU');\n str = str.replace(/[\\u0416]/g, 'ZH');\n\n\t\tstr = str.toLowerCase();\n\n\t\tstr = str.replace(/[^a-z0-9\\s\\'\\:\\/\\[\\]-]/g,'');\n\t\t\n\t\tstr = str.replace(/[\\u0028\\u0029\\u0021\\u003F\\u002E\\u0026\\u005E\\u007E\\u002B\\u002A\\u002F\\u003A\\u003B\\u003C\\u003D\\u003E]/g, '');\n\t\tstr = str.replace(/[\\s\\'\\:\\/\\[\\]-]+/g, ' ');\n\n\t\t// Add special char not used for url rewrite\n\t\tstr = str.replace(/[ ]/g, '-');\n\t\tstr = str.replace(/[\\/\\\\\"'|,;%]*/g, '');\n\n\t\treturn str;\n\t}",
"function txtNoPunctuation (txt){\n let strA = txt.toLowerCase();\n let strB = strA.replace(/[+]/g, \" \");\n let strC = strB.replace(/[-]/g, \"\");\n let strD = strC.replace(/[:;.,!@#$%^&*()''\"\"]/g, \"\");\n return strD;\n}",
"function removePunctuation(str){\n return str.replace(/[.,!?;:()]/g,'')\n}",
"function unmangleUnicode(str) {\n var result = '';\n for (var i = 0, len = str.length; i < len; i += 2) {\n result += str.charAt(i);\n }\n return result;\n}",
"function convertUnicodeString(str) {\r\n\t\tvar convertedText = str.replace(/\\\\u[\\dA-Fa-f]{4}/g, function (unicodeChar) {\r\n\t\t\treturn String.fromCharCode(parseInt(unicodeChar.replace(/\\\\u/g, ''), 16));\r\n\t\t});\r\n\t\treturn convertedText;\r\n\t}",
"function toScottishScreaming(str) {\n\treturn str.replace(/[aiou]/gi, 'e').toUpperCase();\n}",
"static convertToArabic(number) {\n var arabic = { \"0\": \"٠\", \"1\": \"١\", \"2\": \"٢\", \"3\": \"٣\", \"4\": \"٤\", \"5\": \"٥\", \"6\": \"٦\", \"7\": \"٧\", \"8\": \"٨\", \"9\": \"٩\" };\n var chars = number.toString().split(\"\");\n var newNum = new Array();\n for (var i = 0; i < chars.length; i++) {\n if (arabic[chars[i]] == undefined || arabic[chars[i]] == null)\n newNum[i] = chars[i];\n else\n newNum[i] = arabic[chars[i]];\n }\n return newNum.join(\"\");\n }",
"function isArabic(c) {\n\tif (c >= 'ا' && c <= 'ي' || (c == 'ء' || c == 'ؤ' || c == 'ئ' || c == 'أ'))\n\t\treturn true;\n\treturn false;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Used like file_here(import.meta.url, 'really_cool_file.png') | function file_here (here_url, file_name) {
const here_file = fileURLToPath(here_url);
const here = path.dirname(here_file);
return path.join(here, file_name);
} | [
"getFileUrl(file) {\n return RSVP.resolve(file.link('self').href);\n }",
"function asset(url){\n if(url.match(/^(?:https?\\:)\\/\\//)) return url;\n else return 'assets/' + url;\n}",
"async file(source, output, opts = {}) {\n const ext = path.extname(output).substr(1);\n const [res] = await this.capture(source, _.merge(opts, {\n type: ext || 'png',\n name: output\n }));\n return res;\n }",
"function FileInfo() {\n}",
"addImage(url) {\n \n }",
"function Sidead () {\nreturn <img src={require(\"../imgad.jpg\")} alt=\"imgad\" />;\n}",
"function getFileObject(filePathOrUrl, cb) {\n getFileBlob(filePathOrUrl, function(blob) { //fn2 //llama a la funcion getFileBlob con el url introducido y una funcion que: \n cb(blobToFile(blob, '' + $$(\"#nuevocodigo\").val() + '.jpg')); //ejecuta nuestro cb (callback) sobre el blob con nombre y fecha cambiada (el nombre sera 'test.jpg')\n });\n }",
"function get_full_url(file) {\n\n //\n // We just concatenate strings. This is to ensure\n // efficient memory use as opposed to storing the\n // entire URLs as arrays\n //\n // return {domain: COMMONCRAWL_DOMAIN, path: '/crawl-data/' + file + '/wet.paths.gz'};\n return COMMONCRAWL_BASE_URL + file + COMMONCRAWL_WET_PATHS;\n\n}",
"function fileFromServerRelativePath(base, serverRelativePath) {\n return File([base, extractWebUrl(base.toUrl())], `_api/web/getFileByServerRelativePath(decodedUrl='${encodePath(serverRelativePath)}')`);\n}",
"get icon_path() {\n return this.args.icon_path;\n }",
"_downloadOriginalImage() {\n if (this.props.node.downloadOriginalImage) {\n this.props.node.downloadOriginalImage()\n } else {\n console.warn('Failed to download original image. Node missing download function')\n }\n }",
"pathToFileUrl(url) {\n const filePrefix = process.platform === \"win32\" ? \"file:///\" : \"file://\";\n return filePrefix + url;\n }",
"function getFilePath(fileName) {\n return os.userInfo().homedir + \"\\\\AppData\\\\Roaming\\\\.minecraft\\\\mcpipy\\\\\" + fileName + \".py\";\n}",
"static smallImageUrlForRestaurant(restaurant) {\r\n return (`/img/small/${restaurant.photograph}.jpg`);\r\n }",
"get icon_url() {\n return this.args.icon_url;\n }",
"function GetGistFileContent(url, name, callback) {\n $.ajax({\n url: url,\n type: 'GET',\n dataType: 'text',\n cache: false\n }\n ).success(function (data) {\n if (data.length > 0) {\n callback(data, name);\n }\n else {\n LogErrorOverlay(\"Failed to retrieve File '\" + name + \"'.\", \"Github reported an error for this file.\", JSON.stringify(data, null, 2));\n }\n }).error(function (e) {\n LogErrorOverlay(\"Failed to retrieve File '\" + name + \"'.\", \"Github reported an error for this file.\", JSON.stringify(e, null, 2));\n });\n}",
"function uploadIconPic() {\n storageRef.getDownloadURL()\n // Get URL of the uploaded file\n .then(function (url) {\n console.log(url);\n // Save the URL into apps document\n db.collection(\"apps\").doc(docAppID).update({\n \"IconPic\": url\n })\n .then(function () {\n console.log('Added Icon Pic URL to Firestore.');\n redirectToSuccess();\n })\n })\n }",
"buildFileComponent(file) {\n return React.createElement(FileComponent, { file: file, key: file._meta.token });\n }",
"function showIconPicture() {\n // Listen for file selection.\n fileInput.addEventListener('change', function (e) {\n file = e.target.files[0];\n var blob = URL.createObjectURL(e.target.files[0]);\n // Change DOM image.\n image.src = blob;\n\n // Store using this name.\n storageRef = storage.ref(\"images/\" + docAppID + \"icon.jpg\");\n\n storageRef.put(file)\n .then(function () {\n console.log('Uploaded to Cloud Storage.');\n })\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public function `nonEmptyArray`. Returns true if `data` is a nonempty array, false otherwise. | function nonEmptyArray (data) {
return array(data) && data.length > 0;
} | [
"function isZeroArray(arr) {\r\n\t\tif (!arr[0] && !arr[1] && !arr[2] && !arr[3]) return true;\r\n\t}",
"function nonEmpty(jqObject) {\n return jqObject && jqObject.length;\n}",
"function IsArrayLike(x) {\r\n return x && typeof x.length == \"number\" && (!x.length || typeof x[0] != \"undefined\");\r\n }",
"function empty( mixed_var ) {\r\n\treturn (mixed_var===\"\"||mixed_var===0||mixed_var===\"0\"||mixed_var===null||mixed_var===false||(is_array(mixed_var)&&mixed_var.length===0)||(mixed_var === undefined));\r\n}",
"function isArray1D(a) {\n return !isArrayOrTypedArray(a[0]);\n }",
"function notempty_ques_(slice0) /* (slice : sslice) -> bool */ {\n return ((len(slice0))>0);\n}",
"function hasData(cell)\n{\n if (cell == null) return 0;\n return cell.length != 0;\n}",
"function isEmpty(value) {\n if (typeof value === 'undefined') {\n return true;\n }\n\n if (value === null) {\n return true;\n }\n\n if ((typeof value === 'string' || value instanceof String) && value.length === 0) {\n return true;\n }\n\n if (Array.isArray(value) && value.length === 0) {\n return true;\n }\n\n if (typeof value === 'object' && value.constructor === Object && Object.keys(value).length === 0) {\n return true;\n }\n\n return false;\n }",
"isEmpty() {\n return ((this.front === -1) && (this.rear === -1));\n }",
"function ISARRAY(value) {\n return Object.prototype.toString.call(value) === '[object Array]';\n}",
"static #checkIfObjectIsFound(array) {\n\n\t\t// Check if input is defined.\n\t\tif (!array) {\n\t\t\treturn console.log(`${array} is undefined or null.`)\n\t\t}\n\n\t\treturn array.length !== 0;\n\t}",
"function empty_ques_(slice0) /* (slice : sslice) -> bool */ {\n return !((((len(slice0))>0)));\n}",
"function validator(terms_array) {\n\tfor (var i = 0; i < terms_array.length; i++) {\n\t\tif (isNaN(terms_array[i]) || terms_array[i].length == 0) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}",
"function removeEmptyArrays(arr) {\n\treturn arr.filter(x => x.length !== 0)\n}",
"function isEmptyCollection(obj){\n\treturn isCollection(obj) && (\t\t\t\t\t//if it is a non-nullable object AND\n\t\t(Array.isArray(obj) && obj.length == 0) ||\t//it is an empty array, OR\n\t\tjQuery.isEmptyObject(obj)\t\t\t\t\t//it is an empty hashmap\n\t);\n}",
"function ServerBehavior_getIsEmpty()\n{\n if ( (this.parameters && this.parameters.length > 0)\n || (this.applyParameters && this.applyParameters.length > 0)\n )\n {\n return false;\n }\n else\n {\n return true;\n }\n}",
"function isNumericArray(array) {\n var isal = true;\n for (var i = 0; i < array.length; i++) {\n if (!$.isNumeric(array[i])) {\n isal = false;\n }\n }\n return isal;\n }",
"function verifyTeleportDataNotEmpty(data) {\n return !jQuery.isEmptyObject(data._embedded[`city:search-results`]);\n }",
"checkNotesEmpty(notes) {\n for (let i = 0; i < notes.length; i++) {\n if (notes[i]) {\n return false;\n }\n }\n return true;\n }",
"static isArray(input) {\n return input instanceof Array;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
end useAction Initialize GUIScripts:initializeRow Helper method that initializes the row and rowl variables | function initializeRow() {
row = new Array();
rowl = new Array();
row.length = 3;
rowl.length = 3;
for (var i = 0; i < row.length; i++) {
row[i] = ROW_POS + (i*ROW_SIZE);
rowl[i] = LBL_ROW_POS + (i*ROW_SIZE);
}//end i for loop
} | [
"function initializeRows() {\n eventContainer.empty();\n var eventsToAdd = [];\n for (var i = 0; i < events.length; i++) {\n eventsToAdd.push(createNewRow(events[i]));\n }\n eventContainer.append(eventsToAdd);\n }",
"function initializeRows() {\n resultContainer.empty();\n var resultsToAdd = [];\n for (var i = 0; i < results.length; i++) {\n resultsToAdd.push(createNewRow(results[i]));\n }\n resultContainer.append(resultsToAdd);\n }",
"function rowViewModel(initialValues, isNew, initialOverride) {\n var items = (0, _knockout.observableArray)(),\n // observable array to hold the items in the row\n // observable dictionary to hold the items and other properties\n itemDictionary = (0, _knockout.observable)({}),\n rowContext = {\n metadata: context.metadata, // reference to the parent metadata\n rows: rows,\n unique: unique,\n isNew: isNew,\n itemDictionary: itemDictionary,\n editMode: (0, _knockout.observable)(false), // for styling - maybe better if called isActiveRow\n deleteFlag: (0, _knockout.observable)(false),\n data: (0, _knockout.computed)(function () {\n var dict = itemDictionary();\n return _lodash2.default.extend({}, initialValues || {}, Object.keys(dict).reduce(function (d, id) {\n var item = dict[id];\n if (item && item.getValue) {\n d[id] = item.getValue();\n } else {\n d[id] = item;\n }\n return d;\n }, {}));\n })\n },\n row = {}; // the row itself\n var prop = void 0,\n itemViewModels = null,\n rowReadonly = void 0;\n\n // initialize row readonly as the list's state\n rowContext.readonly = (0, _knockout.observable)(readonly());\n\n // rowReadonly - string to run thrown expression parser to show/hide rows\n if ((0, _scalejs5.is)(options.rowReadonly, 'string')) {\n rowReadonly = (0, _knockout.computed)(function () {\n if (rowContext.readonly && rowContext.readonly()) {\n return true; // if readonly is true on context, then row is readonly\n }\n // else, eval the expression to determine if the row is readonly\n return (0, _scalejs2.evaluate)(options.rowReadonly, function (id) {\n var item = itemDictionary()[id];\n if (item && item.getValue) {\n return item.getValue();\n }\n });\n });\n }\n\n // can be utilized by expression parser to get error for an id\n function error(id) {\n var item = itemDictionary()[id];\n if (item && item.inputValue && item.inputValue.error) {\n return item.inputValue.error();\n }\n }\n\n // accurately calculates the index of the row in the list\n rowContext.index = (0, _knockout.computed)(function () {\n return rows().indexOf(row);\n });\n\n // getValueById function for expression parsing\n // todo. refactor this\n rowContext.getValue = function (id) {\n if (id === 'index') {\n return rowContext.index();\n }\n if (id === 'list') {\n return rows();\n }\n if (id === 'row') {\n return rows()[rowContext.index()];\n }\n if (id === 'error') {\n return error;\n }\n if (id === 'parent') {\n return context.data();\n }\n // check the item dictionary\n var item = itemDictionary()[id];\n if (item && item.getValue) {\n return item.getValue();\n }\n\n // if the item doesnt have getValue, return itself\n if ((0, _scalejs5.has)(item)) {\n return (0, _knockout.unwrap)(item);\n }\n\n var value = rowContext.data.peek()[id];\n if ((0, _scalejs5.has)(value)) {\n return value;\n }\n\n prop = rowContext[id];\n\n if ((0, _scalejs5.has)(prop)) {\n return (0, _knockout.unwrap)(prop);\n }\n\n return context.getValue(id);\n };\n\n itemViewModels = node.items.map(function (_item) {\n // deep clone the item as we might mutate it before passing to createViewModels\n var item = _lodash2.default.cloneDeep(_item);\n\n // add readonly computed to the item before passing it to input\n // input will use the already defined observable if it exists\n // but, if the input already has readonly set on it, dont get readonly from row..\n if (rowReadonly && item.input && !(0, _scalejs5.has)(item.input.readonly)) {\n item.input.readonly = rowReadonly;\n }\n\n if (item.options && item.options.unique) {\n if (!item.id) {\n console.error('Cannot set unique on item without id');\n } else if (!unique[item.id]) {\n // only create once\n unique[item.id] = (0, _knockout.observableArray)();\n }\n }\n\n // todo - clean this up?\n if (listItems[item.type]) {\n var ret = listItems[item.type].call(rowContext, item);\n if (item.visible) {\n ret.visible = (0, _knockout.computed)(function () {\n return (0, _scalejs2.evaluate)(item.visible, rowContext.getValue);\n });\n }\n return ret;\n }\n if (options.optimize && initialValues) {\n item.options = item.options || {};\n item.options.value = initialValues[item.id];\n }\n return _scalejs.createViewModel.call(rowContext, item);\n });\n\n // if there are initial values, update the children\n if (initialValues && !options.optimize) {\n itemViewModels.forEach(function (item) {\n // allow for JSON default values don't get overwritten\n // by server data that doesn't contain data\n if (initialValues[item.id]) {\n item.setValue && item.setValue(initialValues[item.id], { initial: initialOverride !== false });\n }\n });\n }\n\n // update items obsArr\n items(itemViewModels);\n\n // generate itemDictionary from the itemViewModels\n // also add each item's inputValue directly on the row\n // this is for MemberExpressions to work properly (list[0].Status)\n itemDictionary(itemViewModels.reduce(function (dict, item) {\n if ((0, _scalejs5.has)(item.id)) {\n dict[item.id] = item;\n row[item.id] = item.inputValue;\n }\n return dict;\n }, (0, _scalejs5.merge)(initialValues || {})));\n // just in case some data doesnt have a column, keep it in the item dict\n\n // TODO: ItemDict or Row? which one is better?\n // rowVM\n row.items = items;\n row.itemDictionary = itemDictionary;\n row.mappedChildNodes = items;\n row.editMode = rowContext.editMode;\n row.deleteFlag = rowContext.deleteFlag;\n row.readonly = function (bool) {\n items().forEach(function (item) {\n if (item.setReadonly) {\n item.setReadonly(bool);\n } else if (item.readonly) {\n item.readonly(bool);\n }\n });\n };\n\n return row;\n }",
"function initialize() {\n // console.time('List init');\n if (options.optimize) {\n _knockout2.default.options.deferUpdates = true;\n }\n rows().forEach(function (row) {\n row.items().forEach(function (item) {\n item.dispose && item.dispose();\n });\n });\n rows.removeAll();\n if (data() && Array.isArray(data()) && data().length > 0) {\n data().forEach(function (item) {\n add(item, false, initial);\n });\n\n // if trackDiffChanges set to true store the original data to noticeboard\n if (node.trackDiffChanges) {\n _scalejs4.default.set(node.id, data());\n }\n } else {\n for (var i = rows().length; i < minRequiredRows; i++) {\n add(null, true, initial);\n }\n }\n initial = undefined;\n if (options.optimize) {\n _knockout2.default.options.deferUpdates = false;\n }\n // console.timeEnd('List init');\n }",
"function Row(width, height, justifyContent, valign){\n\tSet.call(this);\n\tthis.coordinates=[]; //since we could insert objects that can be shared, so we just need to record their coordinate x, to bring it back to the row when need it (for example a pop up that share labels)\n\tthis.sp=[];//spaces between elements\n\tthis.valignment=[];\n\tthis.justifyContent='left';\n\tthis.valign=0;\n\n\tthis.w=0;\n\tthis.xd=1; //expand Distance\n\tif(typeof width==='number'){\n\t\tthis.width=width; // target width\n\t\t//this.w=width; // target width\n\t\tthis.xd=0;\n\t}\n\t\t\n\n\tif(typeof height==='number'){\n\t\tthis.height=height;\n\t}\n\n \tif(typeof valign==='string'){\n\t\tif(valign=='middle' || valign=='bottom'){\n\t\t\tif(valign=='middle'){// || valign=='bottom'){\n\t\t\t\tthis.valign=1;\n\t\t\t}\n\t\t\telse if(valign=='bottom'){\n\t\t\t\tthis.valign=2;\n\t\t\t}\n\t\t}\n\t}\n\n\tif(this.xd==0){\n\t\tif(typeof justifyContent==='string'){\n\t\t\tif(justifyContent=='center' || justifyContent=='right' || justifyContent=='space-between' || justifyContent=='space-around'){\n\t\t\t\tthis.justifyContent=justifyContent;\n\t\t\t}\n\t\t}\n\t}\n}",
"function constructItemRow(rowObject) {\n // Convert to array.\n var rowDataToAppend = constructArrayFromObject(MERGED_SHEET_HEADERS, rowObject); \n // Add the formulas for columns that don't contain static data.\n rowDataToAppend[ORDER_FULFILLED_COLUMN_INDEX] = \" \";\n rowDataToAppend = addOrderDate(rowDataToAppend, rowObject); \n rowDataToAppend = addItemShippedFormula(rowDataToAppend, rowObject); \n rowDataToAppend = addItemTotalFormula(rowDataToAppend);\n rowDataToAppend = addStoreNameFormula(rowDataToAppend);\n // If there is a shipment present, add formulas.\n var orderItemId = rowObject.shipments_shipmentItems_orderItemId\n if (orderItemId != undefined && orderItemId != '') {\n rowDataToAppend = addShipmentFormulas(rowDataToAppend, rowObject);\n }\n // Row data is ready: write it to the array.\n return rowDataToAppend;\n}",
"function BocList_InitializeList(bocList, selectorControlPrefix, count, selection, hasClickSensitiveRows, listMenu)\n{\n var selectedRows = new BocList_SelectedRows (selection);\n if ( selectedRows.Selection != _bocList_rowSelectionUndefined\n && selectedRows.Selection != _bocList_rowSelectionDisabled)\n {\n for (var i = 0; i < count; i++)\n {\n var selectorControlID = selectorControlPrefix + i;\n var selectorControl = document.getElementById (selectorControlID);\n if (selectorControl == null)\n continue;\n var row = selectorControl.parentNode.parentNode;\n\n if (hasClickSensitiveRows)\n BocList_BindRowClickEventHandler(bocList, row, selectorControl, listMenu);\n\n if (selectorControl.checked) \n {\n var rowBlock = new BocList_RowBlock (row, selectorControl);\n selectedRows.Rows[selectorControl.id] = rowBlock;\n selectedRows.Length++;\n }\n }\n }\n _bocList_selectedRows[bocList.id] = selectedRows;\n}",
"function initializeRows(recipes) {\n blogContainer.empty();\n var recipesToAdd = [];\n for (var i = 0; i < recipes.length; i++) {\n recipesToAdd.push(createNewRow(recipes[i]));\n }\n blogContainer.append(recipesToAdd);\n }",
"function CreateTblRow(tblName, field_setting, data_dict, col_hidden) {\n //console.log(\"========= CreateTblRow =========\", tblName);\n //console.log(\"data_dict\", data_dict);\n\n const field_names = field_setting.field_names;\n const field_tags = field_setting.field_tags;\n const field_align = field_setting.field_align;\n const field_width = field_setting.field_width;\n const column_count = field_names.length;\n\n //const col_left_border = (selected_btn === \"btn_overview\") ? cols_overview_left_border : cols_stud_left_border;\n const col_left_border = field_setting.cols_left_border;\n\n// --- lookup index where this row must be inserted\n const ob1 = (data_dict.lastname) ? data_dict.lastname.toLowerCase() : \"\";\n const ob2 = (data_dict.firstname) ? data_dict.firstname.toLowerCase() : \"\";\n // ordering of table overview is doe on server, put row at end\n const row_index = (selected_btn === \"btn_result\") ? b_recursive_tblRow_lookup(tblBody_datatable, setting_dict.user_lang, ob1, ob2) : -1;\n\n// --- insert tblRow into tblBody at row_index\n const tblRow = tblBody_datatable.insertRow(row_index);\n if (data_dict.mapid) {tblRow.id = data_dict.mapid};\n\n// --- add data attributes to tblRow\n tblRow.setAttribute(\"data-pk\", data_dict.id);\n\n// --- add data-sortby attribute to tblRow, for ordering new rows\n tblRow.setAttribute(\"data-ob1\", ob1);\n tblRow.setAttribute(\"data-ob2\", ob2);\n\n// --- add EventListener to tblRow\n tblRow.addEventListener(\"click\", function() {HandleTblRowClicked(tblRow)}, false);\n\n// +++ insert td's into tblRow\n for (let j = 0; j < column_count; j++) {\n const field_name = field_names[j];\n\n // skip columns if in columns_hidden\n if (!col_hidden.includes(field_name)){\n const field_tag = field_tags[j];\n const class_width = \"tw_\" + field_width[j];\n const class_align = \"ta_\" + field_align[j];\n\n // --- insert td element,\n const td = tblRow.insertCell(-1);\n\n // --- create element with tag from field_tags\n const el = document.createElement(field_tag);\n\n // --- add data-field attribute\n el.setAttribute(\"data-field\", field_name);\n\n // --- add text_align\n el.classList.add(class_width, class_align);\n\n // --- add left border before each group\n if(col_left_border.includes(j)){td.classList.add(\"border_left\")};\n\n // --- append element\n td.appendChild(el);\n\n// --- add EventListener to td\n if (field_name === \"withdrawn\") {\n if(permit_dict.permit_crud && permit_dict.requsr_same_school){\n td.addEventListener(\"click\", function() {UploadToggle(el)}, false)\n add_hover(td);\n // this is done in add_hover: td.classList.add(\"pointer_show\");\n };\n } else if (field_name === \"gl_status\") {\n if(permit_dict.permit_approve_result && permit_dict.requsr_role_insp){\n td.addEventListener(\"click\", function() {UploadToggle(el)}, false)\n add_hover(td);\n };\n //} else if ([\"diplomanumber\", \"gradelistnumber\"].includes(field_name)){\n // td.addEventListener(\"change\", function() {HandleInputChange(el)}, false)\n // el.classList.add(\"input_text\");\n };\n // --- put value in field\n UpdateField(el, data_dict)\n } // if (!columns_hidden[field_name])\n } // for (let j = 0; j < 8; j++)\n return tblRow\n }",
"function CreateIngredientTable() {\n u.CreateRow(\"ingredientTable\", \"th\", [\"Food\", \"Quantity\", \"\", \"Morv\", \"-\", \"+\"],[\"\",\"\",\"\",\"\",\"\",\"addIngRowHeader\"],[210,90,60,60,15,15], \"px\");\n AddIngredientsRow();\n u.ID(\"addIngRowHeader\").addEventListener(\"click\", AddIngredientsRow);\n}",
"fillHeaderRow(headerRowNumber, rowData) {\n for (let [i, value] of rowData.entries()) {\n this.tableBodyNode.appendChild(this.createTableDiv('header ' + headerRowNumber, this.keys[i], value, 'string', this.columnFormats[i] + ' tableHeaderDiv'))\n }\n }",
"setRow(index, row) {\n return this.setRowFromFloats(index, row.x, row.y, row.z, row.w);\n }",
"function createNewRow(asset) {\n\n var newItemRow = $(\"<tr>\");\n newItemRow.addClass(\"itemRowClick\");\n newItemRow.data(\"asset\", asset);\n\n var newIndex = $(\"<td>\");\n newIndex.addClass(\"something\");\n newIndex.text(asset.id);\n newIndex.data(\"asset\", asset);\n newItemRow.append(newIndex);\n\n var newAsset = $(\"<td>\");\n newAsset.addClass(\"something\");\n newAsset.data(\"asset\",asset);\n newAsset.text(asset.itemName);\n newItemRow.append(newAsset);\n\n var newLinkRowContainer = $(\"<td>\");\n\n var newLinksRow = $(\"<div>\");\n newLinksRow.attr(\"id\", \"manageLinks\")\n newLinkRowContainer.append(newLinksRow);\n\n // var editIcon = $(\"<span>\");\n // editIcon.addClass(\"glyphicon glyphicon-pencil itemEdit\");\n // editIcon.attr(\"aria-hidden\", \"true\");\n // newLinksRow.append(editIcon);\n\n var deleteIcon = $(\"<span>\");\n deleteIcon.addClass(\"glyphicon glyphicon-remove itemRemove\");\n deleteIcon.data(\"id\", asset.id);\n newLinksRow.append(deleteIcon);\n\n newItemRow.append(newLinkRowContainer);\n\n return newItemRow;\n }",
"_makeRow(rowCtrlNames) {\n\t\tconst row = [];\n\t\tfor (let y = 0; y < rowCtrlNames.length; y++) {\n\t\t\tconst control = this._getSubControlDef(rowCtrlNames[y]);\n\t\t\tif (control && control.visible) {\n\t\t\t\tconst childPropertyId = {\n\t\t\t\t\tname: this.props.control.name,\n\t\t\t\t\tcol: this._getColumnIndex(rowCtrlNames[y])\n\t\t\t\t};\n\t\t\t\tconst parentPropertyId = cloneDeep(this.props.propertyId);\n\n\t\t\t\tlet propertyId = childPropertyId;\n\t\t\t\tif (parentPropertyId.name !== childPropertyId.name) {\n\t\t\t\t\tpropertyId = this.props.controller.setChildPropertyId(parentPropertyId, childPropertyId);\n\t\t\t\t}\n\t\t\t\trow.push(this.controlFactory.createControlItem(control, propertyId));\n\t\t\t}\n\t\t}\n\t\treturn row;\n\t}",
"function buildRow(countySelection) {\n \n for (let j = 0; j < database.length; j++ ) {\n \n if(database[j].content.$t.includes(countySelection) && database[j].gs$cell.col == 1) {\n let sameRow = database[j].gs$cell.row\n //will iterate through the 26 columns for a-z\n for (let r = j; r < j + columns; r++) {\n \n if(sameRow == database[r].gs$cell.row) {\n row.push({cellnum: database[r].title.$t.slice(0,1), text: database[r].content.$t })\n }\n }\n }\n }\n }",
"function RowCompletion(left, middle, right) {\n \t\tthis.left = left ? left : 0;\n \t\tthis.middle = middle ? middle : 0;\n \t\tthis.right = right ? right : 0;\n \t}",
"function addRow(record, index, allItems)\n {\n addRecordToJSONSearch(record,panelNumber)\n }",
"function createNewRow(asset) {\n\n var newItemRow = $(\"<tr>\");\n newItemRow.addClass(\"itemRowClick\");\n newItemRow.data(\"asset\", asset);\n\n var newIndex = $(\"<span>\");\n newIndex.addClass(\"something\");\n newIndex.text(asset.id);\n newItemRow.append(newIndex);\n\n var newAsset = $(\"<span>\");\n newAsset.addClass(\"somthing\");\n newAsset.text(asset.itemName);\n newItemRow.append(newAsset);\n\n var newLinkRowContainer = $(\"<td>\");\n\n var newLinksRow = $(\"<div>\");\n newLinksRow.attr(\"id\", \"manageLinks\");\n newLinkRowContainer.append(newLinksRow);\n\n var editIcon = $(\"<span>\");\n editIcon.addClass(\"glyphicon glyphicon-pencil itemEdit\");\n editIcon.attr(\"aria-hidden\", \"true\");\n editIcon.attr(\"id\", \"icons\");\n editIcon.attr(\"data-toggle\", \"modal\");\n editIcon.attr(\"data-target\", \"#updateItemForm\");\n editIcon.data(\"asset\", asset);\n newLinksRow.append(editIcon);\n\n var deleteIcon = $(\"<span>\");\n deleteIcon.addClass(\"glyphicon glyphicon-remove itemRemove\");\n deleteIcon.attr(\"id\", \"icons\");\n deleteIcon.data(\"id\", asset.id);\n newLinksRow.append(deleteIcon);\n\n newItemRow.append(newLinkRowContainer);\n\n return newItemRow;\n }",
"function createdRow(row, data, dataIndex) {\n // Recompiling so we can bind Angular directive to the DT\n $compile(angular.element(row).contents())($scope);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
constructor objet Film avec les champs title, year et plot | function Film(title,plot,year){
this.title = title
this.plot = plot
this.year = year
} | [
"function createMovie(t, d, g, im) {\n var movie = {\n title: t,\n director: d,\n genre: g,\n imdbGrade: im,\n }\n return movie;\n}",
"function Album(artist, title, year){\n this.artist = artist\n this.title = title\n this.year = year\n this.songs = [];\n}",
"function showFilm(item) {\n var displayPoster = item.children(\"img\").attr(\"src\");\n $('#slideShow').attr(\"src\", displayPoster);\n\n //Use movie ID to look up plot\n var displayID = item.children(\"p\").first().text();\n var displayTitle = item.children(\"h3\").text();\n var displayYear = item.children(\"p\").last().text();\n var omdbURLById = \"https://www.omdbapi.com/?i=\" + displayID + \"&r=json\";\n $.ajax(omdbURLById, {\n complete: function(newXHR){\n var film = $.parseJSON(newXHR.responseText);\n $('#overlay span').html(\"<p>\" + \"Title: \" + displayTitle + \"</p>\" + \"<p>\" + \"Year: \" + displayYear + \"</p>\" + \"<p>\" + \"Plot: \" + film.Plot + \"</p>\");\n }\n });\n\n//Fade in the overlay\n $('#overlay').fadeIn(500);\n}",
"function draw_year() {\n // Calculate the serial date that the camera's z position corresponds to\n serial_date = ((((camera_z / multiplier) - 70)/600) * (latest - earliest)) + earliest;\n // Convert the date from the serialised format back to a nice format \"May 2019\".\n var new_date = moment(\"0000-01-01\", \"YYYY-MM-DD\").add(Math.floor(serial_date), 'days');\n ctx.font = 'bold 2em sans-serif';\n ctx.globalAlpha = 0.7;\n ctx.textAlign = \"right\";\n // Draw the date\n ctx.fillText(new_date.format(\"MMMM YYYY\"), 250, 35);\n}",
"function buildMovieList(){\n\n for(let i=0; i < titles.length; i++){\n\n var mov = {\n 'title':titles[i],\n 'src':images[i],\n 'synopsis':synopsis[i],\n 'directors':directors[i],\n 'actors':actors[i],\n 'year':year[i]\n };\n\n //add to each set of info to allMovieInfo Array\n allMovieInfo.push(mov);\n\n }\n\n}",
"function Title(text) {\n $.jqplot.ElemContainer.call(this);\n // Group: Properties\n \n // prop: text\n // text of the title;\n this.text = text;\n // prop: show\n // wether or not to show the title\n this.show = true;\n // prop: fontFamily\n // css font-family spec for the text.\n this.fontFamily;\n // prop: fontSize\n // css font-size spec for the text.\n this.fontSize ;\n // prop: textAlign\n // css text-align spec for the text.\n this.textAlign;\n // prop: textColor\n // css color spec for the text.\n this.textColor;\n // prop: renderer\n // A class for creating a DOM element for the title,\n // see <$.jqplot.DivTitleRenderer>.\n this.renderer = $.jqplot.DivTitleRenderer;\n // prop: rendererOptions\n // renderer specific options passed to the renderer.\n this.rendererOptions = {}; \n }",
"function create(name, year) {\n return MovieModel.create({\n public_id: randomString({ length: 12 }),\n name: name,\n year: year\n });\n}",
"constructor(p, x, y){\r\n\t\tsuper(\"plot\", x, y, \"Hoe\");\r\n\t\tthis.plot = p;\r\n\t}",
"set title(title) {\n if (Lang.isNull(title)) {\n this._study.title = null;\n return;\n }\n let titleObj = new Title();\n titleObj.value = title;\n this._study.title = titleObj;\n }",
"constructor(title, img, price, desc) {\n this.title = title;\n this.imgURL = img;\n this.price = price;\n this.Description = desc;\n }",
"constructor (dia = 1, mes = 1,ano = 1970){\n this.dia = dia\n this.mes = mes\n this.ano = ano\n }",
"function draw(year){\n\n // filter the data for the corresponding day\n // filter the data to return only the three countries with most medals\n\n\n //TODO append data to draw circles\n // var circles = ...;\n\n //enter the data\n\n\n //exit\n\n //update\n\n\n //TODO append data for texts\n // var text = ...\n\n\n\n }",
"load(data) {\n var _a;\n const { playlistId, title, thumbnail, shortBylineText, videoCount, videoCountShortText, } = data;\n this.id = playlistId;\n this.title = title.simpleText || title.runs[0].text;\n this.videoCount = common_1.stripToInt(videoCount || videoCountShortText.simpleText) || 0;\n // Thumbnail\n this.thumbnails = new _1.Thumbnails().load(((_a = data.thumbnails) === null || _a === void 0 ? void 0 : _a[0].thumbnails) || thumbnail.thumbnails);\n // Channel\n if (shortBylineText && shortBylineText.simpleText !== \"YouTube\") {\n const shortByLine = shortBylineText.runs[0];\n this.channel = new _1.ChannelCompact({\n id: shortByLine.navigationEndpoint.browseEndpoint.browseId,\n name: shortByLine.text,\n client: this.client,\n });\n }\n return this;\n }",
"function setMoviesPage() {\n\n // display movie genres list\n listMovieGenres();\n\n // display movie year list with forwarded range data\n listMovieYears(2000, 2021)\n\n // display popular movies at page startup\n displayPopularMovies();\n}",
"function SimpleStoryCreator() {\n // ************************************************************\n // * All required lists *\n // ************************************************************\n\n // List of all possible story plots\n var rPlotList = [\n\t\"destroy\",\n\t\"kidnap\",\n\t\"witch\",\n\t\"revenge\"\n ];\n\n // List of story intros\n var rIntroList = [\n\t\"Once Upon a Time\",\n\t\"In a land far away\",\n\t\"Before you were born\",\n\t\"In a little village\"\n ];\n\n // List of possible endings for the story\n var rPlotEndList = [\n\t\"flee\",\n\t\"kill\",\n\t\"kill_weapon\"\n ];\n\n // List of all good people (read: Heros)\n var rHeroList = [\n\t{ Article: \"a\" , Name: \"trader\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"merchant\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"salesperson\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"salesman\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"peasant\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"farmer\", Gender: \"male\" },\n\t{ Article: \"a\" , Name: \"farmer's wife\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"hero\", Gender: \"male\" },\n\t{ Article: \"a\" , Name: \"heroine\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"blacksmith\", Gender: \"both\" },\n\t{ Article: \"an\", Name: \"artist\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"poet\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"programmer\", Gender: \"both\" },\n\t{ Article: \"an\", Name: \"artist\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"musician\", Gender: \"both\" },\n\t{ Article: \"a\" , Name: \"princess\", Gender: \"female\" },\n\t{ Article: \"a\" , Name: \"prince\", Gender: \"male\" }\n ];\n\n // List of all adjectives of the Hero\n var rHeroMainAdjectiveList = [\n\t{ Article: \"a\", Word: \"brave\" },\n\t{ Article: \"a\", Word: \"wealthy\" },\n\t{ Article: \"a\", Word: \"rich\" },\n\t{ Article: \"a\", Word: \"poor\" }\n ];\n\n var rHeroSecondaryAdjectiveList = [\n\t{ Male: \"kind to everyone\", Female: \"kind to everyone\" },\n\t{ Male: \"madly in love with his wife\", Female: \"madly in love with her husband\" },\n\t{ Male: \"handsome\", Female: \"beautiful\" }\n ];\n\n // List of all bad people (read: Villains)\n var rVillainList = [\n\t{ Article: \"a\" , Name: \"warlock\" },\n\t{ Article: \"a\" , Name: \"necromancer\" },\n\t{ Article: \"a\" , Name: \"ghost\" },\n\t{ Article: \"a\" , Name: \"demon\" },\n\t{ Article: \"a\" , Name: \"goblin\" },\n\t{ Article: \"a\" , Name: \"troll\" },\n\t{ Article: \"a\" , Name: \"monster\" },\n\t{ Article: \"a\" , Name: \"dwarf\" },\n\t{ Article: \"a\" , Name: \"giant\" },\n\t{ Article: \"a\" , Name: \"barbarian\" },\n\t{ Article: \"a\" , Name: \"grook\" },\n\t{ Article: \"a\" , Name: \"rogue\" },\n\t{ Article: \"a\" , Name: \"bandit\" },\n\t{ Article: \"a\" , Name: \"rascal\" },\n\t{ Article: \"a\" , Name: \"scoundrel\" },\n\t{ Article: \"an\", Name: \"orc\" },\n\t{ Article: \"an\", Name: \"ogre\" },\n\t{ Article: \"a\" , Name: \"soldier\" },\n\t{ Article: \"a\" , Name: \"warrior\" },\n\t{ Article: \"a\" , Name: \"fighter\" },\n\t{ Article: \"a\" , Name: \"viking\" },\n\t{ Article: \"a\" , Name: \"mage\" },\n\t{ Article: \"a\" , Name: \"villain\" },\n\t{ Article: \"an\", Name: \"archer\" },\n\t{ Article: \"a\" , Name: \"phantom\" }\n ];\n\n // List of possible wording for \"kill\"\n var rKillList = [\n\t\"killed\",\n\t\"murdered\",\n\t\"slayed\",\n\t\"assassinated\"\n ];\n\n // List of possible wording for \"flee\"\n var rFleeList = [\n\t\"fled\",\n\t\"fled in terror\",\n\t\"escaped\",\n\t\"manged to escape\",\n\t\"was able to flee\"\n ];\n\n // List of possible wording for \"cheat\"\n var rCheatList = [\n\t\"cheated\",\n\t\"tricked\",\n\t\"was able to trick\",\n\t\"managed to cheat\",\n\t\"fooled\"\n ];\n\n\n // Plot: Destroy; List of ways to destroy an object\n var rDestroyList = [\n\t\"destroy\",\n\t\"ruined\",\n\t\"wrecked\",\n\t\"smashed\",\n\t\"demolished\"\n ];\n\n // Plot: Destroy; List of objects that can be destroyed\n var rDestroyObjectList = [\n\t\"house\",\n\t\"garden\",\n\t\"doghouse\",\n\t\"temple\",\n\t\"clock\",\n\t\"field\",\n\t\"farm\",\n\t\"tower\",\n\t\"building\",\n\t\"residence\",\n\t\"domicile\",\n\t\"place of birth\",\n\t\"home\",\n\t\"hovel\",\n\t\"hut\",\n\t\"flat\",\n\t\"flatlet\",\n ];\n\n\n // Plot: Witch; List of ways to cast the spell\n var rWitchList = [\n\t\"enchanted\",\n\t\"spellbound\",\n\t\"bewitched\",\n\t\"entranced\"\n ];\n\n // Plot: Witch; List of ways to end the spell\n var rWitchEndList = [\n\t\"freed\",\n\t\"ended the spell casted on\",\n\t\"ended the enchantment of\"\n ];\n\n // Plot: Kidnap; List of ways to be kidnaped\n var rKidnapList = [\n\t\"kidnapped\",\n\t\"abducted\",\n\t\"carried off\"\n ];\n\n // List of final moments\n var rFinalMoment = [\n\t\"Then\",\n\t\"Finally\",\n\t\"Ultimately\",\n\t\"In the end\",\n\t\"Thereupon\",\n\t\"Thereat\",\n\t\"After that\"\n ];\n\n // List of \"One day\" events\n var rOneDayList = [\n\t\"One day\",\n\t\"There came a day\",\n\t\"One night\"\n ];\n\n // List of all possible relatives\n var rRelativeList = [\n\t\"dog\",\n\t\"cat\",\n\t\"mother\",\n\t\"father\",\n\t\"grandfather\",\n\t\"grandmother\",\n\t\"brother\",\n\t\"son\",\n\t\"sister\",\n\t\"daughter\",\n\t\"friend\",\n\t\"mate\",\n\t\"uncle\",\n\t\"aunt\",\n\t\"son-in-law\",\n\t\"dauther-in-law\",\n\t\"goldfish\",\n\t\"lover\",\n\t\"lawyer\",\n\t\"helper\"\n ];\n\n // List of possible weapons\n var rWeaponList = [\n\t\"bastard sword\",\n\t\"dagger\",\n\t\"shovel\",\n\t\"rifle\",\n\t\"magnum\",\n\t\"UZI\",\n\t\"AK-47\"\n ];\n\n\n var rStory = []; // Stores the actual story and is returned by GetStoryText\n\n // Name : sprintf\n // Parameters : At least 2 parameters are required. 1 as the actual message, and another for the content.\n // More values have to be added in case of more placeholders.\n // Description: This function replaces placeholders acording to their type. This way it's possible\n // to format a string the way the user wants it.\n // Disclaimer : This function is (C) 2006 by Naden Badalgogtapeh. The source can be found at\n // http://www.naden.de/blog/javascript-printf\n function sprintf() {\n\tif (sprintf.arguments.length < 2) {\n\t return;\n\t}\n\n\tvar data = sprintf.arguments[0];\n\n\tfor (var k = 1; k < sprintf.arguments.length; ++k) {\n\n\t switch (typeof (sprintf.arguments[k])) {\n\t case 'string':\n\t\tdata = data.replace(/%s/, sprintf.arguments[k]);\n\t\tbreak;\n\t case 'number':\n\t\tdata = data.replace(/%d/, sprintf.arguments[k]);\n\t\tbreak;\n\t case 'boolean':\n\t\tdata = data.replace(/%b/, sprintf.arguments[k] ? 'true' : 'false');\n\t\tbreak;\n\t default:\n\t\t/// function | object | undefined\n\t\tbreak;\n\t }\n\t}\n\treturn data;\n }\n\n\n // Name : rRandom\n // Parameters : This function requires 2 parameters:\n // - aMin (Integer); The lowest possible number\n // - aMax (Integer); The highest possible number\n // Description: Generates a random number and returning it.\n // Disclaimer : Exchanged this function with a more reliable solution.\n // The new version is taken from\n // http://www.naden.de/blog/zufallszahlen-in-javascript-mit-mathrandom\n // Authors are:\n // - (C) 2006 by Naden Badalgogtapeh\n // - (C) 2008 by batzee\n // - (C) 2012 by MHN\n function rRandom(aMin, aMax) {\n\tvar lMin = Math.floor( parseInt( aMin ) );\n\tvar lMax = Math.floor( parseInt( aMax ) );\n\n\tif ( lMin > lMax) {\n\t return rRandom( lMax, lMin ); // This is a suggestion from MHN\n\t}\n\n\tif ( lMin == lMax ) {\n\t return lMin;\n\t}\n\n\tvar lRandomNumber;\n\n\t// Prevent that we go over the destined area\n\tdo {\n\t lRandomNumber = Math.random();\n\t}\n\twhile( lRandomNumber == 1.0 );\n\t// End of prevention\n\n\treturn lMin + parseInt( lRandomNumber * ( lMax-lMin + 1 ) );\n }\n\n\n // Name : NewStory\n // Parameters : aStoryMode (optional; string) - In case you want\n // a specific kind of story. Can be ignored otherwise.\n // Description: Creates a plot and builds a story upon the plot.\n // Uses a random hero and a random villain for this.\n // The story is stored in the private variable rStory and can\n // be called by using the GetStoryText-routine\n this.createStory = function ( aStoryMode ) {\n\t// General information about the story\n\tvar lPlotMode = rPlotList[ rRandom( 1, rPlotList.length ) - 1 ];\n\tvar lIntro = rIntroList[ rRandom( 1, rIntroList.length ) - 1 ];\n\tvar lSubIntro = rRandom( 1, 99 );\n\tvar lPlotEndMode = rPlotEndList[ rRandom( 1, rPlotEndList.length ) - 1 ];\n\tvar lHeroID = rRandom( 1, rHeroList.length ) - 1;\n\tvar lVillainID = rRandom( 1, rVillainList.length ) - 1;\n\n\tvar lKill = rKillList[ rRandom( 1, rKillList.length ) - 1 ]; // Plot-End: kill\n\tvar lWeapon = rWeaponList[ rRandom( 1, rWeaponList.length ) - 1 ]; // Plot-End: kill_weapon\n\tvar lFlee = rFleeList[ rRandom( 1, rFleeList.length ) - 1 ]; // Plot-End: flee\n\tvar lDayMode = rRandom( 1, rOneDayList.length ) - 1;\n\tvar lFinal = rFinalMoment[ rRandom( 1, rFinalMoment.length ) - 1 ];\n\n\tvar lKidnapWay = rRandom( 1, rKidnapList.length ) - 1; // Plot: Kidnap\n\tvar lDestroyWay = rRandom( 1, rDestroyList.length ) - 1; // Plot: Destroy\n\tvar lWitchWay = rRandom( 1, rWitchList.length ) - 1; // Plot: Witch\n\tvar lWitchEnd = rWitchEndList[ rRandom( 1, rWitchEndList.length ) - 1 ];\n\n\tvar lObjectID = rRandom( 1, rDestroyObjectList.length ) - 1; // Plot: Destroy\n\tvar lRelativeID = rRandom( 1, rRelativeList.length ) - 1; // Plot: Revenge\n\n\tvar lHeroGender = rHeroList[lHeroID].Gender;\n\tvar lHeroAlternateGender;\n\tvar lHeroName = rHeroList[lHeroID].Name;\n\tvar lHeroArticle = rHeroList[lHeroID].Article;\n\tvar lHeroMainAdjective = rHeroMainAdjectiveList[ rRandom( 1, rHeroMainAdjectiveList.length ) - 1 ];\n\tvar lHeroSecondaryAdjective;\n\tvar lHeroSecondary = rHeroSecondaryAdjectiveList[ rRandom( 1, rHeroSecondaryAdjectiveList.length ) - 1 ];\n\tvar lCheatWord = rCheatList[ rRandom( 1, rCheatList.length ) - 1 ];\n\n\tvar lVillainName = rVillainList[lHeroID].Name;\n\tvar lVillainArticle = rVillainList[lHeroID].Article;\n\n\tif ( aStoryMode == \"destroy\" ) lPlotMode = \"destroy\";\n\tif ( aStoryMode == \"kidnap\" ) lPlotMode = \"kidnap\";\n\tif ( aStoryMode == \"mindcontrol\" ) lPlotMode = \"witch\";\n\tif ( aStoryMode == \"revenge\" ) lPlotMode = \"revenge\";\n\n\n\tswitch ( lHeroGender ) {\n\tcase \"both\":\n\t lHeroGender = \"He\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Male;\n\t if ( rRandom( 1, 100 ) > 50 ) {\n\t\tlHeroGender = \"She\";\n\t\tlHeroSecondaryAdjective = lHeroSecondary.Female;\n\t }\n\t break;\n\tcase \"female\":\n\t lHeroGender = \"She\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Female;\n\t break;\n\tcase \"male\":\n\t lHeroGender = \"He\";\n\t lHeroSecondaryAdjective = lHeroSecondary.Male;\n\t break;\n\t}\n\tlHeroAlternateGender = \"his\";\n\tif ( lHeroGender.toLowerCase() == \"she\" ) lHeroAlternateGender = \"her\";\n\n\n\t// Preparing the story and the plot\n\trStory = [];\n\tvar lPlot = [];\n\tswitch ( lPlotMode ) {\n\tcase \"destroy\":\n\t lPlot.push( \"destroy\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\n\tcase \"kidnap\":\n\t lPlot.push( \"kidnap\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\n\tcase \"witch\":\n\t lPlot.push(\"witch\");\n\t lPlot.push(\"cheat\");\n\t lPlot.push(\"entwitch\");\n\t break;\n\n\tcase \"revenge\":\n\t lPlot.push( \"revenge\" );\n\t if (rRandom(1, 100) >= 50) {\n\t\tlPlot.push(\"cheat\");\n\t }\n\t break;\n\t}\n\tlPlot.push( lPlotEndMode );\n\n\n\t// Adding the intro\n\tvar lPlotLine = sprintf(\"%s there lived %s %s.\", lIntro, lHeroArticle, lHeroName);\n\tif ( lSubIntro > 33 ) lPlotLine = sprintf(\"%s there was %s %s %s.\", lIntro, lHeroMainAdjective.Article, lHeroMainAdjective.Word, lHeroName );\n\tif ( lSubIntro > 66 ) lPlotLine = sprintf(\"%s there was %s %s who was %s.\", lIntro, lHeroArticle, lHeroName, lHeroSecondaryAdjective );\n\trStory.push( lPlotLine );\n\n\t// Adding the rest of the plot\n\tfor (var lIndex = 0; lIndex < lPlot.length; lIndex++) {\n\n\t switch ( lPlot[ lIndex ] ) {\n\t case \"cheat\":\n\t\tlPlotLine = sprintf(\"%s %s the %s.\", lHeroGender, lCheatWord, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"The %s %s the %s.\", lHeroName, lCheatWord, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"destroy\":\n\t\tlPotLine = sprintf(\"%s %s %s %s the %s of the %s.\", rOneDayList[ lDayMode ], lVillainArticle, lVillainName, rDestroyList[ lDestroyWay ], rDestroyObjectList[ lObjectID ], lHeroName );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"entwitch\":\n\t\tlPotLine = sprintf(\"The %s %s the %s.\", lVillainName, lWitchEnd, lHeroName);\n\t\t//if ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"flee\":\n\t\tlPotLine = sprintf(\"%s %s %s.\", lFinal, lHeroGender.toLowerCase(), lFlee );\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s %s.\", lFinal, lHeroName, lFlee );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kidnap\":\n\t\tlPotLine = sprintf(\"%s %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroGender.toLowerCase(), rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rKidnapList[ lKidnapWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kill\":\n\t\tlPotLine = sprintf(\"%s %s %s the %s.\", lFinal, lHeroGender.toLowerCase(), lKill, lVillainName );\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s %s.\", lFinal, lHeroName, lFlee );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"kill_weapon\":\n\t\tlPotLine = sprintf(\"%s %s %s the %s with %s %s.\", lFinal, lHeroGender.toLowerCase(), lKill, lVillainName, lHeroAlternateGender, lWeapon );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"revenge\":\n\t\tlPotLine = sprintf(\"%s %s %s %s the %s of the %s.\", rOneDayList[ lDayMode ], lVillainArticle, lVillainName, lKill, rRelativeList[ lRelativeID ], lHeroName );\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\n\t case \"witch\":\n\t\tlPotLine = sprintf(\"%s %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroGender.toLowerCase(), rWitchList[ lWitchWay ], lVillainArticle, lVillainName);\n\t\tif ( rRandom( 1, 100 ) > 50 ) lPlotLine = sprintf(\"%s the %s was %s by %s %s.\", rOneDayList[ lDayMode ], lHeroName, rWitchList[ lWitchWay ], lVillainArticle, lVillainName);\n\t\trStory.push( lPlotLine );\n\t\tbreak;\n\t };\n\t}\n };\n\n // Name : GetStoryText\n // Parameters : None\n // Description: Returns the stored story as an array where each line is an entry\n this.getStoryText = function () {\n\treturn rStory;\n };\n\n\n // Name : AddHero\n // Parameters : This function requires 3 parameters:\n // - aArticle (string); The article of the hero; Can either be \"a\", \"an\", \"the\"or \"\"\n // - aName (string); the nma or job of the hero\n // - aGender (string); the gender of the hero; Can either be \"male\", \"female\" or \"both\"\n // Description: Adds a new possible hero to the list of heros. The user can define the name/job, the gender and an article\n // which is to be used with the name.\n this.addHero = function (aArticle, aName) {\n\tvar lArticle = aArticle.toLowerCase();\n\tvar lGender = aGender.toLowerCase();\n\n\trHeroList.push( { Article: lArticle, Name: aName, Gender: lGender } );\n };\n\n this.createStory(); // Creatinng a story in advance\n}",
"showInfo() {\n let sp = 25; // Spacing\n push();\n // Vertical offset to center text with the image\n translate(this.x * 2, this.y - 50);\n textAlign(LEFT);\n textSize(20);\n textStyle(BOLD);\n text(movies[this.id].title, 0, 0);\n textStyle(NORMAL);\n text(\"Directed by \" + movies[this.id].director, 0, 0 + sp);\n text(\"Written by \" + movies[this.id].writer, 0, 0 + sp * 2);\n text(\"Year: \" + movies[this.id].year, 0, 0 + sp * 3);\n text(\"Running time: \" + movies[this.id].time + \" min\", 0, 0 + sp * 4);\n // Index of the movie / total movies in the dataset\n text(\"(\" + (this.id + 1) + \"/\" + nMovies + \")\", 0, 0 + sp * 5);\n pop();\n }",
"function DisplayMovieGenres(movie)\n{\n\tvar DivGenres = $(\"#genres\"); \n\tvar DivGenre = '<h2 style=\"margin-left:5px; font-size:15px!important; background-color:#336e7b!important\" class=\"label\">'+movie.name+'</h2>'; \n\tDivGenres.append(DivGenre);\n}",
"create() {\n this.scaleColor = d3.scaleOrdinal().range(getColor(this.color));\n this.canvas = this.mainCanvas();\n this.transformGroup = this.transformGroup();\n this.addTitles(this.data.title, this.data.subtitle);\n this.addPieArcs(this.data.percentages);\n this.addSideStrokes();\n\n return this;\n }",
"function PlaylistEntry(title) {\n\t// alert(\"create new playlist entry.\");\n\tthis.title = title;\n\tthis.url = \"\";\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add IDs to elements that are currently active | function tocSetActiveElementIDs(activeHeadings) {
// Clear existing IDs
const tocActiveIDs = ['toc-active-current',
'toc-active-current-level',];
for (const activeID in tocActiveIDs) {
const elementWithActiveID = document.getElementById( tocActiveIDs[activeID] );
if (elementWithActiveID) {
elementWithActiveID.removeAttribute('id');
}
}
// Get current active element
for (const heading of activeHeadings) {
const currentLevel = tocGetParent( heading );
const depthLevel = parseInt( currentLevel.getAttribute('data-toc-depth') );
// Set toc-active-- IDs
if (depthLevel === activeHeadings.length - 1) {
setID(heading, 'toc-active-current', true, false);
setID(currentLevel, 'toc-active-current-level', true, false);
}
}
} | [
"arrangeId() {\n const rootNode = this.parent.contentDom.documentElement;\n let id = SlideSet.MIN_ID;\n for (let { slideId } of this.selfElement.items()) {\n const oriId = slideId.id;\n const relElements = rootNode.xpathSelect(`.//*[local-name(.)='sldId' and @id='${oriId}']`);\n for (let relIdx in relElements) {\n relElements[relIdx].setAttribute(\"id\", id);\n }\n id++;\n }\n this[$slideAvalidID] = id;\n }",
"function assignIdsToQuestions() {\n for (let i = 0; i < questions.length; i++) {\n (questions[i]).id = '#dropdown' + (i+1);\n }\n}",
"_assignTabIds () {\n this.tabs.forEach(tab => {\n Component.setAttributeIfNotSpecified(tab, this.tabAttribute, Component.generateUniqueId())\n Component.setAttributeIfNotSpecified(tab, 'id', Component.generateUniqueId())\n })\n }",
"function update_active_image_id() {\n var active_img = document.getElementsByClassName(\"big\")[0];\n try {\n active_img_id = active_img.getAttribute('data-img-id');\n } catch (err) {};\n\n }",
"setActivePlayersIds() {\n\t\tlet activePlayersIds = [];\n\t\tthis.table.players.forEach((player) => {\n\t\t\tif (player.active) {\n\t\t\t\tactivePlayersIds.push(player.id);\n\t\t\t}\n\t\t});\n\t\tthis.activePlayersIds = activePlayersIds;\n\t}",
"function addId(){ //Add ID to events, calendar and list\n var cal = document.getElementsByClassName(\"JScal\");\n var eventList = document.getElementsByClassName(\"JSeventList\");\n\n for (i = 0, length = eventList.length; i < length; i++) { //eventList or cal.lenght\n cal[i].href= \"#JSeventID_\" + (i + 1); //Add link to calendar\n eventList[i].id= \"JSeventID_\" + (i + 1); //Add id to list\n }\n }",
"addActiveClass() {\n this.currentInterval = store.get('current-interval');\n const $selectedInterval = this.$intervalsList.find(`li#${this.currentInterval}`);\n this.$intervalsItems.removeClass('selected');\n $selectedInterval.addClass('selected');\n }",
"function genIDs() {\n selectAllH().prop('id', function() {\n // If no id prop for this header, return a random id\n return ($(this).prop('id') === '') ? $(this).prop('tagName') + (randID()) : $(this).prop('id');\n });\n }",
"function getIdSelector(elementId) {\n return \"#\" + elementId.replace(/(:|\\.|\\[|\\])/g, \"\\\\$1\");\n}",
"function addActive (array) {\n array = nodeListToArray(array);\n array.forEach(function (item) {\n add(item, 'is-active');\n });\n}",
"function setListId(string) {\n var new_id_prefix = 'list_id_';\n var new_id = new_id_prefix.concat(string);\n var element = document.getElementsByClassName('shopping_list')[0];\n element.id=new_id;\n}",
"static getParentId(el){\n return $(el).parents('div[class^=\"shiny\"]').prop(\"id\");\n }",
"function setNextItemActive() {\n var items = getItems();\n\n var activeItem = document.getElementsByClassName(\"active\")[0];\n var nextElement = activeItem.nextElementSibling;\n\n if (!nextElement) {\n nextElement = items[0];\n }\n\n changeActiveState(activeItem, nextElement);\n}",
"function updateActiveLink() {\n\tif (this==activeLink){\n\t\treturn;\n\t}\n\t// loops over all li elements\n\tsliderLinks.forEach((link, index) => {\n\t\t// removes 'active' from each\n\t\tlink.classList.remove('active');\n\t\tsliderStack[index].classList.remove('active');\n\t});\n\t// adds 'active' to clicked item\n\tthis.classList.add('active');\n\tsliderStack[sliderLinks.indexOf(this)].classList.add('active');\n\t// stores clicked item\n\tactiveLink = this;\n\tmoveSlides();\n}",
"function addIdSegments(el, nodes, segments) {\n var id_count = 0,\n n = 0;\n while (n < nodes.length) {\n if (nodes[n].hasAttribute(\"id\") && nodes[n].id === el.id) {\n id_count = id_count + 1;\n }\n if (id_count > 1) {\n break;\n }\n n = n + 1;\n }\n if (id_count === 1) {\n // The target element has an ID, that's the last node we need\n if (false && segments.length === 0) {\n segments.unshift(\"//[@id=\\\"\" + el.getAttribute(\"id\") + \"\\\"]\");\n } else {\n segments.unshift(\"id(\\\"\" + el.getAttribute(\"id\") + \"\\\")\");\n }\n return segments.join(\"/\");\n } else {\n segments.unshift(el.localName.toLowerCase() + \"[@id=\\\"\" + el.getAttribute(\"id\") + \"\\\"]\");\n }\n return segments;\n }",
"function globalVariablizeIds (node){ \r\n var snap = XPOrderedSnap(node, 'descendant-or-self::*/@id');\r\n for (var i=0; i < snap.snapshotLength; i++)\r\n {var id = snap.snapshotItem(i).nodeValue;\r\n window[id] = document.getElementById(id);\r\n }\r\n}",
"function changeNoteHighlight(id) {\n\n if (id == undefined) { //remove highlighting from currently highlighted element\n var id = findCurrentNote();\n var sourceElement = findNoteElement(id);\n sourceElement.classList.remove('active-note');\n }\n else { //add highlighting to selected element\n if (id == -1) {\n var note = raw_notes[raw_notes.length-1];\n id = note[\"id\"];\n }\n var targetElement = findNoteElement(id);\n targetElement.classList.add('active-note');\n }\n\n}",
"function tagElementsForReplacement(elements) {\n for (element of elements) {\n element.setAttribute(\"focuspocused\", true);\n }\n }",
"function setActiveBulletClass() {\n for (var i = 0; i < bullets.length; i++) {\n if (slides[i].style['transform'] == 'translateX(0px)') {\n bullets[i].classList.add('active');\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For better user experience I automatically focus on the chat textfield upon pressing a key | function keyPressed() {
if (screen == "game") {
var field = document.getElementById("chatField");
field.focus();
}
if (screen == "lobby") {
var field = document.getElementById("lobby-field");
field.focus();
}
} | [
"function set_msg_focus() {\n\t$('#msg').focus();\n}",
"responding(){\n setTimeout(_=>{\n this.focusInput()\n })\n }",
"function onMessageActive(newval, oldval) {\n if(!newval && !oldval)\n return;\n\n if(newval && !oldval) {\n $scope.focusTextInput();\n }\n }",
"function updChatroomMsgEnter(state){\n $('.messages').on('keypress','#text', function (e) {\n var key = e.which;\n if(key === 13) // the enter key code\n {\n event.preventDefault();\n setUpdatedMessages(state,$('#text').val(),$('.conversation'));\n $('#text').val('');\n }\n });\n}",
"function SetKeyboardFocusHere(offset = 0) {\r\n bind.SetKeyboardFocusHere(offset);\r\n }",
"function scrollToMessage() {\n $('#messages').animate({\n scrollTop: $('#msg-' + $scope.focus).position().top\n }, 500);\n }",
"didFocus () {\n\n }",
"focusInput() {\n if (this.nameInput) {\n this.nameInput.focus();\n }\n }",
"function nameFieldFocus() {\r\n nameField.focus();\r\n }",
"enterXR() {\n if ( this.chatLog ) {\n this.chatLog.input.virtualKeyboardEnabled = true;\n }\n }",
"focusInput(){\n this.amountInput.focus();\n }",
"function firstInputOnFocus() {\r\n\t name.setAttribute(\"autofocus\",true);\r\n}",
"add_focus() {\n this.element.focus();\n }",
"function input_character_keys(key_array_index, event_type, character_key_index, key_code) {\r\n\tkey_array[key_array_index].addEventListener(event_type, function(event) {\r\n\t\tif (event_type == \"keydown\" && document.getElementById(\"mirrored_textarea\") != document.activeElement) {\r\n\t\t\tif (event.key === \" \" || event.key === \"Enter\" || event.key === \"Spacebar\") {\r\n\t\t\t\ttoggle_button(event.target);\r\n\t\t\t\tevent.preventDefault();\r\n\t\t\t\tedit_textarea(character_key_index);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tevent.preventDefault();\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t}\r\n\t});\r\n\r\n\tdocument.addEventListener(\"keydown\", function(event) {\r\n\t\tif (event.defaultPrevented) {\r\n\t\t\treturn; // Do nothing if event already handled\r\n\t\t}\r\n\t\tif (event.code == key_code && modifier_key_pressed == false) {\r\n\t\t\ttoggle_button(event.target);\r\n\t\t\tkey_button_array[key_array_index].classList.add(\"focus\");\r\n\t\t\tsetTimeout(function () {key_button_array[key_array_index].classList.remove(\"focus\");}, 250);\r\n\t\t\tedit_textarea(character_key_index);\r\n\t\t\tevent.preventDefault();\r\n\t\t}\r\n\t});\r\n}",
"function insertText(a) {\n\t$chatline.val($chatline.val()+a).focus();\n}",
"function CLC_SR_SpeakFocus_EventAnnouncer(event){ \r\n if (!CLC_SR_Query_SpeakEvents()){\r\n return true;\r\n }\r\n //Announce the URL bar when focused\r\n if (event.target.id==\"urlbar\"){\r\n CLC_SR_SpeakEventBuffer = event.target.value;\r\n CLC_SR_SpeakEventBuffer = CLC_SR_MSG0010 + CLC_SR_SpeakEventBuffer; \r\n CLC_SR_Stop = true; \r\n window.setTimeout(\"CLC_Shout(CLC_SR_SpeakEventBuffer,1);\", 0);\r\n return true;\r\n } \r\n //Not sure about the rest - none for now\r\n return true;\r\n }",
"activate () {\n this.focus();\n }",
"function SetFocusOnEmail(){\n var emailbox = $j('#mykmx_login .mykmx_body input:first');\n if (emailbox)\n emailbox.focus();\n}",
"function InputText({ userMessage, setUserMessage, sendUserMessages }) {\n return (\n <form className=\"form-input\">\n <input\n className=\"input-text\"\n type=\"text\"\n placeholder=\"Enter a message...\"\n value={userMessage}\n onChange={(e) => setUserMessage(e.target.value)}\n onKeyDown={(e) => (e.key === \"Enter\" ? sendUserMessages(e) : null)}\n />\n <button className=\"button-two\" onClick={(e) => sendUserMessages(e)}>\n <i class=\"fa fa-paper-plane\" aria-hidden=\"true\"></i>\n </button>\n </form>\n );\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
middleware to check req's numbers | function numbersReq(req, res, next) {
console.log(++numberReq);
next();
} | [
"function isValidId(req, res, next) {\n if (!isNaN(req.params.id)) return next();\n next(new Error('Invalid ID'));\n}",
"function validateNumbers() {\n return auctions_id == [0-9]*$ ? axios.post('https://silent-auction-69.herokuapp.com/api/items', auction)\n .then(res => {\n console.log('res:', res)\n })\n .catch(err => {\n console.log('error:', err)\n }) : cogoToast.error('')\n }",
"function bodyHasValidPriceForUpdate(req, res, next) {\n //decronstruct price from request body.\n const { data: { price } = {} } = req.body\n //if price is invalid (price <= 0 OR not an integer), \n //return error status code with message.\n if (res.locals.price <= 0 || typeof res.locals.price !== \"number\") {\n next({\n status: 400,\n message: `price must be an integer greater than $0.`,\n })\n } else {\n //if invalid price, return error status code with message.\n // res.locals.price = price\n return next()\n }\n}",
"function isRequestValid(req){\n return !(req.body === undefined\n || Object.keys(req.body).length < 4\n || !supportedTypes.includes(req.body.type)\n || !activityFields.every(field => req.body.hasOwnProperty(field)));\n}",
"verifyManifoldRequest(req, res, next) {\n verifier.test(req, req._buffer.toString('utf8')).then(next, err => {\n // Verification issue\n logger.warn(`Failed to verify manifold request: %s`, err);\n // Response taken from ruby-sinatra-example:\n res.status(401).send({\n message: 'bad signature'\n });\n });\n }",
"function verifyPID(req, res, callback) {\n const pid = parseInt(req.params.pid, 10);\n \n if (!pid && pid != 0) {\n res.status(400).send(\"Error: Improperly formed request. Missing parameter pid.\");\n }\n else if (!db.posts.feed[pid] || db.posts.feed[pid].isDeleted) {\n res.status(404).send(\"Error: Post not found.\");\n }\n else {\n res.status(200);\n callback();\n }\n}",
"function validate(req) {\n req.checkBody('firstName', 'Invalid firstName').notEmpty();\n req.checkBody('lastName', 'Invalid lastName').notEmpty();\n req.checkBody('dob', 'Date of birth must be in the past').isBefore();\n req.checkBody('password', 'Invalid password').notEmpty();\n req.checkBody('passwordRepeat', 'Invalid password').notEmpty();\n req.checkBody('gender', 'Invalid password').notEmpty();\n}",
"function testifelseServer(req, res) {\n var age = req.body.input.age; // req.body.age create a json\n var returned = common.testifelse({\n \"age\": age\n }); //\n res.send(returned);\n}",
"function inputValidation(req, res, next) {\n\tconst emailRegex = new RegExp(\n\t\t\"^(?=[A-Z0-9][A-Z0-9@._%+-]{5,253}$)[A-Z0-9._%+-]{1,64}@(?:(?=[A-Z0-9-]{1,63}.)\" +\n\t\t\t\"[A-Z0-9]+(?:-[A-Z0-9]+)*.){1,8}[A-Z]{2,63}$\",\n\t\t\"i\"\n\t);\n\n\t// Remove whitespace from beginning and end (better done functionally?)\n\treq.body[\"realname\"] = req.body[\"realname\"].trim();\n\treq.body[\"email\"] = req.body[\"email\"].trim();\n\treq.body[\"subject\"] = req.body[\"subject\"].trim();\n\treq.body[\"msgbody\"] = req.body[\"msgbody\"].trim();\n\n\tif (req.body[\"realname\"].length === 0) {\n\t\tres.sendStatus(400);\n\t\treturn;\n\t}\n\n\tif (req.body[\"email\"].length === 0) {\n\t\tres.sendStatus(400);\n\t\treturn;\n\t}\n\n\tconsole.log(req.body[\"email\"]);\n\n\tif (!emailRegex.test(req.body[\"email\"]) === true) {\n\t\tres.sendStatus(400);\n\t\treturn;\n\t}\n\n\tif (req.body[\"subject\"].length === 0) {\n\t\tres.sendStatus(400);\n\t\treturn;\n\t}\n\n\tif (req.body[\"msgbody\"].length === 0) {\n\t\tres.sendStatus(400);\n\t\treturn;\n\t}\n\n\tnext();\n}",
"function isColumnEqualToNumber(req,column)\n{\n var squery = JSON.stringify(req.params.values)\n squery = squery.substring(1,squery.length-1)\n if(squery.length< column.length+1)\n if(!(column===squery.substring(0,column.length)))\n return false\n if(!(squery.charAt(column.length)==='='))\n return false\n return !isNaN(Number(squery.substring(column.length+1)))\n}",
"function validateObjectIds(req, res, next) {\n // No params\n if (!req || !req.params) {\n return next();\n }\n let valid = true;\n // Check valid object IDs\n _.forEach(req.params, (val, key) => {\n key = key.toLowerCase();\n const idLength = 2;\n try {\n // Make sure we have a valid object ID\n if (key.substring(key.length - idLength) === 'id') {\n // All is an exception for corporate admin\n if (!isValid(val) && val.toLowerCase() !== 'all') {\n valid = false;\n }\n }\n } catch (e) {\n return next(e);\n }\n });\n // Invalid ObjectID passed in\n if (!valid) {\n return res.status(invalidObjectId.code).json(invalidObjectId.res);\n }\n next();\n}",
"tokenPostCheck(req, res, next) {\n let postDataString = '';\n // Get all post data when receive data event.\n req.on('data', (chunk) => {\n postDataString += chunk;\n });\n // When all request post data has been received.\n req.on('end', () => {\n //chuyen doi Object JSON tu chuoi data nhan duoc\n let postDataObject = JSON.parse(postDataString);\n //console.log(postDataObject);\n\n if (postDataObject && postDataObject.Authorization) {\n let token = postDataObject.Authorization;\n //da lay duoc token qua json\n //gan cho req de xu ly token\n req.token=token;\n if (verifyToken(req,res)){\n next();\n }else{\n res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });\n res.end(JSON.stringify({\n success: false,\n message: 'Auth token is not supplied'\n }));\n }\n } else {\n //khong truyen\n res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });\n return res.end(JSON.stringify({\n success: false,\n message: 'Auth token is not supplied ANY!'\n }));\n }\n });\n }",
"function status(req,res,next) {\n\n if ( req.url === \"/ping\" ) {\n res.end(\"ok\");\n } else {\n next();\n }\n }",
"function handleRequest(req, res, urn){\n if(!isRequestValid(req)){\n return res.status(500).json({\n status: 'error',\n message: \"Fields required: \" + activityFields + \" and incorrect type required: Create, Update or Delete\"\n });\n }else return forwardRequest(req, res, urn);\n}",
"function validateToken(req, res) {\r\n var token = getToken(req);\r\n var user = users.getUserByToken(token);\r\n var isValidToken = user != undefined && user != '';\r\n console.log('[validToken] req=' + req.url);\r\n console.log('[validToken] Is Valid Token=%s User=%s', isValidToken, user);\r\n if (!isValidToken) {\r\n invalidToken(req, res);\r\n }\r\n return token;\r\n}",
"static isAuthenticated(req, res, next) {\n const Authorization = req.get('Authorization');\n\n if (Authorization) {\n const token = Authorization.replace('Bearer ', '');\n try {\n // JWTSECRET=some long secret string\n const payload = jwt.verify(token, process.env.JWTSECRET);\n\n // Attach the signed payload of the token (decrypted of course) to the request.\n req.jwt = {\n payload\n };\n\n next();\n } catch {\n // The JSON Web Token would not verify.\n res.sendStatus(401);\n }\n } else {\n // There was no authorization.\n res.sendStatus(401);\n }\n }",
"static async getInfo(req, res, next) {\n const { car_number, slot_number } = req.query\n if (!car_number && !slot_number) {\n throw new FieldRequired('Either car_number or slot_number is required!')\n }\n\n if (slot_number) {\n const carInfo = parkingLot.getInfoBySlotId(slot_number)\n return res.json({ message: \"Fetched car info!\", ...carInfo })\n }\n\n if (car_number) {\n const carInfo = parkingLot.getInfoByCarNumber(car_number)\n return res.json({ message: \"Fetched car info!\", ...carInfo })\n }\n\n }",
"function validateUserId(req, res, next) {\n Users.getById(req.params.id)\n .then((user) => {\n req.user = user;\n next();\n })\n .catch((error) => {\n console.log(error);\n res.status(400).json({ message: \"invalid user id\" });\n });\n}",
"function checkDishId(req, res, next) {\n const dishId = req.params.dishId;\n const {data: {id} } = req.body\n if (\n id !== dishId &&\n id !== null &&\n id !== undefined &&\n id !== \"\"\n ) {\n next({\n status: 400,\n message: `Dish id does not match route id. Dish: ${req.body.data.id}, Route: ${dishId}`,\n });\n }\n return next();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to calculate turn meter tick rate Overrides tickRate attribute for use in Turn Meter calculation | calculateTickRate(enemySpeed){
this.tickRate = Math.round((this.speed / (this.speed + enemySpeed)) * 100);
} | [
"calculateTurnMeter() {\n this.turnMeter += this.tickRate;\n if (this.turnMeter >= 100) {\n this.turnMeter -= 100;\n this.isTurn = true;\n } \n }",
"ticksPerSec () {\n const dt = this.ticks - this.startTick\n return dt === 0 ? 0 : Math.round(dt * 1000 / this.ms()) // avoid divide by 0\n }",
"get framesPerTick() {\n\t\treturn this._framesPerTick;\n\t}",
"function motorGetSpeed() {\n return currentSpeedRpm;\n}",
"get sustainedClockSpeed() {\n return this.getNumberAttribute('sustained_clock_speed');\n }",
"incrementSpeed() {\n\t\t\tswitch (this.speed)\n\t\t\t{\n\t\t\t\tcase 1000:\n\t\t\t\t\tthis.speed = 2000;\n\t\t\t\tbreak;\n\t\t\t\tcase 2000:\n\t\t\t\t\tthis.speed = 5000;\n\t\t\t\tbreak;\n\t\t\t\tcase 5000:\n\t\t\t\t\tthis.speed = 10000;\n\t\t\t\tbreak;\n\t\t\t\tcase 10000:\n\t\t\t\t\tthis.speed = 20000;\n\t\t\t\tbreak;\n\t\t\t\tcase 20000:\n\t\t\t\t\tthis.speed = 50000;\n\t\t\t\tbreak;\n\t\t\t\tcase 50000:\n\t\t\t\t\tthis.speed = 60000; // one second is one minute\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthis.speed = 1000; // one second is one second\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}",
"function speedCalc() {\n\t\t\treturn (0.4 + 0.01 * (50 - invadersAlive)) * difficulty;\n\t\t}",
"function calcMoney(rate) {\n // number of seconds since midnight\n var totalSeconds = (hour() * 60 * 60) + (minute() * 60); \n return (totalSeconds + second()) * rate;\n}",
"get speedVariation() {}",
"calculate() {\n this.times.miliseconds += 1;\n if (this.times.miliseconds >= 100) {\n this.times.seconds += 1;\n this.times.miliseconds = 0;\n }\n if (this.times.seconds >= 60) {\n this.times.minutes += 1;\n this.times.seconds = 0;\n }\n }",
"getSpeed() {\n return this.model ? this.model.getCurrentSpeedKmHour() : null;\n }",
"function getCalc10HoureBase(){\n updateCalcUpdate();\n\n return base10time;\n}",
"function YInputChain_set_refreshRate(newval)\n { var rest_val;\n rest_val = String(newval);\n return this._setAttr('refreshRate',rest_val);\n }",
"setTicksPassed(newTicksPassed) {\n this.ticksPassed = newTicksPassed\n }",
"function getRadians(ts, unit)\n{\n //In order to orient the start of the clock's hands at 12, the\n //clock's hand needs to be rotated by 90 degrees, or PI/2\n var offset = Math.PI/2;\n var radians = 0 + offset;\n var offset_ms, offset_s,offset_mins,offset_hrs;\n //The clock's hands move in the opposite direction of the unit circle.\n //Each incremental movement of the hand must be subtracted from 2 pi.\n switch (unit) {\n case \"ms\":\n offset_ms = (2*Math.PI)-((ts.ms/1000)*(2*Math.PI));\n radians += offset_ms;\n break;\n case \"s\":\n //The offset for seconds written as is allow for the second\n //hand to \"tick\". An adjustment to allow for continuous movement\n //is further below and is conditionally\n offset_s = (2*Math.PI)-((ts.s/60)*(2*Math.PI));\n radians += offset_s;\n break;\n case \"mins\":\n offset_mins = (2*Math.PI)-((ts.mins/60)*(2*Math.PI));\n radians += offset_mins;\n //minutes are adjusted by both the amount of seconds that have passed\n //for the given minute and the portion of milliseconds\n //that have passed for the given second\n offset_s = ((2*Math.PI)*ts.s)/(Math.pow(60,2));\n offset_ms =((2*Math.PI)*ts.ms)/(1000*Math.pow(60,2));\n radians -= offset_s + offset_ms;\n break;\n case \"hrs\":\n\n offset_hrs = (2*Math.PI)-((ts.hrs/12)*(2*Math.PI));\n radians += offset_hrs;\n //hours are adjusted by the combined minutes that have passed for the\n //hour, the portion of seconds that have passed for the minute, and\n //the portion of milliseconds that have passed for the second\n offset_mins = ((2*Math.PI)*ts.mins)/(Math.pow(60,2));\n offset_s = ((2*Math.PI)*ts.s)/(Math.pow(60,3));\n offset_ms = ((2*Math.PI)*ts.ms)/(1000*Math.pow(60,3));\n radians -= offset_mins + offset_s + offset_ms;\n break;\n default:\n radians = radians;\n }\n //Incremental adjustments are to be made to each of the hands based on\n //how much time has elapsed for each smaller unit of measurement\n if (ts.type == 0)\n {\n if (unit==\"s\") {\n //seconds are adjusted by the total amount of ms that have passed\n //for the given second\n radians -= ((2*Math.PI)*ts.ms)/(1000*60);\n }\n }\n return radians;\n}",
"yTickDelta() {\n return 1;\n }",
"async dsBlockRate() {\n return await this.baseJsonRpcRequest('GetDSBlockRate');\n }",
"updateThrust() {\n this._thrust = this.fuel * 0.04;\n }",
"get KM_PER_AU() {\n return (this.CM_PER_AU / this.CM_PER_KM);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
resetSampleOver : PlayList > PlayList | resetSampleOver() {
this.audioOver.pause()
this.audioOver.currentTime = 0
} | [
"function resetPlayed() {\n for (i = 0; i < videoList.length; i++) {\n videoList[i][1] = false;\n }\n}",
"sampleOver() {\n this.audioOver.play()\n this.pause()\n this.resetSong()\n this.setState({elapsedTime: 30000})\n }",
"loadSampleOver() {\n const audioOver = this.audioOver\n\n audioOver.defaultPlaybackRate = 1.0\n audioOver.src = db.alerts[0].src\n }",
"initiateSampleRemoval() {\n for ( let i = 0; i < this.skaterSamples.length; i++ ) {\n if ( !this.skaterSamples.get( i ).removeInitiated ) {\n this.skaterSamples.get( i ).initiateRemove();\n }\n }\n }",
"reset() {\n const _ = this;\n _._counter = _._startCount;\n }",
"resetStats() {\n\t\tthis.gameDataList = [];\n\t\tthis.curGameData = null;\n\t}",
"resetSong() {\n this.audio.currentTime = 0\n }",
"function reset_unit_anim_list()\n{\n for (unit_id in units) {\n var punit = units[unit_id];\n punit['anim_list'] = [];\n }\n anim_units_count = 0;\n}",
"function resetThresholds() {\n \taccumDiff = 0;\n \taccumAmp = 0;\n \tsampleReadRemaining = sampleDecisionThreshold;\n}",
"reset(){\n this.setSpeed();\n this.setStartPosition();\n }",
"function resetOpp(){\n $(\"#opponent-pic\").replaceWith(originalStateOppPic.clone(true));\n $(\"#oppStats\").replaceWith(originalStateOppStats.clone(true));\n players.finishGame = false;\n players.winsCount++;\n \n}",
"resetStats_() {\n this.mediaBytesTransferred = 0;\n this.mediaRequests = 0;\n this.mediaTransferDuration = 0;\n this.mediaSecondsLoaded = 0;\n }",
"resetOnDemandBuffer()\n {\n const video = this.playBuffer();\n this._pendingOnDemandDeletes = [];\n for (var rangeIdx = 0; rangeIdx < video.buffered.length; rangeIdx++)\n {\n let start = video.buffered.start(rangeIdx);\n let end = video.buffered.end(rangeIdx);\n this.deletePendingOnDemand([start, end]);\n }\n }",
"reset(){\n this._input = null;\n this._output = null;\n }",
"reset(){\n\t\tlet audio = document.querySelector(\"audio\")\n\t\taudio.pause();\n\t\taudio.currentTime=0;\n\t\tthis.setState(defaultState);\n\t}",
"function resetMatchedCards() {\n matchedCards = [];\n}",
"resetEverything() {\n this.resetLoader();\n this.remove(0, Infinity);\n }",
"function resetArray(){\n const newArray = [];\n //populate the new away array\n for(let i = 0; i < arraySize; i++){\n newArray.push(randomIntFromInterval(10,500));\n }\n setArray(newArray);\n }",
"reset() {\r\n\t\tthis.number = this.props.index + 1\r\n\t\tthis.counters = {\r\n\t\t\tfigure: 0\r\n\t\t}\r\n\t\t// TODO: Incorporate equation numbers.\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getDiffWords takes in two sentences and returns and an array of changedObjects i.e. words that are changed from the original sentences | function getDiffWords(expected, actual) {
let array = JsDiff.diffWords(expected, actual);
var ans = [];
for (var i = 0; i < array.length; i ++) {
if (!(array[i].added === undefined && array[i].removed === undefined)) {
//sentences with changes
ans.push(array[i]);
}
}
return ans;
} | [
"function compareChangedWords(user, exp) {\n //inputs [user] and [exp] are arrays\n let userArray = [];\n let expArray = [];\n\n user.forEach(function(data) {\n userArray.push(JSON.stringify(data));\n })\n\n exp.forEach(function(data) {\n expArray.push(JSON.stringify(data));\n })\n\n let ans = JsDiff.diffArrays(userArray, expArray);\n let implementedChanges = []; //a pair of added and removed values\n let unimplementedChanges = [];\n let unnecessaryChanges = [];\n\n for (let i = 0; i < ans.length; i++) {\n if ((ans[i].added === undefined && ans[i].removed === true)) {\n let changes = ans[i].value;\n changes.forEach(function(change) {\n change = JSON.parse(change);\n delete change[\"count\"];\n unnecessaryChanges.push(change);\n })\n } else if ((ans[i].added === true && ans[i].removed === undefined)) {\n let changes = ans[i].value;\n changes.forEach(function(change) {\n unimplementedChanges.push(JSON.parse(change));\n })\n } else {\n let changes = ans[i].value;\n changes.forEach(function(change) {\n implementedChanges.push(JSON.parse(change));\n })\n }\n }//end for loop\n\n let implementedArray = [];\n for (let i = 0; i < implementedChanges.length - 1; i++) {\n //make sure every 'removed' is followed by an 'added'\n if (implementedChanges[i].removed === true && implementedChanges[i+1].added === true) {\n let pair = {\n 'removed': implementedChanges[i].value,\n 'added': implementedChanges[i+1].value,\n 'concept': parseInt(wordToConceptCode[implementedChanges[i].value])\n }\n implementedArray.push(pair);\n }\n }\n\n\n let unimplementedArray = [];\n for (let i = 0; i < unimplementedChanges.length - 1; i++) {\n //make sure every 'removed' is followed by an 'added'\n if (unimplementedChanges[i].removed === true && unimplementedChanges[i+1].added === true) {\n let pair = {\n 'to_remove': unimplementedChanges[i].value,\n 'to_add': unimplementedChanges[i+1].value,\n 'concept': - parseInt(wordToConceptCode[unimplementedChanges[i].value])\n }\n unimplementedArray.push(pair);\n }\n }\n return {\n 'implemented_changes': implementedArray,\n 'unimplemented_changes': unimplementedArray,\n 'unnecessary_changes': unnecessaryChanges\n }\n}",
"function calcDiff(oldText,newText) {\n let i=0;j=0;\n while(newText[i] == oldText[i] && i < newText.length) i++\n const common = oldText.slice(0,i)\n oldText = oldText.slice(i); newText = newText.slice(i);\n while(newText[newText.length-j] == oldText[oldText.length-j] && j < newText.length) j++\n return {firstDiff: i, common, oldText: oldText.slice(0,-j+1), newText: newText.slice(0,-j+1)}\n }",
"function compareBySentences(student, rawHTML) {\n let correct = htmlToPassage(rawHTML, true);\n let wrong = htmlToPassage(rawHTML, false);\n correct = passageToSentences(correct);\n wrong = passageToSentences(wrong);\n user = passageToSentences(student);\n\n let changes = {};\n for (let i in correct) {\n let diff_expected = getDiffWords(correct[i], wrong[i]);\n let diff_actual = getDiffWords(user[i], wrong[i]);\n changes[i] = compareChangedWords(diff_actual, diff_expected);\n }\n return changes;\n}",
"function FilterStopWords(wordArray) {\n // get the common words, define storages for uncommon words\n let commonWords = GetStopWords();\n let commonObj = {};\n let uncommonArr = [];\n\n for (i = 0; i < commonWords.length; i++) {\n // we've got an object with all of the common words inside of it \n commonObj[commonWords[i].trim()] = true;\n }\n\n for (i = 0; i < wordArray.length; i++) {\n // we get every word in our book, trim the spaces and lowercase it \n word = wordArray[i].trim().toLowerCase();\n\n // if the passed in word DOESNT MATCH the word in object commonObj, we add it to our uncommonArr array\n if (!commonObj[word]) {\n uncommonArr.push(word);\n }\n }\n // this is now our filtered array, clean of any common word\n return uncommonArr;\n}",
"diffEntities(a, b) {\n return Utils_1.Utils.diff(this.prepareEntity(a), this.prepareEntity(b));\n }",
"function getWords(data) {\n var arr = [];\n var diffs = setupDifficulty();\n\n for (var c in data.stories) {\n if (interests.Interests[c].enabled == 'checked') {\n for (var s in data.stories[c]) {\n for (var t in data.stories[c][s]) {\n switch (data.stories[c][s][t].difficulty) {\n case 'easy':\n if (diffs[0])\n addWords(data.stories[c][s][t].words[0], arr);\n break;\n case 'medium':\n if (diffs[1])\n addWords(data.stories[c][s][t].words[0], arr);\n break;\n case 'hard':\n if (diffs[2])\n addWords(data.stories[c][s][t].words[0], arr);\n break;\n }\n }\n }\n }\n }\n\n arr.sort(compareWord);\n var obj = {};\n obj.words = arr;\n return obj;\n}",
"function getMatches(stringObject) {\n// For each word in a string...\n for (r = 0; r < stringObject.firstStringWords.length; r++) {\n // Compare it to each word in the next string in the array.\n for (j = 0; j <= stringObject.secondStringWords.length; j++) {\n if (stringObject.firstStringWords[r] === stringObject.secondStringWords[j]) {\n stringObject.matchedPhrases.push(stringObject.firstStringWords[r])\n }\n }\n }\n // Removes smaller matches and just keeps the largest match found.\n stringObject.matchedPhrases = reduceMatches(stringObject.matchedPhrases)\n\n // Count matches.\n stringObject.count = stringObject.matchedPhrases.length\n\n // Calculate a percentage that each string is similar to one another.\n let matchedWordCount = 0\n if (stringObject.matchedPhrases.length !== 0) {\n matchedWordCount = stringObject.matchedPhrases.join(\" \").split(\" \").length\n }\n const allWordCount = stringObject.firstString.split(\" \").length\n stringObject.percentMatch = (Math.round((matchedWordCount/allWordCount) * 100) / 100)\n\n // Remove properties from the comparison that we don't want to output.\n delete stringObject.firstStringWords\n delete stringObject.secondStringWords\n\n return stringObject\n}",
"function mergeGettextArrays(po, pot) {\n\t// Holder array for valid strings\n\tvar filteredPo = {};\n\n\t// Iterate POT translations (only valid ones)\n\tObject.keys(pot.translations[\"\"]).forEach(function (key) {\n\t\t// If translation is found..\n\t\tif (po.translations[\"\"].hasOwnProperty(key)) {\n\t\t\t// Copy it back\n\t\t\tfilteredPo[key] = po.translations[\"\"][key];\n\t\t} else {\n\t\t\t// ..else, copy the pot (untranslated) version\n\t\t\tfilteredPo[key] = pot.translations[\"\"][key];\n\t\t}\n\t});\n\t// Replace the translations with the filtered ones and return\n\tpo.translations[\"\"] = filteredPo;\n\treturn po;\n}",
"splitTextSentences(text) {\n const sentences = [];\n const splitText = text.split(SENTENCE_SPLIT_REGEX);\n let currentSentence = splitText[0].replace(/^\\s+/, '');\n for (let i = 1; i < splitText.length; i += 1) {\n const chunk = splitText[i].replace(/^\\s+/, '');\n if (!chunk) continue;\n if (chunk.match(SENTENCE_PUNCT_MATCH_REGEX)) {\n currentSentence += chunk;\n } else {\n sentences.push(currentSentence);\n currentSentence = chunk;\n }\n }\n sentences.push(currentSentence);\n return sentences;\n }",
"function refine(sentences, generate) {\n console.log('refine')\n return sentences.reduce((syllables, sentence, i) => {\n return syllables.concat(generate(sentence).syllables.map(syllable => ({ ...syllable, sentence: i })))\n }, [])\n}",
"function diff(A, B, options, ready){\n // h is a hashtable for the texts in question. It is going to have an element\n // for each word in A and each word in B\n var trimSpace = !!options.trimSpace\n , ignoreCase = !!options.ignoreCase\n \n // h may provide a good opportunity to make use of levelup/leveldb.\n var h = levelup(\"./data_hash\")\n , aggregate_emitter = new EE\n , emitterA = new EE\n , emitterB = new EE\n , lastUSedCode\n , dataA = false\n , dataB = false\n\n diffcodes(A, h, trimSpace, ignoreCase)\n diffcodes(B, h, trimSpace, ignoreCase)\n h.on(\"put\", function(key, value){\n lastUsedCode = value\n })\n\n emitterA.on(\"code\", function(codes) {\n readyA = true \n this.emit('data', new DiffData(codes))\n (dataA && dataB) && createDifs(dataA, dataB)\n })\n\n emitterB.on(\"code\", function(codes) {\n readyB = true\n this.emit(\"data\", new DiffData(codes))\n (dataA && dataB) && createDifs(dataA, dataB)\n })\n\n function createDiffs(dataA, dataB) {\n var max = dataA.length + dataB.length + 1\n , downvector = new Array(2 * max + 2)\n , upvector = new Array(2 * max + 2)\n lcs(dataA, 0, dataB, 0, downvector, upvector)\n optimize(dataA)\n optimize(dataB)\n\n ready(creatediffs(dataA, dataB))\n }\n \n // hashes textlines to number for ease of references\n function diffcodes(text, emmitter, h, trimSpace, ignoreCase) {\n\n var line_emitter = new EE\n , lines\n , codes\n\n text = text.replace(\"\\r\", \"\")\n lines = text.split(\"\\n\", \"\")\n\n codes = new Array(lines.length)\n\n // I'm using the emitter here essentially to avoid nesting scope-- We\n // shouldn't run out of heap just because the file gets big.\n line_emitter.on('lines', encode)\n encode(lines)\n\n // basically for each line, try to read it out of the db. If you fail, then\n // write it to the db instead. \n\n // the wrinkle is that I'm using leveldb-- writes and reads are async,\n // hence the recursive function below which will wait for the async operation to\n // finish before firing the next one in the series.\n\n // this wont be faster than using regular old js objects, but it does have\n // some nice properties.\n function encode(lines) {\n var ready = true\n\n if (lines.length = 0) {\n emitter.emit(\"codes\", codes)\n return\n }\n\n var s = lines.unshift()\n\n if (trimSpace) {\n s.trim()\n }\n \n if (ignoreCase) {\n s = s.toLowerCase()\n }\n\n h.get(s, {}, function(error, data){\n // will return an error if the key does not exist\n if (err){\n h.put(s, lastUsedCode, function(err, dat){\n assert.ok(!err, \"There was an error writing to the DB \\n\" + err)\n console.log(dat) // what the hell is this going to be?\n codes[i] = lastUsedCode\n line_emitter.emit('lines', lines)\n })\n } else {\n codes[i] = data\n line_emitter.emit('lines', lines)\n }\n })\n }\n }\n\n // If a sequence of modified lines starts with a line that contains the same content\n // as the line that appends the changes, the difference sequence is modified so that the\n // appended line and not the starting line is marked as modified.\n // This leads to more readable diff sequences when comparing text files.\n\n // arguments: \n // `data` : a DiffData object\n\n // side-effects:\n // modifies the `data` method in place.\n\n // returns: \n // undefined\n function optimize(data) {\n var start_position, end_position\n\n start_position = 0\n while (start_position < data.length) {\n while ((start_position < data.length) && (data.modified[start_position] == false))\n start_position++;\n end_position = start_position;\n while ((end_position < data.length) && (data.modified[end_position] == true))\n end_position++;\n if ((end_position < data.length) && (data.data[start_position] == data.data[end_position])) {\n data.modified[start_position] = false;\n data.modified[end_position] = true;\n } else {\n start_position = end_position;\n } // if\n } // while\n }\n}",
"function tokenize($text) {\n\tvar tokens = [], lemmatokens = [];\n\tvar doc = nlp($text);\n\tvar sentences = doc.sentences().json();\n\t//console.log(sentences)\n\n\t// each sentence in semantic\n\tsentences.forEach(obj => {\n\t\tlet sentence = obj.text.replace(/[.]/g, '');\t// clear .\n\t\tlet subsentences = sentence.split(/[,?!:;()\\[\\]\"]/);\n\n\t\t// sub sentence (smallest unit for n-gram calculation)\n\t\tsubsentences.forEach(value => {\n\t\t\tlet subsentence = value.trim();\n\t\t\tif (subsentence === '') return;\n\n\t\t\t// normalize word\n\t\t\tlet normsentence = normalize(subsentence);\n\n\t\t\t// lemmatization\n\t\t\tlet lemmasubsentence = lemmatize(normsentence);\n\n\t\t\t// fin\n\t\t\ttokens.push(normsentence.split(' '));\n\t\t\tlemmatokens.push(lemmasubsentence.split(' '));\n\t\t});\n\t});\n\n\t//console.log(tokens);\n\t//console.log(lemmatokens);\n\treturn [tokens, lemmatokens];\n}",
"function getWords() {\n\t\tvar raw = Util.txt.getInputText();\n\t\tvar cleanText = Util.txt.clean(raw);\n\t\t\tcleanText = cleanText.toLowerCase();\n\t\t\tcleanText = cleanText.replace(/[\\t\\s\\n]/g,\" \");\n\t\t\tcleanText = cleanText.replace(/[ ]{2,}/g,\" \");\n\t\tvar words = cleanText.split(\" \");\n\t\t\twords = words.sort();\n\t\treturn Util.gen.unique(words);\n\t}",
"words(content) {\n //@TODO\n let content_array = content.split(/\\s+/);\n const normalized_content = content_array.map((w)=>normalize(w));\n const words = normalized_content.filter((w) => !this.noise_w_set.has(w)); \n return words;\n }",
"function lemmatize($text) {\n\tvar text = $text;\n\tvar doc = nlp($text);\n\tvar verbs = doc.verbs().json();\n\tvar nouns = doc.nouns().json();\n\tvar nouns_ori = doc.nouns().toSingular().json();\n\n\t// verb\n\tverbs.forEach(obj => {\n\t\tlet now = obj.text;\n\t\tlet to = obj.conjugations.Infinitive;\n\n\t\t// do not change\n\t\tif (now === to) return;\n\t\tif (now === '') return;\t\t// e.g. there's will cause one empty entry\n\t\tif (now.indexOf(\"'\") >= 0) return;\t// e.g. didn't => not didn't\n\n\t\t// replace\n\t\tlet re = new RegExp(now, 'g');\n\t\ttext = text.replace(re, to);\n\t});\n\n\t// noun\n\tnouns.forEach((obj, i) => {\n\t\tlet now = obj.text;\n\t\tlet to = nouns_ori[i].text;\n\n\t\t// do not change\n\t\tif (now === to) return;\n\n\t\t// replace\n\t\tlet re = new RegExp(now, 'g');\n\t\ttext = text.replace(re, to);\n\t});\n\n\treturn text;\n}",
"function splitSentenceFrom(delimiterWord)\n{\n\toriginalSentence = delimiterWord.sentence;\n\t\n\tvar newSentence = new Sentence();\n\tnewSentence.text_object = originalSentence.text_object;\n\t\n\toriginalSentence.lastWord = delimiterWord; //delimiter becomes the end of its current sentence\n\t\n\t//put all following words of the original sentence into the new one\n\tvar currentWord = delimiterWord.nextWord;\n\twhile(currentWord && currentWord.sentence == originalSentence)\n\t{\n\t\tif(!newSentence.firstWord)\n\t\t{\n\t\t\tnewSentence.firstWord = currentWord;\n\t\t}\n\t\tcurrentWord.sentence = newSentence;\n\t\tnewSentence.lastWord = currentWord;\n\t\t\n\t\tcurrentWord = currentWord.nextWord;\n\t}\n\t\n\t//rebuild the sentence list links correctly\n\tnewSentence.nextSentence = originalSentence.nextSentence;\n\tif(newSentence.nextSentence)\n\t{\n\t\tnewSentence.nextSentence.previousSentence = newSentence;\n\t}\n\toriginalSentence.nextSentence = newSentence;\n\tnewSentence.previousSentence = originalSentence;\n\t\n\tdelimiterWord.node.parent_text.log.splitSentences(originalSentence, newSentence);\n}",
"function splitSentences(text) {\r\n return text.replace(/([!?]|\\.\\.\\.)\\s+/g, \"$1. \").split(/[.;]\\s/);\r\n}",
"findWordInRecording(recordingData, word, context) {\n let [start, end] = [0, 0],\n phrases = [];\n\n this.buildWordsMapAndSentences(recordingData);\n\n if (!this.isValidInputParams(context, word)) return;\n\n this.mapWords[word].forEach((index) => {\n let start = Math.max(0, index - context);\n let end = Math.min(this.sentences.length, index + context + 1);\n phrases.push(this.sentences.slice(start, end).join(' '));\n });\n\n return phrases;\n }",
"function passageToSentences(passage) {\n let sentences = passage.split('.');\n let indexedSentences = {};\n for (let i = 0; i < sentences.length; i++) {\n if (sentences[i].length > 0) {\n indexedSentences[i] = sentences[i] + \".\";\n }\n }\n return indexedSentences;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Contact Form button pressed | function displayContactForm(){
if(document.querySelector('#contactBtn').querySelector('h2').textContent === 'About'){
ui.changeMainDisplayState('about');
} else{
ui.changeMainDisplayState('contact');
}
} | [
"function contactForm(){\n\t\tif($('#contact-site-form .form-type-textfield.form-item-subject , #contact-site-form .form-type-textarea').hasClass(\"error\")){\t\t\n\t\t\tlocation.hash=\"contact\";\n\t\t}\n\t\t\n\t\tif($('.programme-contact-form .form-item').hasClass(\"error\")){\t\t\n\t\t\t$('.node-type-programmes .vertical-tabs .contact a').trigger(\"click\");\t\t\n\t\t}\t\n\t\t\n\t\t/*$('.about-menu-wrapper .abt-mnu-contact').on(\"click\",function(){\n\t\t\tif($('about-nepad-contact-form ').hasClass(\"hide-block\")){\n\t\t\t\t$('about-nepad-contact-form ').removeClass(\"hide-block\")\n\t\t\t}\n\t\t\telse{\n\t\t\t\t$('about-nepad-contact-form ').addClass(\"hide-block\")\n\t\t\t}\n\t\t});*/\n\t\tvar block = $('.about-nepad-contact-form').clone();\n\t\t$('.about-nepad-contact-form').remove();\n\t\t$('.abt-contact-content').append(block);\n\t\t\n\t}",
"function contactSubmit() {\n $(this).submit();\n }",
"function hookContactForm() {\n // Look for form and for the message sent div.\n var form = document.getElementById('contact-form');\n var msg = document.getElementById('contact-form-message');\n // Where they found?\n if ( form && msg ) {\n // Yes. Now look for the submit button.\n var btn = document.getElementById('contact-form-submit');\n if ( btn ) {\n // Found it! Everything is good add the listener.\n btn.addEventListener( 'click', fakeSend );\n } else {\n // Not found, show error.\n console.error('Error: Your contact form must use a button or input submit type with the provided ID.')\n }\n } else {\n // Not found, show error.\n console.error('Error: You should only include the fake-send.js file on your contact page and the contact form must use the provided ID and include the message div with the provided ID.')\n }\n}",
"function openFeedbackForm(event) {\n var modal = document.getElementById('kfModal') || injectModal();\n modal.style.display = \"block\";\n document.getElementById(\"kfEmail\").focus();\n }",
"function onFormSubmit() {\n delayChat();\n }",
"function clickHandler(event) {\n var element = event.element();\n \n // find the topmost element with the classes we are interested in\n element = element.ancestors().find(function(e){\n return e.hasClassName('phone-name') || e.hasClassName('phone-number');\n }) || element;\n\n // if a phone-name was clicked, find the matching phone-number\n if(element.hasClassName('phone-name')) {\n element = element.siblings().find(function(e){ return e.hasClassName('phone-number'); });\n }\n \n // process the event if a phone-number was targeted\n if(element && element.hasClassName('phone-number')) {\n $('call_destination').value = element.innerHTML.stripScripts().stripTags();\n $('top').scrollTo();\n Form.Element.activate('call_destination');\n event.stop();\n }\n }",
"function contactForms() {\n\t // disable CF7 submit button on click\n\t $('.wpcf7-form input[type=\"submit\"]').on('click', function( event ) {\n\t\t $(this).addClass(\"disabled\");\n\t });\n\n\t // enable CF7 submit button after request processing is complete\n\t document.addEventListener( 'wpcf7submit', function( event ) {\n\t\t $(event.target).find('input[type=\"submit\"]').removeClass(\"disabled\");\n\t }, false );\n\n // fix CF7 not properly initialized and reCaptcha not loading\n // when navigating from ajax-link (i.e. offices to enquiries)\n\t if ($( 'div.wpcf7 > form' ).length) {\n var initRecaptcha = false;\n $( 'div.wpcf7 > form' ).each( function() {\n var $form = $( this );\n // if .ajax-loader was not attached, it means that\n // the wpcf7 was not initialized after ajax navigation\n if ($( '.ajax-loader', $form ).length == 0) {\n wpcf7.initForm( $form );\n if ( wpcf7.cached ) {\n wpcf7.refill( $form );\n }\n initRecaptcha = true;\n }\n })\n\n if (initRecaptcha) {\n $.getScript('https://www.google.com/recaptcha/api.js');\n }\n }\n }",
"function toSubmit() {\n let submit = document.getElementById('submit');\n submit.classList.toggle('bounce');\n}",
"function openMessageFrame(contactElement){\n\n\t\t\t//get a reference to the view object\n\t\t\tvar msgView = document.getElementById(\"message_view\");\n\n\t\t\tif(activeContact.trim() !== \"\"){\n\t\t\t\t\n\t\t\t\t//Change the color of the current active contact to black\n\t\t\t\tvar currentActiveContact = document.getElementById (activeContact);\n\t\t\t\tcurrentActiveContact.style.color = \"black\";\n\t\t\t\tconsole.log(\"Switch from \"+ activeContact );\n\t\t\t}//if Ends \n\n\t\t\t//remove current user's message content and replace them with that of the new user.\n\t\t\tactiveContact = contactElement.textContent; \n\n\t\t\tmsgView.textContent = \"\";\n\n\t\t\tcontactElement.style.color = \"blue\";\n\n\t\t\tconsole.log(\"Active contact: \"+activeContact);\n\n\t\t\t//TODO:Let the sender know that receiver has view the message that was sent.\n\t\t\t//clear the message notication status count to indicate that user has view the message. \n\t\t document.getElementById(activeContact+\"_msg_notice\").textContent = \"\";\n\t\t}",
"function thankYou() {\r\n\tyes.style.display = \"none\";\r\n\tno.style.display = \"none\";\r\n\tfeedback.style.display = \"none\";\r\n\tfadeSubmit();\r\n\tsubmit_button.style.cursor = \"not-allowed\";\r\n\tsubmit_clickable = false;\r\n\tthanks_text.innerHTML = \"Thank you for your feedback!\";\r\n\t//makeThanksText();\r\n}",
"function openAddContactFun(e) {\n\tTi.API.info('$.addBtn.toggle ' + $.addBtn.toggle);\n\tif ($.addBtn.toggle != \"false\") {\n\t\tAlloy.Globals.viewContactOpened = true;\n\t\tvar addContact = Alloy.createController(\"AddContactScreen\");\n\t\tAlloy.Globals.addContactObj = addContact;\n\t\tif (OS_IOS) {\n\n\t\t\tAlloy.Globals.navWindow.openWindow(addContact.getView());\n\t\t} else {\n\n\t\t\taddContact.getView().open();\n\t\t}\n\t\taddContact.oldWin = $.ViewContactScreen;\n\t\tAlloy.Globals.currentWindow = addContact.getView();\n\t} else {\n\t\tAlloy.Globals.Alert(\"You can not add more than 5 contact\");\n\t}\n\n}",
"function AboutButtonClick() {\n console.log(\"About Button was clicked\");\n }",
"function closeContactForm(form) {\n\tif ($(form).attr(\"aria-hidden\") == \"false\") {\n\t\t$(form).attr(\"aria-hidden\", \"true\");\n\t}\n}",
"function activateForm() {\n form.classList.remove('ad-form--disabled');\n switchingFormFieldsetState(false);\n }",
"function validateMessage()\n{\n//variable contactMessage is set by element id contactMessage from the form\n\tvar contactMessage = document.getElementById(\"contactMessage\").value; \n\t//validation for contactMessage\n\tif(contactMessage.length == 0)\n\t{\n\t\tproducePrompt(\"Message is Required\", \"messagePrompt\", \"red\"); \n\t\treturn false; \n\t}\n\tproducePrompt(\"Now press send, you will be contacted shortly. \", \"messagePrompt\", \"green\"); \n\t\treturn true; \n\n}",
"function emailFunction() {\n var x = document.getElementById(\"contactMe\");\n if (x.style.display === \"none\") {\n x.style.display = \"block\";\n } else {\n x.style.display = \"none\";\n }\n }",
"async function handleContactUsSubmit(e) {\n e.preventDefault();\n const res = await Axios.post(requests.contactUs, contactUsDataToPost);\n if (res.status === 200) {\n notifyDistSubmitionSuccess();\n\n setContactEmail(\"\");\n setName(\"\");\n setOrderNumber(\"\");\n setSubject(\"\");\n setYourMsg(\"\");\n }\n }",
"function setContactPage(){\r\n setPage('contact-page');\r\n }",
"handleEditButtonClick() {\n BusinessRulesFunctions.viewBusinessRuleForm(true, this.state.uuid)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Toggles node state between WALL and UNVISITED | toggleWall()
{
if (this.state == State.UNVISITED)
{
this.setState(State.WALL);
}
else
{
this.setState(State.UNVISITED);
}
} | [
"function toggleNight(){\n\tif (nightMode) {\n\t\tnightMode = false;\n\t} else {\n\t\tnightMode = true;\n\t}\n}",
"function switchContent() {\n let nodeId= $(clickedNode).attr('id');\n let node = nodeMap.get(nodeId);\n $(clickedNode).children(\".node_inhalt\").toggleClass(\"invis\");\n if($(clickedNode).children(\".node_inhalt\").hasClass(\"invis\")){\n node.toggleToAbstract();\n node.focus(); }\n else{\n node.toggleToDetailed();\n }\n\n}",
"function ontoggle() {\n selected = !selected;\n logic.ontoggle(selected);\n }",
"function TrueNode() {\n}",
"function toggleShapes(){\n\tif (shapesOn) {\n\t\tshapesOn = false;\n\t} else {\n\t\tshapesOn = true;\n\t}\n}",
"function toggleCabinetLEDs() {\n\n\t if( cabinets === 0 ) {\n\t cabinet_leds.writeSync( 1 );\n\t cabinets = 1;\n\t } else {\n\t cabinet_leds.writeSync( 0 );\n\t cabinets = 0;\n\t }\n\n\t sendReturn();\n\n\t}",
"function mousePressed(){\r\n if(nodeEllipseActive()){\r\n if(nodeEllipseActive().collapsed == false){\r\n visTree.collapse(nodeEllipseActive());\r\n nodeEllipseActive().muted = false;\r\n nodeEllipseActive().collapsed = true;\r\n }\r\n else{\r\n visTree.uncollapse(nodeEllipseActive());\r\n nodeEllipseActive().collapsed = false;\r\n }\r\n }\r\n}",
"function toggleState ( stateOff, stateOn, attrOff, attrOn, expOff, expOn ) {\n btnMenu.attr('data-state', btnMenu.attr('data-state') === stateOff ? stateOn : stateOff);\n\n btnMenu.attr('aria-label', btnMenu.attr('aria-label') === attrOff ? attrOn : attrOff);\n\n btnMenu.attr('aria-expanded', btnMenu.attr('aria-expanded') === expOff ? expOn : expOff);\n}",
"function ToggleSnapping(){\n\tSnapping = !Snapping;\n}//ToggleSnapping",
"toggle() {\n if (this._simulation.started)\n this.stop();\n else\n this.start();\n }",
"function toggleSnap() {\n if (snapping == 'on') {\n snapping = 'off'\n }\n else {\n snapping = 'on'\n }\n}",
"function toggle_postcodes_visibility() {\r\n // Toggle node\r\n for (let i = 0; i < nodes.length; i++) {\r\n if (this.value == nodes[i].location.split(\" \")[0]) {\r\n if (map.hasLayer(nodes[i].layer)) {\r\n nodes[i].layer.removeFrom(map);\r\n nodes[i].label.removeFrom(map);\r\n } else {\r\n nodes[i].layer.addTo(map);\r\n }\r\n }\r\n }\r\n\r\n // Toggle edges\r\n for (let i = 0; i < edges.length; i++) {\r\n if (this.value == edges[i].start_node.location.split(\" \")[0]) {\r\n if (map.hasLayer(edges[i].layer)) {\r\n edges[i].layer.removeFrom(map);\r\n edges[i].label.removeFrom(map);\r\n } else {\r\n edges[i].layer.addTo(map);\r\n }\r\n }\r\n }\r\n}",
"function switchOff() {\n stopGame(); \n infoscreen.text('Game is switched off'); \n usedPattern = []; //usedPattern array is empty\n gameSwitchedOn = false; //sets var gameSwitchedOn status to false\n strictMode = false; //strict mode is off\n $('.levelButton').css('background-color', 'lightskyblue'); //all level buttons get the same color\n }",
"_checkNode(node) {\n node.setAttribute('aria-checked', 'true')\n node.tabIndex = 0\n\n store.dispatch(setLabelBackgroundColor(node.bgColor))\n }",
"step() {\n\n super.step();\n // this.$node.addClass('square');\n this.$node.toggleClass('square-toggle');\n\n\n}",
"toggle() {\n Mousetrap[(this.paused ? 'unpause' : 'pause')]();\n this.paused = !this.paused;\n }",
"toggleHighlight() {\n\t\tthis.setState({\n\t\t\tcheckHighlighted: !this.state.checkHighlighted\n\t\t})\n\t}",
"function toggleExpando(thing)\n{\n if (thing.classList.contains(\"expanded\")) {\n thing.classList.remove(\"expanded\");\n thing.classList.add(\"contracted\");\n } else {\n thing.classList.remove(\"contracted\");\n thing.classList.add(\"expanded\");\n }\n}",
"function classToggle() {\n this.classList.toggle('curtain');\n this.classList.toggle('curtain2');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
STATION SELECTION FUNCTIONS This is the MapSelected function that actually does a lot of the legwork for the application. Basically, this function checks to see which station is selected (using jQUERY) and which year (using the radio button functions from the beginning of this code) to determine which mapping functions to run. Again, this is intended to be scalable: if there were 200 stations added this would become long, but would be relatively easily accomplished with some copy/paste and a few modifications. | function MapSelected() {
map.setZoom(11);
$("#legend").show();
$("#bufferbtns").show();
if (($("#station_name").text() === "Exton") && (rb1.checked === true)) {
// console.log("Someone wants to map Exton 2011!");
exton2011();
legendExton11();
return;
}
else if (($("#station_name").text() === "Exton") && (rb2.checked === true)) {
// console.log("Someone wants to map Exton 2016!");
exton2016();
legendExton16();
return;
}
else if (($("#station_name").text() === "Thorndale") && (rb1.checked === true)) {
// console.log("Someone wants to map Thorndale 2016!");
thorndale2016();
legendThorndale16();
return;
}
else {
alert("Please select data to map");
// console.log("No data is selected!");
}
} | [
"function showStations() {\n\n Object.keys(Hubway.stations).forEach(function(id) {\n \n var row = Hubway.stations[id];\n \n var description = '['+ id + '] ' + row.name + ', ' + row['docks'] + ' bikes'; \n var marker = addMarker(row.latitude, row.longitude, description, \"default\", 10 * defaultMarkerRadius, markerOptions.default, activeStation === +id);\n marker.setStyle(markerOptions.stationUnselected);\n\n marker.bindPopup(description, {autoPan: false});\n marker.on('mouseover', function (e) { this.openPopup(); });\n marker.on('mouseout', function (e) { this.closePopup(); });\n\n // add a reference to the original data\n Hubway.stations[id]['marker'] = marker; \n \n if (selectedFilters['stationStart'][row.id]) {\n selectedFilters['stationStart'][row.id] = {'row': row, 'marker': marker};\n marker.setStyle(markerOptions.stationSelected); \n }\n \n marker.on('click', function (e) { \n if (!selectedFilters['stationStart'][row.id]) { \n selectStation(row.id);\n } else {\n removeStation(row.id);\n }\n });\n \n });\n}",
"function selectStation(id) {\n\n reset = false;\n delete selectedFilters.stationStart[-1];\n\n var marker = Hubway.stations[id]['marker'];\n \n selectedFilters['stationStart'][id] = {'row': Hubway.stations[id], 'marker': marker};\n marker.setStyle(markerOptions.stationSelected);\n\n if (!selectAllStations) {\n redraw();\n }\n \n displaySelectedStationsText(); \n}",
"function findStationDistrict() {\n\n\t// Retrieve pcid from selected polygon.\n\tvar pcid = selectedFeature.attributes.gid;\n\n\tcleanMap();\n\t\t\n\t// Prepare AJAX request endpoint link.\n\tvar endpoint = perlurl + \"getStationsDistrict.pl?pcid=\" + pcid;\n\n\t// Create GML results.\n\tnearby_dockstn = new OpenLayers.Layer.Vector(\"Nearby Docking Stations\", {\n protocol: new OpenLayers.Protocol.HTTP({\n url: endpoint,\n format: new OpenLayers.Format.GML()\n }),\n strategies: [new OpenLayers.Strategy.Fixed()],\n\t\tstyleMap: new OpenLayers.StyleMap()\n });\n\n\t// Style results.\n\tnearby_dockstn.styleMap.styles[\"default\"] = sld.namedLayers[\"DockStnNearby\"].userStyles[0];\n\n\t// Add all layers to the map.\n\tmap.addLayer(nearby_dockstn);\n\t\n\ttoggleSelectResults();\n\n}",
"function chooseStation() {\n var stationId = window.location.hash.substr(1);\n\n if (!stationId) {\n // this is the default if none selected\n stationId = 'nac_radio';\n }\n\n var station = STATIONS[stationId];\n var streamId = station.streamId;\n var url = station.url;\n var logo = station.logo;\n\n $('.cc_streaminfo').each(function(idx, elem) {\n // add the selected streamId onto .cc_streaminfo element IDs,\n // e.g. cc_strinfo_title => cc_strinfo_title_nundahac\n elem = $(elem);\n elem.attr('id', elem.attr('id') + '_' + streamId);\n });\n $('#radio').attr('src', url);\n $('.radiologo img').attr('src',logo);\n }",
"function chooseStation() {\n var stationId = window.location.hash.substr(1);\n\n if (!stationId) {\n // this is the default if none selected\n stationId = 'nac_radio';\n }\n\n var station = STATIONS[stationId];\n var streamId = station.streamId;\n var url = station.url;\n var logo = station.logo;\n\n $('.cc_streaminfo').each(function (idx, elem) {\n // add the selected streamId onto .cc_streaminfo element IDs,\n // e.g. cc_strinfo_title => cc_strinfo_title_nundahac\n elem = $(elem);\n elem.attr('id', elem.attr('id') + '_' + streamId);\n });\n $('#radio').attr('src', url);\n $('.radiologo img').attr('src', logo);\n}",
"function displaySelectedStationsText() {\n\n var description = '<div class=\"results_title\">Selected stations:</div><div class=\"results_group\">';\n \n Object.keys(selectedFilters['stationStart']).forEach(function(id) {\n if (id == -1) { return; }\n description += Hubway.stations[id]['name'] + '<br>';\n });\n \n description += '</div>'\n \n $(\"#js_description\").html(description); \n}",
"function select_simulations(itype, clusters, ligandonly, rev, stnd){\n \n //variables\n var simulationlist, code, URL, custombutton;\n\n //Get selected simulations dynIDs\n simulationlist = $(\".simulation_checkbox:checked\").map(function(){return $(this).attr(\"name\");}).get();\n\n //(Pseudo-)Random identifier for this customized heatmap\n code = Math.random().toString(36).substring(7);\n\n //Open new tab with the results\n URL = window.location.origin + '/contmaps/customized/?itype=' + itype + \"&cluster=\" + clusters + \"&prtn=\" + ligandonly + \"&rev=\" + rev + \"&stnd=\" + stnd + \"&code=\" + code;\n\n //Set new attributes to the custom form, and enable it if any simulations are selected\n custombutton = $(\"#CustomButton\");\n $(\"input[name='SimList']\").val(simulationlist.join(\"&\"));\n custombutton.attr('formaction',URL);\n if (simulationlist.length == 0){\n custombutton.attr('disabled',true);\n }\n else {\n custombutton.attr('disabled',false);\n }\n}",
"function enableDistrictSelect() {\n\n\tcleanMap();\t\n\tselectControl.activate();\n\n}",
"function hideNoYear() {\n\tvar controlsNode = this.parentNode.parentNode;\n\tvar maps = $(controlsNode).parent().parent().find('.map');\n\tvar mapsNode = $(controlsNode.parentNode.parentNode).find('.maps')[0];\n\tvar mapsToOutput = [];\n\tif (this.checked) { // Hide maps\n\t\tfor (var i = 0; i < maps.length; i++) {\n\t\t\tvar year = maps[i].firstElementChild.children[3].textContent;\n\t\t\tif (year != \"No year listed\") {\n\t\t\t\tmapsToOutput.push(maps[i]);\n\t\t\t} else {\n\t\t\t\tnoYearMaps.push(maps[i]);\n\t\t\t}\n\t\t}\n\t} else { // Unhide maps\n\t\tif (controlsNode.children[2].firstElementChild.checked) { // If in descending order\n\t\t\tfor (var i = 0; i < noYearMaps.length; i++) {\n\t\t\t\tmapsToOutput.push(noYearMaps[i]);\n\t\t\t}\n\t\t\tfor (var i = 0; i < maps.length; i++) {\n\t\t\t\tmapsToOutput.push(maps[i]);\n\t\t\t}\n\t\t} else {\n\t\t\tmapsToOutput = maps;\n\t\t\tfor (var i = 0; i < noYearMaps.length; i++) {\n\t\t\t\tmapsToOutput.push(noYearMaps[i]);\n\t\t\t}\n\t\t}\n\t\tnoYearMaps = [];\n\t}\n\toutputMaps(mapsToOutput, mapsNode);\n}",
"function getMapOptions(state) {\r\n\tswitch (state)\r\n\t{\r\n\t\tcase \"US\":\r\n\t\t\treturn {\r\n\t\t\t\tzoom: 3,\r\n\t\t\t center: new google.maps.LatLng(39.977120, -98.067627),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\r\n\t\tcase \"AL\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(32.841667, -86.633333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\r\n\t\tcase \"AK\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 3,\r\n\t\t\t center: new google.maps.LatLng(64.731667, -152.470000),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\r\n\t\tcase \"AZ\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(34.308333, -111.793333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\r\n\t\tcase \"AR\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(34.815000, -92.301667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"CA\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 5,\r\n\t\t\t center: new google.maps.LatLng(36.965000, -120.081667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"CO\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(38.998333, -105.641667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"CT\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 8,\r\n\t\t\t center: new google.maps.LatLng(41.595000, -72.706667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase \"DC\":\r\n\t\t\treturn {\r\n\t\t\t\tzoom: 11,\r\n\t\t\t\tcenter: new google.maps.LatLng(38.93885, -77.035847),\r\n\t\t\t\tmapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"DE\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 8,\r\n\t\t\t center: new google.maps.LatLng(39.181175,-75.385895),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"FL\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(28.062286,-83.300171),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"GA\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(32.713333, -83.495000),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\t\r\n\t\t\r\n\t\tcase \"HI\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(20.951667, -157.27667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"ID\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 5,\r\n\t\t\t center: new google.maps.LatLng(45.367584, -114.239502),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"IL\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(40.013333, -89.306667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"IN\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(39.895000, -86.266667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"IA\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(41.961667, -93.385000),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"KS\": \r\n\t\t\treturn {\r\n\t\t\t\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(38.498333, -98.698333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"KY\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(37.358333, -85.506667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"LA\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(30.968333, -92.536667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"ME\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(45.253333, -69.233333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"MD\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 7,\r\n\t\t\t center: new google.maps.LatLng(39.219487, -76.993103),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"MA\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 7,\r\n\t\t\t center: new google.maps.LatLng(42.340000, -72.031667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"MI\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 5,\r\n\t\t\t center: new google.maps.LatLng(45.061667, -84.938333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"MN\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 5,\r\n\t\t\t center: new google.maps.LatLng(46.025000, -95.326667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"MS\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(32.815000, -89.938333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"MO\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(38.495000, -92.631667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"MT\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(47.031667, -109.638333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"NE\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(41.525000, -99.861667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"NV\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 5,\r\n\t\t\t center: new google.maps.LatLng(39.505000, -116.931667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"NH\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 7,\r\n\t\t\t center: new google.maps.LatLng(43.641667, -71.571667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"NJ\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 7,\r\n\t\t\t center: new google.maps.LatLng(40.070000, -74.558333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"NM\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(34.501667, -106.111667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"NY\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(42.965000, -76.016667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"NC\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(35.603333, -79.455000),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"ND\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(47.411667, -100.568333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"OH\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(40.361667, -82.741667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"OK\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(35.536667, -97.660000),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"OR\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(43.868333, -120.978333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"PA\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(40.896667, -77.746667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"RI\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 8,\r\n\t\t\t center: new google.maps.LatLng(41.671667, -71.576667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"SC\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 7,\r\n\t\t\t center: new google.maps.LatLng(33.830000, -80.873333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"SD\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(44.401667, -100.478333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"TN\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(35.795000, -86.621667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"TX\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 5,\r\n\t\t\t center: new google.maps.LatLng(31.243333, -99.458333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"UT\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(39.386667, -111.685000),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"VT\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(43.926667, -72.671667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"VA\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(37.488333, -78.563333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"WA\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(47.333333, -120.268333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"WV\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 7,\r\n\t\t\t center: new google.maps.LatLng(38.598333, -80.703333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"WI\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(44.433333, -89.763333),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase \"WY\": \r\n\t\t\treturn {\r\n\t\t\t\tzoom: 6,\r\n\t\t\t center: new google.maps.LatLng(42.971667, -107.671667),\r\n\t\t\t mapTypeId: google.maps.MapTypeId.ROADMAP\r\n\t\t\t};\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tdefault:\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t}\r\n}",
"function selectMarkers(start, end)\n{\n for(index in markers)\n {\n\tcurrent = markers[index].frameNo;\n\tif(current >= start && current <= end)\n\t{\n\t markers[index].setVisible(true);\n\t}\n\telse\n\t{\n\t markers[index].setVisible(false);\n\t}\n }\n markerCluster.repaint();\n resetInfoWindow();\n}",
"function getMapStyleUI() {\n if ($(\"#rad1\")[0].checked) {\n return 'satellite';\n } else if ($(\"#rad2\")[0].checked) {\n return 'hybrid';\n } else if ($(\"#rad3\")[0].checked) {\n return 'terrain';\n } else if ($(\"#rad4\")[0].checked) {\n return 'roadmap';\n } \n }",
"function displayStateSelect() {\n //jQuery('#country').each(function() {\n //var si = jQuery(\"#country option:selected\").val();\n var si = jQuery(\"#country\").val();\n if (si == 'United States' || si == '') {\n jQuery('#usstate_div').show();\n jQuery('#caprovince_div').hide();\n jQuery('#usstate').addClass('required-select');\n jQuery('#caprovince').removeClass('required-select');\n jQuery('#postallabel').text('Zip Code');\n }\n else if (si == 'Canada') {\n jQuery('#caprovince_div').show();\n jQuery('#usstate_div').hide();\n jQuery('#caprovince').addClass('required-select');\n jQuery('#usstate').removeClass('required-select');\n jQuery('#postallabel').text('Postal Code');\n }\n else {\n jQuery('#usstate_div').hide();\n jQuery('#caprovince_div').hide();\n jQuery('#usstate').removeClass('required-select');\n jQuery('#caprovince').removeClass('required-select');\n jQuery('#postallabel').text('Postal Code');\n }\n\t//});\n}",
"function identify(event) {\n\tif (map.getZoom() >= 16) {\n\t\tvar lonlat = map.getLonLatFromViewPortPx(event.xy);\n\t\tlonlat.transform(map.getProjectionObject(), new OpenLayers.Projection(\"EPSG:4326\"));\n\t\tselectByCoordinate(lonlat.lon, lonlat.lat);\n\t}\n}",
"function selectHouses() {\n console.log(\"got to selecthouses\");\n // If no further limits have been entered, just make the finalGroup array equal to the areaGroup\n // array — we don't want to filter the houses further — then run updateDisplay().\n if ( builtTarget.value == \"anyyearbuilt\" && accessTarget.value == \"anyaccessibility\" ) {\n //console.log(\"no further filter\");\n finalGroup = areaGroup;\n //console.log(\"final group\", finalGroup);\n updateDisplay();\n } else if ( builtTarget.value == \"anyyearbuilt\" ) {\n // ONLY LIMIT BY ACCESS\n //console.log(\"access filter\");\n for( let i = 0; i < areaGroup.length ; i++ ) {\n if( areaGroup[i].accessible == accessTarget.value ) {\n finalGroup.push(areaGroup[i]);\n }\n }\n updateDisplay();\n } else if ( accessTarget.value == \"anyaccessibility\" ) {\n // ONLY LIMIT BY BUILT\n //console.log(\"built filter\");\n for( let i = 0; i < areaGroup.length ; i++ ) {\n let range = (builtTarget.value).split(\"-\");\n let min = range[0];\n let max = range[1];\n if( areaGroup[i].built >= min && areaGroup[i].built <= max ) {\n finalGroup.push(areaGroup[i]);\n }\n }\n updateDisplay();\n } else {\n // LIMIT BY BOTH\n //console.log(\"both filter\");\n for( let i = 0; i < areaGroup.length ; i++ ) {\n let range = (builtTarget.value).split(\"-\");\n let min = range[0];\n let max = range[1];\n if( areaGroup[i].built >= min && areaGroup[i].built <= max && areaGroup[i].accessible == accessTarget.value ) {\n finalGroup.push(areaGroup[i]);\n }\n }\n updateDisplay();\n }\n\n }",
"static initMapSouthAfrica() {\r\n // Set Active Map\r\n mapOptions['map'] = 'za_mill_en';\r\n\r\n // Init Map\r\n jQuery('.js-vector-map-south-africa').vectorMap(mapOptions);\r\n }",
"function populateResultsTable_by_country() {\n\n\t\t\tvar selectedStates = $(\"#statesListbox_by_country\").val() || [];\n\t\t\tvar HSarray = selected_HS6_Codes\n\n\t\t\timportResultsTable_by_country = searchDBByAbbr(importDestinationDB, selectedStates);\n\t\t\texportResultsTable_by_country = searchDBByAbbr(exportDestinationDB, selectedStates);\n\t\t\tconsole.log('selectedStates: ')\n\t\t\tconsole.log(selectedStates)\n\t\t\tconsole.log('importResultsTable_by_country: ')\n\t\t\tconsole.log(importResultsTable_by_country)\n\t\t\tconsole.log('exportResultsTable_by_country: ')\n\t\t\tconsole.log(exportResultsTable_by_country)\n\t\t\tdrawChart_by_country()\n\t\t\tdrawWorldMap_by_country()\n\t\t}",
"function init(){\n var countrySel = $('#sel-country');\n var categorySel = $('#sel-category');\n var genderSel = $('#sel-gender');\n\n function updateSelections() {\n var params = window.winners.params || {};\n params.country = countrySel.val();\n params.category = categorySel.val();\n params.gender = genderSel.val();\n fetchData();\n }\n\n countrySel.on('change', updateSelections);\n categorySel.on('change', updateSelections);\n genderSel.on('change', updateSelections);\n updateSelections();\n setupMapData();\n}",
"function worldMap(allData) {\n\n // Creates div for the datamap to reside in\n d3v3.select(\"body\")\n .append(\"div\")\n .attr(\"id\", \"container\")\n .style(\"position\", \"relative\")\n .style(\"width\", \"700px\")\n .style(\"height\", \"450px\")\n .style(\"margin\", \"auto\");\n\n // Gets neccesary info from JSON file\n var data = [];\n for (country in datafile) {\n data.push([datafile[country][\"Country code\"],\n datafile[country][\"Happy Planet Index\"],\n datafile[country][\"GDP/capita ($PPP)\"]]);\n }\n\n // Finds specified values and their minimum and maximum\n var dataset = {};\n var score = data.map(function(obj){ return parseFloat(obj[1]); });\n var minValue = Math.min.apply(null, score);\n var maxValue = Math.max.apply(null, score);\n\n // Adds Colour palette based on minimum and maximum\n var paletteScale = d3v3.scale.linear()\n .domain([minValue,maxValue])\n .range([\"#ece7f2\",\"#2b8cbe\"]);\n\n // Converts dataset to appropriate format\n data.forEach(function(item){\n var country = item[0];\n var happy = item[1];\n var gdp = item[2];\n dataset[country] = { HappyPlanetIndex: happy,\n Gdp: gdp,\n fillColor: paletteScale(happy) };\n });\n\n // Renders map based on dataset\n new Datamap({\n element: document.getElementById(\"container\"),\n projection: \"mercator\",\n fills: { defaultFill: \"#F5F5F5\" },\n data: dataset,\n done: function(data) { data.svg.selectAll(\".datamaps-subunit\")\n .on(\"click\", function(geo) {\n scatterPlot(geo.id, datafile); }\n );\n },\n geographyConfig: {\n borderColor: \"#000000\",\n highlightBorderWidth: 2,\n highlightFillColor: function(geo) { return \"#FEFEFE\"; },\n highlightBorderColor: \"#B7B7B7\",\n popupTemplate: function(geo, data) {\n if (!data) { return [\"<div class='hoverinfo'>\",\n \"<strong>\", geo.properties.name, \"</strong>\",\n \"<br>No data available <strong>\", \"</div>\"].join(\"\"); }\n return [\"<div class='hoverinfo'>\",\n \"<strong>\", geo.properties.name, \"</strong>\",\n \"<br>Happy planet index: <strong>\", data.HappyPlanetIndex,\n \"</strong>\",\n \"<br>Gdp: <strong>\", data.Gdp, \"($PPP)</strong>\",\n \"</div>\"].join(\"\");\n }\n }\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Before started, build RuleEngines using vhosts configuration. The resulted _engines holds the engine of map, map domain name to engine instance. One engine may be mapped by multiple domains. If there's 1 domain, then it is the default domain. | prepare() {
this._koa.use(this.mock.bind(this));
this._engines = {};
const vhostConfigs = this._config.vhosts;
let amountOfDomains = 0;
for (const vhostName in vhostConfigs) {
const vhostConfig = vhostConfigs[vhostName];
const engine = new RuleEngine(this._name + '_RuleEngine', vhostConfig);
this._beans.renderThenInitBean(engine, 'RuleEngine:' + vhostName);
for (const domain of vhostConfig.domains) {
if (this._engines[domain]) {
throw new Error(`${this._name}: duplicated domain: domain`);
}
this._engines[domain] = engine;
amountOfDomains++;
if (!this.defaultDomain) {
this.defaultDomain = domain;
}
this._logger.info(`virtual host: ${domain}`);
}
}
if (amountOfDomains !== 1) {
this.defaultDomain = undefined;
}
} | [
"_getEngines(value) {\n if (!value) {\n return null;\n }\n\n return value.split(',').map(function (item) {\n return new engineMap[item]();\n });\n }",
"async _getVirtualHostsPerEnv(token) {\n\t\tthis.log('Loading virtual hosts')\n\t\tconst virtualHostsPerEnvironment = new Map();\n\t\t//get a list of all environments and virtual hosts\n\t\tconst environments = JSON.parse(await this._listEnvironments(token));\n\t\tfor (let env of environments) {\n\t\t\tthis.log(`Processing env ${JSON.stringify(env)}`);\n\t\t\t//get the virtual hosts\n\t\t\tconst virtualHosts = await this._listVirtualHostsForEnvironment(token, env);\n\t\t\tlet vhostDetails = [];\n\t\t\tfor (let vhost of JSON.parse(virtualHosts)) {\n\t\t\t\tlet vHostDetails = await this._listVirtualHostDetailsForEnvironment(token, env, vhost);\n\t\t\t\tvhostDetails.push(JSON.parse(vHostDetails));\n\t\t\t}\n\t\t\tvirtualHostsPerEnvironment.set(env, vhostDetails);\n\t\t}\n\t\treturn virtualHostsPerEnvironment;\n\t}",
"function addEngine(name, require) {\n\tengines[name] = require;\n}",
"async _listVirtualHostsForEnvironment(token, envName) {\n\t\treturn requestPromise({\n\t\t\t...this.requestSettings.hosts(envName, token),\n\t\t\t...this.proxySettings\n\t\t});\n\t}",
"function getRegexSiteMap() {\n var urlRegexString = \"^(?:https?\\:\\/\\/)?(?:www\\.)?\";\n\n return [\n {siteURL: \"debug\", urlRegex: \"localhost\"},\n {siteURL: \"youtube\", urlRegex: urlRegexString + \"youtube\\.com\\/watch.*\"},\n {siteURL: \"pandora\", urlRegex: urlRegexString + \"pandora\\.com.*\"} \n ]\n}",
"function D(name,registrar) {\n var domain = newDomain(name,registrar);\n for (var i = 0; i< defaultArgs.length; i++){\n processDargs(defaultArgs[i],domain)\n }\n for (var i = 2; i<arguments.length; i++) {\n var m = arguments[i];\n processDargs(m, domain)\n }\n conf.domains.push(domain)\n}",
"function configureToLoadJarEngines(loadFromJars = true)\n{\n let defaultBranch = Services.prefs.getDefaultBranch(null);\n\n let url = \"chrome://testsearchplugin/locale/searchplugins/\";\n defaultBranch.setCharPref(\"browser.search.jarURIs\", url);\n\n defaultBranch.setBoolPref(\"browser.search.loadFromJars\", loadFromJars);\n\n // Give the pref a user set value that is the opposite of the default,\n // to ensure user set values are ignored.\n Services.prefs.setBoolPref(\"browser.search.loadFromJars\", !loadFromJars)\n\n // Ensure a test engine exists in the app dir anyway.\n let dir = Services.dirsvc.get(NS_APP_SEARCH_DIR, Ci.nsIFile);\n if (!dir.exists())\n dir.create(dir.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);\n do_get_file(\"data/engine-app.xml\").copyTo(dir, \"app.xml\");\n}",
"static init() {\n\t\tconst oThis = this;\n\t\t// looping over all databases\n\t\tfor (let dbName in mysqlConfig['databases']) {\n\t\t\tlet dbClusters = mysqlConfig['databases'][dbName];\n\t\t\t// looping over all clusters for the database\n\t\t\tfor (let i = 0; i < dbClusters.length; i++) {\n\t\t\t\tlet cName = dbClusters[i],\n\t\t\t\t\tcConfig = mysqlConfig['clusters'][cName];\n\n\t\t\t\t// creating pool cluster object in poolClusters map\n\t\t\t\toThis.generateCluster(cName, dbName, cConfig);\n\t\t\t}\n\t\t}\n\t}",
"function create_scales(){\n //Initializes the axis domains for the big chart\n x.domain(d3.extent(data.map(function(d){return new Date(d.TIMESTAMP)})));\n y.domain(d3.extent(data.map(function(d){return +d[areaYparameter]})));\n //Initializes the axis domains for the small chart\n x2.domain(x.domain());\n y2.domain(y.domain());\n }",
"async function getTargetEngines(asset) {\n let targets = {};\n let compileTarget = BROWSER_CONTEXT.has(asset.env.context) ? 'browsers' : asset.env.context;\n let pkg = await asset.getPackage();\n let engines = pkg && pkg.engines;\n\n if (compileTarget === 'node') {\n let nodeVersion = engines === null || engines === void 0 ? void 0 : engines.node; // Use package.engines.node by default if we are compiling for node.\n\n if (typeof nodeVersion === 'string') {\n targets.node = nodeVersion;\n }\n } else {\n if (engines && (typeof engines.browsers === 'string' || Array.isArray(engines.browsers))) {\n targets.browsers = engines.browsers;\n } else if (pkg && pkg.browserslist) {\n targets.browsers = pkg.browserslist;\n } else {\n let browserslist = await loadBrowserslist(asset);\n\n if (browserslist) {\n targets.browsers = browserslist;\n }\n }\n } // Parse browser targets\n\n\n if (targets.browsers) {\n if (typeof targets.browsers === 'object' && !Array.isArray(targets.browsers)) {\n // let env = asset.options.production\n // ? 'production'\n // : process.env.NODE_ENV || 'development';\n let env = process.env.NODE_ENV || 'development';\n targets.browsers = targets.browsers[env] || targets.browsers.defaults;\n }\n\n if (targets.browsers) {\n targets.browsers = (0, _browserslist.default)(targets.browsers).sort();\n }\n } // Dont compile if we couldn't find any targets\n\n\n if (Object.keys(targets).length === 0) {\n return null;\n }\n\n return targets;\n}",
"registerHealthCheckers() {\n /**\n * Do not register hooks when not running in web\n * environment\n */\n if (!this.isWebOrTestEnvironment) {\n return;\n }\n this.app.container.withBindings(['Adonis/Core/HealthCheck'], (healthCheck) => {\n require('../src/HealthCheck/Checkers/Env').default(healthCheck);\n require('../src/HealthCheck/Checkers/AppKey').default(healthCheck);\n });\n }",
"loadEngineDefaults() {\n for (let key in DEFAULT_SETTINGS) {\n const setting = new Setting(key, DEFAULT_SETTINGS[key]);\n super.set(setting.getName(), setting);\n }\n }",
"function installTestEngine() {\n removeMetadata();\n removeCacheFile();\n\n do_check_false(Services.search.isInitialized);\n\n let engineDummyFile = gProfD.clone();\n engineDummyFile.append(\"searchplugins\");\n engineDummyFile.append(\"test-search-engine.xml\");\n let engineDir = engineDummyFile.parent;\n engineDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);\n\n do_get_file(\"data/engine.xml\").copyTo(engineDir, \"engine.xml\");\n\n do_register_cleanup(function() {\n removeMetadata();\n removeCacheFile();\n });\n}",
"function setUpGeoDefaults() {\n removeMetadata();\n removeCacheFile();\n\n do_check_false(Services.search.isInitialized);\n\n let engineDummyFile = gProfD.clone();\n engineDummyFile.append(\"searchplugins\");\n engineDummyFile.append(\"test-search-engine.xml\");\n let engineDir = engineDummyFile.parent;\n engineDir.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);\n\n do_get_file(\"data/engine.xml\").copyTo(engineDir, \"engine.xml\");\n\n engineDummyFile = gProfD.clone();\n engineDummyFile.append(\"searchplugins\");\n engineDummyFile.append(\"test-search-engine2.xml\");\n\n do_get_file(\"data/engine2.xml\").copyTo(engineDir, \"engine2.xml\");\n\n setLocalizedPref(\"browser.search.defaultenginename\", \"Test search engine\");\n setLocalizedPref(\"browser.search.defaultenginename.US\", \"A second test engine\");\n\n do_register_cleanup(function() {\n removeMetadata();\n removeCacheFile();\n });\n}",
"getPotentialHosts() {\n return this.getPotentialRegions()\n .map((r) => { return r.host; });\n }",
"reload() {\n // start agents for all existing cloud pools\n const agents_to_start = system_store.data.pools.filter(pool =>\n (!_.isUndefined(pool.cloud_pool_info) || !_.isUndefined(pool.mongo_pool_info))\n );\n dbg.log0(`will start agents for these pools: ${util.inspect(agents_to_start)}`);\n return P.map(agents_to_start, pool => this._start_pool_agent(pool));\n }",
"getLUISPrebuiltDomainsForCultureList(params) {\n return this.createRequest('/{culture}', params, 'get');\n }",
"function build_search_for_single_domain (KeyWords){\n universalKeyword = KeyWords[0];\n finalName = shortenName(universalKeyword);\n domain_name_builder();\n\n //Cycle through the specified tlds\n if(!$.isEmptyObject(fundamental_vars.keywords[universalKeyword])){\n handle_requested_domains();\n }\n\n single_keyword_special_prices();\n\n $('.tld-line:hidden:lt(' + fundamental_vars.defaultLimit + ')').show();\n createRequests();\n}",
"function loadHosts() {\n if (noLoadHosts) return;\n\n noLoadHosts = true; // Debounce\n var file = __dirname + \"/\" + hostsFile;\n fs.exists(file, function(exists) {\n\tif (!exists) return;\n\n\thosts = {};\n\tfs.readFile(file, function(err, data) {\n\t _.each(data.toString().split(/[\\n\\r]+/), function(line) {\n\t\tline = line.replace(/\\s*\\#.*$/, '');\n\t\tif (line.match(/^\\s*$/)) return;\n\n\t\tvar parts = line.split(/\\s+/);\n\t\tif (parts && parts.length == 2) {\n\t\t hosts[parts[0]] = parts[1];\n\t\t}\n\t });\n\t if (_.keys(hosts).length > 0) {\n\t\tnoLoadHosts = false;\n\t\tconsole.log('Loaded ' + _.keys(hosts).length + ' hosts from ' + file);\n\t }\n\t});\n });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a pool of bubbles with matter.js. | setupBubblePool(_numBubbles){
let numObjs = _numBubbles;
for (let i = 0; i < numObjs; i++){
this.createBubble
(-99,-99, Math.random()*
(this.maxB-this.minB)+this.minB);
// Grab this object.
this.bubbles[i] = RedHen_2DPhysics.
lastObjectCreated();
// Time to sleep.
RedHen_2DPhysics.lastObjectCreated().
makeSleep(true);
}
} | [
"function generateCircles(number){\n\tfor (var i=0; i<=number;i++){\n\t\tvar circle= new CreateCircle();\n\t\tcircles.push(circle);\n\t};\n}",
"function drawPool() {\n //Draws water\n strokeWeight(2);\n fill(0, 0, 100, 220);\n rect(0, height-100, width, 100);\n\n //Pool deck\n fill(242, 242, 210);\n rect(0, height-102, 50, 102);\n rect(width-50, height-102, 50, 102);\n stroke(242, 242, 210);\n rect(0, height-20, width, 20);\n stroke(0);\n\n //Lines of the pool deck\n line(0, height-102, 0, height);\n line(50, height-21, width-50, height-21);\n strokeWeight(1);\n stroke(0);\n fill(0, 255, 0);\n\n //Diving boards\n rect(0, 110 * 1.5 - 11, width/3 + 10 + 3, 10);\n rect(0, 110 * 4.2 - 11, width/3 + 10 + 3, 10);\n}",
"function releaseBubbles() {\n createBubbles();\n for (var i = 0; i < bubbleCount; i++) {\n containerDiv.appendChild(bubbleBuffer[i]);\n }\n console.log(\"Bubbles released\");\n}",
"function generateTargets() {\n let number = 10;\n let result = [];\n while (result.length < number) {\n result.push({\n id: 'target-' + result.length,\n x: stage.width() * Math.random(),\n y: stage.height() * Math.random()\n });\n }\n return result;\n}",
"function getAllLevels() {\n return [\n [\n new __WEBPACK_IMPORTED_MODULE_2__bubbles_bubbleThree_js__[\"a\" /* default */](canvas.width/2 + 100, canvas.height - 130, 0),\n new __WEBPACK_IMPORTED_MODULE_3__bubbles_bubbleTwo_js__[\"a\" /* default */](canvas.width/2 - 180, canvas.height - 30 - 70, 0),\n new __WEBPACK_IMPORTED_MODULE_3__bubbles_bubbleTwo_js__[\"a\" /* default */](canvas.width/2 + 180, canvas.height - 30 - 70, 0)\n ], [\n new __WEBPACK_IMPORTED_MODULE_3__bubbles_bubbleTwo_js__[\"a\" /* default */](canvas.width/2 - 180, canvas.height - 70 - 100, -0.5),\n new __WEBPACK_IMPORTED_MODULE_3__bubbles_bubbleTwo_js__[\"a\" /* default */](canvas.width/2 - 130, canvas.height - 70 - 100, -0.5),\n // new BubbleTwo(canvas.width/2 - 80, canvas.height - 70 - 100, -0.5),\n // new BubbleTwo(canvas.width/2 + 80, canvas.height - 70 - 100, 0.5),\n new __WEBPACK_IMPORTED_MODULE_3__bubbles_bubbleTwo_js__[\"a\" /* default */](canvas.width/2 + 130, canvas.height - 70 - 100, 0.5),\n new __WEBPACK_IMPORTED_MODULE_3__bubbles_bubbleTwo_js__[\"a\" /* default */](canvas.width/2 + 180, canvas.height - 70 - 100, 0.5)\n ], [\n new __WEBPACK_IMPORTED_MODULE_1__bubbles_bubbleFour_js__[\"a\" /* default */](canvas.width/2 - 180, canvas.height - 70 - 100, -1),\n new __WEBPACK_IMPORTED_MODULE_4__bubbles_bubbleOne_js__[\"a\" /* default */](canvas.width/2 - 300, canvas.height - 160, 0.5),\n new __WEBPACK_IMPORTED_MODULE_4__bubbles_bubbleOne_js__[\"a\" /* default */](canvas.width/2 - 260, canvas.height - 160, 0.5),\n new __WEBPACK_IMPORTED_MODULE_4__bubbles_bubbleOne_js__[\"a\" /* default */](canvas.width/2 + 260, canvas.height - 160, -0.7),\n ],[\n new __WEBPACK_IMPORTED_MODULE_4__bubbles_bubbleOne_js__[\"a\" /* default */](canvas.width/2 - 300, canvas.height - 160, 0.1),\n new __WEBPACK_IMPORTED_MODULE_4__bubbles_bubbleOne_js__[\"a\" /* default */](canvas.width/2 - 260, canvas.height - 160, 0.1),\n new __WEBPACK_IMPORTED_MODULE_4__bubbles_bubbleOne_js__[\"a\" /* default */](canvas.width/2 - 220, canvas.height - 160, 0.1),\n new __WEBPACK_IMPORTED_MODULE_4__bubbles_bubbleOne_js__[\"a\" /* default */](canvas.width/2 + 220, canvas.height - 160, -0.1),\n new __WEBPACK_IMPORTED_MODULE_4__bubbles_bubbleOne_js__[\"a\" /* default */](canvas.width/2 + 260, canvas.height - 160, -0.1),\n new __WEBPACK_IMPORTED_MODULE_4__bubbles_bubbleOne_js__[\"a\" /* default */](canvas.width/2 + 300, canvas.height - 160, -0.1),\n new __WEBPACK_IMPORTED_MODULE_2__bubbles_bubbleThree_js__[\"a\" /* default */](canvas.width/2 + 100, canvas.height - 200, 1),\n new __WEBPACK_IMPORTED_MODULE_3__bubbles_bubbleTwo_js__[\"a\" /* default */](canvas.width/2 - 130, canvas.height - 160, -0.5),\n ], [\n new __WEBPACK_IMPORTED_MODULE_1__bubbles_bubbleFour_js__[\"a\" /* default */](canvas.width/2 - 180, canvas.height - 70 - 100, -0.5),\n new __WEBPACK_IMPORTED_MODULE_3__bubbles_bubbleTwo_js__[\"a\" /* default */](canvas.width/2 - 80, canvas.height - 70 - 100,-0.1),\n new __WEBPACK_IMPORTED_MODULE_3__bubbles_bubbleTwo_js__[\"a\" /* default */](canvas.width/2 + 80, canvas.height - 70 - 100, 0.5),\n new __WEBPACK_IMPORTED_MODULE_4__bubbles_bubbleOne_js__[\"a\" /* default */](canvas.width/2 + 260, canvas.height - 160, -0.5),\n new __WEBPACK_IMPORTED_MODULE_2__bubbles_bubbleThree_js__[\"a\" /* default */](canvas.width/2 + 100, canvas.height - 130, 0),\n ]\n ];\n}",
"function Bubble(x, y, p) {\n this.x = x;\n this.y = y;\n this.degree = p;\n\n // Dtermines the distance from mouse location.\n this.distX = 0;\n this.distY = 0;\n this.isPressed = false;\n\n // Determines the velocity of the note (range: [0,1]).\n // The diameter is the size of the bubble as used in\n // drawning an p5 ellipse.\n this.vel = VELOCITY;\n this.diam = DIAMETER;\n\n // Determines the coloring starting point.\n this.col = randomColor();\n\n this.display = function() {\n stroke(255);\n fill(this.col);\n ellipse(this.x, this.y, this.diam);\n }\n\n this.pressed = function() {\n let d = dist(mouseX, mouseY, this.x, this.y);\n if (d < this.diam / 2) {\n triggerAttack(this.degree, this.vel);\n this.isPressed = true;\n }\n }\n\n this.released = function () {\n let d = dist(mouseX, mouseY, this.x, this.y);\n if (d < this.diam) {\n this.brighten();\n triggerRelease(this.degree);\n this.isPressed = false;\n }\n }\n\n this.brighten = function () {\n this.col.setAlpha(alpha(this.col) + 1);\n }\n\n this.move = function() {\n this.x = this.x + random(-0.5, 0.5);\n this.y = this.y + random(-0.5, 0.5);\n }\n}",
"function setup() {\n createCanvas(500,500);\n // Instantiate the predator using the constructor\n predator = new Predator(width/2,height/2,25,5,color(255,0,0));\n // Run a loop numPrey times to create each prey\n for (var i = 0; i < numPrey; i++) {\n // Instantiate a new prey object\n var newPrey = new Prey(random(0,width),random(0,height),5,7,color(0,0,255));\n // Put the prey object into the array\n prey.push(newPrey);\n }\n}",
"function createSnowChildDivs(element,snowDotArray){\n let snowDot;\n for(i=0;i<100;i++){\n snowDot = document.createElement(\"div\");\n element.appendChild(snowDot);\n snowDot.setAttribute(\"class\",\"snowDot\");\n randomSnowSizes(snowDot);\n snowDot.style.opacity=0;\n fuzzySnow(snowDot);\n startingPosition(snowDot);\n snowDotArray.push(snowDot);\n }\n}",
"setupBackgroundBubbles(){\n let bubbleWrapper = document.getElementById(\"bubbleWrapper\");\n // while(bubbleWrapper.firstChild){\n // bubbleWrapper.removeChild(bubbleWrapper.firstChild); \n // }\n for(let i = 0; i < bubbleWrapper.children.length;i++){\n let bubble = bubbleWrapper.children[i];\n bubble.classList.remove(\"animInf\");\n bubble.classList.add(\"animOnce\");\n bubble.addEventListener(\"animationend\",()=>{bubble.remove()})\n }\n\n for(let i = 0; i < Math.round(bubbleWrapper.offsetWidth / 5); i++){\n let div = document.createElement(\"div\");\n div.setAttribute(\"class\",\"bgBubble animInf\")\n div.setAttribute(\"style\",\"left:\" + Math.round(Math.random() * (bubbleWrapper.offsetWidth - 20)) + \"px; animation: moveUp \" + ((Math.random() * 10) + 5) + \"s linear\");\n bubbleWrapper.appendChild(div)\n }\n }",
"function createChips() {\n chipXCenterOne = -0.5;\n chipYCenterOne = 0.5;\n\n chipXCenterFive = 0.5;\n chipYCenterFive = 0.5;\n\n chipXCenterTen = -0.5;\n chipYCenterTen = -0.5;\n\n chipXCenterTwoFive = 0.5;\n chipYCenterTwoFive = -0.5;\n\n // Generic Circle\n var p = vec2(0.0, 0.0);\n chipVertices = [p];\n var radius = 1;\n var increment = Math.PI / 36;\n\n for (var theta = 0.0; theta < Math.PI * 2 - increment; theta += increment) {\n if (theta == 0.0) {\n chipVertices.push(\n vec2(Math.cos(theta) * radius, Math.sin(theta) * radius)\n );\n }\n chipVertices.push(\n vec2(\n Math.cos(theta + increment) * radius,\n Math.sin(theta + increment) * radius\n )\n );\n }\n\n // Generic Rectangle for chips\n markerVertices = [\n vec2(-1.5, 0.25),\n vec2(-1.5, -0.25),\n vec2(0, 0.25),\n\n vec2(0, 0.25),\n vec2(0, -0.25),\n vec2(-1.5, -0.25),\n ];\n\n chipVertices.push(...markerVertices);\n\n // Make Bet Area from 2 rectangles and 1 part of a circle\n // Wide Area One\n betAreaWideVertices = [\n vec2(-0.15, 0.0),\n vec2(-0.15, 1.4),\n vec2(0.15, 0),\n\n vec2(0.15, 0),\n vec2(0.15, 1.4),\n vec2(-0.15, 1.4),\n ];\n chipVertices.push(...betAreaWideVertices);\n\n // Tall Area One\n betAreaTallVertices = [\n vec2(-0.1, 0.0),\n vec2(-0.1, 1.45),\n vec2(0.1, 0),\n\n vec2(0.1, 0),\n vec2(0.1, 1.45),\n vec2(-0.1, 1.45),\n ];\n\n chipVertices.push(...betAreaTallVertices);\n\n // Corner\n var k = vec2(0.0, 0.0);\n var cornerVerts = [k];\n var radius = 1;\n var increment = Math.PI / 36;\n\n for (var theta = 0.0; theta < Math.PI * 2 - increment; theta += increment) {\n if (theta == 0.0) {\n cornerVerts.push(\n vec2(Math.cos(theta) * radius, Math.sin(theta) * radius)\n );\n }\n cornerVerts.push(\n vec2(\n Math.cos(theta + increment) * radius,\n Math.sin(theta + increment) * radius\n )\n );\n }\n\n chipVertices.push(...cornerVerts);\n\n // Set Colors\n // 1 - white/blue\n chipOnePrimary = vec3(1.0, 1.0, 1.0);\n chipOneSecondary = vec3(20 / 255, 20 / 255, 175 / 255);\n\n // 5 - red/white\n chipFivePrimary = vec3(180 / 255, 10 / 255, 10 / 255);\n chipFiveSecondary = vec3(1.0, 1.0, 1.0);\n\n // 10 - blue/white\n chipTenPrimary = vec3(50 / 255, 50 / 255, 200 / 255);\n chipTenSecondary = vec3(1.0, 1.0, 1.0);\n\n // 25 - black/white\n chipTwoFivePrimary = vec3(0.0, 0.0, 0.0);\n chipTwoFiveSecondary = vec3(1.0, 1.0, 1.0);\n}",
"function setup() {\n createCanvas(windowWidth, 400);\n let b = new Snow(width/2, height/2, 10);\n snow.push(b);\n}",
"makeObjPool () {\n\t\t// Runs update method for objects within this group\n\t\tthis.alienG = this.physics.add.group({classType: Alien, runChildUpdate: true});\n\t\tthis.alienB = this.physics.add.group({classType: AlienB, runChildUpdate: true});\n\t\tthis.alienR = this.physics.add.group({classType: AlienR, runChildUpdate: true});\n\t\tthis.boss = this.physics.add.group({classType: Boss, runChildUpdate: true});\n\n\t\t// Tower group\n\t\tthis.towerW = this.add.group({classType: WoodTower, runChildUpdate: true});\n\t\tthis.towerSC = this.add.group({classType: SCTower, runChildUpdate: true});\n\t\tthis.towerF = this.add.group({classType: FlameTower, runChildUpdate: true});\n\n\t\t// Projectile group\n\t\tthis.projectileW = this.physics.add.group({classType: WoodProjectile, runChildUpdate: true});\n\t\tthis.projectileSC = this.physics.add.group({classType: scProjectile, runChildUpdate: true});\n\t\tthis.projectileF = this.physics.add.group({classType: fProjectile, runChildUpdate: true});\n\t\t\n\t\t// Check for colission (Wood projectile)\n\t\tthis.physics.add.overlap(this.alienG, this.projectileW, this.takeDmg.bind(this));\n\t\tthis.physics.add.overlap(this.alienB, this.projectileW, this.takeDmg.bind(this));\n\t\tthis.physics.add.overlap(this.alienR, this.projectileW, this.takeDmg.bind(this));\n\t\tthis.physics.add.overlap(this.boss, this.projectileW, this.takeDmg.bind(this));\n\n\t\t// Check for colission (SC projectile)\n\t\tthis.physics.add.overlap(this.alienG, this.projectileSC, this.takeDmg.bind(this));\n\t\tthis.physics.add.overlap(this.alienB, this.projectileSC, this.takeDmg.bind(this));\n\t\tthis.physics.add.overlap(this.alienR, this.projectileSC, this.takeDmg.bind(this));\n\t\tthis.physics.add.overlap(this.boss, this.projectileSC, this.takeDmg.bind(this));\n\t\t\n\t\t// Check for colission (Flame projectile)\n\t\tthis.physics.add.overlap(this.alienG, this.projectileF, this.takeDmg.bind(this));\n\t\tthis.physics.add.overlap(this.alienB, this.projectileF, this.takeDmg.bind(this));\n\t\tthis.physics.add.overlap(this.alienR, this.projectileF, this.takeDmg.bind(this));\n\t\tthis.physics.add.overlap(this.boss, this.projectileF, this.takeDmg.bind(this));\n\n\t\t// Listen for player click and runs buildTower\n\t\tthis.input.on('pointerdown', this.buildTower.bind(this));\n\t}",
"function generateBaskets() {\n container = document.getElementById('container');\n var square_dummy = document.getElementById(\"Square1\");\n var rect_dummy = square_dummy.getBoundingClientRect();\n var i = 0;\n for (point in basket_points) {\n basket = document.createElement('div'); \n basket.setAttribute('id', 'Basket' + (i + 1));\n basket.setAttribute('style', 'position: absolute; border:3px solid black; text-align:center');\n basket.style.left = basket_points[point].x + 'px';\n basket.style.top = basket_points[point].y + 'px';\n basket.style.width = rect_dummy.width * 3 + 'px';\n basket.style.height = rect_dummy.height * 2 + 'px';\n container.appendChild(basket);\n i++;\n }\n}",
"function createTreasure() {\n for (i = 0; i <= treasureNumber; i++) {\n let newPiece = new treasurePiece;\n treasure.push(newPiece);\n }\n}",
"function add_grouped(entity_name) {\n var variance_mapping = {\n 'bubble': 100,\n 'jellyfish': 250\n };\n var spawn_mapping = {\n 'bubble': add_bubble,\n 'jellyfish': add_jellyfish\n }\n var max_mapping = {\n 'bubble': 50,\n 'jellyfish': 20\n }\n\n var x_coord = Math.floor(Math.random() * game.world.width);\n var y_coord = 0;\n var n = Math.floor(4 + (Math.random() * max_mapping[entity_name]));\n\n for (var i = 0; i < n; i++) {\n var pos_neg = Math.random() <= 0.5 ? -1 : 1;\n var x_variance = pos_neg * Math.random() * variance_mapping[entity_name];\n var y_variance = -1 * Math.random() * variance_mapping[entity_name];\n\n spawn_mapping[entity_name](\n x_coord + x_variance, y_coord + y_variance);\n }\n}",
"function generateBag() {\n bag = [];\n var contents = \"\";\n //7 shapes\n for (var i = 0; i < 7; i++) {\n //generate shape randomly\n var shape = randomKey(shapes);\n while(contents.indexOf(shape) != -1) {\n shape = randomKey(shapes);\n }\n //update bag with generated shape\n bag[i] = shape;\n contents += shape;\n }\n //reset bag index\n bagIndex = 0;\n }",
"createMatingPool() {\n let matingPool = [],\n limit;\n this.chromosomes.forEach((chromosome, index) => {\n limit = chromosome.fitness * 1000;\n for (let i = 0; i < limit; i++) matingPool.push(index);\n });\n return matingPool;\n }",
"function setup() {\n createCanvas(700, 500);\n dinoStegosaurus = new Dino(200, 200, 5, 40, 87, 83, 65, 68, 16, dinoStegosaurusImage);\n dinoTriceratops = new Dino(100, 100, 5, 40, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW, 32, dinoTriceratopsImage);\n foodLeaves = new Food(100, 100, 10, 25, foodLeavesImage);\n foodBerries = new Food(100, 100, 8, 25, foodBerriesImage);\n foodPlant = new Food(100, 100, 20, 25, foodPlantImage);\n // New classes - Legendary\n // articuno = new CatalystFlood(100, 100, 20, 100, articunoImage);\n // moltres = new CatalystFire(50, 100, 20, 100, moltresImage);\n // zapdos = new CatalystMeteor(50, 100, 20, 100, zapdosImage);\n // Place dinos into array\n dinos = [dinoStegosaurus, dinoTriceratops];\n}",
"function createPallet(){\n\tfor(let i = 0; i < numColor; i++){\n\t\tswatches.push(new ColorSwatch(\t((i*colorSwatchRadius)+colorSwatchRadius/2), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolorSwatchRadius/2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolorSwatchRadius/2, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t colorArray[i]));\n\t}\n\tfillIcon = new FillIcon(canvasWidth-frameThickness*.75, canvasWidth/40, canvasWidth/20);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup Color of all meshs of the scene | function setupNewColorsMeshs() {
cubeMeshs.forEach(object => {
object.children[0].children[0].material[1].color = colorScene;
object.children[0].children[0].material[1].emissive = colorScene;
});
torusMesh.forEach(object => {
switch (countTic > 2) {
case true:
object.children[0].material[1].emissive = new THREE.Color(0xffffff);
object.children[0].material[1].color = new THREE.Color(0xffffff);
object.children[0].material[4].emissive = colorScene;
object.children[0].material[4].color = colorScene;
break;
case false:
object.children[0].material[1].emissive = colorScene;
object.children[0].material[1].color = colorScene;
object.children[0].material[4].emissive = new THREE.Color(0xffffff);
object.children[0].material[4].color = new THREE.Color(0xffffff);
break;
}
});
} | [
"buildMaterials () {\n this._meshes.forEach((mesh) => {\n let material = mesh.material;\n\n let position = new THREE.PositionNode();\n let alpha = new THREE.FloatNode(1.0);\n let color = new THREE.ColorNode(0xEEEEEE);\n\n // Compute transformations\n material._positionVaryingNodes.forEach((varNode) => {\n position = new THREE.OperatorNode(\n position,\n varNode,\n THREE.OperatorNode.ADD\n );\n });\n\n let operator;\n material._transformNodes.forEach((transNode) => {\n position = getOperatornode(\n position,\n transNode.get('node'),\n transNode.get('operator')\n );\n });\n\n // Compute alpha\n material._alphaVaryingNodes.forEach((alphaVarNode) => {\n alpha = new THREE.OperatorNode(\n alpha,\n alphaVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._alphaNodes.forEach((alphaNode) => {\n alpha = getOperatornode(\n alpha,\n alphaNode.get('node'),\n alphaNode.get('operator')\n );\n });\n\n // Compute color\n material._colorVaryingNodes.forEach((colorVarNode) => {\n color = new THREE.OperatorNode(\n color,\n colorVarNode,\n THREE.OperatorNode.ADD\n );\n });\n\n material._colorNodes.forEach((colorNode) => {\n color = getOperatornode(\n color,\n colorNode.get('node'),\n colorNode.get('operator')\n );\n });\n\n // To display surfaces like 2D planes or iso-surfaces whatever\n // the point of view\n mesh.material.side = THREE.DoubleSide;\n\n // Set wireframe status and shading\n if (mesh.type !== 'LineSegments' && mesh.type !== 'Points') {\n mesh.material.wireframe = this._wireframe;\n mesh.material.shading = this._wireframe\n ? THREE.SmoothShading\n : THREE.FlatShading;\n } else {\n mesh.material.wireframe = false;\n // Why ?\n // mesh.material.shading = THREE.SmoothShading;\n }\n\n // Get isoColor node\n mesh.material.transform = position;\n mesh.material.alpha = alpha;\n mesh.material.color = color;\n mesh.material.build();\n });\n }",
"initializeMeshes () {\r\n this.triangleMesh = new Mesh(this.cyanYellowHypnoMaterial, this.triangleGeometry);\r\n this.quadMesh = new Mesh(this.magentaMaterial, this.quadGeometry);\r\n\r\n // texture code\r\n this.texturedQuadMesh = new Mesh(this.texturedMaterial, this.texturedQuadGeometry);\r\n }",
"set MeshRenderer(value) {}",
"set Mesh(value) {}",
"changeColorRed() {\n this.planet.loadTexture('planetred');\n this.mini.loadTexture('planetred');\n }",
"ColorUpdate(colors) {\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(255, 255, 255, 255));\n\n colors.push(vec4(100, 100, 100, 255));\n colors.push(vec4(127, 127, 127, 255));\n colors.push(vec4(10, 10, 10, 210));\n colors.push(vec4(127, 127, 127, 255));\n\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n colors.push(vec4(255, 255, 255, 255));\n colors.push(vec4(127,127, 127, 255));\n \n if (Sky.instance.GlobalTime >= 9 && Sky.instance.GlobalTime < 19){\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 200));\n colors.push(vec4(100, 100, 100, 255));\n // StreetLamp Light turn off\n // ColorUpdate => Black\n }\n else {\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 200));\n colors.push(vec4(255, 255, 0, 255));\n // StreetLamp Light turn on\n // ColorUpdate => Yell Light\n }\n }",
"function lightingSetUp(){\n\n keyLight = new THREE.DirectionalLight(0xFFFFFF, 1.0);\n keyLight.position.set(3, 10, 3).normalize();\n keyLight.name = \"Light1\";\n\n fillLight = new THREE.DirectionalLight(0xFFFFFF, 1.2);\n fillLight.position.set(0, -5, -1).normalize();\n fillLight.name = \"Light2\";\n\n backLight = new THREE.DirectionalLight(0xFFFFFF, 0.5);\n backLight.position.set(-10, 0, 0).normalize();\n backLight.name = \"Light3\";\n\n scene.add(keyLight);\n scene.add(fillLight);\n scene.add(backLight);\n}",
"function setColor() {\n for(let i = 0; i < boxes.length; i++) {\n boxes[i].style.backgroundColor = color[i];\n } \n}",
"function loadSurfaceColor () {\n\n setShaderColor( controller.configure.color.surface );\n\n if ( controller.configure.color.selected === null ) {\n\n setHighlightColor( controller.configure.color.surface );\n\t\t\tconsole.log('highlight color===========>', controller.configure.color.surface)\n } else {\n\n setHighlightColor( controller.configure.color.selected );\n\n }\n\n }",
"createScene() {\n\n this.heightMap = new NoiseMap();\n this.heightMaps = this.heightMap.maps;\n\n this.moistureMap = new NoiseMap();\n this.moistureMaps = this.moistureMap.maps;\n\n this.textureMap = new TextureMap();\n this.textureMaps = this.textureMap.maps;\n\n this.normalMap = new NormalMap();\n this.normalMaps = this.normalMap.maps;\n\n this.roughnessMap = new RoughnessMap();\n this.roughnessMaps = this.roughnessMap.maps;\n\n for (let i=0; i<6; i++) { //Create 6 materials, each with white color\n let material = new THREE.MeshStandardMaterial({\n color: new THREE.Color(0xFFFFFF)\n });\n this.materials[i] = material;\n }\n\n let geo = new THREE.BoxGeometry(1, 1, 1, 64, 64, 64); //Creating a box\n let radius = this.size;\n for (var i in geo.vertices) {\n \t\tvar vertex = geo.vertices[i];\n \t\tvertex.normalize().multiplyScalar(radius);\n \t}\n this.computeGeometry(geo); //Squeezing a box into a sphere\n\n this.ground = new THREE.Mesh(geo, this.materials); //Create ground mesh with squeezed box sphere and 6 materials\n this.view.add(this.ground);\n }",
"function setColour() {\r\n vertices.selectAll(\"circle\")\r\n .style(\"fill\", function (v) {\r\n\r\n // If not connected to any other vertex, set colour to grey\r\n if (!v.degree)\r\n return customColours[2];\r\n\r\n // If general graph, set colour to red\r\n if (selectedAlgorithm == 3)\r\n return customColours[1];\r\n\r\n // If left-hand vertex, set colour to red and if right-hand vertex, set colour to blue\r\n if (v.parity)\r\n return customColours[v.parity % 2];\r\n\r\n // If non-bipartite graph, use one of the standard colours\r\n else\r\n return standardColours(v.id);\r\n\r\n });\r\n}",
"setup() {\n this.material = new THREE.ShaderMaterial({\n uniforms: this.uniforms.uniforms,\n fragmentShader: this.shaders.fragment_shader,\n vertexShader: this.shaders.vertex_shader\n });\n }",
"setFaceColor ( face, RGB) {\n\t\t// debug\n\t\t//console.log(\"atomicGLskyBox(\"+this.name+\")::setFaceColor\");\n\t\tvar r = RGB[0];\n\t\tvar g = RGB[1];\n\t\tvar b = RGB[2];\n\t\t\n\t\t// switch face\n\t\tswitch(face){\n\t\t\tcase \"Front\":\n\t\t\t\tthis.colorsArray[0] =r;\n\t\t\t\tthis.colorsArray[1] =g;\n\t\t\t\tthis.colorsArray[2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[3] =r;\n\t\t\t\tthis.colorsArray[4] =g;\n\t\t\t\tthis.colorsArray[5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[6] =r;\n\t\t\t\tthis.colorsArray[7] =g;\n\t\t\t\tthis.colorsArray[8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[9] =r;\n\t\t\t\tthis.colorsArray[10] =g;\n\t\t\t\tthis.colorsArray[11] =b;\t\t\t\n\t\t\tbreak;\n\n\t\t\tcase \"Back\":\n\t\t\t\tthis.colorsArray[12+0] =r;\n\t\t\t\tthis.colorsArray[12+1] =g;\n\t\t\t\tthis.colorsArray[12+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[12+3] =r;\n\t\t\t\tthis.colorsArray[12+4] =g;\n\t\t\t\tthis.colorsArray[12+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[12+6] =r;\n\t\t\t\tthis.colorsArray[12+7] =g;\n\t\t\t\tthis.colorsArray[12+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[12+9] =r;\n\t\t\t\tthis.colorsArray[12+10] =g;\n\t\t\t\tthis.colorsArray[12+11] =b;\n\t\t\tbreak;\t\t\t\n\t\t\tcase \"Top\":\n\t\t\t\tthis.colorsArray[24+0] =r;\n\t\t\t\tthis.colorsArray[24+1] =g;\n\t\t\t\tthis.colorsArray[24+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[24+3] =r;\n\t\t\t\tthis.colorsArray[24+4] =g;\n\t\t\t\tthis.colorsArray[24+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[24+6] =r;\n\t\t\t\tthis.colorsArray[24+7] =g;\n\t\t\t\tthis.colorsArray[24+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[24+9] =r;\n\t\t\t\tthis.colorsArray[24+10] =g;\n\t\t\t\tthis.colorsArray[24+11] =b;\n\t\t\tbreak;\t\t\t\n\t\t\tcase \"Bottom\":\n\t\t\t\tthis.colorsArray[36+0] =r;\n\t\t\t\tthis.colorsArray[36+1] =g;\n\t\t\t\tthis.colorsArray[36+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[36+3] =r;\n\t\t\t\tthis.colorsArray[36+4] =g;\n\t\t\t\tthis.colorsArray[36+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[36+6] =r;\n\t\t\t\tthis.colorsArray[36+7] =g;\n\t\t\t\tthis.colorsArray[36+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[36+9] =r;\n\t\t\t\tthis.colorsArray[36+10] =g;\n\t\t\t\tthis.colorsArray[36+11] =b;\n\t\t\tbreak;\t\t\t\n\t\t\tcase \"Left\":\n\t\t\t\tthis.colorsArray[48+0] =r;\n\t\t\t\tthis.colorsArray[48+1] =g;\n\t\t\t\tthis.colorsArray[48+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[48+3] =r;\n\t\t\t\tthis.colorsArray[48+4] =g;\n\t\t\t\tthis.colorsArray[48+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[48+6] =r;\n\t\t\t\tthis.colorsArray[48+7] =g;\n\t\t\t\tthis.colorsArray[48+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[48+9] =r;\n\t\t\t\tthis.colorsArray[48+10] =g;\n\t\t\t\tthis.colorsArray[48+11] =b;\n\t\t\tbreak;\t\t\t\t\n\t\t\tcase \"Right\":\n\t\t\t\tthis.colorsArray[60+0] =r;\n\t\t\t\tthis.colorsArray[60+1] =g;\n\t\t\t\tthis.colorsArray[60+2] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[60+3] =r;\n\t\t\t\tthis.colorsArray[60+4] =g;\n\t\t\t\tthis.colorsArray[60+5] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[60+6] =r;\n\t\t\t\tthis.colorsArray[60+7] =g;\n\t\t\t\tthis.colorsArray[60+8] =b;\n\t\t\t\n\t\t\t\tthis.colorsArray[60+9] =r;\n\t\t\t\tthis.colorsArray[60+10] =g;\n\t\t\t\tthis.colorsArray[60+11] =b;\n\t\t\tbreak;\t\n\t\t\tcase \"All\":\n\t\t\t\tthis.colorsArray = [\n\t\t\t\t\t// Front face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Back face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Top face \n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Bottom face : floor\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Left face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t\t// Right face\n\t\t\t\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\t\tr, g, b,\n\t\t\t\t];\t\n\t\t\tbreak;\t\t\n\t\t}\n\t}",
"applyColor(_materialComponent) {\n let colorPerPosition = [];\n for (let i = 0; i < this.vertexCount; i++) {\n colorPerPosition.push(_materialComponent.Material.Color.X, _materialComponent.Material.Color.Y, _materialComponent.Material.Color.Z);\n }\n WebEngine.gl2.bufferData(WebEngine.gl2.ARRAY_BUFFER, new Uint8Array(colorPerPosition), WebEngine.gl2.STATIC_DRAW);\n }",
"function initScene() {\n gScene = new THREE.Scene();\n gScene.background = new THREE.Color(0xcccccc);\n gScene.fog = new THREE.FogExp2(0xcccccc, 0.002);\n}",
"function makeAllNodesFullOpacity(){\n model.nodeDataArray.forEach(node => {\n setOpacity(node, 1);\n })\n}",
"function updateMazeStyle(isLight) {\r\n clearCanvas(); /* Clear the Canvas first */\r\n if (isLight) {\r\n lineClr = 'rgba(0,0,0,0.5)';\r\n } else {\r\n lineClr = 'rgba(255,255,255,0.5)';\r\n }\r\n drawcells(); /* Redraw the cells */\r\n}",
"function createMeshes() {\r\n mesh_lantern1 = createLantern ();\r\n scene.add(mesh_lantern1);\r\n\r\n mesh_lantern2 = mesh_lantern1.clone();\r\n mesh_lantern2.translateX(15.0);\r\n scene.add(mesh_lantern2);\r\n\r\n mesh_lantern3 = mesh_lantern1.clone();\r\n mesh_lantern3.translateZ(-20.0);\r\n scene.add(mesh_lantern3);\r\n}",
"setTextureBaseColor(color) {\n //TODO\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to draw a complete route. id: Unique id of the route. route: A list of coordinates. | function drawRoute(id, route){
for(var i=0; i<route.length-1; i++){
drawSegment(id, route[i], route[i+1]);
}
} | [
"function drawRoute(map, route, color) {\n for (var i = 0; i < route.length; i++) {\n stop = route[i][0];\n var edge = [];\n edge.push(stop.coords);\n\n /* loop to handle forks */\n for (var j = 0; j < route[i][1].length; j++) {\n edge.push(route[i][1][j].coords)\n var path = new google.maps.Polyline({\n path: edge,\n geodesic: true,\n strokeColor: color,\n strokeOpacity: 1.0,\n strokeWeight: 2\n });\n path.setMap(map);\n edge.pop();\n }\n }\n}",
"function drawRoute(coords, color) {\n var routeLine = L.polyline(coords, {\n color: color,\n weight: 7\n });\n\n layers[\"routeLine\"] = new L.LayerGroup();\n layers[\"routeLine\"].addLayer(routeLine);\n layers[\"routeLine\"].addTo(map);\n map.fitBounds(routeLine.getBounds());\n}",
"function drawPolylineByCoordinates(id, coordinates){\n\t\n\tvar polylineCoordinates = [];\n\t\n\tfor(i=0; i<coordinates.length; i++){\n\t\t\n\t\tpolylineCoordinates.push(new google.maps.LatLng(coordinates[i][0], coordinates[i][1]));\n\t}\n\n\tvar polyline = new google.maps.Polyline({\n\t\tpath: polylineCoordinates,\n\t\tgeodesic: true,\n\t\tstrokeColor: '#FF0000',\n\t\tstrokeOpacity: 1.0,\n\t\tstrokeWeight: 2\n\t});\n\t\n\t//Draw the polyline\n\tpolyline.setMap(map);\n\t\n\t//Add the line to the dictionary\n\tif(routesDictionary[id] === undefined){\n\t\n\t\troutesDictionary[id] = [];\n\t}\n\t\t\n\troutesDictionary[id].push(polyline);\n}",
"function drawSegment(id, startCoord, endCoord){\n\n\tvar start = new google.maps.LatLng(startCoord[0], startCoord[1]);\n\tvar end = new google.maps.LatLng(endCoord[0], endCoord[1]);\n\n\t//Payload to be sent to the Maps API\n\tvar request = {\n\t\t\torigin: start,\n\t\t\tdestination: end,\n\t\t\ttravelMode: google.maps.TravelMode.DRIVING\n\t}\t\n\n\t//Returned path\n\tdirectionsService.route(request, function(result, status){\n\n\t\tif (status == google.maps.DirectionsStatus.OK){\n\t\t\tdrawPolyline(id, result.routes[0].legs);\n\t\t}\n\t});\n}",
"function route1Anim(){\n if(delta < 1){\n delta += 0.2;\n } else {\n visitedRoutes.push(allCoordinates[coordinate]) // Once it has arrived at its destination, add the origin as a visited location\n delta = 0;\n coordinate ++;\n drawRoute(); // Call the drawRoute to update the route\n }\n\n const latitude_origin = Number(runLocations.getString(coordinate, 'Position/LatitudeDegrees'));\n const longitude_origin = Number(runLocations.getString(coordinate, 'Position/LongitudeDegrees'));\n\n const latitude_destination = Number(runLocations.getString(coordinate +1,'Position/LatitudeDegrees'));\n const longitude_destination = Number(runLocations.getString(coordinate +1, 'Position/LongitudeDegrees'));\n origin = myMap.latLngToPixel(latitude_origin,longitude_origin);\n originVector = createVector(origin.x, origin.y);\n destination = myMap.latLngToPixel(latitude_destination,longitude_destination);\n destinationVector = createVector(destination.x, destination.y);\n\n runPosition = originVector.lerp(destinationVector, delta);\n\n noStroke(); // remove the stroke from the route\n fill(255,255,0);\n ellipse(runPosition.x, runPosition.y, 7, 7);\n}",
"roadLineDrawtest()\n {\n this.direction.route({\n origin:{lng:-78,lat:39.137},\n destination:{lat:39.281,lng:-76.60},\n travelMode:google.maps.TravelMode.DRIVING\n },(r,s)=>{\n var pathPoints=r.routes[0].overview_path;\n var path=new google.maps.Polyline({\n path:pathPoints\n });\n\n path.setMap(this.map);\n });\n }",
"function displayFromShapeId(shapeId, routeId) {\r\n var source = 'http://www.miamidade.gov/transit/WebServices/BusRouteShape/?ShapeID='+shapeId;\r\n $.getJSON(\r\n 'http://anyorigin.com/dev/get?url='+source+'&callback=?',\r\n (function(thisshapeId, thisRouteId) {\r\n return function(data) {\r\n //if (debug) console.log(\"Data received. Displaying route from the Shape ID: \"+thisshapeId);\r\n // Find the color for the route\r\n var color = \"\";\r\n for (i = 0; i < tripRouteShapeRef.length; i++) {\r\n if (tripRouteShapeRef[i].shapeId == thisshapeId) {\r\n color = tripRouteShapeRef[i].color;\r\n break;\r\n }\r\n }\r\n\r\n if (displayedShapeIds.length === 0) { // Display the first shape ID\r\n addRoutePoints(busLayer, '#'+color, $.parseXML(data.contents), thisRouteId);\r\n addDisplayedShapeId(thisshapeId);\r\n } else { // Check for any duplicate shape ID and not display\r\n for (var displayed in displayedShapeIds) {\r\n if (displayed == thisshapeId) break;\r\n addRoutePoints(busLayer, '#'+color, $.parseXML(data.contents), thisRouteId);\r\n addDisplayedShapeId(thisshapeId);\r\n break;\r\n //if (debug) console.log(\"Added new shapeId: \"+thisshapeId);\r\n }\r\n }\r\n if (debug) console.log(\"tripRouteShapeRef length = \"+tripRouteShapeRef.length);\r\n if (debug) console.log(\"displayedShapeIds length = \"+displayedShapeIds.length);\r\n };\r\n }(shapeId, routeId))\r\n );\r\n}",
"function route2Anim(){\n if(delta < 1){\n delta += 0.2;\n } else {\n visitedRoutes.push(allCoordinates[coordinate]) // Once it has arrived at its destination, add the origin as a visited location\n delta = 0;\n coordinate ++;\n drawRoute(); // Call the drawRoute to update the route\n }\n\n const latitude_origin = Number(runLocations2.getString(coordinate, 'Position/LatitudeDegrees'));\n const longitude_origin = Number(runLocations2.getString(coordinate, 'Position/LongitudeDegrees'));\n\n const latitude_destination = Number(runLocations2.getString(coordinate +1,'Position/LatitudeDegrees'));\n const longitude_destination = Number(runLocations2.getString(coordinate +1, 'Position/LongitudeDegrees'));\n origin = myMap.latLngToPixel(latitude_origin,longitude_origin);\n originVector = createVector(origin.x, origin.y);\n destination = myMap.latLngToPixel(latitude_destination,longitude_destination);\n destinationVector = createVector(destination.x, destination.y);\n\n runPosition = originVector.lerp(destinationVector, delta);\n\n noStroke(); // remove the stroke from the route\n fill(255,255,0);\n ellipse(runPosition.x, runPosition.y, 7, 7);\n}",
"function displayRoute() {\r\n clearOverlays();\r\n var start\r\n var end\r\n if (inputLocation == \"\") { start = currentLocation; end = currentCafeLocation; }\r\n else { start = inputLocation; end = currentCafeLocation; }\r\n\r\n var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get \"DirectionsRendererOptions\" object\r\n directionsDisplay.setMap(map); // map should be already initialized.\r\n\r\n var request = { origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING };\r\n var directionsService = new google.maps.DirectionsService();\r\n directionsService.route(request, function (response, status) {\r\n if (status == google.maps.DirectionsStatus.OK) {\r\n directionsDisplay.setDirections(response);\r\n }\r\n });\r\n markersArray.push(directionsDisplay);\r\n}",
"draw()\n {\n var canvas = document.getElementById(\"CANVAS\");\n var ctx = canvas.getContext(\"2d\");\n var cVehicles = this.getVehicleCount();\n\n ctx.save();\n ctx.scale(def.scale, def.scale);\n\n this._drawRoute(ctx);\n for (let iVehicle = 0; iVehicle < cVehicles; iVehicle ++)\n this._drawVehicle(ctx, route.getVehicle(iVehicle));\n\n ctx.restore();\n }",
"function drawRoad(counter){\n //set background\n background(50);\n //Space between lines\n let space = width / 4;\n //Gap between dashed lines\n let step = height / 10;\n //Line width\n let lineW = 10;\n //Road lines\n //Remove outline on shapes\n noStroke();\n //Dashed lines\n for (i = - 2; i < height; i++) {\n //Yellow lines\n fill(255,i * 25, 0);\n rect(space, step * i + counter, 10, 30);\n rect(space * 3, step * i + counter, 10, 30);\n }\n for(i = 0; i < maxH; i++){\n let val = map(i, 0, maxH, 0, 255);\n stroke(255, val, 0);\n line(0, i, lineW, i);\n \n line(space * 2 - lineW, i, space * 2 - lineW * 2, i);\n line(space * 2 + lineW, i, space * 2 + lineW * 2, i);\n line(maxW - lineW, i, maxW, i); \n }\n}",
"function calcRoute() {\n\t// Prepare the API call\n\tvar start = start_location.geometry.location;\n\tvar end = end_location.geometry.location;\n\tvar request = {\n\t\torigin: start,\n\t\tdestination: end,\n\t\ttravelMode: 'DRIVING'\n\t};\n\n\t// Call Google Maps API\n\tdirectionsService.route(request, function (result, status) {\n\t\tconsole.log(result);\n\t\tif (status == 'OK') {\n\t\t\t// Update the map to show the route\n\t\t\tdirectionsDisplay.setDirections(result);\n\n\t\t\t// List out the roads that the route includes\n\t\t\tvar routes = result.routes;\n\n\t\t\tdocument.getElementById(\"routeslist\").innerHTML = '';\n\t\t\tfor (var i = 0; i < routes[0].legs[0].steps.length; i++) {\n\t\t\t\tvar routePath = routes[0].legs[0].steps[i].path;\n\t\t\t\tvar road_location = routePath[Math.floor(routePath.length / 2)];\n\t\t\t\tvar duration = routes[0].legs[0].steps[i].duration.value;\n\t\t\t\tvar distance = routes[0].legs[0].steps[i].distance.value;\n\n\t\t\t\t// speed in miles per hour\n\t\t\t\tvar speed = distance * 0.000621371 / (duration / 3600);\n\n\t\t\t\t\n\t\t\t\t//console.log(\"Speed: \" + speed);\n\n\t\t\t\tspeed = Math.max(20, Math.round(speed/10) * 10);\n\n\t\t\t\t//console.log(\"New Speed: \" + speed);\n\t\t\t\tvar polyline = routes[0].legs[0].steps[i].polyline;\n\n\t\t\t\tprocessStep(road_location, duration, distance, speed, routePath, polyline);\n\t\t\t}\n\t\t}\n\n\n\t});\n}",
"function addRoad(id, roadShapeArr, showForm, showMapMatch){\n\t\tvar direction=\"BOTH\";\n\n\t\tvar roadGroup = new H.map.Group();\n\t\troadGroup.roadShapeArr = roadShapeArr;\n\t\t// add the road/link as polygon on the map\n\t\tvar road = new H.geo.Strip();\n\t\tfor(var i=0; i<roadShapeArr.length; i++){\n\t\t\troad.pushPoint(new H.geo.Point(roadShapeArr[i][0], roadShapeArr[i][1]));\n\t\t}\n\t\tcurrentRoadShape = new H.map.Polyline(road, roadDisplayOptions[id%6]);\n\t\t// highlight the polyline on mouse hover\n\t\tcurrentRoadShape.addEventListener('pointerenter', function(e){\n\t\t\tdocument.getElementById('mapContainer').style.cursor = 'pointer';\n\t\t\te.currentTarget.setStyle(e.currentTarget.getStyle().getCopy({\n\t\t\t\tlineWidth: 9\n\t\t\t}));\n\t\t});\n\t\tcurrentRoadShape.addEventListener('pointerleave', function(e){\n\t\t\tdocument.getElementById('mapContainer').style.cursor = 'default';\n\t\t\te.currentTarget.setStyle(e.currentTarget.getStyle().getCopy({\n\t\t\t\tlineWidth: 7,\n\t\t\t\tstrokeColor: roadDisplayOptions[e.currentTarget.getGeometry().id%6].style.strokeColor\n\t\t\t}));\n\t\t});\n\t\tcurrentRoadShape.addEventListener('pointercancel', function(e){\n\t\t\tdocument.getElementById('mapContainer').style.cursor = 'default';\n\t\t\te.currentTarget.setStyle(e.currentTarget.getStyle().getCopy({\n\t\t\t\tlineWidth: 7,\n\t\t\t\tstrokeColor: '#000000',\n\t\t\t\tstrokeColor: roadDisplayOptions[e.currentTarget.getGeometry().id%6].style.strokeColor\n\t\t\t}));\n\t\t});\n\t\t\n\t\t// show link details ig availabel on tap\n\t\tcurrentRoadShape.addEventListener('tap', function(e){\n\t\t\tvar selectedRoadId = e.currentTarget.getGeometry().id;\n\t\t\tshowFormForRoad(selectedRoadId);\n\t\t\te.currentTarget.setStyle(e.currentTarget.getStyle().getCopy({\n\t\t\t\tlineWidth: 9\n\t\t\t}));\n\n\t\t\te.currentTarget.setStyle(e.currentTarget.getStyle().getCopy({\n\t\t\t\tlineWidth: 7,\n\t\t\t\tstrokeColor: '#000000',\n\t\t\t\tstrokeColor: roadDisplayOptions[e.currentTarget.getGeometry().id%6].style.strokeColor\n\t\t\t}));\n\t\t});\n\n\t\t// add the polyline to map group\n\t\troadGroup.addObject(currentRoadShape);\n\t\tvar polygonHandles = new H.map.Group();\n\t\troadGroup.addObject(polygonHandles);\n\n\t\tvar oldStrip = currentRoadShape.getGeometry();\n\t\tvar newStrip = new H.geo.Strip();\n\t\t// fix the dbltap adding two points in last place, removing last.\n\t\tfor (var i = 0; i < oldStrip.getPointCount(); i++) {\n\t\t\tnewStrip.pushPoint(oldStrip.extractPoint(i));\n\t\t}\n\t\tnewStrip.id = id;\n\t\tcurrentRoadShape.setGeometry(newStrip);\n\t\t\n\t\t// add mouse event listner to the polyline\n\t\tmakeHandles(currentRoadShape, polygonHandles);\n\t\t\n\t\tmap.addObject(roadGroup);\n\t\troadShapes[id-1]= currentRoadShape;\n\t\t\n\t\t// if the road group already exists in the gourp remove it \n\t\t// and replace with new group\n\t\tif(roadGroups[id]){\n\t\t\troadGroups[id].removeAll();\n\t\t\troadGroups[id] = roadGroup;\n\t\t}else{\n\t\t\n\t\t\t// add option to 'select a road' if this road is new\n\t\t var opt = document.createElement('option');\n\t\t\topt.innerHTML = id;\n\t\t\topt.id = id;\n\t\t\tdocument.getElementById(\"roadSelector\").appendChild(opt);\n\t\t\tdocument.getElementById(\"road-selector\").style.display = 'block';\n\t\t\n\t\t\troadGroups[id] = roadGroup;\n\t\t\taddRowToContainer(newStrip.id, roadShapeArr,showMapMatch);\n\t\t\t\n\t\t\t// show the details in panel if showForm passed true\n\t\t\tif(showForm){\n\t\t\t\tshowFormForRoad(newStrip.id);\n\t\t\t\tdocument.getElementById(\"roadSelector\").selectedIndex = document.getElementById(\"roadSelector\").length-1 ;\n\t\t\t}else{\n\t\t\t\tshowFormForRoad(null);\n\t\t\t}\n\t\t\t\t\n\t\t}\n\t\t\n\t\tcurrentRoadShape = null;\n\t\tunderConstruction = false;\n\t\t// add arrows for direction in the link\n\t\taddDirectionArrows(id, direction);\n\t\tmap.setViewBounds(roadGroup.getBounds());\n\n\t\t\n\t}",
"function applyMapMatchToRoad(id){\n\t\tvar polyLineForSelectedRoad = mapMatchedRoadShapes[id - 1];\n\t\t// if not previsouly map matched , retrieve the coordinates for each mat-matched way point\n\t\tif (polyLineForSelectedRoad){\n\t\t\tdocument.getElementById(\"shape-\"+id).value = generateJSONStringFromPolyLine(polyLineForSelectedRoad);\n\t\t\taddRoad(id, JSON.parse(document.getElementById(\"shape-\"+id).value), true,true);\n\t\t}else{\n\t\t\talert(\"Map matching result does not exist for the selected road, please use the entered coordinates instead.\")\n\t\t}\n\t}",
"function loadDirections(modeID, routeID) {\n\tdisableSubmit();\n\tresetOptions(selectObjDirection);\n\t\n\tdisableSelector(selectObjDirection);\n\t\n\tallStops = [];\n\tallStopsTemp = [];\n\tallDirections = [];\n\t\n\t// If 'Select' is selected then reset everything below.\n\tif(modeID == -1 || routeID == -1) {\n\t} else {\n\t\tconsole.log('Route is: ' + routeID);\n\t\txhr(stopsOnALineURL(modeID, routeID), stopsOnALineCallback);\n \n\t}\n}",
"function showDirectionLineAndDetails(originCoordinates, destinationCoordinates, originName, destName, mode, name) {\n\n\tvar directionQuery = generateDirectionQuery(mode, \n\t\t\t\t\t\toriginCoordinates[0], originCoordinates[1],\n\t\t\t\t\t\tdestinationCoordinates[0], destinationCoordinates[1]);\n\t\n\tvar layerName = 'directions-' + name;\n\tstepsData = {};\n\t$('.instruction-header-cycling').remove();\n\t$('.instruction-header-walking').remove();\n\t$('.instruction').remove();\n\n\n\t$.getJSON(directionQuery, function(data) {\n\t\t\n\t\tdirections = data;\n\n\t\tif (data.code == \"NoRoute\") {\n\t\t\talert(\"No route found!\");\n\t\t\tstepsData = {};\n\t\t\tlinesDrawn = 0;\n\n\t\t\tif ( !(map.getSource('directions-cycling1') === undefined) ) {\n\t\t\t\tmap.removeSource('directions-cycling1');\n\t\t\t\tmap.removeLayer('directions-cycling1');\n\t\t\t}\n\n\t\t\tif ( !(map.getSource('directions-walking1') === undefined) ) {\n\t\t\t\tmap.removeSource('directions-walking1');\n\t\t\t\tmap.removeLayer('directions-walking1');\n\t\t\t}\n\n\t\t\tif ( !(map.getSource('directions-walking2') === undefined) ) {\n\t\t\t\tmap.removeSource('directions-walking2');\n\t\t\t\tmap.removeLayer('directions-walking2');\n\t\t\t}\n\n\t\t\t// Remove highlighted markers if they exist\n\t\t\tif ( !(map.getSource('stations') === undefined) ) {\n\t\t\t\tmap.removeSource('stations');\n\t\t\t\tmap.removeLayer('stations');\n\t\t\t}\n\n\t\t\t\t\t//remove destination marker if it exists\n\n\t\t\tif ( !(map.getSource('destination') === undefined) ) {\n\t\t\t\tmap.removeSource('destination');\n\t\t\t\tmap.removeLayer('destination');\n\t\t\t}\n\n\t\t\tif ($('.instruction-container').css('right', '0%'))\n\t\t\t\t$('.instruction-container').animate({right: '-35%'}, 'slow');\n\n\t\t\t$('.instruction-header-cycling').remove();\n\t\t\t$('.instruction-header-walking').remove();\n\t\t\t$('.instruction').remove();\n\n\n\t\t\treturn;\n\t\t}\n\n\t\tlinesDrawn++;\n\n\t\tvar directionsLineFeatureCollection = \n\t\t\t\t{\"type\": \"FeatureCollection\",\n\t\t\t\t\"features\": [\n\t\t\t\t\t{\"type\": \"Feature\",\n\t\t\t\t\t'properties': {}}\n\t\t\t\t\t]\n\t\t\t\t};\n\n\t\tdirectionsLineFeatureCollection.features[0].geometry = directions.routes[0].geometry;\t\t\n\n\t\t\t\t/* Remove direction lines if they exist */\n\t\tif ( !(map.getSource(layerName) === undefined) ) {\n\t\t\tmap.removeSource(layerName);\n\t\t\tmap.removeLayer(layerName);\n\t\t}\n\n\t\tmap.addSource(layerName, {\n\t\t\t'type': 'geojson',\n\t\t\t'data': directionsLineFeatureCollection\n\t\t});\n\n\t\tmap.addLayer({\n\t\t\t'id': layerName,\n\t\t\t'type': 'line',\n\t\t\t'source': layerName,\n\t \"layout\": {\n\t \"line-join\": \"round\",\n\t \"line-cap\": \"round\",\n\t \"visibility\": \"none\"\n\t },\n\t \"paint\": {\n\t \"line-color\": mode != 'walking' ? \"#2b8cbe\" : \"#fd8d3c\",\n\t \"line-width\": mode != 'walking' ? 4 : 5,\n\t \"line-opacity\": .85,//i != 1 ? .85 : .85\n\t \n\t }\n\t\t}, 'stations');\n\n\t\t// We make the layers visible only if the three directions were found\n\t\tif (linesDrawn == 3) {\n\t\t\tconsole.log(linesDrawn);\n\n\t\t\tif ( !(map.getSource('stations') === undefined) ) {\n\t\t\t\tmap.removeSource('stations');\n\t\t\t\tmap.removeLayer('stations');\n\t\t\t}\n\n\t\t\tmap.addSource('stations',{\n\t\t\t\t'type': 'geojson',\n\t\t\t\t'data': featureCollection\n\t\t\t});\n\n\t\t\tmap.addLayer({\n\t\t\t\t'id':'stations',\n\t\t\t\t'type': 'symbol',\n\t\t\t\t'source': 'stations',\n\t\t\t\t'layout': {\n\t\t\t\t \t\"icon-image\": 'mark-green',\n\t\t\t\t\t\"icon-size\" : 1.5,\n\t\t\t\t\t\"text-field\": \"{availableBikes}\",\n\t\t\t\t \"text-font\": [\"Open Sans Semibold\", \"Arial Unicode MS Bold\"],\n\t\t\t\t \"text-size\" : 10, \n\t\t\t\t\t\"text-anchor\": \"bottom\"\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t//Destination markers\t \n\t\t\tfeatureCollectiond = {\n\t\t\t\t\"type\": \"FeatureCollection\",\n\t\t\t\t\"features\": [] };\n\n\t\t\tvar feature = {\n\t\t\t\t\"type\": \"Feature\",\n\t\t\t\t\"geometry\": {\n\t\t\t\t\"type\": \"Point\",\n\t\t\t\t\"coordinates\": destCoordinates\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\tfeatureCollectiond.features.push(feature);\n\n\t\t\tif ( !(map.getSource('destination') === undefined) ) {\n\t\t\t\tmap.removeSource('destination');\n\t\t\t\tmap.removeLayer('destination');\n\t\t\t}\n\n\t\t\tmap.addSource('destination',{\n\t\t\t\t'type': 'geojson',\n\t\t\t\t'data': featureCollectiond\n\t\t\t});\n\n\t\t\tmap.addLayer({\n\t\t\t\t'id':'destination',\n\t\t\t\t'type': 'symbol',\n\t\t\t\t'source': 'destination',\n\t\t\t\t'layout': {\n\t\t\t\t \t\"icon-image\": 'marker-pink',\n\t\t\t\t\t\"icon-size\" : 2,\n\t\t\t\t\t\n\t\t\t\t}, \n\t\t\t});\n\n\t\t\tif (map.getLayoutProperty('directions-cycling1', 'visibility') == 'none')\n\t\t\t\tmap.setLayoutProperty('directions-cycling1', 'visibility', 'visible');\n\t\t\tif (map.getLayoutProperty('directions-walking1', 'visibility') == 'none')\n\t\t\t\tmap.setLayoutProperty('directions-walking1', 'visibility', 'visible');\n\t\t\tif (map.getLayoutProperty('directions-walking2', 'visibility') == 'none')\n\t\t\t\tmap.setLayoutProperty('directions-walking2', 'visibility', 'visible');\n\n\t\t\tlinesDrawn = 0;\n\t\t}\n\t\t// Get steps from server's JSON response\n\t\tstepsData[layerName] = {};\n\t\tstepsInLayer = stepsData[layerName];\n\t\tstepsInLayer['instructions'] = [];\n\t\tstepsInLayer['duration'] = [];\n\t\tstepsInLayer['distance'] = [];\n\t\tstepsInLayer['totalDuration'] = 0;\n\t\tstepsInLayer['totalDurationUnit'] = '';\n\t\tstepsInLayer['totalDistance'] = 0;\n\t\tstepsInLayer['totalDistanceUnit'] = '';\n\t\tstepsInLayer['originName'] = originName;\n\t\tstepsInLayer['destName'] = destName; \n\n\t\tsteps = directions.routes[0].legs[0].steps;\n\n\t\t// total in minutes\n\t\ttotalDuration = directions.routes[0].duration;\n\t\ttotalDistance = directions.routes[0].distance;\n\n\t\ttotalDurationInMinutes = Math.ceil(totalDuration / 60);\n\t\ttotalDistanceInKm = (totalDistance / 1000).toFixed(1);\n\n\t\tif (totalDuration > 59) {\n\t\t\tstepsInLayer.totalDuration = totalDurationInMinutes;\n\t\t\tstepsInLayer.totalDurationUnit = 'minutes';\n\t\t}\n\t\telse {\n\t\t\tstepsInLayer.totalDuration = totalDuration;\n\t\t\tstepsInLayer.totalDurationUnit = 'seconds';\n\t\t}\n\n\t\tif (totalDistance > 999) {\n\t\t\tstepsInLayer.totalDistance = totalDistanceInKm;\n\t\t\tstepsInLayer.totalDistanceUnit = 'kilometers';\n\t\t}\n\t\telse {\n\t\t\tstepsInLayer.totalDistance = totalDistance;\n\t\t\tstepsInLayer.totalDistanceUnit = 'meters';\n\t\t}\n\n\n\t\t// Add instructions, duration, and distance for each layer\n\t\tsteps.forEach( function(step) {\n\t\t\tstepsInLayer['instructions'].push(step.maneuver.instruction);\n\t\t\tstepsInLayer['duration'].push(step.duration);\n\t\t\tstepsInLayer['distance'].push(step.distance);\n\t\t});\n\n\n\t\tif (Object.keys(stepsData).length == 3) {\n\t\t\t// Show steps in this order\n\t\t\tvar layerNames = ['directions-walking1', 'directions-cycling1', 'directions-walking2'];\n\n\t\t\tvar instructionsContainer = $('.instruction-container');\n\n\t\t\tlayerNames.forEach( function(layerName) {\n\n\t\t\t\tcurrentSteps = stepsData[layerName];\n\t\t\t\tcurrMode = layerName == 'directions-cycling1' ? 'Bike' : 'Walk';\n\n\t\t\t\theaderContent = currMode + \" \" + \"from \" + currentSteps.originName + \" to \" + currentSteps.destName\n\t\t\t\t\t\t\t\t+ \"<br><br>\" + currentSteps.totalDistance + \" \" + currentSteps.totalDistanceUnit + \" \" \n\t\t\t\t\t\t\t\t+ currentSteps.totalDuration + \" \" + currentSteps.totalDurationUnit;\n\n\t\t\t\tif (layerName == 'directions-cycling1') {\n\n\t\t\t\t\theader = \"<div class='instruction-header-cycling'>\"\n\t\t\t\t\t\t\t+ headerContent\n\t\t\t\t\t\t\t+ \"</div>\";\n\t\t\t\t\tinstructionsContainer.append(header);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\theader = \"<div class='instruction-header-walking'>\"\n\t\t\t\t\t\t\t+ headerContent\n\t\t\t\t\t\t\t+ \"</div>\";\n\t\t\t\t\tinstructionsContainer.append(header);\n\t\t\t\t}\n\n\t\t\t\tinstructionsArray = currentSteps.instructions;\n\n\t\t\t\tinstructionsArray.forEach( function(instr, i) {\n\n\t\t\t\t\tdist = (currentSteps.distance[i] >= 1000 ? (currentSteps.distance[i] / 1000).toFixed(2) : currentSteps.distance[i]);\n\t\t\t\t\tdistUnit = (currentSteps.distance[i] >= 1000 ? \"kilometers\" : \"meters\");\n\t\t\t\t\tduration = currentSteps.duration[i] >= 60 ? Math.ceil(currentSteps.duration[i] / 60) : currentSteps.duration[i];\n\t\t\t\t\tdurationUnit = currentSteps.duration[i] >= 60 ? \"minutes\" : \"seconds\";\n\n\t\t\t\t\tinstruction = \"<div class='instruction'>\" + instr + \"<br/><span class='duration-and-distance'>\" \n\t\t\t\t\t\t\t\t\t\t\t+ (duration == 0 ? \"\" : duration) + \" \" + (duration == 0 ? \"\" : durationUnit) + \" \"\n\t\t\t\t\t\t\t\t\t\t\t+ (dist == 0 ? \"\" : dist) + \" \" + (dist == 0 ? \"\" : distUnit);\n\t\t\t\t\t\t\t\t\t\t\t+ \"</span>\"\n\t\t\t\t\t\t\t\t\t\t\t+ \"</div>\";\n\t\t\t\t\tinstructionsContainer.append(instruction);\n\n\t\t\t\t});\n\n\t\t\t});\n\n\t\t\t// Add a blank div in the bottom so as instructions not obscured by Mapbox copyright\n\t\t\tinstructionsContainer.append(\"<div class='instruction'></div>\");\n\n\t\t\t// animate instructions\n\t\t\t$('.instruction-container').animate({right: '0%'}, 'slow');\n\t\t\t$('.exit-button').css(\"visibility\", \"visible\");\n\t\t\tmap.flyTo({\n\t\t\t\tcenter: originCoordinates,\n\t\t\t\tzoom: 15,\n\t\t\t\tspeed: 0.7\n\t\t\t});\n\t\t}\n\n\n\t});\n\n}",
"function routeBetween(x1, y1, x2, y2, coordMode) {\n\n var route = [],\n xDiff = x1 - x2;\n xDirection = -xDiff / Math.abs(xDiff),\n yDiff = y1 - y2,\n yDirection = -yDiff / Math.abs(yDiff);\n\n if (xDiff === 0 && yDiff === 0) {\n return route;\n }\n\n if (coordMode === COORD_MODE_STRAIGHT) {\n for (var i = 1; i < Math.abs(xDiff) + 1; ++i) {\n route.push([x1 + i * xDirection, y1]);\n }\n console.log('route' + JSON.stringify(route));\n var lastX = (route.length !== 0) ? route[route.length - 1][0] : x1;\n for (var i = 1; i < Math.abs(yDiff); ++i) {\n route.push([lastX, y1 + i * yDirection]);\n }\n }\n else if (coordMode === COORD_MODE_DIAGONAL) {\n xDiff = Math.abs(x2 - x1);\n yDiff = Math.abs(y2 - y1);\n\n if (yDiff < xDiff) {\n for (var i = 1; i < Math.abs(yDiff); ++i) {\n route.push([x1 + i * xDirection, y1 + i * yDirection]);\n }\n var lastX = (route.length !== 0 ) ? route[route.length - 1][0] : x1,\n newXDiff = x2 - lastX;\n for (var i = 1; i < Math.abs(newXDiff); ++i) {\n route.push([lastX + i * xDirection, y2]);\n }\n } else {\n for (var i = 1; i < Math.abs(xDiff); ++i) {\n route.push([x1 + i * xDirection, y1 + i * yDirection]);\n }\n var lastY = (route.length !== 0 ) ? route[route.length - 1][1] : y1,\n newYDiff = y2 - lastY;\n for (var i = 1; i < Math.abs(newYDiff); ++i) {\n route.push([x2, lastY + i * yDirection]);\n }\n }\n }\n return route;\n }",
"function drivingRoute(start, end){\n\t\tdirectionsDisplay = new google.maps.DirectionsRenderer();\n\t\tvar myOptions = {\n\t\t zoom:5,\n\t\t mapTypeId: google.maps.MapTypeId.ROADMAP,\n\t\t} \n\t\tmap = new google.maps.Map(document.getElementById(\"map_canvas\"), myOptions);\n\t\tdirectionsDisplay.setMap(map);\n\t\tvar directionsService = new google.maps.DirectionsService();\n\t\t\n\t\tvar request = {\n\t\t\t\torigin:start,\n\t\t\t\tdestination:end,\n\t\t\t\twaypoints: waypts,\n\t\t\t optimizeWaypoints: true,\n\t\t\t\ttravelMode: google.maps.DirectionsTravelMode.DRIVING\n\t\t\t};\n\t\t// calculating distance from google maps (Driving directions)\n\t\t\t\tdirectionsService.route(request, function(response, status) {\n\t\t\t\tif (status == google.maps.DirectionsStatus.OK) {\n\t\t\t\t\tdirectionsDisplay.setDirections(response);\n\t\t\t\t var route = response.routes[0];\n\t\t\t\t \n\t\t\t\t var summaryPanel = document.getElementById('1234');\n\t\t\t\t summaryPanel.innerHTML = ''; // For each route, display summary information.\n\t\t\t\t for (var i = 0; i < route.legs.length; i++) {\n\t\t\t\t var routeSegment = i + 1;\n\t\t\t\t summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +\n\t\t\t\t '</b><br>';\n\t\t\t\t summaryPanel.innerHTML += route.legs[i].start_address + ' to ';\n\t\t\t\t summaryPanel.innerHTML += route.legs[i].end_address + '<br>';\n\t\t\t\t summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';\n\t\t\t\t if(i==0)\n\t\t\t\t \t {\n\t\t\t\t \t document.getElementById(\"distance\").value=route.legs[i].distance.value / 1000;\n\t\t\t\t \t document.getElementById(\"mySubmit\").disabled = false;\n\t\t\t\t \t }\n\t\t\t\t else\n\t\t\t\t \t dist=dist+route.legs[i].distance.value / 1000;\n\t\t\t\t }\n\t\t\t\t document.getElementById(\"distance1\").value=dist;\t\t\t\t \n\t\t\t\t }});\n\t}",
"function drawRoad(x1, y1, x2, y2, color) {\n ctx.beginPath();\n if (Math.abs(x1 - x2) > EPS) {\n ctx.moveTo(x1, y1 + 5);\n ctx.lineTo(x2, y2 + 5);\n ctx.lineTo(x2, y2 - 5);\n ctx.lineTo(x1, y1 - 5);\n } else if (y1 > y2) {\n ctx.moveTo(x1 - 4.5, y1 - 5);\n ctx.lineTo(x2 - 4.5, y2 + 5);\n ctx.lineTo(x2 + 4.5, y2 + 5);\n ctx.lineTo(x1 + 4.5, y1 - 5);\n } else if (y2 > y1) {\n ctx.moveTo(x1 - 4.5, y1 + 5);\n ctx.lineTo(x2 - 4.5, y2 - 5);\n ctx.lineTo(x2 + 4.5, y2 - 5);\n ctx.lineTo(x1 + 4.5, y1 + 5);\n }\n ctx.closePath();\n ctx.fillStyle = COLORS[color];\n ctx.fill();\n ctx.stroke();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
we can create a blank query at the end of history if we're at the last slot, and the query there has already been run | function canCreateBlankQuery() {
return (currentQueryIndex == pastQueries.length -1 &&
lastResult.query.trim() === pastQueries[pastQueries.length-1].query.trim() &&
lastResult.status != newQueryTemplate.status &&
!cwQueryService.executingQuery.busy);
} | [
"function clearHistory() {\n // don't clear the history if existing queries are already running\n if (cwQueryService.executingQuery.busy)\n return;\n\n lastResult.copyIn(dummyResult);\n pastQueries.length = 0;\n currentQueryIndex = 0;\n\n saveStateToStorage(); // save current history\n }",
"function clearCurrentQuery() {\n // don't clear the history if existing queries are already running\n if (cwQueryService.executingQuery.busy || pastQueries.length == 0)\n return;\n\n pastQueries.splice(currentQueryIndex,1);\n if (currentQueryIndex >= pastQueries.length)\n currentQueryIndex = pastQueries.length - 1;\n\n lastResult.copyIn(pastQueries[currentQueryIndex]);\n\n saveStateToStorage(); // save current history\n }",
"function addNewQueryContents(contents) {\n // move to the end of history\n qwQueryService.addNewQueryAtEndOfHistory(contents);\n qc.inputEditor.getSession().setValue(contents);\n }",
"function update_history_program(prog_id) {\n $('#search_prompt').html(\"You may have seen this programme already in the past. Searching for activities with the same title and synopsis.\");\n\n if (typeof snapshot_time == \"undefined\") {\n var url = '/tvdiary/history_json.jim?program_id=' + prog_id;\n } else {\n var url = '/tvdiary/json/history_' + prog_id + '.json?nocache=' + today_start;\n }\n update_history(url, true);\n }",
"function prepareQuery(hash) {\n\t'use strict';\n\tds.historics.prepare({\n\t\t'hash': hash,\n\t\t'start': startTime,\n\t\t'end': endTime,\n\t\t'sources': 'twitter',\n\t\t'name': 'Example historic query'\n\t}, function(err, response) {\n\t\tif (err)\n\t\t\tconsole.log(err);\n\t\telse {\n\t\t\tconsole.log('Prepared query: ' + response.id);\n\t\t\tcreateSubscription(response.id);\n\t\t}\n\t});\n}",
"diff(query) {\n if (this.useInitialQuery(query)) {\n return {\n result: this._INITIAL_QUERY.result,\n complete: true\n };\n }\n return super.diff(query);\n }",
"function initalhistory(){\n\tgetHistory();\n\tclearInterval(inithis);\n}",
"updateQuery(query) {\n this.setState(() => ({\n cursor: null\n }));\n this.props.queryFilter(query.trim());\n }",
"queryHistoricalInfo(query) {\n const { height } = query;\n if (is.undefined(height)) {\n throw new errors_1.SdkError('block height can not be empty');\n }\n const request = new types.staking_query_pb.QueryHistoricalInfoRequest()\n .setHeight(height);\n return this.client.rpcClient.protoQuery('/cosmos.staking.v1beta1.Query/HistoricalInfo', request, types.staking_query_pb.QueryHistoricalInfoResponse);\n }",
"updateHistory(board) {\n /* add current board to history and increment history index\n *** if historyIndex is less than historyLength-1, it \n means that a move has been played after the user has \n used the jump backwards button. Therefore, all elements in history after\n where historyIndex currently is should be erased *** \n */\n const historyIndex = this.state.historyIndex;\n const historyLength = this.state.history.length;\n let history = this.state.history;\n if (historyIndex < historyLength - 1) {\n history = this.state.history.splice(0, historyIndex + 1);\n }\n\n return history.concat([{ board: board }]);\n }",
"getDockScheduledShipsQuery() {\n return `SELECT DISTINCT(ship_id), eta, i.dock_id ` +\n `FROM Intervals i JOIN Timelines tl ON i.timeline_id = tl.id ` +\n `WHERE ship_id is not null ` +\n `AND i.timeline_id = \"${this.timeline_id}\" ` +\n `AND tl.simulation_id = \"${this.simulation_id}\" ORDER by eta; `;\n }",
"function update_history_crid(crid) {\n $('#search_prompt').html(\"This programme is a repeat. Searching for activities with the same CRID.\");\n\n if (typeof snapshot_time == \"undefined\") {\n var url = '/tvdiary/history_json.jim?crid=' + encodeURIComponent(crid);\n } else {\n var url = '/tvdiary/json/history_' + encodeURIComponent(crid) + '.json?nocache=' + today_start;\n }\n update_history(url, true);\n }",
"async doSaveCacheHistory() {\n\t\tlet theUnsaved = this.historyCache.getUnSaved();\n\t\tif (!$.isEmptyObject(theUnsaved)) { await this.doAddToDB('searching', 'history', Object.values(theUnsaved)); }\n\t}",
"function query_test() {\n DB.clear_all()\n let album1 = create_dummy(Album)\n let album2 = create_dummy(Album)\n let album3 = create_dummy(Album)\n let all_albums_query = create_live_query().all(Album).make()\n check.equals(all_albums_query.current().length(),3,'all album check')\n all_albums_query.sync()\n let album4 = create_dummy(Album)\n all_albums_query.sync()\n check.equals(all_albums_query.current().length(),4)\n\n let yellowsub_query = create_live_query().all(Album).attr_eq(\"title\",\"Yellow Submarine\").make()\n yellowsub_query.sync()\n all_albums_query.sync()\n check.equals(all_albums_query.current().length(),4, 'total album count')\n check.equals(yellowsub_query.current().length(),0,'yellow sub should be 0')\n\n create_dummy(Album, {title: 'Yellow Submarine'})\n yellowsub_query.sync()\n all_albums_query.sync()\n check.equals(all_albums_query.current().length(),5, 'total album count')\n check.equals(yellowsub_query.current().length(),1)\n\n\n // make three tracks. one on album1 and two on album 2\n create_dummy(Track, {album:album1, title:'title1'})\n create_dummy(Track, {album:album2, title:'title2'})\n create_dummy(Track, {album:album2, title:'title3'})\n\n // make a track query. verify three tracks total\n let all_tracks_query = create_live_query().all(Track).make()\n all_tracks_query.sync()\n check.equals(all_tracks_query.current().length(),3)\n\n // make a track query for tracks on album1, verify 1 track\n let album1_tracks_query = create_live_query().all(Track).attr_eq('album',album1).make()\n check.equals(album1_tracks_query.current().length(),1)\n\n\n // make a track query for tracks on album2, verify 2 tracks\n let album2_tracks_query = create_live_query().all(Track).attr_eq('album',album2).make()\n check.equals(album2_tracks_query.current().length(),2)\n //check the titles\n check.equals(create_live_query().all(Track).attr_eq('title','title1').make().current().length(),1)\n check.equals(create_live_query().all(Track).attr_eq('title','title2').make().current().length(),1)\n //this one should fail\n check.equals(create_live_query().all(Track)\n .attr_eq('title','title4').make()\n .current().length(),0)\n\n //check if attr in array\n console.log(\"checking if title in [title1,title2]\")\n check.equals(create_live_query().all(Track)\n .attr_in_array('title',['title1','title2','title4']).make()\n .current().length(),2)\n\n //check if track in one of a set of albums\n check.equals(create_live_query().all(Track)\n .attr_in_array('album',[album1,album2]).make()\n .current().length(),3)\n\n // all tracks for all albums.\n let all_albums = create_live_query().all(Album).make()\n let all_album_tracks = create_live_query().all(Track)\n .attr_in_array('album',all_albums).make()\n check.equals(all_album_tracks.current().length(),3)\n\n // make a Selection which contains an array of Albums\n // let selected_albums = create_dummy(Selection, {albums:[album2, album3]})\n\n // make a query of albums in the selection\n // let selected_albums_query = create_live_query().all(Track)\n // .attr_in_array('album',selected_albums).make()\n // check.equals(selected_albums_query.current().length(),2)\n\n // make a query of tracks in albums in selection\n // let selected_tracks_query = create_live_query().all(Track)\n // .attr_eq('album',selected_albums_query).make()\n // check.equals(selected_tracks_query.current().length(),2)\n}",
"function startQuizz() {\n setPreviousTime(currentDate.getTime())\n addTimers();\n setQuestionNumber(0);\n }",
"runSoqlQuery()\n {\n this.setSelectedMapping();\n this.setSelectedAction();\n this.callRetrieveRecordsUsingWrapperApex();\n }",
"add(location, {setIndexToHead = true, message} = {}) {\n const newEntry = new Entry(location)\n if (atom.config.get(\"cursor-history.keepSingleEntryPerBuffer\")) {\n const isSameURI = entry => newEntry.URI === entry.URI\n this.entries.filter(isSameURI).forEach(destroyEntry)\n } else {\n const isAtSameRow = entry => newEntry.isAtSameRow(entry)\n this.entries.filter(isAtSameRow).forEach(destroyEntry)\n }\n\n this.entries.push(newEntry)\n\n if (setIndexToHead) {\n this.setIndexToHead()\n }\n if (atom.config.get(\"cursor-history.debug\") && message) {\n this.log(message)\n }\n }",
"function record(type, args){\n var insert_index = history_index;\n\n //when history_length is not zero, enforce ring history\n if(configs.history_length !== 0){\n insert_index = history_index % configs.history_length;\n }\n\n history[insert_index] = {\n type: type\n ,args: args\n };\n\n history_index++;\n }",
"function updateQueryString() {\n\tsessionStorage[\"query\"] = \"start=\" + sessionStorage[\"start\"] + \"&end=\" + sessionStorage[\"end\"] + \"&pipeline=\" + sessionStorage[\"pipeline\"] + \"&datacen=\" + sessionStorage[\"datacen\"] + \"&network=\" + sessionStorage[\"network\"] + \"&farm=\" + sessionStorage[\"farm\"];\n\twindow.location.search = sessionStorage[\"query\"];\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new PredicateCondition | function PredicateCondition(actionManager,/** defines the predicate function used to validate the condition */predicate){var _this=_super.call(this,actionManager)||this;_this.predicate=predicate;return _this;} | [
"addSelectionPredicate(p) {\n this.selectionPredicates.push(p);\n }",
"constructor(single = true) {\r\n \r\n // List of predicates to check\r\n this.predicates = [];\r\n \r\n // Reference single\r\n this.single = single\r\n \r\n }",
"function createJoinForPredicate(/** predicate A function that tests values */ predicate, /** Optional name for the resulting join function */ name) {\n /**\n * A factory for a join function with logging.\n */ function join(/** The current file being processed */ filename, /** An options hash */ options) {\n const log = createDebugLogger(options.debug);\n /**\n * Join function proper.\n *\n * For absolute uri only `uri` will be provided. In this case we substitute any `root` given in options.\n *\n * Returns Just the uri where base is empty or the uri appended to the base\n */ return function joinProper(/** A uri path, relative or absolute */ uri, /** Optional absolute base path or iterator thereof */ baseOrIteratorOrAbsent) {\n const iterator = typeof baseOrIteratorOrAbsent === \"undefined\" && createIterator([\n options.root\n ]) || typeof baseOrIteratorOrAbsent === \"string\" && createIterator([\n baseOrIteratorOrAbsent\n ]) || baseOrIteratorOrAbsent;\n const result = runIterator([]);\n log(createJoinMsg, [\n filename,\n uri,\n result,\n result.isFound\n ]);\n return typeof result.absolute === \"string\" ? result.absolute : uri;\n function runIterator(accumulator) {\n const nextItem = iterator.next();\n var base = !nextItem.done && nextItem.value;\n if (typeof base === \"string\") {\n const element = predicate(filename, uri, base, accumulator.length, next);\n if (typeof element === \"string\" && _path.default.isAbsolute(element)) {\n return Object.assign(accumulator.concat(base), {\n isFound: true,\n absolute: element\n });\n } else if (Array.isArray(element)) {\n return element;\n } else {\n throw new Error(\"predicate must return an absolute path or the result of calling next()\");\n }\n } else {\n return accumulator;\n }\n function next(fallback) {\n return runIterator(Object.assign(accumulator.concat(base), typeof fallback === \"string\" && {\n absolute: fallback\n }));\n }\n }\n };\n }\n function toString() {\n return \"[Function: \" + name + \"]\";\n }\n return Object.assign(join, name && {\n valueOf: toString,\n toString: toString\n });\n}",
"function createFilterFor(query) {\n var lowercaseQuery = angular.lowercase(query);\n\n return function filterFn(item) {\n var toMatch = angular.lowercase(item.name);\n\n return (toMatch.indexOf(lowercaseQuery) !== -1);\n };\n }",
"function ValueCondition(actionManager,target,/** path to specify the property of the target the conditional operator uses */propertyPath,/** the value compared by the conditional operator against the current value of the property */value,/** the conditional operator, default ValueCondition.IsEqual */operator){if(operator===void 0){operator=ValueCondition.IsEqual;}var _this=_super.call(this,actionManager)||this;_this.propertyPath=propertyPath;_this.value=value;_this.operator=operator;_this._target=target;_this._effectiveTarget=_this._getEffectiveTarget(target,_this.propertyPath);_this._property=_this._getProperty(_this.propertyPath);return _this;}",
"function add_empty_search_condition () {\n var c = new Condition (default_field, COND_LIKE);\n \n // push and add\n conditions.push (c);\n add_search_condition (c, search_cond_next);\n search_cond_next++;\n}",
"function getColumnForPredicate (columns, predicate) {\n let column\n\n if (predicate.uri in columns) {\n column = columns[predicate.uri]\n } else {\n column = new Column()\n column.setPredicate(predicate)\n columns[predicate.uri] = column\n }\n\n return column\n }",
"function PredPrediction(pred, alt) {\n this.alt = alt;\n this.pred = pred;\n return this;\n}",
"filter(predicate)\n {\n let reducer = (node, acc, parents) => {\n if (predicate(node))\n acc.push(node);\n return acc;\n };\n return this.reduce(reducer, []);\n }",
"function and () {\n\t var predicates = Array.prototype.slice.call(arguments, 0)\n\t if (!predicates.length) {\n\t throw new Error('empty list of arguments to or')\n\t }\n\n\t return function orCheck () {\n\t var values = Array.prototype.slice.call(arguments, 0)\n\t return predicates.every(function (predicate) {\n\t return low.fn(predicate) ? predicate.apply(null, values) : Boolean(predicate)\n\t })\n\t }\n\t}",
"function findOrCreate(arr, predicate, construct) {\n const index = arr.findIndex((entry) => predicate(entry));\n if (index >= 0) {\n return arr[index];\n }\n const newEntry = construct();\n arr.push(newEntry);\n return newEntry;\n}",
"addFilterToQuery(filter) {\n const query = {};\n if (filter.mode === 'exactly' && !filter.value) {\n query[this.paths.first] = query[this.paths.last] = filter.inverted ? { $nin: ['', null] } : { $in: ['', null] };\n return query;\n }\n let value = utils.escapeRegExp(filter.value);\n if (filter.mode === 'beginsWith') {\n value = '^' + value;\n }\n else if (filter.mode === 'endsWith') {\n value = value + '$';\n }\n else if (filter.mode === 'exactly') {\n value = '^' + value + '$';\n }\n value = new RegExp(value, filter.caseSensitive ? '' : 'i');\n if (filter.inverted) {\n query[this.paths.first] = query[this.paths.last] = { $not: value };\n }\n else {\n const first = {};\n first[this.paths.first] = value;\n const last = {};\n last[this.paths.last] = value;\n query.$or = [first, last];\n }\n return query;\n }",
"function makeFilterFn$(value$, criteriaFnFactory) {\n return value$\n .map(value => {\n const criteriaFn = criteriaFnFactory(value);\n return function filterStateByCriteria(oldState) {\n const newProjects = oldState.projects.filter(criteriaFn);\n return {...oldState, projects: newProjects};\n };\n })\n .startWith(_.identity); // identity means \"allow anything\"\n}",
"EqualityExpression() {\n return this._BinaryExpression(\"RelationExpression\", \"EQUALITY_OPERATOR\");\n }",
"createFilterQuery() {\n const filterType = this.state.filterType;\n const acceptedFilters = ['dropped', 'stale', 'live'];\n\n if (acceptedFilters.includes(filterType)) {\n const liveIDs = this.state.liveIDs;\n if (filterType === 'dropped') return {'events.id': {$nin: liveIDs}};\n if (filterType === 'stale') return {'events.id': {$in: liveIDs}, end_date: {$lt: new Date()}};\n if (filterType === 'live') return {'events.id': {$in: liveIDs}, end_date: {$gte: new Date()}};\n }\n\n return {};\n }",
"function customFilterFactory(){\n return function(input){\n //change input\n return 'customFilter applied';\n }\n }",
"function StateCondition(actionManager,target,/** Value to compare with target state */value){var _this=_super.call(this,actionManager)||this;_this.value=value;_this._target=target;return _this;}",
"hasCondition(logicalId, props) {\n const matchError = (0, conditions_1.hasCondition)(this.template, logicalId, props);\n if (matchError) {\n throw new Error(matchError);\n }\n }",
"filter (p) {\n return filter(p, this)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Definition of the 'getGitHub' function to get all datas of the '$userLogin' GitHub account... | async function getGitHub($userLogin) {
} | [
"async function getGitHubUsers($userLogin) {\n\n\n}",
"function getRepos(userHandle) {\n const searchURL = `https://api.github.com/users/${userHandle}/repos`\n \n\n fetch(searchURL)\n .then(response => {\n if (response.ok) return response.json()\n return response.json().then((e) => Promise.reject(e))\n })\n .then(responseJson => displayResults(responseJson))\n .catch(error => {\n console.error(error)\n\n alert(error.message)\n });\n}",
"function getGithubPerfilRepos() {\n fetch(URL_GITHUB_PROFILE_REPOS)\n .then((response) => response.json())\n .then((data) => {\n data.map((item) => {\n list.innerHTML += `\n <li>${item.name}</li>\n `\n })\n })\n}",
"async function fetchGithubUserInfo ({ login, accessToken }) {\n debug(`Fetching info for ${login}`)\n const options = {\n url: `https://api.github.com/users/${login}`,\n headers: {\n 'User-Agent': 'request',\n 'Authorization': `token ${accessToken}`\n },\n json: true\n }\n\n const breaker = circuitBreaker(request, circuitBreakerOptions)\n return breaker.fire(options)\n}",
"async function fetchGithubUsersInfo ({ data = [], year, accessToken }) {\n if (!data.length) {\n return []\n }\n const logins = data.map((user) => ({\n accessToken,\n login: user.login\n }))\n\n const users = await Promise.resolve(logins).map(fetchGithubUserInfo, {\n concurrency: 5\n })\n return users\n}",
"async function getGitHubBranches($userLogin, $reposName) {\n\n\n}",
"function processGitHubData(data) {\n const { login, id } = data;\n // only works with two names\n return {\n username: login,\n id: id\n };\n}",
"function getGithubPerfil() {\n fetch(URL_GITHUB_PROFILE)\n .then((response) => response.json())\n .then((data) => {\n img_perfil.setAttribute('src', data.avatar_url)\n bio.textContent = data.bio\n login.textContent = data.login\n })\n}",
"function getStarredRepos(users) {\n\n let loopEndPoint = users.length;\n let loopCounter = 0;\n let namesOfStarredRepos = [];\n\n// Given an array of github user names\n users.forEach(function(user) {\n // Make an API request\n const options = {\n url: `https://api.github.com/users/${user}/starred`,\n headers : {\n 'User-Agent': 'request',\n 'Authorization': 'token ' + process.env.GITHUB_API_TOKEN\n }\n };\n request(options, function(err, res, body) {\n // Put the results in the container as a JSON object\n // Create object that holds info on all the repos contributors,\n // each item is another object holding info about the contributor.\n let repoListing = JSON.parse(body);\n // console.log(repoListing);\n // Iterate over each item in the object\n for (let starredRepo in repoListing) {\n let theEntry = repoListing[starredRepo];\n // Put the repo names into the array of all starred repos.\n namesOfStarredRepos.push(theEntry.full_name);\n }\n loopCounter += 1;\n\n // Return all of the user's starred repos\n // as an array of repo names as strings.\n\n if (loopCounter >= loopEndPoint) {\n printTopFive(namesOfStarredRepos);\n }\n });\n });\n}",
"function getUserInfo(username) {\n fetch(`https://api.github.com/search/users?q=${username}`)\n\t.then(response => response.json())\n\t.then((responseObject) => {\n renderObject(responseObject)\n })\n}",
"function saveGithubData(githubData, userId) {\r\n return new Promise((resolve, reject) => {\r\n let query = 'SELECT * FROM ' + table.GITHUB_LIST + ' WHERE guid = ? AND guser_id = ?'\r\n\r\n db.query(query, [userId, githubData.id], (error, rows, fields) => {\r\n if (error) {\r\n reject({ message: message.INTERNAL_SERVER_ERROR })\r\n } else {\r\n let fullName = ''\r\n let loginName = ''\r\n let email = ''\r\n let company = ''\r\n let location = ''\r\n let bio = ''\r\n let profileUrl = ''\r\n let reposUrl = ''\r\n let reposCount = ''\r\n let followers = ''\r\n let following = ''\r\n let avatarUrl = ''\r\n let createDate = ''\r\n\r\n if (githubData.name !== null)\r\n fullName = githubData.name\r\n if (githubData.login !== null)\r\n loginName = githubData.login\r\n if (githubData.email !== null)\r\n email = githubData.email\r\n if (githubData.company !== null)\r\n company = githubData.company\r\n if (githubData.location !== null)\r\n location = githubData.location\r\n if (githubData.bio !== null)\r\n bio = githubData.bio\r\n if (githubData.html_url !== null)\r\n profileUrl = githubData.html_url\r\n if (githubData.repos_url !== null)\r\n reposUrl = githubData.repos_url\r\n if (githubData.public_repos !== null)\r\n reposCount = githubData.public_repos\r\n if (githubData.followers !== null)\r\n followers = githubData.followers\r\n if (githubData.following !== null)\r\n following = githubData.following\r\n if (githubData.avatar_url !== null)\r\n avatarUrl = githubData.avatar_url\r\n if (githubData.created_at !== null)\r\n createDate = githubData.created_at\r\n\r\n if (rows.length > 0) {\r\n let query = 'UPDATE ' + table.GITHUB_LIST + ' SET gfull_name= ?, glogin_name = ?, gemail = ?, gcompany = ?, glocation = ? , gbio = ?'\r\n +', gprofile_url = ?, grepos_url = ?, gpublic_repos_count = ?, gfollowers_count = ?, gfollowing_count = ?, gavatar_url = ?, gerror_code = ? WHERE guid = ?'\r\n\r\n db.query(query, [fullName, loginName, email, company, location, bio, profileUrl, reposUrl, reposCount, followers, following, avatarUrl, 'success', userId], (error, result, fields) => {\r\n if (error) {\r\n console.log(error)\r\n reject({ message: message.INTERNAL_SERVER_ERROR })\r\n } else {\r\n let extraData = { registerGithub: 1 }\r\n visitModel.checkVisitSessionExtra(db, userId, extraData, 0).then((result) =>{\r\n resolve(true)\r\n })\r\n }\r\n })\r\n } else {\r\n let query = 'INSERT INTO ' + table.GITHUB_LIST + ' (guid, gfull_name, glogin_name, gemail, gcompany, glocation, gbio,'\r\n + ' gprofile_url, grepos_url, gpublic_repos_count, gfollowers_count, gfollowing_count, gavatar_url, gaccount_create_date, guser_id, gerror_code)'\r\n + ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'\r\n\r\n db.query(query, [userId, fullName, loginName, email, company, location, bio, profileUrl, reposUrl, reposCount, followers, following, avatarUrl, createDate, githubData.id, 'success'], (error, result, fields) => {\r\n if (error) {\r\n console.log(error)\r\n reject({ message: message.INTERNAL_SERVER_ERROR })\r\n } else {\r\n let extraData = { registerGithub: 1 }\r\n visitModel.checkVisitSessionExtra(db, userId, extraData, 0).then((result) =>{\r\n resolve(true)\r\n })\r\n }\r\n })\r\n }\r\n }\r\n })\r\n })\r\n}",
"searchRepos() {\n\n if (this.refs.gitUser.refs.input.value === '') {\n return;\n }\n\n this.setState({loading: true});\n\n // Assign user for get their repos\n const gitUSer = this.refs.gitUser.refs.input.value;\n\n // prepare data, use data key!\n let query = JSON.stringify({\n query: `query {\n user(login: \"${gitUSer}\") {\n bio\n url\n company\n email\n avatarUrl\n name\n followers(last: 100) {\n totalCount\n }\n websiteUrl\n starredRepositories(last: 100) {\n totalCount\n }\n repositories(last: 100, orderBy: {field: UPDATED_AT, direction: DESC}) {\n edges {\n node {\n id\n name\n description\n url\n primaryLanguage {\n name\n color\n }\n }\n }\n }\n }\n }`\n });\n\n // use the github endpoint\n fetch(process.env.REACT_APP_GRAPHQL_GITHUB_ENDPOINT, {\n method: 'POST',\n body: query,\n headers: {\n \"Authorization\": process.env.REACT_APP_GITHUB_TOKEN\n }\n }).then(response => {\n return response.json()\n }).then(res => {\n this.setState({\n user: res.data ? res.data.user : null,\n repos: res.data && res.data.user && res.data.user.repositories ? res.data.user.repositories : [],\n loading: false\n })\n })\n }",
"async function downloadData() {\n const releases = [];\n for (const source of sourcesOfTruth) {\n\n // fetch all repos of a given organizaion/user\n const allRepos = await fetch(\n `${baseURL}/users/${source.username}/repos${auth}`\n ).then(res => res.json());\n\n // fetch releases of every repo\n for (const repo of allRepos) {\n const repoName = repo.full_name;\n const repoReleasesURL = repo.releases_url.replace('{/id}', '') + auth;\n const repoReleases = await getRepoReleases(repoName, repoReleasesURL);\n if (repoReleases.length) {\n releases.push(...repoReleases);\n }\n }\n }\n // add date information to the data, to be able to show last updated time\n const data = {\n date: new Date().toLocaleString(),\n releases\n };\n return data;\n}",
"function loginToGithub(loginAgain){\n url = getGitHubRateLimit();\n //if already logged in\n if (url == null && !loginAgain) {\n RepoPullOptions();\n }\n //if user needs to log in\n else {\n var html = HtmlService.createHtmlOutput('<html><script>'\n +'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'\n +'var a = document.createElement(\"a\"); a.href=\"'+url+'\"; a.target=\"_blank\";'\n +'if(document.createEvent){'\n +' var event=document.createEvent(\"MouseEvents\");'\n +' if(navigator.userAgent.toLowerCase().indexOf(\"firefox\")>-1){window.document.body.append(a)}' \n +' event.initEvent(\"click\",true,true); a.dispatchEvent(event);'\n +'}else{ a.click() }'\n +'close();'\n +'</script>'\n // Offer URL as clickable link in case above code fails.\n +'<body style=\"word-break:break-word;font-family:sans-serif;\">Failed to open automatically. <a href=\"'+url+'\" target=\"_blank\" onclick=\"window.close()\">Click here to proceed</a>.</body>'\n +'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'\n +'</html>').setWidth( 90 ).setHeight( 1 );\n showSidebar();\n DocumentApp.getUi().showModalDialog( html, \"Opening ...\" );\n }\n}",
"function loginToGithub2(loginAgain){\n url = getGitHubRateLimit2();\n //if already logged in\n if (url == null && !loginAgain) {\n RepoPullOptions();\n }\n //if user needs to log in\n else {\n var html = HtmlService.createHtmlOutput('<html><script>'\n +'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'\n +'var a = document.createElement(\"a\"); a.href=\"'+url+'\"; a.target=\"_blank\";'\n +'if(document.createEvent){'\n +' var event=document.createEvent(\"MouseEvents\");'\n +' if(navigator.userAgent.toLowerCase().indexOf(\"firefox\")>-1){window.document.body.append(a)}' \n +' event.initEvent(\"click\",true,true); a.dispatchEvent(event);'\n +'}else{ a.click() }'\n +'close();'\n +'</script>'\n // Offer URL as clickable link in case above code fails.\n +'<body style=\"word-break:break-word;font-family:sans-serif;\">Failed to open automatically. <a href=\"'+url+'\" target=\"_blank\" onclick=\"window.close()\">Click here to proceed</a>.</body>'\n +'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'\n +'</html>').setWidth( 90 ).setHeight( 1 );\n showSidebar();\n DocumentApp.getUi().showModalDialog( html, \"Opening ...\" );\n }\n}",
"function lastCommit(username){\n return fetch('https://api.github.com/users/' + username + '/events',{headers: {'Authorization': 'token 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'}} )\n .then(response => response.json())\n .then(user => console.log(\"Last push was: \" + user[0].created_at))\n .catch(error => console.log(\"error!\"))\n // .then(response => {\n // response.json().then( user => {\n // console.log(user);\n // console.log(user[0].created_at);\n // resolve();\n // });\n // });\n}",
"function fetchUserbybranch() {\r\n \tvar deferred = $q.defer();\r\n $http.get('users/')\r\n .then(\r\n function (response) {\r\n deferred.resolve(response.data);\r\n },\r\n function(errResponse){\r\n deferred.reject(errResponse);\r\n }\r\n );\r\n return deferred.promise;\r\n }",
"async loadUserData() {\n let call = \"https://api.github.com/repos/\" + this.props.content + \"/pulls\";\n let data = await this.fetchGithub(call);\n\n let pulls = [];\n this.setState({\n numPulls: data.length >= MAXPULLS ? MAXPULLS : data.length\n });\n\n for (let i = 0; i < this.state.numPulls; i++) {\n let approvals = await this.getApprovals(data[i].number);\n let statuses = await this.getStatuses(data[i].statuses_url);\n let description = this.formatDescription(data[i].body);\n\n pulls[i] = {\n author: data[i].user.login,\n number: data[i].number,\n title: data[i].title,\n description: description,\n timeCreated: getRelativeTime(new Date(data[i].created_at)),\n url: data[i].html_url,\n approvals: approvals,\n statuses: statuses\n };\n }\n\n this.setState({ prs: pulls });\n }",
"async function getRandomGithubRepository() {\n const availablesGithubRepos = [];\n\n githubRepositories.map((repoGithub) => {\n // Check if the GitHub repository exist in our back-end\n const isAvailable = !repositories.some(\n (repo) => repo.title.toLowerCase() === repoGithub.name.toLowerCase()\n );\n\n // If the GitHub repository does not exist in our back-end then we set this repository as available\n if (isAvailable) {\n availablesGithubRepos.push(repoGithub);\n }\n });\n\n // Check if there is an available Github repositories\n if (availablesGithubRepos.length === 0) {\n throw new Error(\"None Github repository available 😕\");\n }\n\n // Get a random integer between 0 and amount of available GitHub repositories\n const randomIndex = Math.floor(\n Math.random() * availablesGithubRepos.length\n );\n\n // Prepare an object to send the params to the getGithubRepositoryLanguages function\n const params = {\n owner: availablesGithubRepos[randomIndex].owner.login,\n name: availablesGithubRepos[randomIndex].name,\n };\n\n // Get techs (languages) from the repository\n const techs = (await getGithubRepositoryLanguages(params)).data;\n\n /**\n * The return of techs variable is something like this:\n *\n * {\n * \"Dart\": 13244,\n * \"Java\": 367,\n * \"JavaScript\": 753\n * }\n *\n * So in this case we are grabbing only the Key of each element and converting it in an Array\n *\n * The result of techsArray should be:\n * [\"Dart\", \"Java\", \"JavaScript\"]\n */\n // Convert techs to an Array\n var techsArray = Object.keys(techs).map((key) => {\n return key;\n });\n\n const repo = {\n title: availablesGithubRepos[randomIndex].name,\n url: availablesGithubRepos[randomIndex].url,\n techs: techsArray,\n };\n\n return repo;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
signup method which renders the signup.hbs view | signup(request, response) {
const viewData = {
title: 'Sign Up',
};
response.render('signup', viewData);
} | [
"static sign_up(callback = null) {\n // Hide the inputs\n window.UI.hide(\"authenticate-inputs\");\n // Change the output message\n this.output(\"Hold on - Signing you up...\");\n // Send the API call\n window.API.send(\"authenticate\", \"signup\", {\n name: window.UI.find(\"authenticate-name\").value,\n password: window.UI.find(\"authenticate-password\").value\n }, (success, result) => {\n if (success) {\n // Call the signin function\n this.sign_in(callback);\n } else {\n // Show the inputs\n window.UI.show(\"authenticate-inputs\");\n // Change the output message\n this.output(result, true);\n }\n });\n }",
"function signUp()\n {\n var email = document.getElementById(\"email\");\n var password = document.getElementById(\"password\");\n const promise = auth.createUserWithEmailAndPassword(email.value, password.value);\n promise.catch(e => alert(e.message));\n \n alert(\"You've successfully signed up, please log in to continue shopping!\");\n if (auth.createUserWithEmailAndPassword(email.value, password.value))\n {\n window.location.href=\"LogInApparelStation.html\"\n }\n }",
"viewRegister(req, res) {\r\n res.render('register', {\r\n message: \"\"\r\n });\r\n }",
"function signUp() {\n $('#main-header').text(\"B-Day List\");\n $('#login-container').hide();\n $('#logout-btn').removeClass('hide');\n $('#add-btn').removeClass('hide');\n }",
"async handleSignup (e) {\n e.preventDefault()\n try {\n const pupil = await client.resource('pupil').create(this.state)\n this.props.history.push('/login')\n } catch (error) {\n console.log(error)\n this.props.history.push('/error')\n }\n }",
"function handleHomeSignUp() {\n\t$('.nav-container').on('click','.signup-button', function(event) {\n\t\tconsole.log('Sign Up clicked');\n\t\tevent.preventDefault();\n\t\tshowSignUp();\t\n\t})\n}",
"function handleShowSignUp() {\n $('body').on(\"click\", \"#js-show-sign-up-form-btn\", (event) => {\n displaySignUpForm($('.js-content'));\n });\n}",
"onSignUp() {\n const { email } = this.state;\n Alert.alert('Confirmation Email to ' + `${email}` + ' has been sent!');\n }",
"async handleCompleteSignup() {\n const { user: { id, fuid }, firebase, setUserAction } = this.getProps(); \n const values = this._getUserSignupValues();\n \n this.toState({ userSectionLoading: true });\n\n let toApi = StateToApi.updateFirebaseUser(values);\n let promise = await this.userRepo.updateFirebaseUser(toApi, fuid);\n if(promise.err) {\n this.toState({ userSectionLoading: false });\n throw new Error('Error updating firebase user');\n }\n \n await SocialMediaHelper.signInWithEmailAndPassword(firebase, values.signupEmail, values.signupPassword);\n \n toApi = StateToApi.signupUser(values);\n promise = await this.userRepo.updateUser(toApi, id);\n if(!promise.err) {\n setUserAction(new User(promise.data));\n }\n \n this.toState({ userSectionLoading: false, openedSection: 'address', isUserSectionDone: true });\n }",
"function signUp(form) {\r\n\r\n var user =\r\n {\"email\" : form.email.value,\r\n \"password\" : form.password[1].value,\r\n \"firstname\" : form.firstname.value,\r\n \"familyname\" : form.familyname.value,\r\n \"gender\" : form.gender.value,\r\n \"city\" : form.city.value,\r\n \"country\" : form.country.value};\r\n\r\n var result = serverstub.signUp(user);\r\n\r\n // status message\r\n document.getElementById('message').innerHTML = \"<h2>\" + result.message + \"</h2>\";\r\n}",
"_signup() {\n\t\tconst { email, password, verify } = this.state;\n\t\tif(!email || !password || !verify) this.setState({ message: 'Not all fields were filled out.' }); \n\t\telse if(email.indexOf('@') < 0) this.setState({ message: 'Invalid email provided.' });\n\t\telse if(password !== verify){\n\t\t\t\tthis.setState({ message: 'Passwords don\\'t match.' });\n\t\t} else {\n\t\t\tthis.props.signup(email, password);\n\t\t}\n }",
"function signup(userData){\n console.log(\"creating new user \"+userData.id);\n return User.create(userData)\n }",
"function signup(email, password){\n return auth.createUserWithEmailAndPassword(email,password);\n }",
"function onSignUpClicked (event) {\n let isValid = true;\n let userType = 'student';\n\n $(getClassName(userType, 'signUpFirstNameError')).hide()\n $(getClassName(userType, 'signUpLastNameError')).hide()\n $(getClassName(userType, 'signUpCountryCodeError')).hide()\n $(getClassName(userType, 'SignUpPhoneNumberError')).hide()\n $(getClassName(userType, 'SignUpEmailError')).hide()\n $(getClassName(userType, 'SignUpPasswordError')).hide()\n const firstName = $(getClassName(userType, 'signUpFirstName'))[0].value;\n const lastName = $(getClassName(userType, 'signUpLastName'))[0].value;\n const countryCode = $(getClassName(userType, 'signUpCountryCode'))[0].value;\n const phoneNumber = $(getClassName(userType, 'signUpPhoneNumber'))[0].value;\n const emailId = $(getClassName(userType, 'signUpEmail'))[0].value;\n const password = $(getClassName(userType, 'signUpPassword'))[0].value;\n if (!firstName) {\n $(getClassName(userType, 'signUpFirstNameError')).text('Please provide First Name');\n $(getClassName(userType, 'signUpFirstNameError')).show()\n isValid = false;\n }\n if (!lastName) {\n $(getClassName(userType, 'signUpLastNameError')).text('Please provide Last Name');\n $(getClassName(userType, 'signUpLastNameError')).show()\n isValid = false;\n }\n if (countryCode === 'none') {\n $(getClassName(userType, 'signUpCountryCodeError')).text('Please select country code');\n $(getClassName(userType, 'signUpCountryCodeError')).show()\n isValid = false;\n }\n if (phoneNumber && !isPhoneNumberValid(phoneNumber)) {\n $(getClassName(userType, 'SignUpPhoneNumberError')).text('Please add valid phone number');\n $(getClassName(userType, 'SignUpPhoneNumberError')).show()\n isValid = false;\n }\n if (!emailId) {\n $(getClassName(userType, 'SignUpEmailError')).text('Please provide email');\n $(getClassName(userType, 'SignUpEmailError')).show()\n isValid = false;\n }\n if (!password) {\n $(getClassName(userType, 'SignUpPasswordError')).text('Please provide password');\n $(getClassName(userType, 'SignUpPasswordError')).show()\n isValid = false;\n }\n\n if (isValid) {\n signUpAPI(userType, firstName, lastName, `${countryCode}${phoneNumber}`, emailId, password)\n }\n}",
"function startRegister() {\n\tif(request.httpParameterMap.MailExisted.value != null && request.httpParameterMap.MailExisted.value != 'true'){\n\t\tapp.getForm('profile').clear();\n\t}\n\n if (app.getForm('login.username').value() !== null) {\n app.getForm('profile.customer.email').object.value = app.getForm('login.username').object.value;\n }\n app.getView({\n ContinueURL: URLUtils.https('Account-RegistrationForm')\n }).render('account/user/registration');\n}",
"function handleCreateAccount() {\n\t$('.open-create-account').on('click', event => {\n\t\t$('.Welcome').addClass(\"hidden\");\n\t\t$('.Create-Account-Page').removeClass(\"hidden\");\n\t});\n}",
"async function signup(name, email, password, select, clientTrainer) {\n const newUser = await auth.createUserWithEmailAndPassword(email, password);\n\n await newUser.user.updateProfile({\n displayName: name,\n });\n\n //Gives every user (trainer or client) an email property in auth object\n await newUser.user.updateEmail(email);\n\n await setUid(newUser.user.uid);\n\n //creates user or trainer in db and sets the usertype to selected value in dropdown\n //adds clients trainer to their user information\n if (select === \"Trainer\") {\n return await db.collection(\"trainers\").doc(newUser.user.email).set({\n userType: select,\n });\n } else {\n return await db.collection(\"users\").doc(newUser.user.uid).set({\n userType: select,\n clientTrainer: clientTrainer,\n });\n }\n }",
"function registrationForm() {\n app.getForm('profile').handleAction({\n confirm: function () {\n var email, profileValidation, password, passwordConfirmation, existingCustomer, Customer, target, customerExist;\n\n Customer = app.getModel('Customer');\n email = app.getForm('profile.customer.email').value();\n \n profileValidation = true;\n customerExist = false;\n \n password = app.getForm('profile.login.password').value();\n passwordConfirmation = app.getForm('profile.login.passwordconfirm').value();\n\n if (password !== passwordConfirmation) {\n app.getForm('profile.login.passwordconfirm').invalidate();\n profileValidation = false;\n }\n\n // Checks if login is already taken.\n existingCustomer = Customer.retrieveCustomerByLogin(email);\n if (existingCustomer !== null) {\n app.getForm('profile.customer.email').invalidate();\n profileValidation = false;\n customerExist = true;\n }\n\n if (profileValidation) {\n profileValidation = Customer.createAccount(email, password, app.getForm('profile'));\n }\n\n if (!profileValidation) {\n \tif(customerExist){\n \t\tresponse.redirect(URLUtils.https('Login-Show','existing', true));\n \t} else {\n \t\tresponse.redirect(URLUtils.https('Account-Show'));\n \t}\n } else {\n \tif (Site.getCurrent().getCustomPreferenceValue('MailChimpEnable')) {\n if (app.getForm('profile.customer.addtoemaillist').value()) {\n \tvar mailchimpHelper = require('*/cartridge/scripts/util/MailchimpHelper.js');\n \tmailchimpHelper.addNewListMember(app.getForm('profile.customer.firstname').value(), app.getForm('profile.customer.email').value());\n }\n } else {\n \tltkSignupEmail.Signup();\n }\n app.getForm('profile').clear();\n target = session.custom.TargetLocation;\n if (target) {\n delete session.custom.TargetLocation;\n //@TODO make sure only path, no hosts are allowed as redirect target\n dw.system.Logger.info('Redirecting to \"{0}\" after successful login', target);\n response.redirect(target);\n } else {\n response.redirect(URLUtils.https('Account-Show', 'registration', 'true'));\n }\n }\n }\n });\n}",
"function viewInSignupLanguage(req) {\n const signupLanguage = req.query.signupLanguage || req.body.signupLanguage;\n if (signupLanguage && languages.isValid(signupLanguage))\n i18n.setLocale(req, signupLanguage);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`_readRDFStarTail` reads the end of a nested RDF triple | _readRDFStarTail(token) {
if (token.type !== '>>') return this._error(`Expected >> but got ${token.type}`, token); // Read the quad and restore the previous context
const quad = this._quad(this._subject, this._predicate, this._object, this._graph || this.DEFAULTGRAPH);
this._restoreContext(); // If the triple was the subject, continue by reading the predicate.
if (this._subject === null) {
this._subject = quad;
return this._readPredicate;
} // If the triple was the object, read context end.
else {
this._object = quad;
return this._getContextEndReader();
}
} | [
"_readRDFStarTailOrGraph(token) {\n if (token.type !== '>>') {\n // An entity means this is a quad (only allowed if not already inside a graph)\n if (this._supportsQuads && this._graph === null && (this._graph = this._readEntity(token)) !== undefined) return this._readRDFStarTail;\n return this._error(`Expected >> to follow \"${this._object.id}\"`, token);\n }\n\n return this._readRDFStarTail(token);\n }",
"function TermTail() {\n var node = new Node('TermTail');\n p.child.push(node);\n p = node;\n if (word == '*' || word == '/') {\n p.operator = word;\n word = nextWord();\n if (!Factor()) {\n return false;\n } else {\n p = node;\n return TermTail();\n }\n }\n return true;\n }",
"getTail() {\n return this._tail;\n }",
"_readObject(token) {\n switch (token.type) {\n case 'literal':\n // Regular literal, can still get a datatype or language\n if (token.prefix.length === 0) {\n this._literalValue = token.value;\n return this._readDataTypeOrLang;\n } // Pre-datatyped string literal (prefix stores the datatype)\n else this._object = this._literal(token.value, this._namedNode(token.prefix));\n\n break;\n\n case '[':\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph, this._subject, this._predicate, this._subject = this._blankNode());\n\n return this._readBlankNodeHead;\n\n case '(':\n // Start a new list\n this._saveContext('list', this._graph, this._subject, this._predicate, this.RDF_NIL);\n\n this._subject = null;\n return this._readListItem;\n\n case '{':\n // Start a new formula\n if (!this._n3Mode) return this._error('Unexpected graph', token);\n\n this._saveContext('formula', this._graph, this._subject, this._predicate, this._graph = this._blankNode());\n\n return this._readSubject;\n\n case '<<':\n if (!this._supportsRDFStar) return this._error('Unexpected RDF* syntax', token);\n\n this._saveContext('<<', this._graph, this._subject, this._predicate, null);\n\n this._graph = null;\n return this._readSubject;\n\n default:\n // Read the object entity\n if ((this._object = this._readEntity(token)) === undefined) return; // In N3 mode, the object might be a path\n\n if (this._n3Mode) return this._getPathReader(this._getContextEndReader());\n }\n\n return this._getContextEndReader();\n }",
"extractLists({ remove = false, ignoreErrors = false } = {}) {\n const lists = {}; // has scalar keys so could be a simple Object\n const onError = ignoreErrors ? (() => true) :\n ((node, message) => { throw new Error(`${node.value} ${message}`); });\n\n // Traverse each list from its tail\n const tails = this.getQuads(null, IRIs[\"default\"].rdf.rest, IRIs[\"default\"].rdf.nil, null);\n const toRemove = remove ? [...tails] : [];\n tails.forEach(tailQuad => {\n const items = []; // the members found as objects of rdf:first quads\n let malformed = false; // signals whether the current list is malformed\n let head; // the head of the list (_:b1 in above example)\n let headPos; // set to subject or object when head is set\n const graph = tailQuad.graph; // make sure list is in exactly one graph\n\n // Traverse the list from tail to end\n let current = tailQuad.subject;\n while (current && !malformed) {\n const objectQuads = this.getQuads(null, null, current, null);\n const subjectQuads = this.getQuads(current, null, null, null);\n let quad, first = null, rest = null, parent = null;\n\n // Find the first and rest of this list node\n for (let i = 0; i < subjectQuads.length && !malformed; i++) {\n quad = subjectQuads[i];\n if (!quad.graph.equals(graph))\n malformed = onError(current, 'not confined to single graph');\n else if (head)\n malformed = onError(current, 'has non-list arcs out');\n\n // one rdf:first\n else if (quad.predicate.value === IRIs[\"default\"].rdf.first) {\n if (first)\n malformed = onError(current, 'has multiple rdf:first arcs');\n else\n toRemove.push(first = quad);\n }\n\n // one rdf:rest\n else if (quad.predicate.value === IRIs[\"default\"].rdf.rest) {\n if (rest)\n malformed = onError(current, 'has multiple rdf:rest arcs');\n else\n toRemove.push(rest = quad);\n }\n\n // alien triple\n else if (objectQuads.length)\n malformed = onError(current, 'can\\'t be subject and object');\n else {\n head = quad; // e.g. { (1 2 3) :p :o }\n headPos = 'subject';\n }\n }\n\n // { :s :p (1 2) } arrives here with no head\n // { (1 2) :p :o } arrives here with head set to the list.\n for (let i = 0; i < objectQuads.length && !malformed; ++i) {\n quad = objectQuads[i];\n if (head)\n malformed = onError(current, 'can\\'t have coreferences');\n // one rdf:rest\n else if (quad.predicate.value === IRIs[\"default\"].rdf.rest) {\n if (parent)\n malformed = onError(current, 'has incoming rdf:rest arcs');\n else\n parent = quad;\n }\n else {\n head = quad; // e.g. { :s :p (1 2) }\n headPos = 'object';\n }\n }\n\n // Store the list item and continue with parent\n if (!first)\n malformed = onError(current, 'has no list head');\n else\n items.unshift(first.object);\n current = parent && parent.subject;\n }\n\n // Don't remove any quads if the list is malformed\n if (malformed)\n remove = false;\n // Store the list under the value of its head\n else if (head)\n lists[head[headPos].value] = items;\n });\n\n // Remove list quads if requested\n if (remove)\n this.removeQuads(toRemove);\n return lists;\n }",
"function ExprTail() {\n var node = new Node('ExprTail');\n p.child.push(node);\n p = node;\n if (word == '+' || word == '-') {\n p.operator = word;\n word = nextWord();\n if (!Term()) {\n return false;\n } else {\n p = node;\n return ExprTail();\n }\n }\n return true;\n }",
"function tail(stream) /* forall<a> (stream : stream<a>) -> stream<a> */ {\n return stream.tail;\n}",
"function ELEMENT_TAIL$static_(){LinkListBEMEntities.ELEMENT_TAIL=( LinkListBEMEntities.BLOCK.createElement(\"tail\"));}",
"function readMtx(pth) {\n var ls = readFile(pth).split('\\n');\n var [, order, size] = ls[1].split(' ').map(parseFloat);\n var g = new DiGraph(order);\n for (var n=2, N=ls.length; n<N; n++) {\n var [i, j, wt] = ls[n].split(' ').map(parseFloat);\n if (wt) g.addLink(i-1, j-1, wt);\n }\n return g;\n}",
"*readQuads(subject, predicate, object, graph) {\n // Convert terms to internal string representation\n subject = subject && (0,N3DataFactory/* termToId */.dW)(subject);\n predicate = predicate && (0,N3DataFactory/* termToId */.dW)(predicate);\n object = object && (0,N3DataFactory/* termToId */.dW)(object);\n graph = graph && (0,N3DataFactory/* termToId */.dW)(graph);\n\n const graphs = this._getGraphs(graph), ids = this._ids;\n let content, subjectId, predicateId, objectId;\n\n // Translate IRIs to internal index keys.\n if (isString(subject) && !(subjectId = ids[subject]) ||\n isString(predicate) && !(predicateId = ids[predicate]) ||\n isString(object) && !(objectId = ids[object]))\n return;\n\n for (const graphId in graphs) {\n // Only if the specified graph contains triples, there can be results\n if (content = graphs[graphId]) {\n // Choose the optimal index, based on what fields are present\n if (subjectId) {\n if (objectId)\n // If subject and object are given, the object index will be the fastest\n yield* this._findInIndex(content.objects, objectId, subjectId, predicateId,\n 'object', 'subject', 'predicate', graphId);\n else\n // If only subject and possibly predicate are given, the subject index will be the fastest\n yield* this._findInIndex(content.subjects, subjectId, predicateId, null,\n 'subject', 'predicate', 'object', graphId);\n }\n else if (predicateId)\n // If only predicate and possibly object are given, the predicate index will be the fastest\n yield* this._findInIndex(content.predicates, predicateId, objectId, null,\n 'predicate', 'object', 'subject', graphId);\n else if (objectId)\n // If only object is given, the object index will be the fastest\n yield* this._findInIndex(content.objects, objectId, null, null,\n 'object', 'subject', 'predicate', graphId);\n else\n // If nothing is given, iterate subjects and predicates first\n yield* this._findInIndex(content.subjects, null, null, null,\n 'subject', 'predicate', 'object', graphId);\n }\n }\n }",
"getLast() {\n if (!this.head) {\n return null;\n }\n let node = this.head;\n while (node) {\n // If next is null, then we are at the last node\n if (!node.next) {\n return node;\n }\n node = node.next;\n }\n }",
"tail() {\n return null;\n }",
"function getTailAndSize(ll) {\n\tlet currentNode = ll.head;\n\tlet counter = 1;\n\n\twhile(currentNode.next) {\n\t\tcurrentNode = currentNode.next;\n\t\tcounter++;\n\t}\n\n\treturn { tail: currentNode, size: counter };\n}",
"function readGraph(resource) {\n // Read the resource's file\n return new Promise((resolve, reject) => {\n fs.readFile(resource.path, {encoding: 'utf8'}, function (err, fileContents) {\n if (err) {\n // If the file does not exist, assume empty contents\n // (it will be created after a successful patch)\n if (err.code === 'ENOENT') {\n fileContents = ''\n debug('empty file in ' + resource.path)\n // Fail on all other errors\n } else {\n return reject(error(500, `Original file read error: ${err}`))\n }\n }\n debug('PATCH -- Read target file (%d bytes)', fileContents.length)\n resolve(fileContents)\n })\n }\n ).catch(err => debug('ERROR in patch.js in readgraph: ' + err))\n}",
"function skip1(previousExpr) {\n \n \n if( previousExpr == always ) {\n /* If there is no previous expression this consume command \n is at the start of the jsonPath.\n Since JSONPath specifies what we'd like to find but not \n necessarily everything leading down to it, when running\n out of JSONPath to check against we default to true */\n return always;\n }\n \n /** return true if the ascent we have contains only the JSON root,\n * false otherwise\n */\n function notAtRoot(ascent){\n return headKey(ascent) != ROOT_PATH;\n }\n \n return lazyIntersection(\n /* If we're already at the root but there are more \n expressions to satisfy, can't consume any more. No match.\n \n This check is why none of the other exprs have to be able \n to handle empty lists; skip1 is the only evaluator that \n moves onto the next token and it refuses to do so once it \n reaches the last item in the list. */\n notAtRoot,\n \n /* We are not at the root of the ascent yet.\n Move to the next level of the ascent by handing only \n the tail to the previous expression */ \n compose2(previousExpr, tail) \n );\n \n }",
"function MODIFIER_NO_TAIL$static_(){LinkListBEMEntities.MODIFIER_NO_TAIL=( LinkListBEMEntities.BLOCK.createModifier(\"no-tail\"));}",
"visitTrailer(ctx) {\r\n console.log(\"visitTrailer\");\r\n if (ctx.OPEN_PAREN() !== null) {\r\n return { type: \"ArgList\", value: this.visit(ctx.arglist()) };\r\n } else if (ctx.OPEN_BRACK() !== null) {\r\n return {\r\n type: \"SubscriptList\",\r\n value: this.visit(ctx.subscriptlist()),\r\n };\r\n } else {\r\n return {\r\n type: \"Property\",\r\n value: ctx.NAME().getText(),\r\n };\r\n }\r\n }",
"get nextPath() { return this.next && this.next.path }",
"_readSubject(token) {\n this._predicate = null;\n\n switch (token.type) {\n case '[':\n // Start a new quad with a new blank node as subject\n this._saveContext('blank', this._graph, this._subject = this._blankNode(), null, null);\n\n return this._readBlankNodeHead;\n\n case '(':\n // Start a new list\n this._saveContext('list', this._graph, this.RDF_NIL, null, null);\n\n this._subject = null;\n return this._readListItem;\n\n case '{':\n // Start a new formula\n if (!this._n3Mode) return this._error('Unexpected graph', token);\n\n this._saveContext('formula', this._graph, this._graph = this._blankNode(), null, null);\n\n return this._readSubject;\n\n case '}':\n // No subject; the graph in which we are reading is closed instead\n return this._readPunctuation(token);\n\n case '@forSome':\n if (!this._n3Mode) return this._error('Unexpected \"@forSome\"', token);\n this._subject = null;\n this._predicate = this.N3_FORSOME;\n this._quantifier = this._blankNode;\n return this._readQuantifierList;\n\n case '@forAll':\n if (!this._n3Mode) return this._error('Unexpected \"@forAll\"', token);\n this._subject = null;\n this._predicate = this.N3_FORALL;\n this._quantifier = this._variable;\n return this._readQuantifierList;\n\n case 'literal':\n if (!this._n3Mode) return this._error('Unexpected literal', token);\n\n if (token.prefix.length === 0) {\n this._literalValue = token.value;\n return this._completeSubjectLiteral;\n } else this._subject = this._literal(token.value, this._namedNode(token.prefix));\n\n break;\n\n case '<<':\n if (!this._supportsRDFStar) return this._error('Unexpected RDF* syntax', token);\n\n this._saveContext('<<', this._graph, null, null, null);\n\n this._graph = null;\n return this._readSubject;\n\n default:\n // Read the subject entity\n if ((this._subject = this._readEntity(token)) === undefined) return; // In N3 mode, the subject might be a path\n\n if (this._n3Mode) return this._getPathReader(this._readPredicateOrNamedGraph);\n } // The next token must be a predicate,\n // or, if the subject was actually a graph IRI, a named graph\n\n\n return this._readPredicateOrNamedGraph;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get if a test rely on AAA wcag rules | function getAAA(currentWcag) {
let level = false;
if (currentWcag) {
dataWCAG.items.forEach(function(current){
if (current.wcag === currentWcag) {
if (current.level === 'AAA') {
level = true;
}
}
});
}
return level;
} | [
"function bevatEenA(tekst) {\n var uitkomst = false;\n\n if (tekst.indexOf(\"a\") >= 0 || tekst.indexOf(\"A\") >= 0) {\n uitkomst = true;\n }\n\n return uitkomst;\n}",
"has_ace() {\n if (this.mycards.includes(1)) return true;\n return false;\n }",
"function atkTest(char, skillNum, atkNum, edgeDist, activeFrame, inactiveFrame, endFrame, endTest, activeTest){\n return function(){\n char.skills[skillNum-1].use();\n char.frameProcess();\n var atk = char.attackList[atkNum];\n for (let i=1; i<activeFrame; i++){\n assert.strictEqual(atk.curFrame, 0, `Skill should not be active on frame ${i}`);\n char.frameProcess();\n }\n for (let i=activeFrame; i<inactiveFrame; i++){\n assert(atk.curFrame!==0, `Skill should be active on frame ${i}`);\n assert.strictEqual(atk.posx, char.posx+(char.radius+atk.radius+edgeDist)*char.facex, \n `Attack x position wrong on frame ${i}`);\n assert.strictEqual(atk.posy, char.posy+(char.radius+atk.radius+edgeDist)*char.facey, \n `Attack y position wrong on frame ${i}`);\n if (activeTest) activeTest(char, atk, i);\n char.frameProcess();\n }\n for (let i=inactiveFrame; i<endFrame; i++){\n assert.strictEqual(atk.curFrame, 0, `Skill not active on frame ${i}`);\n char.frameProcess();\n }\n if (endTest) endTest(char, atk);\n }\n }",
"checkRule(name) {\n const rule = this.rules[name];\n\n switch (rule.recurrent) {\n case true:\n if (typeof name === \"string\" && rule && rule.ruleset) {\n return true;\n }\n break;\n default:\n if (typeof name === \"string\" && rule && typeof rule.test === \"function\" && typeof rule.message === \"string\") {\n return true;\n }\n }\n\n throw new Error(\n name + \" is not a complete rule. A complete rule must contain both `test` function and `message` string.\"\n );\n }",
"_isADateRule (rule) {\n return !! ~['after', 'before', 'date_between', 'date_format'].indexOf(rule);\n }",
"async function testCheck(ip) {\n var nacl = new NACLImpl();\n var interval = 2000; // the aws rules take time to take effect\n\n var rules = await nacl.getRules();\n // await addRule(nacl, 101, 80, \"allow\");\n // await addRule(nacl, 102, 8080, \"allow\");\n // await addRule(nacl, 201, 8081, \"allow\");\n // await testSleep(interval);\n // await testAccess(ip, [80, 8080, 8081, 8082], [true, true, true, false]);\n // console.log('passed:', passed, ' failed:', failed);\n\n await addRule(nacl, 105, 85, \"deny\");\n await addRule(nacl, 205, 8085, \"deny\");\n await testSleep(interval);\n\n \n // 1. deny rule in 100s blocks allow rule in 200s\n var rule = formatRule(\"0.0.0.0/0\", false, 8081, 8081, '6', \"deny\", 110);\n console.log('Provider deny rule conflict:', nacl.checkConflict(rule));\n // 2. deny rule in 200s ignored due to allow rule in 100s\n var rule = formatRule(\"0.0.0.0/0\", false, 80, 80, '6', \"deny\", 210);\n console.log('Tenant deny rule conflict:', nacl.checkConflict(rule));\n // 3. allow rule in 100s masks deny rule in 200s\n var rule = formatRule(\"0.0.0.0/0\", false, 8085, 8085, '6', \"allow\", 115);\n console.log('Provider allow rule conflict:', nacl.checkConflict(rule));\n // 4. allow rule in 200s masked by deny rule in 100s \n var rule = formatRule(\"0.0.0.0/0\", false, 85, 85, '6', \"allow\", 215);\n console.log('Tenant allow rule conflict:', nacl.checkConflict(rule));\n}",
"static canParse( testName ) {\n const benchmarkParserKey = Utils.getBenchmarkParserKey(testName);\n if(benchmarkParserKey) {\n return true;\n }\n return false;\n }",
"_is_testing() {\n return this.env != \"production\" && this.env != \"prod\";\n }",
"function testResponse (res, keyword) {\n // for (var i=0; i<keyword.length; i++) {\n // if (keyword[i].test(res)) {\n // return true;\n // }\n // }\n // if (kyle.test(res) || davis.test(res)) {\n // return true;\n // }\n // if (name===\"Bebe Ballo\" || name===\"Shriyans Lenkala\" || name===\"Keyshawn Ebanks\") { \n // return true;\n // }\n return false;\n}",
"function isPassing(grade){\n return grade >= 10;\n}",
"function testActivityChoiceParsing() { \n Logger.log('Testing activity choice parsing...');\n \n if (!checkActivityChoiceParsing('Throwing',\n '5 pts./15 min.',\n 'Throwing [5 pts./15 min.] Throwing in pairs (at most 3 players/disc)')) {\n return false;\n }\n \n if (!checkActivityChoiceParsing('Playing video games',\n '1 pts./3 hr.',\n 'Playing video games [1 pts./3 hr.] Mindlessly gazing into your phone forever')) {\n return false;\n }\n \n if (!checkActivityChoiceParsing('Sharing media',\n '3 pts.',\n 'Sharing media [3 pts.] Blah blah blah')) {\n return false;\n }\n \n if (!checkActivityChoiceParsing('Daily team check-in',\n '1 pts.',\n 'Daily team check-in [1 pts.] Blah blah blah')) {\n return false;\n }\n \n Logger.log('Test passed.');\n return true;\n}",
"function test(z0, alpha) {\n alpha = alpha || 0.05;\n\n var norm_std = Math.abs(calc_inv_norm_st(alpha/2));\n if (z0 >= -(norm_std) && z0 <= norm_std) return 0;\n else return 1;\n}",
"function isContrastCompliant(background, foreground, compliance) {\n if (compliance === void 0) { compliance = \"normal\"; }\n var ratio;\n switch (compliance) {\n case \"large\":\n ratio = exports.LARGE_TEXT_CONTRAST_RATIO;\n break;\n case \"normal\":\n ratio = exports.NORMAL_TEXT_CONTRAST_RATIO;\n break;\n case \"AAA\":\n ratio = exports.AAA_CONTRAST_RATIO;\n break;\n default:\n ratio = compliance;\n }\n return getContrastRatio_1.default(background, foreground) >= ratio;\n}",
"function processArgs( a ){\n\t\t// If is from a standard GTM UA template tag, automatically allow hit.\n\t\tif( a[0] && a[0].substr && a[0].substr( 0, 3 ) == 'gtm' )\n\t\t\treturn true;\n\t\t// Call listener, return false only if listener returns false.\n\t\treturn callback( a ) !== false;\n\t}",
"calcGoalStatus(goal, assessments) {\n logger.info(\"Get goal status\", goal.id);\n let goalStatus = \"Open\";\n\n if (assessments.length > 0) {\n logger.info(\"Assessment Exists, checking goal\", assessments);\n for (let t = 0; t < assessments.length; t++) {\n if (Date.parse(goal.startDate) <= Date.parse(assessments[t].dateTime) \n && Date.parse(goal.targetDate) < Date.parse(assessments[t].dateTime)) {\n goalStatus = \"Missed\";\n break;\n } else if (Date.parse(goal.startDate) <= Date.parse(assessments[t].dateTime) &&\n Date.parse(goal.targetDate) >= Date.parse(assessments[t].dateTime)) {\n if (goal.measurementType === \"weight\") {\n if (assessments[t].weight <= goal.targetMeasurement) {\n goalStatus = \"Achieved\";\n break;\n } else {\n goalStatus = \"Open\";\n break;\n }\n } else if (goal.measurementType === \"waist\") {\n if (assessments[t].waist <= goal.targetMeasurement) {\n goalStatus = \"Achieved\";\n break;\n } else {\n goalStatus = \"Open\";\n break;\n }\n }\n } else {\n goalStatus = \"Open\"\n break;\n }\n }\n } else {\n logger.info(\"No Assessment Exists\", assessments);\n goalStatus = \"Open\";\n }\n return goalStatus;\n }",
"function isAdultLeaner(data) {\r\n\t\tvar result;\r\n\t\tswitch (data) {\r\n\t\t\tcase \"AA\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"ADLT\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"BBA\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"BCJ\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"BHUM\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"BSB\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"EBCJ\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"HRM\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tcase \"XPCO\":\r\n\t\t\t\tresult = true;\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tresult = false;\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t\treturn result;\r\n\t}",
"calculateHasConfidence(){\n return this.props.techniques.find(r => r.confidence !== undefined) !== undefined;\n }",
"isValidGherkin(gherkin) {\n if (gherkin === null) {\n return false;\n }\n const lines = gherkin.split('\\n')\n .map(Function.prototype.call, String.prototype.trim)\n .filter((line) => line.length > 0 && line.indexOf('Feature:') !== 0 && line.indexOf('Scenario:') !== 0);\n const re = new RegExp('^(Given|When|And|Then|Examples|\\\\||#)', 'i');\n const validLines = lines.filter((line) => re.test(line));\n let numLinesWithData = 0;\n let isData = false;\n for (let i = 0; i < lines.length; i++) {\n if (lines[i].substr(0, 3) === '\"\"\"') {\n numLinesWithData++;\n isData = !isData;\n continue;\n }\n if (isData) {\n numLinesWithData++;\n continue;\n }\n }\n return (lines.length === validLines.length + numLinesWithData);\n }",
"function mustBeTrue (boo){\n\tif (boo === true){\n\t\treturn true;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ex5 Gasiti cel mai lung string intro fraza findLongestString('Wantsome is Awsomeeee today') output 'Awsomeeee' | function findLongestString(stringToFind) {
let stringToSeek = stringToFind.split(" ");
let longestString = stringToSeek[0];
for (let i = 0; i < stringToSeek.length; i++) {
if (longestString.length < stringToSeek[i].length) {
longestString = stringToSeek[i];
}
}
return longestString;
} | [
"function longestSentence(longString) {\n let sentencesObj = {};\n let sentenceArr = longString.split(/([.!?])/);\n\n for (let i = 0; i < sentenceArr.length; i += 2) {\n let indSentence = sentenceArr[i].trimStart().concat(sentenceArr[i + 1]);\n let wordArr = indSentence.split(\" \");\n sentencesObj[wordArr.length] = indSentence;\n }\n\n let biggestKey = Math.max(...Object.keys(sentencesObj));\n\n console.log(`Longest sentence: \"${sentencesObj[biggestKey]}\"`);\n console.log(`The longest sentence has ${biggestKey.toString()} words.`)\n }",
"function LongestWord(sen) {\n let longest = \"\";\n sen.split(\" \").forEach((element) => {\n if (element.length > longest.length) longest = element;\n });\n return longest;\n}",
"function longestRun (string) {\n var charCount = 1;\n var currStr;\n var result;\n if (string === \"\") {\n return [0, 0];\n }\n var strArr = string.match(/([a-zA-Z])\\1*/gi);\n for (var i = 0; i < strArr.length; i++) {\n if (strArr[i].length > charCount) {\n currStr = strArr[i];\n charCount = strArr[i].length;\n }\n }\n if (charCount === 1) {\n return [0, 0];\n }\n result = [string.indexOf(currStr), (string.indexOf(currStr)+currStr.length-1)];\n\n return result;\n}",
"function LongestWord_2(sen) {\n sen = sen.replace(/[.,\\/#!$%\\^&\\*;:{}=\\-_`~()|]/g, \"\");\n\n let longest = \"\";\n sen.split(\" \").forEach((element) => {\n if (element.length > longest.length) longest = element;\n });\n return longest;\n}",
"getSongsLongestWords(song) {\n const words = song.split(' ');\n let one = '',\n two = '',\n temp;\n words.forEach(word => {\n if (word.length > two.length) {\n if (word.length > one.length) {\n temp = one;\n one = word;\n two = temp;\n } else {\n two = word;\n }\n }\n })\n return `${one} ${two}`;\n }",
"function longerString(x1, x2, x3, x4) {\n if (length1(x1) > length1(x2) && length1(x1) > length1(x3) &&\n length1(x1) > length1(x4)) {\n return x1;\n } else if ((length1(x1) < length1(x2) && length1(x2) > length1(x3)) &&\n length1(x2) > length1(x4)) {\n return x2;\n } else if ((length1(x1) < length1(x3) && length1(x3) > length1(x2)) &&\n length1(x3) > length1(x4)) {\n return x3;\n } else\n return x4;\n}",
"function findLongestWord(txt) {\n let strArrayA = txtNoPunctuation(txt);\n let strArrayB = cleanTxt(strArrayA);\n \n let orderedArray = strArrayB.sort(function (wordA, wordB){\n return wordB.length - wordA.length || wordA.localeCompare(wordB);\n });\n \n let filterArray = orderedArray.filter((item, pos, ary) => {\n return !pos || item != ary[pos - 1];\n });\n\n return filterArray.filter((i, index) => (index < 10));\n}",
"function longestVowelSubsequence(s) {\n // Write your code here\n s=s.split('');\n let iIndex=j.findIndex(o=>o==='a');\n let startIndex=iIndex;\n let jIndex=0;\n let j=['a','e','i','o','u'];\n let i=0;\n iIndex++;\n while(iIndex<s.length){\n if(jIndex===5){\n endIndex=iIndex;\n iIndex=s.length;\n // 返回结果\n }\n if(jIndex===0){\n if(s[iIndex]===j[jIndex]){\n startIndex=iIndex;\n iIndex++;\n }else{\n jIndex++;\n }\n }else{\n if(s[iIndex]===j[jIndex]){\n iIndex++;\n jIndex++;\n }else{\n iIndex++;\n }\n }\n \n }\n if(jIndex!==5){\n return 0;\n }\n let result_str=s.slice(startIndex,endIndex);\n let mIndex=0,nIndex=0;\n while(mIndex<result_str.length){\n let curIndex=j.findIndex(o=>o===result_str[mIndex]);\n if(curIndex===nIndex){\n mIndex++;\n }else if(curIndex-nIndex===1){\n nIndex++;\n }else if(curIndex<nIndex){\n result_str.splice(mIndex,1)\n }else{\n mIndex++\n }\n }\n return result_str.length;\n}",
"function findShort(inputString){\n splitString = inputString.split(' ')\n shortestLength = splitString[0].length\n\n for (let word of splitString) {\n if (word.length < shortestLength) {\n shortestLength = word.length\n }\n }\n return shortestLength\n }",
"function last(){\n\tvar isi = \"saya beajar di rumah beajar\";\n\tconsole.log(isi.lastIndexOf(\"beajar\",5)); //nilai angka berfungsi sebagai startnya di index\n}",
"function distinctLongestSubstring(s, k){\n // understand\n // so basically at each index, count longest substring with k charaters\n // if longer then previous longest, set as longest\n // until character count is greater then k\n\n // return longest\n}",
"function allLongestStrings(inputArray) {\n var max = 0;\n var returnArray = []; \n //find max length\n for(var i = 0; i<inputArray.length;i++){\n //if a string is longer than the found max\n if(inputArray[i].length > max){\n //empty return array\n returnArray.length = 0;\n //push element to return array\n returnArray.push(inputArray[i]);\n //set new max length\n max = inputArray[i].length;\n \n }\n //if found element is the same length as the found max.\n else if(inputArray[i].length == max){\n returnArray.push(inputArray[i]);\n }\n \n }\n \n return returnArray;\n}",
"function longestWord(phrasesArray) {\n\n// declare an maxIndex variable and initialize it to 0\n var maxIndex = 0;\n// declare a maxLength variable and initialize it to 0\n var maxLength = 0;\n// FOR EACH phrase in the array\n nbPhrases = phrasesArray.length;\n\n for(var index = 0; index < nbPhrases; index++) {\n// find the length of the phrase\n phraseLength = phrasesArray[index].length;\n// IF the length is bigger than max_length\n if(phraseLength >= maxLength) {\n// set maxIndex to the value of the index of the current phrase\n maxIndex = index;\n// set maxLength to the value of the length of the current phrase\n maxLength = phraseLength;\n }\n }\n\n // RETURN the phrase of phrases_array stocked at index number max_index\n return phrasesArray[maxIndex];\n}",
"function longestName(arr){\n var ruselt =arr.reduce(function(str,elm,i){\n //str=arr[0].name.first+\"\"+arr[0].name.last\n elm=arr[i].name.first+\"\"+arr[i].name.last\n if (str.length > elm.length) {\n return elm=str\n }return elm\n }\n ) \n return ruselt\n}",
"function ThirdGreatest(strArr) { \n\n//Find the lengths of the strings\n var stringLengths = [];\n for (i=0; i < strArr.length; i++) {\t\t\t\t\t\t\t\t\t//Loop goes through each element in the string returning the lengths into a new array\n stringLengths[i] = strArr[i].length;\n }\n\n var unsortedLengths = stringLengths.slice(0);\t\t\t\t\t\t\t//A clone of stringLengths is made so that stringLengths can be sorted\n\n//Sort the lengths\n var sortedLengths = stringLengths.sort(function(a, b) {\t\t\t\t//Array of stringLengths is then sorted into ascending order\n return a - b;\n })\n\n//Find the third greatest\n var thirdGreatestSize = sortedLengths[sortedLengths.length - 3];\t\t//The third greatest string length will be third from the last in the array\n\n//Match the lengths with the original lengths array to find the index\n for (i=0; i < sortedLengths.length; i++) {\t\t\t\t\t\t\t//The loop will then go through the unsorted string lengths array\n\t if (unsortedLengths[i] === thirdGreatestSize) {\t\t\t\t\t//If a match is made with the greatest size then the index of it is stored\n\t var indexOfThird = i;\n\t }\n }\n\n//Use the found index to return the correct word\n return strArr[indexOfThird]\n}",
"function getLongitude(input) {\n // we know input is validated so we know we can go from North/South to the end\n var search = input.search(/[NS]/);\n\n var longitude = \"\";\n if (search == -1) {\n longitude = input.substr(input.search(' '));\n } else {\n longitude = input.substring(search + 1);\n }\n\n return longitude;\n}",
"function longest7SegmentWord(arr) {\n\treturn arr.filter(x => !(/[kmvwx]/.test(x))).sort((a, b) => b.length - a.length)[0] || '';\n}",
"function findStr(str, long){\nvar counter = 0;\nfor(var i = 0; i <= long.length - str.length; i++){\nif(long.slice(i, i + str.length) === str){\n counter++;\n }\n return long.split(str).length\n}\n}",
"function allLongestStrings(inputArray) {\n const sorted = inputArray.sort((a, b) => b.length - a.length);\n return sorted.filter((element) => sorted[0].length === element.length);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clone an element outside the screen to safely get its height, then destroy it. | function getElementHeight (element) {
var clone = element.cloneNode(true)
clone.style.cssText = 'visibility: hidden; display: block; margin: -999px 0'
var height = (element.parentNode.appendChild(clone)).clientHeight
element.parentNode.removeChild(clone)
return height
} | [
"function clone(obj, addInsidePanel, $whereToPut) {\n var $obj = $(obj);\n var $newElement=null;\n \n if ( addInsidePanel ) {\n $newElement=$(\"<div></div>\");\n $newElement.append($(obj.cloneNode(true)));\n } else {\n $newElement=$(obj.cloneNode(true));\n }\n \n $newElement.\n css(\"position\",\"absolute\").\n css(\"top\" ,$obj.offset().top - $obj.scrollTop()).\n css(\"left\" ,$obj.offset().left - $obj.scrollLeft() ).\n css(\"width\" ,$obj.width()).\n css(\"height\",$obj.height());\n\n if ( $whereToPut ) {\n $whereToPut.append($newElement);\n } else if ( $webSiteContainer!=null ) {\n $webSiteContainer.append($newElement);\n }\n\n $obj.hide();\n \n return $newElement;\n }",
"destroyElement() {\n if (this.dom) {\n this.dom.remove();\n }\n }",
"subtract(otherSize) {\n const r = new Size(this.width - otherSize.width, this.height - otherSize.height);\n return r;\n }",
"clone () {\n\n var newBoard = new GameBoard(this.size);\n\n var i,j;\n\n for (i=0; i<this.size; i++) {\n\n for (j=0; j<this.size; j++) {\n\n newBoard.set(this.get(i, j), i, j);\n }\n }\n\n return newBoard;\n }",
"get height() {\n if ( !this.el ) return;\n\n return ~~this.parent.style.height.replace( 'px', '' );\n }",
"copy ()\n {\n return new Rectangle(this.position.copy(), this.width, this.height);\n }",
"setHeight() {\n this.$().outerHeight(this.$(window).height() - this.get('fixedHeight'));\n }",
"detach() {\n const parentNode = this._container.parentNode;\n\n if (parentNode) {\n parentNode.removeChild(this._container);\n\n this._eventBus.fire('propertiesPanel.detach');\n }\n }",
"appendEndingItems(){\n let elementsOnScreen = this.elementsOnScreen();\n // Store a list of the non duplicated elements\n const realElements = Array.from(document.querySelectorAll(`.budgie-item-${this.budgieId}:not(.budgie-item-${this.budgieId}--duplicate)`));\n\n // If the number of elements is greater than the number that fit in the given area\n if(!this.fitsInContainer()){\n // Appends duplicate items equal to the number of elementsOnScreen\n realElements.slice(\n 0,\n elementsOnScreen\n )\n .forEach((element) => {\n let ele = element.cloneNode(true);\n ele.classList.add(`budgie-item-${this.budgieId}--duplicate`);\n ele.classList.add(`budgie-item-${this.budgieId}--duplicate-ending`);\n this.budgieContainer.insertAdjacentElement('beforeend', ele);\n });\n }\n }",
"detach() {\n this.surface = null;\n this.dom = null;\n }",
"function setWindowHeight(element){\n\t$(element).height( getWindowHeight() );\n}",
"function createDragImage(el) {\r\n var clone = deepClone(el);\r\n clone.style.position = 'fixed';\r\n clone.style.margin = '0';\r\n clone.style[\"z-index\"] = '1000';\r\n clone.style.transition = 'opacity 0.2s';\r\n return clone;\r\n}",
"copy() {\n const copy = new Grid(this.size);\n copy.grid = copyBoard(this.grid);\n return copy;\n }",
"destroy() {\n this.viewport.options.divWheel.removeEventListener('wheel', this.wheelFunction);\n }",
"delete() {\n this.deltaX = 0;\n this.deltaY = +5;\n // if bubble currently on the board, remove it\n if (this.row !== undefined && this.col !== undefined) {\n let row = this.board.pieces[this.row];\n let col = this.col;\n row[col] = null;\n }\n this.falling = true;\n this.collided = false;\n this.canvas.objects.push(this);\n }",
"function getBleedHeightInPx() {\n // Creating temporary div with height set in mm and appending it to body\n const tempBleedDiv = document.createElement('div');\n tempBleedDiv.style.height = '8.82mm';\n document.body.appendChild(tempBleedDiv);\n \n // Getting new element's height in px and putting it in a variable\n const bleedHeightInPx = tempBleedDiv.offsetHeight;\n \n // Removing temporary div from the div as we no longer need it\n tempBleedDiv.remove();\n \n // Returning the value in px\n return bleedHeightInPx;\n }",
"function deepClone(el) {\r\n var clone = el.cloneNode(true);\r\n copyStyle(el, clone);\r\n var vSrcElements = el.getElementsByTagName(\"*\");\r\n var vDstElements = clone.getElementsByTagName(\"*\");\r\n for (var i = vSrcElements.length; i--;) {\r\n var vSrcElement = vSrcElements[i];\r\n var vDstElement = vDstElements[i];\r\n copyStyle(vSrcElement, vDstElement);\r\n }\r\n return clone;\r\n}",
"removeTail() {\n let tail = this.snake.dequeue();\n\n this.setTile(tail.x, tail.y, SnakeState.EMPTY);\n\n return {tailX: tail.x, tailY: tail.y};\n }",
"function newGrid (newSize) {\n $('.row').remove();\n createGrid(newSize);\n // $('.column').outerHeight(oldSize*oldPixel/newSize);\n // $('.column').outerWidth(oldSize*oldPixel/newSize);\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if the slider moves, change the differenceThreshold: | function setDifference() {
differenceThreshold = dSlider.value();
} | [
"function changeDelay(value){\n // Inverst slider values. Higher values on slider means lower delay\n value = 5.2 - value;\n if ( value < 1){\n newDelay = -1;\n } else {\n newDelay = Math.pow(value, 4);\n }\n \n // Stop all intervals to change delay\n stopAndClearIntervals()\n\n delay = newDelay;\n\n // Continue any algorithm that was running when the delay slider was touched.\n if ( runningSortingAlgorithm == 0 ) {\n intervalToggleBubbleSort.continue()\n } else if( runningSortingAlgorithm == 1 ) {\n intervalToggleInsertionSort.continue()\n } else if ( runningSortingAlgorithm == 2 ) {\n intervalToggleSelectionSort.continue()\n } else if ( runningSortingAlgorithm == 3 ) {\n intervalToggleMergeSort.continue()\n }\n}",
"function sliderMove()\r\n{\r\n var offset = 0\r\n for (var t = 0; t < sliders.length; t++)\r\n {\r\n var slid = map(sin(angle+offset), -1, 1, 0, 255)\r\n sliders[t].value(slid)\r\n offset += vTest;\r\n } \r\n}",
"function mouseDragged(){\n if(dist(mouseX,mouseY,ball.x,ball.y) <= 1.5*ball.r){\n\tball.drag();\n }\n//use the slider control\n if(dist(mouseX,mouseY,slider.x,slider.y) <= 30){\n \tslider.drag();\n slider.control();\n }\n}",
"through(threshold) {\n\n\t\tlet d = this.value - threshold\n\t\tlet d_old = this.value_old - threshold\n\n\t\treturn d >= 0 && d_old < 0 ? 1 : d <= 0 && d_old > 0 ? -1 : 0\n\n\t}",
"__moveThresholdReached(clientX, clientY) {\n return Math.abs(clientX - this.data.startMouseX) >= this.moveThreshold || Math.abs(clientY - this.data.startMouseY) >= this.moveThreshold;\n }",
"function setDetectorVelocityFn(scope) {\n\tdetector_velocity = scope.detector_velocity_value;\n\tif ( detector_velocity > 0 ) { \n\t\tdetector_speed = (detector_velocity/1200)*3;/** Setting the detector speed based on the slider value */\n\t}\n\telse {\n\t\tdetector_speed = 0;\n\t\tdetector_container.x = detector_container.y = 0;\n\t}\n}",
"function moverDerecha(){\r\n //is para verificar que se cumple un filtro comprobacion//\r\n //si el slider esta siendo animado\r\n if (!slider.is(':animated')) {\r\n slider.animate({\r\n marginLeft : '-142%'\r\n },700, function(){\r\n $('#slider .slide:first').insertAfter('#slider .slide:last');\r\n $('#slider').css('margin-left','-66%');\r\n reiniciarIntervalo();\r\n });\r\n }\r\n }",
"sliderBounce() {\n this.directionX = -this.directionX;\n }",
"upSlider() {\n this.y -= this.sliderSpeed;\n this.y = (this.y < 0 ? 0 : this.y);\n }",
"function getSliderValue() {\n if (!AgeRecalculating) {//todo: weird bug that a second map-move is asked with strange params\n AgeRecalculating = true;\n //get center from map and convert to pix\n slider_lastvalue = slider_value;\n slider_value = 650 - ((timeslider.center.lat + 48.75) / 97.5 * 650);\n getSeqDetails(slider_value, \"closest\");\n \n }\n}",
"_updateHandleAndProgress(newValue) {\n const max = this._effectiveMax;\n const min = this._effectiveMin;\n\n // The progress (completed) percentage of the slider.\n this._progressPercentage = (newValue - min) / (max - min);\n // How many pixels from the left end of the slider will be the placed the affected by the user action handle\n this._handlePositionFromStart = this._progressPercentage * 100;\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\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\t\t\t\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\t\t\n\t\tg_objInner.css(\"left\", currentPosx+\"px\");\n\t\t\n\t}",
"_decreaseX() {\n if (!this._invertedX()) {\n this.valueX = Math.max(this.minX, this.valueX - this.stepX);\n } else {\n this.valueX = Math.max(this.maxX, this.valueX - this.stepX);\n }\n }",
"get threshold() {\n return (0, _Conversions.gainToDb)(this._gt.value);\n }",
"function _rangeSliderEventHandler() {\n const sliderRangeEl = document.querySelector( '#slider-range' );\n const score = sliderRangeEl.textContent;\n track( 'OAH Rate Tool Interactions', 'Score range', score );\n }",
"function changeDelayBetweenSteps() {\n drawing.delay = stepDelaySlider.value;\n updateStepDelaySliderText(drawing.delay);\n}",
"moveSlotSlider(index, newWidth) {\n var left_closet_face_x_value = this.group.getObjectById(this.closet_faces_ids[2]).position.x;\n var rigth_closet_face_x_value = this.group.getObjectById(this.closet_faces_ids[3]).position.x;\n this.selected_slot = this.group.getObjectById(this.closet_slots_faces_ids[index]);\n if (index == 0) {\n let newPosition = left_closet_face_x_value + newWidth;\n this.selected_slot.position.x = newPosition;\n } else {\n var positionLefthSlot = this.group.getObjectById(this.closet_slots_faces_ids[index - 1]).position.x;\n if (positionLefthSlot + newWidth >= rigth_closet_face_x_value) {\n this.selected_slot.position.x = positionLefthSlot;\n } else {\n this.selected_slot.position.x = positionLefthSlot + newWidth;\n }\n }\n }",
"downSlider() {\n this.y += this.sliderSpeed;\n this.y = (this.y >= this.usableHeight ? this.usableHeight : this.y);\n }",
"set smoothness(value) {}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fills the box in the DOM passed as parameter with content | function fillBox (box, content) {
box.html(content);
} | [
"function buildBox() {\n var innerContent = getInnerContent();\n var buttons = '';\n if(curOpt.ok){\n buttons = '<div class=\\'pm-popup-buttons\\'> <button class=\\'button\\'>OK</button></div>';\n }\n var boxHtml = '<div id=\\'pm_'+curOpt.id+'\\' class=\\'pm_popup\\'><div class=\\'pm-popup-inner\\'> '+innerContent + buttons+'</div></div>';\n var thisPopup = $(boxHtml).appendTo('body');\n if (curOpt.ok) {\n //attach events\n thisPopup.find('.button').click(function() {\n $(window).scrollTop(0);\n hide();\n curOpt.ok();\n });\n }\n }",
"function insert_popup() {\n page_content = `<div id=\"enfo_popup\" style=\"background-color: white;\n margin: auto;\n padding: 20px;\n display: none;\n border: 1px solid #888;\n border-radius: 25px;\n width: 30%;\" class=\"modal\"><div class=\"modal-content\" style=\"display:flex; flex-wrap: wrap; border: 2px solid #fff; justify-content: space-evenly;\"><img id=\"enfo_popup_animal_img\" height=\"170px\" width=\"80px\" style=\"padding:8px; flex-grow:1\" src=\"\"></img> <img id=\"enfo_popup_stats_img\" style=\"padding:8px; \" width=\"200px\" height=\"200px\" src=\"\"><p width=\"100px\" height=\"100px\" style=\"padding:8px; flex-grow: 2\" id=\"enfo_popup_text\">placeholder text</p></div></div>`\n page_content = document.body.innerHTML.concat(page_content);\n $(\"body\").html(page_content);\n}",
"function clearContentBox(){\n\t\tcontent.html('');\n\t}",
"function editorNewContent(content, container, activity)\n{\n editorDirty = true;\n activity.contents.push(content);\n addContentElement(content, container, activity);\n}",
"injectTemplate(container, content) {\n container.innerHTML = TEMPLATE;\n const body = container.querySelector('.bitski-dialog-body');\n if (body) {\n body.appendChild(content);\n }\n }",
"function updateDom(box, special, rgb, hex, colorSet, transform) {\n \n // update box background color\n var hexColor = rgbToHexColor(colorSet);\n setBackgroundColor(box, hexColor);\n \n // update color info\n setInnerText(special, transform(colorSet.r) + \" \" + transform(colorSet.g) + \" \" + transform(colorSet.b));\n setInnerText(rgb, colorSet.r + \" \" + colorSet.g + \" \" + colorSet.b);\n setInnerText(hex, hexColor);\n}",
"_updateDomElementContent() {\n const {\n dataId, keyword, source, title, description, urlToImage, formatedDate, link, type,\n } = this._props;\n const {\n cardTitle, cardDate, cardText, cardSource, cardImg, cardKeyword, cardLink,\n } = this._blockElements;\n\n if (type === 'saved') {\n this._domElement.setAttribute('data-saved', true);\n this._domElement.querySelector(cardKeyword).classList.remove(`${cardKeyword.replace('.', '')}_hidden`);\n }\n\n this._domElement.setAttribute('data-id', dataId);\n this._domElement.querySelector(cardTitle).textContent = title;\n this._domElement.querySelector(cardDate).textContent = formatedDate;\n this._domElement.querySelector(cardText).textContent = description;\n this._domElement.querySelector(cardSource).textContent = source;\n this._domElement.querySelector(cardKeyword).textContent = keyword;\n this._domElement.querySelector(cardImg).src = urlToImage;\n this._domElement.querySelector(cardLink).href = link;\n }",
"function attachOnDOM(){\n\tdocument.getElementsByTagName('body')[0].appendChild(getComponent())\n}",
"function addContent(node, content) {\n for (var i = 0, n = content.length; i < n; ++i) {\n node.appendChild(createNode(content[i]));\n }\n }",
"function setHTML(container, content) {\n if (container) {\n // Clear out everything in the container\n while (container.firstChild) {\n container.removeChild(container.firstChild);\n }\n if (content) {\n if (typeof content === 'string') {\n container.innerHTML = content;\n } else {\n container.appendChild(content);\n }\n }\n }\n }",
"function addToDOM(element, someHTML) {\n var div = document.createElement('div');\n div.id = \"b\";\n div.innerHTML = someHTML;\n element.appendChild(div);\n}",
"_buildDOM() {\n const HTML = this.render();\n if (!HTML) { return }\n this.DOMbuilder.build( HTML );\n }",
"fillElements() {\n this.replaceTokens(this.tags, CD.params());\n }",
"function _content(node, content) {\n\t\t//\n\t\tvar contentType = node.nodeType == 1 ? 'innerHTML' : 'data';\n\t\t//\n\t\tif (content) node[contentType] = content;\n\t\t//\n\t\treturn node[contentType];\n\t}",
"function addContent() {\n content.style.visibility = \"visible\";\n}",
"setHtml(element, html){\n element.html(html);\n }",
"function makeCard(id, data)\n{\n $(\"#\" + id).text(data[0]);\n}",
"function addPicnikboxMarkup() {\n\tvar bod = document.getElementsByTagName('body')[0];\n\tvar overlay = document.createElement('div');\n\toverlay.id = 'overlay';\n\tvar pbox = document.createElement('div');\n\tpbox.id = 'picnikbox';\n\tbod.appendChild(overlay);\n\tbod.appendChild(pbox);\n}",
"write(text) {\n this.element.appendChild(document.createElement(\"div\")).textContent = text\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an issue to the chosen issues list and refresh it. | function add_and_refresh(sel) {
return chosen_issues.add_and_refresh(sel);
} | [
"function saveIssue(e) \r\n{\r\n var issueDesc = document.getElementById('issueDescInput').value;\r\n var issueSeverity = document.getElementById('issueSeverityInput').value;\r\n var issueAssignedTo = document.getElementById('issueAssignedToInput').value;\r\n var issueId = chance.guid();\r\n var issueStatus = 'UnSolved';\r\n var issue = {\r\n id: issueId,\r\n description: issueDesc,\r\n severity: issueSeverity,\r\n assignedTo: issueAssignedTo,\r\n status: issueStatus\r\n }\r\n\r\n // if there is no issue description push the issue with no content\r\n if(localStorage.getItem('issues') == null) \r\n {\r\n var issues = [];\r\n issues.push(issue);\r\n localStorage.setItem('issues', JSON.stringify(issues));\r\n } \r\n\r\n // if issue is fully described put the issue along with the contents mentioned\r\n else \r\n {\r\n var issues = JSON.parse(localStorage.getItem('issues'));\r\n issues.push(issue);\r\n localStorage.setItem('issues', JSON.stringify(issues));\r\n }\r\n\r\n // reset the form eachtime after adding an issue to make space to add new issue\r\n document.getElementById('issueInputForm').reset();\r\n fetchIssues();\r\n e.preventDefault();\r\n}",
"function drop_issue(n) {\n chosen_issues.remove(n);\n refresh_chosen_issues($(\"#chosenissues\"));\n var link = $(\"#addissueprompt\");\n link.fadeIn();\n $(\"#addissue\").fadeOut();\n refresh_issues_select($(\"#newissue\"));\n}",
"function getIssues() {\n TestService.getTestCaseWorkItemsByType(test.id, 'BUG').\n then(function(rs) {\n if (rs.success) {\n vm.issues = rs.data;\n if (test.workItems.length && vm.attachedIssue) {\n angular.copy(vm.attachedIssue, vm.newIssue);\n }\n } else {\n messageService.error(rs.message);\n }\n });\n }",
"function initIssues() {\n\t//ids start at 5 so fill in 0-4 to make retrieval bawed on array index trivial\n\tissues = [0, 0, 0, 0, 0,\n {id:5,\tname:\"Alumni\"},\n\t\t\t{id:6,\tname:\"Animals\"},\n\t\t\t{id:7,\tname:\"Children\"},\n\t\t\t{id:8,\tname:\"Disabilities\"},\n\t\t\t{id:9,\tname:\"Disasters\"},\n\t\t\t{id:10,\tname:\"Education\"},\n\t\t\t{id:11,\tname:\"Elderly\"},\n\t\t\t{id:12,\tname:\"Environment\"},\n\t\t\t{id:13,\tname:\"Female Issues\"},\n\t\t\t{id:14, name:\"Fine Arts\"},\n\t\t\t{id:15,\tname:\"General Service\"},\n\t\t\t{id:16,\tname:\"Health\"},\n\t\t\t{id:17,\tname:\"Male Issues\"},\n\t\t\t{id:18, name:\"Minority Issues\"},\n\t\t\t{id:19,\tname:\"Office\"},\n\t\t\t{id:20,\tname:\"Patriotic\"},\n\t\t\t{id:21,\tname:\"Poverty\"},\n\t\t\t{id:22,\tname:\"PR\"},\n\t\t\t{id:23,\tname:\"Recreation\"},\n\t\t\t{id:24,\tname:\"Religious\"},\n\t\t\t{id:25,\tname:\"Service Leaders\"},\n\t\t\t{id:26,\tname:\"Technology\"}\n\t\t\t];\n}",
"function editIssue(obj) {\n // Creates a form for editied issue\n var form = document.createElement(\"form\");\n form.setAttribute(\"id\",\"listAll\");\n\n // ID of issue\n var id = document.createElement(\"p\");\n id.innerHTML = \"<b>ID:</b>\" + obj[\"ID\"];\n\n // Title box\n var tit = document.createElement(\"input\");\n tit.setAttribute('type',\"text\");\n tit.setAttribute('name',\"Title\");\n tit.setAttribute('id', \"title\");\n tit.value = obj[\"title\"];\n var tlabel = document.createElement(\"Label\");\n tlabel.htmlFor = \"text\";\n tlabel.innerHTML = \"<b>Title:</b>\";\n\n // Status option\n var stat = document.createElement(\"select\");\n stat.setAttribute('id', \"status\");\n // Adds New option\n var op = new Option();\n op.value = \"New\";\n op.text = \"New\";\n stat.options.add(op);\n // Adds Assigned option\n var op = new Option();\n op.value = \"Assigned\";\n op.text = \"Assigned\";\n stat.options.add(op);\n // Adds fixed option\n var op = new Option();\n op.value = \"Fixed\";\n op.text = \"Fixed\";\n stat.options.add(op);\n // Adds won't fix option\n var op = new Option();\n op.value = \"Won't Fix\";\n op.text = \"Won't Fix\";\n stat.options.add(op);\n stat.value = obj[\"status\"];\n var slabel = document.createElement(\"Label\");\n slabel.htmlFor = \"text\";\n slabel.innerHTML = \"<b>Status:</b>\";\n\n // Description Box\n var des = document.createElement(\"TEXTAREA\");\n des.setAttribute('type',\"text\");\n des.setAttribute('name',\"Description\");\n des.setAttribute('rows', \"5\");\n des.setAttribute('cols', \"50\");\n des.setAttribute('id', \"msg\");\n des.value = obj[\"description\"];\n var dlabel = document.createElement(\"Label\");\n dlabel.htmlFor = \"text\";\n dlabel.innerHTML = \"<b>Description:</b>\";\n\n // OS option\n var os = document.createElement(\"select\");\n os.setAttribute('id', \"OS\");\n // Adds Windows option\n var oop = new Option();\n oop.value = \"Windows\";\n oop.text = \"Windows\";\n os.options.add(oop);\n // Adds Linux option\n var oop = new Option();\n oop.value = \"Linux\";\n oop.text = \"Linux\";\n os.options.add(oop);\n // Adds Mac option\n var oop = new Option();\n oop.value = \"Mac\";\n oop.text = \"Mac\";\n os.options.add(oop);\n os.value = obj[\"os\"];\n var olabel = document.createElement(\"Label\");\n olabel.htmlFor = \"text\";\n olabel.innerHTML = \"<br><b>OS:</b>\";\n\n // Priority option\n var prio = document.createElement(\"select\");\n prio.setAttribute('id', \"priority\");\n // Adds Low option\n var pop = new Option();\n pop.value = \"Low\";\n pop.text = \"Low\";\n prio.options.add(pop);\n // Adds Medium option\n var pop = new Option();\n pop.value = \"Medium\";\n pop.text = \"Medium\";\n prio.options.add(pop);\n // Adds High option\n var pop = new Option();\n pop.value = \"High\";\n pop.text = \"High\";\n prio.options.add(pop);\n // Adds Very High option\n var pop = new Option();\n pop.value = \"Very High\";\n pop.text = \"Very High\";\n prio.options.add(pop);\n // Adds World Ending option\n var pop = new Option();\n pop.value = \"World Ending\";\n pop.text = \"World Ending\";\n prio.options.add(pop);\n prio.value = obj[\"priority\"];\n var plabel = document.createElement(\"Label\");\n plabel.htmlFor = \"text\";\n plabel.innerHTML = \"<br><b>Priority:</b>\";\n\n // Component box\n var com = document.createElement(\"input\");\n com.setAttribute('type',\"text\");\n com.setAttribute('name',\"Com\");\n com.setAttribute('id',\"component\");\n com.value = obj[\"component\"];\n var clabel = document.createElement(\"Label\");\n clabel.htmlFor = \"text\";\n clabel.innerHTML = \"<br><b>Component:</b>\";\n\n // Assignee box\n var ass = document.createElement(\"select\");\n // Adds all users as possible ass\n for(var i in users) {\n var x = new Option();\n x.value = users[i][\"name\"];\n x.text = x.value;\n ass.add(x);\n }\n var alabel = document.createElement(\"Label\");\n alabel.htmlFor = \"text\";\n alabel.innerHTML = \"<br><b>Assignee:</b>\";\n\n // Submit button\n var but = document.createElement(\"button\");\n but.innerHTML = \"Submit\";\n but.onclick = function() {\n // Url issue is sent to\n const url = 'http://localhost:1234/whap/issues?id=' + obj[\"ID\"];\n // Packs all the info into an object\n var data = {\n name: tit.value,\n id: obj[\"ID\"],\n status: stat.value,\n des: des.value,\n prio: prio.value,\n os: os.value,\n com: com.value,\n ass: ass.value\n }\n // Yeets the data to the server\n putData(url,data)\n // Tells users they did it\n .then(alert(\"You edited it!\"));\n };\n\n // Delete button\n var del = document.createElement(\"button\");\n del.innerHTML = \"<b>DELETE</b>\";\n del.onclick = function() {\n alert(\"Are you sure you want to delete this issue?\\n\" +\n \"Just kidding, it's too late, it's fucking gone.\");\n deleteIssue(obj[\"ID\"]);\n }\n\n // <p> for styling\n var para = document.createElement(\"p\");\n\n // Adds everything to the screen\n form.appendChild(id);\n form.appendChild(tlabel);\n form.appendChild(tit);\n form.appendChild(dlabel);\n form.appendChild(des);\n form.appendChild(clabel);\n form.appendChild(com);\n form.appendChild(alabel);\n form.appendChild(ass);\n form.appendChild(para);\n form.appendChild(slabel);\n form.appendChild(stat);\n form.appendChild(plabel);\n form.appendChild(prio);\n form.appendChild(olabel);\n form.appendChild(os);\n form.appendChild(but);\n form.appendChild(del);\n document.body.appendChild(form);\n}",
"setIssue(issue) {\n this.issue = issue;\n }",
"function updateIssue() {\n const usId = document.getElementById(\"modal-id\").value.substring(5);\n const nom = document.getElementById(\"modal-nom\").value;\n const description = document.getElementById(\"modal-description\").value;\n const priority = document.getElementById(\"modal-priority\").value;\n const difficulty = document.getElementById(\"modal-difficulty\").value;\n\n let jsonData = {\n \"name\": nom,\n \"description\": description,\n \"priority\": priority,\n \"difficulty\": difficulty\n }\n\n sendAjax(\"/api/issue/\" + usId, 'PUT', JSON.stringify(jsonData)).then(() => {\n document.getElementById(\"issue\" + usId + \"-name\").innerHTML = \"<h4><strong>\" + nom + \"</strong></h4>\";\n document.getElementById(\"issue\" + usId + \"-description\").innerHTML = description;\n document.getElementById(\"issue\" + usId + \"-priority-btn\").value = priority;\n document.getElementById(\"issue\" + usId + \"-priority\").innerHTML = \"<h6>Priorité :\" +\n \"<span class=\\\"label label-default\\\">\" + priority + \" </span>\" +\n \"</h6>\";\n document.getElementById(\"issue\" + usId + \"-difficulty-btn\").value = difficulty;\n document.getElementById(\"issue\" + usId + \"-difficulty\").innerHTML = \"<h6>Difficulté :\" +\n \"<span class=\\\"label label-default\\\">\" + difficulty + \" </span>\" +\n \"</h6>\";\n $(\"#modal\").modal(\"hide\");\n })\n .catch(() => {\n $(\".err-msg\").fadeIn();\n $(\".spinner-border\").fadeOut();\n })\n}",
"_onIssueClicked(params) {\n const prefix = commentTypeToIDPrefix[params.commentType];\n const selector = `#${prefix}comment${params.commentID}`;\n\n this._entryViews.forEach(entryView => {\n if (entryView.$el.find(selector).length > 0) {\n entryView.expand();\n }\n });\n\n RB.navigateTo(params.commentURL);\n }",
"function _createIssue() {\n if (currentRepo && currentRepo.repo) {\n var dialog = Dialogs.showModalDialogUsingTemplate(\n Mustache.render(IssueDialogNewTPL, currentRepo)\n );\n \n var submitClass = \"gh-create\",\n cancelClass = \"gh-cancel\",\n $dialogBody = dialog.getElement().find(\".modal-body\"),\n $title = $dialogBody.find(\".gh-issue-title\").focus(),\n $message = $dialogBody.find(\".comment-body\"),\n $preview = $dialogBody.find(\".comment-preview\");\n \n $dialogBody.find('a[data-action=\"preview\"]').on(\"shown\", function (event) {\n $preview.html(marked($message.val()));\n });\n \n $dialogBody.delegate(\".btn\", \"click\", function (event) {\n var $btn = $(event.currentTarget);\n \n if ($btn.hasClass(cancelClass)) {\n dialog.close();\n } else if ($btn.hasClass(submitClass)) {\n $dialogBody.toggleClass(\"loading\");\n \n gh.newIssue($title.val(), $message.val()).done(function (issue) {\n if (issue && issue.html_url) {\n dialog.close();\n _viewIssue(issue);\n } else {\n $dialogBody.toggleClass(\"error loading\");\n }\n });\n }\n });\n } else {\n Dialogs.showModalDialogUsingTemplate(_renderTPL(ErrorProjectNotFoundTPL));\n }\n }",
"function searchIssue(issue) {\n vm.isIssueFound = false;\n TestService.getJiraTicket(issue.jiraId).then(function(rs) {\n if (rs.success) {\n var searchResultIssue = rs.data;\n vm.isIssueFound = true;\n if (searchResultIssue === '') {\n vm.isIssueClosed = false;\n vm.issueJiraIdExists = false;\n vm.issueTabDisabled = false;\n return;\n }\n vm.issueJiraIdExists = true;\n vm.isIssueClosed = vm.closedStatusName.toUpperCase() ===\n searchResultIssue.status.toUpperCase();\n vm.newIssue.description = searchResultIssue.summary;\n vm.newIssue.assignee = searchResultIssue.assigneeName || '';\n vm.newIssue.reporter = searchResultIssue.reporterName || '';\n vm.newIssue.status = searchResultIssue.status.toUpperCase();\n vm.isNewIssue = vm.newIssue.jiraId !== vm.attachedIssue.jiraId;\n vm.issueTabDisabled = false;\n }\n });\n }",
"function _resetIssuesUI() {\n var $noIssues = $issuesWrapper.find(\".no-issues\"),\n $noGithub = $issuesWrapper.find(\".no-github\"),\n $errors = $issuesWrapper.find(\".errors\"),\n $state = $issuesPanel.find(\".issue-state\"),\n $assignee = $issuesPanel.find(\".issue-assignee\");\n \n $issuesWrapper.removeClass(\"loading\");\n $noIssues.addClass(\"hide\");\n $noGithub.addClass(\"hide\");\n $errors.addClass(\"hide\");\n $state.addClass(\"disabled\");\n $assignee.addClass(\"disabled\");\n \n $issuesList.empty();\n }",
"async function createRepositoryIssues({ issues }) {\n const issuesHTML = HtmlBuilder.div()\n .addClass('repository-detail__issues mb-3 border p-3')\n let issueDetailHTML = createIssueDetail({ issue: undefined })\n\n if (!issues || issues.length <= 0) {\n return issuesHTML.append(HtmlBuilder.div(\"Não há issues\"))\n }\n\n async function fetchAndFillIssueDetail({ issue }) {\n const { comments_url } = issue\n const issueComments = await _gitHubService.fetchIssueComments(comments_url)\n issueDetailHTML.html(createIssueDetail({ issue, issueComments }))\n moveToPageElemnt(\"#issue-detail\")\n }\n\n const issuesTableHTML = HtmlBuilder.table(\"\")\n .addClass('table table-striped border')\n .attr('id', 'issues-table')\n const theadHTML = HtmlBuilder.thead(\"\")\n .append(HtmlBuilder.tr()\n .append(HtmlBuilder.th(\"Nome\"))\n .append(HtmlBuilder.th(\"Status\").attr(DataTableConsts.DATATABLE_SELECT_FILTER_COLUMN, DataTableConsts.DATATABLE_SELECT_FILTER_COLUMN))\n .append(HtmlBuilder.th(\"Detalhes\")))\n const tbodyHTML = HtmlBuilder.tbody(\"\")\n\n for (issue of issues) {\n const issueWithoutCache = issue\n const { title, state } = issueWithoutCache\n\n function onOpenIssueDetail() { fetchAndFillIssueDetail({ issue: issueWithoutCache }) }\n\n const trHTML = HtmlBuilder.tr(\"\")\n .append(HtmlBuilder.td(`${title}`))\n .append(HtmlBuilder.td(`${state}`))\n .append(HtmlBuilder.td(HtmlBuilder.button(\"Mais\")\n .addClass('btn btn-primary')\n .click(onOpenIssueDetail)))\n\n tbodyHTML.append(trHTML)\n }\n\n issuesTableHTML.append(theadHTML).append(tbodyHTML)\n issuesHTML\n .append(HtmlBuilder.h3(\"Issues\"))\n .append(issuesTableHTML)\n .append(HtmlBuilder.hr())\n .append(issueDetailHTML)\n\n _dataTableFactory.of(issuesTableHTML)\n\n return issuesHTML\n }",
"function renderIssues(issues) {\n data = JSON.parse(issues);\n\n read_name = \"<h2>Issue Name: \" + data.issues[issueId].name + \"</h2>\";\n document.getElementById(\"issue-name\").innerHTML = read_name;\n\n read_type = \"<h2>Issue Type: \" + data.issues[issueId].type + \"</h2>\";\n document.getElementById(\"issue-type\").innerHTML = read_type;\n\n read_time = \"<h2>Issue occurred date: <time>\" + data.issues[issueId].datetime + \"</time></h2>\";\n document.getElementById(\"issue-date\").innerHTML = read_time;\n\n read_description = \"<h2>Issue Description: </h2> <p>\" + data.issues[issueId].description + \"/<p>\";\n document.getElementById(\"issue-description\").innerHTML = read_description;\n }",
"function show_issues(){\r\n\t\t\tvar xhttp = new XMLHttpRequest();\r\n\t\t\txhttp.onreadystatechange = function(){\r\n\t\t\t\tif(this.readyState == 4 && this.status == 200){\r\n\t\t\t\t\tdocument.getElementById('issues').innerHTML = this.responseText;\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\txhttp.open(\"POST\", \"getissues.php\", true);\r\n\t\t\txhttp.send();\r\n}",
"function updateUIFromIssueColl() {\n\n // Clear the values before populating them\n var empty= \"\";\n $(\"#IURIs\").val(empty);\n $(\"#IURIs\").attr(\"title\", empty);\n $(\"#IEvidence\").val(empty);\n $(\"#IEvidence\").attr(\"title\", empty);\n $(\"#IScreenshots\").val(empty);\n $(\"#INotes\").val(empty);\n $(\"#INotes\").attr(\"title\", empty);\n $(\"#IPriority\").val(empty); \n \n\n // Get Test ID as search criteria\n tid = $( \"#testSel option:selected\" ).val();\n if ((tid === undefined) || (tid === \"\")){\n console.log(\"Empty Test ID\");\n return;\n }\n \n // Get the project name\n var prjName = Session.get(\"projectName\");\n\n // Build search criteria\n var crit={}; var kvp1 = {}; var kvp2 = {};\n kvp1.TID = tid;\n kvp2.PrjName = prjName;\n crit[\"$and\"] = [kvp1, kvp2];\n var i = issueColl.findOne(crit);\n if ((i === undefined) || (i._id <= 0)){\n console.log(\"No issue data found for this Test ID: \" + tid);\n return;\n }\n\n // Update UI values\n $(\"#IURIs\").val(i.IURIs);\n $(\"#IURIs\").attr(\"title\", i.IURIs);\n $(\"#IEvidence\").val(i.IEvidence);\n $(\"#IEvidence\").attr(\"title\", i.IEvidence);\n $(\"#IScreenshots\").val(i.IScreenshots);\n $(\"#INotes\").val(i.INotes);\n $(\"#INotes\").attr(\"title\", i.INotes);\n $(\"#IPriority\").val(i.IPriority); \n updateScreenshots();\n updateCweUI(i.CweId);\n}",
"function assignIssue(issue, keyWord) {\n if (!issue.testCaseId) {\n issue.testCaseId = test.testCaseId;\n }\n issue.type = 'BUG';\n TestService.createTestWorkItem(test.id, issue)\n .then((rs) => {\n const workItemType = issue.type;\n const jiraId = issue.jiraId;\n let message;\n\n if (rs.success) {\n var messageWord;\n switch (keyWord) {\n case 'SAVE':\n messageWord = issue.id ? 'updated' : 'created';\n break;\n case 'LINK':\n messageWord = 'linked';\n break;\n }\n message = generateActionResultMessage(workItemType, jiraId, messageWord, true);\n vm.newIssue = angular.copy(rs.data);\n updateWorkItemList(rs.data);\n vm.initIssueSearch(false);\n initAttachedWorkItems();\n vm.isNewIssue = jiraId !== vm.attachedIssue.jiraId;\n messageService.success(message);\n } else {\n if (vm.isNewIssue) {\n message = generateActionResultMessage(workItemType,\n jiraId, 'assign', false);\n } else {\n message = generateActionResultMessage(workItemType,\n jiraId, 'update', false);\n }\n messageService.error(message);\n }\n });\n }",
"async postIssue() {\n if (!this.API || !this.options || this.issue || this.issueId)\n return;\n // login to create issue\n if (!this.isLogined) {\n this.login();\n }\n // only owner/admins can create issue\n // if (!this.isAdmin) return\n try {\n this.isCreatingIssue = true;\n const issue = await this.API.postIssue({\n title: this.issueTitle,\n content: await this.options.issueContent({\n options: this.options,\n url: getCleanURL(window.location.href),\n }),\n accessToken: this.accessToken,\n });\n const issueR = await this.API.postIssue({\n title: this.issueTitleR,\n content: await this.options.issueContent({\n options: this.options,\n url: getCleanURL(window.location.href),\n }),\n accessToken: this.accessToken,\n });\n this.issue = issue;\n this.issueR = issueR;\n this.isIssueNotCreated = false;\n await this.getComments();\n await this.getRatings();\n await this.getTotalRating();\n await this.getUserRating();\n }\n catch (e) {\n this.isFailed = true;\n }\n finally {\n this.isCreatingIssue = false;\n }\n }",
"function TKR_openIssueUpdateForm() {\n TKR_showHidden($('makechangesarea'));\n TKR_goToAnchor('makechanges');\n TKR_forceProperTableWidth();\n window.setTimeout(\n function () { document.getElementById('addCommentTextArea').focus(); },\n 100);\n}",
"function addToDo(newToDo) {\r\ntoDos.push(newToDo);\r\ndisplayToDos();\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adjust the scroll position to account for sticky header, only if the hash matches an id. This does not handle tags. Some CSS fixes those, but only for reference docs. | function offsetScrollForSticky() {
// Ignore if there's no search bar (some special pages have no header)
if ($("#search-container").length < 1) return;
var hash = escape(location.hash.substr(1));
var $matchingElement = $("#"+hash);
// Sanity check that there's an element with that ID on the page
if ($matchingElement.length) {
// If the position of the target element is near the top of the page (<20px, where we expect it
// to be because we need to move it down 60px to become in view), then move it down 60px
if (Math.abs($matchingElement.offset().top - $(window).scrollTop()) < 20) {
$(window).scrollTop($(window).scrollTop() - 60);
}
}
} | [
"function scrollToHash() {\n if (window.location.hash) {\n ZUI.scrollFromHash(window.location.hash);\n }\n }",
"function Scroll() {\n if (window.pageYOffset > sticky) {\n header.classList.add(\"sticky\");\n \n } else {\n header.classList.remove(\"sticky\");\n }\n}",
"function BAScrollToFragmentIDTarget() {\n\tif (BAAlreadyApplied(arguments.callee)) return;\n\tif (!BA.ua.isSafari || !BA.css.revise.Safari) return;\n\n\tvar target = location.hash || '';\n\t target = target.split('#')[1] || '';\n\t target = document.getElementById(target) || null;\n\tif (target) {\n\t\twindow.scrollTo(0, target.getAbsoluteOffsetBA().Y);\n\t}\n}",
"function icinga_reload_scroll_position() {\n\t/* save current scrolling position */\n\tscroll_pos = icinga_get_scroll_position();\n\n\t/* if scroll position is zero, remove it from the url and reload\n\t if scroll position is NOT zero, add/update scroll option and reload */\n\twindow.location.href = icinga_update_url_option(window.location.href, \"scroll\", (scroll_pos <= 0) ? null : scroll_pos);\n}",
"function setupAutoScroll() {\n $('.header--course-and-subject').append('<div id=\"startScroll\"></div>');\n startScroll = $('#startScroll').offset().top;\n window.addEventListener('scroll', function sidebarScroll() {\n // This value is your scroll distance from the top\n var distanceFromTop = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;\n var sidebar = document.querySelector('.layout-sidebar__side__inner');\n // stop scrolling, reached upper bound\n if (distanceFromTop < startScroll) {\n sidebar.style.position = 'absolute';\n sidebar.style.top = '';\n } else if (distanceFromTop >= startScroll) {\n // make div follow user\n sidebar.style.position = 'fixed';\n sidebar.style.top = '100px';\n }\n });\n}",
"function initSmoothScroll () {\n var scroll = new SmoothScroll();\n\n var smoothScrollWithoutHash = function (selector, settings) {\n \tvar clickHandler = function (event) {\n \t\tvar toggle = event.target.closest( selector );\n\n \t\tif ( !toggle || toggle.tagName.toLowerCase() !== \"a\" || toggle.hash.length === 0 ) return;\n \t\tvar anchor = document.querySelector( toggle.hash );\n \t\tif ( !anchor ) return;\n\n \t\tevent.preventDefault();\n \t\tscroll.animateScroll( anchor, toggle, settings || {} );\n \t};\n\n \twindow.addEventListener('click', clickHandler, false );\n };\n\n smoothScrollWithoutHash( \"a[href*='#']\", {\n offset: 75\n } );\n}",
"function highlightHashTarget() {\n\t\tif (!location.hash) return;\n\n\t\ttry {\n\t\t\tvar target = document.querySelector(location.hash)\n\t\t\tif(target) {\n\t\t\t\ttarget.scrollIntoView({\n\t\t\t\t\tblock: \"start\"\n\t\t\t\t})\n\t\t\t\tsetHeaderActive(target)\n\t\t\t\tvar tocItem = document.querySelector('.toc a[data-target=\"'+location.hash+'\"]');\n\t\t\t\tif(tocItem) setTOCActive(tocItem)\n\t\t\t}\n\t\t}\n\t\tcatch(e) {}\n\t}",
"function setHeaderPositonForDiv()\r\n{\r\n var ctHeader;\r\n if(!IE)\r\n {\r\n ctHeader = getElemnt(\"changeTrackingHeader\");\r\n if(ctHeader)\r\n {\r\n ctHeader.style.position = \"relative\";\r\n }\r\n }\r\n}",
"function OneWordHelper_scrollTo(wordID, fromText) {\n wordID = parseInt(wordID)\n\n // Set the proper \"main\" highlights.\n if(!this.phraseLength) { // we have just one word\n if(this.selectedID) // set regular highlight\n utl.id(\"w-\"+this.selectedID).className = \"highlight\"\n utl.id(\"w-\"+wordID).className = \"highlight hl-main\"\n }\n else { // for multi-word phrases\n if(this.selectedID)\n for(var i = 0; i < this.phraseLength; i++)\n utl.id(\"w-\"+(this.selectedID+i)).className = \"hl-phrase\"\n for(var i = 0; i < this.phraseLength; i++)\n utl.id(\"w-\"+(wordID+i)).className = \"hl-phrase hl-main\"\n }\n this.selectedID = wordID\n\n if(!fromText) {\n var height = window.innerHeight || screen.availHeight\n var wordLoc = utl.id('w-'+wordID).offsetTop\n window.scroll(0, wordLoc - 0.35 * height)\n\n this.showBar(wordID)\n }\n} // _scrollTo function",
"function scrollToPost(id) {\n document.getElementById(id).scrollIntoView(true);\n}",
"function getScrollId() {\n const linkTop = $(this).offset().top;\n const sectionHeight = $(this).height();\n // 2nd check is to unselect the last item if we keep\n // scrolling past it. Give it leeway of 125 to account for padding\n if (linkTop < fromTop && fromTop < (linkTop + sectionHeight + 100)) {\n return this;\n }\n return 0;\n }",
"setupScrollSync () {\n const headerMiddleSelector = this.get('_headerMiddleSelector')\n const bodyLeftSelector = this.get('_bodyLeftSelector')\n const bodyMiddleSelector = this.get('_bodyMiddleSelector')\n const bodyRightSelector = this.get('_bodyRightSelector')\n\n this.syncScrollLeft(headerMiddleSelector, bodyMiddleSelector)\n this.syncScrollLeft(bodyMiddleSelector, headerMiddleSelector)\n\n this.syncScrollTop(bodyLeftSelector, bodyMiddleSelector, bodyRightSelector)\n this.syncScrollTop(bodyMiddleSelector, bodyLeftSelector, bodyRightSelector)\n this.syncScrollTop(bodyRightSelector, bodyLeftSelector, bodyMiddleSelector)\n }",
"applyFixedHeader() {\n if ( $('body').hasClass('allow-fixed-header') ) {\n if ($(window).scrollTop() > 0) {\n $('body').addClass('fixed-header');\n } else {\n $('body').removeClass('fixed-header');\n $('.has-submenu.active').removeClass('show-submenu');\n }\n }\n }",
"function highlightCurrent() {\n obj = document.location.hash.match(/comment_item_(\\d+)/);\n if (obj) {\n $('comment_item_'+obj[1]).addClassName('js_highlighted');\n // The above should be enough to dynamicall define CSS styles, but it's not working, so...\n $$('.js_highlighted .comment_header')[0].style.backgroundColor = '#FDF1C6';\n $('comment_item_'+obj[1]).scrollTo();\n }\n}",
"setScrollOffset() {\n const {\n isMainPageSearch,\n itemHeight,\n } = this.props;\n const { offset } = this.state;\n\n // $list is populated via the ref in the render method below\n if (this.$list) {\n this.$list.scrollTop = isMainPageSearch ? 0 : offset * itemHeight;\n }\n }",
"handleWindowScroll() {\n const sectionHTMLElement = this.sectionHTMLElement.current;\n const { top } = sectionHTMLElement.getBoundingClientRect();\n\n const shouldUpdateForScroll = Section.insideScrollRangeForUpdates.call(this, top);\n if ( shouldUpdateForScroll ) {\n\n this.updateParallaxForScrollPosition(top);\n }\n }",
"function i2uiSyncdScroll(mastertableid, slavetableid)\r\n{\r\n var masterscrolleritem;\r\n var slavescrolleritem;\r\n\r\n if (slavetableid == null)\r\n {\r\n // keep header and data of same table scrolled to same position\r\n masterscrolleritem = document.getElementById(mastertableid+\"_scroller\");\r\n slavescrolleritem = document.getElementById(mastertableid+\"_header_scroller\");\r\n if (slavescrolleritem != null &&\r\n masterscrolleritem != null)\r\n {\r\n slavescrolleritem.scrollTop = masterscrolleritem.scrollTop;\r\n slavescrolleritem.scrollLeft = masterscrolleritem.scrollLeft;\r\n }\r\n }\r\n else\r\n {\r\n // keep data in different tables scrolled to same position\r\n masterscrolleritem = document.getElementById(mastertableid+\"_scroller\");\r\n slavescrolleritem = document.getElementById(slavetableid+\"_scroller\");\r\n if (slavescrolleritem != null &&\r\n masterscrolleritem != null)\r\n {\r\n slavescrolleritem.scrollTop = masterscrolleritem.scrollTop;\r\n }\r\n }\r\n}",
"function updateScroll() {\n\t\tlet elements = container.getElementsByClassName('selected');\n\t\tif (elements.length > 0) {\n\t\t\tlet element = elements[0];\n\t\t\t// make group visible\n\t\t\tlet previous = element.previousElementSibling;\n\t\t\tif (previous && previous.className.indexOf('group') !== -1 && !previous.previousElementSibling) {\n\t\t\t\telement = previous;\n\t\t\t}\n\t\t\tif (element.offsetTop < container.scrollTop) {\n\t\t\t\tcontainer.scrollTop = element.offsetTop;\n\t\t\t} else {\n\t\t\t\tlet selectBottom = element.offsetTop + element.offsetHeight;\n\t\t\t\tlet containerBottom = container.scrollTop + container.offsetHeight;\n\t\t\t\tif (selectBottom > containerBottom) {\n\t\t\t\t\tcontainer.scrollTop += selectBottom - containerBottom;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"function gotoFragment (document) {\n\t\tdocument.getElementById(location.hash.substr(1)).scrollIntoView(true)\n\t\tremoveListener(gotoFragment)\n\t} // gotoFragment (document)"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pyramid. 7 points. Write a function that draws a block pyramid, where the user specifies the side length of each block. By default, we'll draw a pyramid with a base of five blocks. Give the leftmost point of the pyramid an Xcoordinates of 10. Give the bottom of the pyramid a Ycoordinate of 10 less than the height of the canvas. You'll need to use the appropriate Canvas API methods to do this. If you're unsure what your code should do, click the "Example" button to see. When you click the "Pyramid" button, your output should match that of the example. Certain values, such as lengths that are logically too small or practically too large, should be prohibited. Check the example to see what your code should do in these instances. | function drawPyramid() {
const canvas = document.getElementById("canvas8");
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
let blockLength = prompt("Length:");
blockLength = Number(blockLength);
if(blockLength*5+10 > canvas.width || blockLength*5+10 > canvas.height){
alert("The pyramid will not fit on the canvas")
}else if(isNaN(blockLength)==true){
alert("Your input is not a number");
}else{
let x = 10;
let y = canvas.height - 10 - blockLength;
for(let i = 0; i<5; i++){
context.strokeStyle="black";
context.strokeRect(x, y, blockLength, blockLength);
x += blockLength;
}
x = 10;
y -= blockLength;
for(i=0; i<4; i++){
context.strokeStyle="black";
context.strokeRect(x+(.5*blockLength), y, blockLength, blockLength);
x+= blockLength;
}
x = 10;
y -= blockLength;
for(i=0; i<3; i++){
context.strokeStyle="black";
context.strokeRect(x+blockLength, y, blockLength, blockLength);
x+=blockLength;
}
x=10;
y -= blockLength;
for(i=0; i<2; i++){
context.strokeStyle="black";
context.strokeRect(x+1.5*blockLength, y, blockLength, blockLength);
x+=blockLength;
}
x=10;
y-=blockLength;
context.strokeStyle="black";
context.strokeRect(x+2*blockLength, y, blockLength, blockLength);
}
} | [
"function drawConsolePyramid(height) {\n console.log(\" \".repeat(height) + \"*\");\n for (let i = 1; i < height; i++) {\n\n console.log(\" \".repeat(height - i) + \"*\".repeat(i) + \"*\".repeat(i) + \" \".repeat(height - i));\n }\n}",
"function printPyramid(height) {\n for ( var row = 1; row <= height; row++){\n var space = \"\";\n var hash = \"\";\n var space_count = height - row;\n var hash_count = height - space_count;\n for (var i = space_count; i > 0; i--)\n space += \" \";\n for (var j = 0; j <= hash_count; j++)\n hash += \"#\"\n console.log(space, hash);\n }\n}",
"function drawDiamond(lineCount) {\n var middleP, fullStatsArr;\n var starsArr = Array(lineCount).fill(0).map((u, i) => { return i + 1; });\n if (lineCount % 2 == 0) {\n middleP = lineCount / 2;\n fullStatsArr = starsArr.slice(0, middleP).concat(starsArr.slice(0, middleP).reverse());\n } else {\n middleP = Math.round(lineCount / 2);\n fullStatsArr = starsArr.slice(0, middleP).concat(starsArr.slice(0, middleP - 1).reverse());\n }\n // console.log(starsArr);\n var result = fullStatsArr.reduce((p, c) => {\n p = p + ' '.repeat(lineCount - c) + '*'.repeat(c + c - 1) + '\\n';\n return p;\n }, \"\");\n console.log(result);\n}",
"function printReversedPyramid (n) {\n\n for (var i = 1; i <= n; i++) {\n var row = '';\n for (var j = 1; j <= (n - i + 1); j++) {\n row += '*';\n }\n\n console.log(row);\n }\n}",
"changeHeights() {\r\n //1) Initalize height of four corners to random value (between 0 and 1)\r\n this.vBuffer[2] = Math.random()*0.5;\r\n this.vBuffer[this.numVertices*3 - 1] = Math.random()*0.5;\r\n this.vBuffer[this.div*3 + 2] = Math.random()*0.5;\r\n this.vBuffer[this.numVertices*3 - 1 - this.div*3] = Math.random()*0.5;\r\n\r\n //Began recursion\r\n var roughness = 0.5;\r\n this.diamondAlgorithm(0,this.div,0,this.div,this.div,roughness);\r\n }",
"function makeTenprint(){\n let x = 0, y = 0, spc = canvas.width/50;\n for (let i = 0; i < tenprint.length; i++){\n if(x >= canvas.width){\n x = 0;\n y += spc;\n if(y >= canvas.height){\n break;\n }\n }\n tenprint[i+1] = {\n left:[x, y, x + spc, y + spc], \n right:[x, y + spc, x + spc, y]\n };\n x +=spc;\n };\n}",
"function createPitch() {\n ctx.beginPath();\n ctx.moveTo(boardWidth/2,0);\n ctx.lineTo(boardWidth/2,boardHeight);\n ctx.closePath();\n ctx.lineWidth = 8;\n ctx.strokeStyle = \"white\";\n ctx.stroke();\n\n ctx.beginPath();\n ctx.arc(boardWidth/2,boardHeight/2,2*step,0,Math.PI*2,true);\n ctx.stroke();\n \n function goalArea(x0,x1){\n ctx.beginPath();\n ctx.moveTo(x0,boardHeight/2-2*step);\n ctx.lineTo(x1,boardHeight/2-2*step);\n ctx.lineTo(x1,boardHeight/2+2*step);\n ctx.lineTo(x0,boardHeight/2+2*step);\n ctx.stroke();\n }\n\n goalArea(0,2*step)\n goalArea(boardWidth,boardWidth-2*step)\n\n function goalLine(x0,color){\n ctx.beginPath();\n ctx.moveTo(x0,boardHeight/2);\n ctx.lineTo(x0,boardHeight/2-step);\n ctx.lineTo(x0,boardHeight/2+step);\n ctx.strokeStyle = color;\n ctx.stroke();\n }\n\n goalLine(0,\"green\");\n goalLine(boardWidth,\"red\");\n\n function corners(x0,y0,direction){\n ctx.beginPath();\n ctx.arc(x0,y0,step/2,0,Math.PI*0.5,direction);\n ctx.strokeStyle = \"white\";\n ctx.stroke();\n }\n \n corners(0,0,false)\n corners(boardWidth,0,true)\n corners(0,boardHeight,true)\n corners(boardWidth,boardHeight,true)\n\n function semicircle(x0,direction){\n ctx.beginPath();\n ctx.arc(x0,boardHeight/2,step,Math.PI*0.5,Math.PI*1.5,direction);\n ctx.stroke();\n }\n \n semicircle(2*step,true)\n semicircle(boardWidth-2*step,false)\n }",
"function lineWidthButtonLoop(x,y,r){\n // to start off, the values for x, y and r are these\n x = 690;\n y = 300;\n r = 5;\n\n for(var k=0; k<8; k++){\n\n // the second row of buttons have different start values\n if(k == 5){\n x = 692;\n y = 340;\n r = 12;\n }\n\n lineWidthButtonSet[k] = new LineWidthButton(x,y,r,colArray[0][0],colArray[0][0],colArray[1][0],canvas,controlShapes1);\n \n // first row of buttons increase at these rates\n if(k < 5){\n // as the radius increases, I want the gap between the buttons to stay the same\n x = x + 2*r + 9;\n r += 1;\n }\n \n // second row of buttons increase at different rates\n else{\n // as the radius increases, I want the gap between the buttons to stay the same\n x = x + 2*r + 11;\n r += 4;\n }\n \n }\n}",
"function makeSquare (size) {\n var line = ''\n for (var i1 = 0; i1 < size; i1++){\n for (var i = 0; i < size; i++){\n line = line + '*'\n }\n line = line + '\\n'\n}\n return line\n}",
"function marioAgain() {\n\n ////////////// DO NOT MODIFY\n let height; // DO NOT MODIFY\n ////////////// DO NOT MODIFY\n\n // WRITE YOUR EXERCISE 2 CODE HERE\n let space = \" \";\n let block = \"#\";\n let i\n let l\n let outputmario2= \"\";\n let going = false;\n height = prompt (\"Please enter a integer between 1 to 23 for the height value of a Mario-style pyramid. \");\n while (!going) {\n if ( height > 0 && height <= 23){\n going = true\n }\n if ( height <= 0 || height > 23){\n height = prompt (\"Not a acceptable integer you have chosen. Enter a integer between 1 to 23 for the height value of a Mario-style half-pyramid.\");\n }\n }\n height = Number(height)\n for (i= 0; i < height; i ++ ){\n for (l = 0 ; l < height+1 ; l ++){\n if (l > (height -i)-2){\n outputmario2 +=block;\n }else{\n outputmario2 += space;\n }\n }\n outputmario2 += space + space ;\nfor (l = 0 ; l < height+1 ; l ++){\n if (l < i +2){\noutputmario2 += block;\n}\n\n}\noutputmario2+= \"</br>\";\n}\n\n var p = document.getElementById(\"mario-hard-output\");\n p.innerHTML = \"<code>\" + outputmario2 + \"</code>\";\n\n //////////////////////////////// DO NOT MODIFY\n check('mario-again', height); // DO NOT MODIFY\n //////////////////////////////// DO NOT MODIFY\n}",
"function drawBoard(size) {\r\n if (size <= 1) {\r\n alert(\"Specified grid size MUST >= 2!\");\r\n return;\r\n }\r\n \r\n var startx = GAP_SIZE;\r\n var starty = GAP_SIZE;\r\n\r\n for (var row = 0; row < size; ++row) {\r\n for (var col = 0; col < size; ++col) {\r\n drawLine(startx, starty + UNIT_SIZE*row, startx + UNIT_SIZE*(size-1), starty + UNIT_SIZE*row);\r\n drawLine(startx + UNIT_SIZE*col, starty, startx + UNIT_SIZE*col, starty + UNIT_SIZE*(size-1));\r\n }\r\n }\r\n for (var row = 0; row < size; ++row) {\r\n var patch = 0;\r\n if (row >= 10) {\r\n patch = GAP_SIZE/8;\r\n }\r\n drawText(row, GAP_SIZE/8*3-patch, GAP_SIZE/7*8+UNIT_SIZE*row);\r\n }\r\n for (var col = 0; col < size; ++col) {\r\n var patch = 0;\r\n if (col >= 10) {\r\n patch = GAP_SIZE/8;\r\n }\r\n drawText(col, GAP_SIZE/8*7+UNIT_SIZE*col-patch, GAP_SIZE/3*2);\r\n }\r\n \r\n // mark the center an key positions\r\n var radius = STONE_RADIUS/3;\r\n var color = \"black\";\r\n drawCircle(getCanvasPos(board.getPosition((GRID_SIZE-1)/2, (GRID_SIZE-1)/2)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(WIN_SIZE-1, WIN_SIZE-1)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(GRID_SIZE-WIN_SIZE, WIN_SIZE-1)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(WIN_SIZE-1, GRID_SIZE-WIN_SIZE)), radius, color);\r\n drawCircle(getCanvasPos(board.getPosition(GRID_SIZE-WIN_SIZE, GRID_SIZE-WIN_SIZE)), radius, color);\r\n}",
"function caterpillar(y_point){\n for( var i=1; i<=7; i++){\n fill('white');\n ellipse(x_point,y_point,20);\n x_point+=10;\n }\n x_point-=65;\n}",
"function drawRooms() {\n for (let i = 0; i < numberOfFloors; i++) {\n line(0, (height * i) / numberOfFloors, width, (height * i) / numberOfFloors);\n }\n \n fill(0, 0, 0);\n line(width / 4, (height * 0) / numberOfFloors, width / 4, (height * 1) / numberOfFloors);\n line(width / 2, (height * 0) / numberOfFloors, width / 2, (height * 1) / numberOfFloors);\n line((width * 3) / 4, (height * 0) / numberOfFloors, (width * 3) / 4, (height * 1) / numberOfFloors);\n \n line(width / 4 - 20, (height * 1) / numberOfFloors, width / 4 - 20, (height * 2) / numberOfFloors);\n line(width / 2 - 30, (height * 1) / numberOfFloors, width / 2 - 30, (height * 2) / numberOfFloors);\n line((width * 3) / 4 + 50, (height * 1) / numberOfFloors, (width * 3) / 4 + 50, (height * 2) / numberOfFloors);\n \n line(width / 4, (height * 2) / numberOfFloors, width / 4, (height * 3) / numberOfFloors);\n line(width / 2, (height * 2) / numberOfFloors, width / 2, (height * 3) / numberOfFloors);\n line((width * 3) / 4, (height * 2) / numberOfFloors, (width * 3) / 4, (height * 3) / numberOfFloors);\n \n line(width / 4 - 30, (height * 3) / numberOfFloors, width / 4 - 30, (height * 4) / numberOfFloors);\n line(width / 2 + 50, (height * 3) / numberOfFloors, width / 2 + 50, (height * 4) / numberOfFloors);\n line((width * 3) / 4 + 20, (height * 3) / numberOfFloors, (width * 3) / 4 + 20, (height * 4) / numberOfFloors);\n \n line(width / 4 + 20, (height * 4) / numberOfFloors, width / 4 + 20, (height * 5) / numberOfFloors);\n line(width / 2, (height * 4) / numberOfFloors, width / 2, (height * 5) / numberOfFloors);\n line((width * 3) / 4 + 30, (height * 4) / numberOfFloors, (width * 3) / 4 + 30, (height * 5) / numberOfFloors);\n \n line(width / 4 - 30, (height * 5) / numberOfFloors, width / 4 - 30, (height * 6) / numberOfFloors);\n line(width / 2, (height * 5) / numberOfFloors, width / 2, (height * 6) / numberOfFloors);\n line((width * 3) / 4, (height * 5) / numberOfFloors, (width * 3) / 4, (height * 6) / numberOfFloors);\n \n line(width / 4, (height * 6) / numberOfFloors, width / 4, (height * 7) / numberOfFloors);\n line(width / 2, (height * 6) / numberOfFloors, width / 2, (height * 7) / numberOfFloors);\n line((width * 3) / 4, (height * 6) / numberOfFloors, (width * 3) / 4, (height * 7) / numberOfFloors);\n \n verticalCollisionLine1 = collideLineRect(width / 4, (height * 0) / numberOfFloors, width / 4, (height * 1) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine2 = collideLineRect(width / 2, (height * 0) / numberOfFloors, width / 2, (height * 1) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine3 = collideLineRect((width * 3) / 4, (height * 0) / numberOfFloors, (width * 3) / 4, (height * 1) / numberOfFloors, person.x, person.y, person.width, person.width);\n\n verticalCollisionLine4 = collideLineRect(width / 4 - 20, (height * 1) / numberOfFloors, width / 4 - 20, (height * 2) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine5 = collideLineRect(width / 2 - 30, (height * 1) / numberOfFloors, width / 2 - 30, (height * 2) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine6 = collideLineRect((width * 3) / 4 + 50, (height * 1) / numberOfFloors, (width * 3) / 4 + 50, (height * 2) / numberOfFloors, person.x, person.y, person.width, person.width);\n \n verticalCollisionLine7 = collideLineRect(width / 4, (height * 2) / numberOfFloors, width / 4, (height * 3) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine8 = collideLineRect(width / 2, (height * 2) / numberOfFloors, width / 2, (height * 3) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine9 = collideLineRect((width * 3) / 4, (height * 2) / numberOfFloors, (width * 3) / 4, (height * 3) / numberOfFloors, person.x, person.y, person.width, person.width);\n \n verticalCollisionLine10 = collideLineRect(width / 4 - 30, (height * 3) / numberOfFloors, width / 4 - 30, (height * 4) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine11 = collideLineRect(width / 2 + 50, (height * 3) / numberOfFloors, width / 2 + 50, (height * 4) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine12 = collideLineRect((width * 3) / 4 + 20, (height * 3) / numberOfFloors, (width * 3) / 4 + 20, (height * 4) / numberOfFloors, person.x, person.y, person.width, person.width);\n \n verticalCollisionLine13 = collideLineRect(width / 4 + 20, (height * 4) / numberOfFloors, width / 4 + 20, (height * 5) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine14 = collideLineRect(width / 2, (height * 4) / numberOfFloors, width / 2, (height * 5) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine15 = collideLineRect((width * 3) / 4 + 30, (height * 4) / numberOfFloors, (width * 3) / 4 + 30, (height * 5) / numberOfFloors, person.x, person.y, person.width, person.width);\n \n verticalCollisionLine16 = collideLineRect(width / 4 - 30, (height * 5) / numberOfFloors, width / 4 - 30, (height * 6) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine17 = collideLineRect(width / 2, (height * 5) / numberOfFloors, width / 2, (height * 6) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine18 = collideLineRect((width * 3) / 4, (height * 5) / numberOfFloors, (width * 3) / 4, (height * 6) / numberOfFloors, person.x, person.y, person.width, person.width);\n \n verticalCollisionLine19 = collideLineRect(width / 4, (height * 6) / numberOfFloors, width / 4, (height * 7) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine20 = collideLineRect(width / 2, (height * 6) / numberOfFloors, width / 2, (height * 7) / numberOfFloors, person.x, person.y, person.width, person.width);\n verticalCollisionLine21 = collideLineRect((width * 3) / 4, (height * 6) / numberOfFloors, (width * 3) / 4, (height * 7) / numberOfFloors, person.x, person.y, person.width, person.width); \n \n horizontalCollisionLine0 = collideLineCircle(0, (height * 0) / numberOfFloors, width, (height * 0) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine1 = collideLineCircle(0, (height * 1) / numberOfFloors, width, (height * 1) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine2 = collideLineCircle(0, (height * 2) / numberOfFloors, width, (height * 2) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine3 = collideLineCircle(0, (height * 3) / numberOfFloors, width, (height * 3) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine4 = collideLineCircle(0, (height * 4) / numberOfFloors, width, (height * 4) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine5 = collideLineCircle(0, (height * 5) / numberOfFloors, width, (height * 5) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n horizontalCollisionLine6 = collideLineCircle(0, (height * 6) / numberOfFloors, width, (height * 6) / numberOfFloors, person.x + person.width / 2, person.y, person.width);\n \n \n \n collisionAssignment();\n}",
"function displayFloor(){\n var countTilesX;\n var countTilesY;\n\n // initialize variables\n countTilesX = 0;\n countTilesY = 0;\n numberOfTilesX = floor_length / tile_length; // stores number of tiles in a row\n numberOfTilesY = floor_width / tile_width; // stores number of tiles in a column\n\n strokeWeight(2);\n rect(0, 0, floor_length, floor_width); // output the background\n\n // generate tiles\n while (countTilesY < numberOfTilesY){ // prevents drawing over in a column\n if (countTilesX < numberOfTilesX){ // prevents drawing over in a row\n rect((0 + countTilesX) * tile_width, (0 + countTilesY) * tile_length, tile_width, tile_length);\n countTilesX = countTilesX + 1;\n } else {\n countTilesY = countTilesY + 1;\n countTilesX = 0;\n }\n }\n}",
"function ring () {\n ctx.save()\n ctx.fillStyle = \"black\"\n ctx.fillRect(0, 0, w, h)\n ctx.translate(w / 2, h / 2) // move the context to the center of the canvas\n for (let ring = 1; ring < 28; ring++) {\n ctx.fillStyle = `hsl(${ring * 25}, 90%, 50%)`\n for (let dots = 0; dots < ring * 6; dots++) {\n ctx.rotate((Math.PI * 2) / (ring * 6))\n ctx.beginPath()\n ctx.arc(0, ring * 15, 7, 0, Math.PI * 2, true)\n ctx.fill()\n }\n }\n ctx.restore()\n}",
"function run(width, height,size, angle, limit) {\r\n\r\n\tctx.clearRect(0, 0, width, height);\r\n\r\n\tvar branchAngleA = angle; //minus becuase it rotates counter clockwise\r\n \r\n //call the function to draw boxes\r\n\r\n tree(width/2 - 75, height, size, 0, limit);\r\n\r\n\tfunction tree(x, y, size, angle, limit) {\r\n\t\tctx.save();\r\n\t\tctx.translate(x, y);\r\n\t\tctx.rotate(angle);\r\n\t\tctx.fillStyle = 'rgb(0, ' + Math.floor(42.5 * limit) + ', ' + Math.floor(25 * limit) + ' )';\r\n\t\tctx.fillRect(0, 0, size, -size);\r\n\r\n\t\t//left hand square \r\n\r\n\t\tvar x0 = 0, \r\n\t\ty0 = -size, \r\n\t\tsize0 = Math.abs(Math.cos(branchAngleA) * size), \r\n\t\tangle0 = branchAngleA;\r\n\r\n\t\tif (limit > 0) {\r\n\t\t\ttree(x0, y0, size0, angle0, limit - 1);\r\n\t\t} else {\r\n\t\t\tctx.save();\r\n\t\t\tctx.translate(x0, y0);\r\n\t\t\tctx.rotate(angle0);\r\n\t\t\tctx.fillRect(0, 0, size0, -size0);\r\n\t\t\tctx.restore();\r\n\t\t}\r\n\r\n\t\t//right hand square\r\n\r\n\t\tvar y1 = y0 - Math.abs(Math.sin(branchAngleA) * size0);\r\n\t\tvar x1 = x0 + Math.abs(Math.cos(branchAngleA) * size0);\r\n\t\tvar angle1 = angle0 + Math.PI / 2;\r\n\t\tvar size1 = Math.abs(Math.cos(angle1) * size);\r\n\r\n\t\tif (limit > 0) {\r\n\t\t\ttree(x1, y1, size1, angle1, limit - 1);\r\n\t\t} else {\r\n\t\t\tctx.save();\r\n\t\t\tctx.translate(x1, y1);\r\n\t\t\tctx.rotate(angle1);\r\n\t\t\tctx.fillRect(0, 0, size1, -size1);\r\n\t\t\tctx.restore();\r\n\t\t}\r\n\r\n\t\tctx.restore();\r\n\t}\r\n\r\n} // end of function",
"function drawPool() {\n //Draws water\n strokeWeight(2);\n fill(0, 0, 100, 220);\n rect(0, height-100, width, 100);\n\n //Pool deck\n fill(242, 242, 210);\n rect(0, height-102, 50, 102);\n rect(width-50, height-102, 50, 102);\n stroke(242, 242, 210);\n rect(0, height-20, width, 20);\n stroke(0);\n\n //Lines of the pool deck\n line(0, height-102, 0, height);\n line(50, height-21, width-50, height-21);\n strokeWeight(1);\n stroke(0);\n fill(0, 255, 0);\n\n //Diving boards\n rect(0, 110 * 1.5 - 11, width/3 + 10 + 3, 10);\n rect(0, 110 * 4.2 - 11, width/3 + 10 + 3, 10);\n}",
"function drawBlocks() {\n var i, j;\n var color;\n for (i = 0; i < width/BLOCK_SIZE; i++) {\n for (j = 0; j < height/BLOCK_SIZE; j++) {\n color = colorGrid[i][j];\n context.fillStyle = color;\n context.fillRect(i*BLOCK_SIZE, j*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);\n }\n }\n }",
"function drawGrid(cw, ch){\n /*\n Draw the grid. \n */\n var v = 36;\n ctx.globalAlpha = 0.5;\n ctx.lineWidth=1;\n ctx.strokeStyle='blue';\n ctx.setLineDash([5, 15]);\n for( var i=0; i<cw/100; i++){\n drawLine( i * 100, 0+v, i*100, ch+v); ctx.stroke();\n }\n for(var j=0; j<ch/100; j++){\n drawLine(0, j*100+v, cw, j*100+v); ctx.stroke();\n }\n \n /* Randomly initialize puzzle piece elements on the grid (for now).. \n\tChange this later.. \n */\n if( progIter<1){\n for( var i =0; i<=cw/100; i++){\n for(var j=0; j<=ch/100; j++){\n var cI = i.toString()+'-'+j.toString();\n if( cI in gridContent){\n\t\t\t\t//pass\n }else{\n\t\t\t\tif( Math.random()<.4){////if( i%3==0 || j%==0){\n\t\t\t\t\tgridContent[cI]=(nextPuzzlePieceName++);\n\t\t\t\t}else{\n\t\t\t\t\tgridContent[cI]=-1;\n\t\t\t\t}\n }\n }\n }\n }\n ctx.globalAlpha = 1.;\n}",
"function buildSquare(blocks) {\n let pile = { 1: 0, 2: 0, 3: 0, 4: 0 };\n blocks.forEach(b => pile[b]++);\n let rowsToBuild = 4 - pile[4];\n let min13 = Math.min(pile[3], pile[1]);\n rowsToBuild -= min13;\n pile[1] -= min13;\n rowsToBuild -= Math.floor(pile[2] / 2);\n pile[2] = pile[2] % 2;\n let min12 = Math.min(Math.floor(pile[1] / 2), pile[2]);\n rowsToBuild -= min12;\n pile[1] -= 2*min12;\n rowsToBuild -= Math.floor(pile[1] / 4);\n return rowsToBuild < 1;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the name of the network for a chain id | function getNetworkName(chainId) {
if (chainId === CHAIN_ID_MAINNET_ETHEREUM) {
return "Mainnet - Ethereum"
} else if (chainId === CHAIN_ID_TESTNET_GOERLI) {
return "Testnet - Goerli"
} else if (chainId === CHAIN_ID_MAINNET_POLYGON) {
return "Mainnet - Polygon"
} else {
return "..."
}
} | [
"async getChainId(network){}",
"mapNetworkString(networkId) {\n switch (networkId) {\n case 1: return \"Mainnet\";\n case 2: return \"Morden\";\n case 3: return \"Ropsten\";\n case 4: return \"Rinkeby\";\n case 42: return \"Kovan\";\n default: return \"Unknown Network (ID \" + networkId + \")\";\n }\n }",
"function getNetworkID(netName){\n return __netNameIndex[netName];\n}",
"function getNetwork(network) {\n // No network (null)\n if (network == null) {\n return null;\n }\n if (typeof (network) === \"number\") {\n for (var name_1 in networks) {\n var standard_1 = networks[name_1];\n if (standard_1.chainId === network) {\n return {\n name: standard_1.name,\n chainId: standard_1.chainId,\n ensAddress: (standard_1.ensAddress || null),\n _defaultProvider: (standard_1._defaultProvider || null)\n };\n }\n }\n return {\n chainId: network,\n name: \"unknown\"\n };\n }\n if (typeof (network) === \"string\") {\n var standard_2 = networks[network];\n if (standard_2 == null) {\n return null;\n }\n return {\n name: standard_2.name,\n chainId: standard_2.chainId,\n ensAddress: standard_2.ensAddress,\n _defaultProvider: (standard_2._defaultProvider || null)\n };\n }\n var standard = networks[network.name];\n // Not a standard network; check that it is a valid network in general\n if (!standard) {\n if (typeof (network.chainId) !== \"number\") {\n logger.throwArgumentError(\"invalid network chainId\", \"network\", network);\n }\n return network;\n }\n // Make sure the chainId matches the expected network chainId (or is 0; disable EIP-155)\n if (network.chainId !== 0 && network.chainId !== standard.chainId) {\n logger.throwArgumentError(\"network chainId mismatch\", \"network\", network);\n }\n // Standard Network (allow overriding the ENS address)\n return {\n name: network.name,\n chainId: standard.chainId,\n ensAddress: (network.ensAddress || standard.ensAddress || null),\n _defaultProvider: (network._defaultProvider || standard._defaultProvider || null)\n };\n}",
"function getNetworkDetail(netId , detail){\n if (!__subnetIndex[netId])\n return null;\n return netDef.networks[__subnetIndex[netId]][detail];\n}",
"getNetworkId(ip, netmask) {\n\t\tvar networkId = '';\n\t\t// do bitwise AND on the IP address and subnet mask to get network ID\n\t\tfor (var i = 0; i < ip.length; i++) {\n\t\t\tnetworkId += ip.charAt(i) & netmask.charAt(i);\n\t\t}\n\t\treturn networkId;\n\t}",
"function getNetwork() {\n return bitcoinNetwork;\n}",
"function getNetworkSubnet(netID){\n return getNetworkDetail(netID , \"subnet\");\n}",
"static get network()\n\t{\n\t\treturn network;\n\t}",
"get networkBorderGroup() {\n return this.getStringAttribute('network_border_group');\n }",
"function updateNetworkId() {\n gsnStore.getStore().then(function (rst) {\n if (service.store != rst) {\n var baseNetworkId;\n\n if (rst) {\n baseNetworkId = '/' + rst.City + '-' + rst.StateName + '-' + rst.PostalCode + '-' + rst.StoreId;\n baseNetworkId = baseNetworkId.replace(/(undefined)+/gi, '').replace(/\\s+/gi, '');\n }\n Gsn.Advertising.gsnNetworkStore = baseNetworkId;\n }\n });\n }",
"function neighborhoodFromLayer(layer) {\n return layer.feature.properties.NTAName;\n }",
"function parentNetIDOfLeaf(netName){\n if (!isLeaf(netName)){\n showTitle(\"parentOfLeaf-- \"+netName+\" is not a leaf\");\n return false;\n }else\n return (netDefinition.networks[netName].leafOf);\n}",
"payeeName(id) {\n let payee = this.repo.payee(id)\n return payee == null ? '-- payee? --' : payee.name\n }",
"function unique_node_id(name, type) {\n let idstring = node_machine_id_1.machineIdSync();\n return NODE_TYPE[type] + '-' + crypto_1.createHash('sha1').update(`${idstring}-${name}`).digest('base64');\n}",
"setNetworkId(currentNetworkId) {\n this.currentNetworkId = currentNetworkId;\n }",
"suggestNetwork(){\n return _send(NetworkMessageTypes.REQUEST_ADD_NETWORK, {\n domain:location.host,\n network:network\n });\n }",
"function _getWfsLayerIdName(layer_name, table_name) {\n return new Promise(function (resolve, reject) {\n //Get from WFS layer data\n _self.emit(\"log\", \"visits.js\", \"_getWfsLayerIdName(\" + layer_name + \",\" + table_name + \")\", \"info\");\n\n var id_name = null;\n layer_name = layer_name.replace(/\\s+/g, '_');\n axios.get(_options.urlWMS + '?service=WFS&request=DescribeFeatureType&version=1.0.0&typename=' + layer_name).then(function (response) {\n var json = JSON.parse(parser.xml2json(response.data, {\n compact: true,\n spaces: 4\n })); //_self.emit(\"log\",\"visits.js\",\"_getWfsLayerIdName(\"+layer_name+\",\"+table_name+\"),\"info\",json);\n\n if (typeof json.schema != \"undefined\") {\n if (typeof json.schema.complexType != \"undefined\") {\n if (typeof json.schema.complexType.complexContent != \"undefined\") {\n if (typeof json.schema.complexType.complexContent.extension != \"undefined\") {\n if (typeof json.schema.complexType.complexContent.extension.sequence != \"undefined\") {\n if (typeof json.schema.complexType.complexContent.extension.sequence.element != \"undefined\") {\n //id_name MUST be first at position 1\n id_name = json.schema.complexType.complexContent.extension.sequence.element[1]._attributes.name;\n }\n }\n }\n }\n }\n }\n\n if (id_name) {\n resolve({\n 'id_name': id_name,\n 'table': table_name\n });\n } else {\n resolve(null);\n }\n })[\"catch\"](function (error) {\n _self.emit(\"log\", \"visits.js\", \"_getWfsLayerIdName error\", \"error\", error);\n\n reject(error);\n });\n });\n }",
"function zoneIdToName(zoneId) {\n var tmp = \"\";\n var idx;\n for (idx = 0; idx<zoneId.length; idx++) {\n var chr = zoneId[idx];\n if (chr === '=') {\n chr = zoneId[idx+1] + zoneId[idx+2];\n chr = String.fromCharCode(parseInt(chr, 16));\n idx += 2;\n }\n tmp += chr;\n }\n if (tmp.length > 1 && tmp[tmp.length-1] === '.') {\n tmp = tmp.substr(0, tmp.length-1);\n }\n return tmp;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Task 2: Create a function called getFinals that takes `data` as an argument and returns an array of objects with only finals data | function getFinals(data) {
const finals = data.filter(match => match.stage === 'final');
return finals;
} | [
"async function downloadData() {\n const releases = [];\n for (const source of sourcesOfTruth) {\n\n // fetch all repos of a given organizaion/user\n const allRepos = await fetch(\n `${baseURL}/users/${source.username}/repos${auth}`\n ).then(res => res.json());\n\n // fetch releases of every repo\n for (const repo of allRepos) {\n const repoName = repo.full_name;\n const repoReleasesURL = repo.releases_url.replace('{/id}', '') + auth;\n const repoReleases = await getRepoReleases(repoName, repoReleasesURL);\n if (repoReleases.length) {\n releases.push(...repoReleases);\n }\n }\n }\n // add date information to the data, to be able to show last updated time\n const data = {\n date: new Date().toLocaleString(),\n releases\n };\n return data;\n}",
"async function getData() {\n \n /*\n const carsDataReq = await fetch('https://storage.googleapis.com/tfjs-tutorials/carsData.json'); \n const carsData = await carsDataReq.json(); \n const cleaned = carsData.map(car => ({\n mpg: car.Miles_per_Gallon,\n horsepower: car.Horsepower,\n }))\n .filter(car => (car.mpg != null && car.horsepower != null));\n */\n return cleaned;\n }",
"function filterFinalDataByType() {\n\n filterString = \"\";\n filteredFinalData = [];\n for(i = 0; i < localFinalData.length; i++) {\n\n let t = localFinalData[i];\n\n if (filterType == \"users\" && t.is_user == false)\n continue;\n\n if (filterType == \"groups\" && t.is_user == true)\n continue;\n\n filteredFinalData.push(t);\n\n }\n\n }",
"function getTaskCompletionData(task_submissions, task_count) {\n //get number of days between start date and last task date\n let startDate = new Date(SPRINTS[currentSprint].sprintDate);\n let last_date = getLastSubmissionDate(task_submissions);\n\n let date_difference = calculateDateDifference(startDate, last_date);\n \n // console.log(date_difference);\n let tasks_remaining = [];\n\n //foreach day\n for(let i = 0; i <= date_difference; i++) \n {\n let task_date = new Date(startDate.getFullYear(),\n startDate.getMonth(),\n startDate.getDate() + i);\n\n //format the date into the standard date format for scrum tool\n task_date = FormatDate(task_date);\n\n if(task_submissions[task_date] != undefined) {\n task_count -= task_submissions[task_date];\n }\n tasks_remaining.push(task_count);\n }\n // console.log('tasks remaining', tasks_remaining);\n return tasks_remaining;\n}",
"fetchAllData(){\n // clear current prosumerData list\n this.prosumerData = new Array()\n var query = `query { \n simulate {\n consumption\n wind\n }\n \n }`\n\n this.prosumerList.forEach( pro => {\n fetchFromSim(query).then( (data) => {\n // structure of returned data: data['data']['simulate']['getWind']\n this.prosumerData.push(\n {\n \"id\": pro.id,\n \"consumption\": data.data.simulate.consumption,\n \"wind\": data.data.simulate.wind\n }\n )\n })\n })\n }",
"function constructData(data){\r\n const constructedData=[];\r\n data.map(function(i){\r\n constructedData.push({\r\n 'Item_Number': i.gsx$itemnumber.$t,\r\n 'Product_Name': i.gsx$productname.$t\r\n });\r\n });\r\n return constructedData;\r\n }",
"function prepareDataForReserve(data){\n var arr=[];\n for(let o in data[\"seats\"])\n {\n let c=(data[\"seats\"][o]);\n c.map(d1=>{\n let ret=o+\"\";\n ret+=d1;\n arr.push(ret);\n });\n\t\n }\n return arr;\n}",
"function getTaskSubmissions(data) {\n let task_submissions = {};\n\n //get task submission count\n Object.values(data).forEach(row => {\n //foreach row, if has been submitted\n if(row.submitted) {\n //get date is was submitted\n var row_date = row['date-submitted'];\n //add to task submissions or increase submission count\n task_submissions[row_date] == undefined ? task_submissions[row_date] = 1 : task_submissions[row_date]++;\n }\n });\n // console.log('task submissions:',task_submissions);\n return task_submissions;\n \n}",
"function aggregateData(data) {\n const ProgressData = data[0];\n const WakatimeData = data[1];\n const AttendanceData = data[2];\n const UserData = data[3];\n\n return UserData.map((user) => {\n const progress = transformProgress(ProgressData, user);\n const wakatimes = transformWakatime(WakatimeData, user);\n const attendance = transformAttendance(AttendanceData, user);\n const actual = user.toObject();\n\n return Object.assign({}, actual, {\n progress,\n wakatime: wakatimes.wakatimes,\n timeCoding: wakatimes.total,\n attendance: attendance.attendance,\n timeOnSite: attendance.total\n });\n });\n}",
"function getYears(getFinals) {\n return getFinals(fifaData).map(function(data){\n return data[\"Year\"];\n });\n\n}",
"function extractEmails(data){\n let emails = data[Column.emails];\n emails = unaccent(emails).trim();\n emails = emails.replace(new RegExp(/[,; ]/g), \"\")\n emails = emails.split(\"\\n\");\n let emailsObj = emails.reduce((acc, email, index) => {\n if(index === 0){\n acc.primaryEmail = email;\n } \n if(!acc.emails) {\n acc.emails = [];\n }\n acc.emails.push({\n address: email,\n // primary: false,\n type: \"work\"\n });\n return acc;\n },{})\n return emailsObj;\n}",
"function getYears(cbFinals) {\n const finalYears = [];\n const years = cbFinals(fifaData).map(function(element){\n finalYears.push(element.Year);\n })\n return finalYears;\n}",
"function fetchData() {\n // Wait for any ongoing sync to finish. We won't sync a SCORM while it's being played.\n return $mmaModScormSync.waitForSync(scorm.id).then(function() {\n // Get attempts data.\n return $mmaModScorm.getAttemptCount(scorm.id).then(function(attemptsData) {\n return determineAttemptAndMode(attemptsData).then(function() {\n // Fetch TOC and get user data.\n var promises = [];\n promises.push(fetchToc());\n promises.push($mmaModScorm.getScormUserData(scorm.id, attempt, offline).then(function(data) {\n userData = data;\n }));\n\n return $q.all(promises);\n });\n }).catch(showError);\n });\n }",
"function load_tract_data(original_tracts, onloaded_all_data)\n{\n var output_tracts = [],\n source_tracts = original_tracts.slice();\n\n load_more_data();\n\n function load_more_data()\n {\n\n var request_tracts = [];\n\n while(request_tracts.length < CR_API_PAGE && source_tracts.length)\n {\n request_tracts.push(source_tracts.shift());\n }\n censusReporter = ResidentResearch.censusReporter(request_tracts);\n censusReporter.getData(function(tracts)\n {\n output_tracts = output_tracts.concat(tracts);\n console.log(source_tracts.length, request_tracts.length, output_tracts.length);\n if(output_tracts.length == original_tracts.length)\n {\n return onloaded_all_data(output_tracts);\n }\n });\n\n if(source_tracts.length > 0)\n {\n load_more_data();\n }\n }\n}",
"async function getMeals(mealIds) {\n let meals = []\n\n await Promise.all(mealIds.map(async id => {\n const res = await fetch (`/api/meals/${id}`)\n const json = await res.json()\n meals.push(json[0])\n }))\n\n return meals\n}",
"async function getProvider(type, data) {\n try {\n let providers = await Promise.all(\n data.map(async (indiData) => {\n let response = await fetch(\n `https://api.themoviedb.org/3/${type}/${indiData.id}/watch/providers?api_key=your_api_key`\n );\n \n let data = await response.json();\n if (data.results.IN) {\n const res = {\n name:\n type === \"movie\"\n ? indiData.original_title\n : indiData.original_name,\n poster: indiData.poster_path === null ? \"https://allmovies.tube/assets/img/no-poster.png\" : \"https://image.tmdb.org/t/p/w300/\" + indiData.poster_path,\n provider_name: data.results.IN.flatrate ? data.results.IN.flatrate[0].provider_name : \"Not availabe in India\"\n };\n return res;\n } \n else {\n const res = {\n name:\n type === \"movie\"\n ? indiData.original_title\n : indiData.original_name,\n poster: indiData.poster_path === null ? \"https://allmovies.tube/assets/img/no-poster.png\" : \"https://image.tmdb.org/t/p/w300/\" + indiData.poster_path,\n provider_name: \"Not Available in India\"\n };\n return res;\n }\n })\n );\n if(providers.length > 5){\n providers=providers.slice(0,5);\n }\n return providers;\n } catch (err) {\n console.log(err);\n }\n }",
"function genData(init) {\n const tempData = init ? [] : data;\n let i = 10;\n while (i--) {\n tempData.push({ a: `a${i}`, b: `b${i}谁发的都是`, c: `c${i}`, d: `d${i}` })\n }\n return tempData;\n }",
"function dbResults(completedCourses = [], registeringTo = []) {\n let counter = 0;\n const preReqNotCompleted = [];\n for (let i = 0; i < registeringTo.length; i += 1) {\n for (let j = 0; j < completedCourses.length; ) {\n if (registeringTo[i].dependencies.pre !== completedCourses[j]) {\n // preReqCompleted[counter] = registeringTo[i];\n // counter += 1;\n counter += 1;\n if (counter >= completedCourses.length) {\n preReqNotCompleted.push(registeringTo[i]);\n }\n } else {\n j += 1;\n }\n }\n }\n return preReqNotCompleted;\n}",
"getDataSubset(allowed) {\n \n const subsetData = Object.keys(this.data)\n .filter(name => allowed.includes(name))\n .reduce((obj, key) => {\n obj[key] = this.data[key];\n return obj;\n }, {});\n\n return subsetData\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively parses the HIERACHY section of the BVH file lines: all lines of the file. lines are consumed as we go along. firstline: line containing the node type and name e.g. 'JOINT hip' list: collects a flat list of nodes returns: a BVH node including children | function readNode( lines, firstline, list ) {
var node = { name: '', type: '', frames: [] };
list.push( node );
// parse node type and name
var tokens = firstline.split( /[\s]+/ );
if ( tokens[ 0 ].toUpperCase() === 'END' && tokens[ 1 ].toUpperCase() === 'SITE' ) {
node.type = 'ENDSITE';
node.name = 'ENDSITE'; // bvh end sites have no name
} else {
node.name = tokens[ 1 ];
node.type = tokens[ 0 ].toUpperCase();
}
if ( nextLine( lines ) !== '{' ) {
console.error( 'THREE.BVHLoader: Expected opening { after type & name' );
}
// parse OFFSET
tokens = nextLine( lines ).split( /[\s]+/ );
if ( tokens[ 0 ] !== 'OFFSET' ) {
console.error( 'THREE.BVHLoader: Expected OFFSET but got: ' + tokens[ 0 ] );
}
if ( tokens.length !== 4 ) {
console.error( 'THREE.BVHLoader: Invalid number of values for OFFSET.' );
}
var offset = new THREE.Vector3(
parseFloat( tokens[ 1 ] ),
parseFloat( tokens[ 2 ] ),
parseFloat( tokens[ 3 ] )
);
if ( isNaN( offset.x ) || isNaN( offset.y ) || isNaN( offset.z ) ) {
console.error( 'THREE.BVHLoader: Invalid values of OFFSET.' );
}
node.offset = offset;
// parse CHANNELS definitions
if ( node.type !== 'ENDSITE' ) {
tokens = nextLine( lines ).split( /[\s]+/ );
if ( tokens[ 0 ] !== 'CHANNELS' ) {
console.error( 'THREE.BVHLoader: Expected CHANNELS definition.' );
}
var numChannels = parseInt( tokens[ 1 ] );
node.channels = tokens.splice( 2, numChannels );
node.children = [];
}
// read children
while ( true ) {
var line = nextLine( lines );
if ( line === '}' ) {
return node;
} else {
node.children.push( readNode( lines, line, list ) );
}
}
} | [
"function WikiHieroHTML(hiero, scale, line) {\n\n\tvar wh_scale\n\tif(scale !== WH_SCALE_DEFAULT) wh_scale = scale;\n\n\tvar html = \"\"\n \n\tif(line) html += \"<hr />\\n\"\n\n\t//------------------------------------------------------------------------\n\t// Split text into block, then split block into items\n\tvar block = []\n\tblock[0] = []\n\tblock[0][0] = \"\"\n\tvar block_id = 0\n\tvar item_id = 0\n\tvar parenthesis = 0\n\tvar type = 0\n\tvar is_cartouche = false\n\tvar is_striped = false\n\n\tfor (var char=0; char<hiero.length; char++) {\n\t\tvar db = hiero[char]\n\t\tif (hiero[char] === '(') parenthesis++\n\t\telse if (hiero[char] === ')') parenthesis--\n\t\tif(parenthesis === 0) {\n\t\t\tif(hiero[char] === '-' || hiero[char] === ' ') {\n\t\t\t\tif(type !== WH_TYPE_NONE) {\n\t\t\t\t\tblock_id++\n\t\t\t\t\tblock[block_id] = []\n\t\t\t\t\titem_id = 0\n\t\t\t\t\tblock[block_id][item_id] = \"\"\n\t\t\t\t\ttype = WH_TYPE_NONE\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\telse { // don't split block if inside parenthesis\n\t\t\tif(hiero[char] === '-') {\n\t\t\t\titem_id++\n\t\t\t\tblock[block_id][item_id] = '-'\n\t\t\t\ttype = WH_TYPE_CODE\n\t\t\t\t}\n\t\t\t}\n\t\tif(hiero[char] === '!' ) {\n\t\t\tif(item_id > 0) {\n\t\t\t\tblock_id++\n\t\t\t\tblock[block_id] = []\n\t\t\t\titem_id = 0\n\t\t\t\t}\n\t\t\tblock[block_id][item_id] = hiero[char]\n\t\t\ttype = WH_TYPE_END\n\t\t\t}\n\t\telse if (hiero[char].match(/[*:()]/)) {\n\t\t\tif(type === WH_TYPE_GLYPH || type === WH_TYPE_CODE) {\n\t\t\t\titem_id++\n\t\t\t\tblock[block_id][item_id] = \"\"\n\t\t\t\t}\n\t\t\tblock[block_id][item_id] = hiero[char]\n\t\t\ttype = WH_TYPE_CODE\n\t\t\t}\n\t\telse if (hiero[char].match(/[a-zA-Z0-9]/) || hiero[char] === '.' || hiero[char] === '<' || hiero[char] === '>') {\n\t\t\tif(type === WH_TYPE_END) {\n\t\t\t\tblock_id++\n\t\t\t\tblock[block_id] = []\n\t\t\t\titem_id = 0;\n\t\t\t\tblock[block_id][item_id] = \"\"\n\t\t\t\t}\n\t\t\telse if(type === WH_TYPE_CODE) {\n\t\t\t\titem_id++\n\t\t\t\tblock[block_id][item_id] = \"\"\n\t\t\t\t}\n\t\t\tblock[block_id][item_id] += hiero[char]\n\t\t\ttype = WH_TYPE_GLYPH\n\t\t\t}\n\t\t}\n\t// DEBUG: See the block split table\n\tif(WH_DEBUG_MODE) {\n\t\tvar ds = ''\n\t\tfor (var d=0;d<block.length;d++){\n\t\t\tds += \"| \"\n\t\t\tfor (var dd=0;dd<block[d].length;dd++) {\n\t\t\t\tds += block[d][dd] +\" | \"\n\t\t\t\t}\n\t\t\tds += \"\\n\"\n\t\t\t}\n\t\tconsole.log(ds)\n\t\t}\n\n var contentHtml = ''\n\tvar tableHtml = ''\n\tvar tableContentHtml = \"\"\n\n\t//console.log('block',block)\n\t\n\tvar div = wh_scale/100\n\tvar option, glyph\n\tfor (var b=0;b<block.length;b++) {\n\t\t// simplest case, the block contain only 1 code -> render\n\t\tif(block[b].length === 1) {\n\t\t\tif(block[b][0] === \"!\") { // end of line \n\t\t\t\ttableHtml = \"</tr>\" + WH_TABLE_E.WH_TABLE_S + \"<tr>\\n\"\n\t\t\t\tif(line) contentHtml += \"<hr />\\n\"\n\t\t\t\t}\n\t\t\telse if(block[b][0].match('<')) { // start cartouche\n\t\t\t\tcontentHtml += WH_TD_S + WH_RenderGlyph(block[b][0]) + WH_TD_E\n\t\t\t\tis_cartouche = true;\n\t\t\t\tcontentHtml += \"<td>\" + WH_TABLE_S + \"<tr><td height='\" + parseInt(WH_CARTOUCHE_WIDTH * div) + \"px' bgcolor='black'></td></tr><tr><td>\" + WH_TABLE_S + \"<tr>\\n\"\n\t\t\t\t}\n\t\t\telse if(block[b][0].match('>')) { // end cartouche\n\t\t\t\tcontentHtml += \"</tr>\" + WH_TABLE_E + \"</td></tr><tr><td height='\" + parseInt(WH_CARTOUCHE_WIDTH * div) + \"px' bgcolor='black'></td></tr>\" + WH_TABLE_E + \"</td>\\n\"\n\t\t\t\tis_cartouche = false\n\t\t\t\tcontentHtml += WH_TD_S + WH_RenderGlyph(block[b][0]) + WH_TD_E\n\t\t\t\t} \n\t\t\telse if(block[b][0] !== \"\") { // assum is glyph or '..' or '.'\n\t\t\t\toption = \"height='\" + WH_Resize(block[b][0], is_cartouche) + \"px'\"\n\t\t\t\tcontentHtml += WH_TD_S + WH_RenderGlyph(block[b][0], option) + WH_TD_E\n\t\t\t\t}\n\t\t\t}\n\t\t// block contains more than 1 glyph\n\t\telse {\n\t\t\t// convert all codes into '&' to test prefabs glyph\n\t\t\tvar temp = \"\"\n\t\t\tfor (var t=0;t<block[b].length;t++) {\n\t\t\t\tif (block[b][t].match(/[\\*\\:\\!\\(\\)]/)) temp += '&'\n\t\t\t\telse temp += block[b][t]\n\t\t\t\t}\n\t\t\t// test if block is in the prefabs list \n\t\t\tif(temp in _wh_prefabs) {\n\t\t\t\toption = \"height='\" + WH_Resize(temp, is_cartouche) + \"px'\"\n\t\t\t\tcontentHtml += WH_TD_S + WH_RenderGlyph(temp, option) + WH_TD_E\n\t\t\t\t}\n\t\t\t// block must be manually computed \n\t\t\telse {\n\t\t\t\t// get block total height\n\t\t\t\tvar line_max = 0\n\t\t\t\tvar total = 0\n\t\t\t\tvar height = 0\n\t\t\t\tfor (t=0;t<block[b].length;t++) {\n\t\t\t\t\tif(block[b][t] === \":\") {\n\t\t\t\t\t\tif(height > line_max) line_max = height\n\t\t\t\t\t\ttotal += line_max\n\t\t\t\t\t\tline_max = 0\n\t\t\t\t\t\t}\n\t\t\t\t\telse if(block[b][t] === \"*\") {\n\t\t\t\t\t\tif(height > line_max) line_max = height\n\t\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif(block[b][t] in _wh_phonemes) glyph = _wh_phonemes[block[b][t]]\n\t\t\t\t\t\telse glyph = block[b][t]\n\t\t\t\t\t\tif(glyph in _wh_files) height = 2 + _wh_files[glyph][1]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tif(height > line_max) line_max = height\n\t\t\t\ttotal += line_max\n\n\t\t\t\t// render all glyphs into the block\n\t\t\t\ttemp = \"\"\n\t\t\t\tfor (t=0;t<block[b].length;t++) {\n\t\t\t\t\tif(block[b][t] === \":\") temp += \"<br />\"\n\t\t\t\t\telse if(block[b][t] === \"*\") temp += \" \"\n\t\t\t\t\telse {\n\t\t\t\t\t\t// resize the glyph according to the block total height\n\t\t\t\t\t\toption = \"height='\" + WH_Resize(block[b][t], is_cartouche, total) + \"px'\"\n\t\t\t\t\t\ttemp += WH_RenderGlyph(block[b][t], option)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcontentHtml += WH_TD_S + temp + WH_TD_E\n\t\t\t\t}\n\t\t\tcontentHtml += \"\\n\"\n\t\t\t}\n\n\t//console.log('html',html)\n\t//console.log('tableHtml',tableHtml)\n\t//console.log('contentHtml',contentHtml)\n\t//console.log('tableContentHtml',tableContentHtml)\n\n\t\tif(contentHtml.length > 0) {\n\t\t\ttableContentHtml += tableHtml + contentHtml\n\t\t\tcontentHtml = \"\"\n\t\t\ttableHtml = \"\"\n\t\t\t}\n\t\t}\n if(tableContentHtml.length > 0) {\n\t\thtml += WH_TABLE_S + \"<tr>\\n\" + tableContentHtml + \"</tr>\" + WH_TABLE_E\n\t\t}\n\t\t\n\t\t\n\thtml = '<table width=\"100%\"><tr valign=\"middle\"><td>' + html + '</td></tr></table>'\n return html; \n\t}",
"getBands(content, taxid, chromosomes) {\n var lines = {},\n delimiter, tsvLines, columns, line, stain, chr,\n i, init, tsvLinesLength, source,\n start, stop, firstColumn, tmp;\n\n if (content.slice(0, 8) === 'chrBands') {\n source = 'native';\n }\n\n if (\n chromosomes instanceof Array &&\n typeof chromosomes[0] === 'object'\n ) {\n tmp = [];\n for (i = 0; i < chromosomes.length; i++) {\n tmp.push(chromosomes[i].name);\n }\n chromosomes = tmp;\n }\n\n if (typeof chrBands === 'undefined' && source !== 'native') {\n delimiter = /\\t/;\n tsvLines = content.split(/\\r\\n|\\n/);\n init = 1;\n } else {\n delimiter = / /;\n if (source === 'native') {\n tsvLines = eval(content);\n } else {\n tsvLines = content;\n }\n init = 0;\n }\n\n firstColumn = tsvLines[0].split(delimiter)[0];\n if (firstColumn === '#chromosome') {\n source = 'ncbi';\n } else if (firstColumn === '#chrom') {\n source = 'ucsc';\n } else {\n source = 'native';\n }\n\n tsvLinesLength = tsvLines.length;\n\n if (source === 'ncbi' || source === 'native') {\n for (i = init; i < tsvLinesLength; i++) {\n columns = tsvLines[i].split(delimiter);\n\n chr = columns[0];\n\n if (\n // If a specific set of chromosomes has been requested, and\n // the current chromosome\n typeof (chromosomes) !== 'undefined' &&\n chromosomes.indexOf(chr) === -1\n ) {\n continue;\n }\n\n if (chr in lines === false) {\n lines[chr] = [];\n }\n\n stain = columns[7];\n if (columns[8]) {\n // For e.g. acen and gvar, columns[8] (density) is undefined\n stain += columns[8];\n }\n\n line = {\n chr: chr,\n bp: {\n start: parseInt(columns[5], 10),\n stop: parseInt(columns[6], 10)\n },\n iscn: {\n start: parseInt(columns[3], 10),\n stop: parseInt(columns[4], 10)\n },\n px: {\n start: -1,\n stop: -1,\n width: -1\n },\n name: columns[1] + columns[2],\n stain: stain,\n taxid: taxid\n };\n\n lines[chr].push(line);\n }\n } else if (source === 'ucsc') {\n for (i = init; i < tsvLinesLength; i++) {\n // #chrom chromStart chromEnd name gieStain\n // e.g. for fly:\n // chr4\t69508\t108296\t102A1\tn/a\n columns = tsvLines[i].split(delimiter);\n\n if (columns[0] !== 'chr' + chromosomeName) {\n continue;\n }\n\n stain = columns[4];\n if (stain === 'n/a') {\n stain = 'gpos100';\n }\n start = parseInt(columns[1], 10);\n stop = parseInt(columns[2], 10);\n\n line = {\n chr: columns[0].split('chr')[1],\n bp: {\n start: start,\n stop: stop\n },\n iscn: {\n start: start,\n stop: stop\n },\n px: {\n start: -1,\n stop: -1,\n width: -1\n },\n name: columns[3],\n stain: stain,\n taxid: taxid\n };\n\n lines[chr].push(line);\n }\n }\n\n return lines;\n }",
"#checkLineBeforeBio(line) {\n if (line.startsWith('----')) {\n this.#messages.styleMessages.push('Horizontal rule before Biography');\n this.#style.bioHasStyleIssues = true;\n this.#headingBeforeBiography = true;\n } else {\n if (line.startsWith(Biography.#HEADING_START)) {\n if (!this.#headingBeforeBiography) {\n this.#style.bioHasStyleIssues = true;\n this.#headingBeforeBiography = true;\n this.#messages.styleMessages.push('Heading or subheading before Biography');\n }\n } else {\n // See https://www.wikitree.com/wiki/Help:Recommended_Tags\n // this might be too aggressive\n if ((line.startsWith('[[')) && (line.endsWith(']]'))) {\n this.#unexpectedLines.push(line);\n }\n if ((line.includes('through the import of')) ||\n (line.includes('collaborative work-in-progress'))) {\n this.#unexpectedLines.push(line);\n }\n }\n }\n }",
"function hiliteEmlLine(docObj, line) {\n var bgColor;\n if (top.HiliteCodeStatus)\n bgColor = \"#66CCFF\";\n else\n bgColor = \"#E8D152\";\n // unhighlight\n if (typeof docObj.HiliteLine != \"undefined\") {\n\ttrObj = docObj.getElementById(\"LN_\"+docObj.HiliteLine);\n\tif (trObj != null) {\n\t trObj.style.backgroundColor = \"\";\t\t\t\n\t}\n }\t\n // hilighlight\n trObj = docObj.getElementById(\"LN_\"+line);\n if (trObj != null) {\n\ttrObj.style.backgroundColor = bgColor;\n\tdocObj.HiliteLine = line;\n }\n}",
"function headingRule(nodeType, maxLevel) {\n return textblockTypeInputRule(new RegExp(\"^(#{1,\" + maxLevel + \"})\\\\s$\"),\n nodeType, match => ({level: match[1].length}))\n }",
"function createTree(){\n var colCount=0;\n head.find(selectors.row).first().find(selectors.th).each(function () {\n var c = parseInt($(this).attr(attributes.span));\n colCount += !c ? 1 : c;\n });\n\n root = new Node(undefined,colCount,0);\n var headerRows = head.find(selectors.row);\n var currParents = [root];\n // Iteration through each row\n //-------------------------------\n for ( var i = 0; i < headerRows.length; i++) {\n\n var newParents=[];\n var currentOffset = 0;\n var ths = $( headerRows[i] ).find(selectors.th);\n\n // Iterating through each th inside a row\n //---------------------------------------\n for ( var j = 0 ; j < ths.length ; j++ ){\n var colspan = $(ths[j]).attr(attributes.span);\n colspan = parseInt( !colspan ? '1' : colspan);\n var newChild = 0;\n\n // Checking which parent is the newChild parent (?)\n // ------------------------------------------------\n for( var k = 0 ; k < currParents.length ; k++){\n if ( currentOffset < currParents[k].colspanOffset + currParents[k].colspan ){\n var newChildId = 'cm-'+i+'-'+j+'-'+k ;\n $(ths[j]).addClass(currParents[k].classes);\n $(ths[j]).addClass(currParents[k].id);\n $(ths[j]).attr(attributes.id, newChildId);\n \n newChild = new Node( currParents[k], colspan, currentOffset, newChildId );\n tableNodes[newChild.id] = newChild;\n currParents[k].addChild( newChild );\n break;\n }\n }\n newParents.push(newChild);\n currentOffset += colspan;\n }\n currParents = newParents;\n }\n\n var thCursor = 0;\n var tdCursor = 0;\n var rows = body.find(selectors.row);\n var tds = body.find(selectors.td);\n /* Searches which 'parent' this cell belongs to by \n * using the values of the colspan */\n head.find(selectors.row).last().find(selectors.th).each(function () {\n var thNode = tableNodes[$(this).attr(attributes.id)];\n thCursor += thNode.colspan;\n while(tdCursor < thCursor) {\n rows.each(function () {\n $(this).children().eq(tdCursor).addClass(thNode.classes + ' ' + thNode.id);\n });\n tdCursor += $(tds[tdCursor]).attr(attributes.span) ? $(tds[tdCursor]).attr(attributes.span) : 1;\n }\n });\n\n /* Transverses the tree to collect its leaf nodes */\n var leafs=[];\n for ( var node in tableNodes){\n if ( tableNodes[node].children.length === 0){\n leafs.push(tableNodes[node]);\n }\n }\n /* Connects the last row of the header (the 'leafs') to the first row of the body */\n var firstRow = body.find(selectors.row).first();\n for ( var leaf = 0 ; leaf < leafs.length ; leaf++){\n firstRow.find('.' + leafs[leaf].id ).each(function(index){\n var newNode = new Node( leafs[leaf] , 1 , 0, leafs[leaf].id + '--' + leaf + '--' + index);\n newNode.DOMelement = $(this);\n leafs[leaf].addChild(newNode);\n tableNodes[newNode.id] = newNode;\n newNode.DOMelement.attr(attributes.id, newNode.id);\n });\n }\n }",
"function readMtx(pth) {\n var ls = readFile(pth).split('\\n');\n var [, order, size] = ls[1].split(' ').map(parseFloat);\n var g = new DiGraph(order);\n for (var n=2, N=ls.length; n<N; n++) {\n var [i, j, wt] = ls[n].split(' ').map(parseFloat);\n if (wt) g.addLink(i-1, j-1, wt);\n }\n return g;\n}",
"extractBlocks () {\n return new Promise((resolve, reject) => {\n const result = []\n\n // iterate file lines\n const input = fs.createReadStream(_(this).filePath, { encoding: 'utf8' })\n const lineReader = readline.createInterface({input})\n let lineNumber = 0\n let block = null\n lineReader.on('line', lineString => {\n // name, from, to, content\n // detect block start\n // activate inside block flag\n if (!block && this[isAnStartBlock](lineString)) {\n block = this[buildBlock](lineNumber, lineString, reject)\n } else if (block && this[isAnEndBlock](lineString)) {\n block.to = (lineNumber + 1)\n // add block to result\n result.push(block)\n // deactivate inside block\n block = null\n } else if (!block && this[isAInlineBlock](lineString)) {\n block = this[buildInlineBlock](lineNumber, lineString, reject)\n block.to = block.from\n result.push(block)\n block = null\n } else if (block && !block.content) {\n block.content = lineString\n } else if (block && block.content) {\n block.content += `\\n${lineString}`\n }\n\n lineNumber++\n })\n\n input.on('error', (error) => {\n reject(error)\n })\n\n lineReader.on('close', () => {\n lineReader.close()\n resolve(result)\n })\n })\n }",
"breakHeart(frag) {\n\t\tif (frag.safe)\n\t\t\treturn this.callback(frag);\n\t\tlet bits = frag.split(break_re);\n\t\tfor (let i = 0, len = bits.length; i < len; i++) {\n\t\t\t// anchor refs\n\t\t\tconst morsels = bits[i].split(ref_re);\n\t\t\tfor (let j = 0, l = morsels.length; j < l; j++) {\n\t\t\t\tconst m = morsels[j];\n\t\t\t\tif (j % 2)\n\t\t\t\t\tthis.redString(m);\n\t\t\t\telse if (i % 2) {\n\t\t\t\t\tthis.parseHashes(m);\n\t\t\t\t\tthis.callback(safe('<wbr>'));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tthis.parseHashes(m);\n\t\t\t}\n\t\t}\n\t}",
"function mapFamily(arr) {\n console.log('FAM'.green, arr);\n var husbands = arr.filter(node => node.tag === 'HUSB'),\n wives = arr.filter(node => node.tag === 'WIFE'),\n parents = [],\n married = extractValue('MARR', arr),\n children = arr.filter(node => node.tag === 'CHIL');\n pino.info('HUSB'.red, husbands);\n\n if (husbands.length > 0) parents.push(husbands[0]);\n if (wives.length > 0) parents.push(wives[0]);\n //\n parents = parents.map(p => p.data);\n\n var events = ['MARR','DIV']\t// what else?\n .map(key => ({\n type: key,\n nodeList: arr.filter(node => node.tag === key)\n }));\n events = events.filter(obj => obj.nodeList.length > 0)\n .map(obj => ({\n id: 'e_' + treeData.eventId++,\n type: obj.type,\n date: Date.parse(extractValue('DATE', obj.nodeList)),\t// to milliseconds\n place: extractValue('PLAC', obj.nodeList)\n }));\n pino.info('EVENT'.rainbow, events);\n\n var marriages = events.filter(e => e.type === \"MARR\");\n var marriageDate = (marriages.length > 0) ? marriages[0].date : \"\";\n\n return {\n parents: parents,\n married: married || \"unknown\",\n marriageDate: marriageDate,\n children: children.length > 0 ? children.map(obj => obj.data) : [],\n events: events,\n notes: []\n };\n}",
"function parsePokFile(fileContents) {\n\tlet cheats = []\n\tlet currentCheatName = ''\n\tlet currentCodes = []\n\tfor (let line of fileContents.split('\\n')) {\n\t\tswitch (line[0]) {\n\t\t\tcase 'N': // New code name\n\t\t\t\tcurrentCheatName = line.substring(1)\n\t\t\t\tbreak\n\t\t\tcase 'M': // Multi-line code\n\t\t\t\tcurrentCodes.push(line)\n\t\t\t\tbreak\n\t\t\tcase 'Z': // Last code index\n\t\t\t\tcurrentCodes.push(line)\n\n\t\t\t\t// Add the new code to the library.\n\t\t\t\tcheats.push({\n\t\t\t\t\tname: currentCheatName,\n\t\t\t\t\tcodes: currentCodes\n\t\t\t\t})\n\n\t\t\t\t// Clear the current code.\n\t\t\t\tcurrentCheatName = ''\n\t\t\t\tcurrentCodes = []\n\t\t}\n\t}\n\n\treturn cheats\n}",
"buildTree() {\n this.clear();\n\n const columnsCount = this.#sourceSettings.getColumnsCount();\n let columnIndex = 0;\n\n while (columnIndex < columnsCount) {\n const columnSettings = this.#sourceSettings.getHeaderSettings(0, columnIndex);\n const rootNode = new TreeNode();\n\n this.#rootNodes.set(columnIndex, rootNode);\n this.buildLeaves(rootNode, columnIndex, 0, columnSettings.origColspan);\n\n columnIndex += columnSettings.origColspan;\n }\n\n this.rebuildTreeIndex();\n }",
"function getFirstLeaf(node: any): Node {\n while (\n node.firstChild &&\n // data-blocks has no offset\n ((isElement(node.firstChild) &&\n (node.firstChild: Element).getAttribute('data-blocks') === 'true') ||\n getSelectionOffsetKeyForNode(node.firstChild))\n ) {\n node = node.firstChild;\n }\n return node;\n}",
"parse_header(text){\n\t\tconst head=/^(={1,6})(.+?)(={1,6})$/gm,pos=this.pos;\n\t\thead.lastIndex=pos;\n\t\tconst m=head.exec(text);\n\t\t\n\t\tif(m && m.index==pos){\n\t\t\tthis.pos=m.lastIndex;\n\t\t\t\n\t\t\tconst left=m[1],right=m[3];\n\t\t\tlet section,level,content=m[2];\n\t\t\t\n\t\t\tif(content){\n\t\t\t\tif(left.length==right.length){\n\t\t\t\t\tlevel=left.length;\n\t\t\t\t}\n\t\t\t\telse if(left.length<right.length){\n\t\t\t\t\tlevel=left.length;\n\t\t\t\t\tcontent+='='.repeat(right.length-level);\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tlevel=right.length;\n\t\t\t\t\tcontent='='.repeat(left.length-level)+content;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tsection=new Section(left.length,content);\n\t\t\t}\n\t\t\telse{\n\t\t\t\tconst hl=m[0].length;\n\t\t\t\tlevel=hl>>1;\n\t\t\t\tsection=new Section(level,hl%2?'=':'==');\n\t\t\t}\n\t\t\t\n\t\t\tconst path=this.path;\n\t\t\t\n\t\t\twhile(\n\t\t\t\tpath.length>0 && path[path.length-1].level>=level\n\t\t\t){\n\t\t\t\tpath.pop();\n\t\t\t}\n\t\t\tpath.push(section);\n\t\t\tthis.cur=section;\n\t\t\t\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\t}",
"function processSourceCode(doc) {\n var body = doc.getBody();\n\n var startingTripleTick = body.findText('```');\n if (!startingTripleTick) return;\n var endTripleTick = body.findText('```', startingTripleTick);\n if (!endTripleTick) return;\n\n var firstLine = startingTripleTick.getElement();\n var lastLine = endTripleTick.getElement();\n\n var rangeBuilder = doc.newRange();\n rangeBuilder.addElementsBetween(firstLine, lastLine);\n var range = rangeBuilder.build();\n var lineRanges = range.getRangeElements();\n var lines = [];\n\n var firstLineIndex = body.getChildIndex(lineRanges[0].getElement());\n var code = \"\";\n\n // Don't iterate over 0th and last line because they are the tripleticks\n lineRanges[0].getElement().removeFromParent();\n for (var i = 1; i < lineRanges.length - 1; ++i) {\n code += lineRanges[i].getElement().asText().getText() + '\\n';\n lineRanges[i].getElement().removeFromParent();\n }\n lineRanges[lineRanges.length-1].getElement().removeFromParent();\n\n var cell = body.insertTable(firstLineIndex)\n .setBorderWidth(0)\n .appendTableRow()\n .appendTableCell();\n\n var params = {\n 'code': code.trim(),\n 'lexer': /```(.*)/.exec(firstLine.asText().getText())[1],\n 'style': 'monokai'\n };\n var response = UrlFetchApp.fetch(\n \"http://hilite.me/api\",\n {\n 'method': 'post',\n 'payload': params\n }\n );\n\n var xmlDoc = XmlService.parse(response.getContentText());\n // The XML document is structured as\n // - comment\n // - div\n // - pre\n // - spans\n var divTag = xmlDoc.getAllContent()[1];\n var preTag = divTag.getAllContent()[0];\n var spans_or_texts = preTag.getAllContent();\n var span_ranges = [];\n\n var startCharIdx = 0;\n for (var i = 0; i < spans_or_texts.length; ++i) {\n var span_or_text = spans_or_texts[i];\n if (span_or_text.getType() == XmlService.ContentTypes.ELEMENT) {\n // We are seeing a span (spans are styled while texts are not)\n var span_range = {\n start: startCharIdx,\n endInclusive: startCharIdx + span_or_text.getValue().length - 1,\n span: span_or_text\n };\n span_ranges.push(span_range);\n }\n startCharIdx += span_or_text.getValue().length;\n }\n\n var getTagColor = function (tag) {\n return tag.getAttribute('style').getValue().match(/#[0-9 a-f A-F]{6}/);\n };\n\n cell.setText(preTag.getValue().trim());\n\n var cellText = cell.editAsText();\n for (var i = 0; i < span_ranges.length; ++i) {\n var span_range = span_ranges[i];\n cellText.setForegroundColor(\n span_range.start,\n span_range.endInclusive,\n getTagColor(span_range.span)\n );\n }\n cell.setBackgroundColor(getTagColor(divTag));\n cell.setFontFamily('Consolas');\n\n processSourceCode(doc);\n}",
"function readHugeFiles(dirName, processOnFileLine, onError) {\n\tfs.readdir(dirName, function(err, fileNames) {\n\t\tif(err) {\n\t\t\tonError(err)\n\t\t\treturn\n\t\t}\n\n\t\t//Now we have all fileNames....\n\t\tfileNames.forEach(function(fileName) {\n\t\t\tvar filePath = path.join(dirName, fileName)\n\n\t\t\tvar lineReader = readline.createInterface({input: fs.createReadStream(filePath)})\n\n\t\t\tlineReader.on('line', function(line) {\n\t\t\t\tprocessOnFileLine(filePath, line)\n\t\t\t}) \t\n\n\t\t\tlineReader.on('close', function() {\n\t\t\t\tdebug(\"File \" + filePath + \" encounter file close operation\")\n\t\t\t})\n\t\t})\n\t})\t\n}",
"function getEdgesFromFile() {\n masonsGainPage.fileStr = masonsGainPage.inputTarget.value;\n //fileStr: string of file content given by user. \n let rows = masonsGainPage.inputTarget.value.split('\\n');\n let rowNum = rows.length, lastNodeIndex = 0;//start w/ 0\n let from, to, gain, nodeList = {}, nodeNum, forwardNodeList = {}, elementsDictionary = {};\n //if there is an empty space at the end of the file, remove it from rows.\n if (rows[rowNum-1].length == '' || rows[rowNum-1].length == ' ') { \n rows.pop();\n rowNum = rows.length;\n }\n for (let i=0; i<rowNum; i++) {\n rows[i] = rows[i].split(' ');//numbers are separated by a space. \n }\n let i=0;\n //while numbers in 'from' category are apart by 1, add nodes to the graph\n if (rows[i]) {\n from = parseInt(rows[i][0]);\n to = parseInt(rows[i][1]);\n gain = nerdamer(rows[i][2]);\n }\n while (to == from + 1 && rows[i]) {\n addEdgeToAdjacencyListDict(nodeList, from, to, gain);\n addEdgeToAdjacencyListDict(forwardNodeList, from, to, gain);\n addEdgeToElementsDict(elementsDictionary, rows[i][0], rows[i][1], rows[i][2], 'straight');\n if (from > lastNodeIndex) {\n lastNodeIndex = from;\n }\n if (to > lastNodeIndex) {\n lastNodeIndex = to;\n }\n i++;\n if (rows[i]) {\n from = parseInt(rows[i][0]);\n to = parseInt(rows[i][1]);\n gain = nerdamer(rows[i][2]);\n }\n }\n //get the edges nonconsecutive nodes not right next to each other.\n let curveClass, classStr = '';\n for (; i<rowNum; i++) {\n from = parseInt(rows[i][0]);\n to = parseInt(rows[i][1]);\n gain = nerdamer(rows[i][2]);\n addEdgeToAdjacencyListDict(nodeList, from, to, gain);\n if (!nodeList[from]) {//otherwise, must be from last node.\n nodeNum = nodeList.length;\n }\n if (to > from) {//if edge points forward/rightward, add to forwardNodeList\n //forwardNodeList[from].push(new Edge(to, gain));\n addEdgeToAdjacencyListDict(forwardNodeList, from, to, gain);\n }\n else if (from > to) {\n classStr = 'backward ';\n }\n if (to == from+1) {\n curveClass = 'straight';\n } else if (to == from) {\n curveClass = 'loop';\n }else {\n curveClass = 'curved';\n }\n classStr += curveClass;\n addEdgeToElementsDict(elementsDictionary, rows[i][0], rows[i][1], rows[i][2], classStr);\n if (from > lastNodeIndex) {\n lastNodeIndex = from;\n }\n if (to > lastNodeIndex) {\n lastNodeIndex = to;\n }\n }\n if (!nodeNum) {\n nodeNum = nodeList.length+1;\n }\n masonsGainPage.elementsDict = elementsDictionary;\n return [nodeList, forwardNodeList, lastNodeIndex, nodeNum];\n}",
"getChildInTree() {\n if (!this._children || this._children.length === 0)\n return null;\n for (var ch of this._children) {\n if (ch.isStartingPerson)\n return ch;\n if (ch.getChildInTree())\n return ch;\n }\n return null;\n }",
"function adjustH2WrapperLines() {\r\n\t\tvar $h2Wrapper = $(\".h2-wrapper\");\r\n\r\n\t\t$h2Wrapper.each(function() {\r\n\t\t\tvar $this = $(this);\r\n\t\t\tvar $h2Line = $this.children().first();\r\n\t\t\tvar $h2TextWrapper = $this.children().last();\r\n\r\n\t\t\t$h2Line.height($h2TextWrapper.height());\r\n\t\t});\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle input from the underlying xhr: either a state change, the progress event or the request being complete. | function handleProgress() {
var textSoFar = xhr.responseText,
newText = textSoFar.substr(numberOfCharsAlreadyGivenToCallback);
/* Raise the event for new text.
On older browsers, the new text is the whole response.
On newer/better ones, the fragment part that we got since
last progress. */
if( newText ) {
emitStreamData( newText );
}
numberOfCharsAlreadyGivenToCallback = len(textSoFar);
} | [
"function handleRequest() {\n // debugger;\n if (myReq.readyState === XMLHttpRequest.DONE) {\n // debugger;\n // check status here and proceed\n if (myReq.status === 200) {\n // 200 means done and dusted, ready to go with the dataset!\n console.log(myReq);\n handleDataSet(myReq.responseText);\n\n } else {\n // probably got some kind of error code, so handle that \n // a 404, 500 etc... can render appropriate error messages here\n console.error(`${myReq.status} : something done broke, son`);\n }\n } else {\n // request isn't ready yet, keep waiting...\n console.log(`Request state: ${myReq.readyState}. Still processing...`);\n }\n\n }",
"function requestHandle() {\n\t\tif (!isHandled) {\n\t\t\tisHandled = true;\n\t\t\tvueInst.$nextTick(() => {\n\t\t\t\tisHandled = false;\n\t\t\t\thandler();\n\t\t\t});\n\t\t}\n\t}",
"function handleRequest() {\r\n var dateForm = getDateForm();\r\n var paramForm = getParamForm();\r\n if (dateForm !== null && paramForm !== null) {\r\n requestItemInfoAndWait(dateForm, paramForm);\r\n }\r\n}",
"function readyStateChangePoll() {\n\t\t\tif( asyncRequest.req.readyState == 4 ) {\n\t\t\t\tprocessResponse();\n\t\t\t}\n\t\t}",
"function handleResponse(request, responseHandler) {\n if (request.readyState == 4 && request.status == 200) {\n responseHandler(request);\n }\n }",
"handleResponse_(error, request) {\n let segmentInfo;\n let segment;\n let view;\n\n // timeout of previously aborted request\n if (!this.xhr_ ||\n (request !== this.xhr_.segmentXhr &&\n request !== this.xhr_.keyXhr &&\n request !== this.xhr_.initSegmentXhr)) {\n return;\n }\n\n segmentInfo = this.pendingSegment_;\n segment = segmentInfo.playlist.segments[segmentInfo.mediaIndex];\n\n // if a request times out, reset bandwidth tracking\n if (request.timedout) {\n this.abort_();\n this.bandwidth = 1;\n this.roundTrip = NaN;\n this.state = 'READY';\n return this.trigger('progress');\n }\n\n // trigger an event for other errors\n if (!request.aborted && error) {\n // abort will clear xhr_\n let keyXhrRequest = this.xhr_.keyXhr;\n\n this.abort_();\n this.error({\n status: request.status,\n message: request === keyXhrRequest ?\n 'HLS key request error at URL: ' + segment.key.uri :\n 'HLS segment request error at URL: ' + segmentInfo.uri,\n code: 2,\n xhr: request\n });\n this.state = 'READY';\n this.pause();\n return this.trigger('error');\n }\n\n // stop processing if the request was aborted\n if (!request.response) {\n this.abort_();\n return;\n }\n\n if (request === this.xhr_.segmentXhr) {\n // the segment request is no longer outstanding\n this.xhr_.segmentXhr = null;\n segmentInfo.startOfAppend = Date.now();\n\n // calculate the download bandwidth based on segment request\n this.roundTrip = request.roundTripTime;\n this.bandwidth = request.bandwidth;\n this.mediaBytesTransferred += request.bytesReceived || 0;\n this.mediaRequests += 1;\n this.mediaTransferDuration += request.roundTripTime || 0;\n\n if (segment.key) {\n segmentInfo.encryptedBytes = new Uint8Array(request.response);\n } else {\n segmentInfo.bytes = new Uint8Array(request.response);\n }\n }\n\n if (request === this.xhr_.keyXhr) {\n // the key request is no longer outstanding\n this.xhr_.keyXhr = null;\n\n if (request.response.byteLength !== 16) {\n this.abort_();\n this.error({\n status: request.status,\n message: 'Invalid HLS key at URL: ' + segment.key.uri,\n code: 2,\n xhr: request\n });\n this.state = 'READY';\n this.pause();\n return this.trigger('error');\n }\n\n view = new DataView(request.response);\n segment.key.bytes = new Uint32Array([\n view.getUint32(0),\n view.getUint32(4),\n view.getUint32(8),\n view.getUint32(12)\n ]);\n\n // if the media sequence is greater than 2^32, the IV will be incorrect\n // assuming 10s segments, that would be about 1300 years\n segment.key.iv = segment.key.iv || new Uint32Array([\n 0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence\n ]);\n }\n\n if (request === this.xhr_.initSegmentXhr) {\n // the init segment request is no longer outstanding\n this.xhr_.initSegmentXhr = null;\n segment.map.bytes = new Uint8Array(request.response);\n this.initSegments_[initSegmentId(segment.map)] = segment.map;\n }\n\n if (!this.xhr_.segmentXhr && !this.xhr_.keyXhr && !this.xhr_.initSegmentXhr) {\n this.xhr_ = null;\n this.processResponse_();\n }\n }",
"handleInput() {\n this.calculateInputOutput(true);\n }",
"_handleErrorResponse(xhr, callback) {\n var response = xhr.responseText;\n if (_.isString(response) && response !== \"\") {\n try {\n response = JSON.parse(response);\n } catch (e) {\n response = {\n error: e\n };\n }\n }\n callback(response, xhr);\n }",
"function handleStateInput(){\n $('#state-input').change(function(e){\n var selectedState = $(this).find('option:selected').val();\n setState({\n STATE: selectedState\n })\n handleSubmit()\n })\n }",
"function sendAndUpdate(xhr, json) {\n xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');\n xhr.send(json);\n xhr.onreadystatechange = function () {\n if(xhr.readyState == 4){\n if(xhr.status == 200){\n document.getElementById('input_box').innerHTML = \"\";\n document.getElementById('data').innerHTML = \"\";\n if(checkTimeTable == true && checkStaff == false){\n getTimeTable(dataTable, true);\n } else {\n getStaff(dataTable,true);\n }\n }\n }\n }\n}",
"function sendAndUpdate(xhr, json) {\n xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');\n xhr.send(json);\n xhr.onreadystatechange = function () {\n if(xhr.readyState == 4){\n if(xhr.status == 200){\n document.getElementById('input_box').innerHTML = \"\";\n document.getElementById('employees').innerHTML = \"\";\n let employeesTable = document.getElementById('employees');\n getEmployees(employeesTable, true);\n }\n }\n }\n}",
"function responseReceived(e){\n document.getElementById('response').innerHTML = e.target.responseText;\n}",
"function HandleStatus(data, response)\n{\n console.log(response);\n\n //Update selects\n FillUserCars();\n}",
"function handleXhrError(response, ioArgs) {\n if(response instanceof Error){\n if(_ldc) _ldc.hide();\n if(response.dojoType == \"cancel\"){\n //The request was canceled by some other JavaScript code.\n console.debug(\"Request canceled.\");\n }else if(response.dojoType == \"timeout\"){\n //The request took over 5 seconds to complete.\n console.debug(\"Request timed out.\");\n }else{\n //Some other error happened.\n console.error(response);\n if(djConfig.isDebug) alert(response.toSource());\n }\n }\n}",
"send(data) {\n // This is main xhr method\n console.log(\"this is xhr send method\");\n super.send(data);\n this._control.disabled = true;\n this._loaderContainer.classList.remove(\"hidden\");\n }",
"onXHRComplete(inName, inResponse) {\n\t\tconsole.debug(`Loaded raw audio data for '${inName}', doing decode...`);\n\t\tlet ctx = new AudioContext();\n\t\tthis[inName].context = ctx;\n\t\tctx.decodeAudioData(inResponse, \n\t\t\tfunction(inBuffer) { ALL_LOADED_AUDIO.onDecodeAudioSuccess(inName, inBuffer); },\n\t\t\tfunction() { throw `ERROR DECODING AUDIO FOR ${inName}`; }\n\t\t);\n\t}",
"function httpData(xhr, type, dataFilter) {\n\n\t var ct = xhr.getResponseHeader(\"content-type\") || \"\",\n\t xml = type === \"xml\" || !type && ct.indexOf(\"xml\") >= 0,\n\t data = xml ? xhr.responseXML: xhr.responseText;\n\n\t if (xml && data.documentElement.nodeName === \"parsererror\") {\n\t throw \"parsererror\";\n\t }\n\n\t if (typeof dataFilter === 'function') {\n\t data = dataFilter(data, type);\n\t }\n\n\t // The filter can actually parse the response\n\t if (typeof data === \"string\") {\n\t // Get the JavaScript object, if JSON is used.\n\t if (type === \"json\" || !type && ct.indexOf(\"json\") >= 0) {\n\t // Make sure the incoming data is actual JSON\n\t // Logic borrowed from http://json.org/json2.js\n\t if (AJAX_IS_JSON.test(data.replace(AJAX_AT, \"@\").replace(AJAX_RIGHT_SQUARE, \"]\").replace(AJAX_EMPTY, \"\"))) {\n\n\t // Try to use the native JSON parser first\n\t if (window.JSON && window.JSON.parse) {\n\t data = window.JSON.parse(data);\n\n\t } else {\n\t data = ( new Function(\"return \" + data) )();\n\t }\n\n\t } else {\n\t throw \"Invalid JSON: \" + data;\n\t }\n\n\t // If the type is \"script\", eval it in global context\n\t } else if (type === \"script\" || !type && ct.indexOf(\"javascript\") >= 0) {\n\n\t eval.call(window, data);\n\t }\n\t }\n\n\t return data;\n\t }",
"handleStateBuffer(){\n\n if( this.reqPvfOffset == null && this.state.isBufferReady){\n this.send(this.state.buffer);\n this.stat.appendSentToClientTime();\n this.stat.writeToFile(this.state.buffer);\n this.stat.incrementBytesSent(this.state.buffer.length);\n this.state.buffer = null;\n }\n else if(this.reqPvfOffset > 0){\n // console.info(\"pvfOffset :: \" + command.pvfOffset + \" , setting buffer to null\");\n this.state.buffer = null;\n this.state.chunksReminder = null;\n this.state.isToSendBuf = true;\n }\n\n }",
"function gobalAjaxHandler (url, data, callback){\n\t$.ajax({\n\t\turl : url,\n\t\ttype: \"post\",\n\t\tdata : data,\n\t\tsuccess : function(result){\n\t\t\tcallback(result);\n\t\t}\n\t}) ;\n}",
"function attachCallback(req, callback) {\n req.onreadystatechange = function () {\n if (req.readyState == 4) {\n callback(req.status, req.statusText, req.responseText);\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adjust color of all rows, depending whether it is visible or not | function adjustRowsColor(mainTable)
{
if(mainTable=='asns')
mainTable = document.getElementById('asns');
var rows = mainTable.getElementsByTagName("tr");
var rowNumber = 0;
for(var j=0; j<rows.length; j++)
{
if(isVisible(rows[j]))//process only visible rows
{
if(rowNumber%2==0)
rows[j].className = "odd";
else
rows[j].className = "even";
rowNumber++;
}
}
} | [
"function updateRowColor()\n{\n // Re-arrange the colors\n for(j=0,k=0;;j++)\n {\n var str = 'value[' + j + '].status';\n var obj = document.getElementById(str);\n if(obj == null)\n {\n break;\n }\n if(obj.value != HIDE)\n {\n var SelectedRow = document.getElementById('row' + j);\n SelectedRow.className = (k%2==0?\"firstRow\":\"secondRow\");\n k++;\n }\n }\n}",
"function SetAllRowColors()\r\n{\r\n var rows = iDoc.getElementById(\"dataTable\").rows;\r\n for (var i = 1; i < rows.length; i++)\r\n {\r\n SetRowColor(rows[i]);\r\n }\r\n}",
"function SetRowColor(row)\r\n{\r\n if (row.getAttribute(\"selected\") == 1)\r\n {\r\n StyleSetAttributes(row, \"background-color: yellow;\");\r\n }\r\n else if (row.rowIndex % 2 == 1)\r\n {\r\n //StyleSetAttributes(row, \"background-color: lightgoldenrodyellow;\");\r\n StyleSetAttributes(row, \"background-color: #FFF3C3;\");\r\n }\r\n else\r\n {\r\n //StyleSetAttributes(row, \"background-color: #FFFF99;\");\r\n StyleSetAttributes(row, \"background-color: #F6CCC0;\");\r\n }\r\n}",
"colorGrid() {\n for(let i = 0; i < this.columnSize * this.rowSize; i++) {\n if(this.gridArray[i].state == blank) {\n this.gridDOM.children[i].style.backgroundColor = \"#f2f2f2\";\n this.gridDOM.children[i].style.borderColor = \"#959595\";\n } else if(this.gridArray[i].state == unvisited) {\n this.gridDOM.children[i].style.backgroundColor = \"#88FFD1\";\n this.gridDOM.children[i].style.borderColor = \"#3FE1B0\";\n } else if(this.gridArray[i].state == visited) { \n this.gridDOM.children[i].style.backgroundColor = \"#FF848C\";\n this.gridDOM.children[i].style.borderColor = \"#FF505F\";\n } else if(this.gridArray[i].state == start) {\n this.gridDOM.children[i].style.backgroundColor = \"#00DDFF\";\n this.gridDOM.children[i].style.borderColor = \"#0290EE\";\n } else if(this.gridArray[i].state == goal) {\n this.gridDOM.children[i].style.backgroundColor = \"#C588FF\";\n this.gridDOM.children[i].style.borderColor = \"#9059FF\";\n } else if (this.gridArray[i].state == wall) {\n this.gridDOM.children[i].style.backgroundColor = \"black\";\n } else;\n }\n }",
"function setRowColorForPackage(selectorText,doc){//document\r\n\r\n var table = doc.getElementById(\"summaryTableId\" + selectorText);\r\n\r\n if(table){\r\n var rowNum = 0;\r\n for(var j=1, len = table.rows.length; j<len; j++){\r\n if(table.rows[j].style.display.indexOf('none') == -1){\r\n rowNum++;\r\n table.rows[j].className = (rowNum & 1) ? \"prow0\" : \"prow1\";\r\n }\r\n }\r\n }\r\n\r\n}",
"function colorRows() {\n $(document).ready(function(){\n $(\".table1 tr:odd\").css(\"background-color\", \"#BFBFBF\");\n });\n}",
"function setRowColorClassTableSummary(doc)\r\n{\r\n\tvar elements = getElementsByClassName(doc, \"summaryTable\");\r\n\tvar table = elements[0];\r\n if (table){\r\n var rowNum = 0;\r\n for (var i = 1,len = table.rows.length; i < len; i++)\r\n {\r\n if(table.rows[i].style.display.indexOf('none') == -1)\r\n {\r\n rowNum++;\r\n table.rows[i].className = (rowNum & 1) ? \"prow0\" : \"prow1\";\r\n }\r\n }\r\n }\r\n}",
"function colorCheck(rgb, cell) {\n if (cell.style.backgroundColor == rgb) {\n cell.style.backgroundColor = '';\n cell.className = '';\n } else {\n cell.style.backgroundColor = colorPicker.value;\n }\n}",
"function changeColor(e) {\n let column = e.target.cellIndex;\n let row = [];\n\n // start with i = 5 to check for buttom row first\n for (let i = 5; i >= 0; i--) {\n if (tableRow[i].children[column].style.backgroundColor == 'white') {\n row.push(tableRow[i].children[column]);\n if (currentPlayer === 1) {\n row[0].style.backgroundColor = player1Color;\n if (horizontalWin() || verticalWin() || diagonalWin() || diagonalWin2()) {\n playerTurn.textContent = `${player1} WINS!`;\n playerTurn.style.color = player1Color;\n\n return alert(`${player1} WINS!`);\n\n } else if (draw()) {\n playerTurn.textContent = 'Game is a Draw!';\n return alert('DRAW');\n } else {\n playerTurn.textContent = `${player2}'s turn!`\n return currentPlayer = 2;\n }\n\n\n\n\n } else {\n row[0].style.backgroundColor = player2Color;\n if (horizontalWin() || verticalWin() || diagonalWin() || diagonalWin2()) {\n playerTurn.textContent = `${player2} WINS!`;\n playerTurn.style.color = player2Color;\n\n return alert(`${player2} WINS!`);\n\n } else if (draw()) {\n playerTurn.textContent = 'Game is a Draw!';\n return alert('DRAW');\n } else {\n playerTurn.textContent = `${player1}'s turn!`;\n return currentPlayer = 1;\n }\n\n \n }\n }\n }\n}",
"function highlight_curr_row()\r\n{\r\n\r\n\t// temporarily turn off table rendering\r\n\tdata_view.beginUpdate();\r\n\r\n // get current row\r\n\tvar curr_data_row = convert_row_ids([curr_row_selected])[0];\r\n var item = data_view.getItemById(curr_data_row);\r\n var num_cols = item.length;\r\n\r\n // update current row (set to draw box around it -- see select_rows())\r\n item[num_cols-1] = item[num_cols-1] + 10;\r\n\r\n // put row back in table\r\n data_view.updateItem(curr_data_row, item);\r\n\r\n // update previous row\r\n if (prev_row_selected != null) {\r\n\r\n // get previous row\r\n var prev_data_row = convert_row_ids([prev_row_selected])[0];\r\n item = data_view.getItemById(prev_data_row);\r\n\r\n // remove box around previous row\r\n item[num_cols-1] = item[num_cols-1] - 10;\r\n\r\n // put row back in table\r\n data_view.updateItem(prev_data_row, item);\r\n }\r\n\r\n\t// turn on table rendering\r\n\tdata_view.endUpdate();\r\n\r\n}",
"changeColorOfCellsToWhite(){\n for(let y = 0; y < this.height; y++){\n for (let x = 0; x < this.width; x++){\n document.getElementById(`${y}-${x}`).style.backgroundColor = 'white';\n const div = document.createElement('div');\n div.className = 'circle';\n div.className = `${y}-${x}`;\n document.getElementById(`${y}-${x}`).appendChild(div);\n }\n }\n }",
"function updateColor() {\n if( userScore > compScore ) {\n //Player is winning\n table.style.border = \"5px solid #38d020\"\n } else if ( compScore > userScore ) {\n //Computer is winnning\n table.style.border = \"5px solid #d21f1f\"\n } else {\n //If there is a draw\n table.style.border = \"5px solid #363636\"\n }\n}",
"function colorHoldCells(coords, color) {\n colorCells(coords, color, 'hold');\n}",
"function zebraStriping() {\n filterTarget.find(child + ':visible:odd').css({ background: options.zebra.baseColor });\n filterTarget.find(child + ':visible:even').css({ background: options.zebra.altColor });\n }",
"function checkIncorrectSquares() {\n if(this.checked) {\n for (var x = 0; x < colorArray.length; x++) {\n for (var y = 0; y < colorArray.length; y++) {\n var cell = document.getElementById(\"cell\"+x+\"-\"+y);\n if ((cell.style.backgroundColor !== colorArray[x][y].correctColor)\n && cell.style.backgroundColor !== \"lightgray\") {\n colorArray[x][y].incorrect.style.visibility = \"visible\";\n }\n }\n }\n }\n else if(!this.checked){\n for (var a = 0; a< colorArray.length; a++) {\n for (var b = 0; b < colorArray.length; b++) {\n colorArray[a][b].incorrect.style.visibility = \"hidden\";\n }\n }\n }\n }",
"function showColors(player){\n var other = (player + 1) % 2;\n var table1 = document.getElementById(\"top_table\");\n for(var i = 0; i < redTiles[other].length; i++){\n var loc = redTiles[other][i]; //Set any relevant tiles to red\n table1.rows[loc[0]].cells[loc[1]].style.backgroundColor = 'red';\n }\n for(var i = 0; i < whiteTiles[other].length; i++){\n loc = whiteTiles[other][i]; //Set any relevant tiles to white\n table1.rows[loc[0]].cells[loc[1]].style.backgroundColor = 'white';\n }\n\n var table2 = document.getElementById(\"bottom_table\");\n for(var i = 0; i < redTiles[player].length; i++){\n var loc = redTiles[player][i]; //Set any relevant tiles to red\n table2.rows[loc[0]].cells[loc[1]].style.backgroundColor = 'red';\n }\n for(var i = 0; i < whiteTiles[player].length; i++){\n loc = whiteTiles[player][i]; //Set any relevant tiles to white\n table2.rows[loc[0]].cells[loc[1]].style.backgroundColor = 'white';\n }\n}",
"function paintBlock(){\n\tfor(var i = 0; i < 4; i++){\n\t\tif(currentBlock[i].x < 0 || currentBlock[i].x > 19 || currentBlock[i].y < 0 || currentBlock[i].y > 9){\n\t\t\tcontinue;\n\t\t}\n\t\tboardGui.rows[currentBlock[i].x].cells[currentBlock[i].y].style.backgroundColor = \"rgba(255,0,0,0.3)\"; \n\t}\n}",
"function highlightRow(name) {\n var row = document.getElementById('basket-item-' + name);\n row.style.backgroundColor = 'rgba(0, 128, 0, 0.39)';\n row.scrollIntoView();\n setTimeout(function() {\n row.style.backgroundColor = 'rgba(0, 0, 0, 0)'\n }, 500);\n}",
"function OnClickRowEnable(enabled)\r\n{\r\n var rows = iDoc.getElementById(\"dataTable\").rows;\r\n\r\n for (var i = 1; i < rows.length; i++)\r\n {\r\n if (rows[i].getAttribute(\"selected\") == 1)\r\n {\r\n if (enabled == true) StyleRemoveAttributes(rows[i], \"color\"); else StyleSetAttributes(rows[i], \"color: gray;\");\r\n rows[i].setAttribute(\"enabled\", (enabled == true) ? 1 : 0);\r\n changesMade = true;\r\n }\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
show a hotel's detailed view | function showHotelDetails(view, hotelView) {
// render the hotel details view, passing in the hotel view so details view knows where to display from and which hotel to show
view.views['hotel-details'].render(hotelView);
} | [
"retrieveHotel(id){\n return axios.get(`${CONST_API_URL}/showHotelDetails/${id}`);\n }",
"function ViewRooms() { }",
"function viewDetail(id) {\n container.style.visibility = \"visible\";\n wrapper.style.visibility = \"visible\";\n\n // room detail\n fetch(apiRoom)\n .then((response) => response.json())\n .then(function (rooms) {\n\t let roomData = rooms.filter((allRooms) => {\n\t\treturn (allRooms.id == id);\n\t }).map((data) => {\n\t\treturn `<div class=\"info-header\">\n\t <h1>${data.name}<button class=\"close-btn\" onclick=\"hideDetail()\">×</button></h1>\n\t <div class=\"main-info\">\n\t <div class=\"name\">\n\t <i class=\"name-icon\"></i>\n\t <div class=\"name-text\">${data.houseOwner}</div>\n\t </div>\n\t <div class=\"phone\">\n\t <i class=\"phone-icon\"></i>\n\t <div class=\"phone-text\">${data.ownerPhone}</div>\n\t </div>\n\t <div class=\"address\">\n\t <i class=\"address-icon\"></i>\n\t <div class=\"address-text\">${data.address}</div>\n\t </div>\n\t </div>\n\t <h2>${data.price}</h2>\n\t </div>\n\t <div class=\"info\">\n\t <div class=\"info-type\">\n\t <h3>Loại phòng</h3>\n\t <p>${data.category}</p>\n\t </div>\n\t <div class=\"info-area\">\n\t <h3>Diện tích</h3>\n\t <p>${data.area}</p>\n\t </div>\n\t <div class=\"info-deposit\">\n\t <h3>Đặt cọc</h3>\n\t <p>${data.deposit}</p>\n\t </div>\n\t <div class=\"info-capacity\">\n\t <h3>Sức chứa</h3>\n\t <p>${data.capacity}</p>\n\t </div>\n\t <div class=\"info-electric\">\n\t <h3>Tiền điện</h3>\n\t <p>${data.electricPrice}</p>\n\t </div>\n\t <div class=\"info-water\">\n\t <h3>Tiền nước</h3>\n\t <p>${data.waterPrice}</p>\n\t </div>\n\t <div class=\"info-fee\">\n\t <h3>Chi phí khác</h3>\n\t <p>${data.otherPrice}</p>\n\t </div>\n\t <div class=\"info-status\">\n\t <h3>Tình trạng</h3>\n\t <p>${data.status}</p>\n\t </div>\n\t <div class=\"info-description\">\n\t <h3>Mô tả chi tiết</h3>\n\t <p>${data.description}</p>\n\t </div>\n\t </div>`;\n \t });\n\t container.innerHTML = \"\";\n\t container.innerHTML = roomData; \n\t});\n}",
"function showInfoWindow() {\n var marker = this;\n hotels.getDetails({placeId: marker.placeResult.place_id}, function(place, status) {\n if (status !== google.maps.places.PlacesServiceStatus.OK) {\n return;\n }\n hotelInfoWindow.open(hotelMap, marker);\n buildIWContent(place);\n });\n}",
"function openShowtimeView(e) {\r\n\t\tvar showtime = e.source.showtime;\r\n\t\tvar selectSeatsViewController = Alloy.createController('SelectSeatsView', {showtime:showtime, movie:movie});\r\n\t\tcontext.openNewWindow(selectSeatsViewController.getView());\r\n\t}",
"retrieveReviewsForHotelById(id){\n return axios.get(`${CONST_API_URL}/showReviewForHotel/${id}`)\n }",
"static get hotelList() {\n return HotelList;\n }",
"function show(req, res) {\n var yelp = new Yelp({\n consumer_key: oauth_consumer_key,\n consumer_secret: consumerSecret,\n token: oauth_token,\n token_secret: tokenSecret\n });\n\n // Call YELP API\n yelp.search({\n location: req.params.id,\n sort: 2, // Highest Rated\n limit: 40,\n term: 'nightlife'\n }, function (err, data) {\n if (err) {\n console.log(\"Error while getting Yelp results\");\n console.log(err);\n return res.status(500).send(err);\n }\n var venuesList = [];\n for (var i = 0; i < data.total; i++) {\n venuesList.push({\n yelpId: data.businesses[i].id,\n name: data.businesses[i].name,\n rating: data.businesses[i].rating,\n url: data.businesses[i].url,\n imageUrl: data.businesses[i].image_url,\n location: data.businesses[i].location.city,\n description: data.businesses[i].snippet_text\n });\n }\n _search2.default.find({}, function (err, resFind) {\n var result = mergeLists(venuesList, resFind);\n //console.log(result);\n console.log(\"Returning result of size: \" + result.length);\n return res.status(200).send(result);\n });\n });\n}",
"function show(req, res){\n Listing.findById(req.params.id).populate('listing'){\n if(err) return console.log(err)\n res.json(listing)\n }\n }",
"function details() {\n\n var storeID = request.httpParameterMap.StoreID.value;\n var store = dw.catalog.StoreMgr.getStore(storeID);\n\n var pageMeta = require('~/cartridge/scripts/meta');\n pageMeta.update(store);\n\n app.getView({Store: store})\n .render('storelocator/storedetails');\n\n}",
"function showTripDetails(trip) {\n\tconst content = `\t\n\t\t<section class=\"trip-details\">\n\t\t\t\n\t\t</section>\n\t`\n\t$('main').html(content);\n\t$('.trip-details').html(tripToHtml(trip, false));\t\n\t//$('.trip-info').html(tripToHtml(trip));\n}",
"function hotelNames(destination){\n destination.hotels.forEach(function(hotel){\n const div = document.querySelector('#hotel')\n //div.innerHTML = ('')\n const pTag = document.createElement('p')\n pTag.className = 'hotel-list'\n pTag.innerText = `Hotel: ${hotel.name}`\n pTag.dataset.id = hotel.id\n div.append(pTag)\n\n renderItineraryHotel(hotel)\n\n pTag.addEventListener('click', function(e){\n //console.log(e.target)\n //debugger\n if (e.target.className === 'hotel-list'){\n const id = e.target.dataset.id\n const div = document.querySelector('#hotel')\n div.innerHTML = ('')\n fetchHotelDetails(id)\n\n }\n })\n })\n }",
"async show(req, res) {\n // Get all oportunities\n const { data } = await pipedrive_api.get();\n // Array to filter which data receive\n const oportunities = [];\n\n if (data.data) {\n data.data.forEach(client => {\n let {\n title,\n value,\n status,\n won_time,\n person_id: { name },\n } = client;\n oportunities.push({ title, value, status, won_time, name });\n });\n }\n return res.json(oportunities);\n }",
"function displayDetailedRecipe(responseRecipe) {\n\n window.open(`${responseRecipe.sourceUrl}`,\"_blank\");\n\n}",
"function viewMoreHandler(event){\n\t\tvar target = $(event.currentTarget).find('a:visible').attr('id');\n\t\tif(target === \"viewMoreLink\") {\n\t\t\tshowLanding(partnerLandingGridLimit, partnerDetails.length, true);\t\n\t\t\t$('#viewMoreLink').hide();\n\t\t\t$('#viewLessLink').show();\n\t\t} else {\n\t\t\tviewLessItems();\n\t\t\t$('#viewMoreLink').show();\n\t\t\t$('#viewLessLink').hide();\t\t\n\t\t}\n\t}",
"function showDetails(tile) {\n getTransitionsFor(tile).then(function(transitions){\n var enter = transitions.enter,\n details = document.getElementById(\"details\");\n\n details.onclick = hideDetails = function() {\n if (enter.isActive() ) enter.pause();\n transitions.leave.restart();\n };\n\n enter.restart();\n });\n }",
"show(iemId) {\n return Api().get(`iems/${iemId}`)\n }",
"function makeDetailsVisible() {\n setDetailView(\"show-details\");\n setBlurry(\"blurred-out\");\n }",
"function setupView() {\n // set home button view point to initial extent\n var homeButton = new Home({\n view: view,\n viewpoint: new Viewpoint({\n targetGeometry: initialExtent\n })\n });\n \n var track = new Track({\n viewModel:{\n view:view,\n scale: 100000\n }\n });\n\n // layer list\n var layerList = new LayerList({\n view: view, \n listItemCreatedFunction: function(event){\n var item = event.item;\n \n if (item.title === \"Trail Heads\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"th\"),\n open: true\n }\n } else if (item.title === \"Point of Interest\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"poi\"),\n open: true\n }\n } else if (item.title === \"Visitor Recommendations\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"rec\"),\n open: true\n }\n } else if (item.title === \"Roads\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"road\"),\n open: true\n }\n } else if (item.title === \"Trails\"){\n item.open = true;\n item.panel = {\n content: document.getElementById(\"trail\"),\n open: true\n }\n }\n }\n });\n \n // expand layer list\n layerExpand = new Expand({\n expandIconClass: \"esri-icon-layers\",\n expandTooltip: \"Turn on and off Map Layers\",\n expanded: false,\n view: view,\n content: layerList,\n mode: \"floating\", \n group:\"top-left\"\n });\n \n\n // expand widget for edit area\n editExpand = new Expand({\n expandIconClass: \"esri-icon-edit\",\n expandTooltip: \"Add a Visitor Recommendation\",\n expanded: false,\n view: view,\n content: editArea,\n mode: \"floating\",\n group:\"top-left\"\n });\n \n // expand widget for query\n var query = document.getElementById(\"info-div\");\n queryExpand = new Expand ({\n expandIconClass: \"esri-icon-filter\",\n expandTooltip: \"Filter Points of Interest\",\n expanded: false,\n view: view,\n content: query,\n mode: \"floating\",\n group:\"top-left\"\n });\n \n // search widget\n var searchWidget = new Search({\n view:view,\n allPlaceholder: \"Search for SNP Places\",\n locationEnabled: false,\n sources: [{\n featureLayer: poi,\n resultSymbol: {\n type: \"simple-marker\",\n color: [0, 0, 0, 0],\n size: \"17px\",\n style: \"square\",\n outline: {\n color: [0, 255, 255, 1],\n width: \"2px\"\n }\n },\n outFields: [\"*\"],\n popupTemplate: poiP\n }, {\n featureLayer:aoi,\n resultSymbol: {\n type: \"simple-marker\",\n color: [0, 0, 0, 0],\n size: \"17px\",\n style: \"square\",\n outline: {\n color: [0, 255, 255, 1],\n width: \"2px\"\n }\n },\n outFields: [\"*\"],\n popupTemplate: aoiP\n }, {\n featureLayer: trailheads,\n resultSymbol: {\n type: \"simple-marker\",\n color: [0, 0, 0, 0],\n size: \"17px\",\n style: \"square\",\n outline: {\n color: [0, 255, 255, 1],\n width: \"2px\"\n }\n },\n outFields: [\"*\"],\n popupTemplate: trailheadsP\n }, {\n featureLayer:trails,\n resultSymbol: {\n type: \"simple-line\",\n color: [0, 255, 255, 1],\n width: \"2px\"\n },\n outFields: [\"*\"],\n popupTemplate: trailsP\n }]\n });\n // search expand\n searchExpand = new Expand({\n expandIconClass: \"esri-icon-search\",\n expandTooltip: \"Search for SNP Places\",\n view: view,\n content: searchWidget,\n mode: \"floating\",\n group:\"top-left\"\n });\n \n // add all widgets to view \n view.ui.move( \"zoom\", \"bottom-right\");\n view.ui.add([homeButton, track, layerExpand], \"bottom-right\")\n view.ui.add([searchExpand, queryExpand, layerExpand, editExpand],\"top-left\");\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loading the prices and number of units per product from the localStorage | function load(){
// it the web browser supports localStorage
if(typeof(Storage) !== "undefined"){
var finalPrice = 0;
// creating html ids for each of the product
for (var i = 0; i < uniqueSes.length; i++) {
var id = "nrUnits" + uniqueSes[i]; // number of units id
var id_ppu = "ppu" + uniqueSes[i]; // price per unit id
var id_totalPrice = "totalPrice" + uniqueSes[i]; //totalprice per unit id
// if there is an element with the id above, then:
try{
//set the total price for a specific pizza
var totalPrice = document.getElementById(id_ppu).innerHTML * map.get(id);
}catch(err){
}
// final price is a sum of all total prices
finalPrice += totalPrice;
// storing number of units of a procust (id) and total price for that product(id_totalPrice) in localStorage
localStorage.setItem(id, map.get(id));
localStorage.setItem(id_totalPrice, totalPrice);
// getting the no. of units and total price for each product from the localstorage and setting them up in the view.
document.getElementById(id).innerHTML = localStorage.getItem(id);
document.getElementById(id_totalPrice).innerHTML = localStorage.getItem(id_totalPrice) + "£";
// if we reach the last element, then we have to set up the final price
if(i+1 == uniqueSes.length){
finalPrice = finalPrice.toFixed(2);
localStorage.setItem("finalPrice", finalPrice);
document.getElementById("finalPrice").innerHTML = "Final price is: " + localStorage.getItem("finalPrice") + "£";
}
}
}
// if the browser doesn't support localStorage
else {
alert("Sorry, your browser does not support Web Storage...");
}
} | [
"static getDataFromLS(){\r\n let products;\r\n if(localStorage.getItem('products') === null){\r\n products = []\r\n }else{\r\n products = JSON.parse(localStorage.getItem('products'));\r\n }\r\n return products;\r\n }",
"function getOfferPrice() {\n return localStorage.getItem('Price');\n }",
"function onloadCartNumbers() {\n let productNumbers = localStorage.getItem(\"cartNumbers\");\n\n if (productNumbers) {\n document.querySelector(\".cart-container .notificationBadge\").textContent = productNumbers;\n }\n}",
"function cartNumbers(product){\n console.log(product);\n let prodNumber = localStorage.getItem('cartNumbers');\n\n prodNumber = parseFloat(prodNumber); // Converts prodNumber to an integer from a string\n\n if (prodNumber){ // if already exist in the local storage\n localStorage.setItem('cartNumbers', prodNumber + 1);\n document.querySelector('#cart-items-int').textContent = prodNumber + 1;\n }\n else{\n localStorage.setItem('cartNumbers', 1);\n document.querySelector('#cart-items-int').textContent = 1\n }\n setItems(product);\n}",
"function loadProducts() {\n API.getProducts()\n .then(res => {\n setProducts(res.data);\n })\n .catch(err => console.log(err));\n API.getAverage()\n .then(res => {\n res.data[0] ?\n setAverage(res.data[0].average.toFixed(2)) :\n setAverage(0)\n })\n }",
"function getStocks(){\n return JSON.parse(localStorage.getItem(STOCK_STORAGE_NAME));\n}",
"function updateStoredState() {\r\n localStorage.setItem('displayedProducts', JSON.stringify(displayedProducts));\r\n localStorage.setItem('currentVoteCount', JSON.stringify(currentVoteCount));\r\n}",
"function calculaTotal(){\n let arrayProdutos = JSON.parse(localStorage.getItem(\"carrinho\"));\n let valor = 0\n let quantidades = document.querySelectorAll(\"input\")\n // console.log(quantidades)\n\n let i=0\n // iterando no array dos produtos para pegar a quantidade de cada um\n quantidades.forEach(element => {\n arrayProdutos[i].qntd = parseInt(element.value)\n valor += parseInt(element.value) * arrayProdutos[i].preco\n i++\n });\n\n localStorage.setItem(\"carrinho\", JSON.stringify(arrayProdutos));\n $(\"#valorTotal\").text(\"Valor Total: R$\"+ valor +\",00\")\n}",
"function saveCartToLocalStorage() {\n localStorage.setItem('cart', JSON.stringify(Product.allProductsInCart));\n}",
"function loadKittens() {\n kittens = JSON.parse(localStorage.getItem(\"kittens\"))\n if (!kittens) { kittens = [] }\n}",
"function setAmount() {\n localStorage.setItem(\"amount\", JSON.stringify(amount)); //updates the cart\n }",
"function getOrders(){\n return JSON.parse(localStorage.getItem(\"orders\"));\n}",
"function loadQuantity(id) {\n document.getElementById(id).value = window.sessionStorage.getItem(id);\n}",
"function loadBookData() {\n bookDataFromLocalStorage = JSON.parse(localStorage.getItem(\"bookData\"));\n if (bookDataFromLocalStorage == null) {\n bookDataFromLocalStorage = bookData;\n localStorage.setItem(\"bookData\", JSON.stringify(bookDataFromLocalStorage));\n }\n}",
"function loadSettingsFromStorage() {\n // Set default localStorage if first time load\n if (Object.keys(localStorage).length != Object.keys(DEFAULT_SETTINGS).length) {\n deepCopy(DEFAULT_SETTINGS, localStorage);\n }\n deepCopy(localStorage, settings);\n prices = settings['prices'].split(',');\n upgrades = settings['upgrades'].split(',').map((v) => v === 'true' ? true : false);\n }",
"static async getStoreInventory() {\n const storeInventory = storage.get(\"products\").value()\n return storeInventory\n }",
"function setUnits() {\n switch (localStorage.activeTemp) {\n case 'cel':\n currentWeatherBlock.changeUnitsToCelsius(); // refresh current forecast\n dailyWeatherBlock.switchUnitsToCelsius(); // refresh daily forecast\n document.querySelector('.temp-celsius').classList.add('active');\n document.querySelector('.temp-fahrenheit').classList.remove('active');\n break;\n case 'fahr':\n currentWeatherBlock.changeUnitsToFahrenheit();// refresh current forecast\n dailyWeatherBlock.switchUnitsToFahrenheit();// refresh daily forecast\n document.querySelector('.temp-fahrenheit').classList.add('active');\n document.querySelector('.temp-celsius').classList.remove('active');\n break;\n default:\n return null;\n }\n return null;\n }",
"function setItems(product) {\r\n //8 console.log(\"inside of set Items function\");\r\n //8 console.log(\"my prodcut function is\", product);\r\n //8 this will print inside of my set item function, you will see my product is with the name of the product you clicked on\r\n\r\n //8.3 when ever we click on the set item function. this will check if it exist already some items or not\r\n //8.3 the item you want to get product incart in local sotrage to check if it exist and see if something in our local storage\r\n //8.3 if we are trying to get something from our local storage we type this console.log(\"My cartitems are\", cartitems);\r\n //8.3 this will print in console my cart item are with the name,price.. of the item\r\n //8.3 this is in a json foramt\r\n let cartItems = localStorage.getItem('productsInCart');\r\n //8.4 this is what to pass in from json into javascript object\r\n //8.4 we are updating this json\r\n cartItems = JSON.parse(cartItems);\r\n //8.5 if cart item is equal to null this means something is already in our cart/localstorage\r\n //8.5 then we going to do a check\r\n if (cartItems != null) {\r\n\r\n if (cartItems[product.tag] == undefined) {\r\n //8.7 this is to update my cart item what ever in my local sotrage \r\n cartItems = {\r\n //8.7 grab what ever from my cart items before and then using the rest operator from js\r\n ...cartItems,\r\n //8.7 and then add this new product \r\n [product.tag]: product\r\n }\r\n }\r\n //8.7 this is to incrase 1 is already in there\r\n cartItems[product.tag].inCart += 1;\r\n } else {\r\n //8.1 this is the first time you going to click \r\n product.inCart = 1;\r\n cartItems = {\r\n //8.6 setting the product in cart to be 1\r\n [product.tag]: product\r\n }\r\n }\r\n //8.2 we dont want to pass javascript object. we use JSON.stringify to pass as json object on local sotrage. \r\n //8.2 it will show the name, price ... with incart 1.\r\n localStorage.setItem(\"productsInCart\", JSON.stringify(cartItems));\r\n}",
"function getProductPrices()\n {\n $.getJSON(productPricesEndpoint, function (data) {\n prices = data;\n\n updateProductPrices();\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
wrapping for both directions = ((chord index + transpose amount(+1 or 1)) + 12)% 12 ((k+modeOption)+12)%12 | function handleTranspose(mode) {
console.log("Transpose: "+mode)
let modeOption
if (mode=='up') {
modeOption = 1
}
else if(mode=='down'){
modeOption = -1
}
//walk through words and checking type chord
for (let i = 0; i < words.length; i++) {
let sharpFlatNote = 1
if (words[i].type==="chord"){
//console.log("Before: " + words[i].word)
if(words[i].word.includes("#") || words[i].word.includes("b")){
sharpFlatNote = 2
}
if(words[i].word.includes("/")){
for(let j =0;j<semitones.length;j++){
if (words[i].word.substring(words[i].word.indexOf("/")+1,words[i].word.length)==semitones[j].chord) {
words[i].word = words[i].word.replace(semitones[j].chord,semitones[((j+modeOption)+12)%12].chord)
break
}
}
}
for (let k =0; k<semitones.length;k++) {
//console.log(words[i].word)
if (words[i].word.substring(0,sharpFlatNote)==semitones[k].chord) {
words[i].word = words[i].word.replace(semitones[k].chord, semitones[((k+modeOption)+12)%12].chord)
break
}
else if (words[i].word.substring(0,sharpFlatNote)==semitones[k].flat) {
words[i].word = words[i].word.replace(semitones[k].flat,semitones[((k+modeOption)+12)%12].chord)
break
}
//console.log("after replace: "+words[i].word)
}
}
}
} | [
"function getChord() {\n //get all playing keys\n var keys = document.querySelectorAll(\".key.playing\");\n\n //if less than 2 keys there is no chord, return blank\n if (keys.length < 2) {\n return \"\";\n }\n\n //get bass note (lowest playing note)\n var bass = keys[0].dataset.note;\n //get indicies of currently playing notes\n var indicies = [];\n for (i = 0; i < keys.length; i++) {\n indicies.push(keys[i].dataset.pos);\n }\n\n //test every note as a potential root in order\n for (i = 0; i < keys.length; i++) {\n //set current root to test\n var root = i;\n\n //get intervals of all notes from root; stored as a set\n let intervals = new Set();\n for (j = 0; j < indicies.length; j++) {\n //get interval between root and current note\n //if current note is < root shift it an octave up for calculations\n if ((indicies[j] % 12) < (indicies[root] % 12)) {\n var interval = Math.abs(((indicies[j] % 12) + 12) - (indicies[root] % 12));\n }\n else {\n var interval = Math.abs((indicies[j] % 12) - (indicies[root] % 12));\n }\n //mudolo to remove compound intervals\n interval = interval % 12;\n //add interval to set of intervals\n intervals.add(interval);\n }\n\n //loop through every chord in the chord db\n for (j = 0; j < chords.length; j++) {\n //if match found return chord\n if (chordEq(chords[j].intervals, intervals)) {\n //add root note and notation to chord display\n var chord = keys[root].dataset.note + chords[j].notation;\n //if bass note is different from the root add it\n if (bass != keys[root].dataset.note) {\n chord += \"\\\\\" + bass;\n }\n\n return chord\n }\n }\n }\n \n //nothing found; return blank\n return \"\";\n}",
"function rotate90CCW1(m) {\n m = cloneDeep(m);\n const size = m.length;\n // console.log(m.map(i => i.join(', ')).join('\\n'), '\\n');\n\n for (let i = 0; i < Math.floor(size / 2); i++) {\n const first = i;\n const last = size - 1 - i;\n for (let j = first; j < last; j++) {\n const k = j - i;\n const tmp = m[first][last - k];\n // console.log('first:', first, 'last:', last, 'k:', k, 'tmp:', tmp, '\\n');\n\n m[first][last - k] = m[last - k][last];\n m[last - k][last] = m[last][first + k];\n m[last][first + k] = m[first + k][first];\n m[first + k][first] = tmp;\n // console.log(m.map(i => i.join(', ')).join('\\n'), '\\n');\n }\n }\n\n return m;\n}",
"rotate() {\r\n //each piece has a different center of rotation uhoh, see image for reference\r\n //https://vignette.wikia.nocookie.net/tetrisconcept/images/3/3d/SRS-pieces.png/revision/latest?cb=20060626173148\r\n for (let c in this.coords) {\r\n this.coords[c][0] += this.rotationIncrements[this.rotationIndex][c][0]\r\n this.coords[c][1] += this.rotationIncrements[this.rotationIndex][c][1]\r\n }\r\n this.rotationIndex = (this.rotationIndex + 1) % 4\r\n }",
"function immediateRenderChord(MIDINumbers, duration = \"\"){\n\tmusicalElements = \"[\";\n\tfor(var i = 0; i < MIDINumbers.length; i++){\n\t\tmusicalElements += MIDINotes.MIDINoteToABCNote(MIDINumbers[i]) + duration + \" \";\n\t}\n\tmusicalElements += \"]\";\n\t\n\trenderNotation();\n}",
"function C() {\n if (tape[index] !== 1) {\n tape[index] = 1;\n index += 1;\n return D;\n } else {\n tape[index] = 0;\n index += 1;\n return C;\n }\n}",
"function jtabChord (token) {\n\n this.scale = jtab.WesternScale;\n this.baseNotes = this.scale.BaseNotes;\n this.baseChords = jtab.Chords;\n this.chordArray = null;\n this.isValid = false;\n\n this.fullChordName = token;\n this.isCustom = ( this.fullChordName.match( /\\%/ ) != null )\n this.isCaged = ( this.fullChordName.match( /\\:/ ) != null )\n\n\n if (this.isCaged) {\n var parts = this.fullChordName.split(':');\n this.chordName = parts[0];\n this.cagedPos = parts[1];\n } else if (this.isCustom){\n var parts = this.fullChordName.match( /\\[(.+?)\\]/ );\n if(parts){\n this.chordName = parts[1];\n } else {\n this.chordName = '';\n }\n } else {\n this.chordName = this.fullChordName;\n this.cagedPos = 1;\n }\n this.rootExt = this.chordName.replace(/^[A-G#b]{1,2}/,'');\n this.rootNote = this.chordName.substr(0, this.chordName.length - this.rootExt.length);\n var baseNoteInfo = this.baseNotes[this.rootNote];\n if (baseNoteInfo) {\n this.baseName = baseNoteInfo[0] + this.rootExt;\n this.cagedBaseShape = baseNoteInfo[1];\n this.cagedBaseFret = baseNoteInfo[2];\n } else {\n this.cagedBaseShape = '';\n this.cagedBaseFret = 0;\n }\n if ( ( this.isCaged ) && ( this.cagedPos > 1 ) ) {\n this.setCagedChordArray();\n } else if (this.isCustom){\n this.setCustomChordArray();\n } else {\n this.setChordArray(this.baseName);\n }\n}",
"function positionCorner4(cube) {\n //a through b\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n if (checkWhiteCross(cube) && checkCorner4(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W') && (cube[down][0][2] == 'W')) {\n //console.log(a + \" \" + b);\n //console.log(outputCross(a, b, -1, -1, -1, -1, -1));\n var txt = outputCross(a, b, -1, -1, -1, -1, -1);\n commandPositionWhiteCorner4 += txt;\n return;\n }\n\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"b\");\n\n //a through c\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n for(var c = -1; c < 12; c++) {\n singleRotation(c);\n\n if (checkWhiteCross(cube) && checkCorner4(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W') && (cube[down][0][2] == 'W')) {\n //console.log(a + \" \" + b + \" \" + c);\n //console.log(outputCross(a, b, c, -1, -1, -1, -1));\n var txt = outputCross(a, b, c, -1, -1, -1, -1);\n commandPositionWhiteCorner4 += txt;\n return;\n }\n\n singleRotation(11-c);\n } //c\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"c\");\n\n //a through d\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n for(var c = -1; c < 12; c++) {\n singleRotation(c);\n\n for(var d = -1; d < 12; d++) {\n singleRotation(d);\n\n if (checkWhiteCross(cube) && checkCorner4(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W') && (cube[down][0][2] == 'W')) {\n //console.log(a + \" \" + b + \" \" + c + \" \" + d);\n //console.log(outputCross(a, b, c, d, -1, -1, -1));\n var txt = outputCross(a, b, c, d, -1, -1, -1);\n commandPositionWhiteCorner4 += txt;\n return;\n }\n\n singleRotation(11-d);\n } //d\n singleRotation(11-c);\n } //c\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"d\");\n}",
"changeKeyFromChord(chord=this.lastChord) {\n // common key modulation\n let keys = this.chordToKeys[chord.toString()]\n\n if (!keys) {\n // chord doesn't have key, eg. A#m\n return\n }\n\n keys = keys.filter(key => key.name() != this.keySignature.name())\n if (!keys.length) {\n // some chords are only in one key\n return\n }\n\n let newKey = keys[this.generator.int() % keys.length]\n\n // console.warn(`Going from ${this.keySignature.name()} to ${newKey.name()}`)\n this.keySignature = newKey\n this.scale = this.keySignature.defaultScale()\n this.chords = null\n }",
"function stashChord(d) {\n\t\t\t\td.source0 = {x:d.source.x, dx:d.source.dx};\n\t\t\t\td.target0 = {x:d.target.x, dx:d.target.dx};\n\t\t\t}",
"function positionCorner3(cube) {\n //a through b\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n if (checkWhiteCross(cube) && checkCorner3(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W')) {\n //console.log(a + \" \" + b);\n //console.log(outputCross(a, b, -1, -1, -1, -1, -1));\n var txt = outputCross(a, b, -1, -1, -1, -1, -1);\n commandPositionWhiteCorner3 += txt;\n return;\n }\n\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"b\");\n\n //a through c\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n for(var c = -1; c < 12; c++) {\n singleRotation(c);\n\n if (checkWhiteCross(cube) && checkCorner3(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W')) {\n //console.log(a + \" \" + b + \" \" + c);\n //console.log(outputCross(a, b, c, -1, -1, -1, -1));\n var txt = outputCross(a, b, c, -1, -1, -1, -1);\n commandPositionWhiteCorner3 += txt;\n return;\n }\n\n singleRotation(11-c);\n } //c\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"c\");\n\n //a through d\n for (var a = -1; a < 12; a++) {\n singleRotation(a);\n\n for(var b = -1; b < 12; b++) {\n singleRotation(b);\n\n for(var c = -1; c < 12; c++) {\n singleRotation(c);\n\n for(var d = -1; d < 12; d++) {\n singleRotation(d);\n\n if (checkWhiteCross(cube) && checkCorner3(cube) && (cube[down][2][0] == 'W') && (cube[down][0][0] == 'W')) {\n //console.log(a + \" \" + b + \" \" + c + \" \" + d);\n //console.log(outputCross(a, b, c, d, -1, -1, -1));\n var txt = outputCross(a, b, c, d, -1, -1, -1);\n commandPositionWhiteCorner3 += txt;\n return;\n }\n\n singleRotation(11-d);\n } //d\n singleRotation(11-c);\n } //c\n singleRotation(11-b);\n } //b\n singleRotation(11-a);\n } //a\n\n //console.log(\"d\");\n}",
"rotate270() {\n const { x } = this;\n this.x = this.y;\n this.y = -x;\n }",
"step() {\n const r0 = this.rotors[0];\n const r1 = this.rotors[1];\n r0.step();\n // The second test here is the double-stepping anomaly\n if (r0.steps.has(r0.pos) || r1.steps.has(Utils.mod(r1.pos + 1, 26))) {\n r1.step();\n if (r1.steps.has(r1.pos)) {\n const r2 = this.rotors[2];\n r2.step();\n }\n }\n }",
"function COLUMNLETTER(index) {\n\n if (!ISNUMBER(index)) {\n return error$2.value;\n }\n\n // The column is determined by applying a modified Hexavigesimal algorithm.\n // Normally BA follows Z but spreadsheets count wrong and nobody cares.\n\n // Instead they do it in a way that makes sense to most people but\n // is mathmatically incorrect. So AA follows Z which in the base 10\n // system is like saying 01 follows 9.\n\n // In the least significant digit\n // A..Z is 0..25\n\n // For the second to nth significant digit\n // A..Z is 1..26\n\n var converted = \"\",\n secondPass = false,\n remainder,\n value = Math.abs(index);\n\n do {\n remainder = value % 26;\n\n if (secondPass) {\n remainder--;\n }\n\n converted = String.fromCharCode(remainder + 'A'.charCodeAt(0)) + converted;\n value = Math.floor((value - remainder) / 26);\n\n secondPass = true;\n } while (value > 0);\n\n return converted;\n}",
"function letter_spacing(row_nr) {\n if (row_nr % 2) {\n return [\"0\",\"1\"];\n } else {\n return [\"1\",\"0\"];\n }\n }",
"transpose (steps) {\n\n this.notes = this.notes.map((n) => {\n\n n.note += steps;\n return n;\n });\n return this;\n }",
"function printChords(inp){\n var result = [\"\",\"\"]; //output lines\n var str = inp; //local copy of input for modifying\n var offset = 0; //offset caused by pasting the last chord (e.g. Esus2 shifts the following E 5 characters over)\n\n while(str.indexOf(\"[\") != -1){\n //all chords are of the format [chord], find it by finding [ and ]\n var leftBrace = str.indexOf(\"[\");\n var rightBrace = str.indexOf(\"]\");\n\n //take the lyrics from start to [\n result[0] += str.substring(0,leftBrace);\n\n //pad spaces to where the chord belongs on the chord line\n for(i = offset; i < leftBrace; i++)\n result[1] += \" \";\n if(leftBrace < offset) result[1] += \" \"; //if no padding was added (two chords in a row), add a space\n\n //get the chord from between the braces\n result[1] += str.substring(leftBrace+1, rightBrace);\n offset = rightBrace-leftBrace;\n\n //str = remainder of string after ]\n str = str.substring(rightBrace+1, 999).trim();\n }\n result[0] += str;\n console.log(result[1] .green);\n console.log(result[0] .yellow);\n}",
"shiftData(data, angle) {\n return _.each(data, function(set) {\n var initial = set.initial[0];\n\n set.mercator[0] = App.arithmetics.wrapTo180(initial + App.arithmetics.wrapTo180(angle));\n\n return set;\n });\n }",
"indecesToAlgebraic(posRow, posCol){\n let alphaCols = 'abcdefgh';\n\n if(typeof posRow !== 'number'){//} && posCol === undefined){\n [posRow,posCol] = posRow;\n }\n let row = 8 - posRow; //TODO fix this weakness\n // if(this.boardSize !== undefined){\n // let row = this.boardSize - posRow;\n // }\n\n\n let col = alphaCols[posCol];\n\n return col + row;\n }",
"function DrawChord(trips){\n\tvar streetnames = []\n\tfor (var i = 0; i < trips.length; i++) {\n\t\tfor (var j = 0; j < trips[i].streetnames.length; j++) {\n\t\t\tstreetnames.push(trips[i].streetnames[j]);\n\t\t}\n\t}\n\t\n\tvar myConfig = {\n\t\t\"type\": \"chord\",\n\t\tplot:{\n\t\t\tanimation:{\n\t\t\t effect: 4,\n\t\t\t method: 0,\n\t\t\t sequence: 1\n\t\t\t}\n\t\t},\n\t\t\"options\": {\n\t\t \"radius\": \"90%\"\n\t\t},\n\t\t\"plotarea\": {\n\t\t \"margin\": \"dynamic\"\n\t\t},\n\t\t\"series\": [{\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Street Names\"\n\t\t}, {\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Average Speed\"\n\t\t}, {\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Distance\"\n\t\t}, {\n\t\t \"values\": [trips[0].streetnames.length,trips[1].streetnames.length,trips[2].streetnames.length,trips[3].streetnames.length],\n\t\t \"text\": \"Duration\"\n\t\t}]\n\t };\n\t \n\t zingchart.render({\n\t\tid: 'myChart',\n\t\tdata: myConfig,\n\t\theight: \"100%\",\n\t\twidth: \"100%\",\n\t });\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set key:value that will be sent as tags data with the event. | function setTag(key, value) {
callOnHub('setTag', key, value);
} | [
"handleUIStateChange(key, value){\n\t this.props.setPGTtabUIState({\n\t\t[key]: {$set: value}\n\t });\n\t}",
"onFieldTagsKeyDown(event) {\n let me = this;\n\n if (event.key === 'Enter') {\n Neo.main.DomAccess.getAttributes({\n id : event.target.id,\n attributes: 'value'\n }).then(data => {\n VNodeUtil.findChildVnode(me.vnode, {className: 'field-tags'}).vnode.attributes.value = data.value;\n me.tagList = [...me._tagList, data.value];\n });\n }\n }",
"function addLevelDBData(key, value) {\n //console.log(\"Current key value is \" + key)\n db.put(key, JSON.stringify(value), function(err) {\n if (err) return console.log('Block ' + key + ' submission failed', err);\n });\n}",
"set(name, value) {\n this.bkts[this.bucketFor(name)] = value\n }",
"set(key, value = null) {\n // If only argument is an Object, merge Object with internal data\n if (key instanceof Object && value == null) {\n const updateObj = key;\n Object.assign(this.__data, updateObj);\n this.__fullUpdate = true;\n return;\n }\n\n // Add change to internal updates set\n this.__updates.add(key);\n\n // Set internal value selected by dot-prop key\n DotProp.set(this.__data, key, value);\n }",
"function setViewState(key, value) {\n var viewState = jQuery(document).data(kradVariables.VIEW_STATE);\n if (!viewState) {\n viewState = new Object();\n jQuery(document).data(kradVariables.VIEW_STATE, viewState);\n }\n viewState[key] = value;\n}",
"function ssput(k, v) {\n k = _tokey(k);\n v = JSON.stringify(v);\n sessionStorage.setItem(k, v);\n}",
"set user(aValue) {\n this._logService.debug(\"gsDiggEvent.user[set]\");\n this._user = aValue;\n }",
"updateTagAll(value) {\n\t\tlet items = this.state.items;\n\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\titems[i].tag = value;\n\t\t}\n\t\tthis.setState({\n\t\t\ttagAll: value,\n\t\t\titems: items\n\t\t})\n\t}",
"setStorageEntity(key, value, description = \"\", comments = \"\") {\n return spPost(Web(this, \"setStorageEntity\"), request_builders_body({\n comments,\n description,\n key,\n value,\n }));\n }",
"set diggs(aValue) {\n this._logService.debug(\"gsDiggEvent.diggs[set]\");\n this._diggs = aValue;\n }",
"handleSubChartPropertyChange(key, value) {\n const state = this.state;\n state.configuration.charts[0][key] = value;\n this.setState(state);\n this.props.onConfigurationChange(state.configuration);\n }",
"_setAttributes(elem, dict) {\n for (const [key, value] of Object.entries(dict)) {\n console.log(key, value);\n elem.setAttribute(key, value);\n }\n }",
"set surround_key(string){ \n this.key_prefix = string\n this.key_suffix = string\n }",
"function field_set_old_value(key)\n{\n\tthis.old_values[key] = this.getValue(key);\n}",
"function write_tag(category=\"\",item=\"\"){\n if(document.getElementById(\"selected_tags\").value.indexOf(item)!==-1){\n var newKey = firebase.database().ref('kidsBox/'+kid+'/showBox/'+category).push();\n newKey.set({\n tag:item\n });\n firebase.database().ref('/kidsBox/'+kid+\"/incompleteBox/\"+category+\"/\"+log_key+\"/\").set({\n tag:$(\"#selected_tags\").tagsinput(\"items\")\n });\n\n }\n\n}",
"function add(key, value) {\n storeObject.table.push({'key': key, 'value': value});\n writeStore();\n }",
"set topic(aValue) {\n this._logService.debug(\"gsDiggEvent.topic[set]\");\n this._topic = aValue;\n }",
"function _putMarkupCache(instance, key, value) {\n \n var markup = instance.data('markup');\n \n // Create cache if not found\n if (!markup) {\n markup ={};\n instance.data('markup', markup);\n }\n \n // Store\n markup[key] = value;\n }",
"set(id, data) {\n let oldData = this.raw();\n oldData[id] = data;\n this._write(oldData);\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates lasso selecting, expects true/false boolean value, then runs callback if any | updateLassoSelecting(newState, callback = null) {
this.setState({ lassoSelecting: newState }, () => {
if (callback) {
callback();
}
});
} | [
"function sel_change(v, check, F, objs) {\n if (v == check) {\n sel_enable_objs(F, objs);\n } else {\n sel_disable_objs(F, objs);\n }\n}",
"updateHasSelectionAttribute() {\n this.choicesInstance.containerInner.element.setAttribute(\n \"data-has-selection\",\n this.hasSelection\n );\n }",
"_updateAutoHighlight(info) {\n const pickingModuleParameters = {\n pickingSelectedColor: info.picked ? info.color : null\n };\n const {\n highlightColor\n } = this.props;\n\n if (info.picked && typeof highlightColor === 'function') {\n pickingModuleParameters.pickingHighlightColor = highlightColor(info);\n }\n\n this.setModuleParameters(pickingModuleParameters); // setModuleParameters does not trigger redraw\n\n this.setNeedsRedraw();\n }",
"function handleSelection( e )\r\n{\r\n\t//Get selected features\r\n\tvar features = e.selected;\r\n\tvar feature;\r\n\t\r\n\t//TODO???: Handle multi-select?\r\n\tif( features != undefined )\r\n\t{\r\n\t\tfeature = features[0];\r\n\t\t\r\n\t\tif( feature != undefined )\r\n\t\t\t$(\"#shapeList\").val( feature.getId() ).trigger('change');\r\n\t}\t\t\r\n}",
"function ontoggle() {\n selected = !selected;\n logic.ontoggle(selected);\n }",
"function data_option_selected() {\n $(\"#data-set-filter-container\").addClass('data-set-filter-container-slideUp');\n $(\".data-io-clear, .data-io-map\").attr(\"disabled\", false); \n searchFilterClear();\n}",
"highlight() {\n this.model.set('isSelected', true);\n }",
"function toggleSelectable (qid, c, isSelectable) {\n var layersList = $('#scribing-layers-' + qid);\n // Hide scibbles by other users\n layersList.find('option').each(function (i, o) {\n $(o).data('toggleLayer')(false);\n });\n // Make own scribbles un/selectable\n $.each(c.getObjects(), function (i, obj) {\n obj.selectable = isSelectable;\n });\n // Restore scibbles by other users\n layersList.change();\n c.renderAll();\n}",
"function on_piece_select()\n{\n\tupdate_editor();\n}",
"updateCropSelection(d, that, thisLi) {\n that.cropVis.selected_crop = d;\n that.updateCropOnMap(that);\n // Unhighlight previously selected crop and highlight selected crop\n d3.selectAll(\".clickedCropLi\").classed(\"clickedCropLi\", false);\n d3.select(thisLi).attr(\"class\", \"clickedCropLi\");\n let current_countries = [...that.cropVis.selected_countries];\n that.cropVis.selected_countries.clear();\n // that.cropVis.worldMap.clearHighlightedBoundaries();\n that.cropVis.barChart.deleteBarChart();\n that.cropVis.lineChart.deleteLineChart();\n that.cropVis.lineChart.alreadyExistingCountries.clear();\n that.cropVis.table.drawTable();\n for (let country of current_countries) {\n that.cropVis.selected_countries.add(country);\n that.cropVis.barChart.updateBarChart();\n }\n that.cropVis.lineChart.updateLineChart();\n that.cropVis.worldMap.updateAllMapTooltips(that);\n }",
"function updateRemindSelectMenu(boolean)\r\n{\r\n\tvar dropdownbox = document.getElementById('interval_list');\r\n\t\r\n\tif(boolean)\r\n\t{\r\n\t\tdropdownbox.selectedIndex = 0;\r\n\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdropdownbox.selectedIndex = 3;\r\n\t}\r\n\r\n\t$(\"#interval_list\").selectmenu(\"refresh\");\r\n}",
"function toggleLaser() {\n if (tool == LASER) selectTool(PEN);\n else selectTool(LASER);\n }",
"function updateSelect() {\n for (var i=0;i<g_points.length;i++){\n figures.options[i+1] = new Option('Surface' +i, i);\n }\n}",
"function update_selector() {\n let selHas = selection.contains;\n // map groups to divs\n let groups = api.group.list()\n .map(g => h.div([\n h.button({ _: g.name || `group`, title: g.id,\n class: [ \"group\", selHas(g) ? 'selected' : undefined ],\n onclick(e) { selection.toggle(g) }\n }),\n h.div({ class: \"models\"},\n // map models to buttons\n g.models.map(m => [\n h.button({ _: m.file || m.id,\n class: [ selHas(m) ? 'selected' : undefined ],\n onclick(e) {\n if (e.shiftKey) {\n tool.rename([ m ]);\n } else {\n selection.toggle(m);\n }\n },\n onmouseover(e) {\n if (!m.wireframe().enabled) {\n m.opacity({temp: 0.5});\n }\n },\n onmouseleave(e) {\n if (!m.wireframe().enabled) {\n m.opacity({restore: true});\n }\n }\n }),\n h.button({\n class: [ 'square' ],\n onclick(e) {\n m.visible({ toggle: true });\n update_selector();\n }\n }, [ h.raw(m.visible() ? eye_open : eye_closed) ])\n ])\n )\n ]));\n h.bind(grouplist, groups);\n }",
"function _highlightTile() {\n var itemSelected = lv_cockpits.winControl.selection.getItems()._value[0];\n if (!itemSelected.data.spotlighted_at) {\n itemSelected.data.spotlighted_at = new Date();\n }\n else\n itemSelected.data.spotlighted_at = null;\n lv_cockpits.winControl.itemDataSource.change(itemSelected.key, itemSelected.data);\n }",
"selectData(val) {\n if (this._interpolation === \"attr_style_range\") {\n this._selectedData = val;\n for (const canvasData of this._multiCanvas) {\n this._updateCanvas(canvasData.typeId);\n }\n }\n }",
"_updateSelectionOnMultiSelectionChange(value) {\n if (this.multiple && !value) {\n // Deselect all options instead of arbitrarily keeping one of the selected options.\n this.setAllSelected(false);\n }\n else if (!this.multiple && value) {\n this._selectionModel = new SelectionModel(value, this._selectionModel?.selected);\n }\n }",
"function drawSelectionChanged() {\n drawType = drawSelector.value();\n setImage();\n}",
"setSelected () {\n if (this.el.classList.contains(MenuItem.OVER_CLASS)) {\n this.animateSelected()\n } else {\n this.animateOnOver(() => {\n this.animateSelected(() => {\n this.setState()\n })\n })\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overrides the genId method to ensure that a hero always has an id. If the heroes array is empty, the method below returns the initial number (11). if the heroes array is not empty, the method below returns the highest hero id + 1. | genId(heroes) {
return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id)) + 1 : 11;
} | [
"function define_id() {\n var iddef = 0;\n while ( iddef == 0 || iddef > 9999 || FIN_framework.STORYWALKERS.checkids(iddef) ) {\n iddef = Math.floor(Math.random()*10000);\n }\n return iddef;\n }",
"function makeGameId(){\n let result = '';\n let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let charactersLength = characters.length;\n for ( let i = 0; i < 6; i++ ) {\n \tresult += characters.charAt(Math.floor(Math.random() * charactersLength));\n\t}\n\treturn result;\n}",
"function getNextNumber (numberCount, hexagonIndex, robberIndex) {\n if (hexagonIndex === robberIndex) {\n return '' // Desert tile has no number, robber starts on desert\n }\n var random = Math.floor(Math.random() * numberCount.length)\n var toReturn = numberCount[random]\n numberCount.splice(random, 1)\n return toReturn\n}",
"function generateAgents(numHum, propZomb,x,y){\r\n\t//if(gameState){\r\n\t\tfor (var i = 0; i < numHum; i++){\r\n\t\t\tconst human = new Agents('Human',2,traitSelector(),'Blue',initialLocation(x,y));\r\n\t\t\tactiveAgents.push(human);\r\n\t\t}\r\n\t\tfor (var j = 0; j < (numHum*propZomb); j++){\r\n\t\t\tconst zombie = new Agents('Zombie',1,traitSelector(),'Red',initialLocation(x,y));\r\n\t\t\tactiveAgents.push(zombie);\r\n\t\t}\r\n\t//}\r\n}",
"getBestExerciseId(){\n const exerciseKeys = Object.keys(this.exercises).filter(key => key !== 'undefined');// not sure how but some data keys are undefined\n if (exerciseKeys.length <= 0) {\n return null\n }\n var keyIndex = Math.floor(Math.random() * exerciseKeys.length)\n const exercise = exerciseKeys[keyIndex]\n\n return exercise\n }",
"function genIDs() {\n selectAllH().prop('id', function() {\n // If no id prop for this header, return a random id\n return ($(this).prop('id') === '') ? $(this).prop('tagName') + (randID()) : $(this).prop('id');\n });\n }",
"function uniqueId() {\n return id++;\n }",
"function generateNumberToMatch() {\n return Math.floor(Math.random() * 102) + 19;\n}",
"function getRandomMonsterID(){\r\n monsterObj = JSON.parse(fs.readFileSync('public/monsters.json','utf8'));\r\n\r\n /**for different json format - \"{xxx:[{}]}\"**/\r\n //for (m in monsterObj){\r\n //n = Math.floor(Math.random() * monsterObj[x].length) +1;\r\n //}\r\n \r\n n = Math.floor(Math.random() * monsterObj.length);\r\n if (n == 0)\r\n getRandomMonsterID();\r\n else\r\n monsterid = n ;\r\n}",
"function randomNumber() {\n let rng = randomArray[counter];\n counter = (counter + 1) % counterMax;\n return rng;\n}",
"function makeRandomNumber() {\n\t\treturn Math.floor( Math.random() * 9 );\n\t}",
"function getNextGameID() {\n\n gameID++;\n\n const reply = { \"id\": gameID };\n\n return reply;\n\n}",
"spawnOne(i){\n\n // pick which enemy to spawn:\n // shooting enemies appear starting at difficulty level 2,\n // and are more likely to appear at difficulty level 3\n\n let choice='fighter'\n if(levelData.difficulty>1){\n if(levelData.difficulty>2&&Math.random()>0.3) choice='shooter';\n else if(Math.random()>0.6) choice='shooter';\n }\n\n if(i==undefined) i=0;\n enemies.push(new Enemy(\n this.x - 50 + randInt(50) + i*50,\n this.y-80,\n choice\n ));\n }",
"function computerGuessGen() {\n\treturn Math.floor(Math.random() * 101) + 19;\n}",
"function generateTarget() {\n targetScore = Math.floor(Math.random() * (121 - 19) + 19);\n $(\"#targetScore\").text(targetScore);\n}",
"function _makeChangeId() {\n var arr = 'a,b,c,d,e,f,0,1,2,3,4,5,6,7,8,9'.split(',');\n var rnd = '';\n for (var i = 0; i < 40; i++) {\n rnd += arr[Math.floor(Math.random() * arr.length)];\n }\n\n return rnd;\n }",
"function genRandomInteger() {\n let max = 6; // total number of game buttons that represents the upper bound \n let min = 1; // lower bound\n return Math.floor(Math.random() * (max - min + 1) + min);\n}",
"function randomEncounter() {\n\t\treturn Math.floor((Math.random() * encounters.length));\n\t}",
"function getRandomEnemySeed(chosenDifficulty){\n let maxEnemyCount;\n\n if(chosenDifficulty === 'easy'){\n maxEnemyCount = enemyList[0].difficulty[0].easy.length;\n }else if(chosenDifficulty === 'medium'){\n maxEnemyCount = enemyList[0].difficulty[1].medium.length;\n }\n\n return Math.floor(Math.random() * maxEnemyCount);\n}",
"function generateNumberInRandomCell () {\r\n let randomCell = Math.floor(Math.random() * 15);\r\n if (gameCells[randomCell].innerText != \"\") {\r\n randomCell = Math.floor(Math.random() * 15);\r\n }\r\n let span = document.createElement('span');\r\n span.innerText = '2';\r\n span.classList.add('game-piece');\r\n gameCells[randomCell].appendChild(span);\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the current task | get task () {
return this._mem.work === undefined ? null : this._mem.work.task;
} | [
"getCurrentImporterTask() {\n return this._currentImportTask;\n }",
"_executeTask(task) {\n\t\tvar wp = this.idleWorkers.values().next().value;\n\t\treturn wp.invokeTask(task)\n\t}",
"async function getRunningSyncTask() {\n const result = await query(`\n PREFIX ext: <http://mu.semte.ch/vocabularies/ext/>\n PREFIX dct: <http://purl.org/dc/terms/>\n PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n PREFIX adms: <http://www.w3.org/ns/adms#>\n\n SELECT ?s WHERE {\n ?s a ext:SyncTask ;\n dct:creator <http://lblod.data.gift/services/${SERVICE_NAME}> ;\n adms:status <${TASK_ONGOING_STATUS}> .\n } ORDER BY ?created LIMIT 1\n `);\n\n return result.results.bindings.length ? {uri: result.results.bindings[0]['s']} : null;\n}",
"function currentThread() {\n\treturn java.lang.Thread.currentThread();\n}",
"_forceExecuteTask(task) {\n\t\tif (this.idleWorkers.size > 0)\n\t\t\tvar wp = this.idleWorkers.values().next().value;\n\t\telse\n\t\t\tvar wp = Array.from(this.runningWorkers)\n\t\t\t\t.sort((a, b) => a.runningTasks - b.runningTasks)[0];\n\t\treturn wp.invokeTask(task)\n\t}",
"function getTaskById(taskId) {\n\treturn $tasks.filter((task) => task.getId() === taskId)[0];\n}",
"function getDetail() {\n\t\tTasks.get({id: $routeParams.taskId}, function(data) {\n\t\t\t$scope.task = data;\n\t\t});\n\t}",
"get_tasks() {\n TController.get_tasks(this.add_tasks.bind(this));\n }",
"get taskType() {\n if (this.isMarker) {\n return this._taskThing.type;\n }\n if (this.isPlanning) {\n return this._taskThing.rawTask.type;\n } else {\n return this._taskThing.plannedTask.type;\n }\n }",
"getNextTask() {\n let highestPriority = this.taskQueues.length - 1;\n for (let i = highestPriority; i >= 0; i--) {\n // if the queue exists\n let queue = this.taskQueues[i];\n if (!queue) {\n continue;\n }\n // find a runable task\n let taskIndex = lodash_1.findIndex(queue, t => t.isRunnable);\n // if that exists, return the task\n if (taskIndex != -1) {\n let task = queue[taskIndex];\n lodash_1.pullAt(queue, taskIndex);\n return task;\n }\n }\n return undefined;\n }",
"function taskStarting() {\n tasksRunning += 1;\n return null;\n}",
"peekNextTask() {\n let highesPriority = this.taskQueues.length - 1;\n for (let i = highesPriority; i >= 0; i--) {\n let queue = this.taskQueues[i];\n if (!queue) {\n continue;\n }\n let taskIndex = lodash_1.findIndex(queue, t => t.isRunnable);\n if (taskIndex != -1) {\n return queue[taskIndex];\n }\n }\n return undefined;\n }",
"async getSiteDesignTask(id) {\n const task = await SiteDesignsCloneFactory(this, \"GetSiteDesignTask\").run({ \"taskId\": id });\n return hOP(task, \"ID\") ? task : null;\n }",
"function getVmOpsQueueTask(vmId) {\n var subscriptionRegisteredToService = global.Exp.Rdfe.getSubscriptionsRegisteredToService(\"CmpWapExtension\");\n return makeAjaxCall(vmGetOpsQueueTaskUrl, { subscriptionId: subscriptionRegisteredToService[0].id, vmId: vmId });\n }",
"outputTask(task){\r\n console.log(`Task ID: ${task.id} | Text: ${task.text} | Schedule: ${task.schedule} | Label: ${task.label} | Priority: ${task.priority}`);\r\n }",
"get(index) {\n return this._taskArr[index];\n }",
"function todoist_current_tasks_pull_custom() {\n current_tasks_base = todoist_current_tasks_pull()\n current_tasks = current_tasks_base.items\n labels_dictionary = current_tasks_base.labels\n labels_dictionary = array_to_dictionary(labels_dictionary)\n projects_dictionary = current_tasks_base.projects\n current_tasks.forEach(function(D) {\n tasks_array_customize_item(D)\n })\n return current_tasks\n}",
"set task (value) {\n if (this._mem.work === undefined) {\n this._mem.work = {};\n }\n this._mem.work.task = value;\n }",
"_findActiveTaskCandidate() {\n for (const stream of this._streams) {\n if (stream.state === StreamState.Open && stream !== this._activeStream) {\n return stream;\n }\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
an alternative to registerChildWindows, trying... | function registerResultsToDefinition(objResultWindow, objChild, objParent)
{
try
{
if(objParent.childWindows)
{
objParent.childWindows[objParent.childWindows.length] = objChild;
}
else
{
objParent.childWindows[0] = objChild;
if(!objChild.childWindows)
{
objChild.childWindows[0] = objResultWindow;
}
}
}
catch(e)
{
}
} | [
"function WindowsManager () {\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Flag to raise while the main window is open.\r\n\t\t\t * @field\r\n\t\t\t * @private\r\n\t\t\t */\r\n\t\t\tvar isMainWindowOpen = false;\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Returns the default display options for a newly created window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @return { NativeWindowInitOptions }\r\n\t\t\t * \t\tAn object specifying display options for a new window. \r\n\t\t\t */\r\n\t\t\tfunction getDefWindowOptions () {\r\n\t\t\t\tvar options = new NativeWindowInitOptions();\r\n\t\t\t\toptions.type = NativeWindowType.UTILITY;\r\n\t\t\t\treturn options;\r\n\t\t\t}\r\n\r\n\t\t\t/**\r\n\t\t\t * Returns the default display boundaries for a newly created \r\n\t\t\t * window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @return { Rectangle }\r\n\t\t\t * \t\tA rectangle defining the boundaries of this new window.\r\n\t\t\t */\t\t\t\r\n\t\t\tfunction getDefBoundaries () {\r\n\t\t\t\tvar bounds = new Rectangle();\r\n\t\t\t\tbounds.x = Math.max(0, (screen.width-800)/2);\r\n\t\t\t\tbounds.y = Math.max(0, (screen.height-600)/2);\r\n\t\t\t\tbounds.width = 800;\r\n\t\t\t\tbounds.height = 600;\r\n\t\t\t\treturn bounds;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Creates the main window of the application.\r\n\t\t\t * @method\r\n\t\t\t * @public\r\n\t\t\t */\r\n\t\t\tthis.makeMainWindow = function () {\r\n\t\t\t\tvar htmlLoader = HTMLLoader.createRootWindow (\r\n\t\t\t\t\ttrue,\r\n\t\t\t\t\tgetDefWindowOptions(), \r\n\t\t\t\t\tfalse,\r\n\t\t\t\t\tgetDefBoundaries()\r\n\t\t\t\t);\r\n\t\t\t\thtmlLoader.addEventListener('htmlDOMInitialize', function() {\r\n\t\t\t\t\tisMainWindowOpen = true;\r\n\t\t\t\t\tmakeWindowModal (htmlLoader.window, self);\r\n\t\t\t\t\thtmlLoader.window.nativeWindow.addEventListener (\r\n\t\t\t\t\t\t'close',\r\n\t\t\t\t\t\t function() {isMainWindowOpen = false}\r\n\t\t\t\t\t);\r\n\t\t\t\t\tvar event = eventManager.createEvent(\r\n\t\t\t\t\t\tWINDOW_CREATED_EVENT,\r\n\t\t\t\t\t\t{'window': htmlLoader.window}\r\n\t\t\t\t\t);\r\n\t\t\t\t\teventManager.fireEvent(event);\r\n\t\t\t\t});\r\n\t\t\t\thtmlLoader.loadString(' ');\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t/**\r\n\t\t\t * Makes a window modal to a certain parent window.\r\n\t\t\t * @method\r\n\t\t\t * @private\r\n\t\t\t * @param oWindow { Object Window }\r\n\t\t\t * \t\tThe window to be made modal.\r\n\t\t\t * @param oParentWindow { Object Window }\r\n\t\t\t * \t\tThe parent of the modal window. Any attempt to access the \r\n\t\t\t * \t\tparent while the modal window is open will fail.\r\n\t\t\t */\r\n\t\t\tfunction makeWindowModal (oWindow, oParentWindow) {\r\n\t\t\t\t\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'closing',\r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'displayStateChanging', \r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'moving',\r\n\t\t\t\t\tfunction (event) {\r\n\t\t\t\t\t\t//if (isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toParentWindow.nativeWindow.addEventListener (\r\n\t\t\t\t\t'resizing', \r\n\t\t\t\t\tfunction(event) {\r\n\t\t\t\t\t\t//if(isMainWindowOpen) { event.preventDefault() };\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toWindow.nativeWindow.addEventListener(\r\n\t\t\t\t\t'deactivate',\r\n\t\t\t\t\tfunction() {\r\n\t\t\t\t\t\t//oWindow.nativeWindow.activate();\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\toWindow.nativeWindow.addEventListener(\r\n\t\t\t\t\t'closing',\r\n\t\t\t\t\tfunction(){\r\n\t\t\t\t\t\tvar ev = eventManager.createEvent(BROWSER_UNLOAD_EVENT);\r\n\t\t\t\t\t\teventManager.fireEvent(ev);\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t\t \r\n\t\t\t}\r\n\t\t}",
"function defaultWndProc( winInfo ) {\n\t\tshowWindow( winInfo.hWnd );\n\t}",
"_resizeWindowManager() {\n const kMargin = 200;\n let required_height = 0;\n let required_width = 0;\n for (let i in this.windows_) {\n const element = this.windows_[i];\n const top = parseInt(element.style.top);\n const left = parseInt(element.style.left);\n if (top > 0 && left > 0) {\n required_height = Math.max(required_height, top + element.offsetHeight);\n required_width = Math.max(required_width, left + element.offsetWidth);\n }\n }\n this.parent_.style.height = (required_height + kMargin) + \"px\";\n this.parent_.style.width = (required_width + kMargin) + \"px\";\n }",
"function openChildWindow(){\n setErrorFlag();\n var lstrWidth = '750px';//set default width\n var lstrHeight = '450px';//set default height\n var lstrURL;\n var lstrArgument;\n\n lstrURL = openChildWindow.arguments[0];\n if( lstrURL.indexOf(\"?\") == -1 ) {\n lstrURL = lstrURL + \"?childFw=Y\" ;\n } else {\n lstrURL = lstrURL + \"&childFw=Y\" ;\n }\n lstrURL = encodeURI(lstrURL);\n lstrArgument = openChildWindow.arguments[1];\n\n //set the width\n if(openChildWindow.arguments[2] != null && openChildWindow.arguments[2].length > 0 ){\n lstrWidth= openChildWindow.arguments[2];\n }\n\n //set the height\n if(openChildWindow.arguments[3] != null && openChildWindow.arguments[3].length > 0 ){\n lstrHeight= openChildWindow.arguments[3];\n }\n\n // for appending the readonly flag of Parent Screen\n if(document.getElementById('readOnlyFlg') != null && document.getElementById('readOnlyFlg')!= undefined){\n if(lstrURL.indexOf('?') != -1 ){\n lstrURL = lstrURL+ '&childScreen=true&readOnlyFlg='+document.getElementById('readOnlyFlg').value;\n }else{\n lstrURL = lstrURL+ '?childScreen=true&readOnlyFlg='+document.getElementById('readOnlyFlg').value;\n }\n }\n\n //open model dialog\n window.showModalDialog(lstrURL,lstrArgument, 'dialogHeight:' + lstrHeight + ';dialogWidth:' + lstrWidth + ';center:yes;status:no');\n // Set Error Flag to true so that Buttons are not disabled of parent\n isErrFlg = true;\n}",
"function createNewCarWindow() {\n if (newCarWin) {\n return;\n }\n\n newCarWin = new BrowserWindow({width: 450, height: 400, webPreferences :{nodeIntegration : true}});\n newCarWin.loadFile(path.join('src', 'addCar.html'));\n\n // Listen when the window will be closed for destroy it\n newCarWin.on('closed', () => {\n newCarWin = null\n })\n}",
"registerToShell() {\n this.postMessageToShell(MessageType.registration, this.id);\n }",
"function resize(win) {\n prevWindow = win;\n tabCount = win.tabs.length;\n var screenWidth = window.screen.availWidth;\n var screenHeight = window.screen.availHeight;\n \n var leftWindow = {\n left: 0,\n top: 0,\n width: screenWidth / 2,\n height: screenHeight\n };\n \n var rightWindow = {\n left: screenWidth / 2,\n top: 0,\n width: screenWidth / 2,\n height: screenHeight\n };\n \n\n \n chrome.windows.update(win.id, leftWindow);\n chrome.windows.create(rightWindow, getTabs);\n\n}",
"function createWindow(initialParent, defaultContent, setupData) {\n\n defaultContent =\n defaultContent || \"\";\n\n setupData = \n setupData || null;\n\n\t\t\t// if no parent container has been provided, reject request\n\t\t\tif (initialParent == null)\n\t\t\t\treturn 0;\n\t\t\t\n var newWindow = \n new WTWindow(\n this, \n initialParent, \n defaultContent, \n setupData);\n\t\t\t\n windows\n .push(\n newWindow);\n\n\t\t\treturn newWindow.id;\n }",
"_activateAllWindows() {\n // First activate first window so workspace is switched if needed.\n // We don't do this if isolation is on!\n if (!Docking.DockManager.settings.get_boolean('isolate-workspaces') &&\n !Docking.DockManager.settings.get_boolean('isolate-monitors'))\n this.app.activate();\n\n // then activate all other app windows in the current workspace\n let windows = this.getInterestingWindows();\n let activeWorkspace = global.workspace_manager.get_active_workspace_index();\n\n if (windows.length <= 0)\n return;\n\n let activatedWindows = 0;\n\n for (let i = windows.length - 1; i >= 0; i--) {\n if (windows[i].get_workspace().index() == activeWorkspace) {\n Main.activateWindow(windows[i]);\n activatedWindows++;\n }\n }\n }",
"startSecondaryWindow() {\n const elt = document.getElementById(\"application-loading-cover\");\n if (elt) elt.remove();\n\n return this.startWindow().then(() => {\n this.initializeBasicSheet();\n ipcRenderer.on(\"load-settings-changed\", this.populateHotWindow);\n return ipcRenderer.send('window-command', 'window:loaded');\n }\n );\n }",
"onAllWindowsClosed() {\r\n // Stub\r\n }",
"populateHotWindow(event, loadSettings) {\n if (/composer/.test(loadSettings.windowType)) {\n NylasEnv.timer.split('open-composer-window');\n }\n this.loadSettings = loadSettings;\n this.constructor.loadSettings = loadSettings;\n\n this.packages.loadPackages(loadSettings.windowType);\n this.deserializePackageStates();\n this.packages.activate();\n\n this.emitter.emit('window-props-received',\n loadSettings.windowProps != null ? loadSettings.windowProps : {});\n\n const browserWindow = this.getCurrentWindow();\n if (browserWindow.isResizable() !== loadSettings.resizable) {\n browserWindow.setResizable(loadSettings.resizable);\n }\n\n if (!loadSettings.hidden) {\n this.displayWindow();\n }\n }",
"function BAWindow() { }",
"function createBackgroundWindow () {\n backgroundWindow = new BrowserWindow({width: 640, height: 480, show: true})\n backgroundWindow.loadFile('background.html')\n backgroundWindow.on('closed', () => {\n backgroundWindow = null\n })\n}",
"function makeNativeWindow(name, width, height) {\r\n\r\n\t\t\t// For window options:\r\n\t\t\tvar options = new air.NativeWindowInitOptions();\r\n\t\t\toptions.transparent = true; \r\n\t\t\toptions.systemChrome = air.NativeWindowSystemChrome.NONE;\r\n\t\t\toptions.type = air.NativeWindowType.LIGHTWEIGHT;\r\n\r\n\t\t\t// Window size and location:\r\n\t\t\tvar x = (window.screen.width-width)/2;\r\n\t\t\tvar y = (window.screen.height-height)/2;\r\n\t\t\tvar rect = new air.Rectangle(x, y, width, height);\r\n\r\n\t\t\t// Create the window:\r\n\t\t\tvar popup = air.HTMLLoader.createRootWindow(true, options, false, rect);\r\n\r\n\t\t\t// Load the content:\r\n\t\t\tvar page = air.File.applicationDirectory.resolvePath(name + '.html');\r\n\t\t\tpopup.addEventListener(air.Event.COMPLETE,completetHandler);\r\n\t\t\tpopup.load(new air.URLRequest(page.url));\r\n\t\t\t\r\n\t\t\tfunction completetHandler (){\r\n\t\t\t\tpopup.window.windowInit(window);\r\n\t\t\t\tpopup.removeEventListener(air.Event.COMPLETE,completetHandler);\r\n\t\t\t}\r\n\r\n\t\t} // End of makeNativeWindow() function.",
"rearrangeDivs() {\n const margin = 10;\n let twidth = window.innerWidth - this.parent_.offsetLeft;\n // TODO remove this hack\n // If the config is present\n let config = document.getElementById(\"config\");\n if (config !== null) twidth -= config.offsetWidth + 10 + margin;\n\n // Group windows in number needed to fill a row\n const splitter = 20;\n let sizes = [];\n for (let id in this.windows_) {\n let div = this.windows_[id];\n if (div.style.display === \"none\") continue;\n const box = div.getBoundingClientRect();\n const width = box.width + 2 * margin;\n const height = box.height + 2 * margin;\n const num = (twidth / width) | 0;\n if (!sizes[num]) {\n sizes[num] = [];\n }\n sizes[num].push({w: width, h: height, d: div});\n }\n\n // Extract a list of window that fit next to the right most element until we reach its height\n const extract = function(aw, th) {\n let list = [];\n let h = 0;\n for (let i in sizes) {\n for (let e in sizes[i]) {\n let elem = sizes[i][e];\n if (!elem) continue;\n if (elem.w < aw && h + elem.h < th * 1.1) {\n list.push(elem);\n sizes[i][e] = null;\n h += elem.h;\n if (h > th) break;\n }\n }\n if (h > th) break;\n }\n return list;\n }\n // Place an element at a givent place\n const place = function(elem, y, x, aw) {\n elem.style.top = y + \"px\";\n elem.style.left = x + \"px\";\n if (elem.options && elem.options.resize === true) {\n elem.style.width = (aw - 2 * margin) + \"px\";\n elem.click();\n }\n }\n\n // Go through the group one by one and organize the window\n let y = margin;\n for (let i in sizes) {\n if (i <= 0) {\n // Special case for the window that does not fit\n for (let e in sizes[i]) {\n let elem = sizes[i][e];\n place(elem.d, y, margin, twidth);\n y += elem.h;\n }\n } else if (i == 1) {\n // Special case for the window that fit alone (we still try to find another window to fit)\n for (let e in sizes[i]) {\n let elem = sizes[i][e];\n place(elem.d, y, margin);\n const aw = twidth - elem.w;\n const list = extract(aw, elem.h);\n let h = 0;\n for (let d in list) {\n place(list[d].d, y + h, elem.w + margin, aw);\n h += list[d].h;\n }\n y += Math.max(elem.h, h);\n }\n } else {\n // Organize the windows by columns, always add to the smallest one.\n let h = [];\n for (let v = 0; v < i; v++) h.push(0);\n const w = twidth / i;\n for (let e in sizes[i]) {\n let c = h.indexOf(Math.min(...h));\n let elem = sizes[i][e];\n if (!elem) continue;\n place(elem.d, y + h[c], margin + c * w, w);\n h[c] += elem.h;\n }\n let c = h.indexOf(Math.max(...h));\n y += h[c];\n }\n }\n this._resizeWindowManager();\n return true;\n }",
"focusWindow(n){\n if(this.win.n == n){\n this.$emit('focusWindow', n)\n this.focusInput()\n }\n }",
"function ScanParentsForApi(win)\n{\n/*\n Establish an outrageously high maximum number of\n parent windows that we are will to search as a\n safe guard against an infinite loop. This is\n probably not strictly necessary, but different\n browsers can do funny things with undefined objects.\n */\n var nParentsSearched = 0;\n\t\n\tvar api = null;\n\n\tapi = findTheAPI(win);\n\n /*\n Search each parent window until we either:\n -find the API,\n -encounter a window with no parent (parent is null\n or the same as the current window)\n -or, have reached our maximum nesting threshold\n */\n while ( (api == null) &&\n (win.parent != null) && (win.parent != win) &&\n (nParentsSearched <= MAX_PARENTS_TO_SEARCH)\n )\n {\n \n\t\t\tnParentsSearched++;\n win = win.parent;\n\t\t\tapi = findTheAPI(win);\n }\n /*\n If the API doesn't exist in the window we stopped looping on,\n then this will return null.\n */\n return api;\n}",
"visitWindowing_elements(ctx) {\n\t return this.visitChildren(ctx);\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function returns the number of selected outputpins | function updateNumOutputpinsSelected() {
var num = 0;
for ( var i = 0; i < viewModel.selectedModuleOfInterest.availableOutputpinList().length; ++i)
{
num += viewModel.selectedModuleOfInterest.availableOutputpinList()[i].isChecked();
}
viewModel.numOutputpinsSelected(num);
} | [
"function getNumCandidates() {\n return numCandidates;\n } // getNumCandidates",
"function getSelectedLayersCount(){\n\t\tvar res = new Number();\n\t\tvar ref = new ActionReference();\n\t\tref.putEnumerated( charIDToTypeID(\"Dcmn\"), charIDToTypeID(\"Ordn\"), charIDToTypeID(\"Trgt\") );\n\t\tvar desc = executeActionGet(ref);\n\t\tif( desc.hasKey( stringIDToTypeID( 'targetLayers' ) ) ){\n\t\t\tdesc = desc.getList( stringIDToTypeID( 'targetLayers' ));\n\t\t\tres = desc.count \n\t\t}else{\n\t\t\tvar vis = app.activeDocument.activeLayer.visible;\n\t\t\tif(vis == true) app.activeDocument.activeLayer.visible = false;\n\t\t\tcheckVisibility();\n\t\t\tif(app.activeDocument.activeLayer.visible == true){\n\t\t\t\tres =1;\n\t\t\t}else{\n\t\t\t\tres = 0;\n\t\t\t}\n\t\t\tapp.activeDocument.activeLayer.visible = vis;\n\t\t}\n\t\treturn res;\n\t}",
"function getSelectedCount() {\n\tvar vCnt=0;\n\tif(!document.forms[0].customePkArray.length) {\n if(document.forms[0].customePkArray.checked) {\n vCnt=parseInt(vCnt)+1;\n }\n } else {\n \tvar len=document.forms[0].customePkArray.length;\n \tif(len > 0) {\n \t\tfor(var i= 0 ; i< document.forms[0].customePkArray.length;i++) {\n \t\t if (document.forms[0].customePkArray[i].checked==true )\n \t\t {\n \t\t\t\tvCnt=parseInt(vCnt)+1;\n \t\t }\t\t\t\t\n \t\t}\n \t}\n }\n\treturn vCnt;\n}",
"function getNumberOfToppingsSelected() {\n var selections = document.getElementsByClassName(\"form-check-input\")\n var count = 0;\n for (var i = 0; i < selections.length; i++) {\n if (selections[i].type === \"checkbox\" && selections[i].checked === true) {\n count++;\n }\n }\n return count;\n}",
"getSelectedCount()\n {\n return Object.keys(this._selectedItems).length;\n }",
"nTiles(params) {\n return Object.keys(params.style.sources).map(source => {\n return getTiles(params.bounds, params.minZoom, ((params.style.sources[source].tileSize < 512) ? (params.maxZoom + 1) : params.maxZoom)).length\n }).reduce((a, b) => { return a + b }, 0)\n }",
"function count_controls() {\n\t\tvar count = 0,\n\t\t\t\tid;\n\t\tfor (id in controls.lookup) {\n\t\t\tif (controls.lookup.hasOwnProperty(id)) {\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t\treturn count;\n\t}",
"count() {\n const values = utils.removeMissingValuesFromArray(this.values);\n return values.length;\n }",
"function no_of_on_lights(arr){\n arr = command_executor(arr, Light);\n let on_lights_arr = [];\n for( i = 0; i < 1000; i++){\n for( j = 0; j < 1000; j++){\n if(arr[i][j].on){\n on_lights_arr.push(arr[i][j]);\n }\n }\n }\n let length = on_lights_arr.length;\n return length\n}",
"count() {\n return Object.keys(this.locations).reduce(\n ((total, current) => total + Object.keys(this.locations[current]).length)\n , 0);\n }",
"function countIslands (mapStr) {\n var mapArr = mapStr.split('\\n').map(function(row) {return row.split(\"\");});\n var count = 0;\n for (var i = 0; i < mapArr.length; i++) {\n for (var j = 0; j < mapArr[i].length; j++) {\n if (isLand(mapArr[i][j])) {\n count += 1;\n sinkLand(mapArr, i, j);\n }\n }\n }\n return count\n}",
"function getNumCellsinLayer(layerNumber) {\n return layerNumber + 1;\n }",
"function getCount(objects) {\n let i = 0;\n for ( let j = 0; j < objects.length; j++ ) {\n if ( objects[j].x === objects[j].y ) {\n i++;\n }\n }\n return i;\n}",
"bitCount() {\n let result = 0;\n for(let i = 0; i < this.array.length; i++){\n result += BitSet.countBits(this.array[i]) // Assumes we never have bits set beyond the end\n ;\n }\n return result;\n }",
"function GetElementCount(selector)\n {\n return parseInt(typeof selector.attr(\"data-max\") !== \"undefined\" ? selector.attr(\"data-max\") : base.options.elementCount)\n }",
"howManyPieces(player, intersections) { \n let count = 0;\n for (var c = 0; c < intersections.length; c++) { \n if (intersections[c] === player) { count++; }\n }\n return count;\n }",
"function numParBio(b) {\n var banda = docXML.getElementsByTagName(\"banda\")[b].getElementsByTagName(\"biografia\")[0];\n return banda.getElementsByTagName(\"par\").length;\n}",
"function count_moveend_event(mIDX, e) {\r\n\tvar moveendEvents = app[mIDX].map._events[\"moveend\"];\r\n\tif (e) moveendEvents = e.target._events[\"moveend\"];\r\n\tif (!moveendEvents) return 0;\r\n\tvar count = 0;\r\n\t$.each(moveendEvents, function(idx, row) {\r\n\t\tvar ctx = row['ctx'];\r\n\t\t//console.log(getNow(), mIDX, idx, ctx, e);\r\n\t\tif (typeof ctx === 'string' && ctx.startsWith(mIDX)) count += 1;\r\n\t});\r\n\treturn count;\r\n}",
"function getNbPlayers(){\n if($(nb_p1_btn).hasClass(\"active\")){return 1;}\n else if($(nb_p2_btn).hasClass(\"active\")){return 2;}\n else if($(nb_p3_btn).hasClass(\"active\")){return 3;}\n else if($(nb_p4_btn).hasClass(\"active\")){return 4;}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fullsreen methods / Tool methods find the currently selected legend return dimension name and dimension index | _getSelected() {
const option = this._getOption();
// An object like: {dimensionName: true/false}
const selected = option.legend[0].selected;
// _getSelected() must be called after the dataset series is set
if (typeof selected !== 'object') {
throw new Error('Selected is not an object.' +
'_getSelected() must be called after the dataset and series are set');
}
// find the dimensionName whose value is true
const selectedDimension =
Object.keys(selected).find((key) => selected[key]);
// get its index in dataset's dimensions
const seletedIndex = this.dimensions.indexOf(selectedDimension);
return {
dimension: selectedDimension,
index: seletedIndex
};
} | [
"getColorLabel(colorID) {\n if (colorID in this.state.pluginData[\"Legend\"][this.state.activeEntry]) {\n return this.state.pluginData[\"Legend\"][this.state.activeEntry][colorID];\n } else {\n return null;\n }\n }",
"function drawLegend() {\n var shown = buildLabels();\n var idx = 0;\n var legend = svgPath.selectAll(\".legend\").data(colorPath.domain()).enter()\n .append(\"g\").attr(\"class\", \"legend\").attr(\"transform\", function(d) {\n // Use our enumerated idx for labels, not all-color index i\n var y = 0;\n if (shown.includes(d)) {\n y = ph_m + (idx * (pl_w + 2));\n idx++;\n }\n return \"translate(0,\" + y + \")\";\n });\n legend.append(\"rect\").attr(\"x\", ph_m).attr(\"width\", pl_w).attr(\"height\",\n pl_w).style(\"fill\", colorPath).style(\"visibility\", function(d) {\n return shown.includes(d) ? \"visible\" : \"hidden\";\n });\n var x_offset = (ph_m * 2) + pl_w;\n var y_offset = pl_w / 2;\n legend.append(\"text\").attr(\"x\", x_offset).attr(\"y\", y_offset).attr(\"dy\",\n \".35em\").style(\"text-anchor\", \"begin\").style(\"font-size\", \"12px\")\n .text(function(d) {\n if (shown.includes(d)) {\n var core = '';\n var label = '';\n if (d % 2 === 0) {\n isd = d / 4 + 1;\n core = ' (core)';\n } else {\n isd = (d - 1) / 4 + 1;\n }\n if (iaLabels && iaLabels.ISD && iaLabels.ISD[String(isd)]) {\n label = ' ' + iaLabels.ISD[String(isd)];\n }\n return 'ISD-' + isd + label + core;\n } else {\n return null;\n }\n });\n}",
"function loadDimensions(that) {\r\n //Load the Dimensions used by the report definition\r\n if (that.config.dimensions !== undefined) {\r\n $.each(that.config.dimensions, function (index, value) {\r\n that.idxDimension[index] = chart.ndx.dimension(function (d) {\r\n/*\r\n //Dimension based on the Data Object\r\n if (that.config.dimensions[index].context === \"context:object\") {\r\n return d;\r\n }\r\n*/\r\n //Dimension based on a specific field like Category\r\n if (that.config.dimensions[index].context === \"context:field\") {\r\n return d[that.config.dimensions[index].datafield];\r\n }\r\n\r\n //Dimension based on a specific field like Category\r\n if (that.config.dimensions[index].context === \"context:2field\") {\r\n return [d[that.config.dimensions[index].datafield], d[that.config.dimensions[index].datafield2]];\r\n }\r\n\r\n //Dimension based on date\r\n if (that.config.dimensions[index].context === \"context:date\") {\r\n return d.dd;\r\n }\r\n\r\n //Dimension based on day of week\r\n if (that.config.dimensions[index].context === \"context:day\") {\r\n var day = d.dd.getDay();\r\n var name = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\r\n return day + \".\" + name[day];\r\n }\r\n\r\n //Dimension based on month\r\n if (that.config.dimensions[index].context === \"context:month\") {\r\n return d3.time.month(d.dd);\r\n }\r\n\r\n //Dimension based on Quarter of the year\r\n if (that.config.dimensions[index].context === \"context:quarter\") {\r\n var month = d.dd.getMonth() + 1;\r\n if (month <= 3)\r\n return \"Q1\";\r\n else if (month > 3 && month <= 6)\r\n return \"Q2\";\r\n else if (month > 6 && month <= 9)\r\n return \"Q3\";\r\n else\r\n return \"Q4\";\r\n }\r\n\r\n //Dimension based on Range\r\n if (that.config.dimensions[index].context === \"context:range\") {\r\n var number = d.AvgSize;\r\n if (number <= (that.config.dimensions[index].highrange * 0.25))\r\n return \"<25%\";\r\n else if (number > (that.config.dimensions[index].highrange * 0.5) && number <= (that.config.dimensions[index].highrange * 0.75))\r\n return \"<50%\";\r\n else if (number > (that.config.dimensions[index].highrange * 0.75) && number <= (that.config.dimensions[index].highrange * 1))\r\n return \"<75%\";\r\n else\r\n return \"100%\";\r\n }\r\n });\r\n });\r\n }\r\n }",
"function drawLegend() {\n var legend = $(\"#legend\");\n legend.empty();\n\n var legendContainer = $(\"<div>\");\n legendContainer.addClass(\"legendContainer\");\n\n // Nur die Labels, die wir auch anzeigen!\n for(var lbl of usedLabels.entries()) {\n var catId = lbl[0];\n var category = categories[catId];\n var color = resourceColorTable[catId];\n legendContainer.append(\"<div class='label'><div class='color' style='background: \"+color+\"'> </div> \"+category+\"</div>\");\n }\n\n legend.append(legendContainer);\n}",
"initLegend() {\n const self = this;\n\n // Array containing all legend lines (visible or not)\n self.d3.legendLines = [];\n self.curData.forEach(function (datum, index) {\n self.d3.legendLines.push(\n self.d3.o.legend.append(\"p\")\n .style(\"color\", function () {\n if (self.d3.visibleCurves[index]) {\n return self.colorPalette[index];\n } else {\n return \"#CCC\";\n }\n })\n .attr(\"class\", \"ts_label\")\n .style(\"font-size\", \"0.8em\")\n .style(\"cursor\", \"pointer\")\n .style(\"margin\", \"0px 3px\")\n .text(datum.funcId)\n .on(\"click\", function () {\n if (!self.isLoading) {\n // Toggle visibility of the clicked TS\n self.d3.visibleCurves[index] = !self.d3.visibleCurves[index];\n self.quickUpdate();\n }\n })\n .on(\"mouseover\", function () {\n d3.select(this).style(\"text-decoration\", \"underline\");\n })\n .on(\"mouseout\", function () {\n d3.select(this).style(\"text-decoration\", \"none\");\n })\n );\n });\n }",
"function createLegend(legend, chartData, chartOptions, total, rowIndex) {\n\n var totalText = (chartOptions[0].legend[0].totalText) ? chartOptions[0].legend[0].totalText : \"Total : \";\n var legendTitle = (chartOptions[0].legend[0].title) ? chartOptions[0].legend[0].title : \"\";\n var html = \"\";\n\n if (chartOptions[0].legend[0].title) {\n html += \"<div class='spc-legend-head'><h3>\" + legendTitle + \"</h3></div>\";\n }\n html += \"<table class='spc-legend-content'>\";\n html += \"<tr class='spc-legend-th'>\";\n for (var i = 0; i < chartOptions[0].legend[0].columns.length; i++) {\n if (i === 0) {\n html += \"<td colspan='2'>\" + chartOptions[0].legend[0].columns[i] + \"</span></td>\";\n } else {\n html += \"<td>\" + chartOptions[0].legend[0].columns[i] + \"</span></td>\";\n }\n\n }\n html += \"</tr>\";\n var rowsArray = [];\n for (var i = 0; i < chartData.length; i++) {\n var legendGuidesHmtl = \"<div class='spc-legend-guides' style='width:16px;height:16px;background-color:\" + chartData[i].color + \"'></div>\";\n var trId = canvasId + \"_legcol_\" + i;\n\n rowsArray.push(trId);\n\n html += \"<tr id='\" + trId + \"' style='color:\" + chartData[i].color + (typeof rowIndex === 'number' && rowIndex === i ? ';background:' + '#F3F3F3' : '') + \"'>\";\n html += \"<td width='21'>\" + legendGuidesHmtl + \"</td>\"; // Slice guides\n\n for (var k = 0; k < chartOptions[0].legend[0].columns.length; k++) {\n var content = \"\";\n switch (k) {\n case 0:\n content = chartData[i].name;\n break;\n case 1:\n content = chartData[i].value;\n break;\n case 2:\n content = Math.round((chartData[i].value / total) * 100) + \"%\";\n break;\n }\n html += \"<td><span>\" + content + \"</span></td>\";\n }\n html += \"</tr>\";\n\n\n }\n html += \"</table>\";\n if (chartOptions[0].legend[0].showTotal) {\n html += \"<div class='spc-legend-foot'><p>\" + totalText + \"\" + total + \"</span></div>\";\n }\n\n legend.innerHTML = html;\n\n // Interactivity preference\n var interactivity = (chartOptions[0].interactivity) ? chartOptions[0].interactivity : \"enabled\";\n if (interactivity === \"enabled\") { // If enabled\n\n // Attach mouse Event listeners to table rows\n for (var i = 0; i < rowsArray.length; i++) {\n var thisRow = document.getElementById(rowsArray[i]);\n thisRow.chrtData = chartData;\n thisRow.options = chartOptions;\n thisRow.sliceData = chartData[i];\n thisRow.slice = i;\n thisRow.mouseout = true;\n\n thisRow.addEventListener(\"mousedown\", function (e) {\n return function () {\n handleClick(this.chrtData, this.options, this.slice, this.sliceData);\n };\n }(this.chrtData, this.options, this.slice, this.sliceData), false);\n\n var mouseOverFunc = function () {\n\n return function () {\n this.style.background = '#F3F3F3';\n this.style.cursor = 'pointer';\n handleOver(this.chrtData, this.options, this.sliceData);\n };\n };\n\n thisRow.addEventListener(\"mouseover\", mouseOverFunc(this.chrtData, this.options, this.sliceData), false);\n\n thisRow.addEventListener(\"mouseleave\", function (e) {\n if (e.target === this && e.target.clientHeight !== 0) {\n this.style.background = 'transparent';\n this.sliceData.mouseIn = false;\n this.sliceData.focused = false;\n draw(this.chrtData, this.options);\n }\n }, false);\n }\n }\n\n function handleOver(data, options, sliceData) {\n // Assign the hovered element in sliceData\n if (!sliceData.mouseIn) {\n sliceData.mouseIn = true;\n sliceData.focused = true;\n console.log(\"mouse in\");\n draw(data, options);\n }\n return;\n }\n\n /*\n * Handles mouse clicks on legend table rows\n */\n function handleClick(data, options, slice, sliceData) {\n // Reset explode slices\n for (var i = 0; i < data.length; i++) {\n if (i !== slice) {\n data[i].explode = false;\n }\n }\n\n // Check if slice is explode and pull it in or explode it accordingly\n sliceData.explode = (sliceData.explode) ? false : true;\n draw(data, options);\n }\n\n }",
"function refreshLegend() {\n if (isSmall) {\n legend.refresh();\n } else {\n expandLegend.refresh();\n }\n }",
"updateLegendLabel(color, label) {\n let currentLegendData = cloneDeep(this.state.pluginData[\"Legend\"]);\n currentLegendData[this.state.activeEntry][color] = label;\n this.updatePluginData(\"Legend\", currentLegendData);\n }",
"function computeLegend() {\n colorsLegend = [];\n sizesLegend = [];\n sizesLegendText = [];\n R = 0;\n if (sizeType != \"none\" && r!=0 && r!=\"\") {\n if (sizeType == \"scalar\" || sizeType == \"degree\") {\n // test for ints\n var isIntScalar=true,j=0;\n while (j<N && isIntScalar){isIntScalar=isInt(rawSizes[j]); j++;}\n // integer scalars\n if (isIntScalar) {\n var numInts = d3.max(rawSizes)-d3.min(rawSizes)+1;\n // <= 9 values\n if (numInts <= 9){\n sizesLegend = d3.range(d3.min(rawSizes),d3.max(rawSizes)+1);\n }\n // > 9 values\n else\n {\n lower = d3.min(rawSizes);\n upper = d3.max(rawSizes);\n bins = 4;\n step = (upper-lower)/bins;\n sizesLegend.push(lower);\n for (var i=1; i<bins; i++) {sizesLegend.push(lower+i*step);}\n sizesLegend.push(upper);\n }\n }\n // noninteger scalars\n else\n {\n lower = d3.min(rawSizes);\n upper = d3.max(rawSizes);\n bins = 4;\n step = (upper-lower)/bins;\n sizesLegend.push(rounddown(lower,10));\n for (var i=1; i<bins; i++) {sizesLegend.push(round(lower+i*step,10));}\n sizesLegend.push(roundup(upper,10));\n }\n sizesLegendText = sizesLegend.slice(0);\n }\n else if (sizeType == \"binary\") {\n sizesLegendText = [\"false\",\"true\"];\n sizesLegend = [0,1];\n }\n if (sizeType == \"degree\"){\n for (var i in sizesLegend){\n sizesLegend[i] = scaleSize(Math.sqrt(sizesLegend[i]));\n }\n }\n else {\n for (var i in sizesLegend){\n sizesLegend[i] = scaleSize(sizesLegend[i]);\n }\n }\n R = r*d3.max(sizesLegend);\n }\n if (colorType != \"none\") {\n if (colorType == \"categorical\") {\n colorsLegend = scaleColorCategory.domain();\n colorsLegendText = d3.values(catNames);\n }\n else if (colorType == \"binary\") {\n colorsLegend = [0,1];\n colorsLegendText = [\"false\",\"true\"];\n }\n else if (colorType == \"scalar\" || colorType == \"degree\") {\n // test for ints\n var isIntScalar=true,j=0;\n while (j<N && isIntScalar){isIntScalar=isInt(rawColors[j]); j++;}\n // integer scalars\n if (isIntScalar) {\n var numInts = d3.max(rawColors)-d3.min(rawColors)+1;\n // <= 9 values\n if (numInts <= 9){\n colorsLegend = d3.range(d3.min(rawColors),d3.max(rawColors)+1);\n colorsLegendText = colorsLegend.slice(0);\n }\n // > 9 values\n else\n {\n lower = d3.min(rawColors);\n upper = d3.max(rawColors);\n bins = 4;\n step = (upper-lower)/bins;\n colorsLegend.push(lower);\n for (var i=1; i<bins; i++) {colorsLegend.push(lower+i*step);}\n colorsLegend.push(upper);\n colorsLegendText = colorsLegend.slice(0);\n }\n }\n // noninteger scalars\n else\n {\n lower = d3.min(rawColors);\n upper = d3.max(rawColors);\n bins = 4;\n step = (upper-lower)/bins;\n colorsLegend.push(rounddown(lower,10));\n for (var i=1; i<bins; i++) {colorsLegend.push(round(lower+i*step,10));}\n colorsLegend.push(roundup(upper,10));\n colorsLegendText = colorsLegend.slice(0);\n }\n }\n else if (colorType == \"scalarCategorical\") {\n lower = d3.min(rawColors);\n upper = d3.max(rawColors);\n bins = 4;\n step = (upper-lower)/bins;\n colorsLegend.push(lower);\n for (var i=1; i<bins; i++) {colorsLegend.push(Math.round(lower+i*step));}\n colorsLegend.push(upper);\n colorsLegendText = colorsLegend.slice(0);\n }\n }\n drawLegend();\n}",
"function getDatasetInfoById(ds_id) {\n var ds_info, i;\n for (i = 0; i < entry.datasets.length; i++) {\n ds_info = entry.datasets[i];\n if (ds_info[\"id\"] == ds_id) {\n ds_info[\"ref\"] = i; //reference for pulling out datasetinfo from coresponding lists like colorbars\n return ds_info;\n break;\n }\n }\n}",
"createLegends() {\n let legends = [];\n //make on legend for each selected stock\n for (var i in this.state.selectedStocks) {\n var name = this.state.selectedStocks[i][\"name\"];\n var col = this.state.selectedStocks[i][\"color\"];\n var categories = [];\n categories.push({ key: name, label: name });\n\n //style for colored line in legend\n var legendLineStyle = {\n backgroundcolor: col,\n width: \"20px\",\n marginLeft: \"3px\",\n marginRight: \"3px\",\n marginTop: \"10px\",\n height: \"3px\",\n backgroundColor: col,\n float: \"left\"\n };\n\n legends.push(\n <span className=\"legend\">\n <hr style={legendLineStyle} />\n {name}\n </span>\n );\n }\n\n return legends;\n }",
"function chooseAvailableColor() {\n // Count how many times each color is used\n var colorUsage = {};\n colorNames.forEach(function(color) {colorUsage[color] = 0; })\n dataLayers.forEach(function(layer) {\n var color = layer.color;\n if (color in colorUsage)\n colorUsage[color] = colorUsage[color] + 1;\n else\n colorUsage[color] = 1;\n });\n // Convert to array and sort by usage\n colorUsage = Object.entries(colorUsage).sort(function(a,b) {return a[1] - b[1]});\n // Return the first color (the one with the least usage)\n return colorUsage[0][0];\n}",
"function renderLegend() {\n\t\t\titemX = initialItemX;\n\t\t\titemY = y;\n\t\t\toffsetWidth = 0;\n\t\t\tlastItemY = 0;\n\n\t\t\tif (!legendGroup) {\n\t\t\t\tlegendGroup = renderer.g('legend')\n\t\t\t\t\t.attr({ zIndex: 7 })\n\t\t\t\t\t.add();\n\t\t\t}\n\n\n\t\t\t// add each series or point\n\t\t\tallItems = [];\n\t\t\teach(series, function(serie) {\n\t\t\t\tvar seriesOptions = serie.options;\n\n\t\t\t\tif (!seriesOptions.showInLegend) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// use points or series for the legend item depending on legendType\n\t\t\t\tallItems = allItems.concat(seriesOptions.legendType === 'point' ?\n\t\t\t\t\tserie.data :\n\t\t\t\t\tserie\n\t\t\t\t);\n\n\t\t\t});\n\n\t\t\t// sort by legendIndex\n\t\t\tallItems.sort(function(a, b) {\n\t\t\t\treturn (a.options.legendIndex || 0) - (b.options.legendIndex || 0);\n\t\t\t});\n\n\t\t\t// reversed legend\n\t\t\tif (reversedLegend) {\n\t\t\t\tallItems.reverse();\n\t\t\t}\n\n\t\t\t// render the items\n\t\t\teach(allItems, renderItem);\n\n\n\t\t\t// Draw the border\n\t\t\tlegendWidth = widthOption || offsetWidth;\n\t\t\tlegendHeight = lastItemY - y + itemHeight;\n\n\t\t\tif (legendBorderWidth || legendBackgroundColor) {\n\t\t\t\tlegendWidth += 2 * padding;\n\t\t\t\tlegendHeight += 2 * padding;\n\n\t\t\t\tif (!box) {\n\t\t\t\t\tbox = renderer.rect(\n\t\t\t\t\t\t0,\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tlegendWidth,\n\t\t\t\t\t\tlegendHeight,\n\t\t\t\t\t\toptions.borderRadius,\n\t\t\t\t\t\tlegendBorderWidth || 0\n\t\t\t\t\t).attr({\n\t\t\t\t\t\tstroke: options.borderColor,\n\t\t\t\t\t\t'stroke-width': legendBorderWidth || 0,\n\t\t\t\t\t\tfill: legendBackgroundColor || NONE\n\t\t\t\t\t})\n\t\t\t\t\t.add(legendGroup)\n\t\t\t\t\t.shadow(options.shadow);\n\n\t\t\t\t} else if (legendWidth > 0 && legendHeight > 0) {\n\t\t\t\t\tbox.animate(\n\t\t\t\t\t\tbox.crisp(null, null, null, legendWidth, legendHeight)\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// hide the border if no items\n\t\t\t\tbox[allItems.length ? 'show' : 'hide']();\n\t\t\t}\n\n\t\t\t// 1.x compatibility: positioning based on style\n\t\t\tvar props = ['left', 'right', 'top', 'bottom'],\n\t\t\t\tprop,\n\t\t\t\ti = 4;\n\t\t\twhile(i--) {\n\t\t\t\tprop = props[i];\n\t\t\t\tif (style[prop] && style[prop] !== 'auto') {\n\t\t\t\t\toptions[i < 2 ? 'align' : 'verticalAlign'] = prop;\n\t\t\t\t\toptions[i < 2 ? 'x' : 'y'] = pInt(style[prop]) * (i % 2 ? -1 : 1);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlegendGroup.align(extend(options, {\n\t\t\t\twidth: legendWidth,\n\t\t\t\theight: legendHeight\n\t\t\t}), true, spacingBox);\n\n\t\t\tif (!isResizing) {\n\t\t\t\tpositionCheckboxes();\n\t\t\t}\n\t\t}",
"function _initializeLegend(){\r\n // TODO Invoke d3.oracle.ary()\r\n gAry = d3.oracle.ary()\r\n .hideTitle( true )\r\n .showValue( false )\r\n .leftColor( true )\r\n .numberOfColumns( 3 )\r\n .accessors({\r\n color: gLineChart.accessors( 'color' ),\r\n label: gLineChart.accessors( 'series' )\r\n });\r\n\r\n gLegend$ = $( '<div>' );\r\n\r\n if ( pOptions.legendPosition ==='TOP' ) {\r\n gChart$.before( gLegend$ );\r\n } else {\r\n gChart$.after( gLegend$ );\r\n }\r\n }",
"function getSelectedTreat()\n{\n return d3.select('#bar-chart')\n .select(\"#joy-bar-group\")\n .select(\".selected\")\n .data()[0];\n}",
"function getColorMeasureName(chart) {\n const groups = chart.group()\n if (!(groups && groups.reduce)) {\n return null\n }\n const measures = chart.group().reduce()\n if (!Array.isArray(measures)) {\n return null\n }\n\n const colorMeasure = measures.filter(x => x.name === \"color\")\n // This function should always return either a string or null, never \"undefined\", since an\n // \"undefined\" key to the valueFormatter sends us down a weird code path.\n return colorMeasure.length > 0 &&\n typeof colorMeasure[0].measureName !== \"undefined\"\n ? colorMeasure[0].measureName\n : null\n}",
"function drawGexpOverview(i) {\n \n //var gexp = getCol(dataPro,1).map(function(d) { return d.value })\n var gexp = getCol(dataPro,i)\n\n var g = document.getElementById('gexp_panel1'),\n\twindowWidth = g.clientWidth,\n\twindowHeight = g.clientHeight;\n\n var margin = {top: 30, right: 0, bottom: 30, left: 30},\n\twidth = windowWidth - margin.left - margin.right,\n\theight = windowHeight - margin.top - margin.bottom;\n \n var chart1;\n chart1 = makeDistroChart({\n\tdata: gexp,\n\txName:'name',\n\tyName:'value',\n//\taxisLabels: {xAxis: 'Gene', yAxis: 'Values'},\n\tselector:\"#gexp-chart-distro1\",\n\tsvg:\"gexp-chart-distro1-svg\", \n\tchartSize:{height:height, width:width},\n\tmargin:margin,\n\tconstrainExtremes:true});\n chart1.renderBoxPlot();\n chart1.renderDataPlots();\n chart1.renderNotchBoxes({showNotchBox:false});\n chart1.renderViolinPlot({showViolinPlot:false});\n\n var pt = document.getElementById(\"gexp_plottype\").value;\n if(pt == \"box_plot\") {\n\tchart1.boxPlots.show({reset:true});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"notched_box_plot\") {\n\tchart1.notchBoxes.show({reset:true});chart1.boxPlots.show({reset:true, showBox:false,showOutliers:true,boxWidth:20,scatterOutliers:true});chart1.violinPlots.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"violin_plot\") {\t \n\tchart1.violinPlots.show({reset:true, resolution:12});chart1.boxPlots.show({reset:true, showWhiskers:false,showOutliers:false,boxWidth:10,lineWidth:15,colors:['#555']});chart1.notchBoxes.hide();chart1.dataPlots.change({showPlot:false,showBeanLines:false})\n }\n if(pt == \"bean_plot\") {\t \n\tchart1.violinPlots.show({reset:true, width:100, resolution:12});chart1.dataPlots.show({showBeanLines:true,beanWidth:15,showPlot:false,colors:['#555']});chart1.boxPlots.hide();chart1.notchBoxes.hide()\n }\n if(pt == \"beeswam_plot\") {\t \t \n\tchart1.dataPlots.show({showPlot:true, plotType:'beeswarm',showBeanLines:false, colors:null});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.boxPlots.hide();\n }\n if(pt == \"scatter_plot\") {\t \n\tchart1.dataPlots.show({showPlot:true, plotType:40, showBeanLines:false,colors:null});chart1.violinPlots.hide();chart1.notchBoxes.hide();chart1.boxPlots.hide();\n }\n}",
"function Legend() {\n $.jqplot.ElemContainer.call(this);\n // Group: Properties\n \n // prop: show\n // Wether to display the legend on the graph.\n this.show = false;\n // prop: location\n // Placement of the legend. one of the compass directions: nw, n, ne, e, se, s, sw, w\n this.location = 'ne';\n // prop: xoffset\n // offset from the inside edge of the plot in the x direction in pixels.\n this.xoffset = 12;\n // prop: yoffset\n // offset from the inside edge of the plot in the y direction in pixels.\n this.yoffset = 12;\n // prop: border\n // css spec for the border around the legend box.\n this.border;\n // prop: background\n // css spec for the background of the legend box.\n this.background;\n // prop: textColor\n // css color spec for the legend text.\n this.textColor;\n // prop: fontFamily\n // css font-family spec for the legend text.\n this.fontFamily; \n // prop: fontSize\n // css font-size spec for the legend text.\n this.fontSize ;\n // prop: rowSpacing\n // css padding-top spec for the rows in the legend.\n this.rowSpacing = '0.5em';\n // renderer\n // A class that will create a DOM object for the legend,\n // see <$.jqplot.TableLegendRenderer>.\n this.renderer = $.jqplot.TableLegendRenderer;\n // prop: rendererOptions\n // renderer specific options passed to the renderer.\n this.rendererOptions = {};\n // prop: predraw\n // Wether to draw the legend before the series or not.\n this.preDraw = false;\n this.escapeHtml = false;\n this._series = [];\n }",
"beforeUpdate(chart, _args, options) {\n const legend = chart.legend;\n layouts.configure(chart, legend, options);\n legend.options = options;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to calculate total number of possible anagrams | function stringNumOfAnagrams(str) {
for (idx = 0; idx < str.length; idx++) {
anagramCount = (anagramCount * (idx + 1));
}
return anagramCount;
} | [
"function anagramCounter(arrayOfWords) {\n let sortedWords = arrayOfWords.map(word => word.split('').sort().join(''));\n let numberOfAnagrams = 0;\n\n sortedWords.forEach((word, theIndex) => {\n for (let i = theIndex + 1; i < sortedWords.length; i++) {\n if (word === sortedWords[i]) {\n numberOfAnagrams++\n }\n }\n })\n return numberOfAnagrams\n}",
"getAnagrams(letters) {\n if(typeof letters !== 'string') {\n throw(`Anagrams expected string letters, received ${typeof letters}`);\n }\n\n if(letters.length < PERMS_MIN_LEN) {\n throw(`getAnagrams expects at least ${PERMS_MIN_LEN} letters`);\n }\n\n return permutations(letters, trie, {\n type: 'anagram',\n });\n }",
"function makeAnagram(a, b) {\n let count = 0;\n\n //track all the letters that are the longer string and then compare them to the letters from the short string.\n let freq = {};\n\n const longStr = a.length > b.length ? a : b;\n const shortStr = longStr === a ? b : a;\n\n // Log all chars from the long string into an object\n for (let char of longStr) {\n freq[char] >= 0 ? (freq[char] += 1) : (freq[char] = 0);\n }\n\n // see if the character is found in longString --> if so. add to count and subtract from obj\n for (let char of shortStr) {\n if (freq[char] >= 0) {\n count++;\n freq[char] -= 1;\n }\n }\n // The count variable is the common letters between each string\n // subtract count from the length of each string and add result together\n const deletions = longStr.length - count + shortStr.length - count;\n console.log(deletions);\n return deletions;\n}",
"getSubAnagrams(letters) {\n if(typeof letters !== 'string') {\n throw(`Expected string letters, received ${typeof letters}`);\n }\n\n if(letters.length < PERMS_MIN_LEN) {\n throw(`getSubAnagrams expects at least ${PERMS_MIN_LEN} letters`);\n }\n\n return permutations(letters, trie, {\n type: 'sub-anagram',\n });\n }",
"areWordsAnagrams(words) {\n if(words.length === 0) {\n return true;\n }\n\n //All words need to be the same length in order to anagrams\n let length = words[0].length;\n for(let word of words) {\n if(word.length !== length) {\n return false;\n }\n }\n //Bah the worst! Lets go ahead and check the words\n let wordsMap = {};\n for(let word of words) {\n wordsMap[word] = word;\n }\n let localDictionary = new Dictionary(words);\n let anagrams = this.findAnagramsWithoutCache(words[0], localDictionary);\n return (anagrams.length === (words.length - 1));\n }",
"function makeAnagrams(a, b) {\n // O(n*m) approach due to iterating through lengths of both inputs\n let count = 0;\n let arrA = a.split(\"\");\n let arrB = b.split(\"\");\n let totalLength = arrA.length + arrB.length;\n for (let i = 0; i < arrA.length; i++) {\n for (let j = 0; j < arrB.length; j++) {\n if (arrA[i] === arrB[j]) {\n arrB.splice(j, 1);\n count++;\n break;\n }\n }\n }\n return totalLength - count * 2;\n}",
"function numKeypadSolutions(wordlist, keypads) {\n // Write your code here\n // INPUT: an array of acceptable words\n // an array of 7 letter strings, each letter representing a key button\n // OUTPUT: array of numbers corresponding to the number of words from wordlist\n // that can be made from each keypad in order\n // CONSTRAINTS: all words in wordlist are at least 5 letters long\n // first letter of each keypad is guaranteed to be in the word\n // longest word in scrabble dictionary is 15 characters long - must be faster way\n // EDGE CASES: what happens if no letters match?\n\n // iterate over wordlist, and store a set in a new wordlist array of all letters of word\n let wordListSets = wordlist.map(word => {\n let wordSet = new Set();\n for(let i=0; i < word.length; i++) {\n let letter = word[i];\n if(!wordSet.has(letter)) { wordSet.add(letter) }\n }\n return wordSet;\n });\n\n // write a mapping function that takes a keypad string\n // initiates a count at 0\n // makes a set of the string\n // loops through the entire new wordlist array\n // if the word doesn't have keypadstring[0] continue\n // if all letters in word set are contained in string set increment the count\n // return the count\n let numValidSolutions = keypads.map(keyString => {\n let solutionCount = 0;\n let keyStringSet = new Set();\n for(let i=0; i < keyString.length; i++) {\n let letter = keyString[i];\n if(!keyStringSet.has(letter)) { keyStringSet.add(letter) }\n }\n\n for(let j = 0; j < wordListSets.length; j++) {\n let allLettersPresent = true;\n let wordSetInQuestion = wordListSets[j];\n if (!wordSetInQuestion.has(keyString[0])) { continue }\n for(let letter of wordSetInQuestion) {\n if(!keyStringSet.has(letter)) {\n allLettersPresent = false;\n break;\n }\n }\n\n if (allLettersPresent) { solutionCount++ }\n }\n\n return solutionCount;\n })\n\n return numValidSolutions;\n // THE ULTRA 1337 SOLUTION USES A BIT MASK. WTF IS THAT\n}",
"function anagrams(str) {\n if (str.length === 1) {\n return [str];\n } else {\n const allAnagrams = [];\n for (let i = 0; i < str.length; i += 1) {\n const letter = str[i];\n const short = str.substr(0, i) + str.substr(i + 1, str.length - 1);\n const shortAnagrams = anagrams(short);\n for (let j = 0; j < shortAnagrams.length; j += 1) {\n allAnagrams.push(letter + shortAnagrams[j]);\n }\n }\n return [...new Set(allAnagrams)];\n }\n}",
"initAnagramsCache() {\n const keys = Object.keys(this.dictionary.getDictionary());\n const stopWatch = StopWatch.create();\n stopWatch.start();\n const totalKeys = keys.length;\n let numWords = 0;\n for(let key of keys){\n let anagrams = this.findAnagrams(key);\n this.anagramsCache[key] = anagrams.anagrams;\n numWords++;\n if(numWords % 1000 === 0) {\n log.info(numWords + '/' + totalKeys + ' completed');\n }\n if(numWords % 25000 === 0) {\n log.info('25k anagrams completed in: ' + stopWatch.elapsed.seconds + ' seconds');\n }\n }\n stopWatch.stop();\n log.info('Cache completed in: ' + stopWatch.elapsed.seconds + ' seconds');\n }",
"function instagramSticker(phrase) {\n let string = 'instagram'\n let insta = {}\n for (let char of string) {\n insta[char] ? insta[char]++ : insta[char] = 1\n }\n let count = 0\n let word = {}\n let sentence = phrase.split(' ').join('')\n for (let char of sentence) {\n word[char] ? word[char]++ : word[char] = 1\n }\n for (let char in word) {\n let amount = Math.ceil(word[char]/insta[char])\n if (amount > count) count = amount\n }\n return count\n}",
"function aCounter(word) {\n let count = 0;\n let index = 0\n while (index < word.length) {\n let char = word[index];\n if (char === \"a\" || char === \"A\") {\n count += 1;\n }\n index++\n }\n return count;\n }",
"function anagramHelper(str, current, anagrams) {\n if (!str.length && current.length) {\n anagrams.push(current);\n } else {\n for (let i = 0; i < str.length; i++) {\n // base letter, slice and concat\n const newStr = str.slice(0, i).concat(str.slice(i+1));\n const newAna = current.concat(str[i]);\n anagramHelper(newStr, newAna, anagrams);\n }\n }\n}",
"function stringAnagrams(str) {\n var arr = str.split(\"\");\n var result = [];\n var str2 = \"\";\n rStrAnagrams(arr, str2, result);\n return result;\n}",
"function CountAnimals(tur,horse,pigs) {\r\n return (tur*2)+(horse*4)+(pigs*4)\r\n}",
"function update_counts (n, s) {\n digits = PiMill.get_digits(n, s);\n n = digits.length; // In case we went past the end\n for (var i = 0; i < n; i++) {\n digit_counts[digits.charAt(i)]++;\n }\n return n;\n }",
"function answerQuery(l, r) {\n // Return the answer for this query modulo 1000000007.\n const s = word.slice(l - 1, r);\n const wordCount = Array(26);\n for (let i of s) {\n if (!wordCount[i.charCodeAt() - 97]) wordCount[i.charCodeAt() - 97] = 1;\n else wordCount[i.charCodeAt() - 97]++;\n }\n const countMap = {};\n for (let i of wordCount) {\n if (i > 1) {\n if (i % 2 === 0) {\n if (countMap[i]) countMap[i]++;\n else countMap[i] = 1;\n } else {\n if (countMap[i - 1]) countMap[i - 1]++;\n else countMap[i - 1] = 1;\n if (countMap[1]) countMap[1]++;\n else countMap[1] = 1;\n }\n } else if (i === 1) {\n if (countMap[1]) countMap[1]++;\n else countMap[1] = 1;\n }\n }\n console.log(Object.values(countMap).reduce((acc, c) => acc * c, 1));\n}",
"function reducer2(a, e) {\n var summ = 0;\n if (typeof a == \"string\") { // this handles the initial case where the first element is used\n summ = a.length; // as the starting value.\n }\n else {\n summ = a;\n }\n return summ + countLetters(e);\n}",
"function countTinyPairs(a, b, k) {\n let revB = b.reverse();\n let tinyCount = 0;\n\n for (let index = 0; index < a.length; index++) {\n const elementA = a[index];\n const elementB = revB[index];\n let concat = elementA + \"\" + elementB;\n concat = parseInt(concat);\n\n if (concat < k){\n tinyCount += 1;\n }\n }\n\n return tinyCount;\n}",
"function countAs(string) {\n var stringArray = string.split(\"\");\n var count = 0;\n stringArray.forEach(function(letter) {\n if (letter === \"a\") {\n count++;\n }\n });\n return count;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save a cookie for a year. | function setCookie(c_name, value) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + 365);
var c_value = escape(value) + "; expires=" + exdate.toUTCString();
document.cookie = c_name + "=" + c_value;
} | [
"function writeCookie(name, value)\n{\n var expire = \"\";\n expire = new Date((new Date()).getTime() + 24 * 365 * 3600000);\n expire = \"; expires=\" + expire.toGMTString();\n document.cookie = name + \"=\" + escape(value) + expire;\n}",
"function saveYearData() {\n var year = homeControllerVM.homeSelectedRegistrationYear;\n localStorage.setItem('selectedYear', year);\n //var tempYear = localStorage.getItem('selectedYear');\n //homeControllerVM.homeSelectedRegistrationYear = tempYear;\n }",
"function writePersistentCookie (CookieName, CookieValue, periodType, offset) {\nvar expireDate = new Date ();\noffset = offset / 1;\nvar myPeriodType = periodType;\nswitch (myPeriodType.toLowerCase()) {\ncase \"years\": \nvar year = expireDate.getYear(); \n// Note some browsers give only the years since 1900, and some since 0.\nif (year < 1000) year = year + 1900; \nexpireDate.setYear(year + offset);\nbreak;\ncase \"months\":\nexpireDate.setMonth(expireDate.getMonth() + offset);\nbreak;\ncase \"days\":\nexpireDate.setDate(expireDate.getDate() + offset);\nbreak;\ncase \"hours\":\nexpireDate.setHours(expireDate.getHours() + offset);\nbreak;\ncase \"minutes\":\nexpireDate.setMinutes(expireDate.getMinutes() + offset);\nbreak;\ndefault:\nalert (\"Invalid periodType parameter for writePersistentCookie()\");\nbreak;\n} \ndocument.cookie = escape(CookieName ) + \"=\" + escape(CookieValue) + \"; expires=\" + expireDate.toGMTString() + \"; path=/\";\n}",
"function setCookie( /* String */name, /* String */value) {\n\tvar date = new Date();\n\tdate.setFullYear(date.getFullYear() + 20);\n\t$.cookies.del(\"felix-webconsole-\" + name);\n\t$.cookies.set(\"felix-webconsole-\" + name, value, {\n\t\texpiresAt : date,\n\t\tpath : appRoot\n\t});\n}",
"function updateYear(year) {\n homeControllerVM.homeSelectedRegistrationYear = year;\n localStorage.setItem('selectedYear', year);\n }",
"function setSecureCookie(cname, cvalue, exdays) {\r\n var d = new Date();\r\n d.setTime(d.getTime() + (exdays*24*60*60*1000));\r\n var expires = \"expires=\"+ d.toUTCString();\r\n document.cookie = cname + \"=\" + cvalue + \";\" + expires + \";path=/\" + \";secure\";\r\n}",
"function writeCookie(name, value, hours) {\r\n\tvar expire = \"\";\r\n\tif(hours != null) {\r\n\t\texpire = new Date((new Date()).getTime() + hours * 3600000);\r\n\t\texpire = \"; expires=\" + expire.toGMTString() + \"; path=/\";\r\n\t}\r\n\tdocument.cookie = name + \"=\" + escape(value) + expire;\r\n}",
"function setVisits() {\n var firstVisit = getCookie('FirstVisit');\n var lastVisit = getCookie('LastVisit');\n var visits = getCookie('Visits');\n var date = new Date();\n var newDate = date.getTime();\n // date.toUTCString();\n\n if (firstVisit == '') {\n setCookie('FirstVisit', newDate, 365);\n setCookie('Visits', 1, 365);\n }\n\n var hours = ((newDate - lastVisit) / (1000 * 60 * 60)).toFixed(1);\n\n if (hours > 12) {\n visits = visits + 1;\n setCookie('Visits', visits, 365);\n }\n\n setCookie('LastVisit', newDate, 365);\n}",
"function saveLangPreference(lang) {\n //alert(\"saveLangPreference | \"+ lang);\n\ttry{\n\t\tvar date = new Date();\n\t\tdate.setTime(date.getTime()+(999*24*60*60*1000));\n \tvar tmp = window.location.href.substr(7) ;\t\t\n\t\tvar SERVER_NAME = tmp.substr(0, tmp.indexOf(\"http://bet.hkjc.com/\")) ;\n\t\tvar domainName = SERVER_NAME.substr(SERVER_NAME.indexOf(\".\")+1) ;\n\t\tsetCookie('jcbwLangPreference', lang,date,'http://bet.hkjc.com/',domainName); \n\t} catch(e) {};\n\n}",
"set_name (name) {\n this.name = name\n Cookies.set('name', this.name, { expires: this.EXPIRE_DAYS }) \n }",
"function saveToCookies()\n{\n const THREE_YEARS_IN_SEC = 94670777;\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"player_id\",\n \"value\": MY_ID,\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC) });\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"whitelisted_ids_length\",\n \"value\": WHITELISTED_IDS.length.toString(),\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC)});\n for (let index = 0; index < WHITELISTED_IDS.length; index++) {\n const WHITELISTED_ID = WHITELISTED_IDS[index];\n chrome.cookies.set({\n \"url\": DOTABUFF_MATCH_LINK+'*',\n \"name\": \"whitelisted_id\"+index.toString(),\n \"value\": WHITELISTED_ID.toString(),\n \"expirationDate\": ((new Date().getTime() / 1000) + THREE_YEARS_IN_SEC) });\n }\n}",
"function appendInCookie(name, value, days) {\n createCookie(name, readCookie(name)+\" \"+value, days);\n}",
"function savePizzaState() {\n console.log(\"Saving pizza state\");\n Cookies.set(\"version\", CURRENT_VERSION, { expires: 365, path: '/' });\n Cookies.set(\"pizza\", document.getElementById('id_pizza_style').value, { expires: 365, path: '/' });\n Cookies.set(\"dough_balls\", document.getElementById('id_dough_balls').value, { expires: 365, path: '/' });\n Cookies.set(\"size\", document.getElementById('id_size').value, { expires: 365, path: '/' });\n}",
"function saveChar(na, re, gen, gol, sin, le, ti, at){ \n\n\t\t/*console.log( \"\" +\n\n\t\t\tna + ',' + re + ',' + gen + ',' + gold + \",\" + sin + ',' + INDEX + ',' + ti + ',' \n \t+ upgrades.attributes[5].level + \",\" \n \t+ upgrades.attributes[4].level + \",\"\n \t+ upgrades.attributes[3].level + \",\"\n \t+ upgrades.attributes[2].level + \",\"\n \t+ upgrades.attributes[1].level + \",\"\n \t+ upgrades.attributes[0].level + \"\"\n\t\t);*/\n\n \t document.cookie = na + ',' + re + ',' + gen + ',' + gold + \",\" + sin + ',' + INDEX + ',' + ti + ',' \n\t\t\t+ upgrades.attributes[5].level + \",\" \n\t + upgrades.attributes[4].level + \",\"\n\t + upgrades.attributes[3].level + \",\"\n\t + upgrades.attributes[2].level + \",\"\n \t + upgrades.attributes[1].level + \",\"\n \t+ upgrades.attributes[0].level + \"\"\t\n\t \t+ \";expires=Thu, 01 Jan 2020 00:00:00 UTC\";\n\t}",
"function SetProjectDetailsCookies(ProjectCode)\n{\n\t// alert(ProjectCode);\n\tdocument.cookie = \"projectCode=\" + ProjectCode;\n\twindow.location.href = \"ProjectDetails.php?ProjectCode=\"+ProjectCode;\n\tlocalStorage.setItem(\"ProjectCode\", ProjectCode); \n}",
"function setJwtCookie(jwt, response, minutesTilExpire) {\n response.state(_appConfig.settings.get('/JWT/COOKIE/NAME'), jwt, {\n ttl: minutesTilExpire * 60 * 1000, // In milliseconds\n path: _appConfig.settings.get('/JWT/COOKIE/PATH'),\n domain: _appConfig.settings.get('/JWT/COOKIE/DOMAIN')\n });\n}",
"function setTimezoneCookie(timezone) {\n var date = new Date(2099, 1, 1);\n document.cookie = 'timezone=' + timezone + '; path=/; expires=' + date.toUTCString();\n }",
"function saveFavorite(title, year, imdbID, success, error){\n let baseUrl = \"/favorites\";\n let params = {\"Title\":title, \"Year\":year, imdbID};\n baseXHRPost(baseUrl, params, success, error);\n }",
"_initCookies() {\n\n const KEY = window.btoa('' + Math.random() * Math.random() * Math.random() * Math.PI),\n COOKIE = new Cookies(),\n PREFIX = 'default-wid';\n // expire cookie a month from now\n let expDate = new Date(Date.now());\n expDate.setDate(expDate.getDate() + 30);\n COOKIE.set(PREFIX, KEY, { path : '/', expires : expDate });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
End Helper Functions Begin Main Functions =======> main function for Add section And item in navbar | function addnewsection() {
sectionNumber ++;
//=======> Create Anther section
let addSection = document.createElement('section');
addSection.innerHTML = `
<section id="section${sectionNumber}" class="your-active-class">
<div class="landing__container">
<h2 id="se_${sectionNumber}">Section ${sectionNumber}</h2>
<p id="getActive_${sectionNumber}">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi fermentum metus faucibus lectus pharetra dapibus. Suspendisse potenti. Aenean aliquam elementum mi, ac euismod augue. Donec eget lacinia ex. Phasellus imperdiet porta orci eget mollis. Sed convallis sollicitudin mauris ac tincidunt. Donec bibendum, nulla eget bibendum consectetur, sem nisi aliquam leo, ut pulvinar quam nunc eu augue. Pellentesque maximus imperdiet elit a pharetra. Duis lectus mi, aliquam in mi quis, aliquam porttitor lacus. Morbi a tincidunt felis. Sed leo nunc, pharetra et elementum non, faucibus vitae elit. Integer nec libero venenatis libero ultricies molestie semper in tellus. Sed congue et odio sed euismod.</p>
</div>
</section>`;
mainSection.appendChild(addSection);
//=======> Create Anther item in navbar
let addli = document.createElement('li');
addli.innerHTML = `<li ><a id="li_${sectionNumber}" onclick="scroll_to('section${sectionNumber}')">Section ${sectionNumber}</a></li>`;
mynavbar.appendChild(addli);
} | [
"function add_navigation_bar() {\n\tlet nav=document.createElement('nav');\n\tnav.setAttribute('id','minitoc');\n\tdocument.body.insertAdjacentElement('afterbegin',nav);\n\tlet csection=null;\n\tlet csubsection=null;\n\tfor (let slide of slides) if (slide['id']!='outline') {\n\t\tif (slide['section']) {\n\t\t\tlet sname=slide['ssection'] ? slide['ssection'] : slide['section'];\n\t\t\tlet newsection=document.createElement('div');\n\t\t\tnewsection.classList.add('section');\n\t\t\tnewsection.dataset['section']=slide['section'];\n\t\t\tnewsection.innerHTML='<div class=\"title\">'+sname+'</div>';\n\t\t\tcsection=document.createElement('ul');\n\t\t\tcsection.classList.add('slides');\n\t\t\tnewsection.insertAdjacentElement('beforeend',csection);\n\t\t\tnav.insertAdjacentElement('beforeend',newsection);\n\t\t\tcsubsection=null;\n\t\t}\n\t\tif (slide['subsection']) {\n\t\t\tlet cli=document.createElement('li');\n\t\t\tcsubsection=document.createElement('ul');\n\t\t\tcsubsection.dataset['subsection']=slide['subsection'];\n\t\t\tcli.insertAdjacentElement('afterbegin',csubsection);\n\t\t\tcsection.insertAdjacentElement('beforeend',cli);\n\t\t}\n\t\tif (csubsection) csubsection.insertAdjacentHTML('beforeend','<li><a href=\"#'+slide['id']+'\">○</a></li>');\n\t\telse if (csection) csection.insertAdjacentHTML('beforeend','<li><a href=\"#'+slide['id']+'\">○</a></li>');\n\t};\n}",
"addToNavBar() {\r\n const link = $$(\"<a>\");\r\n link.className = \"nav-item nav-link\";\r\n link.href = \"/money/account/\" + this.model.id;\r\n link.textContent = this.model.name;\r\n $$(\".navbar-nav\").appendChild(link);\r\n }",
"function buildNav(){\n for (const section of sections){\n const item=document.createElement(\"li\");\n const link=document.createElement(\"a\");\n link.textContent=section.dataset.nav;\n link.setAttribute(\"href\",\"#\"+section.id);\n item.classList.add(\"item\");\n item.appendChild(link);\n if (section.classList.contains(\"your-active-class\")){\n item.classList.add(\"active\");\n }\n document.querySelector(\"#navbar__list\").appendChild(item);\n }\n}",
"function addSection(id)\n{\n current_template_index=0;\n\n var sectionID = \"section-\"+current_section_index;\n\n showSidebarBrowser();\n $(\".browser-menu-item\").each(function(){\n $(this).prop(\"disabled\", false);\n });\n $(\".sidebar-browser\").attr(\"id\", sectionID);\n $(\".sidebar-browser\").data(\"template-index\", current_template_index);\n\n //html for sidebar section input\n var sectionHtml =\n '<div class=\"sidebar-item sidebar-section\"'+\n 'id=\"'+sectionID+'\">' +\n getSidebarButtonHtml(sectionID) +\n\n '<button class=\"sidebar-btn glyphicon glyphicon-remove remove-section-btn\"'+ //remove section btn\n ' data-section-index=\"'+current_section_index+'\"></button>'+\n '<span id=\"sidebar-title-section-'+ current_section_index +'\">Section Name</span>'+\n '<button class=\"sidebar-btn fa fa-toggle-on toggle-linebreak\"'+ //toggle line break btn\n ' data-section-index=\"'+current_section_index+'\"></button>'+\n '</div>';\n\n current_section_index+=1;\n\n\n $(\".section-list\").append(sectionHtml);\n\n var sectionHtml = '<div class=\"section\" id=\"'+sectionID+'-html\"></div>';\n $(\"#section-container\").append(sectionHtml);\n}",
"function addSlidesNavigation(section,numSlides){appendTo(createElementFromHTML('<div class=\"'+SLIDES_NAV+'\"><ul></ul></div>'),section);var nav=$(SLIDES_NAV_SEL,section)[0];//top or bottom\naddClass(nav,'fp-'+options.slidesNavPosition);for(var i=0;i<numSlides;i++){appendTo(createElementFromHTML('<li><a href=\"#\"><span class=\"fp-sr-only\">'+getBulletLinkName(i,'Slide')+'</span><span></span></a></li>'),$('ul',nav)[0]);}//centering it\ncss(nav,{'margin-left':'-'+nav.innerWidth/2+'px'});addClass($('a',$('li',nav)[0]),ACTIVE);}",
"function buildNav() {\n for (section of sections) {\n target = section.id;\n sectionTitle = section.dataset.nav;\n createMenuItem(target, sectionTitle);\n }\n}",
"function CreateNavbarItem(name, navbar) {\n\tvar navbarItem = document.createElement(\"A\");\n\t\n\tnavbarItem.setAttribute(\"id\", name);\n\tnavbarItem.setAttribute(\"class\", \"navbarItem\");\n\tnavbarItem.setAttribute(\"href\", name + \".html\");\n\tnavbarItem.innerHTML = name;\n\tnavbar.insertBefore(navbarItem, navbar.childNodes[0]);\n}",
"function insertAPISection() {\n //LOGGER.debug(\"FMA insertAPISection Function Executing\");\n\n let fmaUI = $('<div id=\"fmaapistatus\" class=\"sbar-stat\"><h4 class=\"wlinepad\"><span class=\"hd\">FMA API</span></h4></div>').hide();\n\n if (DEBUG)\n fmaUI.css({\n border: '1px dotted red',\n });\n\n let fmaStatusBlock = $(\n '<a class=\"lbut-lt\" id=\"lbut-lt-fma-api-album-id\">»</a> <a class=\"lbut-lt\" id=\"lbut-lt-fma-api-key-id\">»</a> <a id=\"lbut-lt-fma-api-album\" class=\"lbut-lt\">Album info retrieved</a><a class=\"lbut-lt\" id=\"lbut-lt-fma-api-tracks\">Track info retrieved</a>'\n );\n fmaUI.append(fmaStatusBlock);\n\n insertMbUI(fmaUI); // Insert the FMA API Status UI\n\n $('#fmaapistatus').css({\n display: 'inline-block',\n float: 'left',\n height: '120px',\n width: '49%',\n });\n\n fmaUI.slideDown();\n}",
"function renderNavbar() {\n const homeLink = document.createElement('li');\n homeLink.innerText = 'Home';\n homeLink.className = 'menu__link';\n homeLink.onclick = () => scrollTo();\n navbarList.appendChild(homeLink);\n sections.forEach(section => {\n if (!section.dataset || !section.dataset.nav) return;\n const item = document.createElement('li');\n item.innerText = section.dataset.nav;\n item.className = 'menu__link';\n item.onclick = () => scrollTo($(`#${section.id}`));\n navbarList.appendChild(item);\n });\n}",
"function navbarsub(path, loc){\r\r\n\tnavbarhead();\r\r\n\tnavbarhome();\r\r\n\tnavbariter(path);\r\r\n\tnavbarend(loc);\r\r\n}",
"function navbarinfo(path, loc){\r\r\n\tnavbarhead();\r\r\n\tnavbarhome();\r\r\n\tnavbariter(path);\r\r\n\tnavbarend(loc);\r\r\n}",
"function fillNav()\n {\n //make buttons\n var forecast = makeNewButton('Forecast')\n forecast.setAttribute('class', 'col forecast')\n\n var almanac = makeNewButton('Almanac')\n almanac.setAttribute('class', 'col almanac')\n \n var astronomy = makeNewButton('Astronomy')\n astronomy.setAttribute('class', 'col astronomy')\n\n var conditions = makeNewButton('Update Conditions')\n conditions.setAttribute('class', 'col conditions')\n\n //add buttons to nav\n var nav = $('nav')\n nav.append(almanac)\n nav.append(astronomy)\n nav.append(conditions)\n nav.append(forecast)\n }",
"function createEventNavBar() {\n $(\"#nav-bar\").html(\"\");\n for (let i = 0; i < events.length; i++) {\n let navBar = $('<button class = \"event-nav-bar nav-btn\"> </button>');\n // navBar.attr(\"href\", \"#\" + events[i]);\n navBar.attr(\"id\", \"ev-\" + parseInt(i));\n navBar.text(events[i]);\n $(\"#nav-bar\").append(navBar);\n navBar.css({ display: \"flex\" }, { \"flex-direction\": \"column\" });\n }\n}",
"function createFunctionNavBar() {\n $(\"#nav-bar\").html(\"\");\n for (let i = 0; i < functions.length; i++) {\n let navBar = $('<button class = \"function-nav-bar nav-btn\"> </button>');\n // navBar.attr(\"href\", \"#\" + functions[i]);\n navBar.attr(\"id\", \"fc-\" + parseInt(i));\n navBar.text(functions[i]);\n $(\"#nav-bar\").append(navBar);\n navBar.css({ display: \"flex\" }, { \"flex-direction\": \"column\" });\n }\n}",
"accountPageToHeader(){\n if(JSON.parse(sessionStorage.getItem(\"userData\")).Status === \"admin\")\n return (<Menu.Item key = \"AddAccountPage\">\n <a href=\"/#\" onClick={() => this.handleClick(\"AddAccountPage\")}>\n Hantera användare\n </a>\n </Menu.Item>);\n \n }",
"function placeMasterPage() {\r\n addHeader();\r\n addFooter();\r\n addAside();\r\n addLastArticles();\r\n addGroupArchives();\r\n}",
"showSection() {\n\n //close other sections\n shared.closeSections();\n\n //show \"my tickets\"\n $(\"#my_tickets_section\").css(\"display\", \"block\");\n\n //update nav bar\n navBar.setManageDisplay();\n\n navBar.setMenuItem(NAV_MY_TICKETS, true, true);\n navBar.setMenuItem(NAV_MANAGE_TICKETS, false, false);\n navBar.setMenuItem(NAV_LOG_OUT, false, false);\n\n //fill \"my tickets\" table\n this.fillTicketTable();\n }",
"function assignNavAndSidebarHeaders() {\n\t\t\t$(\"#area-blank1 h3\").text(sgeonames[0]);\n\t\t\t$(\"#left-sidebar h3\").text(sgeonames[0]+\" Projects by :\");\n\n\t\t $(\".area-blank\").css(\"display\", \"inline-block\");\n\t\t if (sgeonames[1]) {\n\t\t \t$(\"#area-blank2 h3\").text(sgeonames[1]);\n\t\t\t\t$(\"#right-sidebar h3\").text(sgeonames[1]+\" Projects by :\");\n\t\t \t$(\"#data-buttons\").css(\"display\", \"inline-block\");\n\t\t }\n\t\t}",
"appendCurrentHeader(header) {\n this.currentSectionContent += header + \"\\n\";\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Acquires the lock, waiting if necessary for it to become free if it is already locked. The returned promise is fulfilled once the lock is acquired. After acquiring the lock, you must call `release` when you are done with it. | acquireAsync(timeout) {
if (!this._acquired) {
this._acquired = true;
return Promise.resolve();
}
return new Promise((resolve, reject) => {
//
this._waitingResolvers.push(resolve);
//
if (timeout && timeout > 0) {
//
setTimeout(() => {
//
const index = this._waitingResolvers.indexOf(resolve);
if (index === -1) {
//
// console.info(`has already got lock`);
// has already get locker
} else {
//
this._waitingResolvers.splice(index, 1);
//
const err = new WizTimeoutError(`lock timeout: ${timeout}, waiting resolves: ${this._waitingResolvers.length}`);
reject(err);
//
}
//
}, timeout);
}
//
});
} | [
"async function withLock (productId, transaction, timeout) {\n\n // if there's already a lock on this id...\n if (locks[productId]) {\n\n // and we've exhausted the timeout…\n if (timeout <= 0) {\n // throw an error\n throw new Error('Unable to acquire lock');\n }\n\n // otherwise wait 100ms…\n await sleep(100);\n\n // …and try again, reducing the timeout\n return withLock(productId, transaction, timeout - 100);\n }\n\n // no existing lock on this productId; proceed.\n try {\n // establish the lock so other calls on this id have to wait\n locks[productId] = true;\n\n // perform the transaction\n return await transaction();\n }\n finally {\n // and release the lock\n delete locks[productId];\n }\n}",
"_ensure_future() {\n let ptrobj = _getPtr(this);\n let resolveHandle;\n let rejectHandle;\n let promise = new Promise((resolve, reject) => {\n resolveHandle = resolve;\n rejectHandle = reject;\n });\n let resolve_handle_id = Module.hiwire.new_value(resolveHandle);\n let reject_handle_id = Module.hiwire.new_value(rejectHandle);\n let errcode;\n try {\n errcode = Module.__pyproxy_ensure_future(\n ptrobj,\n resolve_handle_id,\n reject_handle_id\n );\n } catch (e) {\n Module.fatal_error(e);\n } finally {\n Module.hiwire.decref(reject_handle_id);\n Module.hiwire.decref(resolve_handle_id);\n }\n if (errcode === -1) {\n Module._pythonexc2js();\n }\n return promise;\n }",
"lock() {\n const iab = this.iab;\n const stateIdx = this.ibase;\n var c;\n if ((c = Atomics.compareExchange(iab, stateIdx,\n UNLOCKED, LOCKED_NO_WAITERS)) !== UNLOCKED) {\n do {\n if (c === LOCKED_POSSIBLE_WAITERS\n || Atomics.compareExchange(iab, stateIdx,\n LOCKED_NO_WAITERS, LOCKED_POSSIBLE_WAITERS) !== UNLOCKED) {\n Atomics.wait(iab, stateIdx,\n LOCKED_POSSIBLE_WAITERS, Number.POSITIVE_INFINITY);\n }\n } while ((c = Atomics.compareExchange(iab, stateIdx,\n UNLOCKED, LOCKED_POSSIBLE_WAITERS)) !== UNLOCKED);\n }\n }",
"refreshLockToken() {\n const lock = this.getLock();\n\n return new Promise((resolve, reject) => {\n // checkSession does not seem to work without a redirectUri\n // @see https://github.com/auth0/lock/issues/1237\n lock.checkSession({\n redirectUri: window.location.origin\n }, (err, authResult) => {\n if (err) {\n reject(err);\n } else {\n this.setSession(authResult);\n resolve();\n }\n });\n });\n }",
"get locker() {\n return this._locker || (this._locker = new InMemoryLock())\n }",
"function acquire (chain) {\n var resolver = pool.pop() || factory();\n\n // Reset the state of the resolver\n resolver.locks = 0;\n resolver.chain = chain;\n while (resolver.resolved.length > 0) {\n resolver.resolved.pop();\n }\n while (resolver.filters.length > 0) {\n resolver.filters.pop();\n }\n\n return resolver;\n}",
"lock() {\n if (this.isLocked) {\n throw new Error(\"The stream '\" + this + \"' has already been used.\");\n }\n this.isLocked = true;\n if (this.previous) {\n this.previous.lock();\n }\n }",
"async getFork(id) {\n const lock = await Lock.acquire(lockName(id));\n this.reportFork(id, true);\n return lock;\n }",
"get locked() { return false }",
"function liftWithGuard(promise, guard) {\n return promise.then(function (data) {\n return new DummyPromise(function (resolve, reject) {\n if (guard(data)) {\n resolve(data);\n }\n else {\n reject(data);\n }\n });\n });\n }",
"function getScriptLock(){\n if (constants.lock) throw new Error('Global script lock already exists');\n constants.lock = LockService.getScriptLock();\n constants.lock.waitLock(10000);\n}",
"function _wrapInPromise(value) {\n\t\t\treturn $q.when(value);\n\t\t}",
"function SingletonLock() {}",
"async lock(req, doc, tabId, options) {\n if (!options) {\n options = {};\n }\n if (!(req && req.res)) {\n // Use 'error' because this is always a code bug, not a bad\n // HTTP request, and the message should not be disclosed to the client\n throw self.apos.error('error', 'You forgot to pass req as the first argument');\n }\n if (!doc && doc._id) {\n throw self.apos.error('invalid', 'No doc was passed');\n }\n const _id = doc._id;\n if (!tabId) {\n throw self.apos.error('invalid', 'no tabId was passed');\n }\n let criteria = { _id };\n if (!options.force) {\n criteria.$or = [\n {\n advisoryLock: {\n $exists: 0\n }\n },\n {\n 'advisoryLock.updatedAt': {\n $lt: self.getAdvisoryLockExpiration()\n }\n },\n {\n 'advisoryLock._id': tabId\n }\n ];\n }\n // Prevent nuisance locking by matching only\n // documents the user can edit\n criteria = {\n $and: [\n criteria,\n self.apos.permission.criteria(req, 'edit')\n ]\n };\n doc.advisoryLock = {\n username: req.user && req.user.username,\n title: req.user && req.user.title,\n _id: tabId,\n updatedAt: new Date()\n };\n const result = await self.db.updateOne(criteria, {\n $set: {\n advisoryLock: doc.advisoryLock\n }\n });\n if (!result.result.nModified) {\n const info = await self.db.findOne({\n _id\n }, {\n projection: {\n advisoryLock: 1\n }\n });\n if (!info) {\n throw self.apos.error('notfound');\n }\n if (!info.advisoryLock) {\n // Nobody else has a lock but you couldn't get one —\n // must be permissions\n throw self.apos.error('forbidden');\n }\n if (!info.advisoryLock) {\n // Nobody else has a lock but you couldn't get one —\n // must be permissions\n throw self.apos.error('forbidden');\n }\n if (info.advisoryLock.username === req.user.username) {\n throw self.apos.error('locked', {\n me: true\n });\n }\n throw self.apos.error('locked', {\n title: info.advisoryLock.title,\n username: info.advisoryLock.username\n });\n }\n }",
"function cacheNewJwtPromise(jwt, minutesTilExpire) {\n\n return new Promise(function (resolve, reject) {\n let createTime = new Date(),\n expireTime = new Date();\n\n expireTime.setMinutes(expireTime.getMinutes() + minutesTilExpire);\n\n // Save jwt into redis cache\n // \"key\" = jwt, \"value\" = { \"expireTime\": expireTime }\n // Other properties can be added to the \"value\" property later if we need to store other data for the user\n cache.getRedisClient().hset(jwt, _appConfig.settings.get('/REDIS_USER_KEYS/EXPIRE_TIME'), expireTime, function (err, result) {\n if (err) {\n return {\n \"ERROR_CODE\": \"USCNODE001\",\n \"STATUS_CODE\": 503,\n \"ERROR_DESCRIPTION\": \"Cannot connect to Redis cache server\"\n };\n } else {\n cache.getRedisClient().expire(jwt, minutesTilExpire * 60, function (err, result) {\n if (err) {\n return {\n \"ERROR_CODE\": \"USCNODE001\",\n \"STATUS_CODE\": 503,\n \"ERROR_DESCRIPTION\": \"Cannot connect to Redis cache server\"\n };\n } else {\n return resolve(jwt);\n }\n });\n }\n });\n });\n}",
"waitFor(keypath) {\n // Set up a promise for when the result comes in\n return new Promise((resolve, reject) => {\n this.once(keypath, (value) => {\n resolve(value)\n })\n })\n }",
"async request(keypath) {\n \n if (this.isCachedInMemory(keypath)) {\n // We have it in memory so skip the stack and publish the value\n let value = this.getFromMemory(keypath)\n // Publish for anyone waiting on it\n this.publishKeypath(keypath, value)\n // Return it (we are async so this wraps as a promise)\n return value\n }\n \n // Otherwise we need to wait at least for disk\n let promise = this.waitFor(keypath)\n\n // Just dump it into the stack.\n // TODO: It would be more debuggable to vet it here\n this.stack.push(keypath)\n\n if (!this.running) {\n // We just disturbed a sleeping Datasource, so start processing stuff\n \n this.running = true\n\n // Schedule the waiting tasks to be handled\n timers.setImmediate(() => {\n this.processStack()\n })\n }\n\n return promise\n }",
"getPromise(eventName) {\n const existing = this.promises.get(eventName);\n if (existing !== undefined) {\n return existing;\n }\n\n const created = new Promise((resolve, reject) => {\n const subscription = this.onDid(eventName, payload => {\n subscription.dispose();\n this.promises.delete(eventName);\n resolve(payload);\n });\n });\n this.promises.set(eventName, created);\n return created;\n }",
"async function rebuildPackageLocks() {\n const project = new Project(process.cwd());\n\n await removePackageLocks(project);\n console.log('Running npm install...');\n execSync('npm install');\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Language: JSON Description: JSON (JavaScript Object Notation) is a lightweight datainterchange format. | function json(hljs) {
const LITERALS = {
literal: 'true false null'
};
const ALLOWED_COMMENTS = [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
];
const TYPES = [
hljs.QUOTE_STRING_MODE,
hljs.C_NUMBER_MODE
];
const VALUE_CONTAINER = {
end: ',',
endsWithParent: true,
excludeEnd: true,
contains: TYPES,
keywords: LITERALS
};
const OBJECT = {
begin: /\{/,
end: /\}/,
contains: [
{
className: 'attr',
begin: /"/,
end: /"/,
contains: [hljs.BACKSLASH_ESCAPE],
illegal: '\\n'
},
hljs.inherit(VALUE_CONTAINER, {
begin: /:/
})
].concat(ALLOWED_COMMENTS),
illegal: '\\S'
};
const ARRAY = {
begin: '\\[',
end: '\\]',
contains: [hljs.inherit(VALUE_CONTAINER)], // inherit is a workaround for a bug that makes shared modes with endsWithParent compile only the ending of one of the parents
illegal: '\\S'
};
TYPES.push(OBJECT, ARRAY);
ALLOWED_COMMENTS.forEach(function(rule) {
TYPES.push(rule);
});
return {
name: 'JSON',
contains: TYPES,
keywords: LITERALS,
illegal: '\\S'
};
} | [
"function JsonDiff() {\n ;\n}",
"function toJson(o) { return JSON.stringify(o); }",
"function rehype2json() {\n this.Compiler = node => {\n const rootNode = getRootNode(node)\n visit(rootNode, removePositionFromNode)\n return JSON.stringify(rootNode)\n }\n}",
"convertToJSON(potentialJSON) { return convertToJSON(potentialJSON); }",
"function JSONChecker()\n{\n}",
"function LoadJson(){}",
"function jsonify(userInput){\n\treturn JSON.stringify(userInput);\n}",
"function JSONViewer (value) {\n this.value = value;\n}",
"function parseJSON(string) {\n function dateReviver(key, value) {\n var a;\n if (typeof value === 'string') {\n a = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2}(?:\\.\\d*)?)Z$/.exec(value);\n if (a) {\n return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],\n +a[5], +a[6]));\n }\n }\n return value;\n }\n\n return JSON.parse(string, dateReviver);\n }",
"function jsonObjectsToArrayHandler(data) {\n var str = \"[\" + data.replace(/\\n/g, \" \").replace(/\\}\\s*\\{/g, \"}, {\") + \"]\";\n return angular.fromJson(str);\n}",
"toJSON() {\n return {\n firstName: this.firstName,\n lastName: this.lastName,\n age: this.#age\n }\n }",
"function downloadJSON() {\r\n\t// Save the data object as a string into a file\r\n\tsaveTextAsFile(2);\r\n}",
"function ParseJson(jsonStr) {\r\n\r\n\t// Create htmlfile COM object\r\n\tvar HFO = CreateOleObject(\"htmlfile\"), jsonObj;\r\n\r\n\t// force htmlfile to load Chakra engine\r\n\tHFO.write(\"<meta http-equiv='x-ua-compatible' content='IE=9' />\");\r\n\r\n\t// Add custom method to objects\r\n\tHFO.write(\"<script type='text/javascript'>Object.prototype.getProp=function(t){return this[t]},Object.prototype.getKeys=function(){return Object.keys(this)};</script>\");\r\n\r\n\t// Parse JSON string\r\n\ttry jsonObj = HFO.parentWindow.JSON.parse(jsonStr);\r\n\texcept jsonObj = \"\"; // JSON parse error\r\n\r\n\t// Unload COM object\r\n\tHFO.close();\r\n\r\n\treturn jsonObj;\r\n}",
"constructor() {\n super(expressionType_1.ExpressionType.Json, Json.evaluator(), returnType_1.ReturnType.Object, Json.validator);\n }",
"function CreateJsonGrammar(myna) \n{\n // Setup a shorthand for the Myna parsing library object\n let m = myna; \n\n let g = new function() \n {\n // These are helper rules, they do not create nodes in the parse tree. \n this.escapedChar = m.seq('\\\\', m.char('\\\\/bfnrt\"'));\n this.escapedUnicode = m.seq('\\\\u', m.hexDigit.repeat(4)); \n this.quoteChar = m.choice(this.escapedChar, this.escapedUnicode, m.charExcept('\"'));\n this.fraction = m.seq(\".\", m.digit.zeroOrMore); \n this.plusOrMinus = m.char(\"+-\");\n this.exponent = m.seq(m.char(\"eE\"), this.plusOrMinus.opt, m.digits); \n this.comma = m.text(\",\").ws; \n\n // The following rules create nodes in the abstract syntax tree \n \n // Using a lazy evaluation rule to allow recursive rule definitions \n let _this = this; \n this.value = m.delay(function() { \n return m.choice(_this.string, _this.number, _this.object, _this.array, _this.bool, _this.null); \n }).ast;\n\n this.string = m.doubleQuoted(this.quoteChar.zeroOrMore).ast;\n this.null = m.keyword(\"null\").ast;\n this.bool = m.keywords(\"true\", \"false\").ast;\n this.number = m.seq(this.plusOrMinus.opt, m.integer, this.fraction.opt, this.exponent.opt).ast;\n this.array = m.bracketed(m.delimited(this.value.ws, this.comma)).ast;\n this.pair = m.seq(this.string, m.ws, \":\", m.ws, this.value.ws).ast;\n this.object = m.braced(m.delimited(this.pair.ws, this.comma)).ast;\n };\n\n return m.registerGrammar(\"json\", g);\n}",
"function genApplicationJson() {\n return encodeURIComponent(\"application/json\");\n }",
"function exerciseToJSON() {\n //get data from form\n const routineName = routineNameRef.current.value\n const numberOfRounds = numberOfRoundsRef.current.value\n const restBetweenRounds = restBetweenRoundsRef.current.value\n\n //put data into a JSON\n routineJSON.RoutineName = routineName\n routineJSON.NumberOfRounds = numberOfRounds\n routineJSON.RestBetweenRounds = restBetweenRounds\n routineJSON.ExerciseList = exerciseList.toString()\n\n //send JSON to backend with a function call\n console.log( JSON.stringify( routineJSON ) )\n\n //Display confirmation message\n window.alert( \"Congratulations, you have saved a new workout routine!\" )\n\n //Clear Form\n clearForm()\n }",
"function stringifyJSON(obj) {\n // your code goes here\n\n //check for single values\n var singleValue = stringifySingleValues(obj);\n if(singleValue !== false){\n return singleValue;\n }\n\n var jsonParsedFilling = '';\n\n //check for arrays\n if(Array.isArray(obj)){\n jsonParsedFilling = stringifyArrays(obj);\n return jsonParsedFilling;\n\n }\n\n// objects\n jsonParsedFilling = stringifyObjects(obj);\n return jsonParsedFilling;\n}",
"function writeJSON(database) {\n let jsonFile = `[`;\n // Generates unique id for new note\n let id = generateUniqueId({\n length: 10\n });\n\n for (var i = 0; i < database.length; i++) {\n // Correctly formats JSON line breaks\n database[i].text = database[i].text.replace(/(\\r\\n|\\n|\\r)/gm, \"\\\\n\");\n\n // Sets id property of new note object in database array\n if (i === 0) {\n database[i].id = id;\n currentId = database[i].id;\n }\n\n if (i < database.length - 1) {\n jsonFile += `\n {\n \"title\": \"${database[i].title}\",\n \"text\": \"${database[i].text}\",\n \"id\": \"${database[i].id}\"\n },`\n } else {\n jsonFile += `\n {\n \"title\": \"${database[i].title}\",\n \"text\": \"${database[i].text}\",\n \"id\": \"${database[i].id}\"\n }\n]`\n }\n }\n return jsonFile;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Does a binary search on the timeline array and returns the nearest event index whose time is after or equal to the given time. If a time is searched before the first index in the timeline, 1 is returned. If the time is after the end, the index of the last item is returned. | _search(time, param = "time") {
if (this._timeline.length === 0) {
return -1;
}
let beginning = 0;
const len = this._timeline.length;
let end = len;
if (len > 0 && this._timeline[len - 1][param] <= time) {
return len - 1;
}
while (beginning < end) {
// calculate the midpoint for roughly equal partition
let midPoint = Math.floor(beginning + (end - beginning) / 2);
const event = this._timeline[midPoint];
const nextEvent = this._timeline[midPoint + 1];
if ((0, _Math.EQ)(event[param], time)) {
// choose the last one that has the same time
for (let i = midPoint; i < this._timeline.length; i++) {
const testEvent = this._timeline[i];
if ((0, _Math.EQ)(testEvent[param], time)) {
midPoint = i;
} else {
break;
}
}
return midPoint;
} else if ((0, _Math.LT)(event[param], time) && (0, _Math.GT)(nextEvent[param], time)) {
return midPoint;
} else if ((0, _Math.GT)(event[param], time)) {
// search lower
end = midPoint;
} else {
// search upper
beginning = midPoint + 1;
}
}
return -1;
} | [
"function findNearest(time, callback){\n for(i = 0; i < timestamps.length; i++)\n if (timestamps[i] > time){\n callback(measurments[i]);\n break;\n }\n}",
"bisect(t, b) {\n const tms = t.getTime();\n const size = this.size();\n let i = b || 0;\n\n if (!size) {\n return undefined;\n }\n\n for (; i < size; i++) {\n const ts = this.at(i).timestamp().getTime();\n if (ts > tms) {\n return i - 1 >= 0 ? i - 1 : 0;\n } else if (ts === tms) {\n return i;\n }\n }\n return i - 1;\n }",
"function findSlideNum(time) { //Pre: time is in milliseconds\n let low = 0, high = slides.length - 2, average = Math.floor( (low + high) / 2 );\n\n while (low + 1 != high){\n\n if (slides[average].mark < time){\n low = average;\n average = Math.floor((average + high) / 2);\n }\n else if (slides[average].mark > time){\n high = average;\n average = Math.floor((low + average) / 2);\n }\n else {\n return average;\n }\n }\n\n if (slides[average].mark <= time) {\n return low;\n }\n\n return high;\n }",
"function lastTime(arr, num) {\n // for (let i = arr.length - 1; i >= 0; i--) {\n // let num = arr[i];\n // if (num == target) {\n // return i;\n // }\n // }\n let targetIndex;\n for (let i = 0; i < arr.length; i++) {\n let num = arr[i];\n if (num == target) {\n targetIndex = i;\n }\n }\n}",
"function calculateIndex(time) {\n let data = time.split(\":\");\n let currentTime = parseInt(data[0], 10) * 60 + parseInt(data[1], 10);\n let rangeMinutes = parseInt(process.env.rangeMinutes, 10);\n let timeStart = parseInt(process.env.timeStart, 10);\n return Math.floor((currentTime - timeStart) / rangeMinutes);\n}",
"function findStopLessThanOrEqualTo$1(stops, input) {\n var n = stops.length;\n var lowerIndex = 0;\n var upperIndex = n - 1;\n var currentIndex = 0;\n var currentValue, upperValue;\n\n while (lowerIndex <= upperIndex) {\n currentIndex = Math.floor((lowerIndex + upperIndex) / 2);\n currentValue = stops[currentIndex][0];\n upperValue = stops[currentIndex + 1][0];\n if (input === currentValue || input > currentValue && input < upperValue) {\n // Search complete\n return currentIndex;\n } else if (currentValue < input) {\n lowerIndex = currentIndex + 1;\n } else if (currentValue > input) {\n upperIndex = currentIndex - 1;\n }\n }\n\n return Math.max(currentIndex - 1, 0);\n }",
"getSessionForTime(time) {\n const finalSession = this.sessions_[this.sessions_.length - 1];\n\n for (let i = 0; i < this.sessions_.length; ++i) {\n if (this.sessions_[i].beginTime >= time && this.sessions_[i].endTime < time)\n return this.sessions_[i]; // exact match\n\n if (this.sessions_[i].endTime < time)\n continue; // the session is in the past\n\n if (this.sessions_[i].beginTime < finalSession.beginTime)\n return this.sessions_[i]; // session that's nearest in the future\n }\n\n return finalSession;\n }",
"getNearestTime (step, time) {\n\t\tlet prev = this.getPreviousTime(step, time);\n\t\tlet next = this.getNextTime(step, time);\n\t\tif (time - prev <= next - time)\n\t\t\treturn prev;\n\t\treturn next;\n\t}",
"function getCurrent()\n{\n var au=document.getElementById(\"poemAudio\");\n var allLyrics=document.getElementById(\"poemContent\");\n var i=0;\n if(au.currentTime>=timeArray[timeArray.length-1])\n {\n return timeArray.length-1;\n }\n if(timeArray[0]<=au.currentTime && timeArray[1]>=au.currentTime)\n {\n return 0;\n }\n for(i=1;i<timeArray.length;i++)\n {\n if(timeArray[i]>au.currentTime)\n {\n return i-1;\n }\n }\n return i-2;\n}",
"findIndex(pos, end, side = end * Far, startAt = 0) {\n if (pos <= 0)\n return startAt;\n let arr = end < 0 ? this.to : this.from;\n for (let lo = startAt, hi = arr.length;;) {\n if (lo == hi)\n return lo;\n let mid = (lo + hi) >> 1;\n let diff = arr[mid] - pos || (end < 0 ? this.value[mid].startSide : this.value[mid].endSide) - side;\n if (mid == lo)\n return diff >= 0 ? lo : hi;\n if (diff >= 0)\n hi = mid;\n else\n lo = mid + 1;\n }\n }",
"function binarySearch(arr, value) {\n let low = 0;\n let high = arr.length - 1;\n\n while (low <= high) {\n let mid = Math.floor(low + (high - low) / 2);\n if (arr[mid] === value) {\n return mid\n } else if (arr[mid] < value) {\n low = mid + 1;\n } else { //arr[mid] > value\n high = mid - 1;\n }\n }\n\n return -1;\n}",
"getStartPointForTask (event) {\n let start = false;\n let rest = Infinity;\n\n //Check Space between Events currently in the Sequence\n let lastEvent;\n this.sequence.forEach((e, i) => {\n if (i !== 0) {\n const length = this.sequence[i].time.end - lastEvent.time.end;\n if(length > event.time.duration && rest > length - event.time.duration) {\n rest = length - event.time.duration;\n start = this.sequence[i].time.end + 1;\n }\n }\n });\n\n //Get Index of this SequenceElement in the Parent SequenceList\n const id = this.sequenceList.indexOf(this);\n\n //Get SequenceElements next to current Element with different location\n const prev = this.findNextLocation(id, -1);\n const next = this.findNextLocation(id, 1);\n\n //Check Time between previous and current Element, to see if event suits in\n if (prev) {\n const length = this.firstStart - prev.lastEnd - prev.travelTimeToNext;\n if (length > event.time.duration && rest > length - event.time.duration) {\n rest = length - event.time.duration;\n start = this.firstStart - event.time.duration - 1;\n }\n }\n\n //Check Time between next and current Element, to see if event suits in\n if (next) {\n const length = next.firstStart - this.lastEnd - this.travelTimeToNext;\n if (length > event.time.duration && rest > length - event.time.duration) {\n rest = length - event.time.duration;\n start = this.lastEnd + 1;\n }\n }\n return start;\n }",
"function find_job_in_period(start, end, task, jobs){\n for(var i=0;i<jobs.length;i++){\n var job = jobs[i];\n if(job.task === task && job.start >= start && job.start < end){\n return job;\n }\n }\n return null;\n}",
"at(time, value) {\n const timeInTicks = new _TransportTime.TransportTimeClass(this.context, time).toTicks();\n const tickTime = new _Ticks.TicksClass(this.context, 1).toSeconds();\n\n const iterator = this._events.values();\n\n let result = iterator.next();\n\n while (!result.done) {\n const event = result.value;\n\n if (Math.abs(timeInTicks - event.startOffset) < tickTime) {\n if ((0, _TypeCheck.isDefined)(value)) {\n event.value = value;\n }\n\n return event;\n }\n\n result = iterator.next();\n } // if there was no event at that time, create one\n\n\n if ((0, _TypeCheck.isDefined)(value)) {\n this.add(time, value); // return the new event\n\n return this.at(time);\n } else {\n return null;\n }\n }",
"function shiftedBinarySearch(array, target) {\n // Write your code here.\n let L = 0\n let R = array.length - 1\n \n while (L <= R) {\n let mid = Math.floor((L + R) / 2)\n let lVal = array[L], rVal = array[R], midVal = array[mid]\n if (midVal === target) return mid\n if (lVal <= midVal) {\n if (target >= lVal && target <= midVal) {\n R = mid - 1\n } else L = mid + 1\n } else {\n if (target <= rVal && target >= midVal) L = mid + 1\n else R = mid - 1\n }\n }\n return -1\n }",
"function nearestElement(n, arr) {\n const nearest = arr.concat().sort((a, b) => Math.abs(n - a) - Math.abs(n - b) || b - a)[0];\n return arr.indexOf(nearest);\n}",
"function findCurrentLabel(seconds, tolerance){\n var $current = $();\n $(\".toc > li\").each(function(i, element){\n if ($(element).data(\"start_at\") <= seconds + tolerance)\n $current = $(element);\n else\n return false;\n });\n return $current;\n}",
"function getClosestToStartOrEnd() {\r\n\tsecondsInDay = 24*60*60;\r\n\tsecondsSinceMidnight = getSecondsSinceMidnight();\r\n\r\n\r\n\t// Direct Test - First we test which of the numbers is closer on a number line.\r\n\tdirectStart = Math.abs(startTime - secondsSinceMidnight);\r\n\tdirectEnd = Math.abs(endTime - secondsSinceMidnight)\r\n\r\n\tif (directStart < directEnd) {\r\n\t\tdirectWinnerName = 'start';\r\n\t\tdirectWinnerValue = directStart;\r\n\t} else {\r\n\t\tdirectWinnerName = 'end';\r\n\t\tdirectWinnerValue = directEnd;\r\n\t}\r\n\r\n\tconsole.log('Direct Winner Name: ' + directWinnerName);\r\n\tconsole.log('Direct Winner value: ' + directWinnerValue);\r\n\r\n\t// Midnight Test - Next we next which of the number is closer by going over midnight.\r\n\tmidnightStart = secondsInDay - secondsSinceMidnight + startTime;\r\n\tmidnightEnd = secondsInDay - secondsSinceMidnight + endTime;\r\n\r\n\tif (midnightStart < midnightEnd) {\r\n\t\tmidnightWinnerName = 'start';\r\n\t\tmidnightWinnerValue = midnightStart;\r\n\t} else {\r\n\t\tmidnightWinnerName = 'end';\r\n\t\tmidnightWinnerValue = midnightEnd;\r\n\t}\r\n\r\n\tconsole.log('Midnight Winner Name: ' + midnightWinnerName);\r\n\tconsole.log('Midnight Winner value: ' + midnightWinnerValue);\r\n\r\n\t//console.log('Midnight Winner: ' + midnightWinner);\r\n\r\n\tif (directWinnerName == midnightWinnerName) {\r\n\t\treturn directWinnerName;\r\n\t} else {\r\n\t\tif (directWinnerValue < midnightWinnerValue) {\r\n\t\t\treturn directWinnerName;\r\n\t\t} else {\r\n\t\t\treturn midnightWinnerName;\r\n\t\t}\r\n\t}\r\n}",
"function getCutoffIndex(array, value) {\n for (var index = 0; index < array.length; ++index) {\n if (array[index] === value) {\n return index + 1;\n }\n }\n\n return 0;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
==Draw A New Bot Post== 'autor' = autor as a string. 'content' = the text to be written. if autor == botAction.lastAutor the post is added to the previous one. | function drawNewPost(autor, content) {
//console.log("CurrentAutor: " + botAction.currentAutor);
//console.log("paramAutor: " + autor);
if(botAction.lastAutor == autor && autor != ""){
var p = document.createElement('p');
p.innerHTML = escapeCharacters(content);
chatBox.lastElementChild.appendChild(p);
} else {
var act = botdata.characters[autor];
var post = document.createElement('div');
post.className = "fbot_mssg bot";
if (act.avatar){
var img = document.createElement('img');
img.src = act.avatar;
}
var hd = document.createElement('h1');
var name = act.name ? act.name : autor;
hd.innerHTML = name;
hd.style.color = act.color;
var p = document.createElement('p');
p.innerHTML = escapeCharacters(content);
if (act.avatar){ post.appendChild(img); }
post.appendChild(hd);
post.appendChild(p);
chatBox.appendChild(post);
botAction.lastAutor = autor;
}
scrollToEnd();
} | [
"function drawNewInput() {\r\n\tif(botAction.lastAutor == \"user\"){\r\n\t\t\r\n\t\tvar p = document.createElement('p');\r\n\t\tp.innerHTML = userInput.current;\r\n\t\t\r\n\t\tchatBox.lastElementChild.appendChild(p);\r\n\t\t\r\n\t} else {\r\n\t\tvar autor = botdata.characters.user;\r\n\t\t\r\n\t\tvar post = document.createElement('div');\r\n\t\tpost.className = \"fbot_mssg user\";\r\n\t\t\r\n\t\tif(autor.avatar){\r\n\t\t\tvar img = document.createElement('img');\r\n\t\t\timg.src = autor.avatar;\r\n\t\t\timg.style.backgroundColor = autor.color;\r\n\t\t}\r\n\t\t\r\n\t\tvar hd = document.createElement('h1');\r\n\t\tvar name = \"User\";\r\n\t\tif (autor.name)\r\n\t\t\tname = autor.name;\r\n\t\thd.innerHTML = name;\r\n\t\thd.style.color = autor.color;\r\n\t\t\r\n\t\tvar p = document.createElement('p');\r\n\t\tp.innerHTML = userInput.current;\r\n\t\t\r\n\t\tpost.appendChild(hd);\r\n\t\tif(autor.avatar){ post.appendChild(img); }\r\n\t\tpost.appendChild(p);\r\n\t\t\t\r\n\t\tchatBox.appendChild(post);\r\n\t\tbotAction.lastAutor = \"user\";\r\n\t}\r\n}",
"function doAction(i) {\r\n\tvar a = botAction.next[i];\r\n\t\r\n\tbotAction.currentAutor = botAction.lastAutor;\r\n\t\r\n\tif (a.autor && botAction.currentAutor != a.autor)\r\n\t\tbotAction.currentAutor = a.autor\r\n\t\r\n\tif(a.text)\r\n\t\tdrawNewPost(botAction.currentAutor,a.text);\r\n\t\r\n\tif(a.answer)\r\n\t\tanswer = a.answer;\r\n\t\r\n\tif (a.fn)\r\n\t\ta.fn();\r\n\t\r\n\treturn botAction.next[i+1] ? true : false;\r\n}",
"function MakePost(text){\nreturn {\n\ttext: text,\n\tdate: new Date()\n}\n}// this function will display posts in the posts div",
"function create (post_title, post_content) {\n var postData = {title: post_title, content: post_content};\n \n // send POST request to server to create new note on API \n $.post('/api/posts', postData, function(data) {\n var newPost = data;\n render(newPost);\n });\n }",
"function createTextPost(template, post) {\n template.content.querySelector('.postTitle').innerHTML = post.title || 'Post Title';\n template.content.querySelector('.postBody').innerHTML = post.body;\n }",
"function Postagem(titulo,mensagem,autor) {\n this.titulo = titulo,\n this.mensagem = mensagem,\n this.autor= autor,\n this.visualizacoes= 0,\n this.comentarios = [],\n this.estaAoVivo= false\n}",
"function addCommentElement(postElement, id, text, author) {\n\tvar comment = document.createElement('div');\n\tcomment.classList.add('comment-' + id);\n\tcomment.innerHTML = '<span class=\"username\"></span><span class=\"comment\"></span>';\n\tcomment.getElementsByClassName('comment')[0].innerText = text;\n\tcomment.getElementsByClassName('username')[0].innerText = author;\n\n\tvar commentsContainer = postElement.getElementsByClassName('comments-container')[0];\n\tcommentsContainer.appendChild(comment);\n}",
"function createNewPostPage(e){\n\t\te.preventDefault();\n\t\t// If the user clicked the button with id newPost, then display the posting page on the right part of the screen.\n\t\tif (e.target.id == 'newPost'){\n\t\t\tmainContent.innerHTML = `\n\t\t\t\t<form>\n\t\t\t\t\t<p class=\"newPostPageText\">Title: </p> <textarea id=\"newPostTitle\"></textarea><br>\n\t\t\t\t\t<p class=\"newPostPageText\">Content:</p> <textarea id=\"newPostContent\"></textarea><br>\n\t\t\t\t\t<button id=\"submitPostButton\" onclick=\"location.href = '/forum/webpage';\">Post</button>\n\t\t\t\t</form>\n\t\t\t`\n\t\t\treplyBlock.innerHTML = `\n\t\t\t<p class=\"readTerms\">\n\t\t\tPlease do not post NSFW material in the forum.\n\t\t\t<br> <br>\n\t\t\tAny NSFW material and its corresponding post/reply will be deleted.\n\t\t\t</p>\n\t\t\t`\n\t\t}\n\t}",
"function addBlogPost() {\n clearDialogInputs();\n showDialog(blogPosts, \"add\");\n}",
"createNote(){\n let note = Text.createNote(this.activeColor);\n this.canvas.add(note);\n this.notifyCanvasChange(note.id, \"added\");\n }",
"archivePost() {\n var post = {};\n\n if(document.getElementById(\"title\").value) {\n post.title = document.getElementById(\"title\").value;\n }\n else {\n post.title = \"Untitled post\";\n }\n\n if(document.getElementById(\"post\").value) {\n post.post = document.getElementById(\"post\").value;\n }\n else {\n post.post = \"\";\n }\n\n /*If the current post was previously loaded, updates it*/\n if (this.loadedPost) {\n this.postArray[this.loadedPost].title = post.title;\n this.postArray[this.loadedPost].post = post.post;\n }\n /*Else, the post is stored as a new one*/\n else{\n post.id = this.postId;\n this.postId = this.postId + 1; // Updates the post ID for the next post to be created\n this.postArray.push(post);\n }\n\n /*Clears the text area*/\n this.clearPost();\n }",
"function editorNewContent(content, container, activity)\n{\n editorDirty = true;\n activity.contents.push(content);\n addContentElement(content, container, activity);\n}",
"function Post(tistoryObj) {\r\n this.parser = tistoryObj.parser;\r\n this.baseurl = tistoryObj.baseurl;\r\n this.params = {\r\n access_token: tistoryObj.access_token,\r\n format: tistoryObj.format\r\n }\r\n\r\n this._requiredParams = {\r\n 'write': ['title'],\r\n 'modify': ['title', 'postId'],\r\n 'read': ['postId'],\r\n 'attach': ['uploadedfile'],\r\n 'delete': ['postId']\r\n }\r\n}",
"function createNewComment(){\n\n var newComment = document.getElementById( 'comment-input' ).value;\n\n if( newComment.trim() !== '' ){\n\n var newCommentTime = getTimestamp();\n var onPostID = getPostIDforComment();\n\n if( onPostID !== '' ){\n var newCommentObject = {\n postid: onPostID,\n timestamp: newCommentTime,\n commentContent: newComment\n };\n uploadPost( newCommentObject, \"/posts/\" + onPostID + \"/createNewComment\", function(err){\n if(err){\n alert(\"Error creating comment.\");\n }\n else{\n console.log(\"Success adding comment.\");\n }\n });\n\n closeCreateCommentMenu();\n addNewCommentToDOM( newCommentObject );\n\n }\n\n }\n else{\n alert(\"You cannot leave a blank comment.\");\n }\n\n}",
"function createPostObj(postData){\n let simplePost = {};\n let awards = [];\n for(let award of postData[0].data.children[0].data.all_awardings) {\n let awardObj = {};\n awardObj.count = award.count;\n awardObj.type = award.name;\n awards.push(awardObj);\n }\n simplePost.time = getDateTime();\n //Trimming the fat off the post objects to only select desired data\n simplePost.title = postData[0].data.children[0].data.title;\n simplePost.author = postData[0].data.children[0].data.author;\n simplePost.upvotes = postData[0].data.children[0].data.ups;\n simplePost.awards = awards;\n simplePost.awarders = postData[0].data.children[0].data.awarders;\n simplePost.numComments = postData[0].data.children[0].data.num_comments;\n simplePost.subreddit = postData[0].data.children[0].data.subreddit_name_prefixed;\n simplePost.subSubscribers = postData[0].data.children[0].data.subreddit_subscribers;\n simplePost.thumbnail = postData[0].data.children[0].data.thumbnail;\n simplePost.edited = postData[0].data.children[0].data.edited;\n simplePost.linkDomain = postData[0].data.children[0].data.domain;\n simplePost.stickied = postData[0].data.children[0].data.stickied;\n simplePost.linkURL = postData[0].data.children[0].data.url;\n simplePost.comments = [];\n\n //Loop through comment thread and save all comments and their replies\n for(let i = 1; i < postData[1].data.children.length; i++){\n let comment = {};\n comment.body = postData[1].data.children[i].data.body;\n comment.author = postData[1].data.children[i].data.author;\n comment.upvotes = postData[1].data.children[i].data.ups;\n comment.replies = postData[1].data.children[i].data.replies;\n\n simplePost.comments.push(comment);\n }\n return simplePost;\n}",
"function PrepareNewPostForAdding(text) {\r\n //Remove extra spaces\r\n text = $.trim(text);\r\n\r\n //Get youtube video id instead of full link\r\n text = text.replace(/\\[[^\\/].*?\\]/g, function(item) {\r\n if (item.indexOf(\"video\") > -1) {\r\n var attrData = GetYoutubeVideoId(GetAtrrData(item, \"src\"));\r\n item = SetAttrData(item, \"src\", attrData);\r\n }\r\n\r\n return item;\r\n });\r\n\r\n return text;\r\n}",
"function addComment() \n{\n\tvar content = $('textarea#content').val(); \n\tvar id_movie = GetURLParameter('id_movie'); \n\tSaveComment(content, id_movie); \n\t\n}",
"postItem()\n {\n let chatData = duplicate(this.data);\n\n // Don't post any image for the item (which would leave a large gap) if the default image is used\n if (chatData.img.includes(\"/blank.png\"))\n chatData.img = null;\n\n renderTemplate('systems/solaires/templates/chat/post-item.html', chatData).then(html =>\n {\n let chatOptions = SolairesUtility.chatDataSetup(html)\n // Setup drag and drop data\n chatOptions[\"flags.transfer\"] = JSON.stringify(\n {\n data: this.data,\n postedItem: true\n })\n ChatMessage.create(chatOptions);\n });\n }",
"function postComment () {\n let postContent = document.getElementById('comment').value;\n let postTitle = document.getElementById('title').value;\n // Body of the comment post to send to the server\n let post = {\n\t\ttitle : postTitle,\n\t\tcontent : postContent\n\t}\n // send the post\n makeRequest('posts', 'POST', post, auth.jwtToken);\n getAllPosts();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creditUSRowCallback if there is no error displays returned table, updates array of amounts,and displays credit complete message if there is no error, but the session has died refreshes page if there is an error displays default error message (check ws_messages for error message) enables buttons | function creditUSRowCallback(res){
document.getElementById("mCreditUSTableDiv").style.display = '';
document.mForm.mCreditButton.disabled = false;
if (!res.error && !res.value.error){
if (res.value.message == "REFRESH"){
reloadSession();
}
else{
document.getElementById('mCreditUSTableDiv').innerHTML = res.value.usHTML;
errorMessage(res.value.message,"CreditUS","Message");
gOldUSCreditAmt = res.value.usAmt;
gUSCreditEmailUpdated = res.value.usEmail;
}
}
else{
document.getElementById('mCreditUSTableDiv').innerHTML = "";
errorMessage("Error Crediting Transaction","CreditUS","Error");
}
} | [
"function creditUSRow(row){ \n if (formatAmount(document.getElementById('amtCreditUS_'+row),'US')){\n CCT.index.creditUSRow(row,gOldUSCreditAmt[row],document.getElementById('emailCreditUS_'+row).value\n ,document.getElementById('notesCreditUS_'+row).value,creditUSRowCallback);\n \n document.getElementById(\"mCreditUSTableDiv\").style.display = 'none';\n errorMessage(\"Crediting ...\",\"CreditUS\",\"Message\");\n document.mForm.mCreditButton.disabled = true; \n }\n }",
"function creditCARowCallback(res){ \n document.getElementById(\"mCreditCATableDiv\").style.display = '';\n document.mForm.mCreditButton.disabled = false; \n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditCATableDiv').innerHTML = res.value.caHTML;\n errorMessage(res.value.message,\"CreditCA\",\"Message\");\n gOldCACreditAmt = res.value.caAmt;\n gCACreditEmailUpdated = res.value.caEmail;\n //get new files\n getFiles(false,\"CACredit\");\n //open file\n if (res.value.filePath != null && res.value.filePath != \"\"){\n printPage(\"F\",res.value.filePath);\n }\n }\n }\n else{\n document.getElementById('mCreditCATableDiv').innerHTML = \"\";\n errorMessage(\"Error Crediting Transaction\",\"CreditCA\",\"Error\");\n }\n }",
"function creditSearchCallback(res){\n document.getElementById('mCreditLoadingDiv').style.display = 'none';\n document.getElementById('creditTabSet').style.display = '';\n document.mForm.mCreditButton.disabled = false;\n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditUSTableDiv').innerHTML = res.value.usHTML;\n document.getElementById('mCreditCATableDiv').innerHTML = res.value.caHTML;\n gOldUSCreditAmt = res.value.usAmt;\n gOldCACreditAmt = res.value.caAmt; \n gUSCreditEmailUpdated = res.value.usEmail;\n gCACreditEmailUpdated = res.value.caEmail;\n errorMessage(\" \",\"CreditUS\",\"\");\n //clicks the ca tab if no us results, not the best way of ref which tabset to click\n //but the code in ws-lib doesn't seem to ref them anyother way\n if (gUSCreditEmailUpdated.length == 0) { clickTab(2,1); } \n else { clickTab(2,0); } \n }\n }\n else{\n document.getElementById('mCreditUSTableDiv').innerHTML = '';\n document.getElementById('mCreditCATableDiv').innerHTML = '';\n errorMessage(\"Error Loading US Credit Results\",\"CreditUS\",\"Error\");\n errorMessage(\"Error Loading Canada Credit Results\",\"CreditCA\",\"Error\");\n } \n }",
"function sortCreditUSCallBack(res){ \n document.getElementById(\"mCreditUSTableDiv\").style.display = '';\n document.mForm.mCreditButton.disabled = false; \n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditUSTableDiv').innerHTML = res.value.usHTML;\n errorMessage(\" \",\"CreditUS\",\"\");\n gOldUSCreditAmt = res.value.usAmt;\n gUSCreditEmailUpdated = res.value.usEmail;\n \n gUSCreditAmountUpdated = new Array();\n gUSCreditNotesUpdated = new Array();\n\n }\n }\n else{\n document.getElementById('mCreditUSTableDiv').innerHTML = \"\";\n errorMessage(\"Error Sorting Transactions\",\"CreditUS\",\"Error\");\n } \n }",
"function creditCARow(row){ \n if (formatAmount(document.getElementById('amtCreditCA_'+row),'CA')){ \n CCT.index.creditCARow(row,gOldCACreditAmt[row],document.getElementById('emailCreditCA_'+row).value\n ,document.getElementById('notesCreditCA_'+row).value,creditCARowCallback);\n \n document.getElementById(\"mCreditCATableDiv\").style.display = 'none';\n errorMessage(\"Crediting ...\",\"CreditCA\",\"Message\");\n document.mForm.mCreditButton.disabled = true; \n } \n }",
"function sortCreditCACallBack(res){ \n document.getElementById(\"mCreditCATableDiv\").style.display = '';\n document.mForm.mCreditButton.disabled = false; \n \n if (!res.error && !res.value.error){ \n if (res.value.message == \"REFRESH\"){\n reloadSession();\n }\n else{ \n document.getElementById('mCreditCATableDiv').innerHTML = res.value.caHTML;\n errorMessage(\" \",\"CreditCA\",\"\");\n gOldCACreditAmt = res.value.caAmt;\n gCACreditEmailUpdated = res.value.caEmail;\n \n gCACreditAmountUpdated = new Array();\n gCACreditNotesUpdated = new Array();\n }\n }\n else{\n document.getElementById('mCreditCATableDiv').innerHTML = \"\";\n errorMessage(\"Error Sorting Transactions\",\"CreditCA\",\"Error\");\n } \n }",
"function creditSearch(){\n //might need to make these dates to compare\n if (document.mForm.mCreditSentTo.value != \"\" &&\n document.mForm.mCreditSentFrom.value > document.mForm.mCreditSentTo.value){\n document.getElementById(\"mCreditErrorTD\").innerHTML = \"First Sent Date must occur before second date.\";\n document.mForm.mCreditSentFrom.focus();\n document.mForm.mCreditSentFrom.select();\n return;\n }\n CCT.index.creditSearch(document.mForm.mCreditTransID.value\n ,document.mForm.mCreditCustNum.value\n ,document.mForm.mCreditCustName.value\n ,document.mForm.mCreditCSNum.value\n ,document.mForm.mCreditODOC.value\n ,document.mForm.mCreditOrderNum.value\n ,document.mForm.mCreditDCT.value\n ,document.mForm.mCreditDOC.value\n ,document.mForm.mCreditKCO.value\n ,document.mForm.mCreditCCSufix.value\n ,document.mForm.mCreditSentFrom.value\n ,document.mForm.mCreditSentTo.value\n ,document.mForm.mCreditTypeSelect.value\n ,document.mForm.mCreditCardType.value\n ,creditSearchCallback); \n getFiles(false,\"CACredit\");\n \n document.getElementById(\"mCreditErrorTD\").innerHTML = \"<br>\";\n errorMessage(\"Searching ...\",\"CreditUS\",\"Message\");\n errorMessage(\" \",\"CreditCA\",\"\");\n currCreditUSRow = null;\n\t\t currCreditCARow = null;\n\n document.getElementById('creditTabSet').style.display = 'none';\n document.getElementById('mCreditLoadingDiv').style.display = \"\";\n document.mForm.mCreditButton.disabled = true; \n }",
"function sortCreditUS(col){ \n CCT.index.sortCreditUS(col,gUSCreditEmailUpdated,gUSCreditAmountUpdated,gUSCreditNotesUpdated,sortCreditUSCallBack);\n\n document.getElementById(\"mCreditUSTableDiv\").style.display = 'none';\n errorMessage(\"Sorting ...\",\"CreditUS\",\"Message\");\n document.mForm.mCreditButton.disabled = true; \n }",
"function editSelectedFundRow(uniqueRowId) {\n\tvar fundingType = $(\"#\" + uniqueRowId + \" #historyFundRowFundingType\").text();\n\tvar pinNumber = $(\"#\" + uniqueRowId + \" #historyFundRowPin\").text().trim();\n\tvar amount = getFormatedNumber($(\"#\" + uniqueRowId + \" #historyFundRowAmount\").text(), false);\n\teditCashHistoryFundRowId = uniqueRowId;\n\t$(\"#optionsListContainer\").hide(); \t/* Hide select type */\n\t$(\"#cashInfoTxt\").hide();\n\t$(\"#helpCash\").hide();\n\tshowHideAllDeleteButtonOfCash(true); /* Disable all delete buttons */\n\tvar fundingSourceType = fundingType.replace(/[\\s]/g, '');\n\tpinNumber = pinNumber.replace(/[\\s]/g, '');\n\tsetPinNumberInFieldsOnEdit(pinNumber, amount, fundingSourceType);\n\tif(jsonTypeConstant.PRECASH === fundingSourceType) {\n\t\t$(\"#cashPaymentOptionBox1 #cashSelectedFundingSourceImage\").attr(\"src\",\n\t\t\t\tformatMessage(messages[\"checkout.image_fundingSource_URL\"],\tgetImageNameByJsonType(fundingType)));\n\t\t$(\"#cashPaymentOptionBox1\").show();\n\t} else if(jsonTypeConstant.BLACKHAWK == fundingSourceType) {\n\t\t$(\"#cashPaymentOptionBox2 #cashSelectedFundingSourceImage\").attr(\"src\",\n\t\t\t\tformatMessage(messages[\"checkout.image_fundingSource_URL\"], getImageNameByJsonType(fundingType)));\n\t\t$(\"#cashPaymentOptionBox2\").show();\n\t} else if(jsonTypeConstant.INCOMM == fundingSourceType) {\n\t\t$(\"#cashPaymentOptionBox3 #cashSelectedFundingSourceImage\").attr(\"src\",\n\t\t\t\tformatMessage(messages[\"checkout.image_fundingSource_URL\"],\tgetImageNameByJsonType(fundingType)));\n\t\t$(\"#cashPaymentOptionBox3\").show();\n\t}\n\t$(\"#historyFundingSources\").hide(); /* Hide history section */\n\t$(\"#cashSummaryTotalArea\").hide();\n\tclearIntervalApp(submitBtnCreateProfCountdown);\n\tclearIntervalApp(submitBtnAddInfoCountdown);\n\tdeActivateCheckoutPayButton();/* Disable submit button */\n}",
"function handleBpBillerCorpCredsOnSuccess(isMsg) {\n\t/* show the div */ \n $('#billerFormData').show();\n $('#addOrEditSaveBtnDiv').show();\n $('#addBil_billerType').show();\n $('#addBil_postingCategoryLanguage').show();\n $('#addBil_instruction2').show();\n $('#addBil_rightSection').show(); \n \n printBillerData();\n createTableNew();\n \n hideShowCreateAccountForGuestUser();\n if (isMsg) {\n \tshowGeneralErrorMsg(msgType);\n }\n}",
"function renderCreditForm()\n{\n var tableBody = $(\"#credit_content\").find(\"tbody\");\n tableBody.empty();\n\n // render pagination\n renderCreditFormPagination();\n\n for(var i = 0; i < 4; i++)\n {\n var index = i + showPage * CREDIT_NUM_PAGE;\n var credit = creditList[index];\n\n var tableRow = $(\"<tr>\");\n\n if(typeof(credit)!=\"undefined\")\n {\n tableRow.append($(\"<td>\", {\"text\":index + 1}));\n tableRow.append($(\"<td>\", {\"text\":credit.name}));\n tableRow.append($(\"<td>\", {\"text\":credit.actualCredits}));\n tableRow.append($(\"<td>\", {\"text\":credit.standard}));\n }\n else\n {\n tableRow.append($(\"<td>\",{\"text\":\"-\"})).append($(\"<td>\")).append($(\"<td>\")).append($(\"<td>\"));\n }\n\n tableBody.append(tableRow);\n }\n\n}",
"function updateTransactionsDisplay(){\n\t\n\t\t// date to display --> in Date format\n\t\tvar date = Account.transactionsArray[Account.transactionsArray.length -1].date ;\n\t\t\n\t\t// date to display --> in string format\n\t\tdate = getDisplayDate(date);\n\t\t\n\t\t// transaction amount to display\n\t\tvar amount = Account.transactionsArray[Account.transactionsArray.length -1].amount.toFixed(2);\n\t\t\n\t\t// running balance to display\n\t\tvar runBalance = Account.runningBalance.toFixed(2) ;\n\t\t\n\t\tformatDisplay(date, amount, runBalance);\n\t}",
"function getCreditCards(){\n\tif(paymentScreenProps.windowType==\"Modal\" && !isUserLoggedIn()){\n\t\treturn false;\n\t}\n\ttogglePaymentAndIFrameBlock(false);\n\t\n\t\t$('#cancelButton').attr(\"disabled\", true);\n\t\t$.ajax({\n \t\t\ttype: \"POST\",\n \t\t\turl: \"/listCreditCards.do?operation=retrieveCreditCardList\",\n \t\t\tdata: \"displayRadioButtons=\"+paymentScreenProps.displayRadioButtons,\n \t\t\tsuccess: \n\t\t\t\tfunction(data){\t\t\n\t\t\t\t\t\t$('#ccRows').html(data);\n\t\t\t\t\t\t$(\"#profileRow1\").attr(\"checked\", \"checked\");\n\t\t\t\t\t $(\"#profileRow1\").click();\n\t\t\t\t\t\tinit();\t\n\t\t\t\t\t}\n\t\t});\t\n\t\t//highlightExpiredCards();\t\t\t\n}",
"function handleBpSaveBillerCorpAcctCredsOnSuccess() {\n\t/* Storing the biller boxes data into tempBillArray so that is can be populated later after BP_ACCOUNT_LITE API call */\n\tsetTempBillArray(); \n\tif (isGuestMsg) {\n\t\tgettingInfoOfBillerAcc();\n\t\t$('#myAccountBox').show();\n $('#guestUserMyAccountBox').hide();\n isGuestMsg = false;\n\t\tshowGeneralSuccessMsg(messages['addEditBiller.GuestUserBillerSaved'],\n messages['inLine.message.successMessage']);\n } else {\n \t/* Checking for scheduled biller edited and updated credentials it will raise pop up */\n \tif(bp_save_biller_corp_acct_creds_obj.scheduled === true){\n \t\tsuccessfulCredUpdatePopup();\t\n \t\tgettingInfoOfBillerAcc();\n \t} else {\n \t\tgettingInfoOfBillerAcc();\n \t\tshowGeneralSuccessMsg(messages['addEditBiller.alert.billerSaved'],\n \t\t messages['inLine.message.successMessage']);\n \t}\n }\n}",
"function refreshCreditsRemaining() {\n $(\"#credits_remaining\").html(user.creditsRemaining());\n}",
"function barcodenowiseCredit() {\r\n\tvar barcodeCredit = $(\"#barcodeCredit\").val();\r\n\r\n\tvar params = {};\r\n\tparams[\"barcodeCredit\"] = barcodeCredit;\r\n\r\n\tparams[\"methodName\"] = \"barcodenowiseCredit\";\r\n\r\n\t$.post('/SMT/jsp/utility/controller.jsp',\r\n\t\t\t\t\tparams,\r\n\t\t\t\t\tfunction(data) {\r\n\t\t\t\t\t\t$('#barcodewiseCredit').dataTable().fnClearTable();\r\n\t\t\t\t\t\tvar jsonData = $.parseJSON(data);\r\n\t\t\t\t\t\tvar catmap = jsonData.list;\r\n\r\n\t\t\t\t\t\t$(document)\r\n\t\t\t\t\t\t\t\t.ready(\r\n\t\t\t\t\t\t\t\t\t\tfunction() {\r\n\t\t\t\t\t\t\t\t\t\t\t$('#barcodewiseCredit')\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t.DataTable(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfnRowCallback : function(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnRow,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\taData,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tiDisplayIndex) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"th:first\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tnRow)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tiDisplayIndex + 1);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn nRow;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"footerCallback\" : function(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\trow,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstart,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tend,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdisplay) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar api = this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.api(), data;\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Remove\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// the\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// formatting\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// to get\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// integer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// data for\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// summation\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar intVal = function(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ti) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn typeof i === 'string' ? i\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.replace(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t/[\\$,]/g,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'') * 1\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: typeof i === 'number' ? i\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t: 0;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t};\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t6)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t6)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparseFloat(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t2)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t7)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t7)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparseFloat(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t2)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t8)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t8)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparseFloat(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t2)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t9)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t9)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparseFloat(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t2)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t10)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t10)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tparseFloat(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t2)\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Total\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t11)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t11)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr = pageTotal\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(2));\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t12)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t12)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr = pageTotal\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(2));\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// over this\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// page\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageTotal = api\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t13)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.data()\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.reduce(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfunction(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ta,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tb) {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn intVal(a)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t+ intVal(b);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t0);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Update\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// footer\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t$(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tapi\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.column(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t13)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.footer())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.html(\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tstr = pageTotal\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toFixed(2));\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tconsole\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t.log(pageTotal);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdestroy : true,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsearching : true,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcolumns : [\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"srNo\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"billNo\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"firstName\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"barcodeNo\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"categoryName\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"itemName\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"quantity\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"salePrice\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"gst\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"spWithoutTax\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"perProductDisPer\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"discount\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"afterDisTaxAmt\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"totalperItem\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"data\" : \"saleDate\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"width\" : \"5%\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"defaultContent\" : \"\"\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t],\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdom : 'Bfrtip',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tbuttons : [\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\textend : 'copyHtml5',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfooter : true\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\textend : 'excelHtml5',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfooter : true\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\textend : 'csvHtml5',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfooter : true\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\textend : 'pdfHtml5',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tfooter : true,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitle : function() {\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn \"Barcode No Wise Credit Sale Report\";\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\torientation : 'landscape',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tpageSize : 'LEGAL',\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\ttitleAttr : 'PDF'\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t} ]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\tvar mydata = catmap;\r\n\t\t\t\t\t\t$('#barcodewiseCredit').dataTable().fnAddData(mydata);\r\n\r\n\t\t\t\t\t}).error(function(jqXHR, textStatus, errorThrown) {\r\n\t\t\t\tif (textStatus === \"timeout\") {\r\n\t\t\t\t\t$(loaderObj).hide();\r\n\t\t\t\t\t$(loaderObj).find('#errorDiv').show();\r\n\r\n\t\t\t\t}\r\n\t\t\t});\r\n\r\n}",
"function withdrawFunds(call, callback) {\n\n call.on('data', function (response) {\n try {\n var db = new sqlite3.Database(__dirname + \"/../ebanking.db\");\n let { email, account, password, amount } = response\n let sql = `SELECT accounts.account_id as account_id, accounts.balance as balance, users.password as password FROM users INNER JOIN accounts ON users.user_id = accounts.user_id where users.email = '${email}' and accounts.accountType = '${account}'`;\n\n if (!email) {\n callback(null, {\n message: `Please specify an email address`\n });\n return;\n }\n\n if (!account) {\n callback(null, {\n message: `Please Specify an Account Type`\n });\n return;\n }\n\n if (!password) {\n callback(null, {\n message: `Please Specify a Password`\n });\n return;\n }\n\n if (!email) {\n callback(null, {\n message: `Please Specify an Email Address`\n });\n return;\n }\n\n let validString = string => {\n for (let i = 0; i < string.length; i++) {\n let c = string.charCodeAt(i);\n if (c == 34 || c == 10 || c == 8 || c == 39 || c == 13 || c == 9 || c == 92) {\n return false;\n }\n }\n return true;\n }\n\n let regex = \"^[\\\\w!#$%&'*+/=?`{|}~^-]+(?:\\\\.[\\\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[A-Z0-9-]+\\\\.)+[A-Z]{2,6}$\".toLowerCase();\n if (!email.match(regex) || !validString(email)) {\n callback(null, {\n message: `Please specify a valid email address`\n });\n return;\n }\n\n\n if (!validString(account)) {\n callback(null, {\n message: `Please specify a valid account type`\n });\n return;\n }\n\n if (!validString(password)) {\n callback(null, {\n message: `Please specify a valid password`\n });\n return;\n }\n\n email = email.toLowerCase();\n account = account.toLowerCase();\n\n if (!amount || amount <= 0) {\n callback(null, {\n message: \"Cannot withdraw no or a negative amount of money into the account\"\n });\n return;\n }\n\n db.all(sql, [], (err, rows) => {\n if (err) {\n throw err;\n }\n let user\n\n for (let row in rows) {\n user = rows[row];\n break;\n }\n\n if (!user) {\n callback(null, { message: 'Account not found' });\n } else if (sha1(password) != user['password']) {\n callback(null, { message: 'Invalid password' });\n } else if (user['balance'] - (amount * 100) >= 0) {\n db.run(`UPDATE accounts set balance = balance - ${amount * 100} where account_id = ${user['account_id']}`, [], function (err) {\n if (err) {\n return console.error(err.message);\n }\n let updatedBalance = ((user['balance'] - (amount * 100))) / 100\n callback(null, {\n message: `The updated balance of the account is € ${updatedBalance}`,\n balance: updatedBalance,\n email: email,\n account: account\n });\n\n });\n\n } else {\n callback(null, { message: `Insuffient funds to withdraw € ${amount}` });\n return\n }\n\n });\n\n // close the database connection\n db.close();\n } catch (error) {\n console.log(error)\n callback(null, {\n message: \"An error occured\"\n });\n }\n });\n call.on('end', function () {\n\n });\n call.on('error', function (e) {\n callback(null, {\n message: \"An error occured\"\n });\n });\n\n\n\n}",
"function openCashSummaryForEditAmount() {\n\t/* Show History Funds without select a type Option */\n\t$(\"#historyFundingSources\").show();\n\tremoveChitErrorBorder();\n\t$(\"#editCashSummaryTotal\").hide();\n\t$(\"#cashPaymnetInfoMessage\").hide();\n\taddOrRemoveBorderBottom();\n}",
"function paymentSuccededCallback(result) {\n if (result.ErrorCode != 0) {\n //Call failed an error has occurred\n util.showErrors(\n result.ErrorCode,\n result.ErrorDescription,\n 'paymentSuccededCallback'\n );\n } else {\n //Call went good\n redirectToResponsePage(result);\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get Start of the Month from Monthpicker | function getMonthPickerStart(selector) {
jQuery(selector).monthpicker({
showOn: "both",
dateFormat: 'M yy',
yearRange: 'c-5:c+10'
});
} | [
"function nextStartMonth() {\n var thisMonth = new Date().getMonth();\n var nextMonth = 'Jan';\n\n if (0 <= thisMonth && thisMonth < 4) {\n nextMonth = 'May';\n } else if (4 <= thisMonth && thisMonth < 8) {\n nextMonth = 'Sep';\n }\n\n return nextMonth;\n }",
"function getMonthPickerEnd(selector) {\n jQuery(selector).monthpicker({\n showOn: \"both\",\n dateFormat: 'M yy',\n yearRange: 'c-5:c+10',\n });\n}",
"function monthValue(){\n var monthButton = document.getElementById('month').value;\n return monthButton;\n}",
"function getValidMonth(){\r\n\treturn 3;\r\n}",
"getMonthNum() {\n\t\treturn this.props.month.substr(5,6);\n\t}",
"function setMonth() {\n\tvar element = document.getElementById(\"selected_month\");\n\tMONTH = element.options[element.selectedIndex].value;\n\tsetDateContent(MONTH, YEAR);\n}",
"function _getMonth(m) {\n\t\tif(mc.os.config.translations) {\n\t\t\treturn mc.os.config.translations.pc.settings.nodes['_constants'].months[m];\n\t\t} else {\n\t\t\treturn $MONTHS[m];\n\t\t}\n\t}",
"function setCurrMonth(today) {\n form.chooseMonth.selectedIndex = today.getMonth();\n }",
"getPreviousMonth(){\n return new Month(this.year + Math.floor((this.month.index-1)/12), (this.month.index+11) % 12, this.setting.getWeekStartDay());\n }",
"function DateTimeDayMonth() { }",
"function parse_months() {\n var raw_months = month_date_textbox.getValue();\n var months_to_list = raw_months.split(\"-\");\n return months_to_list;\n}",
"function setCurrentMonth() {\n\n // GET THE NEWLY SELECTED MONTH AND CHANGE THE CALENDAR ACCORDINGLY\n var month = tDoc.calControl.month.selectedIndex;\n\n calDate.setMonth(month);\n\n\t// GENERATE THE CALENDAR SRC\n\tcalDocBottom = buildBottomCalFrame();\n\n // DISPLAY THE NEW CALENDAR\n writeCalendar(calDocBottom);\n}",
"nameMonths() {\n var d = new Date()\n var mount = d.getMonth()\n var months = [\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December'\n ]\n\n return [\n {label: months[(mount != 0) ? (mount - 1) : 11], value: 'lastMonth'},\n {label: months[mount], value: 'currentMonth'},\n {label: 'Today', value: 'today'}\n ]\n }",
"function nextMo() {\n showingMonth++;\n if (showingMonth > 11) {\n showingMonth = 0;\n showingYear++;\n }\n update();\n closeDropDown();\n //console.log(\"SHOWING MONTH: \" + showingMonth);\n}",
"function changeMonth(){\n var sel = monthValue();\n monthNum = sel;\n \n clearDays();\n createCalendarEmpty();\n createDays();\n today();\n click();\n}",
"function getCurrentMonthShortname() {\n var d = new Date();\n var months = new Array(12);\n months[0] = \"Jan\";\n months[1] = \"Feb\";\n months[2] = \"Mar\";\n months[3] = \"Apr\";\n months[4] = \"May\";\n months[5] = \"Jun\";\n months[6] = \"Jul\";\n months[7] = \"Aug\";\n months[8] = \"Sep\";\n months[9] = \"Oct\";\n months[10] = \"Nov\";\n months[11] = \"Dec\";\n return months[d.getMonth()];\n}",
"function calenderMonthIsCurrentMonth(){\n if(data.current_date.year == data.calendar.year && data.current_date.month == data.calendar.month){\n return true;\n } else {\n return false;\n }\n}",
"function month_links(start) { \n var startAr = start.split('-');\n var start_year = startAr[0];\n var start_month = startAr[1];\n var monthAr = [];\n var month,this_month,month_date, month_name, m, year;\n var this_m = parseInt(start_month, 10);\n var start_m = (12 + (this_m - 3)) % 12;\n var year = start_year;\n if(this_m - 3 < 0) year--;\n \n for(var i=start_m;i<12+start_m;i++) {\n if(i==12) year++; \n m = i%12;\n if(this_m == m+1) {\n month_name = g_months[m];\n month = '<b>' + month_name + '</b>';\n } else {\n month_name = g_monthsShort[m]; \n month_date = year + \"-\" + zero_pad(m+1) + \"-01\";\n month = '<a href=\"?start=' + month_date +'\" class=\"cal_nav start\" data-value=\"' + month_date + '\">' + month_name + '</a>';\n }\n monthAr.push(month);\n }\n return monthAr.join(' ');\n}",
"populateDaysInMonth() {\n var daysInMonth = [];\n //first day of this.state.monthNumber\n var date = new Date(this.state.year, this.state.monthNumber);\n while (date.getMonth() === this.state.monthNumber) {\n daysInMonth.push(new Date(date));\n //Increment to next day\n date.setDate(date.getDate() + 1)\n }\n return daysInMonth\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a function for postV3ProjectsIdStatusesSha | postV3ProjectsIdStatusesSha(incomingOptions, cb) {
const Gitlab = require('./dist');
let defaultClient = Gitlab.ApiClient.instance;
// Configure API key authorization: private_token_header
let private_token_header = defaultClient.authentications['private_token_header'];
private_token_header.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_header.apiKeyPrefix = 'Token';
// Configure API key authorization: private_token_query
let private_token_query = defaultClient.authentications['private_token_query'];
private_token_query.apiKey = 'YOUR API KEY';
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//private_token_query.apiKeyPrefix = 'Token';
let apiInstance = new Gitlab.ProjectsApi()
/*let id = "id_example";*/ // String | The ID of a projec
/*let sha = "sha_example";*/ // String | The commit has
/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE |
apiInstance.postV3ProjectsIdStatusesSha(incomingOptions.id, incomingOptions.sha, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {
if (error) {
cb(error, null)
} else {
cb(null, data)
}
});
} | [
"getV3ProjectsIdRepositoryCommitsShaStatuses(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | The commit has\n/*let opts = {\n 'ref': \"ref_example\", // String | The ref\n 'stage': \"stage_example\", // String | The stage\n 'name': \"name_example\", // String | The name\n 'all': \"all_example\", // String | Show all statuses, default: false\n 'page': 56, // Number | Current page number\n 'perPage': 56 // Number | Number of items per page\n};*/\napiInstance.getV3ProjectsIdRepositoryCommitsShaStatuses(incomingOptions.id, incomingOptions.sha, incomingOptions.opts, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdRepositoryBranches(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryBranches(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdMilestones(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdMilestones(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdIssues(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdIssues(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdBoardsBoardIdLists(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let boardId = 56;*/ // Number | The ID of a boar\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdBoardsBoardIdLists(incomingOptions.id, incomingOptions.boardId, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdIssuesIssueIdResetSpentTime(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let issueId = 56;*/ // Number | The ID of a project issue\napiInstance.postV3ProjectsIdIssuesIssueIdResetSpentTime(incomingOptions.id, incomingOptions.issueId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"postV3ProjectsIdRepositoryCommitsShaComments(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let sha = \"sha_example\";*/ // String | The commit's SH\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryCommitsShaComments(incomingOptions.id, incomingOptions.sha, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdTriggers(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a project\napiInstance.postV3ProjectsIdTriggers(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdIssuesIssueIdMove(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let issueId = 56;*/ // Number | The ID of a project issu\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdIssuesIssueIdMove(incomingOptions.id, incomingOptions.issueId, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdRepositoryTags(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRepositoryTags(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdRunners(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRunners(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdLabels(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdLabels(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdHooks(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdHooks(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdArchive(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a project\napiInstance.postV3ProjectsIdArchive(incomingOptions.id, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdMergeRequestsMergeRequestIdResetSpentTime(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number | The ID of a project merge_request\napiInstance.postV3ProjectsIdMergeRequestsMergeRequestIdResetSpentTime(incomingOptions.id, incomingOptions.mergeRequestId, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"postV3ProjectsIdMergeRequestsMergeRequestIdAddSpentTime(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let mergeRequestId = 56;*/ // Number | The ID of a project merge_reques\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdMergeRequestsMergeRequestIdAddSpentTime(incomingOptions.id, incomingOptions.mergeRequestId, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"postV3ProjectsIdUploads(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdUploads(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, '')\n }\n});\n }",
"postV3ProjectsIdRefReftriggerBuilds(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The ID of a projec\n/*let ref = \"ref_example\";*/ // String | The commit sha or name of a branch or ta\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdRefReftriggerBuilds(incomingOptions.id, incomingOptions.ref, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }",
"postV3ProjectsIdMembers(incomingOptions, cb) {\n const Gitlab = require('./dist');\nlet defaultClient = Gitlab.ApiClient.instance;\n// Configure API key authorization: private_token_header\nlet private_token_header = defaultClient.authentications['private_token_header'];\nprivate_token_header.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_header.apiKeyPrefix = 'Token';\n// Configure API key authorization: private_token_query\nlet private_token_query = defaultClient.authentications['private_token_query'];\nprivate_token_query.apiKey = 'YOUR API KEY';\n// Uncomment the following line to set a prefix for the API key, e.g. \"Token\" (defaults to null)\n//private_token_query.apiKeyPrefix = 'Token';\n\nlet apiInstance = new Gitlab.ProjectsApi()\n/*let id = \"id_example\";*/ // String | The project I\n/*let UNKNOWN_BASE_TYPE = new Gitlab.UNKNOWN_BASE_TYPE();*/ // UNKNOWN_BASE_TYPE | \napiInstance.postV3ProjectsIdMembers(incomingOptions.id, incomingOptions.UNKNOWN_BASE_TYPE, (error, data, response) => {\n if (error) {\n cb(error, null)\n } else {\n cb(null, data)\n }\n});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set hotline all web | function setHotLine(hotline) {
hotline = '0' + hotline;
hotline = hotline.substr(0, 4) + ' ' + hotline.substr(4, 3) + ' ' + hotline.substr(7, 3);
$('.hotline').html('<i class="fas fa-phone"></i> ' + hotline);
$('.hotline').attr("href", `tel:${hotline}`);
} | [
"function renderHotSpots() {\n config.hotSpots.forEach(renderHotSpot);\n}",
"function launchAutolinkConfig(){\n\t\n\t\n\t\n\t\n}",
"static warmConnections() {\n if (this.preconnected) return;\n\n // The iframe document and most of its subresources come right off youtube.com\n this.addPrefetch('preconnect', 'https://www.youtube-nocookie.com');\n this.addPrefetch('preconnect', 'https://i.ytimg.com');\n this.addPrefetch('preconnect', 'https://s.ytimg.com');\n\n this.preconnected = true;\n }",
"function setHotKeys() {\n\tdocument.onkeydown = function(ev) {\n\t\tev = ev||window.event;\n\t\tkey = ev.keyCode||ev.which;\n\t\tif (key == 18 && !ev.ctrlKey) {\t// start selection, skip Win AltGr\n\t\t\t_hotkeys.alt = true;\n\t\t\t_hotkeys.focus = -1;\n\t\t\treturn stopEv(ev);\n\t\t}\n\t\telse if (ev.altKey && !ev.ctrlKey && ((key>47 && key<58) || (key>64 && key<91))) {\n\t\t\tkey = String.fromCharCode(key);\n\t\t\tvar n = _hotkeys.focus;\n\t\t\tvar l = document.getElementsBySelector('[accesskey='+key+']');\n\t\t\tvar cnt = l.length;\n\t\t\t_hotkeys.list = l;\n\t\t\tfor (var i=0; i<cnt; i++) {\n\t\t\t\tn = (n+1)%cnt;\n\t\t\t\t// check also if the link is visible\n\t\t\t\tif (l[n].accessKey==key && (l[n].offsetWidth || l[n].offsetHeight)) {\n\t\t\t\t\t_hotkeys.focus = n;\n\t // The timeout is needed to prevent unpredictable behaviour on IE.\n\t\t\t\t\tvar tmp = function() {l[_hotkeys.focus].focus();};\n\t\t\t\t\tsetTimeout(tmp, 0);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn stopEv(ev);\n\t\t}\n\t\tif((ev.ctrlKey && key == 13) || key == 27) {\n\t\t\t_hotkeys.alt = false; // cancel link selection\n\t\t\t_hotkeys.focus = -1;\n\t\t\tev.cancelBubble = true;\n \t\t\tif(ev.stopPropagation) ev.stopPropagation();\n\t\t\t// activate submit/escape form\n\t\t\tfor(var j=0; j<this.forms.length; j++) {\n\t\t\t\tvar form = this.forms[j];\n\t\t\t\tfor (var i=0; i<form.elements.length; i++){\n\t\t\t\t\tvar el = form.elements[i];\n\t\t\t\t\tvar asp = el.getAttribute('aspect');\n\n\t\t\t\t\tif (!string_contains(el.className, 'editbutton') && (asp && asp.indexOf('selector') !== -1) && (key==13 || key==27)) {\n\t\t\t\t\t\tpassBack(key==13 ? el.getAttribute('rel') : false);\n\t\t\t\t\t\tev.returnValue = false;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (((asp && asp.indexOf('default') !== -1) && key==13)||((asp && asp.indexOf('cancel') !== -1) && key==27)) {\n\t\t\t\t\t\tif (validate(el)) {\n\t\t\t\t\t\t\tif (asp.indexOf('nonajax') !== -1)\n\t\t\t\t\t\t\t\tel.click();\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\tif (asp.indexOf('process') !== -1)\n\t\t\t\t\t\t\t\tJsHttpRequest.request(el, null, 600000);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tJsHttpRequest.request(el);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tev.returnValue = false;\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tev.returnValue = false;\n\t\t\treturn false;\n\t\t}\n\t\tif (editors!==undefined && editors[key]) {\n\t\t\tcallEditor(key);\n\t\t\treturn stopEv(ev); // prevent default binding\n\t\t}\n\t\treturn true;\n\t};\n\tdocument.onkeyup = function(ev) {\n\t\tev = ev||window.event;\n\t\tkey = ev.keyCode||ev.which;\n\n\t\tif (_hotkeys.alt==true) {\n\t\t\tif (key == 18) {\n\t\t\t\t_hotkeys.alt = false;\n\t\t\t\tif (_hotkeys.focus >= 0) {\n\t\t\t\t\tvar link = _hotkeys.list[_hotkeys.focus];\n\t\t\t\t\tif(link.onclick)\n\t\t\t\t\t\tlink.onclick();\n\t\t\t\t\telse\n\t\t\t\t\t\tif (link.target=='_blank') {\n\t\t\t\t\t\t\twindow.open(link.href,'','toolbar=no,scrollbar=no,resizable=yes,menubar=no,width=900,height=500');\n\t\t\t\t\t\t\topenWindow(link.href,'_blank');\n\t\t\t\t\t\t} else\n\t\t\t\t\t\t\twindow.location = link.href;\n\t\t\t\t}\n\t\t\treturn stopEv(ev);\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n}",
"reload() {\n this.requestWebsites();\n }",
"setRedLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet currentGreenLights = this.config.getDirections()[this.getDirectionIndex()];\n\n // Loop through the greenLights and set the rest to red lights\n\t\tfor (let direction in this.trafficLights) {\n\t\t\tlet elementId = this.trafficLights[direction].name;\n\t\t\tif (currentGreenLights.indexOf(elementId) >= 0) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.trafficLights[direction].color = TRAFFIC_LIGHT_RED;\n\t\t}\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}",
"setYellowLights() {\n\t\t// Get the array traffic lights from the config\n\t\tlet lights = this.config.getDirections()[this.getDirectionIndex()];\n\n\t\t// Set the traffic lights to green based on the direction of the traffic\n\t\tlights.map((direction) => {this.trafficLights[direction].color = TRAFFIC_LIGHT_YELLOW;});\n\n\t\t// Set the color of the traffic lights visually and print a log\n\t\tthis.draw.traffic(this.getTrafficLights());\n\t}",
"function makeHotSpotBackgroundsVisible()\r\n\t\t\t{\r\n\t\t\t\t// Alter the CSS (SmoothDivScroll.css) if you want to customize\r\n\t\t\t\t// the look'n'feel of the visible hot spots\r\n\t\t\t\t\r\n\t\t\t\t// The left hot spot\r\n\t\t\t\t$mom.find(options.scrollingHotSpotLeft).addClass(\"scrollingHotSpotLeftVisible\");\r\n\r\n\t\t\t\t// The right hot spot\r\n\t\t\t\t$mom.find(options.scrollingHotSpotRight).addClass(\"scrollingHotSpotRightVisible\");\r\n\t\t\t}",
"function setTheme(themValueObj) {\n for (const key in themValueObj) {\n document.documentElement.style.setProperty(`--${key}`, themValueObj[key]);\n }\n}",
"function updateHour() {\n\t\t\tdocument.documentElement.setAttribute(\"stylish-hour\", (new Date()).getHours())\n\t\t}",
"function newFlowline(){\n resetFlowline();\n flowline.markers[0].enableEdit(map).startDrawing();\n }",
"setStyle() {\n this.lineStyle = {\n color: globalStore.getData(keys.properties.trackColor),\n width: globalStore.getData(keys.properties.trackWidth)\n }\n }",
"function addEditLinksToWLH() {\n if(wgCanonicalSpecialPageName=='Whatlinkshere')\n {\n var links = document.getElementById(\"mw-whatlinkshere-list\").getElementsByTagName('li');\n for(var i = 0; i<links.length; i++)\n {\n aLink = links[i].getElementsByTagName('a');\n var linkHref = aLink[0].href.replace(\"?redirect=no\",\"\")+\"?action=edit\";\n var tools = getElementsByClassName(links[i], 'span', 'mw-whatlinkshere-tools');\n var editLinkSpan = document.createElement(\"span\");\n editLinkSpan.className = \"mw-whatlinkshere-edit\";\n editLinkSpan.innerHTML = '<a title=\"Edit form\" href=\"' + linkHref + '\">(edit)</a> ';\n links[i].insertBefore(editLinkSpan,tools[0]);\n }\n }\n}",
"setDomElements() {\n this.dom.header = this.dom.el.querySelector('.mf-tabs__header');\n this.dom.tabs = this.dom.el.querySelectorAll('.mf-tabs__tab');\n this.dom.content = this.dom.el.querySelector('.mf-tabs__content');\n this.dom.panels = this.dom.el.querySelectorAll('.mf-tabs__panel');\n }",
"setUrls(urls) {\n this.wrapped.urls = null;\n if (urls) {\n urls.forEach(url => {\n this.addUrl(url);\n });\n }\n return this;\n }",
"function enableMainPageButtons() {\n\t\t\tevents.forEach( ev => { \n\t\t\t\tev.button.mouseEnabled = true;\n\t\t\t\tev.button.cursor = \"pointer\";\n\t\t\t});\n\t\t\n\t\t\tcultures.forEach( cu => { \n\t\t\t\tcu.button.mouseEnabled = true;\n\t\t\t\tcu.button.cursor = \"pointer\";\n\t\t\t});\n\t\t\n\t\t\tself.aboutUsBtn.mouseEnabled = true;\n\t\t\tself.aboutUsBtn.cursor = \"pointer\";\n\t\t\n\t\t\tself.returnBtn.mouseEnabled = true;\n\t\t\tself.returnBtn.cursor = \"pointer\";\n\t\t}",
"_setAuxWeb3Instance() {\n const oThis = this,\n wsProvider = oThis.ic().configStrategy.auxGeth.readOnly.wsProvider;\n\n oThis.web3Instance = web3Provider.getInstance(wsProvider).web3WsProvider;\n }",
"function setNeighborhoodColors() {\n console.log(\"setNeighborhoodColors()\");\n map.data.forEach( function( feature ) {\n // The name is the key in the quickLookup hash\n var key = feature.getProperty( 'NAME' );\n if ( quickLookup[ key ] ) {\n localCrime = quickLookup[ key ].crime;\n localRent = quickLookup[ key ].rent;\n map.data.overrideStyle( feature, {\n fillColor: getFillColor( displayMode ), \n fillOpacity: .7\n } );\n } else {\n map.data.remove( feature );\n console.log(\"removed feature \", feature.getProperty('NAME'));\n }\n } );\n}// End setNeighborhoodColors",
"processPage() {\n this.logger.debug(`${this}start observing`)\n $('head').appendChild(this.stylesheet)\n this.insertIconInDom()\n this.observePage()\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the translation as HTML nodes from the given source message. | get(srcMsg) {
const html = this._i18nToHtml.convert(srcMsg);
if (html.errors.length) {
throw new Error(html.errors.join('\n'));
}
return html.nodes;
} | [
"static parseHTML( content, target, messages ){\n\n let search = function( node, map ){\n let children = node.children;\n for( let i = 0; i< children.length; i++ ){\n if( children[i].id ) map[children[i].id] = children[i];\n if( messages ){\n [\"title\", \"placeholder\"].forEach( function( attr ){\n let matchattr = `data-${attr}-message`;\n if( children[i].hasAttribute( matchattr )){\n let msg = children[i].getAttribute( matchattr );\n children[i].setAttribute( attr, messages[msg] );\n }\n });\n if( children[i].hasAttribute( \"data-textcontent-message\" )){\n let msg = children[i].getAttribute( \"data-textcontent-message\" );\n children[i].textContent = messages[msg] ;\n }\n }\n search( children[i], map );\n }\n };\n\n let nodes = {};\n target.innerHTML = content;\n search( target, nodes );\n return nodes;\n\n }",
"getHTML() {\n return getHTMLFromFragment(this.state.doc.content, this.schema);\n }",
"function renderToMessage_Targets(html, messageData) {\n // Return cases\n if( game.settings.get(MOD_ID, \"targetsSendToChat\") === \"none\" ) { return; }\n if( !messageData.message.roll ) { return; }\n \n var rollDict = JSON.parse(messageData.message.roll);\n let targetedTokens = getTokenObjsFromIds(rollDict.selectedTargets);\n if(!targetedTokens) { return; }\n \n // Build targets message\n let targetNodes = getTokensHTML(targetedTokens);\n if( !targetNodes || targetNodes.length == 0 ) { return; }\n \n // Create Base Info\n let targetsDiv = document.createElement(\"div\");\n targetsDiv.classList.add(\"targetList\");\n \n let targetsLabel = document.createElement(\"span\");\n targetsLabel.classList.add(\"targetListLabel\");\n targetsLabel.innerHTML = `<b>TARGETS:</b>`;\n targetsDiv.append(targetsLabel);\n \n // Add targets\n for(let i = 0; i < targetNodes.length; i++) {\n targetNode = targetNodes[i];\n targetsDiv.append(targetNode);\n }\n \n // append back to the message html\n html[0].append(targetsDiv);\n \n // Add target all hover function\n if( game.settings.get(MOD_ID, \"chatIntegrationClick\") ) {\n let targetsLabelList = html.find(\".targetListLabel\");\n if(targetsLabelList) targetsLabelList.click(_onChatNameClick_all);\n }\n}",
"function collectTextNodes($, $el) {\n let textNodes = [];\n $el.contents().each((ii, node) => {\n if (isTextNode(node)) {\n let $node = $(node);\n textNodes.push($node);\n } else {\n textNodes.push(...collectTextNodes($, $(node)));\n }\n });\n return textNodes;\n}",
"function renderSourceHTML(source) {\n let type = currentPage === \"confirmationPage\" ? \"share_pick\" : \"selects\";\n let sourceBody = document.createElement('div')\n let thumbnail = source.thumbnail.toDataURL();\n sourceBody.classList.add(\"box\")\n if (type === \"share_pick\") {\n sourceBody.style.marginLeft = \"0px\";\n }\n\n let image = \"\";\n if (source.appIcon) {\n image = `<img class=\"icon\" src=\"${source.appIcon.toDataURL()}\" />`;\n }\n sourceBody.innerHTML = `\n <div class=\"heading\">\n ${image}\n <span class=\"screen_label\">${source.name}</span>\n </div>\n <div class=\"${type === \"share_pick\" ? \"image_no_hover\" : \"image\"}\" onclick=\"screensharePicked('${source.id}')\">\n <img src=\"${thumbnail}\" />\n </div>\n `\n return sourceBody;\n}",
"function CLC_GetTextContent(target){\r\n if (!target){\r\n return \"\";\r\n }\r\n if (target.nodeType == 8){ //Ignore comment nodes\r\n return \"\";\r\n } \r\n var textContentFromRole = CLC_GetTextContentFromRole(target);\r\n if (textContentFromRole){\r\n return textContentFromRole;\r\n }\r\n //Ignore scripts in the body\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"script\"){\r\n return \"\";\r\n } \r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"noscript\"){\r\n return \"\";\r\n } \r\n //Do textarea twice because it may or may not have child nodes\r\n if (target.tagName && target.tagName.toLowerCase() == \"textarea\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText; \r\n }\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"textarea\"){\r\n var labelText = CLC_Content_FindLabelText(target.parentNode);\r\n return labelText; \r\n }\r\n //Same logic as textarea applies for buttons\r\n if (target.parentNode && target.parentNode.tagName && target.parentNode.tagName.toLowerCase() == \"button\"){\r\n var labelText = CLC_Content_FindLabelText(target.parentNode);\r\n return labelText + target.textContent; \r\n }\r\n if (target.tagName && target.tagName.toLowerCase() == \"button\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + target.textContent; \r\n }\r\n //Form controls require special processing\r\n if (target.tagName && target.tagName.toLowerCase() == \"input\"){\r\n if (target.type.toLowerCase() == \"radio\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindRadioButtonDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"checkbox\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindCheckboxDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"text\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindTextBlankDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if (target.type.toLowerCase() == \"password\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n if (!labelText){\r\n labelText = CLC_Content_FindPasswordDirectContent(target);\r\n }\r\n return labelText;\r\n }\r\n if ( (target.type.toLowerCase() == \"submit\") || (target.type.toLowerCase() == \"reset\") || (target.type.toLowerCase() == \"button\")){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + \" \" + target.value;\r\n }\r\n if (target.type.toLowerCase() == \"image\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText + \" \" + target.alt;\r\n }\r\n return \"\";\r\n }\r\n //MathML element - Use the functions in clc_mathml_main.js to handle these\r\n if (target.tagName && target.tagName.toLowerCase() == \"math\"){\r\n return CLC_GetMathMLContent(target);\r\n }\r\n //Images\r\n if (target.tagName && target.tagName.toLowerCase() == \"img\"){\r\n if ( target.hasAttribute(\"alt\") && target.alt == \"\" ){\r\n return \"\";\r\n }\r\n if ( target.hasAttribute(\"alt\") ){\r\n return target.alt;\r\n }\r\n //Treat missing alt as null if the user is in Brief Mode\r\n if (CLC_InfoLang == 3){\r\n return \"\";\r\n }\r\n return target.src;\r\n }\r\n //Select boxes - ignore their textContent, only read out the selected value.\r\n //However, if there is a label, use it.\r\n if (target.tagName && target.tagName.toLowerCase() == \"select\"){\r\n var labelText = CLC_Content_FindLabelText(target);\r\n return labelText;\r\n }\r\n //\"Normal\" elements that are just text content and do not require any special action\r\n if (target.textContent){\r\n return target.textContent;\r\n }\r\n return \"\";\r\n }",
"_createMessageNode({author, time, body}) {\n // header of item\n var header = document.createElement(\"header\");\n header.className = \"list-group-item-heading\";\n header.innerHTML = `<strong>${myEscape(author)}</strong> <i class=\"text-muted\">${time}</i>`;\n // body of message\n var content = document.createElement(\"p\");\n content.className = \"list-group-item-text\";\n content.innerHTML = smilify(myEscape(body).replace(/\\n/g, \"<br>\"));\n // node o message\n var node = document.createElement(\"li\");\n node.className = \"list-group-item\";\n node.appendChild(header);\n node.appendChild(content);\n return node;\n }",
"function getHtmlContent(){\n \n }",
"rawHTML(html) {\n this.$messages.html(this.$messages.html() + html);\n return this.$messagesContainer.restoreScrollPosition();\n }",
"function getRelHtml(sourceLabel, targetLabel, type, relDomain) {\r\n\tvar html = '<span class=\"nodeWord '+sourceLabel+'\">('+sourceLabel+')</span>';\r\n\thtml += '<span class=\"relArrow '+relDomain+'\">-[:' + type + ']-></span>';\r\n\thtml += '<span class=\"nodeWord '+targetLabel+'\">('+targetLabel+')</span>';\r\n\treturn html;\r\n}",
"addTranslatedMessagesToDom_() {\n const elements = document.querySelectorAll('.i18n');\n for (const element of elements) {\n const messageId = element.getAttribute('msgid');\n if (!messageId)\n throw new Error('Element has no msgid attribute: ' + element);\n const translatedMessage =\n chrome.i18n.getMessage('switch_access_' + messageId);\n if (element.tagName == 'INPUT')\n element.setAttribute('placeholder', translatedMessage);\n else\n element.textContent = translatedMessage;\n element.classList.add('i18n-processed');\n }\n }",
"function getElements() {\n\n for(let i = 0; i < 6; i++) {\n var idxBeg = $(\"source\").value.indexOf(begSubstrings[i]);\n eoeElements[i] = $(\"source\").value.substring(idxBeg + begSubstrings[i].length - 1);\n var idxEnd = eoeElements[i].indexOf(\"</\");\n eoeElements[i] = eoeElements[i].substring(i,idxEnd);\n }\n\n //A little post-loop cleanup to catch irregularities in styling from page to page\n eoeElements[0] = eoeElements[0].substring(1,eoeElements[0].length)\n\n if(eoeElements[1].substring(0,7) == ` class=`) {\n eoeElements[1] = eoeElements[1].substring(19,eoeElements[1].length)\n }\n\n startOfLinkText = eoeElements[4].lastIndexOf(`>`) + 1\n eoeElements[4] = eoeElements[4].substring(startOfLinkText,eoeElements[4].length)\n\n endOfLink = eoeElements[3].indexOf('jcr:') -1\n eoeElements[3] = \"http://www.buffalo.edu/ubit/news/article.host.html/\" + eoeElements[3].substring(0, endOfLink) + \".detail.html\"\n\n endOfImageLink = eoeElements[5].indexOf(`\"`)\n eoeElements[5] = \"http://www.buffalo.edu/content/shared/www\" + eoeElements[5].substring(0,endOfImageLink)\n\n $(\"textArea\").innerHTML = \"<b>Title: </b>\" + eoeElements[0] +\n \"<br><b>Teaser: </b>\" + eoeElements[1] +\n \"<br><b>Link text: </b>\" + eoeElements[4] +\n \"<br><b>Link: </b>\" + eoeElements[3];\n\n $(\"image\").innerHTML = \"<img src='\" + eoeElements[5] + \"'></img>\"\n}",
"toText() {\n // To avoid this, we would subclass documentFragment separately for\n // MathML, but polyfills for subclassing is expensive per PR 1469.\n // $FlowFixMe: Only works for ChildType = MathDomNode.\n const toText = child => child.toText();\n\n return this.children.map(toText).join(\"\");\n }",
"function parseSource(source) {\n var column,\n doc,\n firstNode,\n parser;\n\n parser = Cc[\"@mozilla.org/xmlextras/domparser;1\"]\n .createInstance(Ci.nsIDOMParser);\n\n try {\n doc = parser.parseFromString(\n // Wrap fragment in fake root element\n \"<root>\" + source + \"</root>\",\n \"application/xml\"\n );\n } catch (ex) {\n logger.warn(\"Unable to parse source line from validator\",\n ex);\n return null;\n }\n\n firstNode = doc.documentElement.firstChild;\n if (firstNode.nodeType === Node.TEXT_NODE) {\n if (firstNode.nextSibling) {\n // Highlighting begins at end of this text\n column = firstNode.nodeValue.length;\n } else {\n // No highlighting, don't know where error was\n column = null;\n }\n } else {\n // Highlighting begins at the start of source\n column = 0;\n }\n\n return {\n columnNumber: column,\n sourceLine: doc.documentElement.textContent\n };\n }",
"loopAndTranslateDOM() {\n\t\tconst Elements = document.querySelectorAll(\n\t\t\t`${this.prms.selectorElementTranslate}, ${this.prms.selectorAttrTranslate}`\n\t\t);\n\t\tconst clearSelector = this.prms.selectorElementTranslate.replace(/\\[|\\]/g, '');\n\t\tconst clearSelectorAttr = this.prms.selectorAttrTranslate.replace(/\\[|\\]/g, '');\n\n\t\tElements.forEach((element) => {\n\t\t\tif (element.hasAttribute(clearSelectorAttr)) {\n\t\t\t\tconst translateAttrib = element.getAttribute(clearSelectorAttr).split('|');\n\t\t\t\telement.setAttribute(translateAttrib[0], this.coreTranslate(translateAttrib[1]));\n\t\t\t} else {\n\t\t\t\telement.innerHTML = this.coreTranslate(element.getAttribute(clearSelector));\n\t\t\t}\n\t\t});\n\n\t\tthis.prms.translatingDone();\n\t}",
"renderAndReply(originalMessage, templateName, params = null) {\n var content = \"\";\n this.mu.compileAndRender(templateName, params)\n .on('data', function (data) {\n content += data.toString();\n })\n .on('end', () => {\n originalMessage.reply(content);\n });\n }",
"toNODE() {\n switch (this._type) {\n case \"NODE\":\n return this._value;\n case \"STRING\":\n let parser = new DOMParser();\n let doc = parser.parseFromString(this._value, \"text/html\");\n return doc.body.firstChild;\n case \"YNGWIE\":\n return this._value.render();\n default:\n throw new _Transform_main_js__WEBPACK_IMPORTED_MODULE_3__.default(\"Cannot transform to NODE from unsuppoted type\", this._value);\n }\n }",
"toTokens(msg) {\n // remove the prefix\n let tokensString = msg.content.slice(1).trim();\n // parse the tokens into an array\n let tokens = parse(tokensString)['_'];\n return tokens;\n }",
"translate(text, target, callback){\n\t\t\t\t// Assume that our default language on every JS or HTML template is en_US\n\t\t\t\ttranslates('en_US', target, text, callback);\n\t\t\t}",
"function consumeMessage(msgBody) {\n var content = new Array();\n var deletionArray = new Array();\n var nextLinkCluster = new Array();\n var breaks = 0;\n var n = msgBody.firstChild;\n\n for (; n; n = n.nextSibling) {\n if (n.nodeType === Node.ELEMENT_NODE) {\n if (n.tagName === \"A\" && n.classList.contains(\"quotelink\") && breaks >= 1) {\n nextLinkCluster.push(n);\n continue;\n } else if (n.tagName === \"BR\") {\n breaks++;\n }\n\n // If new content is found after the next link cluster, ignore what\n // we've acculumated and break, leaving everything for the future\n // calls of consumeXXXX functions.\n } else if (nextLinkCluster.length > 0 ) {\n var nextLinkCluster = new Array();\n break;\n } else {\n breaks = 0;\n }\n\n deletionArray.push(n);\n content.push(n);\n }\n\n // If we fall off the end and nextLinkCluster has any contents, this post\n // has trailing links. The poster is not replying to these but is instead\n // only citing them. Treat them as normal content.\n if (nextLinkCluster.length > 0) {\n deletionArray = deletionArray.concat(nextLinkCluster);\n content = content.concat(nextLinkCluster);\n }\n\n while (content.length > 0 &&\n content[content.length - 1].nodeType === Node.ELEMENT_NODE &&\n content[content.length - 1].tagName === \"BR\") {\n content.pop();\n }\n\n deletionArray.map(function(n) { msgBody.removeChild(n) });\n return content;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
readonly attribute calIDateTime reminderDueBy; | get reminderDueBy()
{
return this._reminderDueBy;
} | [
"get reminderSignalTime()\n\t{\n\t\treturn this._reminderSignalTime;\n\t}",
"get dateTimeReceived()\n\t{\n\t\treturn this._dateTimeReceived;\n\t}",
"get reminderMinutesBeforeStart()\n\t{\n\t\treturn this._reminderMinutesBeforeStart;\n\t}",
"registerReminder() {\n const delayInMs = this.state.reminderDelay * 60000;\n\n navigator.serviceWorker.controller.postMessage({ message: this.state.reminderText, delay: delayInMs });\n\n // todo: get confirmation from sw before clearing vals\n this.setState({ reminderDelay: durations[0], reminderText: '' });\n }",
"getissueDate(){\n\t\treturn this.dataArray[6];\n\t}",
"get timeChecked()\r\n\t{\r\n\t\treturn this._timeChecked;\r\n\t}",
"get reminderIsSet()\n\t{\n\t\treturn this._reminderIsSet;\n\t}",
"relDateText(dateStr, now) {\n if (now == null) {\n now = new Date();\n }\n const date = new Date(dateStr);\n const period = Dates.getDateDeltaString(date, now);\n const relDateKey =\n date > now ? 'notification_is_due' : 'notification_was_due';\n return this._format(relDateKey, { period });\n }",
"function or_set_date(supplier_id)\n{\n\tvar date_del=$(\"#rdate_\"+supplier_id).val();\n\t//Set the date \n\tsupplier_orders_list[supplier_id].requested_delivery_date = date_del;\n}",
"function getReminderInput() {\n return $('#reminder-input').val();\n}",
"constructor(title,days,time,duration,relative_time,relative_to,till,relative_to_till)\r\n {\r\n this.m_start = '' //moment object for start time\r\n this.title = title;\r\n this.days = days;\r\n this.time = time;\r\n this.duration = duration;\r\n this.relative_time = relative_time;\r\n this.relative_to = relative_to;\r\n this.till = till;\r\n this.relative_to_till = relative_to_till;\r\n this.type = ''; //i not put in constructor yet\r\n }",
"get allowNewTimeProposal()\n\t{\n\t\treturn this._allowNewTimeProposal;\n\t}",
"function getDueDate(dueDate) {\n dueDate.setDate(dueDate.getDate());\n return `${dueDate.getFullYear()}/${dueDate.getMonth() + 1}/${dueDate.getDate()}`;\n}",
"get employmentDate() {\n return this._employmentDate;\n }",
"function setCompliantWaiverDate() {\n var complaintWaiverText = Xrm.Page.getAttribute(\"tsowl_complaint_waiver\").getText();\n // Complaint Waiver ==Yes\n if (complaintWaiverText == 'Yes' || complaintWaiverText == 'Yes - AI' || complaintWaiverText == 'Yes - BP') {\n if (InitValues.WAIVER_DATE == \"\") {\n Xrm.Page.data.entity.attributes.get(\"tsowl_complaint_waiver_date\").setValue(new Date());\n }\n else {\n Xrm.Page.data.entity.attributes.get(\"tsowl_complaint_waiver_date\").setValue(InitValues.WAIVER_DATE);\n }\n }\n else {\n Xrm.Page.data.entity.attributes.get(\"tsowl_complaint_waiver_date\").setValue(null);\n }\n}",
"function renewalDate(oh) {\n\n if (oh.planType !== 'A' && oh.status === 'success') {\n return $filter('date')(moment(oh.billingPeriodEndDate).add(1, 'day').format(), 'dd-MMM-yyyy');\n } else {\n return 'N/A';\n }\n\n }",
"function onClickCalendarDate(e)\n{\n//JBARDIN\n var button = this;\n var date = button.getAttribute(\"title\");\n var dat = new Date(date.substr(6,4), date.substr(3,2)-1, date.substr(0, 2));\n\n date = dat.formatString(config.macros.calendar.tiddlerformat);\n var popup = createTiddlerPopup(this);\n popup.className = \"newReminderPopup\";\n popup.appendChild(document.createTextNode(date));\n var newReminder = function() {\n var t = store.tiddlers[date];\n displayTiddler(null, date, 2, null, null, false, false);\n if(t) {\n document.getElementById(\"editorBody\" + date).value += \"\\n<<reminder day:\" + dat.getDate() +\n \" month:\" + (dat.getMonth()+1) +\n \" year:\" + (dat.getYear()+1900) + \" title: >>\";\n } else {\n document.getElementById(\"editorBody\" + date).value = \"<<reminder day:\" + dat.getDate() +\n \" month:\" + (dat.getMonth()+1) +\n \" year:\" + (dat.getYear()+1900) + \" title: >>\";\n }\n };\n var link = createTiddlyButton(popup, \"New reminder\", null, newReminder, \"newReminderButton\"); \n popup.appendChild(document.createElement(\"hr\"));\n\n var t = findTiddlersWithReminders(dat, 0, null, null);\n for(var i = 0; i < t.length; i++) {\n link = createTiddlyLink(popup, t[i].tiddler, false);\n link.appendChild(document.createTextNode(t[i].tiddler));\n }\n\n}",
"linkTime() {\n return {\n value: this.state.start.getTime(),\n requestChange: value => this.setState({start: new Date(Number(value))})\n };\n }",
"get dateTimeCreated()\n\t{\n\t\treturn this._dateTimeCreated;\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Injects SVGs so sprites work on older browsers | function injectSVGs() {
var mySVGsToInject = document.querySelectorAll('img.iconic-sprite');
SVGInjector(mySVGsToInject);
} | [
"function spriteSVGs() {\n\tvar svgSpriteConfig = {\n\t\t\tmode: {\n\t\t\t\tcss: false,\n\t\t\t\tsymbol: {\n\t\t\t\t\tdest: paths.images.dest\n\t\t\t\t}\n\t\t\t},\n\t\t\tshape: {\n\t\t\t\tdimension: {\n\t\t\t\t\tprecision: -1,\n\t\t\t\t},\n\t\t\t\ttransform: [\n\t\t\t\t\t{\n\t\t\t\t\t\tsvgo: {removeViewBox: false}\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t};\n\n\treturn gulp.src(appFiles.svgs)\n\t\t.pipe(svgSprite(svgSpriteConfig)).on('error', errorHandler)\n\t\t.pipe(gulp.dest('.'));\n}",
"function renderSVG(svg, container, options) {\r\n /* Insert SVG object. */\r\n $(container).empty().append(svg);\r\n}",
"_renderIcon () {\n let p = this._props,\n svg = document.createElementNS( this.NS, 'svg' ),\n content = `<use xlink:href=\"#${ p.prefix }${ p.shape }-icon-shape\" />`;\n svg.setAttribute( 'viewBox', '0 0 32 32' );\n this._addSVGHtml( svg, content );\n this.el.appendChild( svg );\n }",
"function createTempImage(){\n tempImage = game.instantiate(new Sprite('./img/beginplaatje.svg'));\n tempImage.setPosition({x: Settings.canvasWidth/2 - 110, y: Settings.canvasHeight/2 - 110});\n tempImage.setSize({x: 200, y: 200});\n}",
"createSVGElement(w,h){const svgElement=document.createElementNS(svgNs$1,'svg');svgElement.setAttribute('height',w.toString());svgElement.setAttribute('width',h.toString());return svgElement;}",
"function create_svg_ecgtoolbar_container(that) {\n var desc_id = that.attr(\"id\");\n var img = that.find(\"img.\"+toolbar_class);\n if (img.length != 0) {\n var img_src = img.attr(\"src\");\n time_1_second_in_pixels = img.attr('data-time_1_second_in_pixels');\n current_1_volt_in_pixels = img.attr('data-current_1_volt_in_pixels');\n // console.log(img.width(), img.height());\n // calculate width and set in css of svg container keeping height fixed to 400px\n // remove measure_img tag and add hide to indicate that image ruler container has been generated\n img.toggleClass(\"hide \"+toolbar_class);\n\n // set image url for svg background\n var main_parent_container_temp = main_parent_container.replace('svg_desc_id', 'svg_'+desc_id);\n main_parent_container_temp = main_parent_container_temp.replace('panzoom_svg_background', \"'\" + img_src + \"'\" );\n\n var updated_html = that.html() + main_parent_container_temp;\n\n that.html(updated_html);\n }\n }",
"createSvgRectElement(x,y,w,h){const el=document.createElementNS(BrowserCodeSvgWriter.SVG_NS,'rect');el.setAttributeNS(svgNs,'x',x.toString());el.setAttributeNS(svgNs,'y',y.toString());el.setAttributeNS(svgNs,'height',w.toString());el.setAttributeNS(svgNs,'width',h.toString());el.setAttributeNS(svgNs,'fill','#000000');return el;}",
"_downloadSvgAsPng() {\n savesvg.saveSvgAsPng(document.getElementById(\"svg\"), \"timeline.png\");\n }",
"toImg(svgText, orgWidth, orgHeight, imgWidth, imgHeight) {\n\t\t// Create Canvas\n\t\tlet canvas = document.createElement('canvas');\n\t\tcanvas.width = imgWidth;\n\t\tcanvas.height = imgHeight;\n\t\tlet ctx = canvas.getContext(\"2d\");\n\n\t\t// show canvas\n\t\t//this._refRenderer.current.appendChild(canvas);\n\n\t\t// Create image\n\t\tlet img = document.createElement('img');\n\t\t// when loaded draw and save\n\t\timg.addEventListener('load', e=> {\n\t\t\t// draw image\n\t\t\tctx.drawImage(img,\n\t\t\t\t0, 0, orgWidth, orgHeight,\n\t\t\t\t//0, 0, imgWidth, imgHeight\n\t\t\t\t0, 0, orgWidth, orgHeight\n\t\t\t);\n\t\t\t// save image\n\t\t\tcanvas.toBlob(function(blob) {\n\t\t\t\tFileSaver.saveAs(blob, \"magboard.png\");\n\t\t\t});\n\t\t\t// clear everything\n\t\t\tthis._refRenderer.current.innerHTML = '';\n\t\t});\n\n\t\t// prepare svg to load image\n\t\tconst encodedString = 'data:image/svg+xml;base64,' + new Buffer(svgText).toString('base64');\n\t\timg.src = encodedString;\t// start loading image\n\t}",
"createSprite() {\n this.sprite = new PIXI.Sprite(PIXI.loader.resources[this.category].textures[this.spriteName]);\n if(this.isOnFloor) {\n this.sprite.position.set(this.x, this.y);\n }\n this.sprite.width = this.sprite.height = this.spriteSize;\n this.floor.itemSprites.addChild(this.sprite);\n\n // would be nice to consolidate to a function. currently not working\n // this._textStyle = new PIXI.TextStyle({\n // fill: '#fff',\n // fontSize: 17\n // });\n // this.itemNameSprite = new PIXI.Text(this.spriteName, this._textStyle);\n // /* eslint-disable-next-line no-extra-parens */\n // this.itemNameSpriteOffset = (this.sprite.width / 2) - (this.itemNameSprite.width / 2);\n // this.itemNameSprite.position.set(\n // this.sprite.position.x + this.itemNameSpriteOffset,\n // this.sprite.position.y - 15\n // );\n // this.floor.itemSprites.addChild(this.itemNameSprite);\n }",
"createSvgRectElement(x,y,w,h){const rect=document.createElementNS(svgNs$1,'rect');rect.setAttribute('x',x.toString());rect.setAttribute('y',y.toString());rect.setAttribute('height',w.toString());rect.setAttribute('width',h.toString());rect.setAttribute('fill','#000000');return rect;}",
"function addGraphicsToLayout()\r{\r var xmlElement = app.activeDocument.xmlElements[0];\r var pageLinkTags = xmlElement.evaluateXPathExpression(\"/Root/page\");\r $.writeln(\"# of tags: \" + pageLinkTags.length);\r for (var x = 0; x < pageLinkTags.length; x++)\r {\r var xmlElement = pageLinkTags[x];\r var tagName = xmlElement.markupTag.name;\r $.writeln(\"xml tag: \" + tagName);\r var pageNameTags = xmlElement.evaluateXPathExpression(\"/page/pageName\");\r if (pageNameTags.length > 0) {\r var pageNameTag = pageNameTags[0];\r var pageNumber = pageNameTag.contents;\r $.writeln(\"page#: \" + pageNumber);\r var page = app.activeDocument.pages.itemByName(pageNumber);\r if (page.textFrames.length > 0) {\r var myTextFrame = page.textFrames[0];\r } else {\r $.writeln(\"ERROR: No Text Frame on page\");\r }\r var imageLinkTags = xmlElement.evaluateXPathExpression(\"/page/graphic/imageLink\");\r for (var y = 0; y < imageLinkTags.length; y++)\r {\r var imageLinkTag = imageLinkTags[y];\r $.writeln(\"imageLink: \" + xmlElement.contents);\r // TO DO !!! UN Hard Code the following path\r var imagePath = \"/Users/scottrichards/Documents/BIP/\" + docData.selectedDocFileName + \"/\" + imageLinkTag.contents;\r $.writeln(\"placing image: \" + imagePath);\r myTextFrame.insertionPoints.item(-1).place(imagePath); \r }\r } \r }\r}",
"_updateSVG() {\n this.SVGInteractor.updateView(this.currentXRange, this.currentYRange, this.width, this.height);\n this.SVGInteractor.updateSelectView(this._currentSelectionPoints);\n }",
"function createSvg(path){\n const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n const pathElement = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n\n attrDict(svg, {\n 'class':'svg-icon',\n 'viewBox': '0 0 20 20'\n })\n\n attrDict(pathElement,{\n 'fill': 'none',\n 'd': path\n })\n svg.appendChild(pathElement);\n return svg;\n}",
"async function loadSVG() {\n const response = await fetch(\"coloringBook.svg\");\n const svgData = await response.text();\n\n document.querySelector(\"#placeSvg\").innerHTML = svgData;\n registerEventListeners();\n}",
"function renderNPCSprites(aDev,aGame)\n{\n ////this makes a temp object of the image we want to use\n //this is so the image holder does not have to keep finding image\n tempImage1 = aDev.images.getImage(\"orb\")\n tempImage2 = aDev.images.getImage(\"fireAmmo\")\t\n for (var i = 0; i < aGame.gameSprites.getSize(); i++)\n {\t\n ////this is to make a temp object for easier code to write and understand\n tempObj = aGame.gameSprites.getIndex(i); \n switch(tempObj.name)\n {\n case \"orb\":\n aDev.renderImage(tempImage1,tempObj.posX,tempObj.posY);\n break;\n case \"fireAmmo\":\n aDev.renderImage(tempImage2,tempObj.posX,tempObj.posY);\n break;\n } \n }\n}",
"function createSpecialMonster(x, y) {\n console.log(\"create special\");\n var monster = svgdoc.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n monster.setAttribute(\"x\", x);\n monster.setAttribute(\"y\", y);\n if (Math.floor(2* Math.random()) == 0){\n monster.speed = MONSTER_SPEED;\n monster.currentMotion = motionType.RIGHT;\n } else {\n monster.speed = - MONSTER_SPEED;\n monster.currentMotion = motionType.LEFT;\n }\n monster.right_boundary = Math.floor((SCREEN_SIZE.w-MONSTER_SIZE.w-x-1) * Math.random())+ x+1 + MONSTER_SIZE.w;\n monster.left_boundary = Math.floor(x * Math.random());\n monster.setAttributeNS(\"http://www.w3.org/1999/xlink\", \"xlink:href\", \"#monster\");\n monster.special = true;\n svgdoc.getElementById(\"monsters\").appendChild(monster);\n}",
"function createAddIcon() {\n const addIcon = document.createElement('img')\n addIcon.classList.add('icon')\n addIcon.src = '/static/images/plus_icon_blue.svg'\n return addIcon\n }",
"updateSprite() {\n\t\tif(!this.multiTexture) {\n\t\t\tthis.graphics.sprite.texture = PIXI.Texture.fromFrame('sprite_' + (this.id < 10 ? '0' : '') + this.id + '.png');\n\t\t}\n\t\telse {\n\t\t\tthis.graphics.sprite.texture = PIXI.Texture.fromFrame('sprite_' + (this.id < 10 ? '0' : '') + this.id + '_' +\n\t\t\t\t\t\t\t\t\t\t\t(this.multiTextureId < 10 ? '0' : '') + this.multiTextureId + '.png');\n\t\t}\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mostrar todos los objetos de JSON y sus propiedades. | function mostrarObjetos(json){
var out="----------------------------Estudiantes----------------------------<br>";
for (var i = 0; i < json.length; i++) {
out+="Nombre: "+json[i].nombre+" - "+"Codigo: "+json[i].codigo+ " - " +"Nota: "+json[i].nota+" <br> ";
}
document.getElementById("infoEstudiantes").innerHTML=out;
} | [
"function showJson() {\n var strJsonExes = JSON.stringify(jsonExes);\n document.querySelector('pre').innerHTML = strJsonExes;\n btn = document.getElementById('show-json')\n showOrHideElement(btn);\n}",
"function AjoutProduit() {\n\n let product = {\n \"name\": document.getElementById(\"addName\").value,\n \"type\": document.getElementById(\"AddSelectType\").value,\n \"description\": document.getElementById(\"addDesc\").value,\n \"price\": document.getElementById(\"addPrice\").value,\n \"quantity\": document.getElementById(\"addQts\").value,\n \"traduction\": document.getElementById(\"AddSelectType\").value\n };\n\n jsonDatas.push(product);\n console.log(jsonDatas);\n allProducts(jsonDatas);\n\n alert(produit.name + \" \" + produit.type + \" \" + produit.traduction);\n\n}",
"function displayObject() {\n var output = Object.values(audi) + \"<br>\" + Object.values(mercedez) + \"<br>\" + Object.values(bmw)\n document.getElementById(\"displayobj\").innerHTML=output;\n}",
"function showProperties(obj) {\n for(let key in obj) {\n if(typeof obj[key] === 'string') {\n console.log(key, obj[key]);\n }\n }\n}",
"function mostrarProductos(productos){\n console.log(\"****************************************\")\n productos.forEach(producto=>{\n \n console.log(\"Codigo del producto \"+producto.codprod)\n console.log(\"producto \"+producto.nomprod)\n console.log(\"precio \"+producto.precio)\n console.log(\"Inventario \"+producto.inventario)\n \n console.log(\"****************************************\") \n\n }\n );\n}",
"function pusher() {\n //var obj = JSON_Obj.orders\n var resposta = [];\n obj.forEach(element => {\n resposta.push(element)\n });\n //for (var i in obj)\n \n //console.log(obj)\n //console.log(typeof resposta[7])\n console.log(resposta)\n }",
"function mostrarDetalles (usuario) {\n $(\"#id\").html(usuario.id);\n $(\"#nombre\").html(usuario.nombre);\n $(\"#username\").html(usuario.username);\n $(\"#nacimiento\").html(usuario.nacimiento);\n $(\"#posts\").html(usuario.posts);\n }",
"function generateUIForJSON(data){\n return `\n <div class=\"quarter\">\n <div class=\"image\">\n <img src=\"${data.picture}\"/>\n </div>\n <div class=\"info\">\n <h3>${data.name}</h3>\n <h4>${data.gender}</h3>\n <h5>${data.email}</h5>\n </div>\n </div>\n `\n}",
"function Listar() {\n $(\"#tbCadastro\").html(\"\");\n $(\"#tbCadastro\").html(\n \"<thead>\" +\n \" <tr>\" +\n \" <th>CPF</th>\" +\n \" <th>Nome</th>\" +\n \" <th></th>\" +\n \" </tr>\" +\n \"</thead>\" +\n \"<tbody>\" +\n \"</tbody>\"\n );\n\t\tfor (var i in tbDados) {\n var cli = JSON.parse(tbDados[i]);\n var novaLinha = $(\"<tr>\");\n var cols = \"\";\n cols += \"<td>\" + cli.cpf + \"</td>\";\n cols += \"<td>\" + cli.nome + \"</td>\";\n cols += \"<td>\" +\n \" <img src='img/edit.png' alt='\" +\n i + \"' class='btnEditar'/>\" + \" \" +\n \"<img src='img/delete.png' alt='\" +\n i + \"' class='btnExcluir'/>\" + \"</td>\";\n novaLinha.append(cols);\n\t\t\t$(\"#tbCadastro\").append(novaLinha);\n }\n }",
"function gettingJasonMembersObj(event) {\n const savedMembers = JSON.parse(event.target.responseText);\n appData.members = savedMembers.members\n jsonsState.push('true');\n addLabelColors();\n //checking only two since i have only 2 AJAX calls\n checkIfCanLoadPage();\n // firstLoad();\n\n //\n // firstLoad();\n // for (const member of appData.members) {\n\n // createMemberList(member.name);\n //\n // }\n}",
"function mostrarProductoC(cliente) {\n console.log(\"***************************\");\n cliente.forEach((client) => {\n console.log(\"ID CLIENTE \" + client.id);\n console.log(\"NOMBRE CLIENTE \" + client.name);\n console.log(\"EMAIL \" + client.email);\n console.log(\"EDAD \" + client.age);\n console.log(\"***************************\");\n });\n}",
"function fillStudentInfo(studentJson) {\n var firstName = studentJson.etudiant.prenom;\n var lastName = studentJson.etudiant.nom;\n var academicYear = studentJson.monAnnee.anneeAcademique;\n var programTitle = studentJson.monAnnee.monOffre.offre.intituleComplet;\n $(\"#student_name\").append(\"<br>\");\n $(\"#student_name\").append(lastName + \", \" + firstName);\n $(\"#academic_year\").append(\"<br>\");\n $(\"#academic_year\").append(academicYear);\n $(\"#program_title\").append(\"<br>\");\n $(\"#program_title\").append(programTitle);\n}",
"async loadFromJSON(JSONs) {\n if(JSONs) {\n let JSONObj = JSONs.JSONItems\n for (let i = 0; i < JSONObj.length; i++) {\n let product = new Product(JSONObj[i].id, JSONObj[i].name, JSONObj[i].price, JSONObj[i].image);\n for (let j = 0; j < JSONObj[i].count; j++) {\n await this.addItem(product);\n }\n }\n }\n }",
"function getJson() {\n axios.get(`${protocol}feeds.ibood.com/nl/nl/offer.json`).then(result => {\n if (isNew(result.data)) {\n currentTitle = result.data.Title;\n\n // try and get the google price\n getGooglePrice(encodeURIComponent(result.data.Title)).then(price => {\n result.data.google = price;\n\n notify(result.data);\n }).catch(err => {\n\n result.data.google = \"n/a\";\n notify(result.data);\n });\n }\n });\n}",
"buscarMedicos() {\n\t\tApiService.chamada(\"Medico/Listar\").Listar()\n\t\t\t.then(resposta => resposta.json())\n\t\t\t.then(resultado => this.setState({ medicos: resultado }))\n\t\t\t.catch(erro => console.log(erro));\n\t}",
"function getTotalObjects(cb) {\n var xhr = new XMLHttpRequest();\n var apiAll = apiMetObject.substring(0, apiMetObject.length - 1);\n xhr.open(\"GET\", apiAll);\n xhr.send();\n xhr.onreadystatechange = function () {\n if (this.readyState == 4 && this.status == 200) {\n cb(JSON.parse(this.responseText));\n console.log(\n \"******** JSON response text \" + JSON.parse(this.responseText)\n );\n }\n };\n}",
"toJSON() {\n let items = _items.get(this);\n let JSONItems = [];\n for( let i = 0; i < items.length ; i++ ) {\n console.log(items[i].getCount());\n JSONItems.push({\n count: items[i].getCount(),\n name: items[i].getProduct().getName(),\n id: items[i].getProduct().getId(),\n price: items[i].getProduct().getPrice(),\n image: items[i].getProduct().getImage()\n });\n }\n return { JSONItems };\n }",
"function loadObjects() {\n $.getJSON('https://secure.toronto.ca/cc_sr_v1/data/swm_waste_wizard_APR?limit=1000', function (data) {\n allObjects = data;\n }).error(function () {\n console.log('error: json not loaded'); // debug\n }).done(function () {\n console.log(\"JSON loaded!\"); // debug\n initLocalStorage();\n $(document).ready(function () {\n document.getElementById(\"favourites\").innerHTML = insertFavourites();\n }); // render the fav list\n addEventListenersToFav();\n });\n\n}",
"function getProducts() {\n $.ajax({\n url: \"files/productlist.json\",\n dataType: 'json',\n success: function(data) {\n var product =\"\";\n\n $.each(data, function(key, value) { // Execute for each set of data\n product = Object.values(value);\n productlist.push(product);\n }); \n },\n error(xhr, status, error) { // Function for error message and error handling\n console.log(error);\n }\n })\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
carga hacemos la transaccion al code behind por medio de Ajax para cargar el droplist | function transacionAjax_CState(State) {
$.ajax({
url: "UsuarioAjax.aspx",
type: "POST",
//crear json
data: { "action": State,
"tabla": 'USUARIOS'
},
//Transaccion Ajax en proceso
success: function (result) {
if (result == "") {
ArrayDroplist = [];
}
else {
ArrayDroplist = JSON.parse(result);
charge_CatalogList(ArrayDroplist, "Select_Estado", 0);
}
},
error: function () {
}
});
} | [
"function loadAllDropDownListAtStart(){\n\t\t//load vào ddl customer\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/customer/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlCustomer').append($('<option>', {\n value: value.customercode,\n text: value.shortname\n }));\n \n //load bên edit\n $('#editFabricInformationDialog').find('#ddlCustomer').append($('<option>', {\n value: value.customercode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl fabric supplier\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/fabricSupplier/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlFabricSupplier').append($('<option>', {\n value: value.fabricsupcode,\n text: value.shortname\n }));\n \n //bên edit\n $('#editFabricInformationDialog').find('#ddlFabricSupplier').append($('<option>', {\n value: value.fabricsupcode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl chori agent\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/agent/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlChoriAgent').append($('<option>', {\n value: value.agentcode,\n text: value.shortname\n }));\n \n $('#editFabricInformationDialog').find('#ddlChoriAgent').append($('<option>', {\n value: value.agentcode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl factory\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/factory/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlFactory').append($('<option>', {\n value: value.factorycode,\n text: value.shortname\n }));\n \n $('#editFabricInformationDialog').find('#ddlFactory').append($('<option>', {\n value: value.factorycode,\n text: value.shortname\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl width\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/width/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.width == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlWidth').append($('<option>', {\n value: value.widthcode,\n text: value.widthcode\n }));\n \n $('#editFabricInformationDialog').find('#ddlWidth').append($('<option>', {\n value: value.widthcode,\n text: value.widthcode\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show! 194');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl currency\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/currency/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDialog').find('#ddlCurrency').append($('<option>', {\n value: value.currencycode,\n text: value.name\n }));\n \n $('#editFabricInformationDialog').find('#ddlCurrency').append($('<option>', {\n value: value.currencycode,\n text: value.name\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t\t\n\t\t//load vào ddl Color\n\t\t$.ajax({\n \t\tdataType: \"json\",\n\t\t\ttype: 'GET',\n\t\t\tdata:{},\n\t\t\tcontentType: \"application/json\",\n\t\t\turl: \"/Chori/color/list\",\n\t\t\tsuccess: function(data){\n\t\t\t\tif(data.status == \"ok\"){\n\t\t\t\t\t$.each( data.list, function( key, value ) {\n $('#addFabricInformationDetailDialog').find('#ddlColor').append($('<option>', {\n value: value.colorcode,\n text: value.description\n }));\n \n $('#editFabricInformationDialog').find('#ddlColor').append($('<option>', {\n value: value.colorcode,\n text: value.description\n }));\n \n $('#addFabricInformationDetailEditVerDialog').find('#ddlColor').append($('<option>', {\n value: value.colorcode,\n text: value.description\n }));\n });\n\t\t\t\t}else{\n\t\t\t\t\talert('This alert should never show!');\n\t\t\t\t}\n\t\t\t},\n\t\t\terror: function(){\n\t\t\t\talert('Error !!');\n\t\t\t}\n \t});\n\t\t//\n\t}",
"function cargarCbxTipoProd(response) {\n\t$(\"#selTipoProd\").empty();\n $.each(response, function () {\n $(\"#selTipoProd\").append($(\"<option></option>\").val(this['idTipoProd']).html(this['descripcion']));\n });\n //inmediatamente a la carga de tipo prod, cargo los prod asociados.\n cargarCbxProd();\n}",
"function GetDropDownList() {\n var typeCodeList = [\"WMSYESNO\", \"WMSRelationShip\", \"INW_LINE_UQ\", \"PickMode\"];\n var dynamicFindAllInput = [];\n\n typeCodeList.map(function (value, key) {\n dynamicFindAllInput[key] = {\n \"FieldName\": \"TypeCode\",\n \"value\": value\n }\n });\n var _input = {\n \"searchInput\": dynamicFindAllInput,\n \"FilterID\": appConfig.Entities.CfxTypes.API.DynamicFindAll.FilterID\n };\n\n apiService.post(\"eAxisAPI\", appConfig.Entities.CfxTypes.API.DynamicFindAll.Url + authService.getUserInfo().AppPK, _input).then(function (response) {\n if (response.data.Response) {\n typeCodeList.map(function (value, key) {\n PickupanddeliverydetailCtrl.ePage.Masters.DropDownMasterList[value] = helperService.metaBase();\n PickupanddeliverydetailCtrl.ePage.Masters.DropDownMasterList[value].ListSource = response.data.Response[value];\n });\n }\n });\n }",
"function cargarDepartamentosPorPais1(campoPais) {\n\tvar divTemp=$(campoPais).closest(\"div[name=formularioEquipoCaso]\");;\n\t//var divTemp=$(campoPais).closest(\"div[name=ubicacion]\");\n\tvar campoDepartamento=null;\n\t$(divTemp).find(\"select[name^='TxtDepartamentoMiembro']\").each(function(){\n\t\tcampoDepartamento=$(this)[0];\n\t\t$(campoDepartamento).find(\"option\").remove();\n\t });\n\t$(divTemp).find(\"select[name^='txtMunicipioMiembro']\").each(function(){\n\t\t$(this).find(\"option\").remove();\n\t });\n\tvar codigoPais = \"codigoPais=\" + campoPais.value;\n\t$.ajax({\n\t\t dataType: \"json\",\n\t\t url: contexto + \"/maestro/obtenerDepartamentosPorPais\",\n\t\t data: codigoPais,\n\t\t success: function (response) {\n\t\t\t //var select = document.getElementById(campoDepartamento);\n\t\t\t var option = document.createElement(\"option\");\n\t\t\t option.value = \"\";\n\t\t\t option.text = \"Seleccionar\";\n\t\t\t campoDepartamento.add(option);\n\t\t\t $.each(response.departamentos, function(index, optionData) {\t \n\t\t\t\t //var select = document.getElementById(campoTemp);\n\t\t\t\t var option = document.createElement(\"option\");\n\t\t\t\t option.value = optionData.codigo;\n\t\t\t\t option.text = optionData.nombre;\n\t\t\t\t campoDepartamento.add(option);\n\t\t\t });\n\t\t }\n\t});\n}",
"function admin_post_edit_load_univ() {\n get_univ(faculty_selector_vars.countryCode, function (response) {\n\n var stored_univ = faculty_selector_vars.univCode;\n var obj = JSON.parse(response);\n var len = obj.length;\n var $univValues = '';\n\n $(\"select[name*='univCode']\").fadeIn();\n for (i = 0; i < len; i++) {\n var myuniv = obj[i];\n var current_univ = myuniv.country_code + '-' + myuniv.univ_code;\n if (current_univ == stored_univ) {\n var selected = ' selected=\"selected\"';\n } else {\n var selected = false;\n }\n $univValues += '<option value=\"' + myuniv.country_code + '-' + myuniv.univ_code + '\"' + selected + '>' + myuniv.univ_name + '</option>';\n\n }\n $(\"select[name*='univCode']\").append($univValues);\n\n });\n }",
"function initDropdown(){\n $.ajax({\n url: '/playlists',\n type: 'GET',\n contentType: 'application/json',\n success: function(res) {\n var pDrop = ``;\n for(var i=0; i<res.length; i++){\n pl = res[i]\n var addD = `<option id=${pl._id}>${pl.name}</option>`\n pDrop = pDrop.concat(addD);\n }\n $('select#selectPlaylist').html(pDrop);\n }\n }); //close ajax brack\n \n }",
"function cargarCbxProd() {\n\t$(function() {\n\t\tvar fillCbxProd = function() {\n\t\t\t//\n\t\t\tconsole.log('entra a fill de producto');\n\t\t\t//\n\t\t\tvar selected = $('#selTipoProd').val();\n\t\t\tvar data = 'tipoRequest=L' + '&idTipoProd=' + selected;\n\t\t\t $.ajax({\n\t type: \"POST\",\n\t url: \"ServletObtProducto\",\n\t data: data,\n\t success: function(response) {\n\t \t$('#selProd').empty();\n\t \t$.each(response, function () {\n\t \t\t$(\"#selProd\").append($(\"<option></option>\").val(this['idProducto']).html(this['nombre']));\n\t \t});\n\t \t$('#selProd').trigger('change');\n\t }, error: function (response) {\n\t \tbootstrap_alert.danger(response.responseText);\n\t }\n\t\t });\n\t\t}\n\t\tfillCbxProd();\n\t});\n\tcargarDatosProd();\n}",
"function FillLanguagesCallBack(data, request) {\n FillDropDowns(\"Language\", data);\n}",
"function BindFranchiseeName(dept, customUrlIT) { \n $('.FranchiseeName option').remove();\n $.ajax({ \n type: \"POST\",\n url: customUrlIT,\n data: '{}',\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function (r) {\n console.log(r);\n //var dept = $(\"#ddlFranchiseeNameIT\");\n //dept.empty().append('<option selected=\"selected\" value=\"0\">--Select--</option>');\n $.each(r.d, function (key, value) {\n dept.append($(\"<option></option>\").val(value.FranchiseeID).text(value.FirmName));\n }); \n dept.multiselect('rebuild');\n }\n });\n}",
"function cargarCiudadPorDepartamentos1(campoDepartamento) {\n\t\n\tvar divTemp=$(campoDepartamento).closest(\"div[name=formularioEquipoCaso]\");\n\tvar campoCiudad=null;\n\t$(divTemp).find(\"select[name^='txtMunicipioMiembro']\").each(function(){\n\t\tcampoCiudad=$(this)[0];\n\t\t$(this).find(\"option\").remove();\n\t });\n\tvar codigoDepartamento = \"codigoDepartamento=\" + campoDepartamento.value;\n\t$.ajax({\n\t\t dataType: \"json\",\n\t\t url: contexto + \"/maestro/obtenerCiudadPorDepartamento\",\n\t\t data: codigoDepartamento,\n\t\t success: function (response) {\n\t\t\t //var select = document.getElementById(campoDepartamento);\n\t\t\t var option = document.createElement(\"option\");\n\t\t\t option.value = \"\";\n\t\t\t option.text = \"Seleccionar\";\n\t\t\t campoCiudad.add(option);\n\t\t\t $.each(response.ciudades, function(index, optionData) {\t \n\t\t\t\t //var select = document.getElementById(campoTemp);\n\t\t\t\t var option = document.createElement(\"option\");\n\t\t\t\t option.value = optionData.codigo;\n\t\t\t\t option.text = optionData.nombre;\n\t\t\t\t campoCiudad.add(option);\n\t\t\t });\n\t\t }\n\t});\n}",
"function initierDropDown(tbl, selId) {\r\n // Fyll inn dropdown\r\n db.transaction(function(tx) {\r\n initierListe(tx, tbl, selId, oppdaterSelect);\r\n }, DbErrorHandler);\r\n}",
"function cargarAbogado(campoAbogado) {\n\t$.ajax({\n\t\t dataType: \"json\",\n\t\t url: contexto + \"/maestro/obtenerAbogados\",\n\t\t data: null,\n\t\t success: function (response) {\n\t\t\t var select = document.getElementById(campoAbogado);\n\t\t\t var option = document.createElement(\"option\");\n\t\t\t option.value = \"\";\n\t\t\t option.text = \"Seleccionar\";\n\t\t\t select.add(option); \n\t\t\t $.each(response.abogados, function(index, optionData) {\t \n\t\t\t\t var select = document.getElementById(campoAbogado);\n\t\t\t\t var option = document.createElement(\"option\");\n\t\t\t\t option.value = optionData.codigo;\n\t\t\t\t option.text = optionData.nombre;\n\t\t\t\t select.add(option);\n\t\t\t });\n\t\t }\n\t});\n}",
"function CargarAlumnos() {\r\n var params = \"Accion=ListarAlumnos\";\r\n var json = cargarArchivoPost(\"Default.aspx\", params);\r\n try {\r\n Alumnos = JSON.parse(json);\r\n BuscarGrupos();\r\n } catch (e) {\r\n swal(\"Oops...!\", \"Hubo un problema intentando cargar la pantalla de alumnos!\", \"error\");\r\n }\r\n }",
"function initierDropDowns() {\r\n console.log(\"initierDropDowns\");\r\n // Fyll inn dropdown for våpen\r\n initierDropDown(\"vaapen\", \"#selectVaapen\");\r\n initierListView(\"vaapen\", \"#vaapenList\");\r\n\r\n}",
"function mapa_cargarSelectSubzonas(lista_subzonas) {\n\tg_lista_subzonas = new Array();\n\tvar html_subzonas = '<option value=\"none\">Selecciona un estado</option>';\n\tif (!(g_mapa_zona_seleccionada_id === 'none')) {\n\t\thtml_subzonas += '<option value=\"all\">Todos</option>';\n\t}\n\tfor (var i = 0; i < lista_subzonas.length; i++) {\n\t\tvar subzona = lista_subzonas[i];\n\t\thtml_subzonas += '<option value=\"' + subzona.estado_codigo + '\">' + subzona.estado_nombre + '</option>';\n\t\tg_lista_subzonas.push(subzona);\n\t}\n\t$('#mapa-subzona-select').html(html_subzonas);\n\t$('#mapa-subzona-select').selectpicker('refresh');\n\t$('#mapa-subzona-select').change(function() {\n\t\tg_mapa_subzona_seleccionada_id = $('#mapa-subzona-select').val();\n\t\tmapa_seleccionarSubZona(g_mapa_subzona_seleccionada_id, true);\n\t});\n\tg_mapa_subzona_seleccionada_id = 'none';\n}",
"function oField_mInitializeDropDownList(p_id, p_list, p_filter, p_placeholder) {\n if (typeof p_filter === 'undefined') p_filter = \"\";\n if (typeof p_placeholder === 'undefined') p_placeholder = \"Select...\";\n var h_data = [];\n if (p_list !== \"\") {\n h_data = oLists_mGetList(p_list);\n }\n $(\"#\" + p_id).kendoDropDownList({\n optionLabel: g_oTranslator.get(p_placeholder),\n dataTextField: \"text\",\n dataValueField: \"value\",\n dataSource: h_data,\n filter: p_filter,\n autoBind: true,\n index: 0,\n height: 350,\n noDataTemplate: g_oTranslator.get(\"No data found.\"),\n cascade: function (e) {\n var data = [{ id: e.sender.element[0].id, value: e.sender.element[0].value, type: 'select', action: 'change' }];\n $(document).trigger('mP_mOnChangeField', data);\n },\n select: function (e) {\n var data = [{ id: e.sender.element[0].id, value: e.sender.element[0].value, type: 'select', action: 'select' }];\n $(document).trigger('mP_mOnChangeField', data);\n },\n popup: {\n appendTo: \"#mainForm\"\n }\n });\n if (p_list === \"CNT\") {\n if (localStorage.scs_language === \"en\") $(\"#\" + p_id).data('kendoDropDownList').value(\"GB\");\n else if (localStorage.scs_language === \"de\") $(\"#\" + p_id).data('kendoDropDownList').value(\"DE\");\n else if (localStorage.scs_language === \"fr\") $(\"#\" + p_id).data('kendoDropDownList').value(\"FR\");\n else $(\"#\" + p_id).data('kendoDropDownList').value(\"NL\");\n }\n if (p_list === \"LNG\") {\n $(\"#\" + p_id).data('kendoDropDownList').value(localStorage.scs_language);\n }\n}",
"function LoadDropDownValuesForPayment(id,str)\r\n{\r\n var dropDownList =document.getElementById(id);\r\n\tif(showACHItem('ccdpay'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"CCD Payment (Corporate)\";\r\n\t optn.value = \"CCD\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('child'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"Child Support Payment\";\r\n\t optn.value = \"CHILD\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('ctx'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"CTX Payment (Corporate Trade Exchange)\";\r\n\t optn.value = \"CTX\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('federal'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"Federal Tax\";\r\n\t optn.value = \"FED\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('iat'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"IAT Payment (International)\";\r\n\t optn.value = \"IAT\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('payment'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"PPD Payment (Personal)\";\r\n\t optn.value = \"PPD\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('state'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"State Tax\";\r\n\t optn.value = \"STATE\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n\tif(showACHItem('stp820'))\r\n\t{\r\n\t var optn=document.createElement(\"OPTION\");\r\n\t optn.text = \"STP 820 Payment\";\r\n\t optn.value = \"STP820\"+str;\r\n\t dropDownList.options.add(optn);\r\n\t}\r\n}",
"function seleccionarUG(combo){\n //var combo=window.event.srcElement;\n //alert('Combo seleccionado ' + combo);\n //combo.name //nombre combo\n //combo.value //devuelve ultimo oid del combo seleccion\n //guardar en un hidden hUltimoOidUG\n //if ( get( 'frmDatos.comboUnidad1', 'T' ) == '' ){\n\t\tif (combo == 0) {\n //alert(\"combo 1\");\n deshabilitarResto(1);\n\t\t cargarCombo1();\n }else \n\t\tif (combo == 1) {\n deshabilitarResto(2);\n if ( get( 'frmDatos.comboUnidad1', 'T' ) != '' ) \n\t\t\t cargarCombo2();\n\t\t else\n\t\t\t comboUnidad2.disabled = true;\n }else \n\t\tif (combo == 2) {\n deshabilitarResto(3);\n\t\t\tif ( get( 'frmDatos.comboUnidad2', 'T' ) != '' )\n\t\t\t\tcargarCombo3();\n\t\t\telse\n\t\t\t comboUnidad3.disabled = true;\n }\n else \n\n\t\tif (combo == 3) {\n deshabilitarResto(4);\n if ( get( 'frmDatos.comboUnidad3', 'T' ) != '' ) \n\t\t\t cargarCombo4();\n\t\t else\n\t\t\t comboUnidad4.disabled = true;\n }\n else \n\n\t\tif (combo == 4) {\n\n deshabilitarResto(5);\n if ( get( 'frmDatos.comboUnidad4', 'T' ) != '' ) \n\t\t\t cargarCombo5();\n\t\t else\n\t\t\t comboUnidad5.disabled = true;\n }\n else \n\n\t\tif (combo == 5) {\n\n deshabilitarResto(6);\n if ( get( 'frmDatos.comboUnidad5', 'T' ) != '' ) \n\t\t\t cargarCombo6();\n\t\t else\n\t\t\t comboUnidad6.disabled = true;\n\n }\n else \n\n\t\tif (combo == 6) {\n\n deshabilitarResto(7);\n if ( get( 'frmDatos.comboUnidad6', 'T' ) != '' ) \n\t\t\t cargarCombo7();\n\t\t else\n\t\t\t comboUnidad7.disabled = true;\n\n }\n else \n\n\t\tif (combo == 7) {\n\n deshabilitarResto(8);\n if ( get( 'frmDatos.comboUnidad7', 'T' ) != '' ) \n\t\t\t cargarCombo8();\n\t\t else\n\t\t\t comboUnidad8.disabled = true;\n }\n else \n\n\t\tif (combo == 8) {\n\n deshabilitarResto(9);\n if ( get( 'frmDatos.comboUnidad8', 'T' ) != '' ) \n\t\t\t cargarCombo9();\n\t\t else\n\t\t\t comboUnidad9.disabled = true;\n\n }\n\n}",
"function add_items(){\n\tget_all_items.done(function(data){\n\t var items = \"<select name='select_item' class='add-item' >\";\n\t for(var i = 0; i < data.length; i++){\n\t\titems += \"<option class='item_option' value=\" +data[i].itemId +\">\";\n\t\titems += data[i].itemName;\n\t\titems += \"</option>\";\n\t }\n\t items += \"</select>\";\n\t $(\"#add_items\").append(items);\n\t items_new_busi = items;\n\t});\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to print out the stops based on the selected route, called by eventlistener | function printStops(){
InsertText("mainContent","");
let currentDropdownValue = document.getElementById("dropdown").value;
if (currentDropdownValue !== ""){ //check that a not default value is selected (otherwise leave blank)
//first, need the route id
let routeNum = 0;
Object.entries(routes).forEach(element => {
if (element[1].shortName === currentDropdownValue.split(" ")[0]){
routeNum = element[1].routeId;
}
});
console.log("routeNum",routeNum);
//then, need to get a list of the stops for that route
//updated to be flexible to out of order stops
let stopsOnRoute = [];
Object.entries(routeStops).forEach(routeStop => {
//found a stop on the route
if (routeStop[1].routeId === routeNum){
//find stop name and create stop to add to array
Object.entries(stops).forEach(stop => {
//found stop obj that matches id
if (parseInt(stop[0]) === routeStop[1].stopId){
//create stop object with id, name, and order # to add to array
stopsOnRoute.push({
id: routeStop[1].stopId,
name: stop[1].name,
order: routeStop[1].stopOrder
});
}
});
}
});
//sort by order and print
stopsOnRoute.sort(compareOrder);
stopsOnRoute.forEach(stop => {
concatText("mainContent", "Stop " + (stop.order) + ": " + stop.name);
});
}
} | [
"function showRoute(itiStructure, day) {\r\n\thideSightDetail();\r\n\tvar stopsArr = [];\r\n\tvar stops = itiStructure.stops;\r\n clearSight();\r\n setMarkers(itiStructure,day);\r\n\tif (day == 0) {\r\n\t\tfor (var i in stops) {\r\n\t\t\tfor (var p in stops[i])\r\n\t\t\t\tstopsArr.push(stops[i][p]);\r\n\t\t}\r\n\t} else { \r\n\t\tfor (var p in stops[day-1])\r\n\t\t\tstopsArr.push(stops[day-1][p]);\r\n\t}\r\n\t_showRoute(stopsArr);\r\n}",
"function getRoutes(){\n\n routeLayer.clearLayers();\n\n var travelOptions = r360.travelOptions();\n travelOptions.addSource(sourceMarker); \n travelOptions.setDate(date);\n travelOptions.setTime(time);\n travelOptions.setTravelType(autoComplete.getTravelType());\n travelOptions.setElevationEnabled(true);\n travelOptions.setWaitControl(waitControl);\n travelOptions.addTarget(targetMarker);\n\n r360.RouteService.getRoutes(travelOptions, function(routes) {\n\n var html = \n '<table class=\"table table-striped\" style=\"width: 100%\"> \\\n <thead>\\\n <tr>\\\n <th>Source</th>\\\n <th>Time</th>\\\n <th>Distance</th>\\\n <th>Target</th>\\\n </tr>\\\n </thead>';\n\n _.each(routes, function(route, index){\n\n currentRoute = route;\n r360.LeafletUtil.fadeIn(routeLayer, route, 500, \"travelDistance\", { color : elevationColors[index].strokeColor, haloColor : \"#ffffff\" });\n\n html +=\n '<tr style=\"margin-top:5px;\">\\\n <td class=\"routeModus routeModus'+index+'\"><img style=\"height: 25px;\" src=\"images/source'+index+'.png\"></td>\\\n <td>' + r360.Util.secondsToHoursAndMinutes(currentRoute.getTravelTime()) + '</td>\\\n <td>' + currentRoute.getDistance().toFixed(2) + ' km </td>\\\n <td class=\"routeModus routeModus'+index+'\"><img style=\"height: 25px;\" src=\"images/target.png\"></td>\\\n </tr>'\n });\n\n html += '</table>';\n\n targetMarker.bindPopup(html);\n targetMarker.openPopup();\n }, \n function(code, message){\n\n if ( 'travel-time-exceeded' == code ) \n alert(\"The travel time to the given target exceeds the server limit.\");\n if ( 'could-not-connect-point-to-network' == code ) \n alert(\"We could not connect the target point to the network.\");\n });\n }",
"function timeBusstop(index, param_lat, param_lng) {\n\tif (color[index] == 'red') {\n\t\tvar dist_busstop_ref = findDistance(param_lat, param_lng, red_lat_bst[0], red_lng_bst[0])\n\t\tvar dist_busstop = findDistance(param_lat, param_lng, red_lat_bst[bus_stp_idx[index]], red_lng_bst[bus_stp_idx[index]])\n\t\tvar length_busstop = red_lat_bst.length\n\t} else if (color[index] == 'yellow') {\n\t\tvar dist_busstop_ref = findDistance(param_lat, param_lng, yellow_lat_bst[0], yellow_lng_bst[0])\n\t\tvar dist_busstop = findDistance(param_lat, param_lng, yellow_lat_bst[bus_stp_idx[index]], yellow_lng_bst[bus_stp_idx[index]])\n\t\tvar length_busstop = yellow_lat_bst.length\n\t} else if (color[index] == 'blue') {\n\t\tvar dist_busstop_ref = findDistance(param_lat, param_lng, blue_lat_bst[0], blue_lng_bst[0])\n\t\tvar dist_busstop = findDistance(param_lat, param_lng, blue_lat_bst[bus_stp_idx[index]], blue_lng_bst[bus_stp_idx[index]])\n\t\tvar length_busstop = blue_lat_bst.length\n\t} else if (color[index] == 'orange') {\n\t\tvar dist_busstop_ref = findDistance(param_lat, param_lng, orange_lat_bst[0], orange_lng_bst[0])\n\t\tvar dist_busstop = findDistance(param_lat, param_lng, orange_lat_bst[bus_stp_idx[index]], orange_lng_bst[bus_stp_idx[index]])\n\t\tvar length_busstop = orange_lat_bst.length\n\t}\n\n\tif (bus_stp_idx[index] == 0) {\n\t\tif (dist_busstop < 0.080) {\n\t\t\ttime_busstop[index][bus_stp_idx[index]] = tme[index]\n\t\t\t// console.log(time_busstop)\n\t\t} else {\n\t\t\tqueryDB2(index)\n\t\t\tbus_stp_idx[index] = bus_stp_idx[index] + 1\n\t\t}\n\t} else if (bus_stp_idx[index] == 12 && color[index] == 'red') {\n\t\tbus_stp_idx[index] = 16;\n\t} else {\n\t\tif (dist_busstop < 0.080) {\n\t\t\ttime_busstop[index][bus_stp_idx[index]] = tme[index]\n\t\t\tqueryDB3(index, bus_stp_idx[index])\n\t\t\t// console.log(time_busstop)\n\t\t\tbus_stp_idx[index] = bus_stp_idx[index] + 1\n\t\t}\n\t\t if (dist_busstop_ref < 0.080 && bus_stp_idx[index] != 0 && bus_stp_idx[index] != (length_busstop - 1)) {\n\t\t\ttime_busstop[index] = []\n\t\t\tbus_stp_idx[index] = 0\n\t\t}\n\t}\n}",
"function displayRoute() {\r\n clearOverlays();\r\n var start\r\n var end\r\n if (inputLocation == \"\") { start = currentLocation; end = currentCafeLocation; }\r\n else { start = inputLocation; end = currentCafeLocation; }\r\n\r\n var directionsDisplay = new google.maps.DirectionsRenderer();// also, constructor can get \"DirectionsRendererOptions\" object\r\n directionsDisplay.setMap(map); // map should be already initialized.\r\n\r\n var request = { origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING };\r\n var directionsService = new google.maps.DirectionsService();\r\n directionsService.route(request, function (response, status) {\r\n if (status == google.maps.DirectionsStatus.OK) {\r\n directionsDisplay.setDirections(response);\r\n }\r\n });\r\n markersArray.push(directionsDisplay);\r\n}",
"function createWaypoints(result) {\n\n // turn overview path of route into polyline\n var pathPolyline = new google.maps.Polyline({\n path: result.routes[0].overview_path\n });\n\n // get points at intervals of 85% of range along overview path of route\n var points = pathPolyline.GetPointsAtDistance(0.85 * range);\n\n // iterate over these points\n for (var i = 0, n = points.length; i < n; i++) {\n\n // find the closest charging station to that point\n var closeStation = getClosestStation(points[i]);\n\n // create waypoint at that station\n var newWaypoint = {\n location: closeStation.latlng,\n stopover: true\n };\n\n // add it to the waypoints array\n waypoints.push(newWaypoint);\n\n // add station info to station stops array\n stationStops.push(closeStation);\n\n // create invisible marker\n var marker = new google.maps.Marker({\n position: closeStation.latlng,\n map: map,\n icon: 'img/invisible.png',\n zIndex: 3,\n });\n\n // add to markers array\n markers.push(marker);\n }\n}",
"function calcRoute() {\n\t// Prepare the API call\n\tvar start = start_location.geometry.location;\n\tvar end = end_location.geometry.location;\n\tvar request = {\n\t\torigin: start,\n\t\tdestination: end,\n\t\ttravelMode: 'DRIVING'\n\t};\n\n\t// Call Google Maps API\n\tdirectionsService.route(request, function (result, status) {\n\t\tconsole.log(result);\n\t\tif (status == 'OK') {\n\t\t\t// Update the map to show the route\n\t\t\tdirectionsDisplay.setDirections(result);\n\n\t\t\t// List out the roads that the route includes\n\t\t\tvar routes = result.routes;\n\n\t\t\tdocument.getElementById(\"routeslist\").innerHTML = '';\n\t\t\tfor (var i = 0; i < routes[0].legs[0].steps.length; i++) {\n\t\t\t\tvar routePath = routes[0].legs[0].steps[i].path;\n\t\t\t\tvar road_location = routePath[Math.floor(routePath.length / 2)];\n\t\t\t\tvar duration = routes[0].legs[0].steps[i].duration.value;\n\t\t\t\tvar distance = routes[0].legs[0].steps[i].distance.value;\n\n\t\t\t\t// speed in miles per hour\n\t\t\t\tvar speed = distance * 0.000621371 / (duration / 3600);\n\n\t\t\t\t\n\t\t\t\t//console.log(\"Speed: \" + speed);\n\n\t\t\t\tspeed = Math.max(20, Math.round(speed/10) * 10);\n\n\t\t\t\t//console.log(\"New Speed: \" + speed);\n\t\t\t\tvar polyline = routes[0].legs[0].steps[i].polyline;\n\n\t\t\t\tprocessStep(road_location, duration, distance, speed, routePath, polyline);\n\t\t\t}\n\t\t}\n\n\n\t});\n}",
"function drawRoute(map, route, color) {\n for (var i = 0; i < route.length; i++) {\n stop = route[i][0];\n var edge = [];\n edge.push(stop.coords);\n\n /* loop to handle forks */\n for (var j = 0; j < route[i][1].length; j++) {\n edge.push(route[i][1][j].coords)\n var path = new google.maps.Polyline({\n path: edge,\n geodesic: true,\n strokeColor: color,\n strokeOpacity: 1.0,\n strokeWeight: 2\n });\n path.setMap(map);\n edge.pop();\n }\n }\n}",
"function drawRoute(id, route){\n\n\tfor(var i=0; i<route.length-1; i++){\n\n\t\tdrawSegment(id, route[i], route[i+1]);\n\t}\n}",
"function drivingRoute(start, end){\n\t\tdirectionsDisplay = new google.maps.DirectionsRenderer();\n\t\tvar myOptions = {\n\t\t zoom:5,\n\t\t mapTypeId: google.maps.MapTypeId.ROADMAP,\n\t\t} \n\t\tmap = new google.maps.Map(document.getElementById(\"map_canvas\"), myOptions);\n\t\tdirectionsDisplay.setMap(map);\n\t\tvar directionsService = new google.maps.DirectionsService();\n\t\t\n\t\tvar request = {\n\t\t\t\torigin:start,\n\t\t\t\tdestination:end,\n\t\t\t\twaypoints: waypts,\n\t\t\t optimizeWaypoints: true,\n\t\t\t\ttravelMode: google.maps.DirectionsTravelMode.DRIVING\n\t\t\t};\n\t\t// calculating distance from google maps (Driving directions)\n\t\t\t\tdirectionsService.route(request, function(response, status) {\n\t\t\t\tif (status == google.maps.DirectionsStatus.OK) {\n\t\t\t\t\tdirectionsDisplay.setDirections(response);\n\t\t\t\t var route = response.routes[0];\n\t\t\t\t \n\t\t\t\t var summaryPanel = document.getElementById('1234');\n\t\t\t\t summaryPanel.innerHTML = ''; // For each route, display summary information.\n\t\t\t\t for (var i = 0; i < route.legs.length; i++) {\n\t\t\t\t var routeSegment = i + 1;\n\t\t\t\t summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +\n\t\t\t\t '</b><br>';\n\t\t\t\t summaryPanel.innerHTML += route.legs[i].start_address + ' to ';\n\t\t\t\t summaryPanel.innerHTML += route.legs[i].end_address + '<br>';\n\t\t\t\t summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';\n\t\t\t\t if(i==0)\n\t\t\t\t \t {\n\t\t\t\t \t document.getElementById(\"distance\").value=route.legs[i].distance.value / 1000;\n\t\t\t\t \t document.getElementById(\"mySubmit\").disabled = false;\n\t\t\t\t \t }\n\t\t\t\t else\n\t\t\t\t \t dist=dist+route.legs[i].distance.value / 1000;\n\t\t\t\t }\n\t\t\t\t document.getElementById(\"distance1\").value=dist;\t\t\t\t \n\t\t\t\t }});\n\t}",
"function onPlaceChanged() {\n\n\tconsole.log(\"Start location: \" + start_location + \", destination: \" + end_location);\n\tif (start_location && end_location) {\n\t\tconsole.log(\"Calculating route between \" + start_location.name + \" and \" + end_location.name);\n\t\tcalcRoute();\n\t}\n}",
"function addRouteMarkers() {\n\n // Add start location\n map.addMarker({\n lat: startLocation[0],\n lng: startLocation[1],\n title: \"Start Location: \" + startLocation[2],\n icon: \"images/start.png\"\n });\n\n // Add end location\n if (endLocation != startLocation) {\n map.addMarker({\n lat: endLocation[0],\n lng: endLocation[1],\n title: \"End Location: \" + endLocation[2],\n icon: \"images/end.png\"\n });\n }\n\n // Add all path markers\n for (var i = 0; i < path.length; i++) {\n map.addMarker({\n lat: path[i][0],\n lng: path[i][1],\n title: path[i][2],\n icon: markers[i],\n infoWindow: {\n content: \"<p>\" + path[i][2] + \"</p><p><input onclick='search([\" + path[i][0] + \",\" + path[i][1] + \"], \\\"\\\")'\" + \" type='button' value='Search Nearby'></p>\" + \n \"<span id='marker' class='delete' onclick='cancelStopMarker(\\\"\" + path[i][2] + \"\\\")'><img src='images/cancel.png' alt='cancel' /></span>\"\n }\n });\n }\n\n fitMap();\n}",
"function sendBusStopList() {\n pebbleHelpers.getLocation(function (error, position) {\n if (error) {\n console.log('location error (' + error.code + '): ' + error.message);\n sendErrorCode(constants.ERROR_CODES.LOCATION_ERROR);\n } else {\n\n var positionArray = [position.coords.latitude, position.coords.longitude];\n\n var nearbyBusStops = busStops.getNearbyBusStops(positionArray);\n\n // iterates through the nearby bus stops and populates two arrays of descriptions and\n // stop id\n var descriptions = [];\n var stopIds = [];\n for (var i = 0; i < nearbyBusStops.length; i++) {\n var busStop = nearbyBusStops[i];\n descriptions.push(\n busStop[busStops.CLOSEST_BUS_STOP_KEYS.description] + constants.MESSAGE_DELIMITER +\n busStop[busStops.CLOSEST_BUS_STOP_KEYS.road] + constants.MESSAGE_DELIMITER +\n busStop[busStops.CLOSEST_BUS_STOP_KEYS.stopId]);\n\n stopIds.push(busStop[busStops.CLOSEST_BUS_STOP_KEYS.stopId]);\n }\n\n // sends the message to the watch\n pebbleHelpers.sendMessageStream(\n constants.APP_MESSAGE_KEYS.KEY_BUS_STOP_LIST_START,\n constants.APP_MESSAGE_KEYS.KEY_BUS_STOP_LIST_VALUE,\n constants.APP_MESSAGE_KEYS.KEY_BUS_STOP_LIST_END,\n descriptions\n );\n }\n })\n}",
"function printMoves(rover){\n\n for (var i = 0 ; i < rover.travelLog.length ; i++){\n console.log(\"COORDINATES \" + i +\": \" + rover.travelLog[i]);\n }\n console.log(\"COORDINATES \" + i +\": \" + rover.x + \",\" + rover.y);\n}",
"function calculateAndDisplayRoute(directionsService, directionsDisplay, distance) {\n directionsService.route({\n origin: startValue,\n destination: endValue,\n travelMode: 'DRIVING',\n }, function(response, status) {\n // console.log(response);\n if (status === 'OK') {\n directionsDisplay.setDirections(response);\n\n } else {\n console.log(\"ERROR - \" + status);\n // window.alert('Directions request failed due to ' + status);\n }\n });\n\n distance.getDistanceMatrix({\n origins: [startValue],\n destinations: [endValue],\n travelMode: 'DRIVING',\n }, function(response, status) {\n console.log(response);\n var length = (response.rows[0].elements[0].duration.value);\n\n tripLength = length * 1000;\n console.log(response.rows[0].elements[0].duration.text);\n // console.log(msLength);\n\n });\n // Get current weather there\n getCurrentWeather();\n} // End of function to calculate directions and distance",
"function showDirectionLineAndDetails(originCoordinates, destinationCoordinates, originName, destName, mode, name) {\n\n\tvar directionQuery = generateDirectionQuery(mode, \n\t\t\t\t\t\toriginCoordinates[0], originCoordinates[1],\n\t\t\t\t\t\tdestinationCoordinates[0], destinationCoordinates[1]);\n\t\n\tvar layerName = 'directions-' + name;\n\tstepsData = {};\n\t$('.instruction-header-cycling').remove();\n\t$('.instruction-header-walking').remove();\n\t$('.instruction').remove();\n\n\n\t$.getJSON(directionQuery, function(data) {\n\t\t\n\t\tdirections = data;\n\n\t\tif (data.code == \"NoRoute\") {\n\t\t\talert(\"No route found!\");\n\t\t\tstepsData = {};\n\t\t\tlinesDrawn = 0;\n\n\t\t\tif ( !(map.getSource('directions-cycling1') === undefined) ) {\n\t\t\t\tmap.removeSource('directions-cycling1');\n\t\t\t\tmap.removeLayer('directions-cycling1');\n\t\t\t}\n\n\t\t\tif ( !(map.getSource('directions-walking1') === undefined) ) {\n\t\t\t\tmap.removeSource('directions-walking1');\n\t\t\t\tmap.removeLayer('directions-walking1');\n\t\t\t}\n\n\t\t\tif ( !(map.getSource('directions-walking2') === undefined) ) {\n\t\t\t\tmap.removeSource('directions-walking2');\n\t\t\t\tmap.removeLayer('directions-walking2');\n\t\t\t}\n\n\t\t\t// Remove highlighted markers if they exist\n\t\t\tif ( !(map.getSource('stations') === undefined) ) {\n\t\t\t\tmap.removeSource('stations');\n\t\t\t\tmap.removeLayer('stations');\n\t\t\t}\n\n\t\t\t\t\t//remove destination marker if it exists\n\n\t\t\tif ( !(map.getSource('destination') === undefined) ) {\n\t\t\t\tmap.removeSource('destination');\n\t\t\t\tmap.removeLayer('destination');\n\t\t\t}\n\n\t\t\tif ($('.instruction-container').css('right', '0%'))\n\t\t\t\t$('.instruction-container').animate({right: '-35%'}, 'slow');\n\n\t\t\t$('.instruction-header-cycling').remove();\n\t\t\t$('.instruction-header-walking').remove();\n\t\t\t$('.instruction').remove();\n\n\n\t\t\treturn;\n\t\t}\n\n\t\tlinesDrawn++;\n\n\t\tvar directionsLineFeatureCollection = \n\t\t\t\t{\"type\": \"FeatureCollection\",\n\t\t\t\t\"features\": [\n\t\t\t\t\t{\"type\": \"Feature\",\n\t\t\t\t\t'properties': {}}\n\t\t\t\t\t]\n\t\t\t\t};\n\n\t\tdirectionsLineFeatureCollection.features[0].geometry = directions.routes[0].geometry;\t\t\n\n\t\t\t\t/* Remove direction lines if they exist */\n\t\tif ( !(map.getSource(layerName) === undefined) ) {\n\t\t\tmap.removeSource(layerName);\n\t\t\tmap.removeLayer(layerName);\n\t\t}\n\n\t\tmap.addSource(layerName, {\n\t\t\t'type': 'geojson',\n\t\t\t'data': directionsLineFeatureCollection\n\t\t});\n\n\t\tmap.addLayer({\n\t\t\t'id': layerName,\n\t\t\t'type': 'line',\n\t\t\t'source': layerName,\n\t \"layout\": {\n\t \"line-join\": \"round\",\n\t \"line-cap\": \"round\",\n\t \"visibility\": \"none\"\n\t },\n\t \"paint\": {\n\t \"line-color\": mode != 'walking' ? \"#2b8cbe\" : \"#fd8d3c\",\n\t \"line-width\": mode != 'walking' ? 4 : 5,\n\t \"line-opacity\": .85,//i != 1 ? .85 : .85\n\t \n\t }\n\t\t}, 'stations');\n\n\t\t// We make the layers visible only if the three directions were found\n\t\tif (linesDrawn == 3) {\n\t\t\tconsole.log(linesDrawn);\n\n\t\t\tif ( !(map.getSource('stations') === undefined) ) {\n\t\t\t\tmap.removeSource('stations');\n\t\t\t\tmap.removeLayer('stations');\n\t\t\t}\n\n\t\t\tmap.addSource('stations',{\n\t\t\t\t'type': 'geojson',\n\t\t\t\t'data': featureCollection\n\t\t\t});\n\n\t\t\tmap.addLayer({\n\t\t\t\t'id':'stations',\n\t\t\t\t'type': 'symbol',\n\t\t\t\t'source': 'stations',\n\t\t\t\t'layout': {\n\t\t\t\t \t\"icon-image\": 'mark-green',\n\t\t\t\t\t\"icon-size\" : 1.5,\n\t\t\t\t\t\"text-field\": \"{availableBikes}\",\n\t\t\t\t \"text-font\": [\"Open Sans Semibold\", \"Arial Unicode MS Bold\"],\n\t\t\t\t \"text-size\" : 10, \n\t\t\t\t\t\"text-anchor\": \"bottom\"\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t//Destination markers\t \n\t\t\tfeatureCollectiond = {\n\t\t\t\t\"type\": \"FeatureCollection\",\n\t\t\t\t\"features\": [] };\n\n\t\t\tvar feature = {\n\t\t\t\t\"type\": \"Feature\",\n\t\t\t\t\"geometry\": {\n\t\t\t\t\"type\": \"Point\",\n\t\t\t\t\"coordinates\": destCoordinates\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\tfeatureCollectiond.features.push(feature);\n\n\t\t\tif ( !(map.getSource('destination') === undefined) ) {\n\t\t\t\tmap.removeSource('destination');\n\t\t\t\tmap.removeLayer('destination');\n\t\t\t}\n\n\t\t\tmap.addSource('destination',{\n\t\t\t\t'type': 'geojson',\n\t\t\t\t'data': featureCollectiond\n\t\t\t});\n\n\t\t\tmap.addLayer({\n\t\t\t\t'id':'destination',\n\t\t\t\t'type': 'symbol',\n\t\t\t\t'source': 'destination',\n\t\t\t\t'layout': {\n\t\t\t\t \t\"icon-image\": 'marker-pink',\n\t\t\t\t\t\"icon-size\" : 2,\n\t\t\t\t\t\n\t\t\t\t}, \n\t\t\t});\n\n\t\t\tif (map.getLayoutProperty('directions-cycling1', 'visibility') == 'none')\n\t\t\t\tmap.setLayoutProperty('directions-cycling1', 'visibility', 'visible');\n\t\t\tif (map.getLayoutProperty('directions-walking1', 'visibility') == 'none')\n\t\t\t\tmap.setLayoutProperty('directions-walking1', 'visibility', 'visible');\n\t\t\tif (map.getLayoutProperty('directions-walking2', 'visibility') == 'none')\n\t\t\t\tmap.setLayoutProperty('directions-walking2', 'visibility', 'visible');\n\n\t\t\tlinesDrawn = 0;\n\t\t}\n\t\t// Get steps from server's JSON response\n\t\tstepsData[layerName] = {};\n\t\tstepsInLayer = stepsData[layerName];\n\t\tstepsInLayer['instructions'] = [];\n\t\tstepsInLayer['duration'] = [];\n\t\tstepsInLayer['distance'] = [];\n\t\tstepsInLayer['totalDuration'] = 0;\n\t\tstepsInLayer['totalDurationUnit'] = '';\n\t\tstepsInLayer['totalDistance'] = 0;\n\t\tstepsInLayer['totalDistanceUnit'] = '';\n\t\tstepsInLayer['originName'] = originName;\n\t\tstepsInLayer['destName'] = destName; \n\n\t\tsteps = directions.routes[0].legs[0].steps;\n\n\t\t// total in minutes\n\t\ttotalDuration = directions.routes[0].duration;\n\t\ttotalDistance = directions.routes[0].distance;\n\n\t\ttotalDurationInMinutes = Math.ceil(totalDuration / 60);\n\t\ttotalDistanceInKm = (totalDistance / 1000).toFixed(1);\n\n\t\tif (totalDuration > 59) {\n\t\t\tstepsInLayer.totalDuration = totalDurationInMinutes;\n\t\t\tstepsInLayer.totalDurationUnit = 'minutes';\n\t\t}\n\t\telse {\n\t\t\tstepsInLayer.totalDuration = totalDuration;\n\t\t\tstepsInLayer.totalDurationUnit = 'seconds';\n\t\t}\n\n\t\tif (totalDistance > 999) {\n\t\t\tstepsInLayer.totalDistance = totalDistanceInKm;\n\t\t\tstepsInLayer.totalDistanceUnit = 'kilometers';\n\t\t}\n\t\telse {\n\t\t\tstepsInLayer.totalDistance = totalDistance;\n\t\t\tstepsInLayer.totalDistanceUnit = 'meters';\n\t\t}\n\n\n\t\t// Add instructions, duration, and distance for each layer\n\t\tsteps.forEach( function(step) {\n\t\t\tstepsInLayer['instructions'].push(step.maneuver.instruction);\n\t\t\tstepsInLayer['duration'].push(step.duration);\n\t\t\tstepsInLayer['distance'].push(step.distance);\n\t\t});\n\n\n\t\tif (Object.keys(stepsData).length == 3) {\n\t\t\t// Show steps in this order\n\t\t\tvar layerNames = ['directions-walking1', 'directions-cycling1', 'directions-walking2'];\n\n\t\t\tvar instructionsContainer = $('.instruction-container');\n\n\t\t\tlayerNames.forEach( function(layerName) {\n\n\t\t\t\tcurrentSteps = stepsData[layerName];\n\t\t\t\tcurrMode = layerName == 'directions-cycling1' ? 'Bike' : 'Walk';\n\n\t\t\t\theaderContent = currMode + \" \" + \"from \" + currentSteps.originName + \" to \" + currentSteps.destName\n\t\t\t\t\t\t\t\t+ \"<br><br>\" + currentSteps.totalDistance + \" \" + currentSteps.totalDistanceUnit + \" \" \n\t\t\t\t\t\t\t\t+ currentSteps.totalDuration + \" \" + currentSteps.totalDurationUnit;\n\n\t\t\t\tif (layerName == 'directions-cycling1') {\n\n\t\t\t\t\theader = \"<div class='instruction-header-cycling'>\"\n\t\t\t\t\t\t\t+ headerContent\n\t\t\t\t\t\t\t+ \"</div>\";\n\t\t\t\t\tinstructionsContainer.append(header);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\theader = \"<div class='instruction-header-walking'>\"\n\t\t\t\t\t\t\t+ headerContent\n\t\t\t\t\t\t\t+ \"</div>\";\n\t\t\t\t\tinstructionsContainer.append(header);\n\t\t\t\t}\n\n\t\t\t\tinstructionsArray = currentSteps.instructions;\n\n\t\t\t\tinstructionsArray.forEach( function(instr, i) {\n\n\t\t\t\t\tdist = (currentSteps.distance[i] >= 1000 ? (currentSteps.distance[i] / 1000).toFixed(2) : currentSteps.distance[i]);\n\t\t\t\t\tdistUnit = (currentSteps.distance[i] >= 1000 ? \"kilometers\" : \"meters\");\n\t\t\t\t\tduration = currentSteps.duration[i] >= 60 ? Math.ceil(currentSteps.duration[i] / 60) : currentSteps.duration[i];\n\t\t\t\t\tdurationUnit = currentSteps.duration[i] >= 60 ? \"minutes\" : \"seconds\";\n\n\t\t\t\t\tinstruction = \"<div class='instruction'>\" + instr + \"<br/><span class='duration-and-distance'>\" \n\t\t\t\t\t\t\t\t\t\t\t+ (duration == 0 ? \"\" : duration) + \" \" + (duration == 0 ? \"\" : durationUnit) + \" \"\n\t\t\t\t\t\t\t\t\t\t\t+ (dist == 0 ? \"\" : dist) + \" \" + (dist == 0 ? \"\" : distUnit);\n\t\t\t\t\t\t\t\t\t\t\t+ \"</span>\"\n\t\t\t\t\t\t\t\t\t\t\t+ \"</div>\";\n\t\t\t\t\tinstructionsContainer.append(instruction);\n\n\t\t\t\t});\n\n\t\t\t});\n\n\t\t\t// Add a blank div in the bottom so as instructions not obscured by Mapbox copyright\n\t\t\tinstructionsContainer.append(\"<div class='instruction'></div>\");\n\n\t\t\t// animate instructions\n\t\t\t$('.instruction-container').animate({right: '0%'}, 'slow');\n\t\t\t$('.exit-button').css(\"visibility\", \"visible\");\n\t\t\tmap.flyTo({\n\t\t\t\tcenter: originCoordinates,\n\t\t\t\tzoom: 15,\n\t\t\t\tspeed: 0.7\n\t\t\t});\n\t\t}\n\n\n\t});\n\n}",
"function loadDirections(modeID, routeID) {\n\tdisableSubmit();\n\tresetOptions(selectObjDirection);\n\t\n\tdisableSelector(selectObjDirection);\n\t\n\tallStops = [];\n\tallStopsTemp = [];\n\tallDirections = [];\n\t\n\t// If 'Select' is selected then reset everything below.\n\tif(modeID == -1 || routeID == -1) {\n\t} else {\n\t\tconsole.log('Route is: ' + routeID);\n\t\txhr(stopsOnALineURL(modeID, routeID), stopsOnALineCallback);\n \n\t}\n}",
"function drawHops($hopsArray, $placement) {\n if($placement === \"map\"){ //draw Hops on the map\n for (var key in $hopsArray) {\n for (var hop in $hopsArray[key]) {\n //make hop times string\n var times = \"\";\n for(var time in $hopsArray[key][hop]){\n if(!isNaN($hopsArray[key][hop][time])){\n times += \"<li>\"+$hopsArray[key][hop][time]+\"ms</li>\";\n }\n }\n\n //create hopData with hop response times\n var hopData = {\n key: key,\n timesString: times\n }\n\n // draw marker into the map\n drawMarker(hop, null, hopData);\n }\n }\n\n //create a path instance with the generated path from markers to the map\n routePath = new L.Polyline(pathLocation, {\n color: '#2980b9', //belize-hole\n weight: 8,\n opacity: 1,\n smoothFactor: 1\n });\n\n //add route path instace to the map\n routePath.addTo(mainMap);\n\n }else if($placement === \"panel\"){ //draw hops on results panel\n //remove loading state in results panel content\n $(\"#vtr-results-panel .vtr-results-panel__search-image\").remove(); //loader image\n $(\"#vtr-results-panel p\").remove(); // loader paragraph\n\n //loop trough the hops array and add them to the results panel\n for (var key in $hopsArray) {\n for (var hop in $hopsArray[key]) {\n \n //get country short from ip2 location / add marker to map to use in flag\n var countryFlag = getHostData(hop, \"country_short\");\n\n //make hop times list\n var times = \"\";\n for(var time in $hopsArray[key][hop]){\n if(!isNaN($hopsArray[key][hop][time])){\n times += \"<li>\"+$hopsArray[key][hop][time]+\"ms</li>\";\n }\n }\n\n //append to the map the result\n $(\"#vtr-results-panel .vtr-results-panel__list\").append(\n \"<li>\\\n <div class='vtr-results-panel__list__hop-number'>\\\n #\"+key+\"\\\n </div>\\\n <div class='vtr-results-panel__list__hop-info'>\\\n <div class='vtr-results-panel__list__hop-info__host'>\\\n \"+hop+\"\\\n </div>\\\n <ul class='vtr-results-panel__list__hop-info__time'>\\\n \"+times+\"\\\n </ul>\\\n </div>\\\n <div class='vtr-results-panel__list__hop-country-flag' style='background-image: url(dist/images/country_flags/64/\"+countryFlag+\"_64.png)'></div>\\\n </li>\"\n );\n }\n }\n }\n}",
"function additionalPass(result, status) {\n\n // if Maps returns a valid response\n if (status == google.maps.DirectionsStatus.OK) {\n \n // initialize variable for checking if route needs any changes\n var needsCorrection = false;\n\n // iterate over legs of route\n for (var i = 0, n = result.routes[0].legs.length; i < n; i++) {\n\n var legLength = result.routes[0].legs[i].distance.value;\n\n // if leg is longer than range\n if (legLength > range) {\n\n // create new polyline for this leg\n var polyline = new google.maps.Polyline({ path: [] });\n\n // iterate over steps of the leg\n for (var j = 0, m = result.routes[0].legs[i].steps.length; j < m; j++) {\n\n // iterate over segments of step\n for (var k = 0, l = result.routes[0].legs[i].steps[j].path.length; k < l; k++) {\n\n // add segment to polyline\n polyline.getPath().push(result.routes[0].legs[i].steps[j].path[k]);\n }\n }\n \n // find point 75% of range along this line\n var nextPoint = polyline.GetPointAtDistance(0.75 * range);\n\n // get closest station to halfway point\n var newStation = getClosestStation(nextPoint);\n \n // create waypoint at that station\n var newWaypoint = {\n location: newStation.latlng,\n stopover: true\n }\n\n // add to waypoints array\n waypoints.push(newWaypoint);\n\n // add station to station stops array\n stationStops.push(newStation);\n\n // create invisible marker\n var marker = new google.maps.Marker({\n position: stationStops[i].latlng,\n map: map,\n icon: 'img/invisible.png',\n zIndex: 3,\n });\n\n // add to markers array\n markers.push(marker);\n\n // indicate that route needs correction\n needsCorrection = true;\n }\n }\n\n // if route needs correction\n if (needsCorrection == true) {\n\n // create new directions request\n var nextRequest = {\n origin: origin,\n destination: destination,\n travelMode: google.maps.TravelMode.DRIVING,\n unitSystem: google.maps.UnitSystem.IMPERIAL,\n waypoints: waypoints,\n optimizeWaypoints: true\n }\n\n // send new directions request\n directionsService.route(nextRequest, function(nextResult, nextStatus) {\n\n // try again\n additionalPass(nextResult, nextStatus)\n });\n }\n\n // otherwise our route is fine as is\n else {\n\n // check for legs longer than 85% of range\n warnLong(result);\n\n // create a clickable info window for each waypoint\n createInfoWindows();\n\n // display route\n directionsDisplay.setDirections(result);\n }\n }\n \n // handle errors returned by the Maps API\n else {\n \n handleErrors(status);\n }\n}",
"function getBound(departureStopName, arrivalStopName) {\n\tvar stationsDict = {\n\t\t\"San Francisco Caltrain\": 0,\n\t\t\"22nd St Caltrain\": 1,\n\t\t\"Bayshore Caltrain\": 2,\n\t\t\"So. San Francisco Caltrain Station\": 3,\n\t\t\"San Bruno Caltrain\": 4,\n\t\t\"Millbrae Caltrain\": 5,\n\t\t\"Broadway Caltrain\": 6,\n\t\t\"Burlingame Caltrain\": 7,\n\t\t\"San Mateo Caltrain\": 8,\n\t\t\"Hayward Park Caltrain\": 9,\n\t\t\"Hillsdale Caltrain\": 10,\n\t\t\"Belmont Caltrain\": 11,\n\t\t\"San Carlos Caltrain\": 12,\n\t\t\"Redwood City Caltrain\": 13,\n\t\t\"Atherton Caltrain\": 14,\n\t\t\"Menlo Park Caltrain\": 15,\n\t\t\"Palo Alto Caltrain\": 16,\n\t\t\"California Ave Caltrain\": 17,\n\t\t\"San Antonio Caltrain\": 18,\n\t\t\"Mt View Caltrain\": 19,\n\t\t\"Sunnyvale Caltrain\": 20,\n\t\t\"Lawrence Caltrain\": 21,\n\t\t\"Santa Clara Caltrain\": 22,\n\t\t\"College Park Caltrain\": 23,\n\t\t\"San Jose Diridon Caltrain\": 24,\n\t\t\"Tamien Caltrain\": 25,\n\t\t\"Capitol Caltrain\": 26,\n\t\t\"Blossom Hill Caltrain\": 27,\n\t\t\"Morgan Hill Caltrain\":28,\n\t\t\"San Martin Caltrain\": 29,\n\t\t\"Gilroy Caltrain\":30\n\t}\n\tif (stationsDict[departureStopName] < stationsDict[arrivalStopName]) {\n\t\treturn \"SB\";\n\t}else if (stationsDict[departureStopName] > stationsDict[arrivalStopName]) {\n\t\treturn \"NB\";\n\t}else {\n\t\t// TODO: returning SB for now so the app doesn't break\n\t\t// Think what we could do is have another template under main.html, could set a \n\t\t// Session var here to display a select again template\n\t\t// Or simply display whatever the welcoming template is?\n\t\t// Am I abusing from Session vars though? \n\t\t// Android app has no 'welcome'view, just shows trips directly\n\t\t// Does have a view for a 'select again' template\n\t\treturn \"SB\";\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the zerobased bit number of the highestorder bit with the given value in the given buffer. If the buffer consists entirely of the other bit value, then this returns `1`. | function highOrder(bit, buffer) {
var length = buffer.length;
var fullyWrongByte = (bit ^ 1) * 0xff; // the other-bit extended to a full byte
while (length > 0 && buffer[length - 1] === fullyWrongByte) {
length--;
}
if (length === 0) {
// Degenerate case. The buffer consists entirely of ~bit.
return -1;
}
var byteToCheck = buffer[length - 1];
var result = length * 8 - 1;
for (var i = 7; i > 0; i--) {
if ((byteToCheck >> i & 1) === bit) {
break;
}
result--;
}
return result;
} | [
"function maxBit(word) {\n if (word == null)\n return -1;\n word = word | 0; // This is not just a JIT hint: clears the high bits\n var mask = singleBitMask(31);\n var result = 31;\n while (result >= 0 && ((mask & word) !== mask)) {\n mask >>>= 1;\n result--;\n }\n return result;\n }",
"max() {\n for(let i = this.array.length - 1; i >= 0; i--){\n const bits = this.array[i];\n if (bits) {\n return BitSet.highBit(bits) + i * bitsPerWord;\n }\n }\n return 0;\n }",
"function secondRightmostZeroBit(n) {\n\treturn 2 ** (Number([...n.toString(2)].reverse().map((el, i) => {\n\t\tif (Number(el) === 0) {\n\t\t\treturn i;\n\t\t}\n\t}).join(\"\")[1]));\n\n\t// return ~(n |= -~n) & -~n;\n}",
"function minBit(word) {\n if (word == null)\n return -1;\n word = word | 0; // This is not just a JIT hint: clears the high bits\n var mask = singleBitMask(0);\n var result = 0;\n while (result < 32 && ((mask & word) !== mask)) {\n mask <<= 1;\n result++;\n }\n if (result > 31)\n result = -1;\n return result;\n }",
"function getByteN(value, n) {\n return ((value >> (8 * n)) & 0b11111111);\n}",
"function decode(value)\n{\n var x = 0;\n while (value) {\n if (phonemes.indexOf(value.slice(0,2)) >= 0) {\n var bit = value.slice(0,2);\n value = value.slice(2);\n }\n else {\n var bit = value.slice(0,3);\n value = value.slice(3); \n }\n x = x * phonemes.length + phonemes.indexOf(bit);\n }\n return x;\n}",
"function getIPCount(bitCount) {\r\n\r\n valor = 32 - bitCount;\r\n return Math.pow(2, valor);\r\n\r\n}",
"function limitBitsNumber(value) {\r\n\r\n if (value > 32) {\r\n\r\n return Math.floor(value / 10);\r\n } else {\r\n return value;\r\n }\r\n}",
"function getHighestZIndex()\n{\n retVal = 0;\n\t\n\tvar tagArray = [\"DIV\",\"IFRAME\",\"IMG\",\"A\",\"UL\",\"LI\",\"OBJECT\"];\n\t\n\tfor ( y = 0; y < tagArray.length; y++ )\n\t{\n\t\t\tvar curTag = tagArray[y];\n\t\t\tvar a = document.getElementsByTagName(curTag);\n\t\t\tfor ( var z = 0; z < a.length; z++ )\n\t\t\t{\n\t\t\t\tvar i = xGetComputedStyle(a[z],\"z-index\",true);\n\t\t\t\tif (i)\n\t\t\t\t{\n\t\t\t\t\tif (i > retVal) { retVal = i; }\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t}\n\t\t\n return retVal;\n}",
"bitCount() {\n let result = 0;\n for(let i = 0; i < this.array.length; i++){\n result += BitSet.countBits(this.array[i]) // Assumes we never have bits set beyond the end\n ;\n }\n return result;\n }",
"function countTheBits(num) {\n\tlet numString;\n\tnumString = num.toString(2)\n\tlet result = 0;\n\tfor (let i = 0; i < numString.length; i++) {\n // console.log(numString[i])\n if(numString[i] == 1){\n result += 1\n }\n \n }\n\n\treturn result;\n}",
"function is0thSet(value) {\n return (value & 0b01);\n}",
"function getCutoffIndex(array, value) {\n for (var index = 0; index < array.length; ++index) {\n if (array[index] === value) {\n return index + 1;\n }\n }\n\n return 0;\n }",
"function getHighestPowerTwo (powerTwoArray, decimalNumber) {\n \n var highestPowerTwo;\n if(decimalNumber > 0){\n for (i=0;i<powerTwoArray.length; i++) {\n if (decimalNumber >= powerTwoArray[i]) {highestPowerTwo = powerTwoArray[i]}\n \n } \n return highestPowerTwo;\n }\n else return highestPowerTwo = 0;\n }",
"function inWord(bit) {\n return Math.floor((bit | 0) / 32);\n }",
"static bytes31(v) { return b(v, 31); }",
"function byteopsCbd(buf) {\r\n var t, d;\r\n var a, b;\r\n var r = new Array(384).fill(0);\r\n for (var i = 0; i < paramsN / 8; i++) {\r\n t = (byteopsLoad32(buf.slice(4 * i, buf.length)) >>> 0);\r\n d = ((t & 0x55555555) >>> 0);\r\n d = (d + ((((t >> 1) >>> 0) & 0x55555555) >>> 0) >>> 0);\r\n for (var j = 0; j < 8; j++) {\r\n a = int16((((d >> (4 * j + 0)) >>> 0) & 0x3) >>> 0);\r\n b = int16((((d >> (4 * j + paramsETA)) >>> 0) & 0x3) >>> 0);\r\n r[8 * i + j] = a - b;\r\n }\r\n }\r\n return r;\r\n}",
"function largestEvenNum(arr) {\n return arr.filter((x) => x % 2 === 0).reduce((a, b) => (a > b ? a : b));\n}",
"function determineBitfieldType(count) {\n\tif (count <= 8) {\n\t\treturn \"uint8\";\n\t} else if (count > 8 && count <= 16) {\n\t\treturn \"uint16\";\n\t} else if (count > 16 && count <= 32) {\n\t\treturn \"uint32\";\n\t} else if (count > 32 && count <= 64) {\n\t\treturn \"uint64\";\n\t} else {\n\t\tconsole.error(\"The number of bools is too damn high!\");\n\t}\n}",
"function getBitFromByte(num, mask) {\n return Boolean(num & mask)\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
SELECT `profile`.guid, f2.`status` AS followed_status, f2.blocked, `profile`.`username`, profile.`fullname`, profile.followers, profile.following, user_metrics.popularity, `profile`.`verified`, profile.is_private, profile.about, profile.domain, `profile`.image_url AS image_url, `profile`.allow_view_followers, `profile`.allow_view_followings FROM `profile` INNER JOIN `friends` ON `friends`.`guid1` = `profile`.`guid` AND `status` = ? AND profile.allow_view_me_followers_list = 1 LEFT JOIN user_metrics ON user_metrics.guid = profile.guid LEFT JOIN `friends` as f2 ON f2.guid1 = ? AND f2.guid2 = profile.guid WHERE `friends`.`guid2` = ? ORDER BY `username` ASC LIMIT 60"; Get followers of other person | function getUsersFollowers(fguid, guid, lastUsername) {
var query = "SELECT `profile`.guid, f2.`status` AS followed_status, f2.blocked, `profile`.`username`, profile.`fullname`, profile.followers, profile.following, user_metrics.popularity, `profile`.`verified`, profile.is_private, profile.about, profile.domain, `profile`.image_url AS image_url, `profile`.allow_view_followers, `profile`.allow_view_followings FROM `profile` INNER JOIN `friends` ON `friends`.`guid1` = `profile`.`guid` AND `status` = ? profile.allow_view_me_followers_list = 1 LEFT JOIN user_metrics ON user_metrics.guid = profile.guid LEFT JOIN `friends` as f2 ON f2.guid1 = ? AND f2.guid2 = profile.guid WHERE `friends`.`guid2` = ? ORDER BY `username` ASC LIMIT 60";
var parameters = [ Relationship.IsFollowing, guid, fguid];
if (isStringWithLength(lastUsername)) {
query = "SELECT `profile`.guid, f2.`status` AS followed_status, f2.blocked, `profile`.`username`, profile.`fullname`, profile.followers, profile.following, user_metrics.popularity, `profile`.`verified`, profile.is_private, profile.about, profile.domain, `profile`.image_url AS image_url, `profile`.allow_view_followers, `profile`.allow_view_followings FROM `profile` INNER JOIN `friends` ON `friends`.`guid1` = `profile`.`guid` AND `status` = ? profile.allow_view_me_followers_list = 1 LEFT JOIN user_metrics ON user_metrics.guid = profile.guid LEFT JOIN `friends` as f2 ON f2.guid1 = ? AND f2.guid2 = profile.guid WHERE `friends`.`guid2` = ? AND username > ? ORDER BY `username` ASC LIMIT 60";
parameters = [ Relationship.IsFollowing, guid, fguid, lastUsername];
}
/**
* Result contains friends info as ( guid, status, blocked, username, fullname
*/
connection.query({
sql : query,
values: parameters,
},
function (error, results, fields) {
printTimeForEvent("End getting Friends");
if (error) {
console.log('Error:', JSON.stringify(error, null, 2));
finalAppResponse( errorResponse( ErrorMessageGeneric))
}
if (results) {
console.log('==== Printing out Results for ' + results.length + ' rows ====');
var friends = followerResults(results);
var response = listFriendsResponse(friends);
printTimeForEvent("getFriends close to end of function");
finalAppResponse( response);
console.log("=============== Done ================");
} else {
console.log('Error:', JSON.stringify(error, null, 2));
finalAppResponse(errorResponse( ErrorMessageGeneric));
}
});
} | [
"function getUsersFollowings(fguid, guid, lastUsername) {\n\n var query = \"SELECT `profile`.guid , f2.`status` AS followed_status, f2.blocked, `profile`.`username`, profile.`fullname`, profile.followers, profile.following, user_metrics.popularity, `profile`.`verified`, profile.is_private, profile.about, profile.domain, `profile`.image_url AS image_url, `profile`.allow_view_followers, `profile`.allow_view_followings FROM `profile` INNER JOIN `friends` ON `friends`.`guid2` = `profile`.`guid` AND `status` = ? AND profile.allow_view_me_followings_list = 1 LEFT JOIN user_metrics ON user_metrics.guid = profile.guid LEFT JOIN `friends` as f2 ON f2.guid1 = ? AND f2.guid2 = profile.guid WHERE `friends`.`guid1` = ? ORDER BY `username` ASC LIMIT 60\";\n var parameters = [ Relationship.IsFollowing, guid, fguid];\n\n if (isStringWithLength(lastUsername)) {\n \n query = \"SELECT `profile`.guid, f2.`status` AS followed_status, f2.blocked, `profile`.`username`, profile.`fullname`, profile.followers, profile.following, user_metrics.popularity, `profile`.`verified`, profile.is_private, profile.about, profile.domain, `profile`.image_url AS image_url, `profile`.allow_view_followers, `profile`.allow_view_followings FROM `profile` INNER JOIN `friends` ON `friends`.`guid2` = `profile`.`guid` AND `status` = ? AND profile.allow_view_me_followings_list = 1 LEFT JOIN user_metrics ON user_metrics.guid = profile.guid LEFT JOIN `friends` as f2 ON f2.guid1 = ? AND f2.guid2 = profile.guid WHERE `friends`.`guid1` = ? AND username > ? ORDER BY `username` ASC LIMIT 60\";\n parameters = [ Relationship.IsFollowing, guid, fguid, lastUsername];\n }\n\n /**\n * Result contains friends info as ( guid, status, blocked, username, fullname\n */\n connection.query({\n sql : query,\n values: parameters,\n }, \n function (error, results, fields) {\n\n printTimeForEvent(\"End getting Friends\");\n\n if (error) {\n console.log('Error:', JSON.stringify(error, null, 2));\n finalAppResponse( errorResponse( ErrorMessageGeneric))\n } \n\n if (results) {\n console.log('==== Printing out Results for ' + results.length + ' rows ====');\n \n var friends = followerResults(results);\n\n var response = listFriendsResponse(friends);\n \n printTimeForEvent(\"getFriends close to end of function\");\n\n finalAppResponse( response);\n\n console.log(\"=============== Done ================\");\n } else {\n console.log('Error:', JSON.stringify(error, null, 2));\n finalAppResponse(errorResponse( ErrorMessageGeneric));\n }\n });\n }",
"function getFollowersForAlbum(guid, albumId, lastUsername) {\n\n printTimeForEvent(\"getFriendsForAlbum\");\n \n var friendsSql = \"SELECT `friends`.`guid1` AS guid, `friends`.`status` AS followed_status, `friends`.`blocked`, `profile`.`username`, profile.`fullname`, profile.followers, profile.following, user_metrics.popularity, `profile`.`verified`, profile.is_private, profile.about, profile.domain, `profile`.image_url AS image_url, `profile`.allow_view_followers, `profile`.allow_view_followings FROM `friends` INNER JOIN `profile` ON `friends`.`guid1` = `profile`.`guid` INNER JOIN album_permissions AS ap ON ap.guid = `friends`.`guid1`AND ap.fguid = `friends`.`guid2` AND album_id = ? LEFT JOIN user_metrics ON user_metrics.guid = profile.guid WHERE `friends`.`guid2` = ? AND `status` = ? ORDER BY `username` ASC LIMIT 60\";\n var parameters = [ guid , albumId, guid, Relationship.IsFollowing];\n \n if (isStringWithLength(lastUsername)) {\n friendsSql = \"SELECT `friends`.`guid1` AS guid, `friends`.`status` AS followed_status, `friends`.`blocked`, `profile`.`username`, profile.`fullname`, profile.followers, profile.following, user_metrics.popularity, `profile`.`verified`, profile.is_private, profile.about, profile.domain, `profile`.image_url AS image_url, `profile`.allow_view_followers, `profile`.allow_view_followings FROM `friends` INNER JOIN `profile` ON `friends`.`guid1` = `profile`.`guid` INNER JOIN album_permissions AS ap ON ap.guid = `friends`.`guid1`AND ap.fguid = `friends`.`guid2` AND album_id = ? LEFT JOIN user_metrics ON user_metrics.guid = profile.guid WHERE `friends`.`guid2` = ? AND `status` = ? AND username > ? ORDER BY `username` ASC LIMIT 60\";\n parameters = [ guid , albumId, guid, Relationship.IsFollowing, lastUsername];\n }\n \n var query = connection.query({\n sql : friendsSql,\n values: parameters\n }, \n function (err, results, fields) {\n \n if (err) {\n printError(err);\n finalAppResponse(errorResponse( ErrorMessageGeneric))\n } else {\n console.log('Result:', JSON.stringify(results, null, 2));\n \n var friends = [];\n results.forEach((result) => {\n console.log(result);\n \n \n var friend = {};\n friend[kGuid] = result.guid;\n friend[kUserName] = result.username;\n friend[kFullName] = result.fullname;\n friend[kFollowedStatus] = result.followed_status;\n friend[kSelectedFriends] = intToBool(result.is_selected);\n \n \n friend[kAbout] = result.about;\n friend[kDomain] = result.domain;\n \n friend[kPrivate] = intToBool(result.is_private);\n friend[kVerified] = intToBool(result.verified);\n \n var blockedUser = false;\n if (result.blocked == BlockedStatus.Blocked) {\n blockedUser = true;\n }\n friend[kBlocked] = blockedUser;\n \n friend[kProfileUrl] = result.image_url;\n \n friend[kAllowFollowersView] = intToBool(result.allow_view_followers);\n friend[kAllowFollowingsView] = intToBool(result.allow_view_followings);\n \n friend[kFollowersCount] = result.followers;\n friend[kFollowingCount] = result.following;\n friend[kScore] = result.popularity === null ? 0 : result.popularity;\n \n friends.push(friend);\n });\n \n var response = listFriendsResponse(friends);\n \n printTimeForEvent(\"getFriends close to end of function\");\n \n finalAppResponse( response);\n }\n });\n }",
"function getFriends() {\n var query = \"SELECT uid, name FROM user WHERE uid IN (Select uid2 from friend where uid1 =me())\";\n\n FB.api(\n {\n method: 'fql.query',\n query: query\n },\n function(response) {\n \n console.log(response);\n\n var html = \"\";\n var friend = new Array();\n for (var i=0; i < response.length; i++) {\n console.log(\"There were this many responses \" + response.length + \" and they are \" + response[i]);\n var name = response[i].name;\n var fuid = response[i].uid;\n fbPhoto.insert({username: name, uid: fuid, selected: 0});\n friend[i] = fuid;\n console.log(name + \" is your friend and their id is \" + fuid);\n \n\n \n\n //html += \"<a href='\"+big+\"' target='_blank'><img src='\"+src+\"' /></a>\";\n }\n\n console.log(\"you hit me with ONE \" + fbPhoto.find().count() );\n\n //getLatestPhotos(friend);\n \n\n\n //var container = document.getElementById(\"container\");\n //container.innerHTML = html;\n\n console.log('done');\n\n }\n );\n\n }",
"function getTopResults(username, friends, timePeriod, unheard, searchType) {\r\n\r\n // first we make the progress bar visible and describe the current status\r\n document.getElementById('status').textContent = 'Getting the top results from all your friends...';\r\n document.getElementById('outer-progress').style.visibility = 'visible';\r\n\r\n // since we don't want to continue any further until we receive all results, we use a list of promises\r\n const promiseList = [];\r\n\r\n // we store all of the top results into an array\r\n const results = [];\r\n\r\n // we also keep track of the progress for this section\r\n let progress = 0;\r\n\r\n // we loop through each user in the friends list\r\n for (let i = 0; i < friends.length; i++) {\r\n\r\n // we search using the appropriate query\r\n const query = {\r\n method: 'user.gettop' + searchType + 's',\r\n user: friends[i],\r\n api_key: key,\r\n period: timePeriod,\r\n format: 'json'\r\n };\r\n\r\n // we attach this query to the last.fm api URL\r\n url.search = new URLSearchParams(query);\r\n\r\n // we then push this fetch request to the list of promises\r\n promiseList.push(fetch(url, options)\r\n .then(response => {\r\n\r\n // if we the fetch request failed for whatever reason, we throw an error\r\n if (!response.ok) {\r\n throw new Error(response.statusText);\r\n }\r\n\r\n return response.json();\r\n\r\n })\r\n .then(response => {\r\n\r\n // we loop through each result in the response array\r\n for (let i = 0; i < response['top' + searchType + 's'][searchType].length; i++) {\r\n\r\n // we declare the current result item in the list\r\n const result = response['top' + searchType + 's'][searchType][i];\r\n\r\n // here we create variables for various metadata for the given result\r\n const score = 51 - result['@attr'].rank;\r\n const name = result.name;\r\n const playcount = parseInt(result.playcount);\r\n const mbid = result.mbid;\r\n const image = result.image[3]['#text'];\r\n\r\n let artist = undefined;\r\n\r\n // if it is an album or track, we also want to fetch the artist for this release\r\n if (searchType !== 'artist') {\r\n artist = result.artist.name;\r\n }\r\n\r\n // before adding this to the results array, we want to ensure\r\n // it doesn't already exist\r\n let found = false;\r\n for (let i = 0; i < results.length; i++) {\r\n\r\n // if it is already in results array, we simply update the score and playcount\r\n if (results[i].name === name\r\n && (artist === undefined\r\n || results[i].artist === artist)) {\r\n results[i].score += score;\r\n results[i].playcount += playcount;\r\n found = true;\r\n break;\r\n }\r\n }\r\n\r\n // if it wasn't in the results array, we add it\r\n if (!found) {\r\n\r\n results.push({\r\n 'score': score,\r\n 'name': name,\r\n 'artist': artist,\r\n 'playcount': playcount,\r\n 'mbid': mbid,\r\n 'image': image\r\n });\r\n }\r\n }\r\n\r\n // we update the progress bar to show the progress for this section\r\n progress++;\r\n document.getElementById('progress').style.width = ((progress / friends.length) * 100) + '%';\r\n })\r\n .catch(error => {\r\n // if there was an error, we alert the user\r\n alert(error + '!');\r\n\r\n // we also want to hide the progress and display the search form again\r\n document.getElementById('outer-progress').style.visibility = 'hidden';\r\n document.getElementById('enterUsername').style.display = 'block';\r\n }));\r\n }\r\n\r\n // once all fetch requests have been returned, we can try and continue\r\n Promise.all(promiseList)\r\n .then(function () {\r\n sortResults(username, friends, unheard, searchType, results)\r\n })\r\n}",
"function lookupFollowers(userLogin, callback) {\n $.ajax({\n type: 'GET',\n url: \"/tatami/rest/followers/lookup?screen_name=\" + userLogin,\n dataType: 'json',\n success: function(data) {\n callback(data);\n }\n });\n return false;\n}",
"function followers(){\n for(var person in data){\n var followersString = \"\";\n followersString += data[person].name + \" follows \";\n data[person].follows.forEach(function(follower, index, followers){\n if(index === followers.length - 1 && index !== 0){\n followersString += \"and \";\n }\n followersString += data[follower].name + \" \";\n });\n var followers = getFollowers(person);\n if(followers){\n followersString += \", this are his/her followers \"\n followers.forEach(function(follower, index, followers){\n if(index === followers.length - 1 && index !== 0){\n followersString += \"and \";\n }\n followersString += data[follower].name + \" \";\n });\n }\n console.log(followersString);\n }\n}",
"async function getOtherUsersFavorites(userId){\n const query = \"SELECT DISTINCT b.bname AS 'Band' FROM Bands b JOIN Favorites f ON f.band_id = b.bid JOIN `User` u ON u.uid = f.uid WHERE u.uid IN (SELECT u.uid FROM `User` u2 JOIN Favorites f2 ON f2.uid = u2.uid JOIN Bands b2 ON b2.bid = f2.band_id WHERE u2.uid != ? AND b2.bname IN (SELECT b2.bname FROM `User` u3 JOIN Favorites f3 ON f3.uid = u3.uid JOIN Bands b3 ON b3.bid = f3.band_id WHERE u3.uid = ?)) AND b.bname NOT IN (SELECT b4.bname FROM `User` u4 JOIN Favorites f4 ON f4.uid = u4.uid JOIN Bands b4 ON b4.bid = f4.band_id WHERE u4.uid = ?);\";\n try {\n const [rows] = await conn.execute(query, [userId, userId, userId]);\n return rows;\n } catch (err) {\n console.error(err);\n return [];\n }\n }",
"getFriends(userId) {\n\t\treturn this._getObjects(\n\t\t\t(\n\t\t\t\t'SELECT DISTINCT u.id, u.email, u.imgUrl FROM user u ' + \n\t\t\t\t'JOIN message m1 ON u.id = m1.recipientId ' + \n\t\t\t\t'JOIN message m2 ON u.id = m2.senderId ' +\n\t\t\t\t'WHERE m1.senderId = :id AND m2.recipientId = :id'\n\t\t\t),\n\t\t\t{\n\t\t\t\tid: userId\n\t\t\t}\n\t\t);\n\t}",
"function getUserInfo(req, res, next) {\n\tvar profileQuery = 'SELECT * FROM movie m INNER JOIN (SELECT ut_mid AS movie_id FROM user_taste WHERE ut_email = \"' + req.query.email + '\"AND likes = 1) temp ON temp.movie_id = m.movie_id';\n\tconnection.query(profileQuery, function(err, userLike) {\n\t\tif (err) {\n\t\t\tthrow err;\n\t\t} else {\n\t\t\tuserDislike(req,res,userLike,next);\n\t\t}\n\t});\n}",
"function get_friends_profile_picture(id, callback){\n var call = '/me?fields=id,friends.uid('+id+').fields(username)';\n call = make_url(call);\n FB.api(url, function(response){\n friend_user_name = response.username;\n\n profile_pic_url = 'https://graph.facebook.com/'+friend_user_name+'/picture';\n //got their usernme\n callback(profile_pic_url);\n });\n}",
"function updateFollowsAvatars(payload) {\n\tvar result = {}\n\tpayload.avatars.forEach((a) => {\n\t\tresult[a.username] = a.avatar\n\t})\n\treturn {type: 'followsAvatars', followsAvatars: result}\n}",
"async function friends(receiverId) {\n try {\n console.log('friends',receiverId);\n const [friends] = await pool.execute(` (select * from friendsTable where receiverId = ${receiverId} and status = 1) union (select * from friendsTable where senderId = ${receiverId} and status = 1)`);\n return friends\n } catch(err) {\n console.log('err', err);\n }\n\n}",
"function getFriends(callback) {\n Friendship.scan().loadAll().exec((err, data) => {\n if (err) {\n callback(null, err.message);\n } else {\n // Construct a map to remove duplicates in the data\n const friendMap = {};\n data.Items.map(item => {\n // Isolate the two friends from the object\n const friend1 = item.attrs.user1;\n const friend2 = item.attrs.user2;\n\n // Place them in the object in alphabetical order\n if (friend1 < friend2) {\n friendMap[friend1 + \"\\t\" + friend2] = true;\n } else {\n friendMap[friend2 + \"\\t\" + friend1] = true;\n }\n });\n\n // Format the data for mapreduce in a string\n const string = Object.keys(friendMap).reduce(format, \"\");\n callback(string, null);\n }\n });\n}",
"follow(fromId, toId) {\n return new Promise((resolve, reject) => {\n // check if this is an initial or reciprocal request\n this.client.zscore(`${this.namespace}:user:${fromId}:${STATE_KEY.pending}`, toId, (err, result) => {\n if (err) { reject(err); }\n // use date for sorted set ordering\n const score = Date.now();\n\n if (result === null) {\n // handle initial request\n this.client.multi()\n .zadd(`${this.namespace}:user:${fromId}:${STATE_KEY.requested}`, score, toId)\n .zadd(`${this.namespace}:user:${toId}:${STATE_KEY.pending}`, score, fromId)\n .exec((error) => {\n if (error) { reject(error); }\n debug(`${fromId} requested to be friends with ${toId}`);\n return resolve();\n });\n } else {\n // handle reciprocal request\n this.client.multi()\n .zrem(`${this.namespace}:user:${fromId}:${STATE_KEY.pending}`, toId)\n .zrem(`${this.namespace}:user:${toId}:${STATE_KEY.requested}`, fromId)\n .zadd(`${this.namespace}:user:${toId}:${STATE_KEY.accepted}`, score, fromId)\n .zadd(`${this.namespace}:user:${fromId}:${STATE_KEY.accepted}`, score, toId)\n .exec((error) => {\n if (error) { reject(error); }\n debug(`${fromId} and ${toId} are now friends`);\n return resolve();\n });\n }\n });\n });\n }",
"function showOtherUser(){\n removeFollowList();\n removeSearchArea();\n var userId = this.dataset.user; // get the user of the clicked name or image\n showedUser = userId;\n removeWritenFields();\n removeErrorSuccesFields();\n document.getElementById(\"profileSection\").style.display = \"block\";\n document.getElementById(\"messagesSection\").style.display = \"none\";\n hideAllProfileSection();\n document.getElementById(\"showProfile\").style.display = \"block\";\n\n getOtherProfile(userId);\n}",
"function suggestUsersToFollow() {\n $.ajax({\n type: 'GET',\n url: \"/tatami/rest/users/suggestions\",\n dataType: 'json',\n success: function(data) {\n makeWhoToFollowList(data);\n }\n });\n}",
"function getFamilyRecipes(username) {\n return DB.execQuery(`SELECT personal_recipes.recipe_id, personal_recipes.username, personal_recipes.recipe_name, \n personal_recipes.ready_in_minutes, personal_recipes.aggregate_likes, personal_recipes.vegetarian, personal_recipes.vegan, personal_recipes.gluten_free, personal_recipes.img_url,\n family_recipes.author, family_recipes.when_prepared FROM personal_recipes INNER JOIN family_recipes ON personal_recipes.recipe_id = family_recipes.recipe_id WHERE username = '${username}' AND is_family = 1;`); \n}",
"function updateFollowers() {\n const alreadyFollowersArray = models.users\n .findById(followingId)\n .then((resultUser) => {\n return resultUser.get({\n plain: true\n }).followers;\n });\n\n return alreadyFollowersArray.then((followersArray) => {\n if (followersArray.indexOf(userId) > -1 && type === 'follow') {\n return Promise.resolve();\n }\n\n if (followersArray.indexOf(userId) === -1 && type === 'unfollow') {\n return Promise.resolve();\n }\n\n return models.users\n .update({\n followers: updateArray(type, followersArray, userId)\n }, {\n where: {\n id: followingId\n },\n returning: true,\n raw: true,\n });\n });\n }",
"function getFamilyUserIds(userId, callback)\n{\n if(userId)\n { \n relationModule.findOne({ hooksForUserId: userId }).then(function (relation) {\n if(relation && relation.trees && relation.trees.length > 0)\n { \n var userDetails;\n for(var treeCount=0;treeCount<relation.trees.length;treeCount++)\n {\n if(relation.trees[treeCount].relations && relation.trees[treeCount].relations.length > 0)\n {\n for(var relCount=0;relCount<relation.trees[treeCount].relations.length;relCount++)\n {\n userDetails = (userDetails) ? userDetails + \",'\" + relation.trees[treeCount].relations[relCount].userId+\"'\" : \n \"'\" +relation.trees[treeCount].relations[relCount].userId+\"'\";\n //userDetails = (userDetails) ? userDetails + \",\" + relation.trees[treeCount].relations[relCount].userId : \n //relation.trees[treeCount].relations[relCount].userId;\n }\n }\n \n if(treeCount == (relation.trees.length - 1))\n {\n callback(null, userDetails);\n }\n } \n }\n else\n {\n var error = new Error(\"No records found for members.\"); \n callback(error);\n }\n }).catch(function(err){\n callback(err); \n });\n }\n else\n { \n var error = new Error(\"User not logged in\"); \n callback(error);\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds route for situations where one of end is inside the other. Typically the route is conduct outside the outer element first and let go back to the inner element. | function insideElement(from, to, fromBBox, toBBox, brng) {
var route = {};
var bndry = expand(boundary(fromBBox, toBBox), 1);
// start from the point which is closer to the boundary
var reversed = bndry.center().distance(to) > bndry.center().distance(from);
var start = reversed ? to : from;
var end = reversed ? from : to;
var p1, p2, p3;
if (brng) {
// Points on circle with radius equals 'W + H` are always outside the rectangle
// with width W and height H if the center of that circle is the center of that rectangle.
p1 = g.point.fromPolar(bndry.width + bndry.height, radians[brng], start);
p1 = bndry.pointNearestToPoint(p1).move(p1, -1);
} else {
p1 = bndry.pointNearestToPoint(start).move(start, 1);
}
p2 = freeJoin(p1, end, bndry);
if (p1.round().equals(p2.round())) {
p2 = g.point.fromPolar(bndry.width + bndry.height, g.toRad(p1.theta(start)) + Math.PI / 2, end);
p2 = bndry.pointNearestToPoint(p2).move(end, 1).round();
p3 = freeJoin(p1, p2, bndry);
route.points = reversed ? [p2, p3, p1] : [p1, p3, p2];
} else {
route.points = reversed ? [p2, p1] : [p1, p2];
}
route.direction = reversed ? bearing(p1, to) : bearing(p2, to);
return route;
} | [
"function findRoute(start, end, map, opt) {\n\n var step = opt.step;\n var startPoints, endPoints;\n var startCenter, endCenter;\n\n // set of points we start pathfinding from\n if (start instanceof g.rect) {\n startPoints = getRectPoints(start, opt.startDirections, opt);\n startCenter = start.center();\n } else {\n startCenter = start.clone().snapToGrid(step);\n startPoints = [start];\n }\n\n // set of points we want the pathfinding to finish at\n if (end instanceof g.rect) {\n endPoints = getRectPoints(end, opt.endDirections, opt);\n endCenter = end.center();\n } else {\n endCenter = end.clone().snapToGrid(step);\n endPoints = [end];\n }\n\n // take into account only accessible end points\n startPoints = _.filter(startPoints, map.isPointAccessible, map);\n endPoints = _.filter(endPoints, map.isPointAccessible, map);\n\n // Check if there is a accessible end point.\n // We would have to use a fallback route otherwise.\n if (startPoints.length > 0 && endPoints.length > 0) {\n\n // The set of tentative points to be evaluated, initially containing the start points.\n var openSet = new SortedSet();\n // Keeps reference to a point that is immediate predecessor of given element.\n var parents = {};\n // Cost from start to a point along best known path.\n var costs = {};\n\n _.each(startPoints, function(point) {\n var key = point.toString();\n openSet.add(key, estimateCost(point, endPoints));\n costs[key] = 0;\n });\n\n // directions\n var dir, dirChange;\n var dirs = opt.directions;\n var dirLen = dirs.length;\n var loopsRemain = opt.maximumLoops;\n var endPointsKeys = _.invoke(endPoints, 'toString');\n\n // main route finding loop\n while (!openSet.isEmpty() && loopsRemain > 0) {\n\n // remove current from the open list\n var currentKey = openSet.pop();\n var currentPoint = g.point(currentKey);\n var currentDist = costs[currentKey];\n var previousDirAngle = currentDirAngle;\n var currentDirAngle = parents[currentKey]\n ? getDirectionAngle(parents[currentKey], currentPoint, dirLen)\n : opt.previousDirAngle != null ? opt.previousDirAngle : getDirectionAngle(startCenter, currentPoint, dirLen);\n\n // Check if we reached any endpoint\n if (endPointsKeys.indexOf(currentKey) >= 0) {\n // We don't want to allow route to enter the end point in opposite direction.\n dirChange = getDirectionChange(currentDirAngle, getDirectionAngle(currentPoint, endCenter, dirLen));\n if (currentPoint.equals(endCenter) || dirChange < 180) {\n opt.previousDirAngle = currentDirAngle;\n return reconstructRoute(parents, currentPoint);\n }\n }\n\n // Go over all possible directions and find neighbors.\n for (var i = 0; i < dirLen; i++) {\n\n dir = dirs[i];\n dirChange = getDirectionChange(currentDirAngle, dir.angle);\n // if the direction changed rapidly don't use this point\n if (dirChange > opt.maxAllowedDirectionChange) {\n continue;\n }\n\n var neighborPoint = currentPoint.clone().offset(dir.offsetX, dir.offsetY);\n var neighborKey = neighborPoint.toString();\n // Closed points from the openSet were already evaluated.\n if (openSet.isClose(neighborKey) || !map.isPointAccessible(neighborPoint)) {\n continue;\n }\n\n // The current direction is ok to proccess.\n var costFromStart = currentDist + dir.cost + opt.penalties[dirChange];\n\n if (!openSet.isOpen(neighborKey) || costFromStart < costs[neighborKey]) {\n // neighbor point has not been processed yet or the cost of the path\n // from start is lesser than previously calcluated.\n parents[neighborKey] = currentPoint;\n costs[neighborKey] = costFromStart;\n openSet.add(neighborKey, costFromStart + estimateCost(neighborPoint, endPoints));\n };\n };\n\n loopsRemain--;\n }\n }\n\n // no route found ('to' point wasn't either accessible or finding route took\n // way to much calculations)\n return opt.fallbackRoute(startCenter, endCenter, opt);\n }",
"function cornerRoute(x1, y1, x2, y2) {\n var corners = findCorners();\n colorBoxes(corners, options.cornerColor);\n\n var graph = createCornerGraph(corners, [[x1, y1], [x2, y2]]);\n dijkstra(graph, keyFromCoordinates(x1, y1));\n\n var foundRoute = [];\n\n var startNode = getNode(graph, x1, y1),\n endNode = getNode(graph, x2, y2),\n node = endNode,\n distance = node.distance,\n lastNode = null;\n if (startNode === null || endNode === null || distance === Infinity) {\n // Start point is a wall\n return [Infinity, []];\n }\n\n while (node.predecessor.node !== null) {\n foundRoute.push(node.position);\n node = node.predecessor.node;\n }\n\n if (!(node.position[0] === x1 && node.position[1] === y1)) {\n // No route found\n return [Infinity, []];\n }\n\n foundRoute.reverse();\n\n\n // Add also the middle blocks to the path\n var lastX = x1,\n lastY = y1,\n newFoundRoute = [[x1, y1]];\n\n for (var i = 0; i < foundRoute.length; ++i) {\n var x = foundRoute[i][0],\n y = foundRoute[i][1],\n middleBoxes = routeBetween(lastX, lastY, x, y, COORD_MODE_DIAGONAL);\n\n for (var k = 0; k < middleBoxes.length; ++k) {\n newFoundRoute.push([middleBoxes[k][0], middleBoxes[k][1]]);\n }\n\n newFoundRoute.push([x, y]);\n lastX = x;\n lastY = y;\n }\n\n foundRoute.push([x1, y1]);\n colorBoxes(newFoundRoute, options.routeColor);\n colorBoxes(foundRoute, options.cornerRouteColor);\n return [distance, newFoundRoute];\n }",
"function findHoleBridge( hole, outerNode ) {\n \n var p = outerNode,\n hx = hole.x,\n hy = hole.y,\n qx = - Infinity,\n m;\n \n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n do {\n \n if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {\n \n var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );\n if ( x <= hx && x > qx ) {\n \n qx = x;\n if ( x === hx ) {\n \n if ( hy === p.y ) return p;\n if ( hy === p.next.y ) return p.next;\n \n }\n \n m = p.x < p.next.x ? p : p.next;\n \n }\n \n }\n \n p = p.next;\n \n } while ( p !== outerNode );\n \n if ( ! m ) return null;\n \n if ( hx === qx ) return m.prev; // hole touches outer segment; pick lower endpoint\n \n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n \n var stop = m,\n mx = m.x,\n my = m.y,\n tanMin = Infinity,\n tan;\n \n p = m.next;\n \n while ( p !== stop ) {\n \n if ( hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {\n \n tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential\n \n if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) {\n \n m = p;\n tanMin = tan;\n \n }\n \n }\n \n p = p.next;\n \n }\n \n return m;\n \n }",
"findPaths(fromNavNode, toNavNode) {\r\n\t\tlet walkingPaths = [[fromNavNode]];\r\n\t\tlet rtn = [];\r\n\r\n\t\twhile( walkingPaths.length > 0 ) {\r\n\t\t\tlet curPath = walkingPaths.pop();\r\n\t\t\tlet curNode = curPath[curPath.length-1].node;\r\n\t\t\tlet noRoute = false;\r\n\t\t\twhile( !noRoute && curNode != toNavNode ) {\r\n\t\t\t\tlet connections = curNode.connections.filter( connection => !curPath.includes(connection) );\r\n\t\t\t\tif ( connections.length > 0 ) {\r\n\t\t\t\t\tfor( let i = 1; i < connections.length; i++ ) {\r\n\t\t\t\t\t\tlet newPath = curPath.slice();\r\n\t\t\t\t\t\tnewPath.push(connections[i]);\r\n\t\t\t\t\t\twalkingPaths.push(newPath);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcurPath.push(connections[0]);\r\n\t\t\t\t\tcurNode = connections[0].node;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tnoRoute = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif ( !noRoute ) {\r\n\t\t\t\trtn.push(curPath);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn rtn;\r\n\t}",
"function routeBetween(x1, y1, x2, y2, coordMode) {\n\n var route = [],\n xDiff = x1 - x2;\n xDirection = -xDiff / Math.abs(xDiff),\n yDiff = y1 - y2,\n yDirection = -yDiff / Math.abs(yDiff);\n\n if (xDiff === 0 && yDiff === 0) {\n return route;\n }\n\n if (coordMode === COORD_MODE_STRAIGHT) {\n for (var i = 1; i < Math.abs(xDiff) + 1; ++i) {\n route.push([x1 + i * xDirection, y1]);\n }\n console.log('route' + JSON.stringify(route));\n var lastX = (route.length !== 0) ? route[route.length - 1][0] : x1;\n for (var i = 1; i < Math.abs(yDiff); ++i) {\n route.push([lastX, y1 + i * yDirection]);\n }\n }\n else if (coordMode === COORD_MODE_DIAGONAL) {\n xDiff = Math.abs(x2 - x1);\n yDiff = Math.abs(y2 - y1);\n\n if (yDiff < xDiff) {\n for (var i = 1; i < Math.abs(yDiff); ++i) {\n route.push([x1 + i * xDirection, y1 + i * yDirection]);\n }\n var lastX = (route.length !== 0 ) ? route[route.length - 1][0] : x1,\n newXDiff = x2 - lastX;\n for (var i = 1; i < Math.abs(newXDiff); ++i) {\n route.push([lastX + i * xDirection, y2]);\n }\n } else {\n for (var i = 1; i < Math.abs(xDiff); ++i) {\n route.push([x1 + i * xDirection, y1 + i * yDirection]);\n }\n var lastY = (route.length !== 0 ) ? route[route.length - 1][1] : y1,\n newYDiff = y2 - lastY;\n for (var i = 1; i < Math.abs(newYDiff); ++i) {\n route.push([x2, lastY + i * yDirection]);\n }\n }\n }\n return route;\n }",
"function carvePath(cell1, cell2){\n\t//cell1 = random frontier, cell2 = adjacent in maze\n\tif(cell1.location.row === cell2.location.row+1){\n\t\tmaze[cell1.location.row][cell1.location.col].dirOutOfCell.N = {row: cell2.location.row, col: cell2.location.col}\n\t\tmaze[cell2.location.row][cell2.location.col].dirOutOfCell.S = {row: cell1.location.row, col: cell1.location.col}\n\t}\n\tif(cell1.location.row === cell2.location.row-1){\n\t\tmaze[cell1.location.row][cell1.location.col].dirOutOfCell.S = {row: cell2.location.row, col: cell2.location.col}\n\t\tmaze[cell2.location.row][cell2.location.col].dirOutOfCell.N = {row: cell1.location.row, col: cell1.location.col}\n\t}\n\tif(cell1.location.col === cell2.location.col+1){\n\t\tmaze[cell1.location.row][cell1.location.col].dirOutOfCell.W = {row: cell2.location.row, col: cell2.location.col}\n\t\tmaze[cell2.location.row][cell2.location.col].dirOutOfCell.E = {row: cell1.location.row, col: cell1.location.col}\n\t}\n\tif(cell1.location.col === cell2.location.col-1){\n\t\tmaze[cell1.location.row][cell1.location.col].dirOutOfCell.E = {row: cell2.location.row, col: cell2.location.col}\n\t\tmaze[cell2.location.row][cell2.location.col].dirOutOfCell.W = {row: cell1.location.row, col: cell1.location.col}\n\t}\n}",
"findElement (locationID, start, end) {\n const self = this;\n this.sequence.forEach(function (e, i) {\n if(e.locationID === locationID) {\n const lastEnd = self.sequence[i - 1] ? self.sequence[i - 1].lastEnd : -1;\n const firstStart = self.sequence[i + 1] ? self.sequence[i + 1].firstStart : Infinity;\n if(lastEnd < start && end < firstStart) {\n return e;\n }\n }\n });\n return null;\n }",
"finalizeSlicedFindPath() {\n\n\t\tlet path = [];\n\t\tif (this.m_query.status == Status.FAILURE) {\n\t\t\t// Reset query.\n\t\t\tthis.m_query = new QueryData();\n\t\t\treturn new FindPathResult(Status.FAILURE, path);\n\t\t}\n\n\t\tif (this.m_query.startRef == this.m_query.endRef) {\n\t\t\t// Special case: the search starts and ends at same poly.\n\t\t\tpath.push(this.m_query.startRef);\n\t\t} else {\n\t\t\t// Reverse the path.\n\t\t\tif (this.m_query.lastBestNode.id != this.m_query.endRef)\n\t\t\t\tthis.m_query.status = Status.PARTIAL_RESULT;\n\n\t\t\tlet prev = null;\n\t\t\tlet node = this.m_query.lastBestNode;\n\t\t\tlet prevRay = 0;\n\t\t\tdo {\n\t\t\t\tlet next = this.m_nodePool.getNodeAtIdx(node.pidx);\n\t\t\t\tnode.pidx = this.m_nodePool.getNodeIdx(prev);\n\t\t\t\tprev = node;\n\t\t\t\tlet nextRay = node.flags & Node.DT_NODE_PARENT_DETACHED; // keep track of whether parent is not adjacent (i.e. due to raycast shortcut)\n\t\t\t\tnode.flags = this.or(this.and(node.flags, ~Node.DT_NODE_PARENT_DETACHED), prevRay); // and store it in the reversed path's node\n\t\t\t\tprevRay = nextRay;\n\t\t\t\tnode = next;\n\t\t\t} while (node != null);\n\n\t\t\t// Store path\n\t\t\tnode = prev;\n\t\t\tdo {\n\t\t\t\tlet next = this.m_nodePool.getNodeAtIdx(node.pidx);\n\t\t\t\tif ((node.flags & Node.DT_NODE_PARENT_DETACHED) != 0) {\n\t\t\t\t\tlet iresult = raycast(node.id, node.pos, next.pos, this.m_query.filter, 0, 0);\n\t\t\t\t\tpath.addAll(iresult.path);\n\t\t\t\t\t// raycast ends on let boundary and the path might include the next let boundary.\n\t\t\t\t\tif (path[path.length - 1] == next.id)\n\t\t\t\t\t\tpath.remove(path.length - 1); // remove to aduplicates\n\t\t\t\t} else {\n\t\t\t\t\tpath.push(node.id);\n\t\t\t\t}\n\n\t\t\t\tnode = next;\n\t\t\t} while (node != null);\n\t\t}\n\n\t\tlet status = this.m_query.status;\n\t\t// Reset query.\n\t\tthis.m_query = new QueryData();\n\n\t\treturn new FindPathResult(status, path);\n\t}",
"function extPart_getIsAroundNode(partName)\n{\n return extPart.getIsNodeRel(partName)\n && ( (String(extPart.getLocation(partName)).search(/before/i) != -1)\n || (String(extPart.getLocation(partName)).search(/after/i) != -1)\n );\n}",
"function findPath(world, pathStart, pathEnd) {\n // shortcuts for speed\n var abs = Math.abs;\n var max = Math.max;\n var pow = Math.pow;\n var sqrt = Math.sqrt;\n\n // keep track of the world dimensions\n // Note that this A-star implementation expects the world array to be square:\n // it must have equal height and width. If your game world is rectangular,\n // just fill the array with dummy values to pad the empty space.\n var worldWidth = world[0].length;\n var worldHeight = world.length;\n var worldSize = worldWidth * worldHeight;\n\n // which heuristic should we use?\n // default: no diagonals (Manhattan)\n var distanceFunction = ManhattanDistance;\n var findNeighbours = function () {\n }; // empty\n\n // distanceFunction functions\n // these return how far away a point is to another\n\n function ManhattanDistance(Point, Goal) {\t// linear movement - no diagonals - just cardinal directions (NSEW)\n return abs(Point.x - Goal.x) + abs(Point.y - Goal.y);\n }\n\n // Neighbours functions, used by findNeighbours function\n // to locate adjacent available cells that aren't blocked\n\n // Returns every available North, South, East or West\n // cell that is empty. No diagonals,\n // unless distanceFunction function is not Manhattan\n function Neighbours(x, y) {\n var N = y - 1,\n S = y + 1,\n E = x + 1,\n W = x - 1,\n myN = N > -1 && canWalkHere(x, N),\n myS = S < worldHeight && canWalkHere(x, S),\n myE = E < worldWidth && canWalkHere(E, y),\n myW = W > -1 && canWalkHere(W, y),\n result = [];\n if (myN)\n result.push({x: x, y: N});\n if (myE)\n result.push({x: E, y: y});\n if (myS)\n result.push({x: x, y: S});\n if (myW)\n result.push({x: W, y: y});\n findNeighbours(myN, myS, myE, myW, N, S, E, W, result);\n return result;\n }\n\n // returns boolean value (world cell is available and open)\n function canWalkHere(x, y) {\n return ((world[y] != null) &&\n (world[y][x] != null) &&\n (world[y][x] !== '#'));\n }\n\n // Node function, returns a new object with Node properties\n // Used in the calculatePath function to store route costs, etc.\n function Node(Parent, Point) {\n var newNode = {\n // pointer to another Node object\n Parent: Parent,\n // array index of this Node in the world linear array\n value: Point.x + (Point.y * worldWidth),\n // the location coordinates of this Node\n x: Point.x,\n y: Point.y,\n // the distanceFunction cost to get\n // TO this Node from the START\n f: 0,\n // the distanceFunction cost to get\n // from this Node to the GOAL\n g: 0\n };\n\n return newNode;\n }\n\n // Path function, executes AStar algorithm operations\n function calculatePath() {\n // create Nodes from the Start and End x,y coordinates\n var mypathStart = Node(null, {x: pathStart[0], y: pathStart[1]});\n var mypathEnd = Node(null, {x: pathEnd[0], y: pathEnd[1]});\n // create an array that will contain all world cells\n var AStar = new Array(worldSize);\n // list of currently open Nodes\n var Open = [mypathStart];\n // list of closed Nodes\n var Closed = [];\n // list of the final output array\n var result = [];\n // reference to a Node (that is nearby)\n var myNeighbours;\n // reference to a Node (that we are considering now)\n var myNode;\n // reference to a Node (that starts a path in question)\n var myPath;\n // temp integer variables used in the calculations\n var length, max, min, i, j;\n // iterate through the open list until none are left\n while (length = Open.length) {\n max = worldSize;\n min = -1;\n for (i = 0; i < length; i++) {\n if (Open[i].f < max) {\n max = Open[i].f;\n min = i;\n }\n }\n // grab the next node and remove it from Open array\n myNode = Open.splice(min, 1)[0];\n // is it the destination node?\n if (myNode.value === mypathEnd.value) {\n myPath = Closed[Closed.push(myNode) - 1];\n do\n {\n result.push([myPath.x, myPath.y]);\n }\n while (myPath = myPath.Parent);\n // clear the working arrays\n AStar = Closed = Open = [];\n // we want to return start to finish\n result.reverse();\n }\n else // not the destination\n {\n // find which nearby nodes are walkable\n myNeighbours = Neighbours(myNode.x, myNode.y);\n\n // test each one that hasn't been tried already\n for (i = 0, j = myNeighbours.length; i < j; i++) {\n myPath = Node(myNode, myNeighbours[i]);\n if (!AStar[myPath.value]) {\n // estimated cost of this particular route so far\n myPath.g = myNode.g + distanceFunction(myNeighbours[i], myNode);\n // estimated cost of entire guessed route to the destination\n myPath.f = myPath.g + distanceFunction(myNeighbours[i], mypathEnd);\n // remember this new path for testing above\n Open.push(myPath);\n // mark this node in the world graph as visited\n AStar[myPath.value] = true;\n }\n }\n // remember this route as having no more untested options\n Closed.push(myNode);\n }\n } // keep iterating until until the Open list is empty\n return result;\n }\n // actually calculate the a-star path!\n // this returns an array of coordinates\n // that is empty if no path is possible\n return calculatePath();\n\n} // end of findPath() function",
"findIndex(pos, end, side = end * Far, startAt = 0) {\n if (pos <= 0)\n return startAt;\n let arr = end < 0 ? this.to : this.from;\n for (let lo = startAt, hi = arr.length;;) {\n if (lo == hi)\n return lo;\n let mid = (lo + hi) >> 1;\n let diff = arr[mid] - pos || (end < 0 ? this.value[mid].startSide : this.value[mid].endSide) - side;\n if (mid == lo)\n return diff >= 0 ? lo : hi;\n if (diff >= 0)\n hi = mid;\n else\n lo = mid + 1;\n }\n }",
"oppositeCorner(corner)\n\t{\n\t\tif (this.start === corner)\n\t\t{\n\t\t\treturn this.end;\n\t\t}\n\t\telse if (this.end === corner)\n\t\t{\n\t\t\treturn this.start;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tconsole.log('Wall does not connect to corner');\n\t\t\treturn null;\n\t\t}\n\t}",
"visitWithin_or_over_part(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function chooseRighthandPath(fromX, fromY, nodeX, nodeY, ax, ay, bx, by) {\n var angleA = geom.signedAngle(fromX, fromY, nodeX, nodeY, ax, ay);\n var angleB = geom.signedAngle(fromX, fromY, nodeX, nodeY, bx, by);\n var code;\n if (angleA <= 0 || angleB <= 0) {\n if (angleA <= 0) {\n debug(' A orient2D:', geom.orient2D(fromX, fromY, nodeX, nodeY, ax, ay));\n }\n if (angleB <= 0) {\n debug(' B orient2D:', geom.orient2D(fromX, fromY, nodeX, nodeY, bx, by));\n }\n // TODO: test against \"from\" segment\n if (angleA > 0) {\n code = 1;\n } else if (angleB > 0) {\n code = 2;\n } else {\n code = 0;\n }\n } else if (angleA < angleB) {\n code = 1;\n } else if (angleB < angleA) {\n code = 2;\n } else if (isNaN(angleA) || isNaN(angleB)) {\n // probably a duplicate point, which should not occur\n error('Invalid node geometry');\n } else {\n // Equal angles: use fallback test that is less sensitive to rounding error\n code = chooseRighthandVector(ax - nodeX, ay - nodeY, bx - nodeX, by - nodeY);\n }\n return code;\n}",
"function findDoor(map){\n\tfor(let r=0;r<map.length;r++){\n\t\tfor(let c=0;c<map[0].length;c++){\n\t\t\tif(map[r][c] == '/'){\n\t\t\t\treturn [c,r];\n\t\t\t}\n\t\t}\n\t}\n}",
"isAncestor(path, another) {\n return path.length < another.length && Path.compare(path, another) === 0;\n }",
"function solution_1 (nums, target, start, end) {\r\n if (start === undefined) start = 0; // arguments.callee won't work if the function uses default parameters\r\n if (end === undefined) end = nums.length - 1; // arguments.callee won't work if the function uses default parameters\r\n\r\n while (start <= end) {\r\n\t\tconst middle = start + Math.floor((end - start) / 2);\r\n\t\tif (nums[middle] === target) {\r\n return middle;\r\n } else if (nums[start] === target) { // this block is not strictly necessary but i thought it would be a nice check\r\n return start;\r\n } else if (nums[end] === target) { // this block is not strictly necessary but i thought it would be a nice check\r\n return end;\r\n\t\t} else if (nums[middle] > nums[end]) {\t\t\t\t\t\t\t\t \t\t// the break must be at or to the right of middle\r\n\t\t\tif (target > nums[end] && target < nums[middle]) {\t \t\t\t// if target exists at all, it must be left of middle\r\n\t\t\t\treturn binarySearch(nums, target, start, middle - 1);\r\n\t\t\t} else {\r\n\t\t\t\tstart = middle + 1;\r\n\t\t\t}\r\n\t\t} else if (nums[middle] < nums[start]) {\t\t\t\t\t\t\t\t \t// the break must be to the left of middle\r\n\t\t\tif (target < nums[start] && target > nums[middle]) {\t \t\t// if target exists at all, it must be right of middle\r\n\t\t\t\treturn binarySearch(nums, target, middle + 1, end);\r\n\t\t\t} else {\r\n\t\t\t\tend = middle - 1;\r\n\t\t\t}\r\n\t\t} else {\t\t// it's unclear which half we can eliminate (due to edge case) so we have no choice but to recurse\r\n\t\t\tconst recurseLeft = arguments.callee(nums, target, start, middle - 1);\r\n\t\t\treturn recurseLeft !== -1 ? recurseLeft : arguments.callee(nums, target, middle + 1, end);\r\n\t\t}\r\n\t}\r\n\treturn -1;\r\n}",
"function trueTraverse(range, tile, terrain, team){\n var tiles = {};\n var onTiles = [];\n \n var boundary = [tile];\n for(var i=0;i<range;i++){\n var b = []; // Holds tiles to start search from for next iteration\n //Searches out from each tile in boundary\n for(var j in boundary){\n var t = boundary[j];\n //Search up\n var nextTile = t.up;\n //Check if tile meets criteria and whether already been searched\n // also makes sure it's not the starting target cell\n if(nextTile && !tiles[nextTile.loc] && nextTile!=tile){\n if(terrain.includes(nextTile.terrain) && (!nextTile.onTile || nextTile.onTile.team == team)){//Checking criteria here\n tiles[nextTile.loc] = nextTile;\n b.push(nextTile); //saves tile for next iteration\n if(nextTile.onTile)\n onTiles.push(nextTile.onTile);\n }\n }\n //Search down\n nextTile = t.down;\n if(nextTile && !tiles[nextTile.loc] && nextTile!=tile){\n if(terrain.includes(nextTile.terrain) && (!nextTile.onTile || nextTile.onTile.team == team)){\n tiles[nextTile.loc] = nextTile;\n b.push(nextTile); //saves tile for next iteration\n if(nextTile.onTile)\n onTiles.push(nextTile.onTile);\n }\n }\n //Search Left\n nextTile = t.left;\n if(nextTile && !tiles[nextTile.loc] && nextTile!=tile){\n if(terrain.includes(nextTile.terrain) && (!nextTile.onTile || nextTile.onTile.team == team)){\n tiles[nextTile.loc] = nextTile;\n b.push(nextTile); //saves tile for next iteration\n if(nextTile.onTile)\n onTiles.push(nextTile.onTile);\n }\n }\n //Search Right\n nextTile = t.right;\n if(nextTile && !tiles[nextTile.loc] && nextTile!=tile){\n if(terrain.includes(nextTile.terrain) && (!nextTile.onTile || nextTile.onTile.team == team)){\n tiles[nextTile.loc] = nextTile;\n b.push(nextTile); //saves tile for next iteration\n if(nextTile.onTile)\n onTiles.push(nextTile.onTile);\n }\n }\n }\n //Updates the boundary to new boundaries\n boundary = b;\n }\n return {tiles: tiles, onTiles: onTiles};\n}",
"function computePath( startingNode, endingNode ) {\n // First edge case: start is the end:\n if (startingNode.id === endingNode.id) {\n return [startingNode];\n }\n\n // Second edge case: two connected nodes\n if ( endingNode.id in startingNode.next ) {\n return [startingNode, endingNode];\n }\n\t\n var path = [];\n var n = endingNode;\n while ( n && n.id !== startingNode.id ) {\n // insert at the beggining\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift\n if ( n.id !== endingNode.id ) {\n path.unshift( n );\n }\n n = n.prev;\n }\n\n if ( path.length ) {\n path.unshift( startingNode );\n path.push( endingNode );\n }\n\n return path;\n}",
"includes(range, target) {\n if (Range.isRange(target)) {\n if (Range.includes(range, target.anchor) || Range.includes(range, target.focus)) {\n return true;\n }\n\n var [rs, re] = Range.edges(range);\n var [ts, te] = Range.edges(target);\n return Point.isBefore(rs, ts) && Point.isAfter(re, te);\n }\n\n var [start, end] = Range.edges(range);\n var isAfterStart = false;\n var isBeforeEnd = false;\n\n if (Point.isPoint(target)) {\n isAfterStart = Point.compare(target, start) >= 0;\n isBeforeEnd = Point.compare(target, end) <= 0;\n } else {\n isAfterStart = Path.compare(target, start.path) >= 0;\n isBeforeEnd = Path.compare(target, end.path) <= 0;\n }\n\n return isAfterStart && isBeforeEnd;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
API for updating the styleRules in an existing page stylesheet across all components. Takes a sheet index value obtained via addPageStyles. | function updatePageStyles(sheetIndex, styleRules, restorePlace) {
return changingStylesheet(function () {
p.stylesheets[sheetIndex] = styleRules;
if (typeof styleRules.join == "function") {
styleRules = styleRules.join("\n");
}
var i = 0, cmpt = null;
while (cmpt = p.reader.dom.find('component', i++)) {
var doc = cmpt.contentDocument;
var styleTag = doc.getElementById('monStylesheet'+sheetIndex);
if (!styleTag) {
console.warn('No such stylesheet: ' + sheetIndex);
return;
}
if (styleTag.styleSheet) {
styleTag.styleSheet.cssText = styleRules;
} else {
styleTag.replaceChild(
doc.createTextNode(styleRules),
styleTag.firstChild
);
}
}
}, restorePlace);
} | [
"function addPageStyles(styleRules, restorePlace) {\n return changingStylesheet(function () {\n p.stylesheets.push(styleRules);\n var sheetIndex = p.stylesheets.length - 1;\n\n var i = 0, cmpt = null;\n while (cmpt = p.reader.dom.find('component', i++)) {\n addPageStylesheet(cmpt.contentDocument, sheetIndex);\n }\n return sheetIndex;\n }, restorePlace);\n }",
"function removePageStyles(sheetIndex, restorePlace) {\n return changingStylesheet(function () {\n p.stylesheets[sheetIndex] = null;\n var i = 0, cmpt = null;\n while (cmpt = p.reader.dom.find('component', i++)) {\n var doc = cmpt.contentDocument;\n var styleTag = doc.getElementById('monStylesheet'+sheetIndex);\n styleTag.parentNode.removeChild(styleTag);\n }\n }, restorePlace);\n }",
"function defineDocumentStyles() {\r\n for (var i = 0; i < document.styleSheets.length; i++) {\r\n var mysheet = document.styleSheets[i],\r\n myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;\r\n config.documentStyles.push(myrules);\r\n }\r\n }",
"function splNvslApplyDynamicStyles() {\n var styles = splNvslConfig.styleSheet;\n\n $('.spl-nvsl-tab').css(styles.nvslTab);\n $('.spl-nvsl-tab a').css(styles.nvslTabAnchor);\n $('.spl-nvsl-tab a').hover(function() {\n $(this).css(styles.nvslTabAnchorHover);\n }, function() {\n $(this).css(styles.nvslTabAnchor);\n });\n\n $('.spl-nvsl-tab-active').css(styles.nvslTabActive);\n $('.spl-nvsl-tab-active a').css(styles.nvslTabActiveAnchor);\n $('.spl-nvsl-tab-active a').hover(function() {\n $(this).css(styles.nvslTabActiveAnchorHover);\n }, function() {\n $(this).css(styles.nvslTabActiveAnchor);\n });\n\n }",
"function addPageStyles(styleRules, restorePlace) {\n console.deprecation(\"Use reader.formatting.addPageStyles instead.\");\n return API.formatting.addPageStyles(styleRules, restorePlace);\n }",
"createStyleSheet(rules, options) {\n const sheet = new StyleSheet(rules, {...options, jss: this})\n this.sheets.add(sheet)\n return sheet\n }",
"function createStyleManager() {\n\t var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},\n\t jss = _ref.jss,\n\t _ref$theme = _ref.theme,\n\t theme = _ref$theme === undefined ? {} : _ref$theme;\n\t\n\t if (!jss) {\n\t throw new Error('No JSS instance provided');\n\t }\n\t\n\t var sheetMap = [];\n\t var sheetOrder = void 0;\n\t\n\t // Register custom jss generateClassName function\n\t jss.options.generateClassName = generateClassName;\n\t\n\t function generateClassName(str, rule) {\n\t var hash = (0, _murmurhash3_gc2.default)(str);\n\t str = rule.name ? rule.name + '-' + hash : hash;\n\t\n\t // Simplify after next release with new method signature\n\t if (rule.options.sheet && rule.options.sheet.options.name) {\n\t return rule.options.sheet.options.name + '-' + str;\n\t }\n\t return str;\n\t }\n\t\n\t /**\n\t * styleManager\n\t */\n\t var styleManager = {\n\t get sheetMap() {\n\t return sheetMap;\n\t },\n\t get sheetOrder() {\n\t return sheetOrder;\n\t },\n\t setSheetOrder: setSheetOrder,\n\t jss: jss,\n\t theme: theme,\n\t render: render,\n\t reset: reset,\n\t rerender: rerender,\n\t getClasses: getClasses,\n\t updateTheme: updateTheme,\n\t prepareInline: prepareInline,\n\t sheetsToString: sheetsToString\n\t };\n\t\n\t updateTheme(theme, false);\n\t\n\t function render(styleSheet) {\n\t var index = getMappingIndex(styleSheet.name);\n\t\n\t if (index === -1) {\n\t return renderNew(styleSheet);\n\t }\n\t\n\t var mapping = sheetMap[index];\n\t\n\t if (mapping.styleSheet !== styleSheet) {\n\t jss.removeStyleSheet(sheetMap[index].jssStyleSheet);\n\t sheetMap.splice(index, 1);\n\t\n\t return renderNew(styleSheet);\n\t }\n\t\n\t return mapping.classes;\n\t }\n\t\n\t /**\n\t * Get classes for a given styleSheet object\n\t */\n\t function getClasses(styleSheet) {\n\t var mapping = (0, _utils.find)(sheetMap, { styleSheet: styleSheet });\n\t return mapping ? mapping.classes : null;\n\t }\n\t\n\t /**\n\t * @private\n\t */\n\t function renderNew(styleSheet) {\n\t var name = styleSheet.name,\n\t createRules = styleSheet.createRules,\n\t options = styleSheet.options;\n\t\n\t var sheetMeta = name + '-' + styleManager.theme.id;\n\t\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof document === 'undefined' ? 'undefined' : _typeof(document)) === 'object') {\n\t var element = document.querySelector('style[data-jss][data-meta=\"' + sheetMeta + '\"]');\n\t if (element) {\n\t options.element = element;\n\t }\n\t }\n\t\n\t var rules = createRules(styleManager.theme);\n\t var jssOptions = _extends({\n\t name: name,\n\t meta: sheetMeta\n\t }, options);\n\t\n\t if (sheetOrder && !jssOptions.hasOwnProperty('index')) {\n\t var index = sheetOrder.indexOf(name);\n\t if (index === -1) {\n\t jssOptions.index = sheetOrder.length;\n\t } else {\n\t jssOptions.index = index;\n\t }\n\t }\n\t\n\t var jssStyleSheet = jss.createStyleSheet(rules, jssOptions);\n\t\n\t var _jssStyleSheet$attach = jssStyleSheet.attach(),\n\t classes = _jssStyleSheet$attach.classes;\n\t\n\t sheetMap.push({ name: name, classes: classes, styleSheet: styleSheet, jssStyleSheet: jssStyleSheet });\n\t\n\t return classes;\n\t }\n\t\n\t /**\n\t * @private\n\t */\n\t function getMappingIndex(name) {\n\t var index = (0, _utils.findIndex)(sheetMap, function (obj) {\n\t if (!obj.hasOwnProperty('name') || obj.name !== name) {\n\t return false;\n\t }\n\t\n\t return true;\n\t });\n\t\n\t return index;\n\t }\n\t\n\t /**\n\t * Set DOM rendering order by sheet names.\n\t */\n\t function setSheetOrder(sheetNames) {\n\t sheetOrder = sheetNames;\n\t }\n\t\n\t /**\n\t * Replace the current theme with a new theme\n\t */\n\t function updateTheme(newTheme) {\n\t var shouldUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;\n\t\n\t styleManager.theme = newTheme;\n\t if (!styleManager.theme.id) {\n\t styleManager.theme.id = (0, _murmurhash3_gc2.default)(JSON.stringify(styleManager.theme));\n\t }\n\t if (shouldUpdate) {\n\t rerender();\n\t }\n\t }\n\t\n\t /**\n\t * Reset JSS registry, remove sheets and empty the styleManager.\n\t */\n\t function reset() {\n\t sheetMap.forEach(function (_ref2) {\n\t var jssStyleSheet = _ref2.jssStyleSheet;\n\t jssStyleSheet.detach();\n\t });\n\t sheetMap = [];\n\t }\n\t\n\t /**\n\t * Reset and update all existing stylesheets\n\t *\n\t * @memberOf module:styleManager~styleManager\n\t */\n\t function rerender() {\n\t var sheets = [].concat(_toConsumableArray(sheetMap));\n\t reset();\n\t sheets.forEach(function (n) {\n\t render(n.styleSheet);\n\t });\n\t }\n\t\n\t /**\n\t * Prepare inline styles using Theme Reactor\n\t */\n\t function prepareInline(declaration) {\n\t if (typeof declaration === 'function') {\n\t declaration = declaration(theme);\n\t }\n\t\n\t var rule = {\n\t type: 'regular',\n\t style: declaration\n\t };\n\t\n\t prefixRule(rule);\n\t\n\t return rule.style;\n\t }\n\t\n\t /**\n\t * Render sheets to an HTML string\n\t */\n\t function sheetsToString() {\n\t return sheetMap.sort(function (a, b) {\n\t if (a.jssStyleSheet.options.index < b.jssStyleSheet.options.index) {\n\t return -1;\n\t }\n\t if (a.jssStyleSheet.options.index > b.jssStyleSheet.options.index) {\n\t return 1;\n\t }\n\t return 0;\n\t }).map(function (sheet) {\n\t return sheet.jssStyleSheet.toString();\n\t }).join('\\n');\n\t }\n\t\n\t return styleManager;\n\t}",
"function setStyle (style, pageName)\n{\n\t// check to see if base page is in page list\n\tif (pageName.indexOf(gBASE_PAGE) >= 0)\n\t\tvar base = style;\n\telse\n\t\tvar base = getStyle (gBASE_PAGE);\n\tpageName = pageName.split (\"<br>\");\n\tfor (var n = 0; n < pageName.length; n++)\n\t\tsetSiteEditorCfgField (pageName[n], gSTYLE, style, base)\t\t\t\n}",
"function update_style() {\n\tvar style = get_style();\n\tif (style !== null) {\n\t\tvar cssName = \"chroma_\" + style + \".css\";\n\t\tvar cssPath = \"inc/css/\" + cssName;\n\t\tvar elem = document.getElementById(\"chroma_style\");\n\t\telem.href = cssPath;\n\t}\n}",
"function reinjectStyles() {\n if (!styleElements) {\n orphanCheck();\n return;\n }\n ROOT = document.documentElement;\n docRootObserver.stop();\n const imported = [];\n for (const [id, el] of styleElements.entries()) {\n const copy = document.importNode(el, true);\n el.textContent += \" \"; // invalidate CSSOM cache\n imported.push([id, copy]);\n addStyleElement(copy);\n }\n docRootObserver.start();\n styleElements = new Map(imported);\n }",
"updateStyles(properties = {}) {\n console.warn(\n `WARNING: Since Vaadin 23, updateStyles() is deprecated. Use the native element.style.setProperty API to set custom CSS property values.`\n );\n\n Object.entries(properties).forEach(([key, value]) => {\n this.style.setProperty(key, value);\n });\n\n this._updateLayout();\n }",
"function findStyleSheet(styleSheetId,styleSheetUrl)\r\n{\r\n\tvar styleSheets = dw.getDocumentDOM().browser.getWindow().document.styleSheets;\r\n\tif(styleSheetId > -1)\r\n {\r\n\t\treturn styleSheets[styleSheetId];\r\n\t}\r\n\t\r\n\tfor(var i=0;i<styleSheets.length;i++)\r\n\t{\t\r\n\t\tif(dw.compareURLs(styleSheets[i].href,styleSheetUrl))\r\n\t\t{\r\n\t\t\treturn styleSheets[i];\r\n\t\t}\r\n\t\telse\r\n\t\t{\t\t\t\r\n\t\t\tvar styleSheet = findNestedStyleSheet(styleSheets[i],styleSheetUrl);\r\n\t\t\tif(styleSheet)\r\n\t\t\t\treturn styleSheet;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}",
"reStyle() {\n console.log('restyle')\n this._destroyStyles();\n this._initStyles();\n }",
"function editProperty(ruleStr,styleSheet,property,value,ruleRepeatCount)\r\n{\r\n\tvar rule = findRule(ruleStr,styleSheet.cssRules,ruleRepeatCount);\r\n var execStr = \"rule.style.\"+property+\"=\"+value;\r\n\trule.style[property] = value;\r\n}",
"function send_update_style_event() {\n\tfor (i = 0; i < frames.length; i++) {\n\t\tframes[i].window.postMessage(\"update_style\", \"*\");\n\t}\n}",
"function reset() {\n\t sheetMap.forEach(function (_ref2) {\n\t var jssStyleSheet = _ref2.jssStyleSheet;\n\t jssStyleSheet.detach();\n\t });\n\t sheetMap = [];\n\t }",
"updateStyle(stateStyle) {\n let {styles} = this.stylesheet;\n\n this.setState({\n containerStyle: assign({}, styles.container, stateStyle)\n });\n }",
"function addStyles() {\n\t styles.use();\n\t stylesInUse++;\n\t}",
"function createStyleSheet() {\n\tvar stylesheet = Banana.Report.newStyleSheet();\n\n var pageStyle = stylesheet.addStyle(\"@page\");\n pageStyle.setAttribute(\"margin\", \"20mm 10mm 20mm 20mm\");\n\n stylesheet.addStyle(\"body\", \"font-family : Helvetica\");\n\n\tstyle = stylesheet.addStyle(\".footer\");\n\tstyle.setAttribute(\"text-align\", \"right\");\n\tstyle.setAttribute(\"font-size\", \"8px\");\n\tstyle.setAttribute(\"font-family\", \"Courier New\");\n\n\tstyle = stylesheet.addStyle(\".heading1\");\n\tstyle.setAttribute(\"font-size\", \"16px\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\t\n\tstyle = stylesheet.addStyle(\".heading2\");\n\tstyle.setAttribute(\"font-size\", \"14px\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\n\tstyle = stylesheet.addStyle(\".heading3\");\n\tstyle.setAttribute(\"font-size\", \"12px\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\n\tstyle = stylesheet.addStyle(\".heading4\");\n\tstyle.setAttribute(\"font-size\", \"9px\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\n\tstyle = stylesheet.addStyle(\".bold\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\n\tstyle = stylesheet.addStyle(\".italic\");\n\tstyle.setAttribute(\"font-style\", \"italic\");\n\n\tstyle = stylesheet.addStyle(\".alignRight\");\n\tstyle.setAttribute(\"text-align\", \"right\");\n\n\t//Warning message.\n\tstyle = stylesheet.addStyle(\".warningMsg\");\n\tstyle.setAttribute(\"font-weight\", \"bold\");\n\tstyle.setAttribute(\"color\", \"red\");\n\tstyle.setAttribute(\"font-size\", \"10\");\n\n\t//Tables\n\tstyle = stylesheet.addStyle(\"table\");\n\tstyle.setAttribute(\"width\", \"100%\");\n\tstyle.setAttribute(\"font-size\", \"8px\");\n\tstylesheet.addStyle(\"table.table td\", \"border: thin solid black\");\n\n\treturn stylesheet;\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method takes an array of statements nodes and then explodes it into expressions. This method retains completion records which is extremely important to retain original semantics. | function replaceExpressionWithStatements(nodes) {
this.resync();
var toSequenceExpression = t.toSequenceExpression(nodes, this.scope);
if (t.isSequenceExpression(toSequenceExpression)) {
var exprs = toSequenceExpression.expressions;
if (exprs.length >= 2 && this.parentPath.isExpressionStatement()) {
this._maybePopFromStatements(exprs);
}
// could be just one element due to the previous maybe popping
if (exprs.length === 1) {
this.replaceWith(exprs[0]);
} else {
this.replaceWith(toSequenceExpression);
}
} else if (toSequenceExpression) {
this.replaceWith(toSequenceExpression);
} else {
var container = t.functionExpression(null, [], t.blockStatement(nodes));
container.shadow = true;
this.replaceWith(t.callExpression(container, []));
this.traverse(hoistVariablesVisitor);
// add implicit returns to all ending expression statements
var completionRecords = this.get("callee").getCompletionRecords();
for (var _i2 = 0; _i2 < completionRecords.length; _i2++) {
var path = completionRecords[_i2];
if (!path.isExpressionStatement()) continue;
var loop = path.findParent(function (path) {
return path.isLoop();
});
if (loop) {
var callee = this.get("callee");
var uid = callee.scope.generateDeclaredUidIdentifier("ret");
callee.get("body").pushContainer("body", t.returnStatement(uid));
path.get("expression").replaceWith(t.assignmentExpression("=", uid, path.node.expression));
} else {
path.replaceWith(t.returnStatement(path.node.expression));
}
}
return this.node;
}
} | [
"visitSeq_of_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"visitExprlist(ctx) {\r\n console.log(\"visitExprlist\");\r\n let exprlist = [];\r\n for (var i = 0; i < ctx.star_expr().length; i++) {\r\n exprlist.push(this.visit(ctx.star_expr(i)));\r\n }\r\n return exprlist;\r\n }",
"visitCursor_manipulation_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function evaluate_sequence(stmts,env) {\n if (is_empty_statement(stmts)) {\n return undefined;\n } else if (is_last_statement(stmts)) {\n return evaluate(first_statement(stmts),env);\n } else {\n var first_stmt_value = \n evaluate(first_statement(stmts),env);\n if (is_return_value(first_stmt_value)) {\n return first_stmt_value;\n } else {\n return evaluate_sequence(\n rest_statements(stmts),env);\n }\n }\n}",
"visitExpr_stmt(ctx) {\r\n console.log(\"visitExpr_stmt\");\r\n if (ctx.augassign() !== null) {\r\n return {\r\n type: \"AugAssign\",\r\n left: this.visit(ctx.testlist_star_expr(0)),\r\n right: this.visit(ctx.getChild(2)),\r\n };\r\n } else {\r\n let length = ctx.getChildCount();\r\n let right = this.visit(ctx.getChild(length - 1));\r\n for (var i = length; i > 1; i = i - 2) {\r\n let temp_left = this.visit(ctx.getChild(i - 3));\r\n right = {\r\n type: \"Assignment\",\r\n left: temp_left,\r\n right: right,\r\n };\r\n }\r\n return right;\r\n }\r\n }",
"visitData_manipulation_language_statements(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function evaluate_array_literal(stmt,env) {\n var array = [];\n var elements = stmt.elements;\n var len = length(elements);\n for (var i = 0; i < len; i = i + 1) {\n array[i] = evaluate(head(elements), env);\n elements = tail(elements);\n }\n return array;\n}",
"function expressionToTree(exp) {\n \"use strict\";\n\n // get rid of spaces on the front of the expression\n var i = 0;\n\n while (1) {\n if (exp[i] === \"(\") {\n // we're dealing with a list\n break;\n } else if (exp[i] === \" \") {\n //do nothing\n } else {\n if (-1 !== exp.search(/\\(|\\)/)) {\n throw \"expression that didn't start with ( has either ( or ) in it\";\n }\n return exp.slice(i);\n }\n i++;\n }\n\n // at this point, we know we're dealing with a list\n var array_to_return = [];\n var start;\n var level = 0;\n var state = \"in_between\";\n\n\n // at this point, we know we're dealing with a list\n for (i++; i < exp.length; i++) {\n switch (state) {\n case \"in_between\":\n switch (exp[i]) {\n case \"(\":\n start = i;\n state = \"in_list\";\n break;\n case \")\":\n return array_to_return;\n case \" \":\n break;\n default:\n start = i;\n state = \"in_token\";\n }\n break;\n case \"in_token\":\n switch (exp[i]) {\n case \")\":\n array_to_return.push(exp.slice(start, i));\n return array_to_return;\n case \" \":\n array_to_return.push(exp.slice(start, i));\n state = \"in_between\";\n break;\n case \"(\":\n array_to_return.push(exp.slice(start, i));\n start = i;\n state = \"in_list\";\n break;\n }\n break;\n case \"in_list\":\n switch (exp[i]) {\n case \"(\":\n level++;\n break;\n case \")\":\n if (level === 0) {\n array_to_return.push(expressionToTree(exp.slice(start, i + 1)));\n state = \"in_between\";\n } else if (level > 0) {\n level--;\n } else {\n throw \"misformed list\";\n }\n break;\n }\n break;\n default:\n throw \"in a weird state\";\n }\n }\n throw \"misformed list\";\n}",
"ExpressionStatement() {\n const expression = this.Expression();\n this._eat(\";\");\n return factory.ExpressionStatement(expression);\n }",
"function removeExpr() {\r\n\r\n var sO = CurStepObj;\r\n var pos;\r\n\r\n // If an expression is active, we remove that expression AND activate\r\n // the space just before that removed expression (i.e., the sapce\r\n // id same as that of removed expression)\r\n //\r\n if (!sO.isSpaceActive) { // expression highlighted\r\n\r\n // console.log(\"no space\");\r\n\r\n pos = sO.activeChildPos;\r\n\r\n if (pos != ROOTPOS) {\r\n\r\n //console.log(\"not root\");\r\n\r\n // If we are deleting an arg of a function call, update the\r\n // header\r\n // \r\n var removed = true;\r\n if (sO.activeParentExpr.isUserFuncCall()) {\r\n removed = removeFuncArg(sO.activeParentExpr, pos);\r\n }\r\n\t //\r\n if (removed) {\r\n sO.activeParentExpr.exprArr.splice(pos, 1);\r\n sO.isSpaceActive = true; // activate space before removed expr\r\n }\r\n\r\n } else { // can't remove root str (e.g., if/else)\r\n\r\n\r\n if (sO.activeParentExpr.exprArr.length ||\r\n sO.activeParentExpr.isCondition()) {\r\n\r\n // Cannot delete non-empty 'foreach' OR any mask box \r\n //\r\n showTip(TipId.RootEdit);\r\n\r\n } else {\r\n\r\n // if no children, mark as deleted (e.g., bare 'foreach')\r\n //\r\n sO.activeParentExpr.deleted = DeletedState.Deleted;\r\n }\r\n }\r\n\r\n } else { // if space highlighted\r\n\r\n // console.log(\"space @\" + sO.activeChildPos);\r\n\r\n //pos = -1; // remove at very end by default\r\n\r\n if (sO.activeChildPos > 0) {\r\n pos = --sO.activeChildPos; // -- to move to previous space\r\n\r\n /*\r\n\t if (pos < 0) { // if we moved to ROOTPS\r\n\t\tsO.isSpaceActive = false; // space no longer active\r\n\t }\r\n\t */\r\n\r\n sO.activeParentExpr.exprArr.splice(pos, 1);\r\n }\r\n\r\n\r\n\r\n // var expr = sO.activeParentExpr.exprArr[pos];\r\n // if (expr.isDefinition()) expr.str = 'DELETED';\r\n\r\n\r\n\r\n }\r\n\r\n}",
"visitDel_stmt(ctx) {\r\n console.log(\"visitSivisitDel_stmt\");\r\n return { type: \"DeleteStatement\", deleted: this.visit(ctx.exprlist()) };\r\n }",
"visitCursor_expression(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"function evalNextParenthesizedExpression(expr){\n //find first and last index of subexpression\n let subexprStart = expr.indexOf(expr.find(element => (/^-?\\($/).test(element)));\n let subexprEnd;\n let bracketCount = 1;\n for (let index = subexprStart+1; index < expr.length; index++) {\n if ((/\\(/).test(expr[index])){\n bracketCount++;\n } else if(expr[index]===')') {\n bracketCount--;\n if (bracketCount===0) {\n subexprEnd = index;\n break;\n }\n } \n }\n\n //split array in it's parts with evaluated subexpr;\n const negative = expr[subexprStart][0] === '-';\n const subexpr = expr.slice(subexprStart+1, subexprEnd) \n const returnValue = [...expr.slice(0, subexprStart), \n (negative)?(operate('*', -1, evaluateInput(subexpr))):evaluateInput(subexpr), \n ...expr.slice(subexprEnd+1) ];\n return returnValue;\n \n}",
"parse_statement() {\n let values = this.find_some(this.parse_base_expr, tk.COMMA, tk.BAR); \n return Ex(pr.Statement, values);\n }",
"function restoreExprObj(eO, seqO, gBodyArr, gExprArr) {\r\n\r\n assert(seqO, \"seqO must be defined\");\r\n\r\n // Add all subexpressions required for ExprObj eO.\r\n //\r\n if (seqO.exprArrSeq) {\r\n\r\n for (var i = 0; i < seqO.exprArrSeq.length; i++) {\r\n\r\n assert((seqO.exprArrSeq[i].mySeq), \"must have seq #\");\r\n\r\n eO.exprArr.push(\r\n loadExprObj(seqO.exprArrSeq[i], gBodyArr, gExprArr)\r\n );\r\n }\r\n }\r\n\r\n // Now, flesh out other filds of eO \r\n\r\n var savedBody = gBodyArr[seqO.mySeq];\r\n\r\n assert(savedBody, \"No saved body for seq#: \" + seqO.mySeq);\r\n assert((savedBody.mySeq == eO.mySeq),\r\n \"seq #s of body and expr must match\");\r\n\r\n // Restore other fields from saved image\r\n //\r\n assert((savedBody.labelExprSeq.mySeq), \"labelexpr must have seq #\");\r\n\r\n eO.str = savedBody.str;\r\n\r\n eO.type = savedBody.type;\r\n\r\n eO.deleted = savedBody.deleted;\r\n\r\n eO.labelExpr = loadExprObj(savedBody.labelExprSeq, gBodyArr, gExprArr);\r\n //\r\n eO.dimIds = savedBody.dimIds.slice(0);\r\n\r\n eO.selDim = savedBody.selDim;\r\n\r\n // The following has to be set in restoreGridObjInExprs after all\r\n // grids of the function are loaded\r\n //\r\n eO.gO = null;\r\n\r\n // TODO: restore all required fields\r\n}",
"ArgumentList() {\n const argumentList = [];\n do {\n argumentList.push(this.AssignmentExpression());\n } while (this._lookahead.type === \",\" && this._eat(\",\"));\n\n return argumentList;\n }",
"function ExpressionParser() {\n \t\tthis.parse = function() {\n\t \t\treturn Statement(); \n\t \t}\n \t\t\n//\t\tStatement := Assignment | Expr\t\n\t\tthis.Statement=function() {return Statement();}\n\t \tfunction Statement() {\n\t \t\tdebugMsg(\"ExpressionParser : Statement\");\n\t\n \t var ast;\n \t // Expressin or Assignment ??\n \t if (lexer.skipLookAhead().type==\"assignmentOperator\") {\n \t \tast = Assignment(); \n \t } else {\n \t \tast = Expr();\n \t }\n \t return ast;\n\t \t}\n\t \t\n//\t\tAssignment := IdentSequence \"=\" Expr \n//\t\tAST: \"=\": l:target, r:source\n \t\tthis.Assignment = function() {return Assignment();}\n \t\tfunction Assignment() {\n \t\t\tdebugMsg(\"ExpressionParser : Assignment\");\n \t\t\n \t\t\tvar ident=IdentSequence();\n \t\t\tif (!ident) return false;\n \t\t\n \t\t\tcheck(\"=\"); // Return if it's not an Assignment\n \t\t\n \t\t\tvar expr=Expr();\n \t\t\t\n \t\t\treturn new ASTBinaryNode(\"=\",ident,expr);\n\t \t}\n \t\t\n\n//\t\tExpr := And {\"|\" And} \t\n//\t\tAST: \"|\": \"left\":And \"right\":And\n \t\tthis.Expr = function () {return Expr();}\t\n \t\tfunction Expr() {\n \t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\n \t\t\tvar ast=And();\n \t\t\tif (!ast) return false;\n \t\t\t\t\t\n \t\t\n \t\t\twhile (test(\"|\") && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Expr\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"|\",ast,And());\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n \t\n//\t\tAnd := Comparison {\"&\" Comparison}\n//\t\tAST: \"&\": \"left\":Comparasion \"right\":Comparasion\t\n\t\tfunction And() {\n \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\tvar ast=Comparasion();\n \t\t\tif (!ast) return false;\n \t\t\t\t\n \t\t\twhile (test(\"&\") && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : And\");\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(\"&\",ast,Comparasion());\n\t \t\t}\n\t \t\treturn ast;\n\t \t}\n\t \t \t\n// \t\tComparison := Sum {(\"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" | \"in\") Sum}\n//\t\tAST: \"==\" | \"!=\" | \"<=\" | \">=\" | \"<\" | \">\" : \"left\":Sum \"right\":Sum\n\t\tfunction Comparasion() {\n \t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\tvar ast=Sum();\n\t\t\tif (!ast) return false;\n\t\t\n\t\t\twhile ((test(\"==\") ||\n\t\t\t\t\ttest(\"!=\") ||\n\t\t\t\t\ttest(\"<=\") ||\n\t\t\t\t\ttest(\">=\") ||\n\t\t\t\t\ttest(\"<\") ||\n\t\t\t\t\ttest(\">\")) ||\n\t\t\t\t\ttest(\"in\") &&\n\t\t\t\t\t!eof())\n\t\t\t{\n \t\t\t\tdebugMsg(\"ExpressionParser : Comparasion\");\n\t\t\t\tvar symbol=lexer.current.content;\n\t\t\t\tlexer.next();\n\t \t\t\tast=new ASTBinaryNode(symbol,ast,Sum());\n\t\t\t} \t\n\t\t\treturn ast;\t\n\t \t}\n\t \t\n//\t\tSum := [\"+\" | \"-\"] Product {(\"+\" | \"-\") Product}\n//\t\tAST: \"+1\" | \"-1\" : l:Product\n//\t\tAST: \"+\" | \"-\" : l:Product | r:Product \n \t\tfunction Sum() {\n \t\t\tdebugMsg(\"ExpressionParser : Sum\");\n\t\t\n\t\t\tvar ast;\n\t\t\t// Handle Leading Sign\n\t\t\tif (test(\"+\") || test(\"-\")) {\n\t\t\t\tvar sign=lexer.current.content+\"1\";\n\t\t\t\tlexer.next();\n\t\t\t\tast=new ASTUnaryNode(sign,Product());\t\n\t \t\t} else {\n\t \t\t\tast=Product();\n\t \t\t} \n \t\t\t\n \t\t\twhile ((test(\"+\") || test(\"-\")) && !eof()) {\n \t\t\t\tdebugMsg(\"ExpressionParser : Sum\");\n \t\t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Product());\t\t\n \t\t\t} \t\n \t\t\treturn ast;\n \t\t}\n\n//\t\tProduct := Factor {(\"*\" | \"/\" | \"%\") Factor} \t\n\t \tfunction Product() {\n\t \t\tdebugMsg(\"ExpressionParser : Product\");\n\n \t\t\tvar ast=Factor();\n \t\t\n\t \t\twhile ((test(\"*\") || test(\"/\") || test(\"%\")) && !eof()) {\n\t \t\t\tdebugMsg(\"ExpressionParser : Product\");\n\n\t \t\t\tvar symbol=lexer.current.content;\n \t\t\t\tlexer.next();\n \t\t\t\tast=new ASTBinaryNode(symbol,ast,Factor());\n \t\t\t} \n\t \t\treturn ast;\n \t\t}\n \t\t\n// \t Factor := \t\t[(\"this\" | \"super\") \".\"]IdentSequence [\"(\" [Expr {\",\" Expr}] \")\"]\n//\t\t\t\t\t | \"!\" Expr \n//\t\t\t\t\t | \"(\" Expr \")\" \n//\t\t\t\t\t | Array \n//\t\t\t\t\t | Boolean\n//\t\t\t\t\t | Integer\n//\t\t\t\t\t | Number\n//\t\t\t\t\t | Character\n//\t\t\t\t\t | String \n \t\tfunction Factor() {\n \t\t\tdebugMsg(\"ExpressionParser : Factor\"+lexer.current.type);\n\n\t \t\tvar ast;\n \t\t\n\t \t\tswitch (lexer.current.type) {\n\t \t\t\t\n\t \t\t\tcase \"token\"\t:\n\t\t\t\t//\tAST: \"functionCall\": l:Ident(Name) r: [0..x]{Params}\n\t\t\t\t\tswitch (lexer.current.content) {\n\t\t\t\t\t\tcase \"new\": \n\t\t\t\t\t\t\tlexer.next();\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar ident=Ident(true);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tcheck(\"(\");\n\t\t\t\t\t\t\n \t\t\t\t\t\t\tvar param=[];\n \t\t\t\t\t\t\tif(!test(\")\")){\n \t\t\t\t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\t\t\tparam[i]=Expr();\n \t\t\t\t\t\t\t\t}\n \t\t\t\t\t\t\t}\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\n \t\t\t\t\t\t\tast=new ASTBinaryNode(\"new\",ident,param);\n \t\t\t\t\t\tbreak;\n \t\t\t\t\t\tcase \"this\":\n \t\t\t\t\t\tcase \"super\":\n\t\t\t\t\t\tcase \"constructor\": return IdentSequence();\n \t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\tbreak;\n\n//\t\t\t\tFactor :=\tIdentSequence \t\t\t\t\n \t\t\t\tcase \"ident\":\n \t\t\t\t return IdentSequence();\n \t\t\t\tbreak;\n \t\t\t\t\n// \t\t\tFactor:= \"!\" Expr\t\t\t\n \t\t\t\tcase \"operator\": \n\t \t\t\t\tif (!test(\"!\")) {\n\t \t\t\t\t\terror.expressionExpected();\n\t \t\t\t\t\treturn false;\n \t\t\t\t\t}\n \t\t\t\t\tlexer.next();\n \t\t\t\t\n\t \t\t\t\tvar expr=Expr();\n \t\t\t\t\tast=new ASTUnaryNode(\"!\",expr);\n\t \t\t\tbreak;\n \t\t\t\t\n//\t\t\t\tFactor:= \"(\" Expr \")\" | Array \t\t\t\n \t\t\t\tcase \"brace\"\t:\n \t\t\t\t\tswitch (lexer.current.content) {\n \t\t\t\t\t\t\n// \t\t\t\t\t \"(\" Expr \")\"\n \t\t\t\t\t\tcase \"(\":\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\tast=Expr();\t\t\t\t\t\n \t\t\t\t\t\t\tcheck(\")\");\n \t\t\t\t\t\tbreak;\n \t\n \t\t\t\t\t\n \t\t\t\t\t\tdefault:\n \t\t\t\t\t\t\terror.expressionExpected();\n \t\t\t\t\t\t \treturn false;\n\t \t\t\t\t\tbreak;\n\t \t\t\t\t}\n\t \t\t\tbreak;\n \t\t\t\n//\t\t\t\tFactor:= Boolean | Integer | Number | Character | String\n//\t\t\t\tAST: \"literal\": l: \"bool\" | \"int\" | \"float\" | \"string\" | \"char\": content: Value \n\t \t\t\tcase \"_$boolean\" \t\t:\t\t\t\n\t \t\t\tcase \"_$integer\" \t\t:\n\t \t\t\tcase \"_$number\" \t\t:\n\t \t\t\tcase \"_$string\"\t\t\t:\t\t\n\t\t\t\tcase \"_$character\"\t\t:\n\t\t\t\tcase \"null\"\t\t\t\t:\n\t\t\t\t\t\t\t\t\t\t\tast=new ASTUnaryNode(\"literal\",lexer.current);\n \t\t\t\t\t\t\t\t\t\t\tlexer.next();\n \t\t\t\tbreak;\n\t\t\t\t\n//\t\t\t\tNot A Factor \t\t\t\t \t\t\t\t\n \t\t\t\tdefault: \terror.expressionExpected();\n \t\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\t\treturn false;\n\t \t\t\t\t\t\tbreak;\n \t\t\t}\n \t\t\treturn ast;\n \t\t}\n\n \n//\t\tIdentSequence := (\"this\" | \"super\") | [(\"this\" | \"super\") \".\"] (\"constructor\" \"(\" [Expr {\",\" Expr}] \")\" | Ident {{ArrayIndex} | \".\" Ident } [\"(\" [Expr {\",\" Expr}] \")\"]);\n//\t\tAST: \"identSequence\": l: [0..x][\"_$this\"|\"_$super\"](\"constructor\" | Ident{Ident | ArrayIndex})\n// \t\tor AST: \"functionCall\": l:AST IdentSequence(Name), r: [0..x]{Params}\n\t\tthis.IdentSequence=function () {return IdentSequence();};\n \t\tfunction IdentSequence() {\n \t\t\tdebugMsg(\"ExpressionParser:IdentSequence()\");\n \t\t\t\n \t\t\tvar ast=new ASTListNode(\"identSequence\");\n \t\t\tif (test(\"this\") || test(\"super\")) {\n \t\t\t\tast.add({\"type\":\"ident\",\"content\":\"_$\"+lexer.current.content,\"line\":lexer.current.line,\"column\":lexer.current.column});\n \t\t\t\tlexer.next();\n \t\t\t\tif (!(test(\".\"))) return ast;\n \t\t\t\tlexer.next();\n \t\t\t}\n\n\t\t\tvar functionCall=false;\n\t\t\tif (test(\"constructor\")) {\n\t\t\t\tast.add({\"type\":\"ident\",\"content\":\"construct\",\"line\":lexer.current.line,\"column\":lexer.current.column});\n\t\t\t\tlexer.next();\n\t\t\t\tcheck(\"(\");\n\t\t\t\tfunctionCall=true;\n\t\t\t} else {\n \t\t\t\tvar ident=Ident(true);\n \t\t\t\n \t\t\t\tast.add(ident);\n \t\t\t\n \t\t\t\tvar index;\n \t\t\t\twhile((test(\".\") || test(\"[\")) && !eof()) {\n \t\t\t\t\t if (test(\".\")) {\n \t\t\t\t\t \tlexer.next();\n \t\t\t\t\t\tast.add(Ident(true));\n \t\t\t\t\t} else ast.add(ArrayIndex());\n \t\t\t\t}\n \t\t\t\tif (test(\"(\")) {\n \t\t\t\t\tfunctionCall=true;\n \t\t\t\t\tlexer.next();\n \t\t\t\t}\n \t\t\t}\n \t\n \t\t\tif (functionCall) {\t\n\t\t\t\tvar param=[];\n\t\t\t\tif(!test(\")\")){\n \t\t\t\t\tparam[0]=Expr();\n\t\t\t\t\tfor (var i=1;test(\",\") && !eof();i++) {\n\t\t\t\t\t\tlexer.next();\n \t\t\t\t\t\tparam[i]=Expr();\t\t\t\t\t\t\t\n \t\t\t\t\t}\n \t\t\t\t}\t \t\t\t\t\t\t\t\t\t\n \t\t\t\tcheck(\")\");\n \t\t\t\tast=new ASTBinaryNode(\"functionCall\",ast,param);\n \t\t\t} \n \t\t\treturn ast;\n \t\t}\n \t\t\n //\t\tArrayIndex:=\"[\" Expr \"]\"\n //\t\tAST: \"arrayIndex\": l: Expr\n \t\tfunction ArrayIndex(){\n \t\t\tdebugMsg(\"ExpressionParser : ArrayIndex\");\n \t\t\tcheck(\"[\");\n \t\t\t \t\t\t\n \t\t\tvar expr=Expr();\n \t\t\n \t\t\tcheck(\"]\");\n \t\t\t\n \t\t\treturn new ASTUnaryNode(\"arrayIndex\",expr);\n \t\t}\n\n//\t\tIdent := Letter {Letter | Digit | \"_\"}\n//\t\tAST: \"ident\", \"content\":Ident\n\t \tthis.Ident=function(forced) {return Ident(forced);}\n \t\tfunction Ident(forced) {\n \t\t\tdebugMsg(\"ExpressionParser:Ident(\"+forced+\")\");\n \t\t\tif (testType(\"ident\")) {\n \t\t\t\tvar ast=lexer.current;\n \t\t\t\tlexer.next();\n \t\t\t\treturn ast;\n \t\t\t} else {\n \t\t\t\tif (!forced) return false; \n \t\t\t\telse { \n \t\t\t\t\terror.identifierExpected();\n\t\t\t\t\treturn SystemIdentifier();\n\t\t\t\t}\n\t\t\t} \t\n \t\t}\n \t}",
"function replaceOrAppendExpr(newExpr) {\r\n\r\n var sO = CurStepObj;\r\n var pos;\r\n\r\n // if there is no active parent expression, nothing to replace. This\r\n // could happen when the focus is not on a code box\r\n //\r\n if (!sO.activeParentExpr)\r\n return;\r\n\r\n\r\n // If an expression is active, we replace that expression with\r\n // newExpr. If a space is active, we append newExpr (replace space)\r\n //\r\n if (!sO.isSpaceActive) { // expression highlighted\r\n\r\n pos = sO.activeChildPos;\r\n\r\n if (pos != ROOTPOS) {\r\n\r\n if (sO.activeParentExpr.isUserFuncCall()) {\r\n\r\n // if we are replacing an arg in a function call, handle it\r\n //\r\n replaceFuncArg(sO.activeParentExpr, pos, newExpr);\r\n\r\n } else {\r\n\r\n // Replace existing expression\r\n //\r\n //sO.activeParentExpr.exprArr.splice(pos, 1, newExpr);\r\n\r\n\t\t//KK: Removed above and added three following ones, to\r\n\t\t// make uniform indexing, now each index is a concat\r\n\t\t// (type 12) and contains anything else as sub-expression\r\n\t\t//TODO: CAUTION: Make sure compatible with rest of the\r\n\t\t// program (code-gen and parallelism detection)!\r\n\r\n \t\tvar concExpr = new ExprObj(false, ExprType.Concat, \"\");\r\n \t\tsO.activeParentExpr.exprArr.splice(pos,1,concExpr);\r\n \t\tsO.activeParentExpr.exprArr[pos].addSubExpr(newExpr);\r\n\r\n\r\n\r\n if (sO.activeParentExpr.isGridCell()) {\r\n\r\n // Write invalid index to 0th dim\r\n //\r\n sO.activeParentExpr.dimIds[0] = -1;\r\n showTip(TipId.CellIndReplace);\r\n logMsg(\r\n \"Removed cell highlight dueto manual arr expr edit\"\r\n );\r\n }\r\n }\r\n\r\n\t} else {\r\n\t showTip(TipId.RootEdit); // can't replace root str (e.g., if)\r\n\t}\r\n\r\n } else { // if space highlighted\r\n\t\r\n\tpos = -1; // append at very end by default\r\n\r\n\tif (sO.activeChildPos >= 0) {\r\n\t pos = sO.activeChildPos; \r\n\t}\r\n\r\n\t// When a space is active, by default, we append the expression\r\n\t// at that space. However, if the space is next to an existing\r\n\t// single character operator, see whether we should combine them\r\n\t// to form a two char operator like +=, -=, ==, etc.\r\n\t// NOTE: A space and the *following* expression share the same\r\n\t// child ID.\r\n\t//\r\n\tvar exparr = sO.activeParentExpr.exprArr;\r\n\r\n if (newExpr.isAssignOp() && (pos > 0) &&\r\n exparr[pos - 1].isUniOperator()) {\r\n\r\n // if the new expression is an assignment operator (single = sign)\r\n // AND the preceding is a single character operator, combine\r\n // them to form a two char operator -- e.g., +=, ==, -=\r\n\r\n exparr[pos - 1].str += newExpr.str;\r\n\r\n } else if (newExpr.isUniOperator() && (pos < exparr.length) &&\r\n exparr[pos].isAssignOp()) {\r\n\r\n // new expression is an single operator (e.g., +/-/..) and the \r\n // following is the assignement operator, combine them \r\n // -- e.g., +=, -=, ==\r\n // NOTE: We add to the expression at 'pos' (not pos+1) because\r\n // 'pos' is the position of space. A space and the \r\n // following expression share the same child ID. \r\n //\r\n exparr[pos].str = newExpr.str + exparr[pos].str;\r\n\r\n } else { // general case\r\n\r\n // Add new expression at the given position\r\n //\r\n exparr.splice(pos, 0, newExpr);\r\n //\r\n // If we are adding an arg to a function call, process argument\r\n // addition -- i.e., insert args into corresponding function \r\n // header\r\n // \r\n if (sO.activeParentExpr.isUserFuncCall()) {\r\n\r\n insertFuncArg(sO.activeParentExpr, pos);\r\n }\r\n\r\n sO.activeChildPos++; // move space to next since we appended\r\n }\r\n }\r\n}",
"function restoreGridObjInExprs(gExprArr, gExprBodyArr, mO) {\r\n\r\n // Go thru all ExprObjs (in gExprArr) we loaded\r\n //\r\n for (var i = 0; i < gExprArr.length; i++) {\r\n\r\n\t// If the ExprObj is valid\r\n\t//\r\n\tif (gExprArr[i] && (gExprArr[i].mySeq > 0) ) {\r\n\r\n\t var seq = gExprArr[i].mySeq; // expr seq #\r\n\t var body = gExprBodyArr[seq]; // body of the expr\r\n\t var fid = body.fOId; // func id recoreded in body\r\n\r\n\t assert((seq == body.mySeq), \"Seq # mismatch\");\r\n\r\n\t var gId = body.gOId; // grid id corresponding \r\n\t \r\n\t if (gId >= 0) { // if grid Id is valid\r\n\r\n\t\tvar fO = mO.allFuncs[fid]; // fO corresponding to fid\r\n\t\tassert((fid < mO.allFuncs.length), \"invalid func id\");\r\n\r\n\t\tassert((gId < fO.allGrids.length), \"invalid grid id\");\r\n\t\tvar gO = fO.allGrids[gId]; \r\n\t\tgExprArr[seq].gO = gO; // set gO in ExprObj\r\n\r\n\t\r\n\t\tassert((mO.allFuncs[fid].allGrids[gId] == gO),\r\n\t\t \"fid:gId does not match with grid object\"); \r\n\r\n\r\n\t\t//alert(\"Set gO in expr\");\r\n\t }\r\n\t}\r\n }\r\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
member function hitCeiling(ypos) applies a collision between the player and a ceiling params: pos:Number the yposition of the ceiling | hitCeiling(ypos){
if(this.vel.y > 0)
return;
this.pos.y = ypos + this.getCol().size.y / 2 + .01;
this.vel.y = 0;
this.onCeil = true;
} | [
"hitGround(ypos){\n\t\t//console.log(this.vel);\n\t\t//console.log(this.pos.x);\n\t\tif(Math.abs(this.vel.y) > 2)\n\t\t\tsfx_enemybump.play();\n\t\tthis.pos.y = ypos - this.getCol().size.y / 2;\n\t\tthis.vel.y = -this.bounceFriction * Math.abs(this.vel.y);\n\t\tif(!this.seeking)\n\t\t\tthis.mov = Math.PI / -2;\n\t}",
"hitGround(ypos){\n\t\t//console.log(this.vel);\n\t\t//console.log(this.pos.x);\n\t\tthis.pos.y = ypos - this.getCol().size.y / 2;\n\t\tif(Math.abs(this.vel.y) > 5)\n\t\tsfx_bump.play();\n\t\tthis.vel.y = 0;\n\t\tthis.canJump = true;\n\t}",
"hitBox(collision){\n\t\tswitch(collision.closestEdge(this.pos.minus(new vec2(this.vel.x, 0)))){\n\t\t\tcase 't': this.hitGround(collision.top()); break;\n\t\t\tcase 'l': this.hitRWall(collision.left()); break;\n\t\t\tcase 'r': this.hitLWall(collision.right()); break;\n\t\t\tcase 'b': this.hitCeiling(collision.bottom()); break;\n\t\t}\n\t}",
"collideEnemyWall() {\n if (this.enemyX < 0) {\n this.inverseVelocity();\n }\n if (this.enemyX > width - this.enemyWidth) {\n this.inverseVelocity();\n }\n if (this.enemyY < 0) {\n this.inverseVelocity();\n }\n if (this.enemyY > height - this.enemyHeight) {\n this.inverseVelocity();\n }\n }",
"function checkCollision(x, y, w, h) {\n if( (chickenX + chickenSize) >= x && \n (chickenY + chickenSize) >= y && \n (chickenX) <= (x + w) && \n (chickenY) <= (y + h)){\n return true;\n } else {\n return false;\n }\n}",
"handleCollisions() {\n //find distance between player and bullet and if close enough, player takes damage\n //and bullet resets\n let d = dist(player.x, player.y, this.x, this.y)\n if ((d < this.exitSize / 2) && this.size >= (this.exitSize - this.exitSize / 6)) {\n //take damage\n player.health -= 20;\n //play sound\n audPlayerHit.play();\n this.explosionHit = 255\n this.reset();\n }\n }",
"function ballWallCollision(){\r\n if(ball.x + ball.radius > cvs.width || ball.x - ball.radius < 0){\r\n ball.dx = - ball.dx;\r\n choque.play();\r\n }\r\n\r\n if(ball.y - ball.radius < 0){\r\n ball.dy = -ball.dy;\r\n choque.play();\r\n }\r\n\r\n if(ball.y + ball.radius > cvs.height){\r\n vidas--; // LOSE LIFE\r\n vidaPerdida.play();\r\n resetBall();\r\n }\r\n}",
"function checkBoundries() {\n if (x > 560) { // if ship is more than the right of the screen\n rightMove = false; // stop it moving\n } else if (x < 40) { // if ship is more than the left of the screen\n moveLeft = false; // stop it moving\n }\n if (y > 560) { // if ship is more than the bottom of the screen\n downmove = false; // stop it moving\n } else if (y < 30) { // if ship is more than the top of the screen\n upmove = false; // stop it moving\n }\n}",
"hitRWall(xpos){\n\t\tif(Math.abs(this.vel.x) > 2)\n\t\t\tsfx_enemybump.play();\n\t\tthis.pos.x = xpos - this.getCol().size.x / 2;\n\t\tthis.vel.x = -this.bounceFriction * Math.abs(this.vel.x);\n\t\tif(!this.seeking)\n\t\t\tthis.mov = Math.PI;\n\t}",
"hitLWall(xpos){\n\t\tif(Math.abs(this.vel.x) > 2)\n\t\t\tsfx_enemybump.play();\n\t\tthis.pos.x = xpos + this.getCol().size.x / 2;\n\t\tthis.vel.x = this.bounceFriction * Math.abs(this.vel.x);\n\t\tif(!this.seeking)\n\t\t\tthis.mov = 0;\n\t}",
"function checkCollision(location, collisionDistance) {\n //first have to project...\n var locationProj = getScreenCoords(location);\n if (!locationProj)\n return true;\n\n var hitTestResult = ge.getView().hitTest(locationProj[0], ge.UNITS_PIXELS, locationProj[1], ge.UNITS_PIXELS, ge.HIT_TEST_BUILDINGS);\n //var hitTestResult = ge.getView().hitTest(0.5, ge.UNITS_FRACTION, 0.75, ge.UNITS_FRACTION, ge.HIT_TEST_BUILDINGS); //0.75 is a guestemate. Not worth calculating\n if (hitTestResult) {\n var charGLat = new GLatLng(me.characterLla[0], me.characterLla[1]);\n var distFromResult = charGLat.distanceFrom(new GLatLng(hitTestResult.getLatitude(), hitTestResult.getLongitude()));\n if (distFromResult < DISTANCE_FROM_COLLISION) {\n currentSpeed = 0;\n return true;\n }\n }\n return false;\n}",
"function ballCollision() {\n if(ball.yPos > height - ball.radius) {\n ball.yPos = height - ball.radius;\n ball.vy *= -1;\n }\n else if(ball.yPos < ball.radius/2) {\n ball.yPos = ball.radius/2;\n ball.vy *= -1;\n }\n}",
"function isColliding(x1, y1, x2, y2, sr){\n var dx = x2 - x1;\n var dy = y2 - y1;\n var dr = sr + 50;\n\n if(dx === 0 && dy === 0){\n return false;\n } else {\n return (Math.pow(dx, 2) + Math.pow(dy, 2)) < Math.pow(dr, 2);\n }\n}",
"function carHit(){\r\n\tfor (var i=0;i<enemyCar.length;i++){\r\n\t\tif ((enemyCar[i][0]<=carX) && (carX<=enemyCar[i][0]+carWidth)){\r\n\t\t\tif ((enemyCar[i][1]<=carY) && (carY<=enemyCar[i][1]+carHeight))\thit();\r\n\t\t\telse if ((enemyCar[i][1]<=(carY+100)) && ((carY+100)<=enemyCar[i][1]+carHeight)) hit();\r\n\t\t}else if ((enemyCar[i][0]<=(carX+40)) && ((carX+40)<=enemyCar[i][0]+carWidth)){\r\n\t\t\tif ((enemyCar[i][1]<=carY) && (carY<=enemyCar[i][1]+carHeight))\thit();\r\n\t\t\telse if ((enemyCar[i][1]<=(carY+100)) && ((carY+100)<=enemyCar[i][1]+carHeight)) hit();\r\n\t\t}\r\n\t}\r\n}",
"function checkBorderCollision() {\r\n //Player\r\n if (player_x >= (canvas_w - player_w)) rightKey = false;\r\n if (player_x <= (0)) leftKey = false;\r\n if (player_y <= (0)) upKey = false;\r\n if (player_y >= (canvas_h - player_h)) downKey = false;\r\n\r\n //AI\r\n if (AI_x >= (canvas_w - AI_w)) rightAI = false;\r\n if (AI_x <= (0)) leftAI = false;\r\n if (AI_y <= (0)) upAI = false;\r\n if (AI_y >= (canvas_h - AI_h)) downAI = false;\r\n}",
"function solidCollision(myObj, myObj2) {\n\tif((myObj2.x > (myObj.x + myObj.width)-2) || (myObj.x > (myObj2.x + myObj2.width) -2)) {\n\t\tif (myObj2.x > myObj.x){\n\t\t\tif(myObj2.speedX < 0){\n\t\t\t\tmyObj2.speedX = 0;\n\t\t\t}\n\t\t} else if (myObj2.x < myObj.x){\n\t\t\tif(myObj2.speedX > 0){\n\t\t\t\tmyObj2.speedX = 0;\n\t\t\t}\n\t\t}\n\t}\n\t\n\telse if((myObj2.y > (myObj.y + myObj.height) -2) || (myObj.y > (myObj2.y + myObj2.height) -2)){\n\t\tif (myObj2.y < myObj.y){\n\t\t\tif(myObj2.speedY > 0){\n\t\t\t\tmyObj2.speedY = 0;\n\t\t\t}\n\t\t}\n\t\tif (myObj2.y > myObj.y){\n\t\t\tif(myObj2.speedY < 0){\n\t\t\t\tmyObj2.speedY = 0;\n\t\t\t}\n\t\t}\n\t}\n}",
"hitLWall(xpos){\n\t\tthis.pos.x = xpos + this.getCol().size.x / 2;\n\t\tthis.vel.x = 0;\n\t}",
"function ballBoundary(){\n ballX = ballX + directionX;\n ballY = ballY + directionY;\n if (ballY >= (windowHeight - 5) || ballY <= 45){\n directionY = directionY * -1;\n }\n}",
"function playerShipAndEnemyCollisionDetection(elapsedTime){\r\n\t\tvar xDiff = myShip.getSpecs().center.x - enemyShip.getSpecs().center.x;\r\n\t\tvar yDiff = myShip.getSpecs().center.y - enemyShip.getSpecs().center.y;\r\n\t\tvar distance = Math.sqrt((xDiff * xDiff) + (yDiff*yDiff));\r\n\r\n\t\tif(distance < myShip.getSpecs().radius + enemyShip.getSpecs().radius){\r\n\t\t\t\r\n\t\t\tparticleGenerator.createShipExplosions(elapsedTime,myShip.getSpecs().center);\r\n\r\n\t\t\tmyShip.getSpecs().hit = true;\r\n\t\t\tmyShip.getSpecs().center.x = canvas.width+20;\r\n\t\t\tmyShip.getSpecs().center.y = canvas.height+20;\r\n\t\t\tmyShip.getSpecs().reset = true;\r\n\t\t\tplayerShipDestroyedAudio.play();\r\n\t\t}\r\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
like bake, but doesn't save new tags the name isn't descriptive, but: (1) I didn't want to complicate the signature of bake() with optional params (2) you come up with a name that isn't half a sentence findOrMake vs. findOrCreate? | static async fry(name, db) {
db = db || Model.__db;
const existing = await Tag_1.byName(name, db);
if (existing)
return existing;
await NoneReady;
const tag = new Tag_1(name, TagCategory.None);
tag._db = db;
return tag;
} | [
"function saveTags(id, tags) {\n tags = tags.trim().split(\",\") //turn comma separated list into array\n tags.forEach(tag => {\n insert_tag.run(tag.trim()) //create tag if it doesn't exist\n insert_docTag.run(id, tag) //add tag to document\n });\n}",
"function wrap( make, options ) {\n\n function getMakeInstance() {\n if ( !getMakeInstance.instance ) {\n getMakeInstance.instance = Make( options );\n }\n return getMakeInstance.instance;\n }\n\n // Lazily extract various tags types as needed, and memoize.\n function lazyInitTags( o, name, regexp ) {\n delete o[ name ];\n var tags = [];\n make.tags.forEach( function( tag ) {\n if( regexp.test( tag ) ) {\n tags.push( tag );\n }\n });\n o[ name ] = tags;\n return tags;\n }\n\n var wrapped = {\n // Application Tags are \"webmaker.org:foo\", which means two\n // strings, joined with a ':', and the first string does not\n // contain an '@'\n get appTags() {\n return lazyInitTags( this, 'appTags', /^[^@]+\\:[^:]+/ );\n },\n\n // User Tags are \"some@something.com:foo\", which means two\n // strings, joined with a ':', and the first string contains\n // an email address (i.e., an '@').\n get userTags() {\n return lazyInitTags( this, 'userTags', /^[^@]+@[^@]+\\:[^:]+/ );\n },\n\n // Raw Tags are \"foo\" or \"#fooBar\", which means one string\n // which does not include a colon.\n get rawTags() {\n return lazyInitTags( this, 'rawTags', /^[^:]+$/ );\n },\n\n // Determine whether this make is tagged with any of the tags\n // passed into `tags`. This can be a String or [ String ],\n // and the logic is OR vs. AND for multiple.\n taggedWithAny: function( tags ) {\n var any = false,\n all = make.tags;\n tags = Array.isArray( tags ) ? tags : [ tags ];\n for( var i = 0; i < tags.length; i++ ) {\n if ( all.indexOf( tags[ i ] ) > -1 ) {\n return true;\n }\n }\n return false;\n },\n\n // Get a list of other makes that were remixed from this make.\n // The current make's URL is used as a key.\n remixes: function( callback ) {\n callback = callback || function(){};\n getMakeInstance()\n .find({ remixedFrom: wrapped._id })\n .then( callback );\n },\n\n // Similar to remixes(), but filter out only those remixes that\n // have a different locale (i.e., are localized versions of this\n // make).\n locales: function( callback ) {\n callback = callback || function(){};\n this.remixes( function( err, results ) {\n if( err ) {\n callback( err );\n return;\n }\n var locales = [];\n results.forEach( function( one ) {\n if ( one.locale !== wrapped.locale ) {\n locales.push( one );\n }\n });\n callback( null, locales );\n });\n },\n\n // Get the original make used to create this remix. Null is sent\n // back in the callback if there was no original (not a remix)\n original: function( callback ) {\n callback = callback || function(){};\n if ( !wrapped.remixedFrom ) {\n callback( null, null );\n return;\n }\n getMakeInstance()\n .find({ _id: wrapped._id })\n .then( callback );\n },\n\n update: function( email, callback ) {\n callback = callback || function(){};\n getMakeInstance()\n .update( wrapped._id, wrapped, callback );\n }\n\n };\n\n // Extend wrapped with contents of make\n [ \"url\", \"contentType\", \"locale\", \"title\",\n \"description\", \"author\", \"published\", \"tags\", \"thumbnail\",\n \"username\", \"remixedFrom\", \"_id\", \"emailHash\", \"createdAt\",\n \"updatedAt\", \"likes\", \"reports\" ].forEach( function( prop ) {\n wrapped[ prop ] = make[ prop ];\n });\n\n // Virtuals will only be exposed while still on the server end\n // forcing us to still manually expose it for client side users.\n wrapped.id = wrapped._id;\n\n return wrapped;\n }",
"function createPet(name, species, well_behaved) {\n return {name, species, well_behaved};\n}",
"async getOrCreateBasket() {\n const customerBaskets = await api.shopperCustomers.getCustomerBaskets({\n parameters: {customerId: customer?.customerId}\n })\n\n if (Array.isArray(customerBaskets?.baskets)) {\n return setBasket(customerBaskets.baskets[0])\n }\n\n // Back to using ShopperBaskets for all basket interaction.\n const newBasket = await api.shopperBaskets.createBasket({})\n setBasket(newBasket)\n }",
"findBookAndMergeShelf(allBooks, searchBook) {\n const propShelf = 'shelf';\n const userBook = allBooks.find(book => book.id === searchBook.id);\n searchBook[propShelf] = userBook ? userBook[propShelf] : 'none';\n }",
"function Make() {\n this.makeName = \"BMW\";\n}",
"function makeBobKey() {\n bobKey = false;\n let p = document.getElementById(\"bobP\").value;\n let q = document.getElementById(\"bobQ\").value;\n let e = document.getElementById(\"bobE\").value;\n keygen(\"bob\", p, q, e);\n }",
"async _saveBlogTags() {\n for (const [key, tags] of Object.entries(this.blogTagsPerBlogPost)) {\n const proms = tags.filter(tag => typeof tag.id === 'string').map(tag => {\n return this._rpc({\n model: 'blog.tag',\n method: 'create',\n args: [{\n 'name': tag.name,\n }],\n });\n });\n const createdIDs = await Promise.all(proms);\n\n await this._rpc({\n model: 'blog.post',\n method: 'write',\n args: [parseInt(key), {\n 'tag_ids': [[6, 0, tags.filter(tag => typeof tag.id === 'number').map(tag => tag.id).concat(createdIDs)]],\n }],\n });\n }\n }",
"tagFromInput(ignoreSearchResults = false) {\n if (this.composing) return;\n\n // If we're choosing a tag from the search results\n if (this.searchResults.length && this.searchSelection >= 0 && !ignoreSearchResults) {\n this.tagFromSearch(this.searchResults[this.searchSelection]);\n\n this.input = '';\n } else {\n // If we're adding an unexisting tag\n let text = this.input.trim();\n\n // If the new tag is not an empty string and passes validation\n if (!this.onlyExistingTags && text.length && this.validate(text)) {\n this.input = '';\n\n // Determine if the inputted tag exists in the typeagedTags\n // array\n let newTag = {\n [this.idField]: '',\n [this.textField]: text\n };\n\n const searchQuery = this.escapeRegExp(\n this.caseSensitiveTags\n ? newTag[this.textField]\n : newTag[this.textField].toLowerCase()\n );\n\n for (let tag of this.typeaheadTags) {\n const compareable = this.escapeRegExp(\n this.caseSensitiveTags\n ? tag[this.textField]\n : tag[this.textField].toLowerCase()\n );\n\n if (searchQuery === compareable) {\n newTag = Object.assign({}, tag);\n\n break;\n }\n }\n\n this.addTag(newTag);\n }\n }\n }",
"function write_tag(category=\"\",item=\"\"){\n if(document.getElementById(\"selected_tags\").value.indexOf(item)!==-1){\n var newKey = firebase.database().ref('kidsBox/'+kid+'/showBox/'+category).push();\n newKey.set({\n tag:item\n });\n firebase.database().ref('/kidsBox/'+kid+\"/incompleteBox/\"+category+\"/\"+log_key+\"/\").set({\n tag:$(\"#selected_tags\").tagsinput(\"items\")\n });\n\n }\n\n}",
"function TagCloud (id, name) {\n this.id = id;\n this.name = name;\n this.tags = [];\n this.addTag = function (word) {\n this.tags.push(word);\n };\n this.toString = function () {\n return `\n===================================================\n${this.name}\n---------------------------------------------------\n${this.tags.map((word) => word).join('\\n')}\n===================================================\n`;\n }\n}",
"async create(req, res) {\n let tagList = req.body.tags;\n try {\n let user = await users.findOne({where: {username : req.params.username}})\n let user_id = user.id\n let uniqueTagList = tagList\n .filter((e, i) => tagList.indexOf(e) === i)\n //create tags\n for(let tag in uniqueTagList){\n let tagInfo = await Tags\n .findOrCreate({\n where: { tag },\n defaults: { tag },\n })\n\n await TagToUser\n .findOrCreate({\n where: {\n tag_id: tagInfo[0].id,\n user_id: user_id\n },\n defaults: {\n tag_id: tagInfo[0].id,\n user_id: user_id\n }\n })\n }\n\n res.status(200).send()\n } catch(error) {\n console.log(error)\n res.status(400).send(error)\n }\n }",
"merge(things = iCrypto.pRequired(\"merge\"), nameToSave = iCrypto.pRequired(\"merge\")){\n\n if (!this.keysExist(things))\n throw \"merge: some or all objects with such keys not found \";\n\n console.log(\"Mergin' things\");\n let result = \"\";\n for (let i= 0; i< things.length; ++i){\n let candidate = this.get(things[i]);\n if (typeof (candidate) === \"string\" || typeof(candidate) ===\"number\" )\n result += candidate;\n else\n throw \"Object \" + things[i] + \" is not mergeable\";\n }\n this.set(nameToSave, result);\n return this;\n }",
"function TagSuggest() {}",
"getAccountByName(name, commit=true) {\n for (let i = 0; i < this.accounts.length; i++) {\n let account = this.accounts[i];\n if (account.name === name) {\n return account;\n }\n }\n if (commit) {\n let newAccount = new Account(name);\n this.accounts.push(newAccount);\n return newAccount;\n } else {\n return undefined;\n }\n }",
"getTagConfig(tagName: string): NodeConfig {\n if (TAGS[tagName]) {\n return {\n ...TAGS[tagName],\n tagName,\n };\n }\n\n return {};\n }",
"function changePersonToBart(person) {\n //changes the property of firstName to be 'Bart'\n person.firstName = 'Bart'\n\n //changes the property of 'favorite color' to be orange\n person[\"favorite color\"] = \"orange\"\n \n //removes the last item in the hobbies array\n person.hobbies.pop()\n \n //adds a new item to the hobbies array\n person.hobbies.push('Skateboarding')\n \n //returns the object with the updated properties\n return person\n}",
"function addTag(req, res) {\n var errorCallback = function(err) {\n res.send({error: 'Unable to add tag'});\n };\n\n Model('findOne', {_id: req.params.id}, function(user) {\n console.log('user is ' + user);\n\n var specifiedTag = decodeURI(req.params.tag);\n\n if(user.tags.indexOf(specifiedTag) < 0) {\n user.tags.push(specifiedTag);\n }\n\n user.save(function(errSave) {\n if(errSave) {\n errorCallback();\n }\n\n res.send({success: 'Successfully added tag!'});\n });\n }, errorCallback);\n}",
"function addSpecifiedWord()\n{\n\tvar text = newWord.value;\n\tif (text == \"\")\n\t{\n\t\talert(\"Cannot add an empty value!\");\n\t\treturn;\n\t}\n\taddWord(text, loadedData.length);\n\tloadedData.push(text);\n\tsave(text);\n\tnewWord.value = \"\";\n\t\n\t// necessary to filter out added word\n\t// if necessary\n\tsearch();\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
D(name,registrar): Create a DNS Domain. Use the parameters as records and mods. | function D(name,registrar) {
var domain = newDomain(name,registrar);
for (var i = 0; i< defaultArgs.length; i++){
processDargs(defaultArgs[i],domain)
}
for (var i = 2; i<arguments.length; i++) {
var m = arguments[i];
processDargs(m, domain)
}
conf.domains.push(domain)
} | [
"function createDomainObject(domainName) {\n return { name: domainName, count: 1 };\n}",
"createDomainSecDnsExtension(data) {\n var config = this.config;\n var namespace = config.namespaces.DNSSEC.xmlns;\n var secCreate = {\n \"_attr\": {\n \"xmlns:secDNS\": namespace\n }\n };\n if (data.dsData || data.keyData) {\n var processedSecDns = SecDnsExtension.prototype.processSecDns(data);\n for (var key in processedSecDns)\n secCreate[key] = processedSecDns[key];\n } else {\n return;\n }\n var processedExtension = {\n 'secDNS:create': secCreate\n };\n\n return processedExtension;\n }",
"function addDomain(domain){\n\n\tdb.collection('domains').insert({\"domain\": domain, \"grade\": \"Calculating\"}, function(err, result) {});\n\n\ttestSSL(domain, 0, function(grade){\n\t\tdb.collection('domains').update({\"domain\": domain},{$set: {\"grade\": grade}}, function(err, result){});\n\t});\n}",
"function Domain(props) {\n return __assign({ Type: 'AWS::SDB::Domain' }, props);\n }",
"static get(name, id, state) {\n return new Domain(name, state, { id });\n }",
"function DDSLoader() {}",
"function DnsProvider(name, nsCount){\n if(typeof nsCount === 'undefined'){\n nsCount = -1;\n }\n return function(d) {\n d.dnsProviders[name] = nsCount;\n }\n}",
"static init(diagnoses = []) {\n const self = new DoctorRegistrar();\n self.diagnoses = diagnoses; // diagnoses.forEach(diagnosis => self.diagnoses.push(diagnosis));\n }",
"function askForDomain () {\n return inquirer.prompt([{\n type: 'input',\n name: 'domain',\n message: 'Enter a domain name'\n }]).then(answers => answers.domain);\n}",
"function dig ( dns, domain, settings ) {\n\treturn new Promise(( resolve, reject ) => {\n\t\tlet packet = buildPacket(domain);\n\t\tlet timeoutInstance;\n\n\t\tlet IPv = isIPv4(dns) ? 4 : 6;\n\n\t\tlet client = dgram.createSocket('udp' + IPv.toString());\n\t\tclient.send(packet, settings.port, dns, (err) => {\n\t\t\tif (err) fail();\n\t\t\telse {\n\t\t\t\ttimeoutInstance = setTimeout(() => {\n\t\t\t\t\tfail();\n\t\t\t\t}, settings.timeoutLength);\n\t\t\t}\n\t\t});\n\n\t\tclient.on('message', ( response, server ) => {\n\n\t\t\tclearTimeout(timeoutInstance);\n\n\t\t\ttry { client.close(); }\n\t\t\tcatch (error) { console.log(error); }\n\n\t\t\tlet didResolve = validateResponse(response);\n\t\t\tresolve(didResolve);\n\t\t});\n\n\t\tfunction fail () {\n\t\t\ttry { client.close(); }\n\t\t\tcatch (error) { console.log(error); }\n\t\t\tresolve(false);\n\t\t}\n\t});\n}",
"function setDomains( domains, callback ) {\n\tchrome.storage.sync.set( {\n\t\tdomains: domains\n\t}, callback );\n}",
"function gen_new_packet(id, flags, codes) {\n var dns_packet = { id: id, flags: flags, codes: codes, qd: 0, an: 0, ns: 0, ar: 0,\n question: {},\n answers: [],\n authority: [],\n additional: []\n };\n return dns_packet;\n}",
"function createDiscovery() {\n var buf = createHeader()\n writeHeaderType(buf, 'D')\n return buf\n}",
"CreateDelegationOfDomainWithSameNicThanV3(domain) {\n let url = `/email/domain/${domain}/migrateDelegationV3toV6`;\n return this.client.request('POST', url);\n }",
"function Server() {\n var netServer = null; // the net module server\n var whois = null; // manages the connections with the whois servers\n var logger = null;\n \n // domain name validation regex\n var dnameRegex = XRegExp('^[a-z0-9-]+\\.(([a-z]{2,}\\.[a-z]{2,2})|([a-z]{2,}))$');\n\n // callback for when the user sends data to the server\n var dataListener = function(data,session) {\n data = data.toString().trim().toLowerCase();\n\n if( !dnameRegex.test(data) ) {\n // domain name validation failed, return error to user\n session.clientWrite('The domain name provided is invalid');\n session.clientEnd();\n logger.log( '[server][' + session.getID() + '] domain name regex failed for'\n + ' input: ' + data );\n } else {\n session.initQuery(data);\n logger.log( '[server][' + session.getID() + '] query received: '\n + session.getDomainName() );\n whois.query(session);\n }\n }\n\n // callback function that initialises a session with a client\n var connectionListener = function(client) {\n var session = new Session();\n session.init(client,logger);\n\n function dataListenerDummy(data) {\n dataListener(data,session);\n }\n\n // we expect only one line of data from the client, ignore everything else by\n // using a one time callback function\n client.once( 'data', dataListenerDummy );\n logger.log( '[server][' + session.getID() + '] new connection: '\n + JSON.stringify( client.address() ) );\n }\n\n return {\n // getter for verbose\n isVerbose:function() {\n return verbose;\n }, \n\n // initialises the Server class\n init:function(main) {\n // get logger object\n logger = main.logger;\n\n // create whois server manager object\n whois = main.whois;\n\n // create server\n netServer = net.createServer(connectionListener).listen(9000);\n logger.log('[server] server created on port 9000');\n }\n }\n}",
"static hashDomain(domain) {\n const domainFields = [];\n for (const name in domain) {\n if (domain[name] == null) {\n continue;\n }\n const type = domainFieldTypes[name];\n (0, index_js_4.assertArgument)(type, `invalid typed-data domain key: ${JSON.stringify(name)}`, \"domain\", domain);\n domainFields.push({ name, type });\n }\n domainFields.sort((a, b) => {\n return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name);\n });\n return TypedDataEncoder.hashStruct(\"EIP712Domain\", { EIP712Domain: domainFields }, domain);\n }",
"function createDepartment(name, cost) {\n\n log(`\\n\\n`);\n log(y(`ADDING NEW DEPARTMENT...`));\n log(`\\n\\n`);\n\n connection.query(`INSERT INTO departments SET ?`, {\n\n department_name: name,\n over_head_costs: cost\n\n },\n function (err, res) {\n\n if (err) throw err;\n\n log(y(`DEPARTMENT --${name}-- ADDED...`));\n log(y(`RETURNING to S_MODE Terminal...`));\n\n supervisorTerminal();\n\n });\n}",
"getRecords(domainId) {\n return __awaiter(this, void 0, void 0, function* () {\n const res = yield this.api.apiCall(\"GET\", `/domains/${domainId}/dns`);\n return res.data;\n });\n }",
"create(req, res) {\n Origin.create(req.body)\n .then(function (neworigin) {\n res.status(200).json(neworigin);\n })\n .catch(function (error){\n res.status(500).json(error);\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set up change listener when DateField is available. Not in dateField config to enable users to supply their own listeners block there | updateDateField(dateField) {
const me = this;
dateField.on({
change({ userAction, value }) {
if (userAction && !me.$isInternalChange) {
me._isUserAction = true;
me.value = value;
me._isUserAction = false;
}
},
thisObj : me
});
} | [
"function fieldChanged(type, name, linenum) {\r\n\t\r\n\tsetStatusSetDate(name);\r\n\t\r\n}",
"function setDateHandlers(field){\n \n $(field).on({\n \n // On focus...\n \n 'focus': function(event){\n \n // Remove validation\n \n $(this).removeClass('invalid');\n \n // Show date picker if not shown already\n \n if(!$(this).siblings('.date-picker').is(':visible')){\n \n showDatePicker(this);\n \n }\n \n },\n \n // On defocus, validate\n \n 'blur': function(event){\n \n // If valid date, format\n \n if(isValidDate($(this).val())){\n \n let date = new Date($(this).val());\n $(this).val(zeroPad(date.getMonth() + 1, 2) + '/' + zeroPad(date.getDate(), 2) + '/' + date.getFullYear());\n \n }\n \n // Otherwise, make invalid\n \n else if($(this).val().length > 0){\n \n $(this).addClass('invalid');\n \n }\n \n },\n \n // On tab, hide date picker\n \n 'keydown': function(event){\n \n if(event.which == 9){\n \n $(this).siblings('.date-picker').hide();\n \n }\n \n },\n \n // On typing...\n \n 'keyup': function(event){\n \n // Get current cursor position\n \n let cursorPosition = this.selectionStart;\n \n // Remove non-date characters\n \n let value = $(this).val();\n $(this).val(value.replace(/[^0-9\\/]/g, ''));\n \n // If if typed character was removed, adjust cursor position\n \n let startLength = value.length;\n let endLength = $(this).val().length;\n \n if(startLength > endLength){\n \n setCursorPosition(this, cursorPosition - 1);\n \n }\n \n // If valid date, adjust date picker\n \n if(isValidDate($(this).val())){\n \n showDatePicker(this);\n \n }\n \n }\n \n });\n \n}",
"_listenDateFormatSelected() {\n var self = this;\n self.m_dateFormatChangeHandler = function (e) {\n if (!self.m_selected)\n return;\n var $selected = $(e.target).find(':selected');\n var value = $selected.val();\n var domPlayerData = self._getBlockPlayerData();\n var xSnippet = $(domPlayerData).find('XmlItem');\n $(xSnippet).attr('dateFormat', value);\n self._setBlockPlayerData(domPlayerData);\n };\n $(Elements.JSON_ITEM_DATE_FORMAT, self.$el).on('change', self.m_dateFormatChangeHandler);\n }",
"changeDateField(config) {\n const\n me = this,\n result = new DateField(ObjectHelper.assign({\n // To be able to use transformDateValue for parsing without loosing time, a bit of a hack\n keepTime : true,\n flex : 1,\n step : '1 d',\n\n updateInvalid() {\n const updatingInvalid = me.updatingInvalid;\n\n DateField.prototype.updateInvalid.apply(this, arguments);\n me.dateField && !updatingInvalid && me.updateInvalid();\n }\n }, config));\n\n // Must set *after* construction, otherwise it becomes the default state\n // to reset readOnly back to\n if (me.readOnly) {\n result.readOnly = true;\n }\n\n return result;\n }",
"function prepareListener() {\n var droppy;\n droppy = document.getElementById(\"datecheck\");\n droppy.addEventListener(\"change\",getDoctors);\n}",
"function setListenersDate(element){\n\telement.addEventListener(\"focus\", function(){eventFocusOnDate(element);});\n\telement.addEventListener(\"blur\", function(event){eventLostFocusOnDate(element, event);});\n\telement.addEventListener(\"keyup\", function(){eventKeyUp(element);});\n}",
"function handleDiliveryDateChange(e) {\n setDeliveryDate(e.target.value)\n setDrawer(false)\n }",
"add_change(func) {\n this.add_event(\"change\", func);\n }",
"despatchChangeEvent() {\n const eventDetail = {\n fldorigin: this.fldorigin,\n fieldName: this.fldname,\n fieldType: this.fldtype,\n isRange: false,\n isMulti: true,\n fieldValue: this.filterValue\n };\n const changeEvent = new CustomEvent(\"filtervaluechange\", {\n detail: eventDetail\n });\n this.dispatchEvent(changeEvent);\n }",
"setListener(cell) {\n var self = this;\n switch(cell.type) {\n case 'date':\n cell.$td.on('focus', function(event) {\n cell.clearError();\n var $dateInput = $('<input value=\"' + cell.contents + '\">');\n $dateInput.css('width', '85px');\n $(this).empty();\n $(this).append($dateInput);\n var startDate = cell.contents ? cell.contents : new Date().toLocaleDateString(\"en-US\");\n\n var picker = datepicker($dateInput.get(0), (date) => {\n cell.contents = formatSlashDate(date);\n cell.columnInfo.set_column(self.item, cell.contents);\n self.sendUpdate();\n });\n $dateInput.on('focusout', function(event) {\n cell.$td.text(cell.contents);\n if(cell.errorMessage) {\n cell.showError(cell.errorMessage);\n }\n });\n\n $dateInput.focus();\n });\n break;\n // TODO: fill these options in\n case 'money':\n cell.$td.on('focusin', function(event) {\n cell.clearError($(this));\n cell.setText(unFormatMoney(cell.getText()));\n $(this).selectText();\n });\n cell.$td.on('focusout', function(event) {\n // HACK: event firing multiple times causes\n // text to go to $0.00 without this\n var text = cell.getText().replace('$', '')\n if(text == undefined) {\n return;\n }\n\n if(!isNaN(text)) {\n var amt = parseFloat(text);\n $(this).attr('value', amt);\n cell.contents = amt;\n // cell.setText(formatMoney(amt));\n cell.columnInfo.set_column(self.item, cell.contents);\n self.sendUpdate();\n } else {\n cell.setText(\"$0.00\");\n }\n });\n break;\n case 'selector':\n cell.$td.on('focus', event => {\n cell.clearError();\n cell.$td.empty();\n var datalist = self.makeSelectInput(cell);\n cell.$td.append(datalist);\n\n var $input = $(datalist[0]);\n $input.focus();\n $input.select();\n });\n \n break;\n case 'number':\n cell.$td.on('focusin', event => {\n cell.clearError();\n cell.$td.selectText();\n });\n cell.$td.on('focusout', event => {\n if(!isNaN(cell.getText())) {\n cell.setText()\n cell.columnInfo.set_column(self.item, cell.contents);\n self.sendUpdate();\n } else {\n cell.$td.text(\"0\");\n }\n });\n break;\n default: // type 'text'\n cell.$td.on('focusin', function(event) {\n cell.clearError($(this));\n $(this).selectText(); \n });\n cell.$td.on('focusout', function(event) {\n cell.setText();\n cell.columnInfo.set_column(self.item, cell.contents);\n self.sendUpdate();\n });\n break;\n }\n }",
"function _setFieldListener(field, callback) {\n\t field.addEventListener('input', callback);\n\t }",
"triggerDateChange() {\n\t\tlet time = getPrivate(this, 'timestamp');\n\t\tif (get(this, 'utc')) {\n\t\t\ttime = _time.utcFromLocal(time).timestamp();\n\t\t}\n\n\t\tlet timestamp;\n\t\tif (!isNone(get(this, 'timestamp'))) {\n\t\t\ttimestamp = time;\n\t\t\tset(this, '__lastTimestamp', timestamp);\n\t\t\tset(this, 'timestamp', timestamp);\n\t\t}\n\n\t\tlet unix;\n\t\tif (!isNone(get(this, 'unix'))) {\n\t\t\tunix = _time(time).unix();\n\t\t\tset(this, '__lastUnix', unix);\n\t\t\tset(this, 'unix', unix);\n\t\t}\n\n\t\tthis.setState();\n\t\tthis.sendAction('onChange', { timestamp, unix });\n\t}",
"function processChange(value) {\n //console.log(\"Calendar clicked\");\n //If we are working with the start input\n if(cntrl.getStartCal()) {\n cntrl.setSelectedStartDate(value); \n }\n //If we are working with the end input\n else {\n cntrl.setSelectedEndDate(value);\n }\n //Autoclose after selection\n cntrl.updateDateRange();\n }",
"function initCal() {\n const cal = document.querySelector('#calendar');\n const datepicker = new Datepicker(cal, {\n autohide: true\n });\n \n cal.addEventListener('changeDate', updatePlaykit);\n}",
"_listenFieldSelected() {\n var self = this;\n self.m_fieldChangeHandler = function (e) {\n if (!self.m_selected)\n return;\n var $selected = $(e.target).find(':selected');\n var fieldName = $selected.val();\n var fieldType = $selected.data('type');\n var domPlayerData = self._getBlockPlayerData();\n var xSnippet = $(domPlayerData).find('XmlItem');\n $(xSnippet).attr('fieldType', fieldType);\n $(xSnippet).attr('fieldName', fieldName);\n self._setBlockPlayerData(domPlayerData);\n };\n $(Elements.JSON_ITEM_TEXT_FIELDS, self.$el).on('change', self.m_fieldChangeHandler);\n }",
"_setOnChange() {\n let self = this;\n this.onChange = function() {\n self.value = self.innerGetValue(); // Update inner value\n if (self._onChangeCB) self._onChangeCB.call(self); // call user defined callback\n };\n this.innerMapOnChange(); // Map the event that will trigger onChange\n }",
"registerOnValidatorChange(fn) {\n this._onValidatorChange = fn;\n }",
"function departureDateHandler() {\n\thandlePastDate();\t\t\t\t\t\t// Ensures that a past date is handled.\n\tdateInverter();\t\t\t\t\t\t\t// Inverts dates if necessary.\n}",
"_onChange(event) {\n // For change event on the native <input> blur, after the input is cleared,\n // we schedule change event to be dispatched on date-picker blur.\n if (\n this.inputElement.value === '' &&\n !(event.detail && event.detail.sourceEvent && event.detail.sourceEvent.__fromClearButton)\n ) {\n this.__dispatchChange = true;\n }\n\n event.stopPropagation();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Activate or deactivate tag via AJAX | function activateDeactive(id, status) {
$.simpleAjax({
crud: "Etiquetas",
type: "GET",
url:
$("#DATA").data("url") + `/tags/setStatus/${id}/${status}`,
form: "",
loadingSelector: ".panel",
successCallback: function (data) {
table.ajax.reload();
},
errorCallback: function (data) {
}
});
} | [
"function setInactiveUser() {\r\r\n jQuery.post(\r\r\n swapchic_ajax.ajax_url,\r\r\n {\r\r\n 'action': 'ajaxSetInactiveUser'\r\r\n },\r\r\n function(){\r\r\n\r\r\n }\r\r\n );\r\r\n}",
"function indicateSelectedTag(tag) {\n clearSelectedTags();\n tag.classList.add(\"tags-btn__selected\");\n}",
"function disapprove_btn_click(e) {\n\t//console.log(e);\n\tvar post_id = e.target.getAttribute('data-post-id');\n\tconsole.log('disapproving post #'+post_id);\n\te.target.setAttribute('value', 'disapproving...');\n\te.target.disabled = true;\n\tvar xmlhttp = new XMLHttpRequest();\n xmlhttp.onreadystatechange = function() {\n\t\tif (xmlhttp.readyState == 4) {\n\t\t\tif (xmlhttp.status == 200) {\n\t\t\t\tconsole.log('post disapproval accepted');\n\t\t\t\tif (xmlhttp.responseText == 'deleted') {\n\t\t\t\t\t// content deleted based on disapproval\n\t\t\t\t\tconsole.log('post is now deleted');\n\t\t\t\t\tvar the_post = document.getElementById('post-' + post_id);\n\t\t\t\t\tthe_post.parentNode.removeChild(the_post);\n\t\t\t\t} else {\n\t\t\t\t\t// content still needs more votes\n\t\t\t\t\tconsole.log('post needs more votes');\n\t\t\t\t\te.target.setAttribute('value', 'LAME. (Needs more votes to be deleted.)');\n\t\t\t\t}\n\t\t\t} else if (xmlhttp.status == 400) {\n\t\t\t\tconsole.error('There was an error 400 when trying to disapprove the post: ' + xmlhttp.responseText);\n\t\t\t} else if (xmlhttp.status == 500) {\n\t\t\t\tconsole.error('There was an error 500 when trying to disapprove the post: ' + xmlhttp.responseText);\n\t\t\t} else {\n\t\t\t\tconsole.error('Something other than 200 was returned when disapproving the post: ' + xmlhttp.responseText);\n\t\t\t}\n\t\t}\n\t}\n\txmlhttp.open(\"POST\", \"/content/process/\", true);\n\txmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\txmlhttp.send(\"a=disapprove&post_id=\" + post_id);\n}",
"function switchPressTwo(){\n\t\tif(document.getElementById(\"relay2\").className == \"relay2 active\"){\n\t\t\tmicrogear.chat(\"pieplug\",\"OFF2\");\n\t\t}else if(document.getElementById(\"relay2\").className == \"relay2\"){\n\t\t\tmicrogear.chat(\"pieplug\",\"ON2\");\n\t\t}\n\t}",
"function approve_btn_click(e) {\n\t//console.log(e);\n\tvar post_id = e.target.getAttribute('data-post-id');\n\tconsole.log('approving post #'+post_id);\n\te.target.setAttribute('value', 'approving...');\n\te.target.disabled = true;\n\tvar xmlhttp = new XMLHttpRequest();\n xmlhttp.onreadystatechange = function() {\n\t\tif (xmlhttp.readyState == 4) {\n\t\t\tif (xmlhttp.status == 200) {\n\t\t\t\tconsole.log('post approval accepted');\n\t\t\t\tif (xmlhttp.responseText == 'approved') {\n\t\t\t\t\t// content totally approved\n\t\t\t\t\tconsole.log('post is now approved');\n\t\t\t\t\te.target.setAttribute('value', 'APPROVED.');\n\t\t\t\t\te.target.parentNode.parentNode.className = e.target.parentNode.parentNode.className.replace('peer-approval', '');\n\t\t\t\t\tvar unneeded_stuff = e.target.parentNode.parentNode.getElementsByClassName('peer-approval');\n\t\t\t\t\tfor (var i = 0; i < unneeded_stuff.length; i++) {\n\t\t\t\t\t\tunneeded_stuff[i].parentNode.removeChild(unneeded_stuff[i]);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// content still needs more votes\n\t\t\t\t\tconsole.log('post needs more votes');\n\t\t\t\t\te.target.setAttribute('value', 'APPROVED. (Needs more votes to be public.)');\n\t\t\t\t}\n\t\t\t} else if (xmlhttp.status == 400) {\n\t\t\t\tconsole.error('There was an error 400 when trying to approve the post: ' + xmlhttp.responseText);\n\t\t\t} else if (xmlhttp.status == 500) {\n\t\t\t\tconsole.error('There was an error 500 when trying to approve the post: ' + xmlhttp.responseText);\n\t\t\t} else {\n\t\t\t\tconsole.error('Something other than 200 was returned when approving the post: ' + xmlhttp.responseText);\n\t\t\t}\n\t\t}\n\t}\n\txmlhttp.open(\"POST\", \"/content/process/\", true);\n\txmlhttp.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n\txmlhttp.send(\"a=approve&post_id=\" + post_id);\n}",
"function updateTag(attrib) {\n\tvar dom = dw.getDocumentDOM();\n\tvar theObj = dom.getSelectedNode(); //new TagEdit(dom.getSelectedNode().outerHTML);\n\n\tif (attrib) {\n\t\tswitch (attrib) {\n\t\t\tcase \"name\":\n\t\t\t\tif (theObj.getAttribute(\"name\") != NAME.value && NAME.value != \"\") {\n\t\t\t\t\tif ((theObj.getAttribute(\"id\"))&&\n\t\t\t\t\t (theObj.getAttribute(\"name\"))&&\n\t\t\t\t\t (theObj.getAttribute(\"id\") == theObj.getAttribute(\"name\"))) {\n\t\t\t\t\t\t\ttheObj.setAttribute(\"id\", NAME.value);\n\t\t\t\t\t\t}\n\t\t\t\t\tif (!(theObj.getAttribute(\"id\"))) {\n\t\t\t\t\t\ttheObj.setAttribute(\"id\", NAME.value);\n\t\t\t\t\t}\n\t\t\t\t\ttheObj.setAttribute(\"name\", NAME.value);\n\t\t\t\t\teditOccurred = true;\n\t\t\t\t} else if (theObj.getAttribute(\"name\") && NAME.value == \"\") {\n\t\t\t\t\ttheObj.removeAttribute(\"name\");\n\t\t\t\t\teditOccurred = true;\n\t\t\t\t}\n\t\t\t\t\n//\t\t\t\tif (NAME.value != \"\" && !dwscripts.isValidVarName(NAME.value)) {\n//\t\t\t\t\t\talert(MM.MSG_InvalidIDAutoFix);\t// test the case of a name with first chr a number or special chr\n//\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase \"action\":\n\t\t\t\tif (theObj.getAttribute(\"action\") != ACTION.value && ACTION.value != \"\") {\n\t\t\t\t\ttheObj.setAttribute(\"action\", ACTION.value);\n\t\t\t\t} else if (theObj.getAttribute(\"action\") && ACTION.value == \"\") {\n\t\t\t\t\ttheObj.removeAttribute(\"action\");\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase \"method\":\n\t\t\t\tif (theObj.getAttribute(\"method\") != METHOD.getValue() && METHOD.getValue() != \"\") {\n\t\t\t\t\ttheObj.setAttribute(\"method\", METHOD.getValue());\n\t\t\t\t\t//when the method changes, we modify the enctype combo box to reflect valid values\n\t\t\t\t\tupdateEncTypeList(METHOD.getValue());\n\t\t\t\t} else if (theObj.getAttribute(\"method\") && METHOD.getValue() == \"\") {\n\t\t\t\t\ttheObj.removeAttribute(\"method\");\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase \"target\":\n\t\t\t\tif (theObj.getAttribute(\"target\") != TARGET.getValue() && TARGET.getValue() != \"\") {\n\t\t\t\t\ttheObj.setAttribute(\"target\", TARGET.getValue());\n\t\t\t\t} else if (theObj.getAttribute(\"target\") && TARGET.getValue() == \"\") {\n\t\t\t\t\ttheObj.removeAttribute(\"target\");\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase \"enctype\":\n\t\t\t\tif (theObj.getAttribute(\"enctype\") != ENCTYPE.getValue() && ENCTYPE.getValue() != \"\") {\n\t\t\t\t\ttheObj.setAttribute(\"enctype\", ENCTYPE.getValue());\n\t\t\t\t} else if (theObj.getAttribute(\"enctype\") && ENCTYPE.getValue() == \"\") {\n\t\t\t\t\ttheObj.removeAttribute(\"enctype\");\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\t// Common tags\n\t\t\tcase \"format\":\n\t\t\t\tif (theObj.getAttribute(\"format\") != FORMAT.getValue() && FORMAT.getValue() != \"\") {\n\t\t\t\t\ttheObj.setAttribute(\"format\", FORMAT.getValue());\n\t\t\t\t\tupdateSkinList();\n\t\t\t\t\ttheObj.removeAttribute(\"skin\");\n\t\t\t\t\tSKIN.pickValue(\"\");\n\t\t\t\t} else if (theObj.getAttribute(\"format\") && FORMAT.getValue() == \"\") {\n\t\t\t\t\ttheObj.removeAttribute(\"format\");\n\t\t\t\t\tupdateSkinList();\n\t\t\t\t\ttheObj.removeAttribute(\"skin\");\n\t\t\t\t\tSKIN.pickValue(\"\");\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase \"style\":\n\t\t\t\tif (theObj.getAttribute(\"style\") != STYLE.value && STYLE.value != \"\") {\n\t\t\t\t\ttheObj.setAttribute(\"style\", STYLE.value);\n\t\t\t\t} else if (theObj.getAttribute(\"style\") && STYLE.value == \"\") {\n\t\t\t\t\ttheObj.removeAttribute(\"style\");\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase \"skin\":\n\t\t\t\tif (theObj.getAttribute(\"skin\") != SKIN.getValue() && SKIN.getValue() != \"\") {\n\t\t\t\t\ttheObj.setAttribute(\"skin\", SKIN.getValue());\n\t\t\t\t} else if (theObj.getAttribute(\"skin\") && SKIN.getValue() == \"\") {\n\t\t\t\t\ttheObj.removeAttribute(\"skin\");\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase \"preserveData\":\n\t\t\t\tif (theObj.getAttribute(\"preserveData\") != PRESERVEDATA.getValue() && PRESERVEDATA.getValue() != \"\") {\n\t\t\t\t\ttheObj.setAttribute(\"preserveData\", PRESERVEDATA.getValue());\n\t\t\t\t} else if (theObj.getAttribute(\"preserveData\") && PRESERVEDATA.getValue() == \"\") {\n\t\t\t\t\ttheObj.removeAttribute(\"preserveData\");\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase \"scriptSrc\":\n\t\t\t\tif (theObj.getAttribute(\"scriptSrc\") != SCRIPTSRC.value && SCRIPTSRC.value != \"\") {\n\t\t\t\t\ttheObj.setAttribute(\"scriptSrc\", SCRIPTSRC.value);\n\t\t\t\t} else if (theObj.getAttribute(\"scriptSrc\") && SCRIPTSRC.value == \"\") {\n\t\t\t\t\ttheObj.removeAttribute(\"scriptSrc\");\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase \"archive\":\n\t\t\t\tif (theObj.getAttribute(\"archive\") != ARCHIVE.value && ARCHIVE.value != \"\") {\n\t\t\t\t\ttheObj.setAttribute(\"archive\", ARCHIVE.value);\n\t\t\t\t} else if (theObj.getAttribute(\"archive\") && ARCHIVE.value == \"\") {\n\t\t\t\t\ttheObj.removeAttribute(\"archive\");\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase \"height\":\n\t\t\t\tif (HEIGHT.value != \"\") {\n\t\t\t\t\tif (HEIGHT.value != parseInt(HEIGHT.value) || parseInt(HEIGHT.value) < 0) {\n\t\t\t\t\t\talert(MM.MSG_ValuePositiveInteger);\n\t\t\t\t\t\tif (theObj.getAttribute(\"height\"))\n\t\t\t\t\t\t\tHEIGHT.value = theObj.getAttribute(\"height\");\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tHEIGHT.value = \"\"; \n\t\t\t\t\t} else if (theObj.getAttribute(\"height\") != HEIGHT.value) {\n\t\t\t\t\t\ttheObj.setAttribute(\"height\", HEIGHT.value);\n\t\t\t\t\t\teditOccurred = true;\n\t\t\t\t\t}\n\t\t\t\t} else if (theObj.getAttribute(\"height\")) {\n\t\t\t\t\ttheObj.removeAttribute(\"height\");\n\t\t\t\t\teditOccurred = true;\n\t\t\t\t}\n\t\t\tbreak;\n\n\t\t\tcase \"width\":\n\t\t\t\tif (WIDTH.value != \"\") {\n\t\t\t\t\tif (WIDTH.value != parseInt(WIDTH.value) || parseInt(WIDTH.value) < 0) {\n\t\t\t\t\t\talert(MM.MSG_ValuePositiveInteger);\n\t\t\t\t\t\tif (theObj.getAttribute(\"width\"))\n\t\t\t\t\t\t\tWIDTH.value = theObj.getAttribute(\"width\");\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tWIDTH.value = \"\";\n\t\t\t\t\t} else if (theObj.getAttribute(\"width\") != WIDTH.value) {\n\t\t\t\t\t\ttheObj.setAttribute(\"width\", WIDTH.value);\n\t\t\t\t\t\teditOccurred = true;\n\t\t\t\t\t}\n\t\t\t\t} else if (theObj.getAttribute(\"width\")) {\n\t\t\t\t\ttheObj.removeAttribute(\"width\");\n\t\t\t\t\teditOccurred = true;\n\t\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t} \n}",
"function enableButtons() {\n $j(\"#open_item\").removeClass(\"disabled\");\n $j(\"#open_item\").addClass(\"enabled\");\n $j(\"#go_to_item_location\").removeClass(\"disabled\");\n $j(\"#go_to_item_location\").addClass(\"enabled\");\n }",
"function changeActiveUser(flag){\n\tvar active = \"\";\n\tif(flag == false && $('#enableactiveuser').is(':checked') == false){\n\t\tactive = globalUserName;\n\t}else{\n\t\tactive = $('#selectActiveUser').val();\n\t\tif(active == \"\" | active == undefined || active == null){\n\t\t\tactive = $('#activeuserlabel').text();\n\t\t}\n\t}\n\tif(flag == false && $('#enableactiveuser').is(':checked') == false && ($('#selectActiveUser').val() == null || $('#selectActiveUser').val() == \"\" || $('#selectActiveUser').val() == undefined)){\n\t\t$('#activeuserlabel').css('color','gray');\n\t}else if(flag == false && $('#enableactiveuser').is(':checked') == false && ($('#selectActiveUser').val() != null && $('#selectActiveUser').val() != \"\" && $('#selectActiveUser').val() != undefined)){\n $(\"#selectActiveUser\").removeAttr(\"disabled\");\n\t}else if(flag == false && $('#enableactiveuser').is(':checked') == true && ($('#selectActiveUser').val() != null && $('#selectActiveUser').val() != \"\" && $('#selectActiveUser').val() != undefined)){\n $(\"#selectActiveUser\").attr(\"disabled\",true);\n\t}else if(flag == false && $('#enableactiveuser').is(':checked') == true && ($('#selectActiveUser').val() == null || $('#selectActiveUser').val() == \"\" || $('#selectActiveUser').val() == undefined)){\n\t\t$('#activeuserlabel').css('color','black');\n\t}\n\tvar sessionid = seletedSessionId.split(\"__\");\n\tvar url = getURL('Console') + \"action=changeActiveUser&query={'MAINCONFIG': [{'sessionid': '\"+sessionid[1]+\"','username':'\"+active+\"'}]}\";\n \t$.ajax({\n \turl: url,\n dataType: 'html',\n \t method: 'POST',\n \tproccessData: false,\n async:false,\n \t success: function(data) {\n\t\t\tgetActiveUser();\n\t\t}\n \t});\n}",
"function processStateTabs(id){\n\t\tif(id == \"dna-al\"){\n\t\t\tdocument.getElementById(\"dna-cv\").disabled = false;\n\t\t} else if(id == \"dna-cv\"){\n\t\t\tdocument.getElementById(\"dna-clb\").disabled = false;\n\t\t\tdocument.getElementById(\"dna-pr\").disabled = false;\n\t\t} else if(id == \"dna-pr-variant\"){\n\t\t\tdocument.getElementById(\"dna-pr-snp\").disabled = false;\n\t\t\tdocument.getElementById(\"dna-pr-indel\").disabled = false;\n\t\t} else if(id == \"dna-pr-snp\"){\n\t\t\tdocument.getElementById(\"dna-ann-snp\").disabled = false;\n\t\t\tdocument.getElementById(\"dna-ann\").disabled = false;\n\t\t} else if(id == \"dna-pr-indel\"){\n\t\t\tdocument.getElementById(\"dna-ann-indel\").disabled = false;\n\t\t\tdocument.getElementById(\"dna-ann\").disabled = false;\n\t\t} else if(id == \"dna-pr-cnv\"){\n\t\t\tdocument.getElementById(\"dna-ann-del\").disabled = false;\n\t\t\tdocument.getElementById(\"dna-ann\").disabled = false;\n\t\t} else if(id == \"dna-pr-sv\"){\n\t\t\tdocument.getElementById(\"dna-ann-del\").disabled = false;\n\t\t\tdocument.getElementById(\"dna-ann-ins\").disabled = false;\n\t\t\tdocument.getElementById(\"dna-ann\").disabled = false;\n\t\t}\n\t}",
"sendActiveState_() {\n this.sendToChromeVox_(\n {type: 'activeState', active: this.engineID_.length > 0});\n }",
"setInactive() {\n if (this.isActive()) {\n this.element.setAttribute(Constants.DATA_ATTRIBUTE_ACTIVE, false);\n }\n if (this.parentView && this.parentView.setInactive) {\n this.parentView.setInactive();\n }\n }",
"function ontoggle() {\n selected = !selected;\n logic.ontoggle(selected);\n }",
"ajaxHandler(data) {\n 'use strict';\n\n if (data.enabled === true) {\n $('#refreshBox span.enable').hide();\n $('#refreshBox span.disable').show();\n $.otp.autorefresh.enabled = true;\n } else if (data.enabled === false) {\n $('#refreshBox span.enable').show();\n $('#refreshBox span.disable').hide();\n $.otp.autorefresh.enabled = false;\n }\n }",
"function showTags() {\n document.getElementById(\"tagView\").innerHTML = currentTags;\n }",
"function setQuestionActiveCallback(data, status) {\n\tif(status == \"success\"){\n\t\tvar questionID = data.responseJSON.questionId;\n\t\tdisplayStopButton(questionID);\n\t\t$('[questionid=\"'+questionID+'\"]').find('.playBtnGroup').addClass('active');\n\t\t$(\"#presentTab\").click();\n\t}\n}",
"function activar() {\n let nombreSede = this.dataset.nombre;\n let sede = buscarSedePorNombre(nombreSede);\n\n sede[6] = true;\n\n swal({\n title: \"Activar sede\",\n text: \"¿Está seguro que desea activar esta sede?\",\n buttons: [\"Cancelar\", \"Aceptar\"],\n }).then((willDelete) => {\n if (willDelete) {\n actualizarSede(sede);\n mostrarSedesDesactivadas();\n }\n });\n}",
"_activateSelectedTab () {\n this.tabToActivate.setAttribute('aria-selected', 'true')\n this.tabToActivate.removeAttribute('tabindex')\n this.panelToActivate.removeAttribute('hidden')\n\n this.activeTab = this.tabToActivate\n }",
"function switchContent() {\n let nodeId= $(clickedNode).attr('id');\n let node = nodeMap.get(nodeId);\n $(clickedNode).children(\".node_inhalt\").toggleClass(\"invis\");\n if($(clickedNode).children(\".node_inhalt\").hasClass(\"invis\")){\n node.toggleToAbstract();\n node.focus(); }\n else{\n node.toggleToDetailed();\n }\n\n}",
"refreshMainTagTree() {\n let $currentTagTree = $('#tree-container').find('.tagtree-widget')\n\n if ($currentTagTree.length) {\n let postData = {\n _token: this.ajaxToken,\n _action: 'requestMainTagTree',\n }\n\n let url = this.routes.tagsTreeAjax\n\n $.ajax({\n url: url,\n type: 'get',\n cache: false,\n dataType: 'json',\n data: postData,\n })\n .done((data) => {\n if ($currentTagTree.length && typeof data.tagTree !== 'undefined') {\n $currentTagTree.fadeOut('slow', () => {\n $currentTagTree.replaceWith(data.tagTree)\n $currentTagTree = $('#tree-container').find('.tagtree-widget')\n $currentTagTree.fadeIn()\n this.initNestables()\n this.bindMainTrees()\n this.resize()\n this.lazyload.bindAjaxLink()\n })\n }\n })\n .always(() => {\n this.lazyload.canvasLoader.hide()\n })\n } else {\n console.debug('No main tag-tree available.')\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns Bootstrap classnames from `size` and validation props, along with passthrough props. | function propsWithBsClassName(_ref) {
var className = _ref.className,
isInvalid = _ref.isInvalid,
isValid = _ref.isValid,
size = _ref.size,
props = _objectWithoutProperties(_ref, _excluded$d);
return _objectSpread2(_objectSpread2({}, props), {}, {
className: cx('form-control', 'rbt-input', {
'form-control-lg': isSizeLarge(size),
'form-control-sm': isSizeSmall(size),
'is-invalid': isInvalid,
'is-valid': isValid
}, className)
});
} | [
"sizingClasses(oldOptions) {\n if (oldOptions.size !== this.size) {\n return [\"sizing\", \"reset-size\" + oldOptions.size, \"size\" + this.size];\n } else {\n return [];\n }\n }",
"generateSizes(props) {\n const srcset = props.srcset.sort(sortBy('width'));\n let error = false;\n let sizes = '';\n\n srcset.forEach((image, index) => {\n if (image.src === undefined) {\n error = new Error('Required field \"width\" is undefined');\n }\n\n if (index > 0) {\n sizes = (sprintf('(min-width: %s) %dpx,', props.media_queries[(index-1)], image.width)) + sizes;\n } else {\n sizes = (sprintf(' %dpx', image.width)) + sizes;\n }\n\n });\n\n if (error !== false) {\n return error;\n }\n\n return sizes;\n }",
"havingSize(size) {\n if (this.size === size && this.textSize === size) {\n return this;\n } else {\n return this.extend({\n style: this.style.text(),\n size: size,\n textSize: size,\n sizeMultiplier: sizeMultipliers[size - 1]\n });\n }\n }",
"classNames(...classes) {\r\n let classesToAdd = [];\r\n\r\n classes.forEach(classObj => {\r\n // simple class name; apply it outright\r\n if (typeof classObj === 'string') {\r\n classesToAdd.push(classObj);\r\n\r\n } else if (typeof classObj === 'object') {\r\n Object.keys(classObj).forEach(className => {\r\n if (classObj[className] === true) {\r\n classesToAdd.push(className);\r\n }\r\n });\r\n }\r\n });\r\n\r\n this.classList.add(...classesToAdd);\r\n }",
"validateButtonClass(classStyle) {\n console.log(\"This button has the following class style: \" + classStyle);\n if(classStyle == \"\") {\n classStyle = \"btn btn-primary head-button\";\n }\n return classStyle;\n }",
"function Col(props) {\n const size = props.size\n .split(` `)\n .map(s => `col-${ s}`)\n .join(` `);\n\n return <div className={size}>{props.children}</div>;\n}",
"function _calculateSizes(){\n _dimensions.viewportWidth = $(\".cs-job-tasks\").width();\n _dimensions.defaultActiveTaskWidth = 240;\n _dimensions.workflows = {};\n\n // Break out calculations by workflow id\n $('.cs-workflow').each(function(i){\n var id = $(this).data('workflow'),\n displayDetails = $(this).data('display_details');\n _dimensions.workflows[id] = displayDetails;\n _dimensions.workflows[id].tasksAllClosedWidth = _dimensions.viewportWidth / _dimensions.workflows[id].taskCount;\n _dimensions.workflows[id].activeTaskWidth = _dimensions.defaultActiveTaskWidth;\n _dimensions.workflows[id].tasksOneOpenWidth = (_dimensions.viewportWidth - _dimensions.workflows[id].activeTaskWidth) / (_dimensions.workflows[id].taskCount - 1);\n CS_CSSOverride.addStyle('.cs-workflow.workflow-' + id + ' .cs-task', 'width', _dimensions.workflows[id].tasksAllClosedWidth + 'px');\n CS_CSSOverride.addStyle('.cs-workflow.workflow-' + id + ' .cs-job.task-selected .cs-task', 'width', _dimensions.workflows[id].tasksOneOpenWidth + 'px');\n CS_CSSOverride.addStyle('.cs-workflow.workflow-' + id + ' .cs-job.task-selected .cs-task.selected', 'width', _dimensions.workflows[id].activeTaskWidth + 'px');\n CS_CSSOverride.addStyle('.cs-workflow.workflow-' + id + ' .job-entry.cs-job.view-glance .cs-job-tasks .job-inner', 'height', _dimensions.workflows[id].tasksAllClosedWidth + 'px');\n });\n }",
"addCss() {\n const me = this,\n owner = me.owner,\n inputEl = owner.getInputEl(),\n labelEl = owner.getLabelEl();\n\n owner .addCls(me.ownerCls);\n inputEl.cls.push(me.inputCls);\n labelEl.cls.push(me.labelCls);\n }",
"function getClassNames() {\n\tvar names = [];\n\tfor (var name in classes) {\n\t\tnames.push(name);\n\t}\n\treturn names;\n}",
"iconClasses() {\n return iconClasses(this.icon, this.iconSize)\n }",
"function setTileSizes() {\n $tileList = mainDiv.find(selector);\n for (var i = 0; i < $tileList.length; i++) {\n var size = $tileList.eq(i).attr(\"data-size\");\n var wdt = tileRatio * baseWH * tileSize[size].w-margin;\n var hgh = baseWH * tileSize[size].h-margin;\n $tileList.eq(i).css({\"width\": wdt, \"height\": hgh}).addClass('w' + tileSize[size].w + ' ' + 'h' + tileSize[size].h);\n }\n }",
"function addSizesToElement(element, sizes){\n var classString = element.className;\n var currentSizes = getElementSizes(element);\n classString = stripColumns(classString);\n for(i in sizes){\n currentSizes[i] += sizes[i];\n classString += (' col-' + i + '-' + currentSizes[i]);\n }\n element.className = classString;\n}",
"function getClassNames(node) {\n\tif (node) {\n\t\tvar classAttrName = 'class';\n\t\tvar classNames = node.getAttribute(classAttrName) || \"\";\n\t\treturn classNames.split(/\\s+/).filter(function(n) {\n\t\t\treturn n != '';\n\t\t});\n\n\t}\n}",
"function columnSizeValidation(props, propName, componentName) {\n componentName = componentName || \"ANONYMOUS\";\n\n if (props[propName]) {\n const size = props[propName];\n\n if (typeof size === \"number\") {\n return (size <= 6 && size >= 0)\n ? null\n : new Error(\"Prop \" + propName + \" in \" + componentName + \" is \" + size + \", should be a number between 0 to 6\");\n }\n else {\n return new Error(\"Prop \" + propName + \" in \" + componentName + \" should be a number, not a \" + typeof size);\n }\n }\n}",
"function getElementSizes(element){\n var classString = element.className;\n var outObj = {};\n let regexp = /col-[\\w]+-[0-9]+/ig;\n let array = [...classString.matchAll(regexp)];\n for(i in array){\n let string = array[i][0];\n string = string.replace('col-','');\n const index = string.indexOf('-');\n const col = string.substring(0,index);\n const value = parseInt(string.substring(index + 1));\n outObj[col] = value;\n }\n return outObj;\n}",
"function Size(width,height){this.width=width;this.height=height;}",
"function SizeConstraintSet(props) {\n return __assign({ Type: 'AWS::WAF::SizeConstraintSet' }, props);\n }",
"function transformSizes(requestSizes) {\n let sizes = [];\n let sizeObj = {};\n\n if (utils.isArray(requestSizes) && requestSizes.length === 2 && !utils.isArray(requestSizes[0])) {\n sizeObj.width = parseInt(requestSizes[0], 10);\n sizeObj.height = parseInt(requestSizes[1], 10);\n sizes.push(sizeObj);\n } else if (typeof requestSizes === 'object') {\n for (let i = 0; i < requestSizes.length; i++) {\n let size = requestSizes[i];\n sizeObj = {};\n sizeObj.width = parseInt(size[0], 10);\n sizeObj.height = parseInt(size[1], 10);\n sizes.push(sizeObj);\n }\n }\n\n return sizes;\n}",
"__getSize(node) {\n const sizeClass = this.__getClassStartingWith(node, 'fs');\n const fontSize = this.__parseCSSValueToInt(\n cssTree[`.${sizeClass}`]['font-size']\n );\n return fontSize;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the king stands on a threatened field | checkKingsStatus(player){
let tile = this.boardMatrix[player.figureList.King[0].positionY][player.figureList.King[0].positionX];
for(let threat of tile.threatenedBy){
if(player.number !== threat.team) return true;
}
return false;
} | [
"isWeakerThan(hand) {\n // ˅\n return this.judgeGame(hand) === -1;\n // ˄\n }",
"shouldQuarantine() {\n if (this.passengers.find(passenger =>\n passenger.isHealthy === false )) {\n return true\n } else {\n return false\n }\n }",
"isStrongerThan(hand) {\n // ˅\n return this.judgeGame(hand) === 1;\n // ˄\n }",
"function C006_Isolation_Yuki_CheckToEat() {\n\t\n\t// Yuki forces the player if she has the egg\n\tif (C006_Isolation_Yuki_EggInside) {\n\t\tOverridenIntroText = GetText(\"LickEgg\");\n\t\tGameLogAdd(\"Pleasure\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t}\n\n\t// Yuki forces the player if she's dominant\n\tif (ActorGetValue(ActorSubmission) <= -3) {\n\t\tOverridenIntroText = GetText(\"LickSub\");\n\t\tGameLogAdd(\"Pleasure\");\n\t\tC006_Isolation_Yuki_CurrentStage = 200;\n\t}\n\n}",
"function checkEngage(cell, opponent) {\n if (cell === opponent) {\n // TODO: basic support for eating power-ball (which is not in the game yet)\n if (gPacman.isSuper) {\n console.log('Ghost is dead');\n } else {\n clearInterval(gIntervalGhosts);\n gIntervalGhosts = undefined;\n gState.isGameDone = true;\n // TODO: GameOver popup with a play again button\n console.log('Game Over!');\n return true;\n }\n }\n return false;\n}",
"isGameFieldValid() {\n\t\tlet self = this;\n\t\tlet isValid = true;\n\t\tthis.birds.forEach(function(bird) {\n\t\t\tlet h = bird.getHeight();\n\t\t\tlet location = bird.getLocation();\n\t\t\tlet x = location.x;\n\t\t\tlet y = location.y;\n\t\t\tisValid = self.fieldSize.isWithinField(h, x, y);\n\t\t\tif (!isValid) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t});\n\t\treturn isValid;\n\t}",
"function city_has_building(pcity,\n\t\t pimprove)\n{\n /* TODO: implement. */\n return false;\n}",
"function isAnyPartTimeWage(dailyWage){\n return dailyWage.includes(\"80\");\n }",
"function checkCollision(x, y, w, h) {\n if( (chickenX + chickenSize) >= x && \n (chickenY + chickenSize) >= y && \n (chickenX) <= (x + w) && \n (chickenY) <= (y + h)){\n return true;\n } else {\n return false;\n }\n}",
"function check() {\n\tif (userHp <= 0) {\n\t\tline();\n\t\tconsole.log('You LOST to a racoon! How sad for you. :(');\n\t\tline();\n\t\trematch();\n\t} else if (racHp <= 0) {\n\t\tline();\n\t\tconsole.log('You WON! You live to fight another day!');\n\t\tline();\n\t\trematch();\n\t} else {\n\t\tline();\n\t\tconsole.log(`You have ${userHp}Hp left. The raccoon has ${racHp}Hp left`);\n\t\tline();\n\t\tround();\n\t}\n}",
"checkLegal (player, x, y) {\n\n //Is the space occupied?\n if (this.board.get(x, y) !== 0) {\n return false;\n }\n\n return this.__evaluationTest(player, x, y);\n\n }",
"has_ace() {\n if (this.mycards.includes(1)) return true;\n return false;\n }",
"function isInField(x, y)\n{\n if (g_field.x > x || x >= g_field.x + g_field.width )\n {\n return false;\n }\n if (g_field.y > y || y >= g_field.y + g_field.height )\n {\n return false;\n }\n return true;\n}",
"function busted(hand) {\n if (getTotal(hand) > MAX_VALUE) {\n return true;\n } else {\n return false;\n }\n}",
"function canProceedToNextLevel(pelletsEaten) {\n return pelletsEaten === 244; // PacMan needs to eat all 244 pellets to proceed\n}",
"checkEat() {\n let x = convert(this.snake[0].style.left);\n let y = convert(this.snake[0].style.top);\n\n let check = false;\n if (x === this.bait.x && y === this.bait.y) check = true;\n\n return check;\n }",
"function check(smuggler,sheriff,players,decks){\n\tvar smugglerStats = players[smuggler].game;\n\tvar declared = smugglerStats.declared;\n\tvar sheriffStats = players[sheriff].game;\n\tvar lying=false;\n\tvar penalty=0;\n\t//forfeit any bribes\n\tfor(var bribe in player.bribe){\n\t\taddGood(sheriff,bribe);\n\t}\n\tfor(var good in smugglerStats.bag){\n\t\tif(good.name!=declared){\n\t\t\t//reset penalty to start being incurred to smuggler\n\t\t\tif(!lying){\n\t\t\t\tpenalty=0;\n\t\t\t}\n\t\t\tlying=true;\n\t\t\t//discard the good\n\t\t\tif(decks.leftHeap>decks.rightHeap){\n\t\t\t\tdecks.rightHeap.push(good);\n\t\t\t}else{\n\t\t\t\tdecks.leftHeap.push(good);\n\t\t\t}\n\t\t\tpenalty+=good.penalty;\n\t\t}else{\n\t\t\t//if player has been consistently truthful add more penalty\n\t\t\tif(!lying){\n\t\t\t\tpenalty+=good.penalty;\n\t\t\t}\n\t\t}\n\t\tpassThrough(smuggler);\n\t\tvar result;\n\t\tif(!lying){\n\t\t\tsheriffStats.money-=penalty;\n\t\t\tsmugglerStats.money+=penalty;\n\t\t\tresult = 'Tricked again! You lost {penalty} coins for incorrect inspection';\n\t\t}else{\n\t\t\tsheriffStats.money+=penalty;\n\t\t\tsmugglerStats.money-=penalty;\n\t\t\tresult = 'Gotcha! You caught them red handed. Nothing like a good profit';\n\t\t}\n\t\treturn{\"result\":result};\n\t}\n}",
"function isPersonOldEnoughToDrinkAndDrive(obj){\n \n //the condition below checks whether the age satisfies the condition. If the condition is met it returns false\n //because it is illegal to drive and drink in Nigeria\n if (obj.age >= 18){\n return \"false\";\n }else {\n return \"false\";\n }\n}",
"function gameWon(){\n var allCardsFound;\n for (var i = 0; i < cardNb; i++){\n if(!card[i].found){\n allCardsFound = false;\n return allCardsFound;\n }\n }\n if (allCardsFound !== false){\n titleText = \"CONGRATULATIONS\"\n subtitleText = \"You won!\"\n return true;\n }\n else{\n return false;\n }\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
_____________________________________________________________________// This function gets the first index of x values that corresponds to an x valuer greater than x passed, starting from i index _____________________________________________________________________ | function FSS_GetSuperiorIndexOfXValue(i, x)
{
var j, n;
//
j = i;
n = this.coordX.length;
//post("Function GetSuperiorIndexOfXValue i = ", i, " x = ", x, "\n");
while ((this.coordX[j] < x) && (j < n))
{
j += 1;
//post("j=", j, "\n");
}
if (j == n)
{
return (n-1);
}
else
{
if (this.coordX[j] > x)
{
return (-1);
}
else
{
return j;
}
}
return i;
} | [
"function findIndexes (a, v) {\n var upper = _.findIndex(a,function(o) { return o > v});\n if ( upper === 0 ) {\n return [ upper, upper];\n } else if ( upper === -1) {\n return [ a.length-1, a.length-1];\n } \n return [ upper-1, upper];\n }",
"function frogRiverOne(arr, x) {\n let map = {};\n // start at one\n let earliest = -1;\n // start at -1 indicated from the get go that\n for (let i = 0; i < arr.length; i++) {\n if (!map[i + 1] && arr.indexOf(i + 1) !== -1) {\n map[i + 1] = arr.indexOf(i + 1);\n if (arr.indexOf(i + 1) > earliest) {\n earliest = arr.indexOf(i + 1); //?\n }\n }\n }\n if (Object.keys(map).length !== x) {\n // if the map doest have all the values then the other side cant be reached - should return -1\n return -1;\n }\n\n earliest;\n map;\n return earliest;\n}",
"function solution(X, A) {\n var numberOfX = A.filter(function(value) {\n return value === X\n }).length\n\n var count = 0\n\n for (i = 0; i < A.length; i ++) {\n var secondHalfLength = A.length - (i + 1)\n var missingXs = numberOfX - count\n\n if (count === (secondHalfLength - missingXs)) return i\n\n if (A[i] === X) count++\n }\n\n return -1\n }",
"bisection(ab) { // x-axis value\n var ju = this.numKnots-1;\t\t\t\t\t\t\t\t\t\t\t // upper limit\n var jl = 0;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // lower limit\n var jm;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // midpoint\n\n while (ju - jl > 1)\t\t\t\t\t\t\t\n {\n jm = Math.round((ju + jl)/2);\t\t\t\t\t\t\t\t\t// midpoint formula\n\n if (ab > this.arySrcX[jm])\n jl = jm;\n else\n ju = jm;\n }\n return jl;\t\t\n }",
"function indexed_minimumm_calculator(arr, n){\n\tlet least;\n\tfor(i = 0; i < n; i++){\n\t\tleast = Math.min(...arr);\n\t\tleast_index = arr.indexOf(least);\n\t\tarr.splice(least_index, 1);\n\t}\n\treturn least\n}",
"bisect(t, b) {\n const tms = t.getTime();\n const size = this.size();\n let i = b || 0;\n\n if (!size) {\n return undefined;\n }\n\n for (; i < size; i++) {\n const ts = this.at(i).timestamp().getTime();\n if (ts > tms) {\n return i - 1 >= 0 ? i - 1 : 0;\n } else if (ts === tms) {\n return i;\n }\n }\n return i - 1;\n }",
"function position(list, num) {\n for(var i=0; i<list.length ;i++){\n\n if(list[i]>=num &&i<list.length ) {\n\n return i;\n }\n }\n return list.length;\n}",
"evaluatePosition(x)\n {\n let position=-1;\n if(x instanceof Hashable)\n {\n let hashCode=x.hashVal();\n position= hashCode%this._size;\n }\n return position;\n }",
"function getCutoffIndex(array, value) {\n for (var index = 0; index < array.length; ++index) {\n if (array[index] === value) {\n return index + 1;\n }\n }\n\n return 0;\n }",
"function peak(arr){\n \n for(i=0; i < arr.length - 1; i++){\n \n if( arr.slice(0, i + 1).reduce((a,c) => a + c, 0) ===\n \n arr.slice(i + 2).reduce((a,c) => a + c, 0) ) {\n \n return i + 1\n }\n } \n \n return - 1\n \n}",
"function checkTheIndexes(arr, index, result){\n\t//arr[[minusElement, index],[-2,2]]\n\tvar i;\n\tvar j;\n\tfor(i = 0; i < arr.length; i++){\n\t\tfor(j = 0; j < arr.length; j++){\n\t\t\tif(arr[i][1] === index){\n\t\t\t\treturn arr[i][0]\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}",
"function shiftedBinarySearch(array, target) {\n // Write your code here.\n let L = 0\n let R = array.length - 1\n \n while (L <= R) {\n let mid = Math.floor((L + R) / 2)\n let lVal = array[L], rVal = array[R], midVal = array[mid]\n if (midVal === target) return mid\n if (lVal <= midVal) {\n if (target >= lVal && target <= midVal) {\n R = mid - 1\n } else L = mid + 1\n } else {\n if (target <= rVal && target >= midVal) L = mid + 1\n else R = mid - 1\n }\n }\n return -1\n }",
"function ChangingSequence(arr) { \n //loop through each number in array\n for(var i = 1; i < arr.length - 1; i++){\n \t//if current number is greater than previous number and also greater than next number, return index of number\n \tif(arr[i] > arr[i-1] && arr[i] > arr[i+1]){\n \treturn i;\n }\n \t//else if current number is less than previous number and also less than next number, return index of number\n else if(arr[i] < arr[i-1] && arr[i] < arr[i+1]){\n \treturn i;\n }\n }\n //if loop finishes without returning out, return -1\n return -1; \n}",
"function findStopLessThanOrEqualTo$1(stops, input) {\n var n = stops.length;\n var lowerIndex = 0;\n var upperIndex = n - 1;\n var currentIndex = 0;\n var currentValue, upperValue;\n\n while (lowerIndex <= upperIndex) {\n currentIndex = Math.floor((lowerIndex + upperIndex) / 2);\n currentValue = stops[currentIndex][0];\n upperValue = stops[currentIndex + 1][0];\n if (input === currentValue || input > currentValue && input < upperValue) {\n // Search complete\n return currentIndex;\n } else if (currentValue < input) {\n lowerIndex = currentIndex + 1;\n } else if (currentValue > input) {\n upperIndex = currentIndex - 1;\n }\n }\n\n return Math.max(currentIndex - 1, 0);\n }",
"findIndex(pos, end, side = end * Far, startAt = 0) {\n if (pos <= 0)\n return startAt;\n let arr = end < 0 ? this.to : this.from;\n for (let lo = startAt, hi = arr.length;;) {\n if (lo == hi)\n return lo;\n let mid = (lo + hi) >> 1;\n let diff = arr[mid] - pos || (end < 0 ? this.value[mid].startSide : this.value[mid].endSide) - side;\n if (mid == lo)\n return diff >= 0 ? lo : hi;\n if (diff >= 0)\n hi = mid;\n else\n lo = mid + 1;\n }\n }",
"function getIndexToIns(arr, num) {\n arr.sort(function(a, b) {\n return a - b;\n });\n for (var i = 0; i < arr.length; i++) {\n if (num <= arr[i]) {\n break;\n }\n }\n return i;\n}",
"function binarySearch(arr, value) {\n let low = 0;\n let high = arr.length - 1;\n\n while (low <= high) {\n let mid = Math.floor(low + (high - low) / 2);\n if (arr[mid] === value) {\n return mid\n } else if (arr[mid] < value) {\n low = mid + 1;\n } else { //arr[mid] > value\n high = mid - 1;\n }\n }\n\n return -1;\n}",
"function minScoreIndex(array, elements) {\n var minimumScoreIndex = minScore(array, elements);\n for (i = 0; i < BOARD_ELEMENTS; i++) {\n if (array[i] == minimumScoreIndex) {\n return i;\n }\n }\n\n}",
"function getSectionIndex(max, x = 0) {\n let num = Math.floor(Math.random() * max);\n\n if (num === x) {\n return getSectionIndex(max, x);\n }\n\n return num;\n}",
"function getIndex(array, index, key, order) {\n var value = array[index][key],\n tempIndex = index;\n for (var i = index + 1; i < array.length; i++) {\n if (order === \"asc\" && array[i][key] < value || order === \"desc\" && array[i][key] > value) {\n tempIndex = i;\n value = array[i][key];\n }\n }\n return tempIndex;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Answers the question: can the cell (i,j) in the puzzle contain the number in cell "c" | function canBeA(puzzle, i, j, c) {
var x = Math.floor(c / 9);
var y = c % 9;
var value = puzzle[x][y];
if (puzzle[i][j] === value) return true;
if (puzzle[i][j] > 0) return false;
// if not the cell itself, and the mth cell of the group contains the value v, then "no"
// eslint-disable-next-line guard-for-in,no-restricted-syntax
for (var m in Array.from(Array(9).keys())) {
var rowPeer = { x: m, y: j };
var columnPeer = { x: i, y: m };
var SquarePeer = {
x: Math.floor(i / 3) * 3 + Math.floor(m / 3),
y: Math.floor(j / 3) * 3 + m % 3
};
if (!(rowPeer.x === x && rowPeer.y === y) && puzzle[(rowPeer.x, rowPeer.y)] === value) return false;
if (!(columnPeer.x === x && columnPeer.y === y) && puzzle[(columnPeer.x, columnPeer.y)] === value) return false;
if (!(SquarePeer.x === x && SquarePeer.y === y) && puzzle[(SquarePeer.x, SquarePeer.y)] === value) return false;
}
return true;
} | [
"function colCheck(puzzle) {\n for (var c = 0; c < puzzle.length; c++) {\n if(checkColumn(puzzle,c) == false) return false;\n }\n return true;\n}",
"function Check3Cells(RowA, ColA, RowB, ColB, RowC, ColC) {\n\n // Check if all cells are taken by ActivePlayer\n if ($scope.Board[RowA][ColA] == ActivePlayer &&\n $scope.Board[RowB][ColB] == ActivePlayer &&\n $scope.Board[RowC][ColC] == ActivePlayer) {\n\n // Place victory image (either CROSS_WIN or NOUGHT_WIN) in cells and return true\n $scope.Board[RowA][ColA] += 2;\n $scope.Board[RowB][ColB] += 2;\n $scope.Board[RowC][ColC] += 2;\n return true;\n\n }\n else\n return false;\n\n }",
"static EXACT_COVER(sudoku) {\n sudoku.plain.forEach((cell, cellIndex) => {\n // skip if cell is already filled\n if (cell.value === 0) {\n const { row, col, block } = sudoku.getUnitsByPlainIndex(cellIndex);\n const rowCandidates = Sudoku_1.default.getDigitSet(row);\n const colCandidates = Sudoku_1.default.getDigitSet(col);\n const blockCandidates = Sudoku_1.default.getDigitSet(block);\n const candidates = cell.candidates.filter((candidate) => !rowCandidates.includes(candidate) &&\n !colCandidates.includes(candidate) &&\n !blockCandidates.includes(candidate));\n cell.candidates = candidates;\n }\n });\n return sudoku;\n }",
"function sudokuCheck (boardStr) {\n let storage = [{}, {}, {}]\n var solved = true;\n let board = boardStr.split('\\n');\n var result = 'solved';\n reset(storage);\n\n board.forEach(function (row, rowIndex) {\n\n \tif (rowIndex % 3 === 0 && rowIndex !== 0) {\n\n \t\tstorage.forEach(function (sudoku) {\n \t\t\tfor (var key in sudoku) {\n \t\t\t\tif (sudoku[key] !== 1) {\n \t\t\t\t\tsolved = false;\n \t\t\t\t\treturn\n \t\t\t\t}\n \t\t\t}\n \t\t});\n\n \t\tif (!solved) {\n \t\t\tresult = 'invalid'\n \t\t} else {\n \t\t\treset(storage);\n \t\t}\n \t}\n\n \tfor (var i = 0; i < row.length; i++) {\n \t\tif (i < 3) {\n \t\t\tstorage[0][row[i]]++;\n \t\t} else if (i < 6) {\n \t\t\tstorage[1][row[i]]++;\n \t\t} else {\n \t\t\tif (rowIndex > 5) {\n \t\t\t\tconsole.log(row[i])\n \t\t\t\tconsole.log(storage[2])\n \t\t\t}\n \t\t\tstorage[2][row[i]]++;\n \t\t}\n \t}\n\n });\n\n storage.forEach(function (sudoku) {\n \tfor (var key in sudoku) {\n \t\tif (sudoku[key] !== 1) {\n \t\t\tsolved = false;\n \t\t\treturn\n \t\t}\n \t}\n });\n\n if (!solved) {\n \tresult = 'invalid'\n }\n\n return result;\n}",
"function sudokuVerifier(grid) { \n let columns = [];\n let squares = [];\n \n //Grabbing columns\n for(let i = 0; i < 9; i++){\n let tempColumn = [];\n for(let j = 0; j < 9; j++){\n tempColumn.push(grid[j][i]);\n }\n columns.push(tempColumn);\n }\n //grabbing squares, the first two for loops control the current square\n //for instance, i = 0 and j = 0 they are grabbing the top left square\n //they are just multipliers for the position\n for( let i = 0; i < 3; i++){\n for( let j = 0; j < 3; j++){\n let tempSquare = [];\n for(let k = 0; k < 3; k++){\n for(let l = 0; l < 3; l++){\n let x = k + (i * 3);\n let y = l + (j * 3);\n tempSquare.push(grid[x][y]);\n }\n }\n squares.push(tempSquare);\n }\n }\n // numbers in the arrays are still strings, plus the placeholder is a period\n let validChars = '123456789.'.split('');\n return [columns, squares, grid].every( rows => { // All the grids, horizontal, vertical, squares\n return rows.every( row => { // rows in each grid\n let prevArr = [];\n if(row.length !== 9){\n return false;\n }\n return row.every( char => {\n //checks if its a valid character and it hasn't been called before\n if(!prevArr.includes(char) && validChars.includes(char)){\n //dont want to add the place holder otherwise most puzzles would fail!\n if(char !== '.'){\n prevArr.push(char)\n }\n return true;\n } else {\n return false;\n }\n });\n })\n })\n}",
"function isSolvable (puzzleArray, rows, cols) {\n let product = 1\n for (let i = 1, l = rows * cols - 1; i <= l; i++) {\n for (let j = i + 1, m = l + 1; j <= m; j++) {\n product *= (puzzleArray[i - 1] - puzzleArray[j - 1]) / (i - j)\n }\n }\n return Math.round(product) === 1\n}",
"function solve(board) {\n\tconst empty = findUnassigned(board);\n \n\t//if no cell is empty the board is solved\n\tif (!empty) {\n\t\treturn true;\n\t}\n\n\tconst row = empty[0];\n\tconst col = empty[1];\n\n\tfor (let i = 1; i < 10; i++) {\n\n\t\t//if i is valid at empty cell, set cell to i\n\t\tif (checkRow(board, row, col, i) && checkColumn(board, row, col, i) && checkGrid(board, row, col, i)) { \n\t\t\tboard[row][col] = i;\n\n\t\t\tif (solve(board)) { \n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// unset cell\n\t\t\tboard[row][col] = 0;\n\t\t}\n\t}\n\n\treturn false;\n}",
"function areNumbersInRange(puzzle) {\n for (var i = 0; i < puzzle.length; i++) {\n if (puzzle[i] < 0 || puzzle[i] > 9) {\n return false;\n }\n }\n return true;\n }",
"function checkTicketNumber(i, j) {\n for (let k = 0; k < rules.length; k++) {\n if (nearbyTickets[i][j] >= rules[k][1] && nearbyTickets[i][j] <= rules[k][2]) return true;\n if (nearbyTickets[i][j] >= rules[k][3] && nearbyTickets[i][j] <= rules[k][4]) return true;\n }\n return false;\n}",
"function checkGrid(board, y, x, num) {\n\tconst baseX = 3 * Math.floor(x / 3);\n\tconst baseY = 3 * Math.floor(y / 3);\n\n\tfor (let i = 0; i < 3; i++) {\n\t\tfor (let j = 0; j < 3; j++) {\n\t\t\tif (!(j + baseY == y && i + baseX == x) && board[j + baseY][i + baseX] == num) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}",
"function rowsChecker(puzzle){\n for(let i=0;i<9;i++){\n if(repeatsChecker(getRow(puzzle,i))===false){\n return false\n }\n }\n return true\n}",
"function checkRowForWin() {\n var i, totalCount = 1;\n var leftSideComplete = false;\n var rightSideComplete = false;\n var cells = [];\n var row, col;\n \n for(i = 1; i < _config.col; i++){\n \n if (_config.resultArray[c + i] &&\n _config.resultArray[c + i][r] == _config.resultArray[c][r]) {\n //found one \n totalCount++;\n row = r;\n col = c + i;\n cells.push({r:[row],c:[col]}); //Keeping records of winning cells\n }else{\n rightSideComplete = true;\n }\n \n if (_config.resultArray[c - i]\n && _config.resultArray[c - i][r] == _config.resultArray[c][r]) {\n //found one\n totalCount++;\n row = r;\n col = c - i;\n cells.push({r:[row],c:[col]}); //Keeping records of winning cells\n }else{\n leftSideComplete = true;\n }\n \n if (totalCount >= 4){\n //alert(_config.resultArray[c][r] + \" has won the game\");\n cells.push({r:[r],c:[c]});\n _config.winingCells = cells;\n return true;\n }\n \n if (leftSideComplete && rightSideComplete){\n return false;\n }\n \n }\n \n return false;\n }",
"function match3Column() {\n console.log('Checking column matches')\n for (let i = 0; i < width ** 2; i++) {\n if (i >= width ** 2 - width * 2) {\n // console.log(`ignoring i ${i}`)\n } else {\n const first = cells[i].classList[0]\n const second = cells[i + width].classList[0]\n const third = cells[i + width * 2].classList[0]\n const match3C = first === second && first === third\n if (match3C) {\n // console.log(` starting from ${i} ${first} and ${second} and ${third} are the same in the column `)\n return true\n }\n }\n }\n}",
"function safePawns(pawnPosition) {\r\n let nbPawn = pawnPosition.length;\r\n let count = 0;\r\n for (let i = 0; i < nbPawn; i++) {\r\n let workingPawn = pawnPosition[i]\r\n for (let j = 0; j < nbPawn; j++) {\r\n //if pawn have pawn on each side column\r\n if ((workingPawn[0].charCodeAt(0) - 1 == pawnPosition[j][0].charCodeAt(0) || workingPawn[0].charCodeAt(0) + 1 == pawnPosition[j][0].charCodeAt(0)) && (workingPawn[1] - 1 == pawnPosition[j][1])) {\r\n count++\r\n break;\r\n }\r\n }\r\n }\r\n console.log(count);\r\n}",
"function checkBoard() {\n\t\tfor (var i = 0 ; i < 9 ; i++) {\n\t\t\tfor (var k = 0 ; k < 9 ; k++) {\n\t\t\t\tvar col = i+1;\n\t\t\t\tvar row = k+1;\n\t\t\t\tvar string = \"e\"+(col)+(row);\n\t\t\t\tuserBoard[i][k] = document.getElementById(string).value;\n\t\t\t}\n\t\t}\n\t\tfor (var a = 0 ; a < 9 ; a++) {\n\t\t\tfor (var b = 0 ; b < 9 ; b++) {\n\t\t\t\tif ((userBoard[a][b] == goalBoard[a][b]) || (userBoard[a][b] == 0) || (userBoard[a][b] == null)) {\n\t\t\t\t\twrongBoard[a][b] = true;\n\t\t\t\t} else {\n\t\t\t\t\twrongBoard[a][b] = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcheckWrongBoard();\n\n\t}",
"isPossible(row, col) {\n\n // ROW CHECK\n for (let i = 0; i < col; i++)\n if (this.board[row][i])\n return false\n\n // DIAGONAL DOWN\n for (let i = row, j = col; i >= 0 && j >= 0; i--, j--)\n if (this.board[i][j])\n return false\n\n // DIAGONAL UP\n for (let i = row, j = col; j >= 0 && i < this.size; i++, j--)\n if (this.board[i][j])\n return false\n\n return true;\n }",
"function checkConflictSquare(currentSquare, currentSelectedNumber){\n return grid[currentSquare-1].indexOf(currentSelectedNumber) > -1;\n}",
"function checkSolution() {\r\n if (tileMap.empty.position !== 3) {\r\n return false;\r\n }\r\n\r\n for (var key in tileMap) {\r\n if (key == 1 || key == 9) {\r\n continue;\r\n }\r\n\r\n var prevKey = key == 4 ? 'empty' : key == 'empty' ? 2 : key - 1;\r\n if (tileMap[key].position < tileMap[prevKey].position) {\r\n return false;\r\n }\r\n }\r\n\r\n // Clear history if solved\r\n history = [];\r\n return true;\r\n }",
"function search_in_board(element){\r\n\r\n var element_found = 0;\r\n \r\n for(i=0;i<8;i++)\r\n {\r\n for(j=0;j<8;j++)\r\n {\r\n if( document.getElementById(`${i}${j}`).textContent == element )\r\n {\r\n element_found = 1;\r\n \r\n var a = [];\r\n a[0] = i;\r\n a[1] = j;\r\n \r\n return a;\r\n }\r\n }\r\n }\r\n if(element_found == 0){\r\n return -1;\r\n }\r\n}",
"__hasOccupiedNeighbours(colour, x, y){\n if (x - 1 > -1) {\n if(this.board.get(x-1, y) === colour){\n return true;\n }\n }\n if (y - 1 > -1) {\n if(this.board.get(x, y-1) === colour){\n return true;\n }\n }\n if (x + 1 < this.size) {\n if(this.board.get(x+1, y) === colour){\n return true;\n }\n }\n if (y + 1 < this.size) {\n if(this.board.get(x, y+1) === colour){\n return true;\n }\n }\n return false;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registro de los slides por numero. / SlideWindow Constructor / p_xo = Coordenada X en pixels. p_yo = Coordenada Y en pixels. p_hgt = Altura en pixels. p_wth = Ancho X en pixels. p_to = Timeout en segundos | function SlideWindow(name, url, p_wth, p_hgt, p_to) {
this.base = AbstractWindow;
this.base(url, 0, 0, p_wth, 1);
/* Atributes */
this.name = name;
this.timeOut = p_to * 1000 || 15000; //TimeOut
this.yoEnd; //Ending move coordinate
this.xoEnd; //Ending move coordinate
this.process = -1; //Generic process
this.createContent = function() {
var ifrm = document.createElement("iframe");
ifrm.className= this.classShow;
ifrm.setAttribute("class", this.classShow);
ifrm.height = this.hgt;
ifrm.src = this.url;
ifrm.style.scrolling = "auto";
return ifrm;
}
this.ultimoElementoActivo = function() {
var index = slideRegister.length - 1;
while ((index >= 0) && (slideRegister[index] == undefined)) index--;
var ret = (slideRegister[index])? slideRegister[index] : undefined;
//Si se acumularon muchas ventanas cerradas y no hay ninguna activa, reinicio el registro.
if ((!ret) && (slideRegister.length > 50)) slideRegister = Array();
return ret;
}
/* Determina Xo e Yo */
//Asume que es la primera ventana.
this.xo = this.determineWidth() - this.wth - 5;
this.yo = this.determineHeight() - 5;
//Se posiciona basandose en el slide anterior.
var elem = this.ultimoElementoActivo();
if (elem != undefined) {
//Se supone que la nueva ventana va a estar encima de la ultima mostrada.
var xoAux = this.xo;
this.xo = elem.xo;
//Se calcula hasta donde llega, si se sale de la pantalla, lo mueve al costado.
var yoAux = elem.yoEnd;
if ((yoAux - p_hgt) < 0)
//Se va de pantalla.
this.xo = this.xo - this.wth - 5;
else
//No se va de pantalla.
this.yo = elem.yoEnd;
}
/* Determina la posicion final */
this.yoEnd = this.yo - p_hgt - 5;
this.xoEnd = this.xo;
/* Se setean los estilos */
this.classShow = "iwinSlideWindow";
/* Muestra la ventana */
this.show();
/* Registra la ventana */
slideRegister.push(this);
slideNameRegister[this.name] = this;
/* Mueve la ventana */
iwinMoveIt(slideRegister.length - 1);
return this;
} | [
"function slideWindow() {\n ++windowSb;\n ++windowSm;\n\n if (Number(windowSm) >= Number(totalFrames)) {\n windowSm = totalFrames - 1;\n return; // Done\n }\n\n windowPanel.animate({\n left: sfSlots[windowSb].position().left + 2\n }, 50);\n sendInfoFrame(windowSm); //After a slide, send a info frame\n}",
"function setSlidesAndWrapper() {\n var i;\n zwiperSlides = zwiperContainer.querySelectorAll('.' + zwiperSettings.slide);\n console.log('Number of slides: ', zwiperSlides.length);\n\n // create wrapper that serves as the sliding element\n zwiperWrapper = document.createElement('div');\n addClass(zwiperWrapper, 'zwiper-wrapper');\n\n for (i = 0; i < zwiperSlides.length; i += 1) {\n zwiperWrapper.appendChild(zwiperSlides[i]);\n }\n\n zwiperContainer.appendChild(zwiperWrapper);\n\n // set width for each of the slides\n for (i = 0; i < zwiperSlides.length; i += 1) {\n zwiperSlides[i].setAttribute('style', 'width: ' + zwiperContainerWidth + 'px;');\n }\n\n // wrapper is container width * nr of slides\n zwiperWrapper.setAttribute('style', 'width: ' + (zwiperContainerWidth * zwiperSlides.length) + 'px;');\n zwiperWrapper.style[prefixProp.transform] = 'translate3D(0,0,0)';\n }",
"function createWindow() {\n\n windowPanel = $(\"<div></div>\"); //Sliding Window\n windowPanel.addClass(\"swindow\");\n var sfSlot = sfSlots[windowSb];\n var width = sfSlot.outerWidth() * windowSize + windowSize * 10 + 2;\n windowPanel.css(\"width\", width);\n windowPanel.css({\n top: sfSlot.position().top - 10,\n left: sfSlot.position().left,\n position: \"absolute\"\n });\n $(\"#medium\").append(windowPanel);\n}",
"function AbstractWindow(url, p_xo, p_yo, p_wth, p_hgt) {\r\n /* Clase para mostrar la ventana*/\r\n\tthis.classHide = \"iwinContainerHide\";\r\n\t/* Clase para ocultar la ventana*/\r\n\tthis.classShow = \"iwinContainer\";\t\r\n\t/* Atributos */\r\n this.xo = p_xo || 0;\r\n this.yo = p_yo || 0;\r\n this.wth = p_wth || 100;\r\n this.hgt = p_hgt || 100;\r\n this.url = url;\r\n this.created = false;\r\n this.visible = false;\r\n /*HTML Atributes */\r\n this.element = null;\r\n /* Methods */\r\n\t/* This function shows de basedow */\r\n\tthis.show = function() {\r\n\t\t\t\t\t\tthis.show_prev();\r\n\t\t\t\t\t\t/* Se crea la ventana */\r\n\t\t\t\t\t\tthis.element = document.createElement(\"div\");\t\t\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\tthis.element.appendChild(this.createContent());\r\n\t\t\t\t\t\t/* Se agrega la ventana al cuerpo de la pagina */\r\n\t\t\t\t\t\tdocument.body.appendChild(this.element);\r\n\t\t\t\t\t\tthis.element.className = this.classShow;\t\t\t\t\t\t\r\n\t\t\t\t\t\tthis.locateWindow(this.xo, this.yo, this.wth, this.hgt);\r\n\t\t\t\t\t\tthis.visible = true;\r\n\t\t\t\t\t\tthis.show_next();\r\n\t\t\t\t}\r\n\t\r\n /* This function Hides the basedow */\r\n\tthis.hide =\tfunction() {\t\t\r\n\t\t\t\t\tvar ret = true;\r\n\t\t\t\t\tif (this.onHideStart) eval(this.onHideStart);\r\n\t\t\t\t\tif (ret) {\r\n\t\t\t\t\t\tthis.hide_prev();\r\n\t\t\t\t\t\tthis.element.className = this.classHide;\r\n\t\t\t\t\t\tthis.visible = false;\r\n\t\t\t\t\t\tthis.hide_next();\r\n\t\t\t\t\t\tif (this.onHideEnd) eval(this.onHideEnd);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\tthis.locateWindow =\tfunction (x, y, w, h) {\r\n\t\t\t\t\t\t\t\tthis.wth=w;\r\n\t\t\t\t\t\t\t\tthis.hgt=h;\r\n\t\t\t\t\t\t\t\tthis.xo=x;\r\n\t\t\t\t\t\t\t\tthis.yo=y;\r\n\t\t\t\t\t\t\t\tthis.element.style.left = x + 'px' ;\r\n\t\t\t\t\t\t\t\tthis.element.style.top = y + 'px';\t\r\n\t\t\t\t\t\t\t}\r\n\tthis.determineWidth = \tfunction() {\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tvar w = window.innerWidth\r\n\t\t\t\t\t\t\t\t\t\t|| document.documentElement.clientWidth\r\n\t\t\t\t\t\t\t\t\t\t|| document.body.clientWidth;\t\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\treturn w;\r\n\t\t\t\t\t\t\t}\r\n\tthis.determineHeight =\tfunction() {\r\n\t\t\t\t\t\t\t\tvar h = window.innerHeight\r\n\t\t\t\t\t\t\t\t\t|| document.documentElement.clientHeight\r\n\t\t\t\t\t\t\t\t\t|| document.body.clientHeight; \r\n\t\t\t\t\t\t\t\treturn h;\r\n\t\t\t\t\t\t\t}\r\n\t/****\r\n\t** Metodos a definir en una clase hijo\r\n\t*****/\r\n\t/* Funcion que genera el contenido de la ventana, debe ser redefinida por las clases herederas para cambiar su funcionamiento \r\n\t* @Abstract\r\n\t*/\r\n\tthis.createContent = \tfunction() { alert(\"Debe redefinir el metodo 'createContent'\");\t}\r\n\t/* Metodos a redefinir en una clase hijo para ejecutar codigo propio antes y despues de la operacion show*/\t\t\t\r\n\tthis.show_prev = function() {}\r\n\tthis.show_next = function() {}\t\r\n\t/* Metodos a redefinir en una clase hijo para ejecutar codigo propio antes y despues de la operacion hide */\t\t\t\r\n\tthis.hide_prev = function() {}\r\n\tthis.hide_next = function() {}\t\r\n\t/**\r\n\t * Eventos que el usuario puede definir para obtener control de la ventana\r\n\t * Si devuelven false, susupende la ejecución del evento. \r\n\t */\r\n\tthis.onHideStart = undefined;\t//Antes de Cerrar (Debe devolver true/false).\r\n\tthis.onHideEnd = undefined;\t//Despues de Cerrar\r\n}",
"function Slider(prefix,dir,dim,progress,add_px)\n\t{\n\t//get block and asign it with events\n\n\tthis.scroll_left_button = document.get_elements_by_class_name(prefix+'_scroll_button_left')[0];\n\tthis.scroll_right_button = document.get_elements_by_class_name(prefix+'_scroll_button_right')[0];\n\tthis.container = document.get_elements_by_class_name(prefix+'_item_container')[0];\n\tthis.container_visible = document.get_elements_by_class_name(prefix+'_block')[0]; //to calculate margin distance for moving\n\n\n\tif (progress=='on')\n\t\t{\n\t\tthis.progress_bar = document.get_elements_by_class_name(prefix+'_progress_bar')[0]; //for progress bar\n\t\tthis.progress_bar_feel = this.progress_bar.get_elements_by_class_name(prefix+'_feel')[0]; \n\t\t}\n\n\t\t\n\tvar obj = this; //nessesary for passing OBJECT for next functions\n\t\n\n\tthis.scroll_left_button.add_event_listener('click',function() {obj.move_left()},false);\n\tthis.scroll_right_button.add_event_listener('click',function() {obj.move_right()},'false');\n\tthis.container.add_event_listener('mousedown',function(event) {obj.touch_click_on(event);try{event.preventDefault()}catch(err){event.returnValue=false};},false);\n\tthis.container.add_event_listener('mouseup',function(event) {obj.touch_click_off(event)},false);\n\tthis.container.add_event_listener('mousemove',function(event) {obj.mouse_move(event);event.returnValue=false;},false);\n\n\t//for touch events add new listener\n\n\tthis.container.add_event_listener('touchstart',function(event) {obj.touch_click_on(event);try{event.preventDefault()}catch(err){event.returnValue=false;}},false);\n\tthis.container.add_event_listener('touchend',function(event) {obj.touch_click_off(event);try{event.preventDefault()}catch(err){event.returnValue=false;}},false);\n\tthis.container.add_event_listener('touchmove',function(event) {obj.mouse_move(event);try{event.preventDefault()}catch(err){event.returnValue=false;}; return false;},false);\n\n\n\n\n\tthis.prefix = prefix;\n\t\n\tthis.dir = dir; //direction X - horizontal, Y - vertical\n\tthis.dim = dim; // dimensions px - pixels, % - interests\n\tthis.add_px = add_px; //add pixels to distanse between items\n\n\tthis.cur_transX = 0; //current translate X value\n\tthis.cur_transY = 0; //current translate Y value;\n\tthis.cur_transY_tmp = 0; //using for previous value of transX.Y during mousemoving\n\tthis.cur_transX_tmp = 0;\n\n\tthis.cur_mouse_flag = 'stop'; //flag for touch scroll activation\n\tthis.cur_mouseX = 0; //current mouse coordinates (retrives from listener when flag !=stop)\n\tthis.cur_mouseY = 0; \n\tthis.onclick_mouseX = 0; //coordinates of mouse cursor when mouse buttons had pressed\n\tthis.onclick_mouseY = 0;\t\n\t\n\tthis.container_height = 0; //is determinig during set_container_size execution\n\tthis.container_width = 0; //nessesary to know margin top and left distance\n\tthis.container_X_width = 0; //width of block, using for screen size changing (width of visible container on load page moment)\n\n\n\t//for ie8 python determine browser and write additional block at the end of html with display=none, if we will find block - innertion must me 'off', because ie8 do not perfect work with innertion\n\tthis.innertion_da = document.get_element_by_id('ie8_marker');\n\tif (this.innertion_da)\n\t\t{\n\t\tthis.innertion_da = 'no'; //we have found ie8 marker\n\t\t}\n\n\telse\n\t\t{\n\t\tthis.innertion_da = 'yes';\n\t\t}\n\tthis.max_left = 0; //max left - max dis for move to the end on X (set cont size)\n\tthis.max_top = 0; //max top - max distance for moving to the down on Y line \n\tthis.innertion_array = []; //array for innertion\n\tthis.innertion_array_time = [] //array with time\n\tthis.innertion_prev_time = 0; //previous timestamp\n\tthis.innertion_prev_trans = 0; //previous cur_transX\n\tthis.innertion_items=5; //kolvo items in array for avg speed calculations\n\n\n/// train with speed\n\tthis.prev_time = 0;\n\tthis.progress_bar_par = progress; //\"on\" - parametr to switch on progress bar animate\n\tthis.feel_width = 0; // width of feeling div from progress bar (X line) in %%\n\tthis.feel_height = 0; // height of feeling div from progress bar (Y line in %%)\n\tthis.pb_length = 0; //length of progress bar (by X or by Y) \n\n\t/////////////////////////\n\n\tthis.move_left = function()\n\t\t{\n\t\t//check if slider is working\n\t\tif (this.id_timer!='none'&&this.id_timer!=undefined)\n\t\t\t{\n\t\t\treturn;\n\t\t\t}\n\n\n\t\tthis.check_container_size(); // it to keep actual block size when screen size changing\n\t\t//for click efect\n\t\tthis.scroll_left_button.className += ' '+this.prefix+'_scroll_button_left_click';\n\t\tthis.id_timer = setInterval(\n\t\t\tfunction()\n\t\t\t{\n\t\t\tobj.scroll_left_button.className = obj.prefix+'_scroll_button_left';clearInterval(obj.id_timer);\n\t\t\tobj.id_timer = 'none';\n\t\t\t},200)\n\n\n\t\t//forsmoth moving\n\t\tif (this.dir=='X')\n\t\t\t{\n\t\t\tif (this.cur_transX==0) //for spring\n\t\t\t\t{\n\t\t\t\tback_ = function()\n\t\t\t\t\t{\n\t\t\t\t\tobj.transition_on_off(0.2);\n\t\t\t\t\tobj.container.style['left'] = '0px';\n\t\t\t\t\tclearInterval(obj.id_ttt);\n\t\t\t\t\t}\n\t\t\t\tthis.transition_on_off(0.2);\n\t\t\t\tthis.container.style['left'] = '50px';\n\t\t\t\tthis.id_ttt = setInterval(back_,200);\n\t\t\t\t}\n\t\t\telse //simple moving by X\n\t\t\t\t{\n\t\t\t\tthis.transition_on_off(1);\n\t\t\t\tthis.move_by(200);\n\t\t\t\tthis.transition_on_off(0);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tif (this.cur_transY==0) //for spring\n\t\t\t\t{\n\t\t\t\tback_ = function()\n\t\t\t\t\t{\n\t\t\t\t\tobj.transition_on_off(0.2);\n\t\t\t\t\tobj.container.style['top'] = '0px';\n\t\t\t\t\tclearInterval(obj.id_ttt);\n\t\t\t\t\t}\n\t\t\t\tthis.transition_on_off(0.2);\n\t\t\t\tthis.container.style['top'] = '50px';\n\t\t\t\tthis.id_ttt = setInterval(back_,200);\n\t\t\t\t}\n\t\t\telse //simple moving by Y\n\t\t\t\t{\n\t\t\t\tthis.transition_on_off(1);\n\t\t\t\tthis.move_by(200);\n\t\t\t\tthis.transition_on_off(0);\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\n\n\tthis.move_right = function()\n\t\t{\n\t\tthis.check_container_size(); // it to keep actual block size when screen size changing\n\n\t\t//check if slider is working\n\t\tif (this.id_timer!='none'&&this.id_timer!=undefined)\n\t\t\t{\n\t\t\treturn;\n\t\t\t}\n\n\t\t//for click effect\n\t\tthis.scroll_right_button.className += ' '+this.prefix+'_scroll_button_right_click';\n\t\tthis.id_timer = setInterval(\n\t\t\tfunction()\n\t\t\t{\n\t\t\tobj.scroll_right_button.className = obj.prefix+'_scroll_button_right';clearInterval(obj.id_timer);\n\t\t\tobj.id_timer = 'none';\n\t\t\t},200)\n\t\t\n\n\t\t//for smoth\n\t\tif (this.dir=='X')\n\t\t\t{\n\t\t\tif (this.cur_transX==-this.max_left) //for spring\n\t\t\t\t{\n\t\t\t\tback_ = function()\n\t\t\t\t\t{\n\t\t\t\t\tobj.transition_on_off(0.2);\n\t\t\t\t\tobj.container.style['left'] = -obj.max_left+'px';\n\t\t\t\t\tclearInterval(obj.id_ttt);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\td = -this.max_left-50;\n\t\t\t\tthis.transition_on_off(0.2);\n\t\t\t\tthis.container.style['left'] = d+'px';\n\t\t\t\tthis.id_ttt = setInterval(back_,200);\n\t\t\t\t}\n\t\t\telse //simple moving by X\n\t\t\t\t{\n\t\t\t\tthis.transition_on_off(1);\n\t\t\t\tthis.move_by(-200);\n\t\t\t\tthis.transition_on_off(0);\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tif (this.cur_transY==-this.max_top) //for spring\n\t\t\t\t{\n\t\t\t\tback_ = function()\n\t\t\t\t\t{\n\t\t\t\t\tobj.transition_on_off(0.2);\n\t\t\t\t\tobj.container.style['top'] = -obj.max_top+'px';\n\t\t\t\t\tclearInterval(obj.id_ttt);\n\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\td = -obj.max_top-50;\n\t\t\t\tthis.transition_on_off(0.2);\n\t\t\t\tthis.container.style['top'] = d+'px';\n\t\t\t\tthis.id_ttt = setInterval(back_,200);\n\t\t\t\t}\n\t\t\telse //simple moving by Y\n\t\t\t\t{\n\t\t\t\tthis.transition_on_off(1);\n\t\t\t\tthis.move_by(-200);\n\t\t\t\tthis.transition_on_off(0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\n\tthis.touch_click_on = function(e)\n\t\t{\n\t\tthis.check_container_size(); // it to keep actual block size when screen size changing\n\t\tif (!e) {e = window.event}\n\t\ttry //for touches\n\t\t\t{\n\t\t\tif (this.innertion_da=='yes')\n\t\t\t\t{\n\t\t\t\tthis.innertion('start'); //for innertion (initial prev variables)\n\t\t\t\t}\n\t\n\t\t\tt = e.changedTouches[0];\n\t\t\tthis.onclick_mouseY = t.clientY;\n\t\t\tthis.onclick_mouseX = t.clientX;\n\t\t\tthis.cur_mouse_flag = 'start';\n\t\t\tthis.cur_transX_tmp = this.cur_transX;\n\t\t\tthis.cur_transY_tmp = this.cur_transY;\n\n\t\t\t}\n\t\tcatch(err)\n\t\t\t{\n\t\t\tif (this.innertion_da=='yes')\n\t\t\t\t{\n\t\t\t\tthis.innertion('start'); //for innertion (initial prev variables)\n\t\t\t\t}\n\n\t\t\tthis.onclick_mouseX = e.clientX;\n\t\t\tthis.onclick_mouseY = e.clientY;\n\t\t\tthis.cur_mouse_flag = 'start';\n\t\t\tthis.cur_transX_tmp = this.cur_transX;\n\t\t\tthis.cur_transY_tmp = this.cur_transY;\n\t\t\t}\n\n\t\t}\n\n\tthis.touch_click_off = function(e)\n\t\t{\n\n\t\tif (!e) {e = window.event}\n\t\tthis.cur_mouse_flag = 'stop';\n\n\t\tif (this.dir=='X')\n\t\t\t{\n\t\t\tif (this.cur_transX>0) //spring\n\t\t\t\t{\n\t\t\t\tthis.transition_on_off(0.2);\n\t\t\t\tthis.container.style['left'] = '0px'; \n\t\t\t\tthis.transition_on_off(0);\n\t\t\t\tthis.cur_transX = 0;\n\t\t\t\t}\n\t\t\tif (this.cur_transX>=-this.max_left-50&this.cur_transX<-this.max_left)\n\t\t\t\t{\n\t\t\t\tthis.transition_on_off(0.2);\n\t\t\t\tthis.container.style['left'] = -this.max_left+'px';\n\t\t\t\tthis.transition_on_off(0);\n\t\t\t\tthis.cur_transX = -this.max_left;\n\t\t\t\t}\n\n\t\t\tif (this.cur_transX>-this.max_left&this.cur_transX<0&this.innertion_da=='yes')\n\t\t\t\t{\n\t\t\t\tspeed = this.innertion('stop'); //for innertion\n\t\t\t\tdis = speed*300*0.7;\n\t\t\t\tif (dis!=0)\n\t\t\t\t\t{\t\t\t\t\t\n\t\t\t\t\tthis.transition_on_off(1);\n\t\t\t\t\tthis.move_by(dis);\n\t\t\t\t\tthis.transition_on_off(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\telse\n\t\t\t{\n\t\t\tif (this.cur_transY>0) //spring\n\t\t\t\t{\n\t\t\t\tthis.transition_on_off(0.2);\n\t\t\t\tthis.container.style['top'] = '0px';\n\t\t\t\tthis.transition_on_off(0);\n\t\t\t\tthis.cur_transY = 0;\n\t\n\t\t\t\t}\n\t\t\tif (this.cur_transY>=-this.max_top-50&this.cur_transY<-this.max_top)\n\t\t\t\t{\n\t\t\t\tthis.transition_on_off(0.2);\n\t\t\t\tthis.container.style['top'] = -this.max_top+'px';\n\t\t\t\tthis.transition_on_off(0);\n\t\t\t\tthis.cur_transY = -this.max_top;\n\t\n\t\t\t\t}\n\t\t\tif (this.cur_transY>-this.max_top&this.cur_transY<0&this.innertion_da=='yes')\n\t\t\t\t{\n\t\t\t\tspeed = this.innertion('stop'); //for innertion\n\t\t\t\tdis = speed*300*0.7;\n\t\t\t\tif (dis!=0)\n\t\t\t\t\t{\t\t\t\t\t\n\t\t\t\t\tthis.transition_on_off(1);\n\t\t\t\t\tthis.move_by(dis);\n\t\t\t\t\tthis.transition_on_off(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\n\t\t\t}\n\n\t\t}\n\n\n\t\n\n\n//////////////////////////////\n\n\tthis.set_container_size = function() //fit size of container, by X or Y, add_px - add_px to each item\n\t\t{\n\t\t//get item container size\n\t\tarray_items = document.get_elements_by_class_name(prefix+'_item');\n\t\t\n\t\tlen_arr = array_items.length;\n\t\tlen_itemX = array_items[0].offsetWidth;\n\t\tlen_itemY = array_items[0].offsetHeight;\n\n\t\tif (this.dir=='X')\n\t\t\t{\n\n\t\t\tif (this.container_visible.offsetWidth!=this.container_X_width)\n\t\t\t\t{\n\t\t\t\tthis.container_X_width = this.container_visible.offsetWidth;\n\t\t\t\t}\n\n\t\t\tthis.container_width = len_arr*(len_itemX+this.add_px);\n\t\t\tthis.container.style.width = this.container_width+'px';\n\t\t\tthis.max_left = this.container_width - this.container_visible.offsetWidth;\n\t\t\t}\n\n\t\telse\n\t\t\t{\n\n\t\t\t//width of items may be different because text may lay verticaly caused screen declining and different items can havedifferent desciption\n\n\t\t\tvar total_width\t=0;\n\t\t\tfor (i=0;i<len_arr;i=i+1)\n\t\t\t\t{total_width = total_width+array_items[i].offsetHeight}\n\n\t\t\t\n\t\t\tthis.container_height = len_arr*(this.add_px)+total_width+30; //30px is height of free item above all other items (under top line), also you need to correct check_size() function\n\t\t\tthis.container.style.height = this.container_height+'px';\n\t\t\tthis.max_top = this.container_height - this.container_visible.offsetHeight;\n\t\t\t\n\t\t\t}\n\n\n\t\t//set progress bar height or width\n\t\tif (this.dir=='X'&this.progres_bar_par=='on')\n\t\t\t{\n\t\t\tdif_koef = this.max_left/this.container_width;\n\t\t\tthis.feel_width = 1 - dif_koef;\t\t\t\n\t\t\tthis.progress_bar_feel.style['width'] = this.feel_width*100+'%';\n\t\t\tthis.pb_length = this.progress_bar.offsetWidth;\t\n\t\t\t}\n\t\n\t\tif (this.dir=='Y'&this.progress_bar_par=='on')\n\t\t\t{\n\t\t\tdif_koef = this.max_top/this.container_height;\n\t\t\tthis.feel_height = 1 - dif_koef;\t\t\t\n\t\t\tthis.progress_bar_feel.style['height'] = this.feel_height*100+'%';\n\t\t\tthis.pb_length = this.progress_bar.offsetHeight;\t\n\t\t\t}\n\n\t\t//set no-selection for all images in container (switched off, because it is working throught bumbling to container with its event handler and preventDefault. Also mousemove for ie8 must be alse preventDefault)\n//\t\tfor (i=0;i<len_arr;i=i+1)\n//\t\t\t{\n//\t\t\timages = array_items[i].get_elements_by_tag_name('img');\n//\t\t\tkolvo_img = images.length;\n//\t\t\tfor (k=0;k<kolvo_img;k=k+1)\n//\t\t\t\t{\n//\t\t\t\timg_ = images[k];\n//\t\t\t\timg_.add_event_listener('mousedown',function(event){try{event.preventDefault()}catch(err){event.returnValue=false;}},false);\n\t\t\t\t\n//\t\t\t\t}\n//\t\t\t}\n\n\n\n\t\t}\n\n\tthis.set_container_size() //put it to the end of file to provide firtsly initializing of function and next execution;\n\n\n\n\tthis.check_container_size = function() //it is nessesary when window size is changing to keep scrolling (calculation of new block size and free width, it is only for X direction)\n\t\t{\n\n\t\tif (this.dir=='X')\n\t\t\t{\n\t\t\tif (this.container_visible.offsetWidth!=this.container_X_width)\n\t\t\t\t{\n\t\t\t\tthis.max_left = this.container_width - this.container_visible.offsetWidth;\n\t\t\t\tthis.container_X_width = this.container_visible.offsetWidth;\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\n\t\t\t//for y we need to calculate new height in a case of changing screen width, because text push block height\n\t\t\tif (this.container_visible.offsetWidth!=this.container_X_width)\n\t\t\t\t{\n\t\t\t\tarray_items = document.get_elements_by_class_name(prefix+'_item');\n\t\t\t\n\t\t\t\tlen_arr = array_items.length;\n\t\t\t\tlen_itemY = array_items[0].offsetHeight;\n\t\t\t\t\n\t\t\t\tvar total_width\t=0;\n\t\t\t\tfor (i=0;i<len_arr;i=i+1)\n\t\t\t\t\t{total_width = total_width+array_items[i].offsetHeight}\n\n\t\t\t\n\t\t\t\tthis.container_height = len_arr*(this.add_px)+total_width+30;\n\t\t\t\tthis.container.style.height = this.container_height+'px';\n\t\t\t\tthis.max_top = this.container_height - this.container_visible.offsetHeight;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\n\t\t}\n\n\n\n\n\tthis.innertion = function(status_)\n\t\t{\n\t\n\t\tif (status_=='start')\n\t\t\t{\n\t\t\tthis.innertion_array = []; //new inner masiv for distansecollection\n\t\t\tthis.innertion_array_time = [] //new array for time collection\n\t\t\tthis.innertion_prev_time = new Date().getTime();\n\t\t\tif (this.dir=='X')\n\t\t\t\t{\n\t\t\t\tthis.innertion_prev_trans = this.cur_transX;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tthis.innertion_prev_trans = this.cur_transY;\n\t\t\t\t}\n\t\t\t}\n\n\t\n\t\tif (status_=='moving')\n\t\t\t{\n\t\t\tif (this.dir=='X')\n\t\t\t\t{\n\t\t\t\tdif = this.cur_transX-this.innertion_prev_trans;\n\t\t\t\tthis.innertion_prev_trans = this.cur_transX;\n\t\t\t\tcur_time = new Date().getTime();\n\t\t\t\ttime_dif = cur_time - this.innertion_prev_time;\n\t\t\t\tthis.innertion_prev_time = cur_time;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tdif = this.cur_transY-this.innertion_prev_trans;\n\t\t\t\tthis.innertion_prev_trans = this.cur_transY;\n\t\t\t\tcur_time = new Date().getTime();\n\t\t\t\ttime_dif = this.innertion_prev_time - cur_time;\n\t\t\t\tthis.innertion_prev_time = cur_time;\n\t\t\t\t}\n\n\t\t\tthis.innertion_array.push(dif);\n\t\t\tthis.innertion_array_time.push(time_dif);\n\t\t\t}\n\t\telse //stop\n\t\t\t{\n\t\t\tlen = this.innertion_array.length;\n\t\t\ttotal_time = 0;\n\t\t\ttotal_dis = 0;\n\t\t\tfor (i=0;i<this.innertion_items;i=i+1)\n\t\t\t\t{\n\t\t\t\ttotal_dis = total_dis+Math.abs(this.innertion_array[len-1-i]);\n\t\t\t\ttotal_time = total_time+Math.abs(this.innertion_array_time[len-1-i]);\n\t\t\t\t\n\t\t\t\t}\n\t\t\tlast_dis = this.innertion_array[len-1]; \n\t\t\tspeed = total_dis/total_time;\n\t\t\tif (last_dis>0)\n\t\t\t\t{\n\t\t\t\tspeed = speed;\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tspeed = -speed;\n\t\t\t\t}\n\t\t\tif (this.innertion_array.length<this.innertion_items)\n\t\t\t\t{speed=0}\n\t\t\tthis.innertion_array = [];\n\t\t\tthis.innertion_array_time = [];\n\t\t\treturn speed;\n\t\t\t}\n\t\t}\n\n\n\n\n\tthis.move_by = function(dis) //obj = this,dis = distance for moving, dim = dimensions:px or %%, dir = direction:'X' or 'Y'\n\t\t{\n\t\tif (this.dir=='X')\n\t\t\t{\n\t\t\tdis_move = dis+this.cur_transX;\n\t\t\tif (dis_move<=-this.max_left)\n\t\t\t\t{dis_move = -this.max_left}\n\t\t\tif (dis_move>=0)\n\t\t\t\t{dis_move = 0}\n\t\t\tthis.container.style['left'] = dis_move+this.dim;\n\t\t\tthis.cur_transX = dis_move;\n\t\t\t\n\t\t\tif(this.progress_bar_par=='on')\n\t\t\t\t{\n\t\t\t\tpb_mv = -this.cur_transX/this.container_width;\n\t\t\t\tpb_mv = pb_mv*this.pb_length;\n\t\t\t\tthis.progress_bar_feel.style['margin'] = '0px 0px 0px '+pb_mv+'px';\n\t\t\t\t}\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\tdis_move = dis+this.cur_transY;\n\t\t\tif (dis_move<=-this.max_top)\n\t\t\t\t{dis_move = -this.max_top}\n\t\t\tif (dis_move>=0)\n\t\t\t\t{dis_move = 0}\n\n\t\t\tthis.container.style['top'] = dis_move+this.dim;\n\t\t\tthis.cur_transY = dis_move;\n\t\t\tif(this.progress_bar_par=='on') //for progress bar moving\n\t\t\t\t{\n\t\t\t\tpb_mv = -this.cur_transY/this.container_height;\n\t\t\t\tpb_mv = pb_mv*this.pb_length; //calculate in pixels length\n\t\t\t\tthis.progress_bar_feel.style['margin'] = pb_mv+'px 0px 0px -1px';\n\t\t\t\t}\n\t\t\t}\n\n\t\n\t\t}\n\n\tthis.move_by(0); //this is nessesary to provide smoth moving from the first click\n\n\tthis.transition_on_off = function(speed)\n\t\t{\n\t\tthis.container.offsetHeight;\n\t\tif (this.dir=='X')\n\t\t\t{\n\t\t\tthis.container.style['transition'] = 'left '+speed+'s ease';\n\t\t\tthis.container.style['-moz-transition'] = 'left '+speed+'s ease';\n\t\t\tthis.container.style['-o-transition'] = 'left '+speed+'s ease';\n\t\t\tthis.container.style['-ms-transition'] = 'left '+speed+'s ease';\n\t\t\tthis.container.style['-webkit-transition'] = 'left '+speed+'s ease';\n\t\t\tthis.container.style['-khtmltransition'] = 'left '+speed+'s ease';\n\t}\n\t\telse\n\t\t\t{\n\t\t\tthis.container.style['transition'] = 'top '+speed+'s ease';\n\t\t\tthis.container.style['-moz-transition'] = 'top '+speed+'s ease';\n\t\t\tthis.container.style['-o-transition'] = 'top '+speed+'s ease';\n\t\t\tthis.container.style['-webkit-transition'] = 'top '+speed+'s ease';\n\t\t\tthis.container.style['-ms-transition'] = 'top '+speed+'s ease';\n\t\t\tthis.container.style['-khtml-transition'] = 'top '+speed+'s ease';\n\t\t\t}\n\t\t}\n\n\n\n\t//mouse move listener, translate in specific direction by move px\n\tthis.mouse_move = function(e)\n\t\t{\n\t\t\n\t\tif (obj.cur_mouse_flag!='stop')\n\t\t\t{\n\t\t\tif (!e) e = window.event;\n\t\t\ttry\n\t\t\t\t{\n\t\t\t\tt = e.changedTouches[0]\n\t\t\t\tobj.cur_mouseX = t.clientX;\n\t\t\t\tobj.cur_mouseY = t.clientY;\n\t\t\t\t}\n\t\t\tcatch(err)\n\t\t\t\t{\n\t\t\t\t\t\t\t\t\n\t\t\t\tobj.cur_mouseX = e.clientX; \n\t\t\t\tobj.cur_mouseY = e.clientY;\t\t\n\t\t\t\t}\n\t\t\n\t\n\t\t\tif (this.dir=='X')\n\t\t\t\t{\n\t\t\t\tdif = obj.cur_mouseX - obj.onclick_mouseX;\n\n\t\t\t\tdif = dif/1;\n\t\t\t\tdif = dif.toFixed(0);\n\t\t\t\tdif = dif*1;\n\n\t\t\t\tmove_dif = obj.cur_transX_tmp+dif;\n\t\t\t\tif (move_dif<=-this.max_left-50)\n\t\t\t\t\t{\n\t\t\t\t\tmove_dif = -this.max_left-50;\n\t\t\t\t\tthis.container.style['left'] = move_dif+this.dim;\n\t\t\t\t\tthis.cur_transX = move_dif;\n\t\t\t\t\treturn false;\t\n\t\t\t\t\t}\n\t\t\t\n\t\t\t\tif (move_dif>=50) //check if if edge has riched\n\t\t\t\t\t{\n\t\t\t\t\tmove_dif = 50;\n\t\t\t\t\tthis.container.style['left'] = move_dif+this.dim;\n\t\t\t\t\tthis.cur_transX = move_dif;\n\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\tthis.container.style['left'] = move_dif+this.dim;\n\t\t\t\t\tthis.cur_transX = move_dif;\n\t\t\t\t\tthis.innertion('moving'); //for innertion pass distance (loging)\n\t\t\t\t\tif (this.progress_bar_par=='on'&move_dif<=0&move_dif>=-this.max_left)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tpb_mv = -this.cur_transX/this.container_width;\n\t\t\t\t\t\tpb_mv = pb_mv*this.pb_length;\n\t\t\t\t\t\tthis.progress_bar_feel.style['margin'] = '0px 0px 0px '+pb_mv+'px';\n\t\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tif (this.progress_bar_par=='on'&move_dif>=0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tthis.progress_bar_feel.style['margin'] = '0px 0px 0px -1px';\n\t\t\t\t\t\t}\n\t\t\t\t\tif (this.progress_bar_par=='on'&move_dif<=-this.max_left)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tpb_mv = (1-this.feel_width)*this.pb_length;\n\t\t\t\t\t\tthis.progress_bar_feel.style['margin'] = '0px 0px 0px '+pb_mv+'px';\n\t\t\t\t\t\t}\t\n\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tdif = obj.cur_mouseY - obj.onclick_mouseY;\n\t\t\t\tdif = dif/1;\n\t\t\t\tdif = dif.toFixed(0);\n\t\t\t\tdif = dif*1;\n\t\t\t\t\n\t\t\t\tmove_dif = obj.cur_transY_tmp+dif;\n\t\t\t\tif (move_dif<=-this.max_top-50)\n\t\t\t\t\t{\n\t\t\t\t\tmove_dif = -this.max_top-50;\n\t\t\t\t\tthis.container.style['top'] = move_dif+this.dim;\n\t\t\t\t\tthis.cur_transY = move_dif;\n\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\tif (move_dif>=50) //checkinf if edge has riched \n\t\t\t\t\t{\n\t\t\t\t\tmove_dif = 50;\n\t\t\t\t\tthis.container.style['top'] = move_dif+this.dim;\n\t\t\t\t\tthis.cur_transY = move_dif;\n\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\tthis.container.style['top'] = move_dif+this.dim;\n\t\t\t\t\tthis.cur_transY = move_dif;\n\t\t\t\t\tthis.innertion('moving'); //for innertion pass distance\t(loging)\n\t\t\t\t\tif (this.progress_bar_par=='on'&move_dif<=0&move_dif>=-this.max_top)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tpb_mv = -this.cur_transY/this.container_height;\n\t\t\t\t\t\tpb_mv = pb_mv*this.pb_length;\n\t\t\t\t\t\tthis.progress_bar_feel.style['margin'] = pb_mv+'px 0px 0px -1px';\n\t\t\t\t\t\t}\n\t\t\t\t\tif (this.progress_bar_par=='on'&move_dif>=0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tthis.progress_bar_feel.style['margin'] = '0px 0px 0px -1px';\n\t\t\t\t\t\t}\n\t\t\t\t\tif (this.progress_bar_par=='on'&move_dif<=-this.max_top)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tpb_mv = (1-this.feel_height)*this.pb_length;\n\t\t\t\t\t\tthis.progress_bar_feel.style['margin'] = pb_mv+'px 0px 0px -1px';\n\t\t\t\t\t\t}\t\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\t}\n\n\n\t\t\t\n\n\t\t\t}\n\n\n\t\t}\n\n\t}",
"function mostrarPrimeiraImagem() {\n if (slidePosition !== 0) {\n slidePosition = 0; \n }\n\n updateDot();\n updateSlidePosition();\n}",
"function createSlides() {\n people.forEach( (person, index) => {\n const div = document.createElement('div');\n div.classList.add('slide');\n div.innerHTML =\n `\n <div class=\"profile-container\">\n <img class=\"profile-photo\" src=\"${person.image}\" alt=\"\" />\n <div class=\"nav-container\">\n <button class=\"nav-btn prev\" onclick=\"prevSlide()\"><img src=\"images/icon-prev.svg\" alt=\"Prev\"/></button>\n <button class=\"nav-btn next\" onclick=\"nextSlide()\"><img src=\"images/icon-next.svg\" alt=\"Next\"/></button>\n </div>\n \n </div>\n \n <div class=\"text-container\">\n <p>${person.quote}</p>\n \n <p><span class=\"name\">${person.name}</span> <span class=\"job-title\">${person.jobTitle}</span></p>\n </div>\n `\n slides.push(div)\n })\n\n // addToDOM()\n}",
"function resizedw(){\n loadSlider(slider);\n }",
"function createSlide(fileNameList, i, slideShowContainer) {\n let fileName = fileNameList[0][i];\n let fileDescription = fileNameList[1][i];\n let fileHeader = fileNameList[2][i];\n\n // Creates slide div\n let mySlides = document.createElement(\"div\");\n mySlides.setAttribute(\"class\", \"mySlide\");\n slideShowContainer[0].appendChild(mySlides);\n\n // Creates image element within mySlides\n let mySlidesImage = document.createElement(\"img\");\n mySlidesImage.setAttribute(\"class\", \"mySlides-img\");\n mySlidesImage.setAttribute(\"alt\", \"bilde av \" + fileName);\n mySlidesImage.setAttribute(\"src\", \"../img/\" + fileName);\n mySlides.appendChild(mySlidesImage);\n console.log(\"my slides image: \", mySlidesImage);\n\n // Creates a div element for text an title on each slide\n let mySlidesCaption = document.createElement(\"div\");\n mySlidesCaption.setAttribute(\"class\", \"mySlides-caption\");\n\n // Creates a header element within mySlideCaption\n let mySlidesHeader = document.createElement(\"h3\");\n mySlidesHeader.setAttribute(\"class\", \"mySlides-header\");\n mySlidesCaption.appendChild(mySlidesHeader);\n\n // Defines the title of the header for each slide\n let header = document.createTextNode(fileHeader);\n mySlidesHeader.appendChild(header);\n\n // Creates a paragraph element within mySlideCaption\n let mySlidesText = document.createElement(\"p\");\n mySlidesText.setAttribute(\"class\", \"mySlides-text\");\n mySlidesCaption.appendChild(mySlidesText);\n\n // Defines the text in the paragraph on each slide\n let text = document.createTextNode(fileDescription);\n mySlidesText.appendChild(text);\n mySlides.appendChild(mySlidesCaption);\n console.log(\"myslides med tekst: \", mySlides);\n}",
"function displaySlide(n) {\r\n slideIndex = n;\r\n showSlides();\r\n}",
"function MyWindow($opt){//name deve essere uguale al nome della variabile che contiene il nuovo oggetto\n\tthis.opt=$opt;\n\tvar test=$opt['name'];\n\tvar _self=this;\n\t$zindex++;\n\tthis.name=$opt['name'];\n\tthis.chiudi= function(){\n\t\tthis.windows.innerHTML=\"\";\n\t\treturn;\n\t};\n\tthis.hide= function(){\n\t\tthis.windows.style.visibility=\"hidden\";\n\t\treturn;\n\t};\n\tthis.show= function(){\n\t\tthis.windows.style.visibility=\"visible\";\n\t\treturn;\n\t};\n\tthis.centra= function(){\n\t\tvar MyWindowsHeight=this.windows.offsetHeight;\n\t\tvar MyWindowsWidth=this.windows.offsetWidth;\n\t\tvar browserHeight=getTop(document.getElementById('SpaceCalculator'));\n\t\tvar browserWidth=getLeft(document.getElementById('SpaceCalculator'));\n\t\tvar MyTop=(browserHeight-MyWindowsHeight)/2;\n\t\tvar MyLeft=(browserWidth-MyWindowsWidth)/2;\n\n\t\tthis.windows.style.top=MyTop;\n\t\tthis.windows.style.left=MyLeft;\n\t\treturn;\n\t};\n\tthis.fadeOut= function(){\n\t\tthis.windows.style.opacity=0.9;\n\t\treturn;\n\t};\n\tthis.fadeIn=function($to, $time){\n\t\tif($time){//se ho impostato un tempo calcolo quanti cicli servono\n\t\t\tvar $numCicli=Math.round($time/$MyTimer)\n\t\t}else{//se non l'ho impostato allora vuole dire che voglio sia fatto subito\n\t\t\tvar $numCicli=1;\n\t\t}\n\t\tvar $step=$differenza/$numCicli;\n\t\tvar $resta=$to-$step;\n\t\tfor($ciclo=1;$ciclo<=$numCicli;$ciclo++){\n\t\t\t// opacity = (opacity == 100)?99.999:h;\n\t\t\t// IE/Win\n\t\t\t//this.windows.style.filter = \"alpha(opacity:\"+h+\")\";\n\t\t\t// Safari<1.2, Konqueror\n\t\t\t//this.windows.style.KHTMLOpacity = (this.windows.style.KHTMLOpacity+$step/100);\n\t\t\t// Older Mozilla and Firefox\n\t\t\t//this.windows.style.MozOpacity = (this.windows.style.MozOpacity+$step/100);\n\t\t\t// Safari 1.2, newer Firefox and Mozilla, CSS3\n\t\t\t//this.windows.style.opacity = $step*$ciclo;\n\t\t\t//h=h-Conf['DecrementoOpacita'];\n\t\t\t//alert($ciclo+'->'+this.windows.style.opacity);\n\t\t}\n\t\tif(timerID!=''){\n\t\t\tclearTimeout(timerID);\n\t\t}\n\t\tvar timerID=setTimeout(this.fadeIn(),$MyTimer,$resta,$time-$MyTimer)\n\t\treturn;\n\t};\n\tvar $id='MyWindowsID_'+$opt['name'];\n\n\t/*Definisco tutti i tag html che mi serviranno per costruire la mia finestrella*/\n\t//contorno superore\n\tvar MyTopSx= document.createElement(\"td\");\n\tMyTopSx.setAttribute(\"class\",\"TopSx\");\n\t\n\tvar MyTopDx= document.createElement(\"td\");\n\tMyTopDx.setAttribute(\"class\",\"TopDx\");\n\t\n\tvar MyBgTop= document.createElement(\"td\");\n\tMyBgTop.setAttribute(\"class\",\"BgTop\");\n\t\n\tvar MyTopTr=document.createElement(\"tr\");\n\tMyTopTr.appendChild(MyTopSx);\n\tMyTopTr.appendChild(MyBgTop);\n\tMyTopTr.appendChild(MyTopDx);\n\t\n\t//contorno testo\n\tvar MyBgDx= document.createElement(\"td\");\n\tMyBgDx.setAttribute(\"class\",\"BgDx\");\n\t\n\tvar MyBgSx= document.createElement(\"td\");\n\tMyBgSx.setAttribute(\"class\",\"BgSx\");\n\t\n\tvar MyBgMainContainer=document.createElement(\"div\");\n\tMyBgMainContainer.setAttribute(\"class\",\"main\");\n\t\n\tMyBgMainContainer.innerHTML=$opt['txt'];\n\n\t//Eventuale barra del tittolo\n\tif($opt['title']!=null){\n\t\tvar MyTitle=document.createElement(\"div\");\n\t\tMyTitle.setAttribute(\"class\",\"TitleBarTxt\");\n\t\tMyTitle.innerHTML=$opt['title'];\n\t\t\n\t\tvar MyCloseButtonImage=document.createElement(\"img\");\n\t\tMyCloseButtonImage.setAttribute(\"src\",\"./../oLibs/MyWindow/img/chiudi.png\");\n\t\tMyCloseButtonImage.setAttribute(\"alt\",\"X\");\n\t\t\n\t\tvar MyCloseButtonLink=document.createElement(\"a\");\n\t\tMyCloseButtonLink.appendChild(MyCloseButtonImage);\n\t\tif($opt['isPermanent']==true){\n\t\t\tMyCloseButtonLink.onclick=function(){\n\t\t\t\t_self.hide();\n\t\t\t}\n\t\t}else{\n\t\t\tMyCloseButtonLink.onclick=function(){\n\t\t\t\t_self.chiudi();\n\t\t\t}\n\t\t}\n\n\t\tvar MyCloseButton=document.createElement(\"div\");\n\t\tMyCloseButton.appendChild(MyCloseButtonLink);\n\t\tMyCloseButton.setAttribute(\"class\",\"closeButton\");\n\t\t\n\t\tvar MyTitleBar=document.createElement(\"div\");\n\t\tMyTitleBar.setAttribute(\"class\",\"TitleBar\");\n\t\tMyTitleBar.appendChild(MyTitle);\n\t\tMyTitleBar.appendChild(MyCloseButton);\n\t}\n\t//fine barra del titolo continuo con la finestrella\n\tvar MyBgMain= document.createElement(\"td\");\n\tMyBgMain.setAttribute(\"class\",\"mainBG\");\n\tif($opt['title']){\n\t\t//se ho creato la barra del titolo la mostro\n\t\tMyBgMain.appendChild(MyTitleBar);\n\t}\n\tMyBgMain.appendChild(MyBgMainContainer);\n\t\n\tvar MyBgTr=document.createElement(\"tr\");\n\tMyBgTr.appendChild(MyBgSx);\n\tMyBgTr.appendChild(MyBgMain);\n\tMyBgTr.appendChild(MyBgDx);\n\t\n\t//contorno inferiore\n\tvar MyBottomSx= document.createElement(\"td\");\n\tMyBottomSx.setAttribute(\"class\",\"BottomSx\");\n\t\n\tvar MyBottomDx= document.createElement(\"td\");\n\tMyBottomDx.setAttribute(\"class\",\"BottomDx\");\n\t\n\tvar MyBgBottom= document.createElement(\"td\");\n\tMyBgBottom.setAttribute(\"class\",\"BgBottom \");\n\t\n\tvar MyBottomTr=document.createElement(\"tr\");\n\tMyBottomTr.appendChild(MyBottomSx);\n\tMyBottomTr.appendChild(MyBgBottom);\n\tMyBottomTr.appendChild(MyBottomDx);\n\t\n\t//Tabella\n\tvar MyTable=document.createElement(\"table\");\n\tMyTable.setAttribute(\"class\",\"MyTable\");\n\tMyTable.setAttribute(\"cellspacing\",\"0px\");\n\tMyTable.appendChild(MyTopTr);\n\tMyTable.appendChild(MyBgTr);\n\tMyTable.appendChild(MyBottomTr);\n\n\tMyTable.style.zIndex=$zindex;\n\tif($opt['width']){\n\t\tMyTable.width=$opt['width']+'px';\n\t}\n\tif($opt['height']){\n\t\tMyTable.height=$opt['height']+'px';\n\t\tMyTable.style.maxheight=$opt['height']+'px';\n\t}\n\n\t//La aggiungo al body tenendola nascosta\n\tMyTable.style.visibility='hidden';\n\tMyTable.style.top=0;//imposto a zero per evitare sfarfallamenti con la barra di scorrimento su firefox\n\tMyTable.style.left=0;//idem come sopra\n\tdocument.body.appendChild(MyTable);\n\n\t//posiziono la finestrella al centro del browser\n\tvar MyWindowsHeight=MyTable.offsetHeight;\n\tvar MyWindowsWidth=MyTable.offsetWidth;\n\t//se mi sono passato qualche parametro per il posizionamento mi ricavo i dati\n\tif($opt['position']){\n\t\tswitch ($opt['position']){\n\t\t\tcase 'top-left':\n\t\t\t\t$opt['top']=getTop($opt['this']);\n\t\t\t\t$opt['left']=getLeft($opt['this']);\n\t\t\tbreak;\n\t\t\tcase 'top-right':\n\t\t\t\t$opt['top']=getTop($opt['this']);\n\t\t\t\t$opt['left']=getLeft($opt['this'])+$opt['this'].offsetWidth-MyWindowsWidth;\n\t\t\tbreak;\n\t\t\tcase 'bottom-left':\n\t\t\t\t$opt['top']=getTop($opt['this'])+$opt['this'].offsetHeight+MyWindowsHeight;\n\t\t\t\t$opt['left']=getLeft($opt['this']);\n\t\t\tbreak;\n\t\t\tcase 'bottom-right':\n\t\t\t\t$opt['top']=getTop($opt['this'])+$opt['this'].offsetHeight+MyWindowsHeight;\n\t\t\t\t$opt['left']=getLeft($opt['this'])+$opt['this'].offsetWidth-MyWindowsWidth;\n\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t$opt['top']=getTop($opt['this']);\n\t\t\t\t$opt['left']=getLeft($opt['this']);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(isNaN($opt['top']) || isNaN($opt['left'])){\n\n\t\tvar browserHeight=getTop(document.getElementById('SpaceCalculator'));\n\t\tvar browserWidth=getLeft(document.getElementById('SpaceCalculator'));\n\n\t\tvar MyTop=(browserHeight-MyWindowsHeight)/2;\n\t\tvar MyLeft=(browserWidth-MyWindowsWidth)/2;\n\n\t}else{\n\t\tvar MyTop=$opt['top']-MyWindowsHeight;\n\t\tvar MyLeft=$opt['left'];\n\t}\n/*---------------------------------------------------------------------------*/\n\tif($opt['isTip']){//se si tratta di un tips\n\t\t//MyTop-=18; //Altezza\n\t\t//MyLeft+=54;//larghezza\n\t}\n\tMyTable.style.top=MyTop+'px';\n\tMyTable.style.left=MyLeft+'px';\n\n\t//finito di posizionarla posso finalmente mostrarla\n\tif($opt['isVisible']!=false){\n\t\tMyTable.style.visibility='visible';\n\t}\n\n\tif($opt['title']){//se c'è un titolo e quindi una barra del titolo allora probabilmente voglio che la finestra sia draggabile\n\t\t//aggiongo il drag and drop\n\t\tvar theHandle = MyTitleBar;\n\t\tvar theRoot = MyTable;\n\t\tDrag.init(theHandle, theRoot);\n\t}\n\t//----------------\n\tthis.windows=MyTable;\n\n\tif($opt['autoCloseTime']){\n\t\tthis.timer='';\n\t\t//programmo già una chiusura se non vado sopra col mouse\n\t\t/*\n\t\t$opt['this'].onmouseout=function(){\n\t\t\t\tthis.timer=setTimeout(function(){_self.hide();},$opt['autoCloseTime'])\n\t\t}\n*/\n\t\tthis.windows.onmouseout=function(){\n\t\t\t//var _self=this;\n\t\t\t//if(this.timer==''){\n\t\t\t\t//alert('test');\n\t\t\t\tthis.timer=setTimeout(function(){_self.hide();},$opt['autoCloseTime'])\n\t\t\t//}\n\t\t}\n\t\tthis.windows.onmouseover=function(){\n\t\tif(this.timer){\n\t\t\t\tclearTimeout(this.timer);\n\t\t\t\tthis.timer='';\n\t\t\t}\n\t\t}\n\t\treturn;\n\t};\n\treturn this;\n}",
"function slider() {\n if (position) {\n buildSlidePositionHtml(numSlides);\n }\n\n if (navigation) {\n buildSlideNavHtml();\n }\n\n if (autoPlay) {\n play();\n }\n}",
"function slider(curWidth,curposition,direction)\n{\n\n/* \n\tGet current image width based on size of browser window\n Get total width of all images in an array\n*/\n\nlet getDivInner = document.getElementById(\"slider_inner\");\nlet getDivOuter = document.getElementById(\"slider_outer\");\nlet getDivContainer = document.getElementById(\"slider_container\");\nsliderImages = getDivInner.getElementsByTagName(\"img\");\ntotalWidth = (sliderImages.length * curWidth + curWidth);\ncurrentWidth = curWidth + \"px\";\nstopPosition = 0;\nposition = curposition;\ncurDirection = direction;\n\nfor (let j = 0; j < sliderImages.length; j++)\n{\n\tsliderImages[j].style.maxWidth = currentWidth;\n}\t\ngetDivContainer.style.width = currentWidth;\ngetDivInner.style.width = totalWidth + \"px\"; \ngetDivOuter.style.width = currentWidth;\n\nmoveSlide = setInterval(function(){moveSlider(curWidth,curposition)},speed); \n}",
"drawSlider() {\n let c = color(255, 255, 255);\n fill(c);\n noStroke();\n rect(this.x, this.y + this.topPadding + this.lateralPadding, this.width, this.height, 1, 1, 1, 1);\n }",
"function buildSlidePositionHtml(numSlides) {\n var html = \"<div class='slide-position'><div class='bullets'>\";\n var active = \" active\";\n\n for (i = 1; i <= numSlides; i++) {\n html = html + \"<div class='bullet\" + active + \"' data-slide-id='\" + i + \"'></div>\";\n active = \"\";\n }\n\n html = html + \"</div></div>\";\n\n $('.slider-wrapper').append(html);\n\n $bullets = $('.slider-wrapper .slide-position .bullets')\n}",
"createPhotoBoothWindow () {\n this.createWindow()\n\n setup.toggleLoading(this.currentWindow)\n this.getCameraStream()\n }",
"function initProgress()\n{\n /* Count the number of slides, give each slide a number */\n numslides = 0;\n for (const h of document.body.children)\n if (isStartOfSlide(h)) h.b6slidenum = ++numslides; // Save number in element\n\n /* Find all elements that are progress bars, unhide them. */\n progressElts = document.getElementsByClassName(\"progress\");\n for (const e of progressElts)\n if (typeof e.b6savedstyle === \"string\") e.style.cssText = e.b6savedstyle;\n\n /* Find all that should contain the current slide number, unhide them. */\n slidenumElts = document.getElementsByClassName(\"slidenum\");\n for (const e of slidenumElts)\n if (typeof e.b6savedstyle === \"string\") e.style.cssText = e.b6savedstyle;\n\n /* Find all that should contain the # of slides, fill and unhide them. */\n for (const e of document.getElementsByClassName(\"numslides\")) {\n if (typeof e.b6savedstyle == \"string\") e.style.cssText = e.b6savedstyle;\n e.textContent = numslides;\t// Set content to number of slides\n }\n\n /* Set the # of slides in a CSS counter on the BODY. */\n document.body.style.setProperty('counter-reset', 'numslides ' + numslides);\n\n}",
"function setupSlides() {\n const config = Reveal.getConfig;\n\n Reveal.getSlides().forEach(function (slide) {\n slide.style.height = pageHeight + \"px\";\n\n if (Reveal.getConfig().center || slide.classList.contains(\"center\")) {\n // Reveal implements centering by adjusting css:top. Remove this.\n slide.style.top = \"\";\n\n // div for centering with flex layout\n let vcenter = document.createElement(\"div\");\n vcenter.classList.add(\"v-center\");\n\n // div for wrapping slide content\n var wrapper = document.createElement(\"div\");\n wrapper.classList.add(\"v-wrapper\");\n\n // move children from slide to wrapping div\n for (let i = 0; i < slide.children.length; ) {\n let e = slide.children[i];\n // skip whiteboard and footer\n if (\n e.classList.contains(\"whiteboard\") ||\n e.classList.contains(\"footer\")\n ) {\n ++i;\n } else {\n wrapper.appendChild(e);\n }\n }\n\n // add divs to slide\n slide.appendChild(vcenter);\n vcenter.appendChild(wrapper);\n }\n });\n }",
"function slidecoords(xbeg, ybeg, xend, yend, steps, rate) {\n\tif (blnNS && (dblVer >= 5)) {\n\t\tthis.x = Math.round(xbeg+((xend-xbeg)*(this.i/steps)));\n\t\tthis.css.left = this.x + \"px\";\n\t\tthis.y = Math.round(ybeg+((yend-ybeg)*(this.i/steps)))\n\t\tthis.css.top = this.y + \"px\";\n\t} else {\n\t\tthis.css.left = this.x = Math.round(xbeg+((xend-xbeg)*(this.i/steps)));\n\t\tthis.css.top = this.y = Math.round(ybeg+((yend-ybeg)*(this.i/steps)));\n\t}\n\tthis.i++;\n\tif (this.i <= steps) {\n\t\tslidingID2 = setTimeout(this.self+\".slidecoords(\"+xbeg+\", \"+ybeg+\", \"+xend+\", \"+yend+\", \"+steps+\", \"+rate+\")\", rate); \n\t} else { \n\t\tthis.i = 1;\n\t\tthis.sliding = false;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomizes bot's shield swaps. | _randomizeBotShield() {
if (random(0, 100) < 1 && !this._bot.shield.isActive)
this._bot.shield._swapShield();
} | [
"shuffle() {\r\n for (let i = 0; i < this.len(); i++) {\r\n this.swap(\r\n this.getLinkByPosition(\r\n Math.floor(Math.random() * (window.innerWidth - 10)),\r\n Math.floor(Math.random() * (window.innerHeight - 10))\r\n ),\r\n this.getLinkByPosition(\r\n Math.floor(Math.random() * (window.innerWidth - 10)),\r\n Math.floor(Math.random() * (window.innerHeight - 10))\r\n )\r\n );\r\n }\r\n console.log(\"shuffle\");\r\n }",
"function gameLogicSetup() {\n //shuffle the multipliers array. multiplier at index 0 will be safe 1, index 1 safe 2 etc.\n shuffle(multipliers);\n //shuffle the safes then splice the array to get only 4 values\n shuffle(safes);\n selected_safes = safes.slice(0, 4);\n}",
"shuffle() {\n \n for (let i = 0; i < this._individuals.length; i++) {\n let index = getRandomInt( i + 1 );\n let a = this._individuals[index];\n this._individuals[index] = this._individuals[i];\n this._individuals[i] = a;\n }\n }",
"shuffleElements() { \n this.deck.shuffle();\n }",
"function repeatMoles () {\r\n randHoleIdx = Math.floor(Math.random()*(holes.length)+1);\r\n holes[randHoleIdx].classList.toggle(\"mole\");\r\n}",
"function diamond4() {\n return Math.floor(Math.random() * 11 + 1);\n }",
"function randomizeColors() {\n for (let i = ORIGINAL_COLORS.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * i);\n const temp = ORIGINAL_COLORS[i];\n ORIGINAL_COLORS[i] = ORIGINAL_COLORS[j];\n ORIGINAL_COLORS[j] = temp;\n }\n}",
"randomize(height, width){\n const speedRange = 1.75;\n const sizeRange = 3;\n this.x = Math.floor(Math.random()*width)\n this.y = Math.floor(Math.random()*height);\n this.speed = (Math.random()*speedMax)+speedMin;\n //this.size = (Math.random()*sizeRange)+1;\n }",
"function scramble(graph) {\n if (graph.nodes.length < 4) return graph;\n do {\n graph.nodes.forEach (function (node) {\n node[0] = Math.random ();\n node[1] = Math.random ();\n });\n } while (!intersections (graph.links));\n return graph;\n }",
"shuffleGuessList() {\r\n this.mixedGuessList = super.shuffle(this.guessList.slice());\r\n }",
"randomlyAttack() {\n const possibleAttacks = Object.values(this.attacks);\n return possibleAttacks[Math.floor(Math.random() * possibleAttacks.length)];\n }",
"function shuffleAllVerbs(){\n\n\n\n\n//var randIndex = Math.floor(Math.random() * 11);\n//var randPEIndex = Math.floor(Math.random() * 6);\n//var randVerbPickIndex = Math.floor(Math.random() * 4);\n\ndocument.getElementById(answers[0]).innerHTML = pluPerEndingsFirstPerfect[randPEIndex][1] + verbsFirstPer[randIndex][1] ;\n\ndocument.getElementById(answers[1]).innerHTML = perEndingsFirst[randPEIndex][1] + verbsFirst[randIndex][1] ;\n\ndocument.getElementById(answers[2]).innerHTML = futPerEndings[randPEIndex][1] + verbsFirstPer[randIndex][1];\n//document.getElementById(answers[2]).innerHTML = perEndingsFirstImp[randPEIndex][1] + verbsFirst[randIndex][1] ;\n\ndocument.getElementById(answers[3]).innerHTML = perEndingsFirstPerfect[randPEIndex][1] + verbsFirstPer[randIndex][1] ;\n\ndocument.getElementById(\"startButton\").innerHTML = randVerbPick[randVerbPickIndex];\n\n\n\n\n}",
"function diamond3() {\n return Math.floor(Math.random() * 11 + 1);\n }",
"changeRandomWeight(){\n\t\tvar i = Math.floor(Math.random() * this.genes.length)\n\n\t\t//we can only use an available gene\n\t\tif (this.genes[i] != null){\n\t\t\tthis.genes[i].weigth = (Math.random() * 2) - 1 //betwenn -1 and 1\n\t\t} else {\n\t\t\tthis.changeRandomWeight()\n\t\t}\n\t}",
"function randomStyler()\n{\n\tvar zoneStyle = Math.floor((Math.random() * 3) );\n\tconsole.log('randomZone='+ zoneStyle);\n\treturn \t stylesArray[zoneStyle];\n}",
"function randomize() {\n $(\"#saturation\").slider('value', rand(0, 100));\n $(\"#lightness\").slider('value', rand(0, 100));\n\n var min = rand(0, 360);\n var max = rand(0, 360);\n\n if (min > max) {\n min = min + max;\n max = min - max;\n min = min - max;\n }\n\n $(\"#hue\").slider('values', 0, min);\n $(\"#hue\").slider('values', 1, max);\n }",
"function assignMole() {\n\tvar circle = circles[Math.floor(Math.random() * circles.length)];\n\tcircle.style.backgroundImage = \"url(mole.png)\";\n\tcircle.hasMole = true;\n}",
"shuffleSpells() {\n this.spellDeck.shuffle();\n }",
"function randomizeCards() {\n\tvar imgArr = ['0 0', '0 0', '0 160px', '0 160px', \t\t\t\t\t//array of images\n\t\t\t\t '0 360px', '0 360px', '200px 190px', '200px 190px',\n\t\t\t\t '200px 360px', '200px 360px', '420px 360px', '420px 360px', \n\t\t\t\t '200px 600px', '200px 600px', '420px 590px', '420px 590px', \n\t\t\t\t '410px 160px', '410px 160px'];\n\tvar i = 0;\n\t\n\tfor ( i ; i < cardsArr.length ; i++ ) {\n\t\tvar elCard = cardsArr[i];\n\t\trandomIndex = Math.floor(Math.random() * (imgArr.length));\n\t\telCard.style.background = 'url(monetliliestiles.jpg) ' + imgArr[randomIndex];\n\t\timgArr.splice(randomIndex,1);\n\t\telCard.className = 'card assigned';\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates news array depending on whether there is a search filter or not | updateNews(state, [payload, type]) {
// Empty the contry news array if there is a new search parameter
if (type && type !== state.newsType && type.trim() !== 'covid19') {
state.newsInCountry = [];
}
// Stores value of the search paramter in the store
state.newsType = type && type.trim();
// Remove duplicates from news items
const filteredArticles = payload.articles.filter((el, index, self) => {
const exists = index === self.findIndex((t) => (
t.title === el.title
));
return exists;
});
// Checks if items already exist in the array
if (state.news.length > 0 || state.newsInCountry.length > 0) {
// Get title of last elements and compare to avoid duplicate fetching of news item
const lastNewsItem = state.news.length > 0 && state.news[state.news.length - 1].title;
const lastCountryNewsItem = state.newsInCountry.length > 0
&& state.newsInCountry[state.newsInCountry.length - 1].title;
const lastItemInFilteredArray = filteredArticles[filteredArticles.length - 1].title;
if (lastNewsItem !== lastItemInFilteredArray
|| lastCountryNewsItem !== lastItemInFilteredArray
) {
// Checks if there is no search parameter and pushes into the corresponding array
if (!type || (type && type.trim() === 'covid19')) {
state.news.push(...filteredArticles);
state.newsInCountry = [];
} else if (type.trim() !== 'covid19') {
state.newsInCountry.push(...filteredArticles);
state.news = [];
}
}
} else if (!type || type.trim() === 'covid19') {
state.news.push(...filteredArticles);
} else {
state.newsInCountry.push(...filteredArticles);
}
} | [
"function updateFilter()\r\n\t{\r\n\t\tvar activeCount = filterBox.find(\"input[type=checkbox]\").filter(\":checked\").length;\r\n\r\n\t\tif (activeCount == 0)\r\n\t\t{\r\n\t\t\ttoys.show();\r\n\t\t\tupdateStatus();\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\ttoys.show();\r\n\r\n\t\t\r\n\t\ttoys.each(function(index, toy) {\r\n\t\t\t\ttoy = $(toy);\r\n\t\t\r\n\t\t\t$.each(filterGroups, function(index, group) {\r\n\t\t\t\tvar active = group.element.find(\"input[type=checkbox]\").filter(\":checked\");\r\n\t\t\t\t\r\n\t\t\t\tif (active.length == 0) {\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t\r\n\t\t\t\tvar inFilter = false;\r\n\t\t\t\t\r\n\t\t\t\tactive.each(function(index, filter) {\r\n\t\t\t\t\tfilter = $(filter);\r\n\t\t\t\t\r\n\t\t\t\t\tvar col = filter.attr(\"col\");\r\n\t\t\t\t\tvar pattern = filter.attr(\"pattern\");\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (toy.find(\"td\").eq(col).text() == pattern)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tinFilter = true;\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\t\t\t\t\r\n\t\t\t\tif (!inFilter) {\r\n\t\t\t\t\ttoy.hide();\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t});\r\n\t\t\r\n\t\tupdateStatus();\r\n\t}",
"update_results() {\n this.selected_item = '';\n var obj = this.filters;\n Object.getOwnPropertyNames(obj).forEach(key => {\n this.results = this.results.filter(e => e[key] === obj[key]);\n });\n }",
"changeMainNews(news) {\n\n this.mainNews = news;\n this.writer = this.writers.filter((el) => { return el.id == this.mainNews.writerId})[0].value;\n mvc.apply();\n }",
"queryJSON(search) {\n for (let i = 0; i < this.state.wasteJSON.length; i++) {\n if(this.state.wasteJSON[i]['keywords'].includes(search)) {\n this.state.searchJSON.push(this.state.wasteJSON[i]);\n }\n }\n }",
"function updateFromFilters(){\n\n //$(\"input\").prop('disabled', true);\n\n var newList = _(elements)\n .forEach(function(d){ map.removeLayer(d.marker) })\n .filter(computeFilter)\n .forEach(function(d){ d.marker.addTo(map) })\n .value();\n\n updateList(newList);\n updateFromMap();\n }",
"getNews() {\n\n this.dataBase.findByIndex(\"/news\",\n [\"_id\", \"title\", \"attachment\", \"seoDescription\", \"isMainNews\", \"createDate\", \"writerId\"], \"categoryId\", mvc.routeParams.id).then( data => {\n\n if (data) {\n this.listMainNews = data.docs.filter((el) => { return el.isMainNews});\n if (this.listMainNews.lenght > 3) {\n this.listMainNews = this.listMainNews.slice(0, 3);\n }\n this.mainNews = this.listMainNews[0];\n this.getWriters();\n mvc.apply();\n } else {\n this.getNews();\n }\n }, () => {\n this.getNews();\n });\n }",
"function siteFiltering() {\n\tvar note = new Object();\n\tif(sitePrefix == '') {\n\t\tsitePrefix = getSitePrefix();\n\t\tnote.filter = 'site';\n\t} else {\n\t\tsitePrefix = '';\n\t\tnote.filter = 'all';\n\t}\n\t\n\tputObjectInNotes(noteFile, note, 'filter_');\n\tvar start = new Date();\n\tclickedRefresh('no');\n\tvar end = new Date();\n\t//alert('switch in: ' + (end-start) + ' ms');\n}",
"_onSearchInputChanged(searchInput) {\n if(searchInput) {\n this.listedProjects = this.projects.filter(project => {\n return project.name.toLowerCase().includes(searchInput.toLowerCase());\n });\n } else {\n // no search input, show all projects that were loaded\n this.listedProjects = this.projects;\n }\n }",
"function setupSearchFilter() {\n // an internal function that will add/remove a hidden element called \"addl_query\" to the\n // participant search form. The element will contain filtering information that will be used by\n // lunr in the participant search to filter out the found results based on the additional filter\n // items.\n function updateSearchFormFields(ev) {\n let searchForm = document.getElementById(\"participant_search_form\");\n let form = ev.target.closest(\"[data-js-search-filter]\");\n let checked = [...form.querySelectorAll(\":checked\")];\n let queries = {};\n for (let i = 0; i < checked.length; i++) {\n if (!queries[checked[i].name]) {\n queries[checked[i].name] = [];\n }\n queries[checked[i].name].push(`${checked[i].name}:${checked[i].value}`);\n }\n newQueries = Object.values(queries).map((q) => q.join(\" \"));\n searchForm\n .querySelectorAll(\"input[type='hidden']\")\n .forEach((e) => e.remove());\n for (let i = 0; i < newQueries.length; i++) {\n let input = document.createElement(\"input\");\n input.setAttribute(\"type\", \"hidden\");\n input.setAttribute(\"name\", \"addl_query\");\n input.setAttribute(\"value\", newQueries[i]);\n searchForm.append(input);\n }\n searchForm.querySelector(\"[type='submit']\").click();\n }\n\n // when the search filter items are changed, update the search fields\n on(\"change\", \"[data-js-search-filter]\", updateSearchFormFields);\n\n // when the search filter items are reset, update the search fields once the call stack clears (\n // setTimeout with timeout of 0)\n on(\"reset\", \"[data-js-search-filter]\", function (ev) {\n setTimeout(function () {\n updateSearchFormFields(ev);\n }, 0);\n });\n}",
"getAllNews() {\n\n this.dataBase.findByIndex(\"/news\", [\"_id\", \"title\", \"attachment\"],\"categoryId\", mvc.routeParams.id).then( data => {\n if (data) {\n let length = data.docs.length;\n this.liftNewsInCategory = data.docs.slice(0, length / 2);\n this.rightNewsInCategory = data.docs.slice(length / 2, length);\n mvc.apply();\n } else {\n this.getAllNews()\n }\n }, () => {\n this.getAllNews();\n });\n\n }",
"updateHistory(flag) {\n this.search.current = `?status=${this.params.status.join('+')}&assignee=${this.params.assignee.join('+')}`;\n if (!flag) window.history.pushState({ state: this.search.current }, this.search.current, ('search' + this.search.current));\n }",
"function updateJobs(searchTerm) {\n setSearchTerm(searchTerm);\n }",
"function search()\n{\n\tvar searchText = searchInput.value;\n\n\t// if input's empty\n\t// displaying everything\n\tif (searchText == \"\")\n\t{\n\t\tshowAllFilteredWordEntries();\n\t\treturn;\n\t}\n\n\t// hiding everything except the matched words\n\tfor (let i = 0; i < loadedData.length; i++)\n\t{\n\t\tlet entry = getFilteredWordEntry(i);\n\t\tvar regx = new RegExp(searchText);\n\t\tif (regx.test(loadedData[i]))\n\t\t\tentry.hidden = false;\n\t\telse\n\t\t\tentry.hidden = true;\n\t}\n}",
"clearSearchResults() {\n if (this.state.filter.length > 0) {\n this.fetchConsumerComplaintList()\n this.props.history.push(`/home/consumers?activeTab=consumer-complaints&activePage=1&limit=10`)\n }\n }",
"setSearch( key, text ) {\n let d = this._lists[ key ] || null;\n if ( d ) d.search = String( text || '' ).trim();\n this.emit( 'change', this._lists );\n return d;\n }",
"function update_filters() {\n //get currently selected (or unselected values for all ids in columns.head)\n for (var i = 0; i < columns.length; i++) {\n columns[i].filter = $('#'+columns[i].cl).val();\n }\n\n // apply filter\n filtered_dataset = full_dataset.filter(filter_function);\n filtered_unique_columns = unique_columns.map(column_filter);\n\n // update display\n update_select_boxes();\n generate_table();\n}",
"function append(item)\n{\n if(recentSearch.includes(item))\n {\n for(var i = 0; i < recentSearch.length; i++)\n {\n if(recentSearch[i] === item)\n {\n recentSearch.splice(i, 1);\n break;\n }\n }\n recentSearch.push(item);\n }\n else if(recentSearch.length === 12)\n {\n recentSearch.splice(0, 1);\n recentSearch.push(item);\n }\n else\n {\n recentSearch.push(item);\n }\n}",
"refreshData(newSearchTerm, newSortBy, newIsAscending) {\n this.updateDataFilters(newSearchTerm, newSortBy, newIsAscending);\n const { searchTerm, sortBy, isAscending } = this.dataFilters;\n const data = this.state.transactions.filtered(\n 'serialNumber BEGINSWITH[c] $0',\n searchTerm,\n );\n let sortDataType;\n switch (sortBy) {\n case 'serialNumber':\n case 'numberOfItems':\n sortDataType = 'number';\n break;\n default:\n sortDataType = 'realm';\n }\n this.setState({ data: sortDataBy(data, sortBy, sortDataType, isAscending) });\n }",
"function filter () {\n \t\tjq('#tblList').DataTable().search(\n \t\tjq('#tblList_filter').val()\n \t\t).draw();\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the node corresponding to this statement, or creates a new one if one does not exist yet. | _getOrAddNode($stmt, create, forceNodeType) {
const _create = create ?? false;
let node = this.#nodes.get($stmt.astId);
// If there is not yet a node for this statement, create
if (node === undefined && _create) {
const nodeType = forceNodeType ?? CfgUtils.getNodeType($stmt);
const nodeId = this.#deterministicIds ? this.#nextId() : undefined;
node = Graphs.addNode(
this.#graph,
this.#dataFactory.newData(nodeType, $stmt, nodeId, this.#splitInstList)
);
// Associate all statements of graph node
for (const $nodeStmt of node.data().stmts) {
// Check if it has not been already added
if (this.#nodes.get($nodeStmt.astId) !== undefined) {
throw new Error(
"Adding mapping twice for statement " +
$nodeStmt.astId +
"@" +
$nodeStmt.location
);
}
this.#nodes.set($nodeStmt.astId, node);
}
} else {
throw new Error("No node for statement at line " + $stmt.line);
}
return node;
} | [
"addNode(n) {\n if (!this.getNode(n)) {\n const tempNode = node.create({ name: n });\n const clone = this.nodes.slice(0);\n clone.push(tempNode);\n this.nodes = clone;\n\n return tempNode;\n }\n\n return null;\n }",
"getOrNode() {\n return new OrNode();\n }",
"_createNodes() {\n // Test all statements for leadership\n // If they are leaders, create node\n for (const $stmt of Query.searchFromInclusive(this.#jp, \"statement\")) {\n if (CfgUtils.isLeader($stmt)) {\n\n if (this.#splitInstList && CfgUtils.getNodeType($stmt) === CfgNodeType.INST_LIST) {\n this._getOrAddNode($stmt, true, CfgNodeType.INST_LIST);\n\n for (const $right of $stmt.siblingsRight) {\n if (!CfgUtils.isLeader($right))\n this._getOrAddNode($right, true, CfgNodeType.INST_LIST);\n else \n break;\n }\n }\n else\n this._getOrAddNode($stmt, true);\n }\n }\n\n // Special case: if starting node is a statement and a graph node was not created for it (e.g. creating a graph starting from an arbitrary statement),\n // create one with the type INST_LIST\n if (\n this.#jp.instanceOf(\"statement\") &&\n this.#nodes.get(this.#jp.astId) === undefined\n ) {\n this._getOrAddNode(this.#jp, true, CfgNodeType.INST_LIST);\n }\n }",
"get(id, create=true) {\n\t\tlet node = this.nodes.get(id);\n\t\tif(! node && create) {\n\t\t\tnode = new Node(this.network, id);\n\t\t\tthis.nodes.set(id, node);\n\t\t}\n\n\t\treturn node;\n\t}",
"getNode(name) {\n return this.nodes.find((n) => n.name === name) || null;\n }",
"get(nodeId) {\n if (nodeId) {\n var node = this.db.database.get(nodeId)\n if (node.length === 1) {\n return node[0]\n }\n }\n }",
"get topNode() {\n return new TreeNode(this, 0, 0, null)\n }",
"getTargetNode(props: PropsT) {\n const { children, targetRef, targetSelector } = props\n if (children) {\n return ReactDOM.findDOMNode(this._target)\n }\n if (targetRef) {\n return ReactDOM.findDOMNode(targetRef)\n }\n if (targetSelector) {\n return document.querySelector(targetSelector)\n }\n return null\n }",
"statement() {\n return this._statement;\n }",
"function grabNode(id) {\n return nodesData[id];\n }",
"function getUniqueNode(nodeName) {\n return uniqueNodes.get(getTrueNodeName(nodeName).trueName);\n }",
"node() {\n return this.frame().node;\n }",
"function SBParticipant_getNode()\n{\n return this.node;\n}",
"function get_xml_node(which_doc, which_id){\r\n\ttry {\r\n\t\treturn which_doc.getElementsByTagName(which_id)[0];\r\n\t}\r\n\tcatch(err) {\r\n\t\treturn null;\r\n\t}\r\n}",
"function makeNode(javaNode) {\n if (!javaNode) {\n return null;\n }\n if (_domNodes.containsKey(javaNode)) {\n return _domNodes.get(javaNode);\n }\n const isElement = javaNode.getNodeType() === org.w3c.dom.Node.ELEMENT_NODE;\n const jsNode = isElement ? new window.DOMElement(javaNode) : new window.DOMNode(javaNode);\n _domNodes.put(javaNode, jsNode);\n return jsNode;\n }",
"createBlankNode(suggestedName) {\n let name, index;\n // Generate a name based on the suggested name\n if (suggestedName) {\n name = suggestedName = `_:${suggestedName}`, index = 1;\n while (this._ids[name])\n name = suggestedName + index++;\n }\n // Generate a generic blank node name\n else {\n do { name = `_:b${this._blankNodeIndex++}`; }\n while (this._ids[name]);\n }\n // Add the blank node to the entities, avoiding the generation of duplicates\n this._ids[name] = ++this._id;\n this._entities[this._id] = name;\n return this._factory.blankNode(name.substr(2));\n }",
"_getNode(idx) {\n let currentNode = this.head;\n let count = 0;\n\n while (currentNode !== null && count !== idx) {\n currentNode = currentNode.next;\n count++;\n }\n return currentNode;\n }",
"ExpressionStatement() {\n const expression = this.Expression();\n this._eat(\";\");\n return factory.ExpressionStatement(expression);\n }",
"add(statement) {\n this.statements.push(statement);\n return this;\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the bext score and the move to make, by traversing down each node to check the score. note that the lower the score, the better it is for black. | dftraverse(){ //callback is a function to be used when you either reached the last node, or exhaust all the previous
(function recurse(currentnode,alpha,beta){
//apply aplha beta pruning here.
/**
* alpha for white, beta for black
*/
if(!currentnode) return;
var effscore = currentnode.score;
//console.log(currentnode.playercolor + "," + currentnode.effectivescore);
for(var i = 0; i < currentnode.children.length; i++){
recurse(currentnode.children[i],alpha,beta);
//onsole.log(currentnode.children[i].playercolor + " " + currentnode.children[i].effectivescore);
if(currentnode.playercolor == "W"){ //maximiser
//get higher score;
effscore = Math.max(effscore, currentnode.children[i].effectivescore);
alpha = Math.max(alpha,effscore);
if(alpha >= beta) break;
}
else{ //minimiser
//get lower score;
effscore = Math.min(effscore, currentnode.children[i].effectivescore);
beta = Math.min(beta,effscore);
if(beta <= alpha) break;
}
//add code to get score here.
}
currentnode.effectivescore = effscore;
//console.log(currentnode.playercolor + "," + currentnode.effectivescore);
})(this,Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);
} | [
"__score(){\n this.p1Score = 0;\n this.p2Score = 0;\n\n //Will be Used to Track Which Spaces Have Been Checked\n var visited = new GameBoard(this.size);\n\n for(var row = 0; row < this.size; row++){\n for(var col = 0; col < this.size; col++){\n var hasBlackNeighbours = false;\n var hasWhiteNeighbours = false;\n\n //Only Check Empty Spaces Which Have Not Yet Been Visited\n if(visited.get(row, col) === 0 && this.board.get(row, col) === 0){\n visited.set(1, row, col);\n //An Array Containing The Coordinates of a Grouping of Empty Spaces\n var emptySpaces = this.board.__getArmyCoords(0, row, col);\n\n for(var i = 0; i < emptySpaces.length; i++){\n visited.set(1, emptySpaces[i].x, emptySpaces[i].y);\n if(this.__hasOccupiedNeighbours(2, emptySpaces[i].x, emptySpaces[i].y)){\n hasBlackNeighbours = true;\n }\n if(this.__hasOccupiedNeighbours(1, emptySpaces[i].x, emptySpaces[i].y)){\n hasWhiteNeighbours = true;\n }\n //If The Grouping of Spaces Has Black and White\n //Neighbours, the territory is not owned by either\n if(hasBlackNeighbours && hasWhiteNeighbours){\n break;\n }\n }\n if(!(hasBlackNeighbours && hasWhiteNeighbours)){\n if(hasBlackNeighbours){\n this.p2Score += emptySpaces.length;\n }else if(hasWhiteNeighbours){\n this.p1Score += emptySpaces.length;\n }\n }\n }\n }\n }\n //Score = Territory Owned + Stones Captured + Stones on Board + Komi\n this.p1Score += this.p1Captured + this.board.count(1);\n this.p2Score += this.p2Captured + this.board.count(2) + 6.5;\n }",
"function nextMove() {\n\n nodes = 0;\n leaves = 0;\n\n console.time(\"ai move\");\n\n let alpha = -Infinity;\n let beta = Infinity;\n\n let bestScore = Infinity;\n let bestPiecePos = null;\n let bestMove = null;\n\n if (opening) {\n\n if (move_n >= opening_move.length) {\n opening = false;\n }\n else {\n\n let next_move = opening_move[move_n].move;\n let next_piece = opening_move[move_n].piece;\n\n if (isAiMoveValid(board[next_piece.y][next_piece.x], next_move.x, next_move.y)) {\n\n bestPiecePos = next_piece;\n bestMove = next_move;\n\n }\n else {\n\n opening = false;\n\n }\n\n move_n++;\n\n } \n \n }\n\n if (!opening) {\n\n for (let y = 0; y < CELLS; y++) {\n\n for (let x = 0; x < CELLS; x++) {\n\n let piece = board[y][x];\n\n //Find next AI piece\n if (piece != null && piece.player == 'ai') {\n\n //Store piece's original position so it can be reverted later\n let piece_x = piece.x;\n let piece_y = piece.y;\n let firstMove;\n if (piece instanceof Pawn || piece instanceof King || piece instanceof Rook) {\n firstMove = piece.firstMove;\n }\n\n let moves = piece.getMoves();\n\n //Loop through piece's possible moves\n for (let key in moves) {\n\n for (let i = 0; i < moves[key].length; i++) {\n\n let move = moves[key][i];\n\n //Check if move is valid\n if (isAiMoveValid(piece, move.x, move.y)) {\n\n nodes++;\n\n //if (key == 'special_l' || key == 'special_r') console.log(\"king check\");\n\n //Castling\n let isCastling = (piece instanceof King && (key == 'special_r' || key == 'special_l'));\n let rook;\n let rook_x;\n let rook_firstMove;\n\n if (isCastling) { \n\n rook = castleRook(piece, move.x, move.y);\n\n if (rook == null || !rook.firstMove) {\n continue;\n } else {\n\n piece.hasCastled = true;\n\n //Store castle rooks original data\n rook_x = rook.x;\n rook_firstMove = rook.firstMove;\n\n //Move rook\n board[rook.y][rook.x] = null;\n board[rook.y][rook.castlex] = rook;\n\n //Update pos in rook\n rook.x = rook.castlex;\n rook.firstMove = false;\n }\n\n }\n \n\n //Store destination cell's content (piece or null) so it can be reverted\n let dest_cell = board[move.y][move.x];\n\n //Move piece on board\n board[move.y][move.x] = piece;\n board[piece.y][piece.x] = null;\n\n //Update pos in piece\n piece.x = move.x;\n piece.y = move.y;\n\n if (piece instanceof Pawn || piece instanceof King || piece instanceof Rook) {\n piece.firstMove = false;\n }\n\n //Run minimax and calculate score\n let score = Infinity;\n\n if (!isInCheck(_cking)) {\n score = alphabetaMax(0, alpha, beta);\n }\n\n if (score < beta) {\n beta = score;\n }\n\n //Check if score is better than best score\n if (score < bestScore) {\n\n bestScore = score;\n bestPiecePos = { x: piece_x, y: piece_y };\n bestMove = move;\n\n }\n\n //Revert values\n board[move.y][move.x] = dest_cell;\n board[piece_y][piece_x] = piece;\n piece.x = piece_x;\n piece.y = piece_y;\n if (piece instanceof Pawn || piece instanceof King || piece instanceof Rook) {\n piece.firstMove = firstMove;\n }\n\n if (isCastling) {\n\n piece.hasCastled = false;\n\n //Revert rook values\n rook.x = rook_x;\n rook.firstMove = rook_firstMove;\n board[rook.y][rook.castlex] = null;\n board[rook.y][rook.x] = rook;\n\n }\n\n } else {\n\n break;\n\n }\n\n }\n\n }\n\n }\n\n\n }\n\n }\n\n }\n\n if (bestPiecePos == null) {\n alert(\"You win!\");\n console.timeEnd(\"ai move\");\n playerTurn = false;\n return;\n }\n \n\n //Move piece\n let piece = board[bestPiecePos.y][bestPiecePos.x];\n\n //Check if it was a castling move\n if (piece instanceof King) {\n\n //Distance king moved along x axis\n let dx = Math.abs(bestPiecePos.x - bestMove.x);\n\n //Check if king was moved more than one space\n if (dx > 1) {\n\n let rook = castleRook(piece, bestMove.x, bestMove.y);\n\n piece.hasCastled = true;\n\n //Move rook\n board[rook.y][rook.x] = null;\n board[rook.y][rook.castlex] = rook;\n\n clearCell(rook.x, rook.y);\n\n rook.x = rook.castlex;\n rook.firstMove = false;\n\n drawPiece(rook);\n\n }\n\n }\n\n //Add move notation before updating piece\n addMoveNotation(piece, bestMove.x, bestMove.y);\n\n board[bestMove.y][bestMove.x] = piece;\n board[piece.y][piece.x] = null;\n\n //Clear cells\n clearCell(piece.x, piece.y);\n clearCell(bestMove.x, bestMove.y); \n\n //Update piece\n piece.x = bestMove.x;\n piece.y = bestMove.y;\n\n if (piece instanceof Pawn || piece instanceof King || piece instanceof Rook) {\n\n if (piece.firstMove) {\n piece.firstMove = false;\n }\n\n }\n\n //Draw piece\n drawPiece(piece);\n\n updateScoreArea();\n updateMoveList();\n\n if (playerColor == 'white') move_no++;\n\n playerTurn = true;\n\n console.timeEnd(\"ai move\");\n\n}",
"function getTotalScore() {\n\n let ai = 0;\n let human = 0;\n\n //Calculate pawn penalties\n //Number of pawns in each file\n let human_pawns = [];\n let ai_pawns = [];\n\n for (let x = 0; x < 8; x++) {\n\n let h_cnt = 0;\n let a_cnt = 0;\n\n for (let y = 0; y < 8; y++) {\n\n let chk_piece = board[y][x];\n\n if (chk_piece != null && chk_piece instanceof Pawn) {\n\n if (chk_piece.player == 'human') h_cnt++;\n else a_cnt++;\n\n //Pawn rank bonuses\n if (x > 1 && x < 6) {\n\n //Normalize y to chess rank 1 - 8\n let rank = (chk_piece.player == 'human') ? Math.abs(y - 7) + 1 : y + 1;\n\n switch (x) {\n\n case 2:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 3.9 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 2.3 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 2.3 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 3.9 * (rank - 2);\n break;\n\n case 3:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 5.4 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 7.0 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 7.0 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 5.4 * (rank - 2);\n break;\n\n case 4:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 7.0 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 5.4 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 5.4 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 7.0 * (rank - 2);\n break;\n\n case 5:\n if (chk_piece == 'human' && chk_piece.color == 'white') human += 2.3 * (rank - 2);\n else if (chk_piece == 'human' && chk_piece.color == 'black') human += 3.9 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'white') ai -= 3.9 * (rank - 2);\n else if (chk_piece == 'ai' && chk_piece.color == 'black') ai -= 2.3 * (rank - 2);\n break;\n\n }\n\n }\n\n }\n\n }\n\n human_pawns.push(h_cnt);\n ai_pawns.push(a_cnt);\n\n }\n\n for (let i = 0; i < 8; i++) {\n\n //Doubled pawn penalty\n if (human_pawns[i] > 1) human -= (8 * human_pawns[i]);\n if (ai_pawns[i] > 1) ai += (8 * ai_pawns[i]);\n\n //Isolated pawn penalties\n if (i == 0) {\n if (human_pawns[i] > 0 && human_pawns[i + 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i + 1] == 0) ai += (10 * ai_pawns[i]);\n }\n else if (i == 7) {\n if (human_pawns[i] > 0 && human_pawns[i - 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i - 1] == 0) ai += (10 * ai_pawns[i]);\n }\n else {\n if (human_pawns[i] > 0 && human_pawns[i - 1] == 0 && human_pawns[i + 1] == 0) human -= (10 * human_pawns[i]);\n if (ai_pawns[i] > 0 && ai_pawns[i - 1] == 0 && ai_pawns[i + 1] == 0) ai += (10 * ai_pawns[i]);\n }\n\n }\n\n //Get material score\n for (let y = 0; y < 8; y++) {\n\n for (let x = 0; x < 8; x++) {\n\n if (board[y][x] != null) {\n\n let piece = board[y][x];\n\n //Material\n if (piece.player == 'human') human += piece.score;\n else ai += piece.score; \n\n //Knight bonuses/penalties \n if (piece instanceof Knight) {\n\n //Center tropism\n let c_dx = Math.abs(3.5 - x);\n let c_dy = Math.abs(3.5 - y);\n\n let c_sum = 1.6 * (6 - 2 * (c_dx + c_dy));\n\n if (piece.player == 'human') human += c_sum;\n else ai -= c_sum;\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = 1.2 * (5 - (k_dx + k_dy));\n\n human += k_sum;\n\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = 1.2 * (5 - (k_dx + k_dy));\n\n ai -= k_sum;\n\n }\n\n }\n\n //Rook bonuses/penalties\n else if (piece instanceof Rook) {\n\n //Seventh rank bonus\n if (piece.player == 'human' && y == 1) human += 22;\n else if (piece.player == 'ai' && y == 6) ai -= 22;\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = -1.6 * Math.min(k_dx, k_dy);\n\n human += k_sum;\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = -1.6 * Math.min(k_dx, k_dy);\n\n ai -= k_sum;\n\n }\n\n //Doubled rook bonus\n //Check rank\n let left_chk = true;\n let right_chk = true;\n let up_chk = true;\n let down_chk = true;\n for (let i = 1; i < 8; i++) {\n\n if (!left_chk && !right_chk && !down_chk && !up_chk) break;\n\n //Check left side\n if (x - i >= 0 && left_chk) {\n\n let chk_piece = board[y][x - i];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else left_chk = false;\n }\n\n } else left_chk = false;\n\n //Check right side\n if (x + i < 8 && right_chk) {\n\n let chk_piece = board[y][x + i];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else right_chk = false;\n }\n\n } else right_chk = false;\n\n //Check up side\n if (y - i >= 0 && up_chk) {\n\n let chk_piece = board[y - i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else up_chk = false;\n }\n\n } else up_chk = false;\n\n //Check down side\n if (y + i < 8 && down_chk) {\n\n let chk_piece = board[y + i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Rook && chk_piece.player == piece.player) break;\n else down_chk = false;\n }\n\n } else down_chk = false;\n\n }\n\n //Doubled rook found\n if (left_chk || right_chk || down_chk || up_chk) {\n\n if (piece.player == 'human') human += 8;\n else ai -= 8;\n\n }\n\n //Open file bonus\n let open_file = true;\n\n for (let i = 1; i < 8; i++) {\n\n //Check up\n if (y - i >= 0) {\n\n let chk_piece = board[y - i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Pawn) {\n open_file = false;\n break;\n }\n }\n\n }\n\n //Check down\n if (y + i < 8) {\n\n let chk_piece = board[y + i][x];\n if (chk_piece != null) {\n if (chk_piece instanceof Pawn) {\n open_file = false;\n break;\n }\n }\n\n }\n\n }\n\n if (open_file) {\n\n if (piece.player == 'human') human += 8;\n else ai -= 8;\n\n }\n\n\n }\n\n //Queen bonuses/penalties\n else if (piece instanceof Queen) {\n\n //King tropism\n if (piece.player == 'human') {\n\n let k_dx = Math.abs(_cking.x - x);\n let k_dy = Math.abs(_cking.y - y);\n\n let k_sum = -0.8 * Math.min(k_dx, k_dy);\n\n human += k_sum;\n\n\n } else {\n\n let k_dx = Math.abs(_pking.x - x);\n let k_dy = Math.abs(_pking.y - y);\n\n let k_sum = -0.8 * Math.min(k_dx, k_dy);\n\n ai -= k_sum;\n\n }\n\n }\n\n //King bonuses/penalties\n else if (piece instanceof King) {\n\n //Cant castle penalty\n if (!piece.hasCastled) {\n\n //Castling no longer possible as king has moved at least once\n if (!piece.firstMove) {\n\n if (piece.player == 'human') human -= 15;\n else ai += 15;\n\n } else {\n\n //Rooks\n let q_rook;\n let k_rook;\n\n //Check flags, true if castling is available\n let q_rook_chk = false;\n let k_rook_chk = false;\n\n if (piece.player == 'human') {\n\n if (piece.color == 'white') {\n\n q_rook = castleRook(piece, x - 2, y);\n k_rook = castleRook(piece, x + 2, y);\n\n } else {\n\n q_rook = castleRook(piece, x + 2, y);\n k_rook = castleRook(piece, x - 2, y);\n\n }\n\n } else {\n\n if (piece.color == 'white') {\n\n q_rook = castleRook(piece, x + 2, y);\n k_rook = castleRook(piece, x - 2, y);\n\n } else {\n\n q_rook = castleRook(piece, x - 2, y);\n k_rook = castleRook(piece, x + 2, y);\n\n }\n\n }\n\n q_rook_chk = q_rook != null && q_rook.firstMove;\n k_rook_chk = k_rook != null && k_rook.firstMove;\n\n //Castling no longer available\n if (!q_rook_chk && !k_rook_chk) {\n\n if (piece.player == 'human') human -= 15;\n else ai += 15;\n \n }\n //Queen side castling not available\n else if (!q_rook_chk) {\n\n if (piece.player == 'human') human -= 8;\n else ai += 8;\n\n }\n //King side castling not available\n else if (!k_rook_chk) {\n\n if (piece.player == 'human') human -= 12;\n else ai += 12;\n\n }\n\n }\n\n //Check kings quadrant\n let enemy_pieces = 0;\n let friendly_pieces = 0;\n\n //Find quadrant\n //Top/Left\n if (y < 4 && x < 4) {\n\n for (let i = 0; i < 4; i++) {\n\n for (let j = 0; j < 4; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Top/Right\n else if (y < 4 && x >= 4) {\n\n for (let i = 0; i < 4; i++) {\n\n for (let j = 4; j < 8; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Bottom/Left\n else if (y >= 4 && x < 4) {\n\n for (let i = 4; i < 8; i++) {\n\n for (let j = 0; j < 4; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n //Bottom/Right\n else {\n\n for (let i = 4; i < 8; i++) {\n\n for (let j = 4; j < 8; j++) {\n\n let chk_piece = board[i][j];\n if (chk_piece != null) {\n\n //Skip this cell as this is the king\n if (i == y && x == j) continue;\n\n //Enemy piece found\n if (piece.player != chk_piece.player) {\n\n if (chk_piece instanceof Queen) enemy_pieces += 3;\n else enemy_pieces++;\n\n }\n //Friendly piece found\n else {\n\n if (chk_piece instanceof Queen) friendly_pieces += 3;\n else friendly_pieces++;\n\n }\n\n }\n\n }\n\n }\n\n }\n\n if (enemy_pieces > friendly_pieces) {\n\n let diff = enemy_pieces - friendly_pieces;\n\n if (piece.player == 'human') human -= (5 * diff);\n else ai += (5 * diff);\n\n }\n\n }\n\n }\n\n //Bishop bonuses/penalties\n if (piece instanceof Bishop) {\n\n //Back rank penalty\n if (piece.player == 'human' && y == 7) human -= 11;\n else if (piece.player == 'ai' && y == 0) ai += 11;\n\n //Bishop pair bonus\n let pair = false;\n\n for (let i = 0; i < 8; i++) {\n\n for (let j = 0; j < 8; j++) {\n\n if (i == y && j == x) continue;\n\n let chk_piece = board[i][j];\n\n if (chk_piece != null && chk_piece.player == piece.player && chk_piece instanceof Bishop) {\n pair = true;\n break;\n }\n\n }\n\n }\n\n if (pair && piece.player == 'human') human += 50;\n else if (pair && piece.player == 'ai') ai -= 50;\n\n //Pawn penalties\n let p_cntr = 0;\n\n //Top left\n if (x - 1 >= 0 && y - 1 >= 0 && board[y - 1][x - 1] != null && board[y - 1][x - 1] instanceof Pawn) p_cntr++;\n\n //Top right\n if (x + 1 < 8 && y - 1 >= 0 && board[y - 1][x + 1] != null && board[y - 1][x + 1] instanceof Pawn) p_cntr++;\n\n //Bottom left\n if (x - 1 >= 0 && y + 1 < 8 && board[y + 1][x - 1] != null && board[y + 1][x - 1] instanceof Pawn) p_cntr++;\n\n //Bottom right\n if (x + 1 < 8 && y + 1 < 8 && board[y + 1][x + 1] != null && board[y + 1][x + 1] instanceof Pawn) p_cntr++;\n\n if (piece.player == 'human') human -= (p_cntr * 3);\n else ai += (p_cntr * 3);\n\n }\n\n\n \n }\n\n }\n\n }\n\n return ai + human;\n\n}",
"function checkScore() {\n if (locArray[currentLocation].hasVisited === false) {\n locArray[currentLocation].hasVisited = true;\n score = score + 5; \n } else if (locArray[currentLocation].hasVisited === true) {\n score = score + 0; \n } \n }",
"minimax(newBoard, player) {\n let unvisitedCells = newBoard.unvisitedCells();\n\n if (this.checkWinner(newBoard, this.humanPlayer.identifier)) {\n return { score: -10 };\n } else if (this.checkWinner(newBoard, this.computerPlayer.identifier)) {\n return { score: 10 };\n } else if (unvisitedCells.length === 0) {\n return { score: 0 };\n }\n\n let moves = [];\n for (let i = 0; i < unvisitedCells.length; i++) {\n let move = {};\n move.index = newBoard.board[unvisitedCells[i]];\n newBoard.board[unvisitedCells[i]] = player;\n\n if (player === this.computerPlayer.identifier) {\n let result = this.minimax(newBoard, this.humanPlayer.identifier);\n move.score = result.score;\n } else {\n let result = this.minimax(newBoard, this.computerPlayer.identifier);\n move.score = result.score;\n }\n\n newBoard.board[unvisitedCells[i]] = move.index;\n\n moves.push(move);\n }\n\n let bestMove;\n if (player === this.computerPlayer.identifier) {\n let bestScore = -Infinity;\n for (let i = 0; i < moves.length; i++) {\n if (moves[i].score > bestScore) {\n bestScore = moves[i].score;\n bestMove = i;\n }\n }\n } else {\n let bestScore = Infinity;\n for (let i = 0; i < moves.length; i++) {\n if (moves[i].score < bestScore) {\n bestScore = moves[i].score;\n bestMove = i;\n }\n }\n }\n\n return moves[bestMove];\n }",
"function MiniGameChessStart(Depth) {\n\t\n\tvar MinMaxDepth = Depth;\n\t\t\n\t/**\n\t * Finds a random move to make\n\t * @return {string} move to make\n\t */\n\tvar randomMove = function() {\n\t var possibleMoves = game.moves();\n\t var randomIndex = Math.floor(Math.random() * possibleMoves.length);\n\t return possibleMoves[randomIndex];\n\t};\n\n\t/**\n\t * Evaluates current chess board relative to player\n\t * @param {string} color - Players color, either 'b' or 'w'\n\t * @return {Number} board value relative to player\n\t */\n\tvar evaluateBoard = function(board, color) {\n\t // Sets the value for each piece using standard piece value\n\t var pieceValue = {\n\t\t'p': 100,\n\t\t'n': 350,\n\t\t'b': 350,\n\t\t'r': 525,\n\t\t'q': 1000,\n\t\t'k': 10000\n\t };\n\n\t // Loop through all pieces on the board and sum up total\n\t var value = 0;\n\t board.forEach(function(row) {\n\t\trow.forEach(function(piece) {\n\t\t if (piece) {\n\t\t\t// Subtract piece value if it is opponent's piece\n\t\t\tvalue += pieceValue[piece['type']]\n\t\t\t\t\t * (piece['color'] === color ? 1 : -1);\n\t\t }\n\t\t});\n\t });\n\n\t return value;\n\t};\n\n\t/**\n\t * Calculates the best move looking one move ahead\n\t * @param {string} playerColor - Players color, either 'b' or 'w'\n\t * @return {string} the best move\n\t */\n\tvar calcBestMoveOne = function(playerColor) {\n\t // List all possible moves\n\t var possibleMoves = game.moves();\n\t // Sort moves randomly, so the same move isn't always picked on ties\n\t possibleMoves.sort(function(a, b){return 0.5 - Math.random()});\n\n\t // exit if the game is over\n\t if (game.game_over() === true || possibleMoves.length === 0) return;\n\n\t // Search for move with highest value\n\t var bestMoveSoFar = null;\n\t var bestMoveValue = Number.NEGATIVE_INFINITY;\n\t possibleMoves.forEach(function(move) {\n\t\tgame.move(move);\n\t\tvar moveValue = evaluateBoard(game.board(), playerColor);\n\t\tif (moveValue > bestMoveValue) {\n\t\t bestMoveSoFar = move;\n\t\t bestMoveValue = moveValue;\n\t\t}\n\t\tgame.undo();\n\t });\n\n\t return bestMoveSoFar;\n\t}\n\n\t/**\n\t * Calculates the best move using Minimax without Alpha Beta Pruning.\n\t * @param {Number} depth - How many moves ahead to evaluate\n\t * @param {Object} game - The game to evaluate\n\t * @param {string} playerColor - Players color, either 'b' or 'w'\n\t * @param {Boolean} isMaximizingPlayer - If current turn is maximizing or minimizing player\n\t * @return {Array} The best move value, and the best move\n\t */\n\tvar calcBestMoveNoAB = function(depth, game, playerColor,\n\t\t\t\t\t\t\t\t\tisMaximizingPlayer=true) {\n\t // Base case: evaluate board\n\t if (depth === 0) {\n\t\tvalue = evaluateBoard(game.board(), playerColor);\n\t\treturn [value, null]\n\t }\n\n\t // Recursive case: search possible moves\n\t var bestMove = null; // best move not set yet\n\t var possibleMoves = game.moves();\n\t // Set random order for possible moves\n\t possibleMoves.sort(function(a, b){return 0.5 - Math.random()});\n\t // Set a default best move value\n\t var bestMoveValue = isMaximizingPlayer ? Number.NEGATIVE_INFINITY\n\t\t\t\t\t\t\t\t\t\t\t : Number.POSITIVE_INFINITY;\n\t // Search through all possible moves\n\t for (var i = 0; i < possibleMoves.length; i++) {\n\t\tvar move = possibleMoves[i];\n\t\t// Make the move, but undo before exiting loop\n\t\tgame.move(move);\n\t\t// Recursively get the value of this move\n\t\tvalue = calcBestMoveNoAB(depth-1, game, playerColor, !isMaximizingPlayer)[0];\n\t\t// Log the value of this move\n\t\t//console.log(isMaximizingPlayer ? 'Max: ' : 'Min: ', depth, move, value, bestMove, bestMoveValue);\n\n\t\tif (isMaximizingPlayer) {\n\t\t // Look for moves that maximize position\n\t\t if (value > bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t} else {\n\t\t // Look for moves that minimize position\n\t\t if (value < bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t}\n\t\t// Undo previous move\n\t\tgame.undo();\n\t }\n\t // Log the best move at the current depth\n\t //console.log('Depth: ' + depth + ' | Best Move: ' + bestMove + ' | ' + bestMoveValue);\n\t // Return the best move, or the only move\n\t return [bestMoveValue, bestMove || possibleMoves[0]];\n\t}\n\n\t/**\n\t * Calculates the best move using Minimax with Alpha Beta Pruning.\n\t * @param {Number} depth - How many moves ahead to evaluate\n\t * @param {Object} game - The game to evaluate\n\t * @param {string} playerColor - Players color, either 'b' or 'w'\n\t * @param {Number} alpha\n\t * @param {Number} beta\n\t * @param {Boolean} isMaximizingPlayer - If current turn is maximizing or minimizing player\n\t * @return {Array} The best move value, and the best move\n\t */\n\tvar calcBestMove = function(depth, game, playerColor,\n\t\t\t\t\t\t\t\talpha=Number.NEGATIVE_INFINITY,\n\t\t\t\t\t\t\t\tbeta=Number.POSITIVE_INFINITY,\n\t\t\t\t\t\t\t\tisMaximizingPlayer=true) {\n\t // Base case: evaluate board\n\t if (depth === 0) {\n\t\tvalue = evaluateBoard(game.board(), playerColor);\n\t\treturn [value, null]\n\t }\n\n\t // Recursive case: search possible moves\n\t var bestMove = null; // best move not set yet\n\t var possibleMoves = game.moves();\n\t // Set random order for possible moves\n\t possibleMoves.sort(function(a, b){return 0.5 - Math.random()});\n\t // Set a default best move value\n\t var bestMoveValue = isMaximizingPlayer ? Number.NEGATIVE_INFINITY\n\t\t\t\t\t\t\t\t\t\t\t : Number.POSITIVE_INFINITY;\n\t // Search through all possible moves\n\t for (var i = 0; i < possibleMoves.length; i++) {\n\t\tvar move = possibleMoves[i];\n\t\t// Make the move, but undo before exiting loop\n\t\tgame.move(move);\n\t\t// Recursively get the value from this move\n\t\tvalue = calcBestMove(depth-1, game, playerColor, alpha, beta, !isMaximizingPlayer)[0];\n\t\t// Log the value of this move\n\t\t//console.log(isMaximizingPlayer ? 'Max: ' : 'Min: ', depth, move, value, bestMove, bestMoveValue);\n\n\t\tif (isMaximizingPlayer) {\n\t\t // Look for moves that maximize position\n\t\t if (value > bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t alpha = Math.max(alpha, value);\n\t\t} else {\n\t\t // Look for moves that minimize position\n\t\t if (value < bestMoveValue) {\n\t\t\tbestMoveValue = value;\n\t\t\tbestMove = move;\n\t\t }\n\t\t beta = Math.min(beta, value);\n\t\t}\n\t\t// Undo previous move\n\t\tgame.undo();\n\t\t// Check for alpha beta pruning\n\t\tif (beta <= alpha) {\n\t\t //console.log('Prune', alpha, beta);\n\t\t break;\n\t\t}\n\t }\n\t // Log the best move at the current depth\n\t //console.log('Depth: ' + depth + ' | Best Move: ' + bestMove + ' | ' + bestMoveValue + ' | A: ' + alpha + ' | B: ' + beta);\n\t // Return the best move, or the only move\n\t return [bestMoveValue, bestMove || possibleMoves[0]];\n\t}\n\n\t// Computer makes a move with algorithm choice and skill/depth level\n\tvar makeMove = function(algo, skill=3) {\n\t // exit if the game is over\n\t if (game.game_over() === true) {\n\t\t//console.log('game over');\n\t\treturn;\n\t }\n\t // Calculate the best move, using chosen algorithm\n\t if (algo === 1) {\n\t\tvar move = randomMove();\n\t } else if (algo === 2) {\n\t\tvar move = calcBestMoveOne(game.turn());\n\t } else if (algo === 3) {\n\t\tvar move = calcBestMoveNoAB(skill, game, game.turn())[1];\n\t } else {\n\t\tvar move = calcBestMove(skill, game, game.turn())[1];\n\t }\n\t // Make the calculated move\n\t game.move(move);\n\t // Update board positions\n\t board.position(game.fen());\n\t}\n\n\t// Computer vs Computer\n\tvar playGame = function(algo=4, skillW=2, skillB=2) {\n\t if (game.game_over() === true) {\n\t\t//console.log('game over');\n\t\treturn;\n\t }\n\t var skill = game.turn() === 'w' ? skillW : skillB;\n\t makeMove(algo, skill);\n\t window.setTimeout(function() {\n\t\tplayGame(algo, skillW, skillB);\n\t }, 250);\n\t};\n\n\t// Handles what to do after human makes move.\n\t// Computer automatically makes next move\n\tvar onDrop = function(source, target) {\n\t // see if the move is legal\n\t var move = game.move({\n\t\tfrom: source,\n\t\tto: target,\n\t\tpromotion: 'q' // NOTE: always promote to a queen for example simplicity\n\t });\n\n\t // If illegal move, snapback\n\t if (move === null) return 'snapback';\n\n\t // Log the move\n\t //console.log(move)\n\n\t // make move for black\n\t window.setTimeout(function() {\n\t\tmakeMove(4, MinMaxDepth);\n\t }, 200);\n\t};\n\n\tvar board,\n\t\tgame = new Chess();\n\n\t// Actions after any move\n\tvar onMoveEnd = function(oldPos, newPos) {\n\t // Alert if game is over\n\t if (game.game_over() === true) {\n\t\t//alert('Game Over');\n\t\t//console.log('Game Over');\n\t }\n\n\t // Log the current game position\n\t //console.log(game.fen());\n\t};\n\n\t// Check before pick pieces that it is white and game is not over\n\tvar onDragStart = function(source, piece, position, orientation) {\n\t if (game.game_over() === true || piece.search(/^b/) !== -1) {\n\t\treturn false;\n\t }\n\t};\n\n\t// Update the board position after the piece snap\n\t// for castling, en passant, pawn promotion\n\tvar onSnapEnd = function() {\n\t board.position(game.fen());\n\t};\n\n\t// Creates the board div\n\tif (document.getElementById(\"DivChessBoard\") == null) {\n\t\tvar div = document.createElement(\"div\");\n\t\tdiv.setAttribute(\"ID\", \"DivChessBoard\");\n\t\tdiv.className = \"HideOnDisconnect\";\n\t\tdiv.style.width = \"600px\";\n\t\tdiv.style.height = \"600px\";\n\t\tdocument.body.appendChild(div);\n\t}\n\n\t// Configure the board\n\tvar cfg = {\n\t draggable: true,\n\t position: 'start',\n\t // Handlers for user actions\n\t onMoveEnd: onMoveEnd,\n\t onDragStart: onDragStart,\n\t onDrop: onDrop,\n\t onSnapEnd: onSnapEnd\n\t}\n\tboard = ChessBoard('DivChessBoard', cfg);\n\n\t// Resets the board and shows it\n\tboard.clear();\n\tboard.start();\n\tgame.reset();\n\tMiniGameChessResize();\n\tMiniGameChessBoard = board;\n\tMiniGameChessGame = game;\n\n}",
"function minimax(game, depth, alpha, beta, isMaximizingPlayer, sum, color)\n{\n positionCount++; \n var children = game.ugly_moves({verbose: true});\n \n // Sort moves randomly, so the same move isn't always picked on ties\n children.sort(function(a, b){return 0.5 - Math.random()});\n\n var currMove;\n // Maximum depth exceeded or node is a terminal node (no children)\n if (depth === 0 || children.length === 0)\n {\n return [null, sum]\n }\n\n // Find maximum/minimum from list of 'children' (possible moves)\n var maxValue = Number.NEGATIVE_INFINITY;\n var minValue = Number.POSITIVE_INFINITY;\n var bestMove;\n for (var i = 0; i < children.length; i++)\n {\n currMove = children[i];\n\n // Note: in our case, the 'children' are simply modified game states\n var currPrettyMove = game.ugly_move(currMove);\n var newSum = evaluateBoard(currPrettyMove, sum, color);\n var [childBestMove, childValue] = minimax(game, depth - 1, alpha, beta, !isMaximizingPlayer, newSum, color);\n \n game.undo();\n \n if (isMaximizingPlayer)\n {\n if (childValue > maxValue)\n {\n maxValue = childValue;\n bestMove = currPrettyMove;\n }\n if (childValue > alpha)\n {\n alpha = childValue;\n }\n }\n\n else\n {\n if (childValue < minValue)\n {\n minValue = childValue;\n bestMove = currPrettyMove;\n }\n if (childValue < beta)\n {\n beta = childValue;\n }\n }\n\n // Alpha-beta pruning\n if (alpha >= beta)\n {\n break;\n }\n }\n\n if (isMaximizingPlayer)\n {\n return [bestMove, maxValue]\n }\n else\n {\n return [bestMove, minValue];\n }\n}",
"function score(state) {\n const result = calculateWinner(state.squares);\n if (result === 'X') {\n return -10;\n } else if (result === 'O') {\n return 10;\n } else {\n return 0;\n }\n}",
"function score(boardState)\n{\n if (checkWin(boardState) == X)\n {\n return 10;\n }\n else if(checkWin(boardState) == O)\n {\n return -10;\n }\n else if(checkWin(boardState) == NONE)\n {\n return 0;\n }\n}",
"function minimax(state, limit, player) {\n var moves = [];\n if(limit > 0) {\n //Loop over the state matrix checking if the squares are undefined (empty).\n //Values set to the gameboard columns, 7x6.\n for(var idx1 = 0; idx1 < 7; idx1++) {\n for(var idx2 = 0; idx2 < 6; idx2++) {\n //If the square is empty create a new object representing a potential move.\n if(state[idx1][idx2] === undefined) {\n //Added to code to ensure the computers markers drop to the bottom of the column. The same principle as\n //what can be found in 'click' function ensuring the users marker drops to the bottom of the column.\n idx2 = 5;\n while(state[idx1][idx2]) {\n idx2 = idx2 - 1;\n }\n if(idx2 >= 0) {\n var move = {\n x: idx1,\n y: idx2,\n //When a potential move is generated, use the deepClone function to also store the state after this move.\n state: deepClone(state),\n score: 0\n };\n move.state[idx1][idx2] = player;\n //Check to see if the game is at a leaf in the game tree or at an internal node. The distinction is made by first checking to see if the 'limit' is 1 or if the game has been won.\n if(limit === 1 || check_game_winner(move.state) !== undefined) {\n //Updated upon creation of heuristic function. Calls the function instead of the previous hard-coded heuristic based on game winner.\n move.score = heuristic(move.state);\n }\n // Handling of the internal node case.\n else {\n //Recursively calculate all moves and call the minimax function with the updated move.state, the 'limit' reduced by 1 and the players switched.\n //Assign list of all posible moves to move.moves.\n //It's important to remember that moves are given a score!\n move.moves = minimax(move.state, limit - 1, player == 'Red' ? 'Yellow' : 'Red');\n var score = undefined;\n //Loop over all of the move.moves handling one of three cases:\n for(var idx3 = 0; idx3 < move.moves.length; idx3++) {\n //Meaning this is the current move and assign the 'score' the moves score.\n if(score === undefined) {\n score = move.moves[idx3].score;\n }\n //The current player is 'Red' (user), calculate the score as the max of the score and that potential moves score.\n else if(player === 'Red') {\n score = Math.max(score, move.moves[idx3].score);\n }\n //The current player is 'Yellow' (computer), calculate the score as the max of the score and that potential moves score.\n else if(player === 'Yellow') {\n score = Math.min(score, move.moves[idx3].score);\n }\n }\n move.score = score;\n }\n moves.push(move);\n }\n }\n }\n }\n }\n return moves;\n}",
"function drawScoreboard() {\r\n \r\n ctx.fillStyle = \"black\";\r\n ctx.font = \"30px Arial\";\r\n ctx.fillText(\"Score: \" + score, 20, 380);\r\n\r\n if(score < 20) {\r\n ctx.fillStyle = \"black\";\r\n ctx.font = \"30px Arial\";\r\n ctx.fillText(\"Level 1 \", 280, 380);\r\n }\r\n\r\n if(score >= 20) {\r\n ctx.fillStyle = \"black\";\r\n ctx.font = \"30px Arial\";\r\n ctx.fillText(\"Level 2 \", 280, 380);\r\n }\r\n}",
"function checkScore() {\n if (totalScoreNumber === currentGoalNumber && currentGoalNumber != 0) {\n wins++;\n $(\"#wins\").text(\"Wins: \" + wins);\n setNumbers();\n }\n else if (totalScoreNumber > currentGoalNumber) {\n losses++;\n $(\"#losses\").text(\"Losses: \" + losses);\n setNumbers();\n }\n }",
"function calculateScore(games) {\n\tconst a = [0, 0]\n\tconst x = games.map(x => {\n\t\tif (x[0] === \"R\" && x[1] === \"P\" || x[0] === \"P\" && x[1] === \"S\" || x[0] === \"S\" && x[1] === \"R\") return \"B\";\n\t\tif (x[0] === \"R\" && x[1] === \"S\" || x[0] === \"S\" && x[1] === \"P\" || x[0] === \"P\" && x[1] === \"R\") return \"A\";\n\t\tif (x[0] === \"R\" && x[1] === \"R\" || x[0] === \"S\" && x[1] === \"S\" || x[0] === \"P\" && x[1] === \"P\") return \"T\";\n\t})\n\tfor (let i = 0; i < x.length; i++) {\n\t\tif (x[i] === \"A\") a[0]++;\n\t\tif (x[i] === \"B\") a[1]++;\n\t}\n\treturn a[0] > a[1] ? \"Abigail\" : a[0] < a[1] ? \"Benson\" : \"Tie\";\n}",
"function matchNumbers(score) {\n\n console.log(score + ' :score');\n console.log(goalNumber + ' :Goal');\n\n // win if score = goalnumber\n if (score === goalNumber) {\n\n $('.win-lose').text('You Win!');\n $('win-lose').css('color', 'darkgreen')\n\n winsCounter++;\n $('#wins').text('Wins: ' + winsCounter);\n\n newGame();\n }\n\n // lose if score > goalnumber\n else if (score > goalNumber) {\n\n $('.win-lose').text('You Lost.');\n $('.win-lose').css('color', 'red');\n\n lossCounter++;\n $('#losses').text('Losses: ' + lossCounter);\n\n newGame();\n }\n\n }",
"function displayScore(){\n\n // set fill for this entire function\n fill(fgColor-100);\n // divide score into rows (set row length)\n var row=4;\n // check left paddle's score\n for(var i=0; i<leftPaddle.score; i++){\n // for each point, display a ball.\n // determine which row this ball falls into\n var leftScoreRow = floor(i/row);\n // determine x pos depending on score and row size\n var leftScoreX = scoreSize+1.5*i*scoreSize-leftScoreRow*(1.5*row*scoreSize);\n // determine y pos depending on score and row size\n var leftScoreY = scoreSize+leftScoreRow*1.5*scoreSize;\n // display ball\n rect(leftScoreX, leftScoreY,scoreSize,scoreSize);\n }\n // check right paddle's score,\n // and do the same.\n for(var i=0; i<rightPaddle.score; i++){\n var rightScoreRow = floor(i/row);\n var rightScoreX = width-(scoreSize+1.5*i*scoreSize-rightScoreRow*(1.5*row*scoreSize));\n var rightScoreY = scoreSize+rightScoreRow*1.5*scoreSize;\n rect(rightScoreX, rightScoreY,scoreSize,scoreSize);\n }\n\n}",
"function scoringLogic(score){\n\n if (score > 20 && score < 40) {\n dropRate = 30\n wallIncreaseSpeed = 0.3\n dropBallSpeed = 3\n }\n else if (score > 40 && score < 60) {\n dropRate = 20\n wallIncreaseSpeed = 0.5\n dropBallSpeed = 4\n }\n else if (score > 60 && score < 80){\n dropRate = 15\n wallIncreaseSpeed = 0.7\n dropBallSpeed = 5\n }\n else if (score > 80 && score < 100){\n dropRate = 15\n wallIncreaseSpeed = 0.8\n dropBallSpeed = 5\n }\n else if (score > 100){\n dropRate = 10\n wallIncreaseSpeed = 1.2\n dropBallSpeed = 5\n }\n}",
"function evaluateLine(indx1, indx2, indx3) {\n var score = 0;\n\n // First cell\n if (board[indx1].player === playerType.BOT) {\n score = 1;\n }\n else if (board[indx1].player === playerType.HUMAN) {\n score = -1;\n }\n\n // Second cell\n if (board[indx2].player === playerType.BOT) {\n if (score == 1) { // cell1 is mySeed\n score = 10;\n }\n else if (score == -1) { // cell1 is oppSeed\n return 0;\n }\n else { // cell1 is empty\n score = 1;\n }\n }\n else if (board[indx1].player === playerType.HUMAN) {\n if (score == -1) { // cell1 is oppSeed\n score = -10;\n }\n else if (score == 1) { // cell1 is mySeed\n return 0;\n }\n else { // cell1 is empty\n score = -1;\n }\n }\n\n // Third cell\n if (board[indx3].player === playerType.BOT) {\n if (score > 0) { // cell1 and/or cell2 is mySeed\n score *= 10;\n }\n else if (score < 0) { // cell1 and/or cell2 is oppSeed\n return 0;\n }\n else { // cell1 and cell2 are empty\n score = 1;\n }\n }\n else if (board[indx1].player === playerType.HUMAN) {\n if (score < 0) { // cell1 and/or cell2 is oppSeed\n score *= 10;\n }\n else if (score > 1) { // cell1 and/or cell2 is mySeed\n return 0;\n }\n else { // cell1 and cell2 are empty\n score = -1;\n }\n }\n return score;\n}",
"function makeBestMove(game, color) {\n if (color === 'b')\n {\n var move = getBestMove(game, color, globalSum)[0];\n }\n else\n {\n var move = getBestMove(game, color, -globalSum)[0];\n }\n\n globalSum = evaluateBoard(move, globalSum, 'b');\n\n return move;\n}",
"function makeBestMove() {\n\t\t\t// look for winning move\n\t\t\t//then findBestCorner();\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add/remove mouseout event to the element | add_out(func) {
this.add_event("mouseout", func);
} | [
"onElementMouseOut(event) {\n super.onElementMouseOut(event);\n\n const me = this;\n\n // We must be over the event bar\n if (event.target.closest(me.eventInnerSelector) && me.resolveTimeSpanRecord(event.target) && me.hoveredEventNode) {\n // out to child shouldn't count...\n if (event.relatedTarget && DomHelper.isDescendant(event.target.closest(me.eventInnerSelector), event.relatedTarget)) return;\n\n me.unhover(event);\n }\n }",
"function mouseouthandler(event) {\n //console.log(\"the mouse is no longer over canvas:: \" + event.target.id);\n mouseIn = 'none';\n }",
"function elementMouseout(e){\n\t\t\tapplyBg(this,\"jQueryMultipleBgStaticSelector\");\n\t\t}",
"function handleMouseOut(event, d) {\n jobsG.selectAll(\".job\").transition()\n .duration(\"100\")\n .style(\"opacity\", 1);\n\n releasesG.selectAll(\".release\").transition()\n .duration(\"100\")\n .style(\"opacity\", 1);\n\n deadlinesG.selectAll(\".deadline\").transition()\n .duration(\"100\")\n .style(\"opacity\", 1);\n \n tooltip.transition()\n .duration(\"100\")\n .style(\"opacity\", 0);\n\n tooltip.selectAll('*').remove();\n }",
"function outEvent() {\n if (isMovable(this)) {\n this.classList.remove(\"movabletile\");\n } \n }",
"function ul_mouseout() {\n if (!dragActive)\n clearListItemStyles();\n }",
"function onOut(ev) {\n var rect = pickRect(ev.target);\n if (rect != null && isHighlighted(rect) && !isSticky(rect)) {\n toggleHighlightClassAndOutgoingEdges(rect);\n }\n }",
"function onPicOut(event) {\n event.target.classList.add(\"picOut\");\n event.target.classList.remove(\"picOver\");\n}",
"function hoverOffOption(event) {\n $(event.target).css(\"border-color\",\"transparent\");\n }",
"function pwPlateSelector_plateOnMouseOut(plate){\r\n\t//empty function\r\n}",
"mouseOut() {\n this.setState({\n markingMenu: { ...this.state.markingMenu, mouseOver: false }\n });\n }",
"function onMouseOut(e) {\n // Only take action if the relatedTarget is not the currentTarget or a child of the currentTarget\n if (e.relatedTarget && (e.currentTarget !== e.relatedTarget) && !hasChild(e.currentTarget, e.relatedTarget)) {\n dismissTooltipOfParent(e.currentTarget);\n }\n }",
"function mouseout() {\n d3.select(this).select('text')\n .transition().duration(200)\n .style({opacity: 0.0});\n sizeNodes('artist', node);\n }",
"function mouseoutHeader(event) {\n\toutputEl.innerHTML = `You left me!`;\n}",
"imageMouseOutHandler() {\n clearInterval(this.triggerTime);\n }",
"function hEvent_HotArea_MouseOut( oSource )\r\n\t\t{\r\n\t\t\tevent.cancelBubble = true;\r\n\t\t\tGetCurrTaskBarImg( oSource.id );\r\n\t\t\tGetCurrTaskBar( oSource.id );\r\n\t\t\t\r\n\t\t\t// Condition for execution.\r\n\t\t\tif(g_oCurrTaskBarImg == TaskBarImg1 || g_oCurrTaskBarImg == TaskBarImg2 || g_oCurrTaskBarImg == TaskBarImg3 )\r\n\t\t\t{\r\n\t\t\t\tif(g_oCurrTaskBar.className == \"taskbar_normal_up_over\")\r\n\t\t\t\t{\r\n\t\t\t\t\tg_oCurrTaskBarImg.src = g_img_taskbar_normal_up;\r\n\t\t\t\t\tg_oCurrTaskBar.className = \"taskbar_normal_up\";\r\n\t\t\t\t}\r\n\t\t\t\telse if(g_oCurrTaskBar.className == \"taskbar_normal_down_over\")\r\n\t\t\t\t{\r\n\t\t\t\t\tg_oCurrTaskBarImg.src = g_img_taskbar_normal_down;\r\n\t\t\t\t\tg_oCurrTaskBar.className = \"taskbar_normal_down\";\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}",
"onLayerMouseLeave() {}",
"function mouse_out_controls()\n{\n\t$(\".chalk_player .media_controls\").attr(\"data-mouse-in\",\"0\");\n}",
"removeMouseInteractions() {\t\t\t\n\t\tthis.ctx.canvas.removeEventListener(\"click\", this.towerStoreClick);\n\t\t\n\t\tthis.ctx.canvas.removeEventListener(\"mousemove\", this.towerStoreMove);\t\t\n\t}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
updates both placesForItinerary and markerPositions by array at once method for itinerary | updateItineraryAndMapByArray(places){
let newMarkerPositions = [];
this.setState({placesForItinerary: places});
places.map((place) => newMarkerPositions.push(L.latLng(parseFloat(place.latitude), parseFloat(place.longitude))));
this.setState({markerPositions: newMarkerPositions});
this.setState({reverseGeocodedMarkerPositions: []});
} | [
"function updateMarkers(jsonData) {\n // For DEMO purpose, randomly generates base employee number for each office\n // let boston = (Math.floor(Math.random() * 10) + 1);\n // let sanfran = (Math.floor(Math.random() * 10) + 1);\n // let orlando = (Math.floor(Math.random() * 10) + 1);\n // let chicago = (Math.floor(Math.random() * 10) + 1);\n\n let boston = 0;\n let sanfran = 0;\n let orlando = 0;\n let chicago = 0;\n\n let marker;\n const labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n let labelIndex = 0;\n\n // Count each office location's number of employees\n jsonData.forEach((employee) => {\n (employee.location === 'Boston') ? boston++ : null;\n (employee.location === 'San Francisco') ? sanfran++ : null;\n (employee.location === 'Chicago') ? chicago++ : null;\n (employee.location === 'Orlando') ? orlando++ : null;\n });\n\n // Markers array\n let markers = [\n ['Boston', boston, 42.3135417, -71.1975856],\n ['Chicago', chicago, 41.8339026, -88.0130316],\n ['SanFrancisco', sanfran, 37.7578149, -122.507812],\n ['Orlando', orlando, 28.4813986, -81.5091802]\n ];\n \n // Place each marker\n for (let i = 0; markers.length > i; i++) {\n let position = new google.maps.LatLng(markers[i][2], markers[i][3]);\n bounds.extend(position);\n\n // Setting each marker location\n marker = new google.maps.Marker({\n position,\n map,\n title: markers[i][0],\n label: labels[labelIndex++ % labels.length]\n }); \n \n // Display employee numbers\n $(`#num-emp-${markers[i][0]}`).text(markers[i][1]); \n\n //Automatically center the map fitting all markers on the screen on resizing window\n $(window).resize(function(){\n map.fitBounds(bounds);\n });\n }\n}",
"function setPostal(markerArray) {\n \n markerArray.forEach(function(marker) {\n \n let lat = marker.getPosition().lat();\n \n let lng = marker.getPosition().lng();\n \n \n let url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=';\n url += lat;\n url += ',';\n url += lng;\n url += '&key=AIzaSyA0dTID9kEIw0w2LDUE444_M0Go7YM4apA&result_type=postal_code';\n\n $.ajax({\n url : url,\n dataType: 'json',\n success : function(data){\n marker.postal = data.results[0].address_components[0].short_name;\n \n },\n error: function(request, error) {\n window.alert(\"Request: \" + JSON.stringify(request));\n }\n });\n });\n}",
"function updateCrimeMarkers(newLocations) {\n resetMarkers();\n // remove all references to previous markers, full delete\n crimeMarkers = [];\n\n for (let i = 0; i < newLocations.length; i++) {\n let position = newLocations[i].location;\n let title = newLocations[i].crimeType;\n\n // create a new marker for each location\n let marker = new google.maps.Marker({\n position: position,\n title: title,\n animation: google.maps.Animation.DROP,\n id: i,\n date: formatDate(newLocations[i].date),\n reportNum: newLocations[i].reportNum\n });\n // add to markers array\n crimeMarkers.push(marker);\n\n // add listeners to open infowindow with crime details on click\n marker.addListener('click', setupCrimeMarkerListener);\n\n let latLng = new google.maps.LatLng(newLocations[i].location.lat, newLocations[i].location.lng);\n heatMapData.push(latLng);\n\n }\n showCrimes();\n\n // re-check standard view by default\n document.getElementById('toggleStandard').checked = true;\n}",
"function setMarkers(location) {\n\n for (i = 0; i < location.length; i++) {\n location[i].holdMarker = new google.maps.Marker({\n position: new google.maps.LatLng(location[i].lat, location[i].lng),\n map: map,\n title: location[i].title,\n icon: {\n url: 'img/marker.png',\n size: new google.maps.Size(25, 40),\n origin: new google.maps.Point(0, 0),\n anchor: new google.maps.Point(12.5, 40)\n },\n shape: {\n coords: [1, 25, -40, -25, 1],\n type: 'poly'\n }\n });\n\n //function to place google street view images within info windows\n //determineImage();\n getFlickrImages(location[i]);\n //Binds infoWindow content to each marker\n //Commented for testing\n // location.contentString = '<img src=\"' + streetViewImage +\n // '\" alt=\"Street View Image of ' + location.title + '\"><br><hr style=\"margin-bottom: 5px\"><strong>' +\n // location.title + '</strong><br><p>' +\n // location.cityAddress + '<br></p><a class=\"web-links\" href=\"http://' + location.url +\n // '\" target=\"_blank\">' + location.url + '</a>';\n\n //Testing flickr out (not yet)\n\n\n var infowindow = new google.maps.InfoWindow({\n content: arrayMarkers[i].contentString\n });\n\n //Click marker to view infoWindow\n //zoom in and center location on click\n new google.maps.event.addListener(location[i].holdMarker, 'click', (function(marker, i) {\n return function() {\n numb = i;\n infowindow.setContent(location[i].contentString);\n infowindow.open(map, this);\n var windowWidth = $(window).width();\n if (windowWidth <= 1080) {\n map.setZoom(14);\n } else if (windowWidth > 1080) {\n map.setZoom(16);\n }\n map.setCenter(marker.getPosition());\n location[i].picBoolTest = true;\n };\n })(location[i].holdMarker, i));\n\n //Click nav element to view infoWindow\n //zoom in and center location on click\n var searchNav = $('#nav' + i);\n searchNav.click((function(marker, i) {\n return function() {\n infowindow.setContent(location[i].contentString);\n infowindow.open(map, marker);\n map.setZoom(16);\n map.setCenter(marker.getPosition());\n location[i].picBoolTest = true;\n };\n })(location[i].holdMarker, i));\n }\n}",
"function updateHotelsMap(stadiumIndex) {\n hotelMap.panTo(stadiums[stadiumIndex].location);\n // If zoom is too far you get no results...\n hotelMap.setZoom(14);\n \n // Search for hotels in the selected city, within the viewport of the map.\n var search = {\n bounds: hotelMap.getBounds(),\n types: ['lodging']\n };\n\n hotels.nearbySearch(search, function(results, status) {\n\n if (status === google.maps.places.PlacesServiceStatus.OK) {\n clearHotelMarkers();\n\n for (var i = 0; i < results.length; i++) {\n\n // Create a marker for each hotel found, and assign a letter for the icon label\n var labels = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n \n hotelMarkers[i] = new google.maps.Marker({\n draggable: false,\n position: results[i].geometry.location,\n animation: google.maps.Animation.DROP,\n icon: 'https://developers.google.com/maps/documentation/javascript/images/marker_green'+labels[i]+'.png',\n });\n \n // If the user clicks a hotel marker, show the details of that hotel in an info window.\n hotelMarkers[i].placeResult = results[i];\n google.maps.event.addListener(hotelMarkers[i], 'click', showInfoWindow);\n setTimeout(dropHotelMarker(i), i * 100);\n }\n\n // Keep the stadium on the hotel results map so its easier to see where you are looking\n var stadium = new google.maps.Marker({\n map: hotelMap,\n draggable: false,\n animation: google.maps.Animation.DROP,\n position: stadiums[stadiumIndex].location,\n title: stadiums[stadiumIndex].name,\n icon: 'assets/images/rugby_ball.png'\n });\n stadium.setMap(hotelMap);\n }\n });\n}",
"function addQuakeMarkers(quakes, map) {\n //loop over the quakes array and add a marker for each quake\n var quake;\n\n for (var i = 0; i < quakes.length; i++) {\n quake = quakes[i];\n quake.mapMarker = new google.maps.Marker({\n map : map,\n position : new google.maps.LatLng(quake.location.latitude, quake.location.longitude)\n });\n\n google.maps.event.addListener(quake.mapMarker, \"click\", function() {\n // Automatically close\n if (gov.usgs.iw) {\n gov.usgs.iw.close();\n }\n\n //create an info window with the quake info\n gov.usgs.iw = new google.maps.InfoWindow({\n content : new Date(quake.datetime).toLocaleString() + \": magnitude \" + quake.magnitude + \" at depth of \" + quake.depth + \" meters\"\n });\n\n //open the info window\n gov.usgs.iw.open(map, this);\n });\n }\n}",
"function updateElevation() {\n if (markers.length > 1) {\n var travelMode = 'direct';\n if (travelMode != 'direct') {//I disabled the other travelmodes.\n calcRoute(travelMode);\n } else {\n var latlngs = [];\n for (var i in markers) {\n latlngs.push(markers[i].getPosition());\n }\n\n elevationService.getElevationAlongPath({\n path : latlngs,\n samples : SAMPLES\n }, plotElevation);\n //updateText(latlngs);//new plan: call from within plotElevation so that I can use the array of elevations.\n }\n }\n}",
"function buildBreweries(brewery) {\n for (var i = 0; i < brewery.length; i++) {\n brewery[i].current = new google.maps.Marker({\n position: new google.maps.LatLng(brewery[i].lat, brewery[i].lng),\n\t\t\t\t\tanimation: google.maps.Animation.DROP,\n map: map,\n name: brewery[i].name,\n });\n\n brewery[i].breweryDetails = '<h4>' + brewery[i].name + '</h4>' +\n '<p>' + brewery[i].street + '<br>' + brewery[i].city + \", \" + brewery[i].state + \" \" + brewery[i].zip + '<br></p>' +\n '<p><a href=\"' + brewery[i].web + '\" target=\"_blank\">' + brewery[i].web + '</a></p>';\n\n var displayDetails = new google.maps.InfoWindow({\n content: markers()[i].breweryDetails\n });\n\n/* Opens InfoWindow when related marker is clicked, causes marker bounce animation, zooms in and centers map on related marker */\n new google.maps.event.addListener(brewery[i].current, 'click', (function(marker, i) {\n return function() {\n displayDetails.setContent(brewery[i].breweryDetails);\n marker.setAnimation(google.maps.Animation.BOUNCE);\n setTimeout(function(){ marker.setAnimation(null); }, 2200);\n displayDetails.open(map,this);\n var browserWidth = $(window).width();\n if(browserWidth <= 1000) {\n map.setZoom(11);\n }\n else if(browserWidth > 1000) {\n map.setZoom(17);\n }\n map.setCenter(marker.getPosition());\n };\n })(brewery[i].current, i));\n\n/* When navigation item is clicked, opens InfoWindow of related marker, causes marker bounce animation, and zooms in and centers map on related marker */\n var navItemSearch = $('#brewery' + i);\n navItemSearch.click((function(marker, i) {\n return function() {\n displayDetails.setContent(brewery[i].breweryDetails);\n marker.setAnimation(google.maps.Animation.BOUNCE);\n setTimeout(function(){ marker.setAnimation(null); }, 2200);\n displayDetails.open(map,marker);\n map.setCenter(marker.getPosition());\n map.setZoom(15);\n };\n })(brewery[i].current, i));\n }\n}",
"function setFlaggedPositions() {\n\tfor (let i = 0; i < positions.length; i++) {\n\t\tfor (let j = 0; j < positions.length; j++) {\n\t\t\tif (positions[i][j] == 2) {\n\n\t\t\t}\n\t\t\telse if (positions[i][j]) {\n\n\t\t\t}\n\t\t}\n\t}\n}",
"updateMarkerData(markerData) {\n let currentData = cloneDeep(this.state.pluginData[\"Marker\"]);\n currentData[this.state.activeEntry] = markerData;\n this.updatePluginData(\"Marker\", currentData);\n }",
"function updateDatapoints() {\n\t\t//remove all markers from the map in order to be able to do a refresh\n\t\tmarkers.clearLayers();\n\t\tmarkers_list = {};\n\t\t//for every datapoint\n\t\tbyId.top(Infinity).forEach(function(p, i) {\n\t\t\t//create a marker at that specific position\n\t\t\tvar marker = L.circleMarker([p.latitude,p.longitude]);\n\t\t\tmarker.setStyle({fillOpacity: 0.5,fillColor:'#0033ff'});\n\t\t\t//add the marker to the map\n\t\t\tmarkers.addLayer(marker);\n\t\t});\n\t}",
"function initMap(array) {\r\n //new map with options\r\nmap = new google.maps.Map(document.getElementById(\"map\"), {\r\n center: { lat: 40.683347, lng: -73.953903 },\r\n zoom: 12,\r\n});\r\n\r\nfor(let i = 0; i < array.length; i++){\r\n addMarker(array[i])\r\n }\r\n}",
"function passToMap() {\n let startBar = [STORE.brewList[0].longitude, STORE.brewList[0].latitude];\n let otherBars = [];\n STORE.brewList.forEach((bar) => {\n otherBars.push([bar.longitude, bar.latitude, bar.name]);\n });\n removeMarkers();\n recenter(startBar);\n addMarker(otherBars);\n}",
"placeShips() {\n if(this.ships.length > 0) {\n for(let i = 0; i < this.ships.length; i++) {\n const ship = this.ships[i];\n for(let j = 0; j < ship.coords.length; j++) {\n const index = this.findCellByXY(ship.coords[j].x, ship.coords[j].y);\n this.matrix[index].status = 's';\n }\n }\n }\n }",
"function updateMap() {\n\tif (myKeyWords == \"\") {\n\t\tfor (var i = 0; i < MAX_K; i++){\n\t\t\tkNearMarkers[i].setVisible(false);\n\t\t}\n\t\treturn ;\n\t}\n\t$.post(\"/search/\", {\n\t\tuserPos:myMarker.getPosition().toUrlValue(),\n\t\tkeyWords:myKeyWords,\n\t}, function(data, status){\n\t\t/* Cancel all the old k-near-markers */\n\t\tfor (var i = 0; i < MAX_K; i++){\n\t\t\tkNearMarkers[i].setVisible(false);\n\t\t}\n\t\t\n\t\t/* Return result from django backend */\n\t\tvar dataJSON = $.parseJSON(data);\n\t\t\n\t\t$(\"#BestMap\").attr(\"src\", dataJSON.BestMap);\n\t\t\n\t\t/* Display the new k-near-markers*/\n\t\t$.each(dataJSON.Pos, function(i, item){\n\t\t\tif (i < MAX_K){\n\t\t\t\t//alert(item.Lat + ';' + item.Lng);\n\t\t\t\tkNearMarkers[i].setPosition({lat:item.Lat, lng:item.Lng});\n\t\t\t\tkNearMarkers[i].setVisible(true);\n\t\t\t\tkNearMarkers[i].setTitle(item.Name + \"\\nAddr: \" + item.Addr \n\t\t\t\t+ \".\\nPCode: \" + item.Pcode);\n\t\t\t\t\n\t\t\t\tif (i < MAX_PANEL) {\n\t\t\t\t\t$(\"#name\"+i).text(item.Name);\n\t\t\t\t\t$(\"#info\"+i).text(\"Address: \" + item.Addr + \". PCode: \" + item.Pcode);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\t//$( \"#rtnMsg\" ).text( data );\n\t});\n\t//$( \"#test_input\" ).text( this.value );\n}",
"function placeGoodMarkers() {\n\tGOOD_listener = google.maps.event.addListener(map, 'click', function(event) {\n\t\tplaceGoodMarker(event.latLng);\n\t});\n}",
"renderVeteranMarkers() {\n const locations = new Set();\n let currentVets = this.state.currentVets;\n if (this.state.currentVets.length + this.state.currentPos.length > 10) {\n currentVets = this.state.currentVets.slice(\n 0,\n 10 - this.state.currentPos.length\n );\n }\n return currentVets.map(veteran => {\n const coordinate = {\n latitude: parseFloat(veteran.lat),\n longitude: parseFloat(veteran.lng),\n };\n //Change coordinate if two pins are in the same location\n if (locations.has(coordinate)) {\n coordinate[\"latitude\"] =\n coordinate[\"latitude\"] + this.state.region.latitudeDelta / 20;\n }\n locations.add(coordinate);\n return (\n <MapView.Marker\n coordinate={coordinate}\n onPress={this.onMarkerPress(veteran, \"veteran\")}\n key={`veteran-${veteran.id}`}\n >\n <ConnectPin pinType=\"veteran\" />\n </MapView.Marker>\n );\n });\n }",
"function refreshMarkers(data) {\n\n // remove all currently visible markers\n clearMarker(markersArray);\n\n // parse the AIS data to extract the vessels\n var vessels = parseXml(data);\n\n // create and return GoogleMaps markers for each of the extracted vessels\n jQuery.extend(true, markersArray, convertToGoogleMarkers(map,vessels));\n\n}",
"function addMarker(location,array) {\r\n var marker = new google.maps.Marker({\r\n position: location,\r\n map: map\r\n });\r\n array.push(marker);\r\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
validates that media was flowing in given rooms. | async function validateMediaFlow(room) {
const testTimeMS = 6000;
// wait for some time.
await new Promise(resolve => setTimeout(resolve, testTimeMS));
// get StatsReports.
const statsBefore = await room.getStats();
const bytesReceivedBefore = getTotalBytesReceived(statsBefore);
// wait for some more time.
await new Promise(resolve => setTimeout(resolve, testTimeMS));
const statsAfter = await room.getStats();
const bytesReceivedAfter = getTotalBytesReceived(statsAfter);
console.log(`Total bytes Received in ${room.localParticipant.identity}'s Room: ${bytesReceivedBefore} => ${bytesReceivedAfter}`);
if (bytesReceivedAfter <= bytesReceivedBefore) {
throw new Error('no media flow detected');
}
} | [
"function check_room_winners(turn)\n{\n for(var room in room_winner)\n {\n //check for rooms that dont already have a winner\n if(room_winner[room]==0)\n {\n var lines_complete = 0; \n var temp_room = rooms[room];\n for(var key in temp_room)\n {\n if(temp_room[key]!=0)\n {\n lines_complete++;\n }\n else \n {\n break;\n }\n }\n if(lines_complete==4)\n {\n room_winner[room]=turn; \n if(turn==PLAYER_TURN)\n alert(\"You have conquered room \" + (Number(room)+1));\n else \n alert(\"I have conquered room \" + (Number(room)+1));\n }\n }\n } \n}",
"function enterState(newState) {\n let validTransitions = rooms[currentRoom].canChangeTo;\n if (validTransitions.includes(newState)) {\n currentRoom = newState;\n } else {\n console.log(`Can't go that way`);\n }\n}",
"function filter(room) {\n let items = schedules;\n items = items.filter((item) => room ? item.timetable.room.id === room.id : true)\n setSchedulesFiltered(items)\n }",
"onRoomList(rooms) {\n this.store.commit('Main/SET_ROOM_LIST', rooms);\n }",
"function addClickValidator(element, room) {\n //Add the event handlers for touch start and touch end to show the focus\n //when clicked on the room\n element.addEventListener('touchstart', listener);\n element.addEventListener('touchend', listener);\n var listener = function() {\n element.classList.toggle('focus');\n }\n\n //Adding the onclick event handler to check if user clicked on correct room\n element.onclick = function() {\n //Scroll to right panel as the outcome of the mapping is shown in teddy\n //dialogue which is in right panel\n scrollRightPanelContainer();\n //Check if the current item id is part of room chosen\n if(room.itemId.includes(currentItem.itemId)) {\n //Progress the game in correct mapping flow taking to next question\n handleGameProgress(true);\n } else {\n //Progress the game in incorrect mapping flow remaining in same question\n handleGameProgress(false);\n }\n }\n}",
"validateParcelsInEstate(estateId, parcels) {\n return __awaiter(this, void 0, void 0, function* () {\n const lands = yield this.getLandOfEstate(estateId);\n const incorrectParcel = lands.find(parcel => !parcels.some(p => coordinateHelpers_1.isEqual(parcel, p)));\n if (incorrectParcel) {\n errors_1.fail(errors_1.ErrorType.ETHEREUM_ERROR, `LAND ${incorrectParcel.x},${incorrectParcel.y} is not included at Estate ${estateId}`);\n }\n });\n }",
"function showRooms(rooms) {\n var counter = 1;\n\n for (var room in rooms) {\n createRoomListing(room, counter);\n counter++;\n }\n }",
"function Room(origin, length, width, front_door, back_door, right_door, left_door) {\n this.front_door = front_door;\n this.back_door = back_door;\n this.right_door = right_door;\n this.left_door = left_door;\n this.length = length;\n this.width = width;\n\n this.isInDoorWay = function(x, y, z) {\n if (this.back_door) {\n if (z <= this.back_door.mesh.position.z + person_height && z >= this.back_door.mesh.position.z - person_height) {\n if (x <= this.back_door.mesh.position.x + this.back_door.length/2 && x >= this.back_door.mesh.position.x - this.back_door.length/2) {\n return 0;\n }\n } if (z > this.back_door.mesh.position.z - 1) {\n player.current_room = (this.back_door.rooms[0] == player.current_room) ? this.back_door.rooms[1] : this.back_door.rooms[0];\n return 0;\n }\n }\n if (this.front_door) {\n if (z <= this.front_door.mesh.position.z + person_height && z >= this.front_door.mesh.position.z - person_height) {\n if (x <= this.front_door.mesh.position.x + this.front_door.length/2 && x >= this.front_door.mesh.position.x - this.front_door.length/2) {\n return 1;\n }\n } if (z < this.front_door.mesh.position.z - 1) {\n player.current_room = player.current_room = (this.front_door.rooms[0] == player.current_room) ? this.front_door.rooms[1] : this.front_door.rooms[0];\n return 1;\n }\n }\n if (this.right_door) {\n if (x <= this.right_door.mesh.position.x + person_height && x >= this.right_door.mesh.position.x - 2*person_height) {\n if (z <= this.right_door.mesh.position.z + this.right_door.length/2 && z >= this.right_door.mesh.position.z - this.right_door.length/2) {\n return 2;\n }\n } if (x >= this.right_door.mesh.position.x - 1) {\n player.current_room = player.current_room = (this.right_door.rooms[0] == player.current_room) ? this.right_door.rooms[1] : this.right_door.rooms[0];\n return 2;\n }\n }\n if (this.left_door) {\n if (x <= this.left_door.mesh.position.x + 2*person_height && x >= this.left_door.mesh.position.x - person_height) {\n if (z <= this.left_door.mesh.position.z + this.left_door.length/2 && z >= this.left_door.mesh.position.z - this.left_door.length/2) {\n return 3;\n }\n } if (x <= this.left_door.mesh.position.x - 1) {\n player.current_room = player.current_room = (this.left_door.rooms[0] == player.current_room) ? this.left_door.rooms[1] : this.left_door.rooms[0];\n return 3;\n }\n }\n return -1;\n }\n\n this.isInDoorView = function(x,y,z, wall) {\n if (this.front_door && wall.mesh.position.z == this.front_door.mesh.position.z) {\n if (x <= this.front_door.mesh.position.x + this.front_door.length/2 && x >= this.front_door.mesh.position.x - this.front_door.length/2) {\n return true;\n }\n }\n if (this.back_door && wall.mesh.position.z == this.back_door.mesh.position.z) {\n if (x <= this.back_door.mesh.position.x + this.back_door.length/2 && x >= this.back_door.mesh.position.x - this.back_door.length/2) {\n return true;\n }\n }\n if (this.right_door && wall.mesh.position.x == this.right_door.mesh.position.x) {\n if (z <= this.right_door.mesh.position.z + this.right_door.length/2 && z >= this.right_door.mesh.position.z - this.right_door.length/2) {\n return true;\n }\n }\n if (this.left_door && wall.mesh.position.x == this.left_door.mesh.position.x) {\n if (z <= this.left_door.mesh.position.z + this.left_door.length/2 && z >= this.left_door.mesh.position.z - this.left_door.length/2) {\n return true;\n }\n }\n return false;\n }\n\n var wall_material = new THREE.MeshLambertMaterial({color:0x080A0A,wireframe:true});\n this.walls = createRoom(origin, length, width, wall_material);\n\n this.corners = new Array();\n this.corners[0] = new THREE.Vector3(origin.x - width/2, origin.y - person_height, origin.z+length/2); //back left bottom\n this.corners[1] = new THREE.Vector3(origin.x + width/2, origin.y - person_height, origin.z+length/2); // back right bottom\n this.corners[2] = new THREE.Vector3(origin.x - width/2, origin.y + length - person_height, origin.z + length/2); // back left top\n this.corners[3] = new THREE.Vector3(origin.x + width/2, origin.y + length - person_height, origin.z + length/2); // back right top\n this.corners[4] = new THREE.Vector3(origin.x - width/2, origin.y - person_height, origin.z - length/2); //front left bottom\n this.corners[5] = new THREE.Vector3(origin.x + width/2, origin.y - person_height, origin.z - length/2); // front right bottom\n this.corners[6] = new THREE.Vector3(origin.x - width/2, origin.y + length - person_height, origin.z - length/2); //front left top\n this.corners[7] = new THREE.Vector3(origin.x + width/2, origin.y + length - person_height, origin.z - length/2); //front right top\n}",
"function checkInvaderWallLimit() {\n\t\tif ((invaders[0][invader_leftLimit].x < 0)\n\t\t\t|| (invaders[0][invader_rightLimit].x + \n\t\t\t\tinvaders[0][invader_rightLimit].width > canvas.width)) {\n\t\t\tinvader_vector = invader_vector * -1;\n\t\t\t// Invader drop (wub wub wub)\n\t\t\tfor (var i = 0; i < NUM_ROWS; i++) {\n\t\t\t\tfor (var j = 0; j < NUM_COLS; j++) {\n\t\t\t\t\tinvaders[i][j].y = invaders[i][j].y + 15;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"_generateRoom() {\n let count = 0;\n while (count < this._roomAttempts) {\n count++;\n let room = _features_js__WEBPACK_IMPORTED_MODULE_1__[\"Room\"].createRandom(this._width, this._height, this._options);\n if (!room.isValid(this._isWallCallback, this._canBeDugCallback)) {\n continue;\n }\n room.create(this._digCallback);\n this._rooms.push(room);\n return room;\n }\n /* no room was generated in a given number of attempts */\n return null;\n }",
"async function sync_meetings(){\n log(\"Beginning sync of active meeting rooms\");\n var fetched_rooms = (await active_meetings.once('value'));\n if(fetched_rooms.exists()){\n fetched_rooms = fetched_rooms.val();\n log(\"Found room:\" + fetched_rooms);\n for(var room_name in fetched_rooms){\n //Add rooms to fetched_rooms\n var room = fetched_rooms[room_name];\n \n var voice_channel = get_channel(room.voice);\n\n if(voice_channel == null){\n return;\n }\n\n meeting_rooms[room_name] = room;\n if(voice_channel.members.size == 0){\n meeting_rooms[room_name][\"timeout\"] = setTimeout(function(){\n delete_room(room_name);\n }, server.MEETING_TIMEOUT_TIME * 1000);\n var owner = get_member(room.owner_id);\n owner.send(\"Your meeting room \" + room_name + \" will delete in \" + server.MEETING_TIMEOUT_TIME + \" seconds unless the voice chat becomes active in this time period\");\n } \n }\n }\n}",
"static updateRoomStatus(room) {\n if (!room) {\n return;\n }\n if (!Memory.Traveler) {\n Memory.Traveler = {}\n Memory.Traveler.rooms = {}\n }\n if (!Memory.Traveler.rooms[room.name])\n Memory.Traveler.rooms[room.name] = {};\n if (room.controller) {\n if (room.controller.owner && !room.controller.my) {\n Memory.Traveler.rooms[room.name].avoid = 1;\n } else {\n delete Memory.Traveler.rooms[room.name].avoid;\n }\n }\n }",
"function validate() {\n var allSafeSquaresOpen = true;\n\n for (var x = 0; x < MSBoard.columns; x++) {\n for (var y = 0; y < MSBoard.rows; y++) {\n square = MSBoard.squares[x][y];\n if (!square.open && !square.mine) {\n allSafeSquaresOpen = false\n }\n square.open = true;\n }\n }\n\n updateView();\n\n if (allSafeSquaresOpen) {\n alert(\"You won!\")\n gameOver = true;\n } else {\n alert(\"Mines were left. You lost.\")\n gameOver = true;\n }\n}",
"function validateInputs(hotelToSave){\n\t\tvar valid = true;\n\t\tif(isNaN(hotelToSave.ratePerRoom)) {\n\t\t\thotel.validationMessages.rateShouldBeNumber = true;\n\t\t\tvalid = false;\n\t\t}\n\t\tif( hotelToSave.contact !== undefined) {\n\t\t\tif(isNaN(hotelToSave.contact.phone1)) {\n\t\t\t\thotel.validationMessages.phone1ShouldBeNumber = true;\n\t\t\t\tvalid = false;\n\t\t\t}\n\t\t\t\n\t\t\tif(isNaN(hotelToSave.contact.phone2)) {\n\t\t\t\thotel.validationMessages.phone2ShouldBeNumber = true;\n\t\t\t\tvalid = false;\n\t\t\t}\n\t\t}\n\t\treturn valid;\n\t}",
"getRoomStack(rooms) {\n var result = [];\n for (var i = 0; i < rooms.length; i++) {\n var room = rooms[i]\n if (\n room.Name !== \"Entrance Hall\"\n && room.Name !== \"Foyer\"\n && room.Name !== \"Grand Staircase\"\n && room.Name !== \"Upper Landing\"\n ) {\n result.push(room);\n }\n }\n return result;\n }",
"function addRoomsToData(data) {\r\n // filter down to only rooms that can accept a new player\r\n var availableRooms = _.filter(rooms, function (room) {\r\n return room.playerIds.length < 4;\r\n });\r\n\r\n // if no rooms are available, create a new room\r\n if (availableRooms.length == 0) {\r\n var newRoom = generateRoom();\r\n rooms.push(newRoom);\r\n availableRooms.push(newRoom);\r\n }\r\n\r\n // convert available rooms to just room id and player count\r\n // and attach to data message\r\n data.rooms = _.map(availableRooms, function (room, index) {\r\n return {\r\n roomId: room.id,\r\n roomIndex: index + 1,\r\n playerCount: room.playerIds.length\r\n };\r\n });\r\n\r\n // attach total number of rooms to data message\r\n data.totalRooms = rooms.length;\r\n\r\n // map-reduce to get total number of players in game\r\n // and attach to message\r\n var roomCounts = _.map(rooms, function (room) {\r\n return room.playerIds.length;\r\n });\r\n data.playersInRooms = _.reduce(roomCounts, function (sum, count) {\r\n return sum + count;\r\n });\r\n }",
"function checkReserveParts(){\n \n for(var part in reservationsJSONarr){\n \n if(!(part in progressData)){\n \n //handle the mismatch\n reservationsJSONarr[part].removed = historyIndex;\n }\n }\n //saveReservations();\n}",
"function isThereADoorToGoToRoom (handlerInput, room){\n const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();\n \n // get the doors in the currentRoom\n const currentRoomDoors = sessionAttributes.gamestate.currentRoom.elements.doors\n \n var canGo = false;\n \n // check if there is a door to go to the room\n if (Object.keys(currentRoomDoors).find(key => (currentRoomDoors[key].roomName === room.name))){\n canGo = true;\n }\n \n return canGo;\n}",
"validateGamesQuantity(){\n\n const list = this.getGamesList().childNodes;\n\n if(list.length > 3){\n\n this.disableElement(this[createInputElement]);\n this.disableElement(this[sliderMenuElement]);\n this.showMessage('You have exceeded allowed number of active games. Complete your active games.');\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mark the field as touched | _markAsTouched() {
this._onTouched();
this._changeDetectorRef.markForCheck();
this.stateChanges.next();
} | [
"fieldTouched(id) {\n const {allFieldsStatus} = this.state;\n allFieldsStatus[id] = true;\n this.setState({allFieldsStatus});\n }",
"handleBlur() {\n this._focussed = false;\n }",
"function fieldRendered(field){\n\t\t// will fire change immediately, no waiting for blur\n\t\tfield.el.on(\"change\", fieldChanged, field);\n\t}",
"didFocus () {\n\n }",
"function touchStart() {\r\n getTouchPos();\r\n\r\n draw(ctx,touchX,touchY);\r\n lastX = touchX, lastY = touchY;\r\n event.preventDefault();\r\n }",
"_handleFocusChange() {\n this.__focused = this.contains(document.activeElement);\n }",
"function setChanged (){\n\t\tformModified = true;\n\t}",
"function emitOnHit(event) {\r\n if (self.onHit) {\r\n self.onHit(event);\r\n }\r\n }",
"function _setFieldListener(field, callback) {\n\t field.addEventListener('input', callback);\n\t }",
"dirty() {\n this.signal();\n }",
"resetOnTouchWater() {\n if (this.y <= 0) {\n alert(\"You won\");\n this.startPosition();\n }\n }",
"setMedium(name, data) {\n this.fieldTouched('medium');\n if (data !== null) {\n const {qualification} = this.state;\n qualification.medium = data;\n this.setState({qualification, medium_error: ''}, () => {\n this.checkForErrors()\n });\n }\n }",
"function fieldChanged(type, name, linenum) {\r\n\t\r\n\tsetStatusSetDate(name);\r\n\t\r\n}",
"function SetAnyChangeToTrue()\t\n\t\t{\n\t\t\t//Change has taken place\n\t\t\tanyChange = 1;\n\t\t}",
"enterFieldModifier(ctx) {\n\t}",
"responding(){\n setTimeout(_=>{\n this.focusInput()\n })\n }",
"startChanged () {\r\n this.$nextTick(() => {\r\n if (this.model.end) {\r\n this.$validator.validate('end')\r\n }\r\n })\r\n this.errors.remove('start')\r\n }",
"setStateOfCell(i,j){\n this.field[i][j].setState(true);\n this.field[i][j].draw();\n }",
"function localPaddleTouched()\n{\n // Our paddle was touched. We are now master so update that flag.\n g_i_am_master_flag = true;\n\n // Publish a SYNC message now.\n publishSyncMessage();\n\n // Set the flag that tells us to ignore the master flag on incoming SYNC messages\n // for a short while (See the header notes in pubnub_pong.js).\n g_ignore_remote_master_flag = true;\n\n // Start the timer that clears the flag to ignore the remote master flag setting\n // in SYNC messages. Wait 1/2 a second before clearing the flag.\n setTimeout(clearIgnoreRemoteMasterFlag, 500);\n}",
"updateDateField(dateField) {\n const me = this;\n\n dateField.on({\n change({ userAction, value }) {\n if (userAction && !me.$isInternalChange) {\n me._isUserAction = true;\n me.value = value;\n me._isUserAction = false;\n }\n },\n thisObj : me\n });\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ADD DOM NODES Each DOM node has an "index" assigned in order of traversal. It is important to minimize our crawl over the actual DOM, so these indexes (along with the descendantsCount of virtual nodes) let us skip touching entire subtrees of the DOM if we know there are no patches there. | function _VirtualDom_addDomNodes(domNode, vNode, patches, eventNode)
{
_VirtualDom_addDomNodesHelp(domNode, vNode, patches, 0, 0, vNode.b, eventNode);
} | [
"function findAndAdd(n, matches) {\n\tif (! n || ! n.parentNode) return;\n\tif (! matches) matches = function(n) { return true; };\n\tvar df = document.createDocumentFragment();\n\tcollectNodes(n, matches, df);\n\t// for (var i=0; i<df.childNodes.length; i++) {\n\t//\tconsole.log(df.childNodes[i]);\n\t// }\n\tn.parentNode.appendChild(df);\n}",
"rebuildTreeIndex() {\n let columnIndex = 0;\n\n this.#rootsIndex.clear();\n\n arrayEach(this.#rootNodes, ([, { data: { colspan } }]) => {\n // Map tree range (colspan range/width) into visual column index of the root node.\n for (let i = columnIndex; i < columnIndex + colspan; i++) {\n this.#rootsIndex.set(i, columnIndex);\n }\n\n columnIndex += colspan;\n });\n }",
"function addHandles ( nrHandles, base ) {\n\n var index, handles = [];\n\n // Append handles.\n for ( index = 0; index < nrHandles; index += 1 ) {\n\n // Keep a list of all added handles.\n handles.push( base.appendChild(addHandle(index )) );\n }\n\n return handles;\n }",
"function add_elem(element, index) {\n //Get old element and copy to new element\n var ul = document.getElementById(element);\n var li_old = ul.children[ul.children.length-1];\n var li_new = li_old.cloneNode(true); \n\n //Empty values and change index\n EmptyValues(li_new);\n ChangeIndex(li_new, index+1);\n\n //Change index of all following elements in list.\n for (var i=index+1; i<ul.children.length; i++)\n ChangeIndex(ul.children[i], i+1);\n \n //Insert element at given position.\n InsertIntoList(ul, li_new, index);\n}",
"addSet() {\n const elemIndex = this.getNumElements();\n this.parents.push(elemIndex);\n this.sizes.push(1);\n this.numSets++;\n return elemIndex;\n }",
"createCommentNodes () {\n const comments = this.createComments();\n const nodes = [];\n for (let i = 0; i < this.canvasHeight; i++) {\n nodes[i] = document.createComment(comments[i]);\n }\n return nodes\n }",
"function attachListenersAndNumerizeDocument() {\n waitForTracklist(() => { // At least one tracklist loaded\n numerize()\n attachTracklistModificationListeners(numerize)\n })\n}",
"cleanLineNumbers(element) {\n const elementCopy = element.cloneNode(true);\n const children = elementCopy.childNodes;\n // using for-of did not work as expected\n for (let i = 0; i < children.length; i++) {\n if (this.getLineNumber(children[i])) {\n children[i].remove();\n }\n if (children[i].childNodes.length > 0) {\n const cleanChildren = this.cleanLineNumbers(children[i]);\n elementCopy.replaceChild(cleanChildren, children[i]);\n }\n }\n return elementCopy;\n }",
"function applyToDOM(){\n var hasSortedAll = elmObjsSorted.length===elmObjsAll.length;\n if (isSameParent&&hasSortedAll) {\n if (isFlex) {\n elmObjsSorted.forEach(function(elmObj,i){\n elmObj.elm.style.order = i;\n });\n } else {\n if (parentNode) parentNode.appendChild(sortedIntoFragment());\n else console.warn('parentNode has been removed');\n }\n } else {\n var criterium = criteria[0]\n ,place = criterium.place\n ,placeOrg = place==='org'\n ,placeStart = place==='start'\n ,placeEnd = place==='end'\n ,placeFirst = place==='first'\n ,placeLast = place==='last'\n ;\n if (placeOrg) {\n elmObjsSorted.forEach(addGhost);\n elmObjsSorted.forEach(function(elmObj,i) {\n replaceGhost(elmObjsSortedInitial[i],elmObj.elm);\n });\n } else if (placeStart||placeEnd) {\n var startElmObj = elmObjsSortedInitial[placeStart?0:elmObjsSortedInitial.length-1]\n ,startParent = startElmObj.elm.parentNode\n ,startElm = placeStart?startParent.firstChild:startParent.lastChild;\n if (startElm!==startElmObj.elm) startElmObj = {elm:startElm};\n addGhost(startElmObj);\n placeEnd&&startParent.appendChild(startElmObj.ghost);\n replaceGhost(startElmObj,sortedIntoFragment());\n } else if (placeFirst||placeLast) {\n var firstElmObj = elmObjsSortedInitial[placeFirst?0:elmObjsSortedInitial.length-1];\n replaceGhost(addGhost(firstElmObj),sortedIntoFragment());\n }\n }\n }",
"[RENDER_TO_DOM](range) {\n range.deleteContents();\n range.insertNode(this.root);\n }",
"__groupNodesByPosition(rawNodes) {\n const nodes = [];\n let tmpStack = [];\n _.each(rawNodes, (rawNode, index) => {\n // Check current and next node position\n const $rawNode = $(rawNode);\n const currentNodePosition = this.__getBottomPosition($rawNode);\n let nextNodePosition = -9999;\n if (rawNodes[index + 1]) {\n nextNodePosition = this.__getBottomPosition(rawNodes[index + 1]);\n }\n\n const isListItem = this.__isListItem($rawNode);\n let gapThreshold = 20;\n if (isListItem) {\n gapThreshold = 15;\n }\n\n // Too far appart, we need to add them\n if (currentNodePosition - nextNodePosition > gapThreshold) {\n let content = $rawNode.html();\n\n // We have something in the stack, we need to add it\n if (tmpStack.length > 0) {\n tmpStack.push($rawNode);\n content = _.map(tmpStack, tmpNode => tmpNode.html()).join('\\n');\n tmpStack = [];\n }\n\n nodes.push({ type: this.getNodeType($rawNode), content });\n return;\n }\n\n // Too close, we keep in the stack\n tmpStack.push($rawNode);\n });\n return nodes;\n }",
"reorder () {\n let nodes = []\n\n walk(this.root.children, (node) => {\n nodes.push(node)\n })\n\n let { baseOrder } = this\n nodes.forEach((node, i) => {\n node.order = baseOrder + i\n })\n }",
"visitAdd_hash_index_partition(ctx) {\n\t return this.visitChildren(ctx);\n\t}",
"skipChild() {\n\t\tIncrementalDOM.elementVoid(jsxRenderer_.incElementCount);\n\t}",
"function walkDom(n) {\n do {\n console.log(n); // can use document.write instead\n if (n.hasChildNodes()) {\n walkDom(n.firstChild)\n }\n } while (n = n.nextSibling)\n}",
"removeAllChildren() {\n this.__childNodes = [];\n this.repeats = [];\n this.dispatchNodeEvent(new NodeEvent('repeated-fields-all-removed', this.repeats, false));\n }",
"function recursiveStepForHierarchicalOrder(rootID, node, index, createdPage) {\n if (node.nodes[index].nodes.length > 0) {\n createHierarchies(createdPage.id, node.nodes[index], 0);\n };\n createHierarchies(rootID, node, index + 1)\n }",
"function BARegisterDOMMethodsRoundRobin() {\n\tif ((typeof Node == 'object' || typeof Node == 'function') && Node.prototype) return;\n\tif (BAAlreadyApplied(arguments.callee)) return;\n\tdocument.getElementsByTagNameBA('*').forEach(BARegisterDOMMethodsTo);\n}",
"function ChangeIndex(element, index) {\n\n //Element with additional list inside element. (descriptions)\n if (element.getElementsByTagName(\"ul\").length != 0) {\n ChangeIndexOfAttribute(element, \"id\", index);\n ChangeIndexOfAttribute(element.children[0], \"id\", index);\n var div = element.children[1];\n ChangeIndexOfAttribute(div, \"id\", index);\n var list_span = div.getElementsByTagName(\"span\");\n for (var i=0; i<list_span.length; i++) {\n ChangeIndex(div, index);\n }\n }\n //No extra list inside element.\n else {\n var list_span = element.getElementsByTagName(\"span\");\n for (var i=0; i<list_span.length; i++) {\n ChangeIndexOfAttribute(list_span[i], \"onclick\", index);\n ChangeIndexOfAttribute(list_span[i], \"id\", index);\n }\n }\n}",
"function createHierarchies(rootID, node, index) {\n if (isCanceled)return;\n if (index >= node.nodes.length) return;\n let object = specif.getSpecIFObjectForID(node.nodes[index].object);\n if (object) {\n let page = createPageFromObject(object, rootID);\n page.title = pageNumber(node.object, index, object) + \" \" + page.title;\n data.createPage(page, function (response) {\n let createdPage = JSON.parse(response);\n let log = \"<p>/\";\n let notFirst = false;\n createdPage.ancestors.forEach(function (entry) {\n if (notFirst)\n log += entry.title + \"/\";\n else\n notFirst = true;\n });\n log += page.title;\n reorderCreatedPage(rootID, node, index, createdPage, specif.isChapter(object));\n }, function (err) {\n console.log(page);\n console.log(err);\n error(err)\n })\n } else {\n createHierarchies(rootID, node, index + 1)\n }\n }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
data Maybe x = Nothing | Just x | function Maybe(value){
this.value = value;
} | [
"function maybe_6(b) /* (b : bool) -> maybe<()> */ {\n return (b) ? Just(_unit_) : Nothing;\n}",
"function maybe_7(i) /* (i : int) -> maybe<int> */ {\n return ($std_core._int_eq(i,0)) ? Nothing : Just(i);\n}",
"function maybe_3(m, nothing) /* forall<a> (m : maybe<a>, nothing : a) -> a */ {\n return $default(m, nothing);\n}",
"function null_1(i) /* (i : int) -> null<int> */ {\n return $null(maybe_7(i));\n}",
"function dnull(c){\n return c==null?'0':c;\n}",
"function maybe_5(xs) /* forall<a> (xs : list<a>) -> maybe<a> */ {\n return (xs == null) ? Nothing : Just(xs.head);\n}",
"function nullable(struct) {\n return new Struct$1({ ...struct,\n validator: (value, ctx) => value === null || struct.validator(value, ctx),\n refiner: (value, ctx) => value === null || struct.refiner(value, ctx)\n });\n}",
"static isNull(value) { return value === null; }",
"NullLiteral() {\n this._eat(\"null\");\n return {\n type: \"NullLiteral\",\n value: null,\n };\n }",
"function isUndefined(){\n return;\n}",
"function maybe(t) /* forall<a> (t : try<a>) -> maybe<exception> */ {\n return (t._tag === 1) ? Just(t.exception) : Nothing;\n}",
"function isNullOrUndefined(variable) { \r\n\treturn variable === null || variable === undefined; \r\n}",
"function isNull(input){\n return input==null || \n input==\"\" || \n input<0 ||\n input=='NA' ||\n input=='na' ||\n input=='Na' ||\n input=='NaN' ||\n input=='none' ||\n input=='999'\n}",
"function optional(struct) {\n return new Struct$1({ ...struct,\n validator: (value, ctx) => value === undefined || struct.validator(value, ctx),\n refiner: (value, ctx) => value === undefined || struct.refiner(value, ctx)\n });\n}",
"function xorForMaybe(a, b) {\n var aIsSome = Maybe_1.isNotNullAndUndefined(a);\n var bIsSome = Maybe_1.isNotNullAndUndefined(b);\n if (aIsSome && !bIsSome) {\n return a;\n }\n if (!aIsSome && bIsSome) {\n return b;\n }\n // XXX: We can choose both `null` and `undefined`.\n // But we return `undefined` to sort with [Optional Chaining](https://github.com/TC39/proposal-optional-chaining)\n return undefined;\n}",
"function notNullish(value) {\n return value !== null && value !== undefined;\n}",
"function nullobj(obj)\r\n{\r\n\treturn obj || { };\r\n}",
"function isNil(value){\n if (value === null || value === undefined) return true;\n return false;\n}",
"function NilNode() {\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to open the Preview Modal | function openPreview(name, url){
console.log(name, url);
var modal = '<div class="modal fade" id="bookPreview" tabindex="-1" role="dialog" aria-labelledby="bookPreviewLabel" aria-hidden="true">' +
'<div class="modal-dialog" role="document">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<h5 class="modal-title" id="bookPreviewLabel">'+ name +'</h5>' +
'<button type="button" class="close" data-dismiss="modal" aria-label="Close">' +
'<span aria-hidden="true">×</span>' +
'</button>' +
'</div>' +
'<div class="modal-body">' +
'<iframe src="'+ url +'&output=embed" frameborder="0">' +
'</iframe>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
$('body').prepend(modal);
$('#bookPreview').modal('show');
$('#bookPreview').on('hidden.bs.modal', function(e){
$('#bookPreview').remove();
});
} | [
"function displayBlob() {\n $('#modalBlob').modal('show');\n}",
"function showPreview(index)\r\n {\r\n var $window = $(window);\r\n\r\n // get a element\r\n var a = $previews.eq(index).find(\"a\");\r\n var aTop = a.offset().top;\r\n var centerTop = $window.height() / 2;\r\n var scrollTop = $window.scrollTop();\r\n var diff = aTop - (centerTop + scrollTop);\r\n\r\n $window.scrollTop(scrollTop + diff);\r\n\r\n a.click();\r\n }",
"function open_prediction_modal(app, {ack, payload, context}, title){\n \n // Acknowledge the command request\n ack();\n \n // Return a view payload to open up a modal window\n try {\n const result = app.client.views.open({\n token: context.botToken,\n // Pass a valid trigger_id within 3 seconds of receiving it\n trigger_id: payload.trigger_id,\n // View payload\n view: question_modal.q_view(title)\n });\n\n } catch (error) {\n console.error(error);\n }\n console.log(\"Exiting open_prediction_modal\")\n\n}",
"_openConfirmRunAlgoModal(evt) {\n\n if ('mediaIds' in evt.detail)\n {\n this._confirmRunAlgorithm.init(\n evt.detail.algorithmName, evt.detail.projectId, evt.detail.mediaIds, null);\n }\n else\n {\n this._confirmRunAlgorithm.init(\n evt.detail.algorithmName, evt.detail.projectId, null, evt.detail.mediaQuery);\n }\n\n this._confirmRunAlgorithm.setAttribute(\"is-open\",\"\");\n this.setAttribute(\"has-open-modal\", \"\");\n document.body.classList.add(\"shortcuts-disabled\");\n }",
"function openAssessmentPlanModal () {\n\t'use strict';\n\t$('#topicDialogBackground').css('display', 'block');\n\t$('#assessment-plan').css('display', 'block');\n}",
"function rexShowMediaPreview() {\n var value, img_type;\n if($(this).hasClass(\"rex-js-widget-media\"))\n {\n value = $(\"input[type=text]\", this).val();\n img_type = \"rex_mediabutton_preview\";\n }else\n {\n value = $(\"select :selected\", this).text();\n img_type = \"rex_medialistbutton_preview\";\n }\n\n var div = $(\".rex-js-media-preview\", this);\n\n var url;\n var width = 0;\n if('.svg' != value.substr(value.length - 4) && $(this).hasClass(\"rex-js-widget-preview-media-manager\"))\n url = './index.php?rex_media_type='+ img_type +'&rex_media_file='+ value;\n else\n {\n url = '../media/'+ value;\n width = 246;\n }\n\n if(value && value.length != 0 && $.inArray(value.split('.').pop(), rex.imageExtensions))\n {\n // img tag nur einmalig einf�gen, ggf erzeugen wenn nicht vorhanden\n var img = $('img', div);\n if(img.length == 0)\n {\n div.html('<img />');\n img = $('img', div);\n }\n img.attr('src', url);\n if (width != 0)\n img.attr('width', width);\n\n div.stop(true, false).slideDown(\"fast\");\n }\n else\n {\n div.stop(true, false).slideUp(\"fast\");\n }\n }",
"PreviewMenu(name) {\n return this._openMenu(name, true);\n }",
"function win() {\n modal.style.display = \"block\";\n}",
"function openCommentModal() {\n $( '#discussion-modal' ).foundation('reveal', 'open');\n }",
"function display_form(){\r\n $('#staticBackdrop').modal('show');\r\n}",
"open() {\n return spPost(WebPartDefinition(this, \"OpenWebPart\"));\n }",
"function open_img_selection() {\n if (!initializedLibraryUpload) {\n initializeLibraryUploadForm();\n initializedLibraryUpload = true;\n }\n $('#select-img-modal').modal('open');\n}",
"function showScriptPreviewFromFlex(url, label, jobHash) {\n // add preview image tag\n $('#logPopup').html('<img/>');\n\n // set onload handler\n $(\"#logPopup img\").error(function() {\n alert(\"The preview is not provided for \"+label+'.');\n }).one('load', function() {\n $('#logPopup').dialog('option', 'height', this.height+50);\n $('#logPopup').dialog('option', 'width', this.width+25);\n $('#logPopup').dialog('option', 'title', \"Script Preview (\"+label+\")\");\n $('#logPopup').dialog('open');\n });\n\n // set src and start loading\n $('#logPopup img').attr('src', url);\n}",
"function openVideo(video_id) {\n $(modal.replace(\"{VIDEO_ID}\", video_id)).appendTo('body').modal();\n}",
"function openCreateLayerModal() {\n layerManagementWidget.expanded = false; //Close the widget that opens the window so it won't be in the way.\n\n //Create the list of features and renderers that available to create a layer from.\n const featureOptions = projectFeatures.map( (feature) => {\n const elem = document.createElement(\"option\");\n elem.value = feature.name;\n elem.text = feature.name;\n return elem;\n });\n\n const layerSelect = document.getElementById(\"layer-feature-select\");\n layerSelect.replaceChildren(...featureOptions);\n layerSelect.appendChild(new Option(\"None\", false));\n\n const rendererOptions = projectRenderers.map( ( renderer ) => {\n const elem = document.createElement(\"option\");\n elem.value = renderer.name;\n elem.text = renderer.name;\n return elem;});\n\n const rendererSelect = document.getElementById(\"layer-renderer-select\");\n rendererSelect.replaceChildren(...rendererOptions);\n rendererSelect.appendChild(new Option(\"None\", false));\n\n //Open the window\n document.getElementById(\"create-layer-modal\").style.display = \"block\";\n }",
"openLinkDialog () {\n if (!this.view) {\n this.initDialog();\n }\n\n this.view.open();\n }",
"function thisopenEntityMiniPopupWin(pk) {\r\n if (pk == 0) {\r\n alert(getMessage(\"cs.entity.information.error.notRecorded\"));\r\n return;\r\n }\r\n\r\n var path = getCISPath() + \"/ciEntityMiniPopup.do?pk=\" + pk;\r\n\r\n if (isDivPopupEnabled()) {\r\n //openDivPopup(popupTitle, urlToOpen, isModel, isDragable, popupTop, popupLeft, popupWidth, popupHeight, contentWidth, contentHeight)\r\n openDivPopup(\"\", path, true, true, \"\", \"\", \"900\", \"890\", \"890\", \"880\", \"\", true);\r\n }\r\n else {\r\n var mainwin = window.open(path, 'EntityMiniPopup',\r\n 'width=900,height=700,innerHeight=700,innerWidth=875,scrollbars');\r\n mainwin.focus();\r\n }\r\n return;\r\n}",
"function openModal() {\n\t\t\t//Create timestamp object\n\t\t\tconst timestamp = { session_id: new Date().getTime() };\n\t\t\tconsole.log(timestamp);\n\n\t\t\t//Get and/or set page variation\n\t\t\tlet imgId = '';\n\t\t\tif($cookies.imgValue !== undefined) {\n\t\t\t\timgId = $cookies.imgValue;\n\t\t\t} else {\n\t\t\t\timgId = Math.floor(Math.random() * 2).toString();\n\t\t\t\t$cookies.imgValue = imgId;\n\t\t\t}\n\n\t\t\t//Modify modal instance\n\t\t\tconst modalInstance = $uibModal.open({\n\t\t\t\tappendTo: angular.element(document).find('aside'),\n\t\t\t\tanimation: true,\n\t\t\t\tariaLabelledBy: 'modal-title',\n\t\t\t\tariaDescribedBy: 'modal-body',\n\t\t\t\ttemplateUrl: 'myModalContent',\n\t\t\t\tcontroller: 'ModalController',\n\t\t\t\tcontrollerAs: 'ctrl',\n\t\t\t\tresolve: {\n\t\t\t\t\timgId:function() {\n\t\t\t \treturn imgId;\n\t\t\t }\n\t\t\t\t},\n\n\t\t });\n\n\t\t\t//Display modal data to browser console\n\t\t modalInstance.result.then(function(data) {\n\t\t \tconsole.log(data);\n\t\t }, function() {});\n\t\t}",
"function getDefaultshowPreviewPanel() {\n\t return true;\n\t }"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r2owebviewclose Directive Its an attribute directive. When this directive is used as an attribute to an element, the click on the element will close the webview overlay | function r2oWebviewClose(){
return {
restrict : "A",
link: function(scope, element, attrs){
element.on('click', function(){
window.shopWebViewOverlay.close();
});
}
};
} | [
"_closeModel() {\n this._model.querySelector('.close').addEventListener('click', e => {\n this._hideModel();\n });\n }",
"function addCloseButtonFunctionality(){\n\t\t\t\n\t\t\t\n\t\t}",
"function customOverlayClose() {\n $('.ui-widget-overlay').show().css('height', (2 * $window.height()) + 'px');\n $('.ui-widget-overlay').addClass('_close_on_click_out');\n}",
"function closeElement(element) {\r\n element.remove();\r\n}",
"function closeDiv(element) {\r\n\telement.style.display='none';\t\t\t\t\t\r\n}",
"function closeEvent() {\n var event = new Event('close-interface');\n document.dispatchEvent(event);\n}",
"_setAdhesionCloseLink() {\n this.adhesionCloseLink = document.getElementById('close-adhesion-ad');\n }",
"close() {\n return spPost(WebPartDefinition(this, \"CloseWebPart\"));\n }",
"function closeOnClick(event){\n //make sure the area being clicked is just the overlay\n if(event.target.id == \"overlay\"){\n closeOverlay();\n }\n\n}",
"function closePopupVideo() {\n $body.removeClass('overflow');\n $overlayVideo.removeClass('open');\n setTimeout(function () {\n player.stopVideo();\n }, 250);\n }",
"close() {\n this.removeAttribute('expanded');\n this.firstElementChild.setAttribute('aria-expanded', false);\n // Remove the event listener\n this.dispatchCustomEvent('tk.dropdown.hide');\n }",
"function closeLink() {\n setTimeout(() => {\n window.close();\n }, 100);\n}",
"function close_image() {\n image_viewer.style.display = \"none\";\n}",
"close() {\n this.showModal = false;\n\n this.onClose();\n }",
"function closeOverlay(e) {\n if (isVideoOpen === true) {\n const mosVideoWrapper =\n document.getElementsByClassName(\"mos-video-wrapper\");\n const flipCardInner = document.getElementsByClassName(\"flip-card-inner\");\n const mosVideo = document.getElementsByClassName(\"mos-video\");\n\n for (let i = 0; i < mosVideoWrapper.length; i++) {\n mosVideoWrapper[i].style.display = \"none\";\n }\n\n for (let i = 0; i < mosVideo.length; i++) {\n mosVideo[i].pause();\n mosVideo[i].currentTime = 0;\n }\n\n for (let i = 0; i < flipCardInner.length; i++) {\n flipCardInner[i].style.visibility = \"visible\";\n }\n\n setIsVideoOpen(false);\n }\n }",
"@action closeDialog() {\r\n\t\tif (this.dialog) this.dialog.opened = false;\r\n\t}",
"closeShareCollection() {\n this.isShowShareCollection = false;\n if (this.is_copied) {\n this.closeSocialSharing('link');\n }\n }",
"function onClickToolbarClose(e)\n{\n\tif (!e) var e = window.event;\n\tclearMessage();\n\tif(this.parentNode.id)\n\t\tcloseTiddler(this.parentNode.id.substr(7),e.shiftKey || e.altKey);\n\te.cancelBubble = true;\n\tif (e.stopPropagation) e.stopPropagation();\n\treturn(false);\n}",
"function closeQrcode() {\n\tlet cl=document.getElementById('coverlayer');\n\tcl.addEventListener('transitionend',function(event) {\n\t\tcl.parentNode.removeChild(cl);\n\t});\n\tcl.style.opacity='0';\n\tlet syncd=document.getElementById('qrcode-view');\n\tsyncd.addEventListener('transitionend',function(event) {\n\t\tsyncd.parentNode.removeChild(syncd);\n\t\ton_qrcode=false;\n\t},{once:true});\n\tsyncd.classList.remove('active');\n}",
"function closeSitebar() {\n\t// hack\n\t// map calls closeSitebar when polygone is clicked\n\t// if open call is called 100ms before it will not be called\n\tif (_globals.globals.callSitebarTimestamp + 100 < Date.now()) {\n\t\t(0, _jquery2.default)(\"body\").addClass(\"sidebar-closed\");\n\t\t(0, _jquery2.default)(\".sequenceContainer\").hide();\n\t\t(0, _helper.sendEvent)(\"dataChanged\", {\n\t\t\ttask: \"focusNode\",\n\t\t\tdata: null\n\t\t});\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function name : validateAdsAddPageForm Return type : bollean Date created : 28th February 2008 Date last modified : 28th February 2008 Author : Sandeep Kumar Last modified by : Sandeep Kumar Comments : This function is used to validate the CMS form. User instruction : validateAdsAddPageForm(formname) | function validateAdsAddPageForm(formname,isimage)
{
var frmAdType = $("#"+formname+" input[type='radio']:checked").val();
if(frmAdType=='html'){
if($('#frmTitle').val() == ''){
alert(TIT_REQ);
$('#frmTitle').focus()
return false;
}else if($('#frmHtmlCode').val() == ''){
alert(HTML_REQ);
$('#frmHtmlCode').focus()
return false;
}
}else{
if($('#frmTitle').val() == ''){
alert(TIT_REQ);
$('#frmTitle').focus()
return false;
}else if($('#frmAdUrl').val() == ''){
alert(URL_LINK_REQ);
$('#frmAdUrl').focus()
return false;
}else if(IsUrlLink($('#frmAdUrl').val()) ==false){
alert(ENTER_VALID_LINK);
$('#frmAdUrl').select();
return false;
}
if(isimage==0){
if($('#frmImg').val() == ''){
alert(IMG_REQ);
$('#frmImg').focus()
return false;
}
}
if($('#frmImg').val() != ''){
var ff = $('#frmImg').val();
var exte = ff.substring(ff.lastIndexOf('.') + 1);
var ext = exte.toLowerCase();
if(ext!='jpg' && ext!='jpeg' && ext!='gif' && ext!='png'){
alert(ACCEPTED_IMAGE_FOR);
$('#frmImg').focus();
return false;
}
}
}
} | [
"function validateCMSAddPageForm(formname)\n{\n \n if($('#frmDisplayPageTitle').val() == '')\n {\n alert(PAGE_DISP_TITLE);\n $('#frmDisplayPageTitle').focus()\n return false;\n }\n if($('#frmPageTitle').val() == '')\n {\n alert(PAGE_TIT_REQ);\n $('#frmPageTitle').focus()\n return false;\n } \n if($('#frmPageDisplayOrder').val() == '' )\n {\n alert(PAGE_ORDER_REQ);\n $('#frmPageDisplayOrder').focus()\n return false;\n } \n \n}",
"function pageValidate(){\n var txtFieldIdArr = new Array();\n txtFieldIdArr[0] = \"tf1_SysName,\"+LANG_LOCALE['12134'];\n if (txtFieldArrayCheck(txtFieldIdArr) == false) \n return false;\n \n if (alphaNumericValueCheck (\"tf1_SysName\", '-', '') == false) \n return false;\n\n if (isProblemCharArrayCheck(txtFieldIdArr, \"'\\\" \", NOT_SUPPORTED) == false) \n return false;\n}",
"function validateNewsLetterMailForm(formID)\n{\n if(validateForm(formID, 'frmNewsLetterName', 'Title', 'R','frmSubscriberList','Subscriber','R'))\n { \n return true;\n } \n else \n {\n return false;\n }\n}",
"function validateAddPaymentForm()\n{\n\tvar box, i;\n\tvar form = document.addPayment;\n\t\n\tfor(i=0; i<4; i++)\n\t{\n\t\tbox=form.elements[i];\n\t\t//if it encountered a box without a value, an alert box would appear informing the user\n\t\tif(!box.value)\n\t\t{\n\t\t\t$().toastmessage({position:'middle-center', stayTime:2000});\n\t\t\t$().toastmessage('showErrorToast', \"You haven't filled in the \"+box.name+\".\");\n\t\t\tbox.focus();\n\t\t\treturn false;\n\t\t}\n\t}\n\t//if the form is complete, a confirm box would appear asking the user if he/she wants to continue\n\tvar confirmAdd = confirm(\"Continue Addition of Payment Entry?\");\n\t\n\t//return the answer of the user (true or false)\n\treturn confirmAdd;\n}",
"function validateBillingAddress(formname)\n{\n\t\n if(validateForm(formname,'frmAddressLine1', 'Address', 'R','frmCountry', 'Country', 'R', 'frmState', 'State','R', 'frmCity', 'City', 'R', 'frmZipCode', 'Zip Code', 'R'))\n {\t\n\t\t\n\t\t\n return true;\n } \n else \n {\n return false;\n } \n}",
"function validateForm() {\n clientErrorStorage = new Object();\n var summaryTextExistence = new Object();\n var validForm = true;\n\n jQuery.watermark.hideAll();\n pauseTooltipDisplay = true;\n\n if (validateClient) {\n // Turn on this flag to avoid prematurely writing out messages which will cause performance issues if MANY\n // fields have validation errors simultaneously (first we are only checking for errors, not checking and\n // writing simultaneously like normal)\n clientErrorExistsCheck = true;\n\n // Temporarily turn off this flag to avoid traversing unneeded logic (all messages will be shown at the end)\n messageSummariesShown = false;\n\n // Validate the whole form\n validForm = jq(\"#kualiForm\").valid();\n\n // Handle field message bubbling manually, but do not write messages out yet\n jQuery(\"div[data-role='InputField']\").each(function () {\n var id = jQuery(this).attr('id');\n var field = jQuery(\"#\" + id);\n var data = getValidationData(field);\n var parent = field.data(\"parent\");\n handleMessagesAtGroup(parent, id, data, true);\n });\n\n // Toggle the flag back to default\n clientErrorExistsCheck = false;\n\n // Message summaries are going to be shown\n messageSummariesShown = true;\n\n // Finally, write the result of the validation messages\n writeMessagesForPage();\n }\n\n if (!validForm) {\n validForm = false;\n\n //ensure all non-visible controls are visible to the user\n jQuery(\".error:not(:visible)\").each(function () {\n cascadeOpen(jQuery(this));\n });\n\n jumpToTop();\n showClientSideErrorNotification();\n jQuery(\".uif-pageValidationMessages li.uif-errorMessageItem:first > a\").focus();\n }\n\n jq.watermark.showAll();\n pauseTooltipDisplay = false;\n\n return validForm;\n}",
"function validateBrand(formname)\n{\n if(validateForm(formname, 'frmBrandName', 'Brand Name', 'R', 'frmCategoryID', 'Brand Category', 'R'))\n {\t\n return true;\n } \n else \n {\n return false;\n } \n}",
"function validateCoupon(formname)\n{\n \n if(validateForm(formname, 'frmCouponCode', 'Coupon Code', 'R','frmCouponPriceValue', 'Price Value', 'RisDecimal', 'frmMinimumPurchaseAmount', 'Minimum Purchase Amount', 'RisDecimal', 'frmCouponPriceValue', 'Price Value', 'regDecimal','frmCouponActivateDate', 'Coupon Activate date', 'R','frmCouponExpiryDate', 'coupon expiry date', 'R'))\n {\t\n \t\n var CouponActivateDate=document.forms[0].frmCouponActivateDate.value;\n var CouponExpiryDate=document.forms[0].frmCouponExpiryDate.value;\n if(CouponActivateDate > CouponExpiryDate)\n {\n alert(SORRY_CANT_COMPLETE_YOUR_REQ);\n return false;\n }\n } \n else \n {\n return false;\n } \n}",
"function validPdfForm() {\r\n return true;\r\n}",
"function validateSize(formname)\n{\n if(validateForm(formname, 'frmSizeName', 'Size Name', 'R'))\n {\t\n return true;\n } \n else \n {\n return false;\n } \n}",
"function validateForm() {\n\tif ( noShortCircuitAnd(\n\t\tvalidateItemName(), \n\t\tvalidatePounds(), \n\t\tvalidateOunces(), \n\t\tvalidateQuantity(), \n\t\tvalidateSampleDate()) ) {\n\t\t\n\t\treturn true; //Go ahead and submit form\n\t} else {\n\t\talert(\"Please correct the designated errors and submit again.\");\n\t\treturn false; //Cancel the form submit\n\t}//end if\n}",
"function validateOfficeAddressEditForm(formname)\n{\n var inputFocus = true;\n var allowedExtensions = new Array('jpg','jpeg','gif','png');\n if($('#frmAddressTitle').val() == '')\n {\n alert(OFF_LOC_REQ);\n $('#frmAddressTitle').focus();\n return false;\n } \n if($('#frmAddressImage').val() != '')\n {\n if(!validateFileExtension($('#frmAddressImage').val(), allowedExtensions, '#frmAddressImage' , ACCEPT_FORMAT, inputFocus))\n {\n return false;\n }\n }\n}",
"function validateSlideTwo() {\n\tvar bizName = document.forms[\"register\"][\"businessname\"].value;\n\tvar bizInfo = document.forms[\"register\"][\"businessinfo\"].value;\n\tvar bizPhone = document.forms[\"register\"][\"businessphone\"].value;\n\tvar bizNameError = document.getElementById(\"error-businessname\");\n\tvar bizInfoError = document.getElementById(\"error-businessinfo\");\n\tvar bizPhoneError = document.getElementById(\"error-businessphone\");\n\tvar bizAddr =document.forms[\"register\"][\"businessaddress\"].value;\n\tvar bizAddrError = document.getElementById(\"error-businessaddress\");\n\t\n\n\n\t//validates business name\n\t\tif (bizName == \"\") {\n\t\tbizNameError.innerHTML = \"This field is required\";\n\t} \n\t else {\n\t\tbizNameError.innerHTML = \"\";\n\t}\n\n\n\t//validates business info\n\tif (bizInfo == \"\") {\n\t\tbizInfoError.innerHTML = \"This field is required\";\n\t} \n\telse {\n\t\tbizInfoError.innerHTML = \"\";\n\t}\n\n\n\t//validates business phone\n\tif (bizPhone == \"\") {\n\t\tbizPhoneError.innerHTML = \"This field is required\";\n\t}\telse if (isNaN(bizPhone)) {\n\t\tbizPhoneError.innerHTML = \"Only numbers allowed\";\n\t}\n\t else if (bizPhone.length != 11){\n\t\tbizPhoneError.innerHTML = \"Number must be 11 characters long\";\n\t} else {\n\t\tbizPhoneError.innerHTML = \"\";\n\t};\n\n\tif (bizAddr == \"\") {\n\t\tbizAddrError.innerHTML = \"This field is required\";\n\t}\n\n\t//if either fails validation remain on current slide else move to next slide\n\tif (bizPhone == \"\" || bizPhone.length != 11 || bizName == \"\" || bizInfo == \"\" || isNaN(bizPhone) || bizAddr == \"\") {\n\t\tcurrentSlide(2);\n\t} else{\n\t\tplusSlides(1);\n\t};\n}",
"function ValidateForm() {\n objForm = document.getElementById(\"aspnetForm\");\n if (objForm.ctl00_ContentPlaceHolder1_Route_ID.selectedIndex == 0) {\n alert(\"Please select a route plan to copy from.\");\n objForm.ctl00_ContentPlaceHolder1_Route_ID.focus();\n return false;\n }\n if (objForm.ctl00_ContentPlaceHolder1_RP_ID.selectedIndex == 0) {\n alert(\"Please select a default plan to copy to.\");\n objForm.ctl00_ContentPlaceHolder1_RP_ID.focus();\n return false;\n }\n\n if (planExists(objForm, objForm.ctl00_ContentPlaceHolder1_RP_ID.value)) {\n if (!confirm(\"You have already defined a route plan for the selected default plan. Are you sure you want to overwrite ?\")) {\n objForm.ctl00_ContentPlaceHolder1_RP_ID.focus();\n return false;\n }\n }\n\n // return true \n}",
"function validateGiftCard(formname)\n{\n \n if(validateForm(formname, 'frmGiftCardName', 'Gift Card Name', 'R','frmGiftCardAmount', 'Gift Card Amount', 'R'))\n {\t\n \t\n return true;\n } \n else \n {\n return false;\n } \n}",
"function validateGetCalendarForm() {\r\n //TODO: Check valid years, etc.\r\n}",
"function validateMessage(formname)\n{\n\t\n if(validateForm(formname,'frmSendToIds', 'Select Users', 'R', 'frmMessageType', 'Message Type', 'R', 'frmMessageSubject', 'message Subject', 'R'))\n {\t\n\t\t\n\t\t\n return true;\n } \n else \n {\n return false;\n } \n}",
"function validateShippingCostForm(formID)\n{\n if(validateForm(formID, 'frmCountry', 'Country Name', 'R','frmShippingCostState','State Name','R','frmShippingCost','Shipping Cost','R'))\n { \n if($('#frmShippingCostType').val() == 'Percentage')\n {\n if($('#frmShippingCost').val() > 100)\n {\n alert(SHIPP_COST_PERCEN);\n $('#frmShippingCost').focus();\n return false;\n }\n }\n\t\t\n return true;\n } \n else \n {\n return false;\n }\n}",
"function valBlog(frm){\n\tvar passed=true;\n\tvar errorCount=0;\n\tvar t= frm.title.value;\t\n\tvar tags= frm.tags.value;\t\n\t\n\tif(t==\"\" || t==null){\n\t\terrorCount++;\n\t\tdocument.getElementById(\"title_err\").innerHTML=\"You must enter a title\";\n\t}else if(t.length>100){\n\t\terrorCount++;\n\t\tdocument.getElementById(\"title_err\").innerHTML=\"Your title cannot be more than 100 characters.\";\n\t}//end of title validation\n\t\n\tif(tags==\"\" || tags==null){\n\t\terrorCount++;\n\t\tdocument.getElementById(\"tag_err\").innerHTML=\"You must enter atleast one tag\";\n\t}//end of tag validation\n\t\n\t\tif(errorCount !=0)\n\t{\n\t\treturn false;\n\t}\n}"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.